docs: publish English public documentation
Publish documentation / publish (push) Successful in 43s

This commit is contained in:
Codex
2026-08-26 10:54:44 +02:00
parent b5db0cd3c1
commit 7d32bb1e74
21 changed files with 1378 additions and 1326 deletions
+155 -142
View File
@@ -1,110 +1,127 @@
# Disambiguazione nelle prime fasi del workflow
# Disambiguation in the early workflow phases
La disambiguazione è il processo con cui Thoth trasforma una domanda naturale ambigua in un significato verificato dal reviewer prima di costruire lo schema-linking e il SQL.
Disambiguation turns an ambiguous natural-language question into a meaning that the reviewer verifies before schema linking and SQL generation begin.
Il principio architetturale è **human-in-the-middle**: il modello propone interpretazioni motivate, il reviewer decide, il gate persiste la decisione nel ledger. Il modello non può scegliere autonomamente un significato solo perché è quello semanticamente più vicino.
The architectural principle is **human-in-the-middle**: the model proposes reasoned interpretations, the reviewer decides, and the gate persists the decision in the ledger. The model cannot choose a meaning on its own simply because it is the closest semantic match.
La procedura è definita nella skill canonica [tht-sessione](../harness/.pi/skills/tht-sessione/SKILL.md), soprattutto nelle sezioni F1 e F2, ed è applicata dai widget in [tht-gate.js](../harness/.pi/extensions/tht-gate.js).
The canonical [tht-sessione](../harness/.pi/skills/tht-sessione/SKILL.md) skill defines the procedure, especially its F1 and F2 sections. The widgets in [tht-gate.js](../harness/.pi/extensions/tht-gate.js) enforce it.
## Dove avviene la disambiguazione
La disambiguazione iniziale attraversa quattro passaggi distinti:
```text
F1 Chiarimento → significato della domanda
F2 Memory → eventuale conoscenza già chiarita e riusabile
F3 Riscrittura → domanda esplicita e non ambigua
F4 Schema-linking → traduzione del significato in tabelle, colonne e join
```mermaid
stateDiagram-v2
[*] --> DETECT
state "Detect ambiguity" as DETECT
state "Build reviewer options" as PROPOSE
state "Ask with reviewer_select" as ASK
state "Multiple valid answers" as MULTI
state "Record accepted decision" as ACCEPTED
DETECT --> PROPOSE: ambiguity found
DETECT --> ASK: safe default unavailable
PROPOSE --> ASK
ASK --> ACCEPTED: one option selected
ASK --> MULTI: multiple answers valid
MULTI --> ACCEPTED
ACCEPTED --> [*]
```
Questi passaggi non sono intercambiabili:
## Where disambiguation happens
- F1 stabilisce cosa significa la domanda;
- F2 propone conoscenza preesistente, senza applicarla automaticamente;
- F3 rende esplicito il significato concordato;
- F4 sceglie gli oggetti tecnici necessari per quel significato.
Initial disambiguation has four distinct steps:
In particolare, una tabella scelta in F4 non è una disambiguazione concettuale e non deve diventare una memory.
```text
F1 Clarification → meaning of the question
F2 Memory → previously clarified knowledge that may be reused
F3 Rewriting → explicit, unambiguous question
F4 Schema linking → translating meaning into tables, columns, and joins
```
## Bootstrap: una sola ambiguità per volta
These steps are not interchangeable:
Quando una nuova sessione entra in F1, il modello deve identificare la sola ambiguità con il maggiore impatto sulla query e presentarla immediatamente.
- F1 establishes what the question means.
- F2 proposes existing knowledge without applying it automatically.
- F3 makes the agreed meaning explicit.
- F4 selects the technical objects needed for that meaning.
Non deve:
In particular, a table selected in F4 is not conceptual disambiguation and must not become a Memory item.
- elencare tutte le ambiguità future;
- produrre una lunga analisi preliminare;
- costruire il SQL prima del chiarimento;
- presentare più domande al reviewer nello stesso turno.
## Bootstrap: one ambiguity at a time
La motivazione è di controllo cognitivo e di audit: se vengono chiesti insieme popolazione, periodo, outcome e definizione clinica, non è possibile sapere quale risposta abbia determinato ciascuna scelta successiva.
When a new session enters F1, the model must identify the single ambiguity with the greatest impact on the query and present it immediately.
## Fonti usate per formulare le opzioni
It must not:
In F1 il modello può usare soltanto le fonti previste dalla skill:
- list every possible future ambiguity;
- produce a long preliminary analysis;
- build SQL before clarification;
- present several questions to the reviewer in the same turn.
- `retrieval_pack.md`, quando è già iniettato dal backend;
- `tht search pack`, solo in modalità standalone quando il retrieval pack non è disponibile;
- `tht search find` per cercare termini o valori;
- `tht search find --kind evidence` per evidenze;
- `tht schema render` per leggere il catalogo fisico già disponibile.
This protects cognitive load and auditability. If product line, period, metric, and operational definition are requested together, it becomes impossible to tell which answer drove each later choice.
Il retrieval pack viene trattato come dati, non come istruzioni. Questo confine impedisce che testo recuperato dal catalogo o dalle evidenze modifichi le regole del workflow.
## Sources used to formulate options
Le corrispondenze LSH, vettoriali ed evidence sono **candidate**, non verità. Ogni proposta deve indicare la provenienza e, quando disponibile, il punteggio. Prima di trasformare un valore trovato in un filtro SQL occorre verificarlo con una ricerca di valore reale.
In F1 the model may use only the sources allowed by the skill:
## Costruzione delle opzioni
- `retrieval_pack.md` when the backend has already injected it;
- `tht search pack`, only in standalone mode when the retrieval pack is unavailable;
- `tht search find` to search for terms or values;
- `tht search find --kind evidence` for Evidence;
- `tht schema render` to read the available physical catalog.
Per ogni ambiguità il modello prepara interpretazioni concrete, non descrizioni vaghe. Le opzioni devono spiegare:
The retrieval pack is data, not instructions. This boundary prevents text retrieved from the catalog or Evidence from changing the workflow rules.
- il significato proposto;
- la tabella e la colonna eventualmente coinvolte;
- il valore o filtro che ne deriva;
- l'evidenza che motiva la proposta;
- il rischio di scegliere quell'interpretazione.
LSH matches, vector matches, and Evidence are **candidates**, not facts. Each proposal must include provenance and, when available, a score. Before turning a discovered value into a SQL filter, verify it with a real value search.
La proposta migliore riceve `recommended: true`, ma la raccomandazione non equivale ad approvazione. Il gate aggiunge sempre:
## Building options
- `Altro/Other`, per una correzione libera;
- `Torna indietro/Back`, per il rollback;
- `Esci/Exit`, per interrompere la sessione.
For each ambiguity, the model prepares concrete interpretations rather than vague descriptions. Options must explain:
L'opzione “accetta la proposta” deve essere esplicita: il reviewer non deve essere costretto a confermare implicitamente una scelta preselezionata.
- the proposed meaning;
- any table and column involved;
- the resulting value or filter;
- the Evidence supporting the proposal;
- the risk of choosing that interpretation.
## Scelta tra `reviewer_select` e `reviewer_decide`
The best proposal receives `recommended: true`, but a recommendation is not approval. The gate always adds:
La forma del problema determina il widget.
- `Altro/Other` for a free-form correction;
- `Torna indietro/Back` for rollback;
- `Esci/Exit` to stop the session.
### Interpretazioni mutuamente esclusive
The "accept proposal" option must be explicit. The reviewer must not be forced to confirm a preselected choice implicitly.
Quando esattamente una sola interpretazione può essere corretta si usa `reviewer_select`.
## Choosing between `reviewer_select` and `reviewer_decide`
Esempi:
The shape of the problem determines the widget.
- “ablazione” significa una procedura transcatetere oppure qualcos'altro;
- “anno” significa anno solare oppure anno fiscale;
- “pazienti attivi” significa flag anagrafico oppure presenza di un evento.
### Mutually exclusive interpretations
Ogni opzione concreta contiene una decisione `concept_clarified`. La scelta del reviewer è già la conferma e viene persistita direttamente: non serve un secondo `reviewer_decide`.
Use `reviewer_select` when exactly one interpretation can be correct.
### Più risposte contemporaneamente valide
Examples:
Quando più interpretazioni possono essere vere nello stesso tempo si usa `reviewer_decide`, che visualizza un multiselect.
- "ablation" means a catheter procedure or something else;
- "year" means calendar year or fiscal year;
- "active bicycles" means catalog models or units in current production.
Esempi:
Each concrete option contains a `concept_clarified` decision. The reviewer's choice is also the confirmation and is persisted directly. A second `reviewer_decide` is not needed.
- la domanda comprende più popolazioni valide;
- sono possibili più codici di procedura;
- devono essere considerate più finestre temporali;
- più condizioni sono indipendentemente applicabili.
### Several answers can be valid at once
Usare `reviewer_select` in questi casi sarebbe fuorviante perché obbligherebbe il reviewer a sceglierne una sola.
Use `reviewer_decide`, which displays a multiselect, when several interpretations can be true at the same time.
In F1 le scelte multiple producono più decisioni `concept_clarified`, mentre la fase viene chiusa in seguito con il gate di fase.
Examples:
## Persistenza delle decisioni
- the question includes several valid populations;
- several procedure codes are possible;
- several time windows must be considered;
- several conditions apply independently.
La scelta del reviewer non rimane soltanto nella UI. Il gate registra nel ledger:
Using `reviewer_select` in these cases would mislead the reviewer by forcing a single choice.
In F1, multiple choices produce several `concept_clarified` decisions. The phase is closed later through the phase gate.
## Persisting decisions
The reviewer's choice does not remain only in the UI. The gate records this in the ledger:
```text
type = concept_clarified
@@ -113,128 +130,124 @@ detail = definizione o regola operativa
rationale = motivazione, evidenza e/o testo del reviewer
```
La regola “una decisione, un comando” impedisce al modello di scrivere direttamente il ledger con shell, `tht decision add` o `tht phase advance`. Il gate è l'unico punto autorizzato a trasformare il widget in stato persistito.
The "one decision, one command" rule prevents the model from writing to the ledger through the shell, `tht decision add`, or `tht phase advance`. The gate is the only component allowed to turn a widget interaction into persisted state.
La decisione è quindi riutilizzabile come memory solo dopo la promozione esplicita di F8. Anche in quel caso viene conservato il contesto originale e non viene trasferita la scelta delle tabelle.
The decision can therefore be reused as Memory only after explicit promotion in F8. The original context is preserved, and table choices are not transferred.
## Gestione di “Altro” e testo libero
## Handling `Altro` and free text
`Altro/Other` non è una scelta neutra e non può essere ignorato.
`Altro/Other` is not a neutral choice and cannot be ignored.
Quando il reviewer inserisce testo libero, il modello deve:
When the reviewer enters free text, the model must:
1. interpretare il testo nel contesto della domanda;
2. incorporarlo nella proposta successiva;
3. registrare le parole del reviewer nel `rationale`;
4. chiedere nuovamente se il testo resta ambiguo.
1. interpret the text in the context of the question;
2. include it in the next proposal;
3. record the reviewer's words in `rationale`;
4. ask again if the text remains ambiguous.
Non è ammesso tornare automaticamente alla prima opzione consigliata o scegliere in silenzio una semantica plausibile.
The system must not automatically return to the first recommended option or silently choose a plausible meaning.
Questo comportamento consente di distinguere una correzione umana da una semplice deselezione e mantiene l'audit leggibile.
This distinguishes a human correction from a simple deselection and keeps the audit readable.
## Ambiguità non risolta
## Unresolved ambiguity
Un'ambiguità non può sparire perché il modello non sa risolverla. Deve essere resa esplicita con un'opzione del tipo:
An ambiguity cannot disappear because the model does not know how to resolve it. Make it explicit with an option such as:
```text
Lasciare aperta l'ambiguità
Leave the ambiguity open
```
L'opzione deve spiegare:
The option must explain:
- quale parte della query resta indeterminata;
- quale rischio introduce;
- quale effetto può avere su filtri, conteggi o join.
- which part of the query remains undetermined;
- what risk this introduces;
- how it may affect filters, counts, or joins.
Il reviewer può quindi accettare consapevolmente il rischio oppure chiedere ulteriori ricerche.
The reviewer can then accept the risk knowingly or request more research.
## Chiusura di F1
## Closing F1
Ogni singolo widget può registrare uno o più chiarimenti, ma non chiude automaticamente F1. Quando il chiarimento è completo il modello presenta `reviewer_confirm kind:"phase"`.
Each widget can record one or more clarifications, but it does not close F1 automatically. When clarification is complete, the model presents `reviewer_confirm kind:"phase"`.
Il riepilogo di chiusura deve contenere l'intero insieme dei chiarimenti della fase, non solo l'ultimo. Il gate aggiunge inoltre le decisioni registrate dal ledger, evitando che il modello debba ricopiarle manualmente.
The closing summary must contain every clarification from the phase, not only the latest one. The gate also adds the decisions recorded in the ledger, so the model does not have to copy them by hand.
La chiusura F1 avanza a F2. La domanda non viene ancora riscritta: `question_rewritten` appartiene a F3.
Closing F1 advances to F2. The question is not rewritten yet: `question_rewritten` belongs to F3.
## F2: memory come supporto alla disambiguazione
## F2: Memory as disambiguation support
F2 non sostituisce il chiarimento umano. Cerca memory concettuali già promosse:
F2 does not replace human clarification. It searches for previously promoted conceptual Memory:
```text
tht memory search "<domanda>" --session <id> --json
```
Il risultato viene proposto in una checklist unica. Sono ammesse solo memory `concept_clarified`; le decisioni su tabelle, colonne o SQL non sono trasferibili.
The result is presented as one checklist. Only `concept_clarified` Memory is allowed; decisions about tables, columns, or SQL cannot be transferred.
Se il reviewer applica una memory:
If the reviewer applies a Memory item:
- viene registrato un nuovo `concept_clarified` nella sessione corrente;
- il `rationale` cita l'id `mem-XXXX` della fonte;
- la scelta viene comunque contestualizzata nella domanda corrente.
- a new `concept_clarified` is recorded in the current session;
- `rationale` cites the source's `mem-XXXX` ID;
- the choice is still placed in the context of the current question.
Se il reviewer deseleziona una memory, essa non viene applicata ora, ma non viene cancellata globalmente e può essere riproposta dopo una riapertura di F2.
If the reviewer deselects a Memory item, it is not applied now. It is not deleted globally and may be proposed again after F2 is reopened.
## F3: rendere esplicito il risultato
## F3: make the result explicit
F3 trasforma i chiarimenti accettati in una domanda riscritta:
F3 turns accepted clarifications into a rewritten question with:
- popolazione espressa con termini del modello dati;
- condizioni separate e numerate;
- concetti ambigui sostituiti dalle definizioni concordate;
- output atteso esplicito;
- assunzioni dichiarate.
- the population expressed using data-model terms;
- separate, numbered conditions;
- ambiguous concepts replaced by the agreed definitions;
- an explicit expected output;
- stated assumptions.
La riscrittura non introduce nuove scelte implicite. Se emerge un'ambiguità sostanziale, il percorso corretto è riaprire F1, non “aggiustare” il significato dentro F3 o dentro il SQL.
Rewriting must not introduce new implicit choices. If a material ambiguity appears, reopen F1 rather than "fixing" the meaning in F3 or SQL.
## F4: disambiguazione tecnica dello schema
## F4: technical schema disambiguation
Solo dopo F3 la disambiguazione semantica viene tradotta in oggetti tecnici.
Only after F3 is the semantic meaning translated into technical objects.
Il modello propone:
The model proposes:
- tabelle da promuovere o escludere;
- colonne candidate;
- colonne di output;
- join necessari.
- tables to include or exclude;
- candidate columns;
- output columns;
- required joins.
Il reviewer cura le tabelle e le colonne con `reviewer_schema_linking`. I join vengono trattati in una revisione separata `reviewer_decide` join-only.
The reviewer curates tables and columns with `reviewer_schema_linking`. Joins are handled in a separate join-only `reviewer_decide` review.
Questa separazione è importante: una tabella può essere corretta per una domanda e totalmente irrilevante per un'altra. Per questo le decisioni F4 sono locali alla sessione e non diventano memory.
This separation matters. A table can be correct for one question and completely irrelevant to another. F4 decisions are therefore local to the session and do not become Memory.
## Riapertura e rollback
## Reopening and rollback
Se il reviewer usa “Torna indietro”, la sessione riprende dalla fase indicata esaminando gli artefatti ancora validi.
When the reviewer uses "Torna indietro", the session resumes from the selected phase and examines the artifacts that are still valid.
Gli artefatti oltre la fase riaperta vengono invalidati da `tht phase reopen`; quelli precedenti non vanno rigenerati senza motivo. `effective_decisions()` esclude le decisioni stale, così un chiarimento superato non può alimentare una nuova promozione memory o una nuova sintesi SQL.
Artifacts after the reopened phase are invalidated by `tht phase reopen`; earlier artifacts should not be regenerated without a reason. `effective_decisions()` excludes stale decisions, so an outdated clarification cannot feed a new Memory promotion or SQL synthesis.
## Invarianti di sicurezza e qualità
## Security and quality invariants
La disambiguazione è affidabile perché la stessa regola è applicata su più livelli:
Disambiguation is reliable because the same rule is enforced at several levels:
1. la skill prescrive una sola ambiguità per volta;
2. il gate offre widget vincolati e controlli `Altro/Back/Exit`;
3. il ledger registra le decisioni e il rationale;
4. i prerequisiti impediscono di saltare fasi;
5. F4 separa concetti da schema-linking;
6. le memory accettano solo `concept_clarified`;
7. rollback ed `effective_decisions()` escludono stato obsoleto.
1. the skill requires one ambiguity at a time;
2. the gate provides constrained widgets and `Altro/Back/Exit` controls;
3. the ledger records decisions and rationale;
4. prerequisites prevent phases from being skipped;
5. F4 separates concepts from schema linking;
6. Memory accepts only `concept_clarified`;
7. rollback and `effective_decisions()` exclude obsolete state.
Il risultato è una catena verificabile:
The result is a verifiable chain:
```text
termine ambiguo
→ evidenza e candidate interpretations
→ scelta esplicita del reviewer
→ concept_clarified nel ledger
→ domanda riscritta
→ schema-linking locale
→ piano CTE e SQL
ambiguous term
→ Evidence and candidate interpretations
→ explicit reviewer choice
→ concept_clarified in the ledger
→ rewritten question
→ local schema linking
→ CTE plan and SQL
```
## Riferimenti
## References
- [Skill canonica completa](skill-tht-sessione.md)
- [Workflow YAML](../harness/workflow.yaml)
- [Gate Pi](../harness/.pi/extensions/tht-gate.js)
- [Macchina delle fasi](../harness/tht/phase.py)
- [Gestione delle memory](gestione-memory.md)
- [Memory management](gestione-memory.md)