feat(opt): three efficiency levers for NL→SQL workflow

Lever 1: Join-graph via FK logics in annotations + suggest-fks command
  - TableAnnotation.foreign_keys field stores curated logical FKs (DWH has no FK constraints)
  - tht schema suggest-fks: mine from approved SQL, heuristics (time_key → dim_time),
    same-name discovery + explicit --assume flag for multi-owner PKs
  - mschema renders 【Foreign keys】 section populated; validation in merge.py
  - SKILL.md F4 now reads FKs from mschema-text, no custom data_time_key logic

Lever 2: Context-pack consolidation at kickoff (tht search pack)
  - Single embedding of question, reused for schema + evidence + solved searches
  - One command: tht search pack <question> --session <id> → retrieval_pack.md
  - Graceful degradation when Ollama/vector store unreachable (exit 0, empty sections)
  - SKILL.md F1 prescribes as first call; reduces model thinking turns via pre-retrieval

Lever 3: Phase-summary recap v2 auto-construction from session ledger
  - tht session show --json includes full decisions ledger
  - tht phase meta --json exports 'emits' (substantive decision types per phase)
  - Gate appends deterministic 【Decisioni registrate in questa fase】 section (appendLedgerSection)
  - Model authors only summary + checks; recap table comes from persisted state (exact by construction)
  - SKILL.md Disciplina 6: brief model output, gate fills the rest

Tests: 358 Python (including 10 FK + 3 pack + 1 session-ledger tests) + 111 JS gate tests, all pass.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-07 17:43:08 +02:00
co-authored by Claude Fable 5
parent 87e875bc81
commit e24b41b156
19 changed files with 936 additions and 29 deletions
@@ -199,3 +199,32 @@ test("enrichPhaseSummaryV2 preserves open_questions/checks untouched", () => {
assert.deepEqual(out.checks, [{ label: "x", status: "ok" }]);
assert.deepEqual(out.open_questions, ["domanda aperta"]);
});
// --- appendLedgerSection -----------------------------------------------------------
const { appendLedgerSection } = require("../enrich.js");
test("appendLedgerSection appends only the phase's substantive decisions", () => {
const data = { schema_version: 2, summary: "s", sections: [{ title: "Criteri", items: [] }] };
const decisions = [
{ seq: 1, type: "concept_clarified", subject: "ablazione", detail: "solo transcatetere", rationale: "r1" },
{ seq: 2, type: "phase_approved", subject: "phase:1", detail: "", rationale: "" }, // meta: non in emits
{ seq: 3, type: "table_promoted", subject: "dim_patient", detail: "", rationale: "" }, // altra fase
];
const out = appendLedgerSection(data, decisions, ["concept_clarified", "ambiguity_open"]);
assert.equal(out.sections.length, 2);
const ledger = out.sections[1];
assert.equal(ledger.title, "Decisioni registrate in questa fase (dal ledger)");
assert.equal(ledger.items.length, 1);
assert.equal(ledger.items[0].label, "concept_clarified: ablazione");
assert.equal(ledger.items[0].value, "solo transcatetere");
// input non mutato
assert.equal(data.sections.length, 1);
});
test("appendLedgerSection is a no-op without matching decisions or with empty ledger", () => {
const data = { schema_version: 2, summary: "s" };
assert.equal(appendLedgerSection(data, [], ["concept_clarified"]), data);
assert.equal(appendLedgerSection(data, [{ type: "sql_approved", subject: "x" }], ["concept_clarified"]), data);
assert.equal(appendLedgerSection(data, undefined, undefined), data);
});
+22
View File
@@ -151,10 +151,32 @@ function enrichCteResultColumns(payload, planTables, getColumns) {
return { ...payload, columns };
}
// Contract C bis. Appends a deterministic "decisions of this phase" section built
// from the session ledger, so the model's recap can stay thin (Discipline 6 exactness
// comes from persisted state, not model prose). `decisions` is session-show's ledger
// dump; `emits` is the phase's substantive decision-type list from workflow.yaml.
// No matching decisions -> data returned unchanged. Pure: returns a NEW object.
function appendLedgerSection(data, decisions, emits) {
const emitSet = new Set(emits || []);
const rows = (decisions || []).filter((d) => d && emitSet.has(d.type));
if (rows.length === 0) return data;
const section = {
title: "Decisioni registrate in questa fase (dal ledger)",
items: rows.map((d) => ({
label: `${d.type}: ${d.subject}`,
value: d.detail || "",
kind: "decision",
rationale: d.rationale || "",
})),
};
return { ...data, sections: [...(data.sections || []), section] };
}
module.exports = {
memoizeGetColumns,
enrichCtePlanV2,
buildCteResultV2,
enrichCteResultColumns,
enrichPhaseSummaryV2,
appendLedgerSection,
};
+17 -1
View File
@@ -42,6 +42,7 @@ import {
buildCteResultV2,
enrichCteResultColumns,
enrichPhaseSummaryV2,
appendLedgerSection,
} from "./gate/enrich.js";
import { isReserved } from "./reserved-labels.mjs";
@@ -898,11 +899,26 @@ export default function (pi) {
"Riepilogo di fase v2 non valido:\n- " + v.errors.join("\n- "),
);
}
const enriched = enrichPhaseSummaryV2(
let enriched = enrichPhaseSummaryV2(
data,
phaseMetaForNum(ctx, curNum),
makeGetColumns(ctx),
);
// Recap deterministico: appende la sezione "decisioni di questa fase"
// dal ledger (best-effort: un errore di lettura non blocca il gate).
try {
const show = JSON.parse(
tht(ctx, ["session", "show", session, "--json"]),
);
const meta = phaseMeta(ctx).phases.find((p) => p.num === curNum);
enriched = appendLedgerSection(
enriched,
show.decisions,
meta ? meta.emits : [],
);
} catch {
// ledger non leggibile: il riepilogo resta quello del modello
}
artifact = { ...artifact, data: enriched };
}