@turingcode/cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,265 @@
1
+ import { readdirSync, readFileSync } from "node:fs";
2
+ import { dirname, join, resolve } from "node:path";
3
+ import { validateContract } from "./contract.js";
4
+ import { contractDiag, show, sortDiagnostics } from "./diagnostics.js";
5
+ import { checkShape } from "./shape.js";
6
+ import { validateSourceKinds } from "./source_kinds.js";
7
+ /** Most .json files scanned in one folder to resolve upstream pins without a manifest (spec §8.2). */
8
+ export const MAX_KIT_DIR_SCAN_FILES = 256;
9
+ const pinOf = (data) => {
10
+ const d = data;
11
+ return d && typeof d === "object" && typeof d.contract_id === "string" && typeof d.version === "string"
12
+ ? `${d.contract_id}@${d.version}` : null;
13
+ };
14
+ /**
15
+ * Reads and parses a JSON file.
16
+ *
17
+ * @param {string} path - File path.
18
+ * @param {string} table - Diagnostic table label.
19
+ * @param {Diagnostic[]} out - Receives MISSING_FILE / BAD_JSON diagnostics.
20
+ * @returns {{ok: boolean, data: unknown}} The parsed value when ok.
21
+ */
22
+ export function readJson(path, table, out) {
23
+ let text;
24
+ try {
25
+ text = readFileSync(path, "utf-8").replace(/^/, "");
26
+ }
27
+ catch (e) {
28
+ out.push(contractDiag("CONTRACT.MISSING_FILE", `cannot read ${path}: ${e.message}`, { table }, path, "a readable file"));
29
+ return { ok: false, data: undefined };
30
+ }
31
+ try {
32
+ return { ok: true, data: JSON.parse(text) };
33
+ }
34
+ catch (e) {
35
+ out.push(contractDiag("CONTRACT.BAD_JSON", `${path}: ${e.message}`, { table }, path, "valid JSON"));
36
+ return { ok: false, data: undefined };
37
+ }
38
+ }
39
+ /**
40
+ * Indexes the contracts in one folder by `contract_id@version`.
41
+ * Files that are not contract objects are not indexed (they are not pins).
42
+ *
43
+ * @param {string} dir - Folder to scan.
44
+ * @param {Diagnostic[]} out - Receives BOUND_EXCEEDED / DUPLICATE diagnostics.
45
+ * @returns {Map<string, string> | null} pin -> file path, or null when the folder could not be fully indexed.
46
+ */
47
+ export function indexFolder(dir, out) {
48
+ const index = new Map();
49
+ let files;
50
+ try {
51
+ files = readdirSync(dir).filter(f => f.endsWith(".json")).sort();
52
+ }
53
+ catch (e) {
54
+ out.push(contractDiag("CONTRACT.MISSING_FILE", `cannot list ${dir}: ${e.message}`, {}, dir, "a folder"));
55
+ return null;
56
+ }
57
+ if (files.length > MAX_KIT_DIR_SCAN_FILES) {
58
+ out.push(contractDiag("CONTRACT.BOUND_EXCEEDED", `${dir} holds ${files.length} .json files`, {}, String(files.length), `<= ${MAX_KIT_DIR_SCAN_FILES} (use --kit-manifest)`));
59
+ return null;
60
+ }
61
+ for (const f of files) {
62
+ const path = join(dir, f);
63
+ let pin = null;
64
+ try {
65
+ pin = pinOf(JSON.parse(readFileSync(path, "utf-8").replace(/^/, "")));
66
+ }
67
+ catch {
68
+ // Unparseable files cannot be a pin target; a pin that needs one is reported as not found.
69
+ }
70
+ if (pin && index.has(pin)) {
71
+ out.push(contractDiag("CONTRACT.DUPLICATE", `${pin} is in both ${index.get(pin)} and ${path}`, {}, pin, "one file per contract_id@version"));
72
+ }
73
+ else if (pin) {
74
+ index.set(pin, path);
75
+ }
76
+ }
77
+ return index;
78
+ }
79
+ /**
80
+ * Status from diagnostics, most fundamental problem first.
81
+ *
82
+ * @param {Diagnostic[]} diags - All diagnostics.
83
+ * @returns {ContractCheckStatus} The status.
84
+ */
85
+ function statusOf(diags) {
86
+ const codes = new Set(diags.filter(d => d.severity === "FAIL").map(d => d.code));
87
+ if (codes.has("CONTRACT.MISSING_FILE") || codes.has("CONTRACT.UPSTREAM_NOT_FOUND"))
88
+ return "MISSING_DATA";
89
+ if (codes.has("CONTRACT.BOUND_EXCEEDED"))
90
+ return "SEARCH_BOUND_EXCEEDED";
91
+ return codes.size ? "INVALID_CONTRACT" : "VALID";
92
+ }
93
+ /**
94
+ * Validates a contract, or with `kit` the whole cross-stage contract graph (spec §2.1).
95
+ *
96
+ * @param {ContractCheckInput} input - Tool inputs.
97
+ * @returns {ContractCheckResult} Status, diagnostics and (with kit) resolved graph edges.
98
+ *
99
+ * @example
100
+ * contractCheck({ contract_path: "stage2.json", source_kinds_path: "source_kinds.json" }).status; // "VALID"
101
+ */
102
+ export function contractCheck(input) {
103
+ const diags = [];
104
+ const result = (extra = {}) => {
105
+ const all = sortDiagnostics(diags);
106
+ return {
107
+ status: statusOf(all), contract_id: null, version: null, engine_schema_version: null,
108
+ source_kinds_version: null, checked_contracts: [], diagnostics: all, ...extra,
109
+ };
110
+ };
111
+ const invalidInput = (message) => ({ ...result(), status: "INVALID_INPUT",
112
+ diagnostics: [contractDiag("CONTRACT.MISSING_FIELD", message, {}, show(input), "see spec §2.1 inputs")] });
113
+ if (!input.source_kinds_path)
114
+ return invalidInput("source_kinds_path is required");
115
+ if (input.kit && !input.contract_path && !input.kit_manifest_path) {
116
+ return invalidInput("kit needs contract_path or kit_manifest_path");
117
+ }
118
+ if (!input.kit && !input.contract_path)
119
+ return invalidInput("contract_path is required");
120
+ if (!input.kit && input.kit_manifest_path)
121
+ return invalidInput("kit_manifest_path needs kit: true");
122
+ const reg = readJson(input.source_kinds_path, "source_kinds", diags);
123
+ let registry = null;
124
+ if (reg.ok) {
125
+ const regDiags = validateSourceKinds(reg.data);
126
+ diags.push(...regDiags);
127
+ registry = regDiags.length ? null : reg.data;
128
+ }
129
+ const loaded = new Map();
130
+ /** Loads and validates one contract file once. */
131
+ const load = (path, expectedPin) => {
132
+ const key = resolve(path);
133
+ const seen = loaded.get(key);
134
+ if (seen)
135
+ return seen;
136
+ const own = [];
137
+ const file = readJson(path, "*", own);
138
+ const pin = file.ok ? pinOf(file.data) : null;
139
+ if (file.ok) {
140
+ own.push(...validateContract(file.data, registry));
141
+ if (expectedPin && pin !== expectedPin) {
142
+ own.push(contractDiag("CONTRACT.MANIFEST_MISMATCH", `manifest pins ${expectedPin} to ${path}`, {}, pin ?? "(no contract_id@version)", expectedPin));
143
+ }
144
+ }
145
+ const label = pin ?? path;
146
+ diags.push(...own.map(d => ({ ...d, message: `${label}: ${d.message}` })));
147
+ const entry = { path, pin, contract: file.ok && !own.some(d => d.severity === "FAIL") ? file.data : null };
148
+ loaded.set(key, entry);
149
+ return entry;
150
+ };
151
+ let manifest = null;
152
+ if (input.kit_manifest_path) {
153
+ const m = readJson(input.kit_manifest_path, "kit_manifest", diags);
154
+ manifest = new Map();
155
+ if (m.ok && checkShape(m.data, { obj: { contracts: { map: "string" } } }, "$", { table: "kit_manifest" }, diags)) {
156
+ const base = dirname(input.kit_manifest_path);
157
+ for (const [pin, rel] of Object.entries(m.data.contracts)) {
158
+ manifest.set(pin, join(base, rel));
159
+ }
160
+ }
161
+ }
162
+ const folderIndex = new Map();
163
+ /**
164
+ * Finds the file of an upstream pin: the manifest, else the pinning contract's folder.
165
+ * Returns null when the folder could not be indexed (already reported).
166
+ */
167
+ const locate = (pin, from) => {
168
+ if (manifest)
169
+ return manifest.get(pin);
170
+ const dir = dirname(resolve(from.path));
171
+ if (!folderIndex.has(dir))
172
+ folderIndex.set(dir, indexFolder(dir, diags));
173
+ const index = folderIndex.get(dir);
174
+ return index ? index.get(pin) : null;
175
+ };
176
+ /** Reports an upstream pin that has no file, unless the lookup itself already failed. */
177
+ const notFound = (pin, from, path) => path === undefined && diags.push(contractDiag("CONTRACT.UPSTREAM_NOT_FOUND", `${from.pin ?? from.path}: upstream ${pin} not found`, {}, pin, manifest ? "an entry in the kit manifest" : `a contract file in ${dirname(from.path)}`));
178
+ const roots = [];
179
+ if (input.contract_path)
180
+ roots.push(load(input.contract_path));
181
+ for (const [pin, path] of manifest ?? [])
182
+ roots.push(load(path, pin));
183
+ const root = roots[0];
184
+ if (!input.kit) {
185
+ for (const pin of root.contract?.upstream_contracts ?? []) {
186
+ const path = locate(pin, root);
187
+ if (!path)
188
+ notFound(pin, root, path);
189
+ }
190
+ }
191
+ else {
192
+ const maxDepth = root?.contract?.bounds.max_cross_stage_depth;
193
+ const done = new Set();
194
+ const stack = [];
195
+ /** Depth-first walk of upstream pins with cycle and depth checks. */
196
+ const visit = (node) => {
197
+ if (done.has(node))
198
+ return;
199
+ if (stack.includes(node)) {
200
+ const chain = [...stack.slice(stack.indexOf(node)), node].map(n => n.pin ?? n.path).join(" -> ");
201
+ diags.push(contractDiag("CONTRACT.CYCLE", `upstream cycle ${chain}`, {}, chain, "an acyclic graph"));
202
+ return;
203
+ }
204
+ if (maxDepth !== undefined && stack.length >= maxDepth) {
205
+ const chain = [...stack, node].map(n => n.pin ?? n.path).join(" -> ");
206
+ diags.push(contractDiag("CONTRACT.BOUND_EXCEEDED", `upstream chain deeper than max_cross_stage_depth`, {}, chain, `<= ${maxDepth} levels`));
207
+ return;
208
+ }
209
+ stack.push(node);
210
+ for (const pin of node.contract?.upstream_contracts ?? []) {
211
+ const path = locate(pin, node);
212
+ if (path)
213
+ visit(load(path, pin));
214
+ else
215
+ notFound(pin, node, path);
216
+ }
217
+ stack.pop();
218
+ done.add(node);
219
+ };
220
+ roots.forEach(visit);
221
+ }
222
+ const edges = [];
223
+ if (input.kit) {
224
+ const byPin = new Map([...loaded.values()].filter(l => l.pin).map(l => [l.pin, l]));
225
+ for (const l of loaded.values()) {
226
+ const c = l.contract;
227
+ if (!c)
228
+ continue;
229
+ const rules = [...c.tables.flatMap(t => t.rules.map(r => ({ r, table: t.name }))),
230
+ ...c.cross_table_rules.map(r => ({ r, table: "*" }))];
231
+ for (const { r, table } of rules.filter(x => x.r.primitive === "foreign_key")) {
232
+ const p = r.params;
233
+ for (const id of p.target_contracts ?? []) {
234
+ const pin = c.upstream_contracts.find(u => u.split("@")[0] === id);
235
+ const target = pin ? byPin.get(pin)?.contract : undefined;
236
+ if (!pin || !target)
237
+ continue; // unpinned / unresolved targets are already reported
238
+ const at = { table, row_id: r.rule_id, column: "params.target_table" };
239
+ if (p.target_table !== undefined) {
240
+ const t = target.tables.find(x => x.name === p.target_table);
241
+ const col = p.target_column ?? t?.id_column ?? undefined;
242
+ if (!t || !col || !t.columns.some(x => x.name === col)) {
243
+ diags.push(contractDiag("CONTRACT.ORPHAN_REF", `${l.pin}: ${pin} has no ${p.target_table}.${col ?? "(id)"}`, at, `${p.target_table}.${col ?? ""}`, target.tables.map(x => x.name).join(", ")));
244
+ continue;
245
+ }
246
+ }
247
+ edges.push({ from_contract: l.pin, table, column: p.column, to_contract: pin, target_table: p.target_table ?? "*" });
248
+ }
249
+ }
250
+ }
251
+ }
252
+ const checked = [...loaded.values()].filter(l => l.pin).map(l => {
253
+ const [contract_id, version] = l.pin.split("@");
254
+ return { contract_id, version };
255
+ });
256
+ const head = root?.contract;
257
+ return result({
258
+ contract_id: head?.contract_id ?? null,
259
+ version: head?.version ?? null,
260
+ engine_schema_version: head?.engine_schema_version ?? null,
261
+ source_kinds_version: head?.source_kinds_version ?? null,
262
+ checked_contracts: checked,
263
+ ...(input.kit ? { graph_edges: edges } : {}),
264
+ });
265
+ }
@@ -0,0 +1,197 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { contractCheck } from "./contract_check.js";
3
+ const TYPE_TEXT = {
4
+ id: "row ID",
5
+ enum: "one listed value",
6
+ text: "text",
7
+ number_or_text: "number or text",
8
+ unit: "unit (see Units)",
9
+ id_ref: "one row ID",
10
+ id_ref_list: "row IDs, comma-separated",
11
+ quote: "text copied exactly from the cited source",
12
+ };
13
+ const code = (v) => `\`${String(v)}\``;
14
+ const list = (vs) => vs.map(code).join(", ");
15
+ /** Escapes a cell for a Markdown table. */
16
+ const cell = (s) => s.replace(/\|/g, "\\|");
17
+ /**
18
+ * Says in words what a `when` filter selects.
19
+ *
20
+ * @param {Rule} rule - The rule.
21
+ * @returns {string} e.g. "For rows where `Kind` is `EXTRACTED`: ", or "".
22
+ */
23
+ function whenText(rule) {
24
+ const parts = [rule.when, rule.params.when].filter(Boolean).flatMap(w => Object.entries(w).map(([col, v]) => `${code(col)} is ${Array.isArray(v) ? `one of ${list(v)}` : code(v)}`));
25
+ return parts.length ? `For rows where ${parts.join(" and ")}: ` : "";
26
+ }
27
+ /**
28
+ * One plain-language sentence for a rule, for the prompt guide.
29
+ *
30
+ * @param {Rule} rule - The rule.
31
+ * @param {Contract} c - The contract (for upstream names).
32
+ * @returns {string} The sentence.
33
+ */
34
+ function ruleText(rule, c) {
35
+ const p = rule.params;
36
+ switch (rule.primitive) {
37
+ case "conditional_non_dash":
38
+ return `When ${code(p.when_column)} is ${p.in.length > 1 ? "one of " : ""}${list(p.in)}, ${code(p.target_column)} must have a real value (not \`-\`).`;
39
+ case "quote_on_line":
40
+ return `${code(p.quote_col)} must be copied from a single line of the reply of the call in ${code(p.call_col)}`
41
+ + (p.max_words ? `, at most ${p.max_words} words` : "") + ".";
42
+ case "token_whole_in_quote":
43
+ return `${code(p.target_col)} must appear in ${code(p.quote_col)} as a whole token`
44
+ + (p.forbid_quote_equals_value ? `, and ${code(p.quote_col)} must hold more than the value alone` : "") + ".";
45
+ case "token_provenance":
46
+ return `Every number in ${code(p.target_col)} must come from ${code(p.quote_col)} or ${code(p.value_col)}`
47
+ + (p.include_table_header ? " (or the header line of the cited reply table)" : "") + ".";
48
+ case "unit_in_quote":
49
+ return `${code(p.unit_col)} (or a spelling of the same unit) must appear as a word in ${code(p.quote_col)}.`;
50
+ case "unit_missing_in_quote":
51
+ return `${code(p.unit_col)} may not be \`-\` when ${code(p.quote_col)} writes a known unit right after `
52
+ + `${list(p.value_cols)}.`;
53
+ case "foreign_key": {
54
+ const where = p.target_contracts
55
+ ? `${p.target_table ? code(p.target_table) : "a table"} of ${list(p.target_contracts)} (the upstream output)`
56
+ : code(`${p.target_table}.${p.target_column ?? "ID"}`);
57
+ return `Every ID in ${code(p.column)} must exist in ${where}` + (p.allow_dash ? "; `-` means none." : ".");
58
+ }
59
+ case "source_priority_order":
60
+ return `${code(p.chosen_col)} must be the fact in ${code(p.facts_list_col)} (at least two) whose `
61
+ + `${code(p.doc_kind_col)} ranks highest in: ${list(c.source_order ?? [])}`
62
+ + (p.reason_col ? `; explain the choice in ${code(p.reason_col)}.` : ".");
63
+ case "page_span_coverage":
64
+ return `Every server file ${p.source_kind_ids ? `of kind ${list(p.source_kind_ids)} ` : ""}that a fact cites `
65
+ + "must be read in full: pages covering row 0 to total_rows with no gap.";
66
+ case "id_pattern":
67
+ return `${code(p.id_col)} must match ${code(p.pattern)}.`;
68
+ case "unique_id":
69
+ return `${code(p.id_col)} values must be unique.`;
70
+ case "allowed_values":
71
+ return `${code(p.column)} must be one of ${list(p.values)}`
72
+ + (p.multi_valued_sep ? ` (several allowed, separated by ${code(p.multi_valued_sep)})` : "") + ".";
73
+ case "non_empty":
74
+ return `${list(p.columns)} must not be empty.`;
75
+ case "sentinel_row":
76
+ return `Keep ${p.min_count === p.max_count ? `exactly ${p.min_count}` : `${p.min_count} to ${p.max_count}`} `
77
+ + `row(s) whose ${code(p.id_col)} is ${code(p.id_value)}.`;
78
+ case "extension_reader_citation":
79
+ return `When an upstream stage (${list(p.upstream_stages)}) declares an extension whose Reader is this stage, `
80
+ + "cite its column name (or one of its row IDs; a table's name or row IDs for a new table) outside the "
81
+ + `${list(p.exclude_sections ?? ["Inputs", "Extensions"])} sections.`;
82
+ case "written_equals":
83
+ return `${code(p.written_col)} must equal the exact value of ${code(p.expr_col)} `
84
+ + `(at least ${p.min_sig_digits ?? 6} significant digits when it does not terminate).`;
85
+ case "margin_sign_agrees":
86
+ return `${code(p.verdict_col)} must agree with the sign of ${code(p.result_col)} (FEASIBLE >= 0).`;
87
+ }
88
+ return `${code(rule.primitive)} with ${code(JSON.stringify(p))}.`;
89
+ }
90
+ /**
91
+ * Renders one table: its columns, ID format, sentinel rows, rules and prose rules.
92
+ *
93
+ * @param {Table} t - The table.
94
+ * @param {Contract} c - The contract.
95
+ * @returns {string[]} Markdown lines.
96
+ */
97
+ function tableSection(t, c) {
98
+ const lines = [`## ${t.name}${t.required ? "" : " (optional)"}`, ""];
99
+ if (t.id_column)
100
+ lines.push(`Row ID: ${code(t.id_column)}, matching ${code(t.id_pattern)}, unique.`);
101
+ for (const s of t.sentinel_rows ?? []) {
102
+ lines.push(`Keep ${s.min_count === s.max_count ? `exactly ${s.min_count}` : `${s.min_count} to ${s.max_count}`} `
103
+ + `row(s) whose ID starts with ${code(s.id_prefix)}; their IDs need not match the pattern.`);
104
+ }
105
+ lines.push("", "| Column | Content | Must be filled | `-` allowed | Values / references |", "|---|---|---|---|---|");
106
+ for (const col of t.columns) {
107
+ const values = col.ref_target ? `IDs of ${code(col.ref_target)}` : col.allowed_values ? list(col.allowed_values) : "";
108
+ lines.push(`| ${col.name} | ${TYPE_TEXT[col.type]} | ${col.required ? "yes" : "no"} | ${col.allow_dash ? "yes" : "no"} `
109
+ + `| ${cell(values)} |`);
110
+ }
111
+ const rules = t.rules.map(r => `- ${whenText(r)}${ruleText(r, c)}${r.severity === "NOTE" ? " (advice)" : ""}`);
112
+ const prose = c.prose_rules.filter(r => r.section === t.name).map(r => `- ${r.text}`);
113
+ if (rules.length || prose.length)
114
+ lines.push("", "Rules:", ...rules, ...prose);
115
+ lines.push("");
116
+ return lines;
117
+ }
118
+ /**
119
+ * Renders a contract as the Markdown table guide for a stage prompt (spec §2.3).
120
+ *
121
+ * @param {Contract} c - A valid contract.
122
+ * @param {SourceKinds} registry - Its pinned source_kinds registry.
123
+ * @returns {string} The guide.
124
+ */
125
+ export function renderGuide(c, registry) {
126
+ const lines = [
127
+ `# ${c.stage_id}: tables to write (${c.contract_id}@${c.version})`, "",
128
+ c.input_format === "csv"
129
+ ? "Write each table as `<Table>.csv` in the output folder, header row first."
130
+ : "Write each table under its own `## <Table>` heading as a Markdown table: a header row with exactly the "
131
+ + "columns below in this order, a `|---|` separator row, then one row per item. Write `\\|` for a `|` "
132
+ + "inside a cell. Leave no table out, and add no table or column that is not declared.",
133
+ "",
134
+ ];
135
+ for (const t of c.tables)
136
+ lines.push(...tableSection(t, c));
137
+ const crossProse = c.prose_rules.filter(r => !c.tables.some(t => t.name === r.section));
138
+ if (c.cross_table_rules.length || crossProse.length) {
139
+ lines.push("## Rules across tables", "");
140
+ lines.push(...c.cross_table_rules.map(r => `- ${ruleText(r, c)}`), ...crossProse.map(r => `- ${r.section}: ${r.text}`), "");
141
+ }
142
+ const policy = c.extensions_policy;
143
+ lines.push("## Extensions", "");
144
+ if (!policy.allowed) {
145
+ lines.push("No extra tables or columns are allowed.", "");
146
+ }
147
+ else {
148
+ lines.push(`To add a column to a table, or a new table, first declare it in a \`## ${policy.table_name}\` table with columns `
149
+ + `${list(policy.required_columns)}: one row per added column (\`Column\` = its name) or per new table `
150
+ + "(`Column` = `*`). Added columns go after the declared columns.", policy.mode === "strict"
151
+ ? `\`Type\` is one of ${list(policy.allowed_types)} (a \`numeral\` cell holds a number, an \`id_ref\` cell row IDs); `
152
+ + `\`Source\` is one of ${list(policy.allowed_sources)}; \`Reader\` matches ${code(policy.reader_pattern)}.`
153
+ : `\`Reader\` matches ${code(policy.legacy_reader_pattern)}.`, "");
154
+ }
155
+ if (registry.kinds.length) {
156
+ lines.push(`## Server files (source_kinds@${registry.source_kinds_version})`, "");
157
+ for (const k of registry.kinds) {
158
+ lines.push(`- ${code(k.kind_id)}: files named ${code(k.filename_pattern)}, document kind ${code(k.doc_kind)}; `
159
+ + (k.read_mode === "all_pages" ? "read every page, row 0 to total_rows" : "read the cited rows by row ID")
160
+ + (k.trigger_mode === "per_extracted_part" ? ", for every part you extract." : ", whenever you cite a page of one."));
161
+ }
162
+ lines.push("");
163
+ }
164
+ if (c.source_order)
165
+ lines.push(`Source priority, highest first: ${list(c.source_order)}.`, "");
166
+ const ut = c.unit_table;
167
+ if (ut) {
168
+ lines.push("## Units", "", `Write units as one of: ${list(ut.kept_units)}.`);
169
+ const conv = Object.entries(ut.convert_units).map(([from, [to, f]]) => f === "1" ? `${code(from)} is ${code(to)}` : `${code(from)} is ${code(to)} × ${f}`);
170
+ if (conv.length)
171
+ lines.push(`Other spellings: ${conv.join("; ")}.`);
172
+ if (ut.unit_factors?.length)
173
+ lines.push(`Scale by these factors only, written next to \`*\` or \`/\`: ${list(ut.unit_factors)}.`);
174
+ lines.push("");
175
+ }
176
+ return lines.join("\n").replace(/\n{3,}/g, "\n\n").trimEnd() + "\n";
177
+ }
178
+ /**
179
+ * contract_describe: validates the contract, then renders its prompt guide.
180
+ *
181
+ * @param {DescribeInput} input - Tool inputs.
182
+ * @returns {DescribeResult} OK with the Markdown guide, or the contract's problems.
183
+ */
184
+ export function describeContract(input) {
185
+ const checked = contractCheck(input);
186
+ if (checked.status !== "VALID") {
187
+ return { status: checked.status, contract: null, diagnostics: checked.diagnostics };
188
+ }
189
+ const read = (p) => JSON.parse(readFileSync(p, "utf-8").replace(/^/, ""));
190
+ const c = read(input.contract_path);
191
+ return {
192
+ status: "OK",
193
+ contract: { contract_id: c.contract_id, version: c.version, source_kinds_version: c.source_kinds_version },
194
+ markdown: renderGuide(c, read(input.source_kinds_path)),
195
+ diagnostics: checked.diagnostics,
196
+ };
197
+ }
@@ -0,0 +1,129 @@
1
+ /** code -> [fix_hint, evidence]; every CONTRACT.* code has one entry. */
2
+ const CONTRACT_HINTS = {
3
+ "CONTRACT.BAD_JSON": ["Fix the JSON syntax of the file.", "spec §3.1"],
4
+ "CONTRACT.BAD_TYPE": ["Give the field the JSON type named in 'expected'.", "spec §3.1"],
5
+ "CONTRACT.BAD_VALUE": ["Use one of the values named in 'expected'.", "spec §3.1"],
6
+ "CONTRACT.MISSING_FIELD": ["Add the field; the engine never fills in a default.", "spec §3.1"],
7
+ "CONTRACT.UNKNOWN_FIELD": ["Remove the field or correct its spelling.", "spec §3.1"],
8
+ "CONTRACT.DUPLICATE": ["Give each entry a unique name.", "spec §3.1"],
9
+ "CONTRACT.BAD_REGEX": ["Write a valid JavaScript regular expression.", "spec §3.1"],
10
+ "CONTRACT.UNKNOWN_PRIMITIVE": ["Use a primitive from the closed catalog.", "spec §3.3"],
11
+ "CONTRACT.GROUP_MISMATCH": ["Set check_group to the primitive's group.", "spec §3.3"],
12
+ "CONTRACT.INVALID_RULE_PARAMS": ["Match the primitive's params signature.", "spec §3.3 normative params"],
13
+ "CONTRACT.UNSPECIFIED_PARAMS_SIGNATURE": ["This primitive's params are not settled yet; expect changes.", "spec §9 Q2-Q3"],
14
+ "CONTRACT.REQUIRES_FIELD": ["Add the top-level field that this rule needs.", "spec §3.1"],
15
+ "CONTRACT.ORPHAN_REF": ["Point the reference at a table/column that exists.", "spec §2.1"],
16
+ "CONTRACT.CYCLE": ["Remove the circular upstream_contracts pin.", "spec §2.1"],
17
+ "CONTRACT.UPSTREAM_NOT_FOUND": ["Provide the pinned upstream contract file (manifest or same folder).", "spec §2.1"],
18
+ "CONTRACT.MANIFEST_MISMATCH": ["Make the manifest key match the file's contract_id@version.", "spec §2.1"],
19
+ "CONTRACT.VERSION_MISMATCH": ["Pin the version that the given file actually has.", "spec §3.5"],
20
+ "CONTRACT.FLOAT_LITERAL": ["Write the factor as a string, e.g. \"0.001\", so it stays exact.", "spec §3.4"],
21
+ "CONTRACT.AST_ERROR": ["Fix the expression so it parses and evaluates exactly.", "spec §3.4"],
22
+ "CONTRACT.BOUND_EXCEEDED": ["Simplify the input or raise the bound in contract.bounds.", "spec §8.2"],
23
+ "CONTRACT.MISSING_FILE": ["Check the path; the file must exist and be readable.", "spec §2.1"],
24
+ "CONTRACT.REDUNDANT_RULE": ["Remove the rule; the table declaration already enforces it.", "table declarations"],
25
+ };
26
+ /** code -> fix_hint for table_check diagnostics; evidence is the rule or declaration that failed. */
27
+ const TABLE_HINTS = {
28
+ "C0.MISSING_TABLE": "Add the table under a '## <Table>' heading with its header row.",
29
+ "C0.UNDECLARED_TABLE": "Remove the table, or declare it in the Extensions table with Column '*'.",
30
+ "C0.DUPLICATE_TABLE": "Merge the rows into one table under a single heading.",
31
+ "C0.BAD_TABLE": "Write the table as a header row, a '|---|' separator row, then data rows.",
32
+ "C0.COLUMN_MISMATCH": "Use exactly the expected column names, in the expected order.",
33
+ "C0.UNDECLARED_COLUMN": "Remove the column, or declare it in the Extensions table.",
34
+ "C0.EXTENSION_MISSING": "Add the table or column that the Extensions table declares, or remove its row.",
35
+ "C0.ROW_SHAPE": "Give the row one cell per column; write '\\|' for a '|' inside a cell.",
36
+ "C0.MISSING_ID": "Give the row its ID.",
37
+ "C0.BAD_ID": "Write the ID in the expected format.",
38
+ "C0.DUPLICATE_ID": "Give each row a unique ID.",
39
+ "C0.EMPTY_CELL": "Fill the cell; write '-' only where the column allows it.",
40
+ "C0.DASH_NOT_ALLOWED": "Replace '-' with a real value; this column does not allow '-'.",
41
+ "C0.BAD_VALUE": "Use one of the allowed values, spelled exactly.",
42
+ "C0.VALUE_REQUIRED": "Fill this cell with a real value; '-' is not allowed for this kind of row.",
43
+ "C0.SENTINEL_COUNT": "Keep exactly the required number of these rows.",
44
+ "C0.INVALID_EXTENSION": "Fix the Extensions row so it names a real table and a new column (or '*').",
45
+ "C0.INVALID_EXTENSION_TYPE": "Use one of the allowed extension types.",
46
+ "C0.INVALID_EXTENSION_SOURCE": "Use one of the allowed extension sources.",
47
+ "C0.INVALID_EXTENSION_READER": "Write the reader in the allowed form, e.g. 'stage 3' or 'supervisor'.",
48
+ "C0.EXTENSION_TYPE": "Make the cell match the type its Extensions row declares.",
49
+ "C1.UNKNOWN_REF": "Cite only IDs that exist in the referenced table.",
50
+ "C1.EXTENSION_NOT_CITED": "Cite the extension's column name (or one of its row IDs) where this stage uses it.",
51
+ "C1.MISSING_UPSTREAM_OUTPUT": "Pass the upstream stage's output file.",
52
+ ...Object.fromEntries(["C0", "C1", "C2", "C3", "C4", "C5"].map(g => [`${g}.NOT_CHECKED`, "Nothing to fix: this engine version cannot check this rule yet, so check it yourself."])),
53
+ "TABLE.MISSING_FILE": "Check the path; the file must exist and be readable.",
54
+ "TABLE.INVALID_INPUT": "Fix the command arguments named in the message.",
55
+ "TABLE.BOUND_EXCEEDED": "Split the table or raise the bound in contract.bounds.",
56
+ };
57
+ /**
58
+ * Builds a table_check diagnostic; the check group is the code's prefix.
59
+ *
60
+ * @param {string} code - A key of TABLE_HINTS, e.g. `C0.BAD_ID`.
61
+ * @param {string} message - What is wrong.
62
+ * @param {Where} at - Table, row ID and column of the finding.
63
+ * @param {string} found - Observed value.
64
+ * @param {string} expected - Required value.
65
+ * @param {string} evidence - Rule ID or declaration that the finding comes from.
66
+ * @param {"FAIL"|"NOTE"} [severity="FAIL"] - Severity.
67
+ * @returns {Diagnostic} The diagnostic.
68
+ */
69
+ export function tableDiag(code, message, at, found, expected, evidence, severity = "FAIL") {
70
+ const fix_hint = TABLE_HINTS[code];
71
+ if (fix_hint === undefined) {
72
+ throw new Error(`no hint for diagnostic code ${code}`);
73
+ }
74
+ return {
75
+ check_group: code.split(".")[0], severity, table: at.table ?? "*", row_id: at.row_id ?? "-",
76
+ column: at.column ?? "-", code, message, found, expected, fix_hint, evidence,
77
+ };
78
+ }
79
+ /**
80
+ * Builds a CONTRACT diagnostic with its fix hint and evidence.
81
+ *
82
+ * @param {string} code - A key of CONTRACT_HINTS.
83
+ * @param {string} message - What is wrong.
84
+ * @param {Where} at - Location in the contract.
85
+ * @param {string} found - Observed value.
86
+ * @param {string} expected - Required value.
87
+ * @param {"FAIL"|"NOTE"} [severity="FAIL"] - Severity.
88
+ * @returns {Diagnostic} The diagnostic.
89
+ */
90
+ export function contractDiag(code, message, at, found, expected, severity = "FAIL") {
91
+ const hint = CONTRACT_HINTS[code];
92
+ if (!hint) {
93
+ throw new Error(`no hint for diagnostic code ${code}`);
94
+ }
95
+ const [fix_hint, evidence] = hint;
96
+ return {
97
+ check_group: "CONTRACT", severity, table: at.table ?? "*", row_id: at.row_id ?? "-",
98
+ column: at.column ?? "-", code, message, found, expected, fix_hint, evidence,
99
+ };
100
+ }
101
+ /**
102
+ * Sorts diagnostics deterministically by (check_group, severity, table, row_id, column, code).
103
+ *
104
+ * @param {Diagnostic[]} list - Diagnostics.
105
+ * @returns {Diagnostic[]} A sorted copy.
106
+ */
107
+ export function sortDiagnostics(list) {
108
+ const key = (d) => [d.check_group, d.severity, d.table, d.row_id, d.column, d.code, d.message];
109
+ return [...list].sort((a, b) => {
110
+ const ka = key(a);
111
+ const kb = key(b);
112
+ for (let i = 0; i < ka.length; i++) {
113
+ if (ka[i] !== kb[i]) {
114
+ return ka[i] < kb[i] ? -1 : 1;
115
+ }
116
+ }
117
+ return 0;
118
+ });
119
+ }
120
+ /**
121
+ * Short, single-line JSON rendering of any value for `found` fields.
122
+ *
123
+ * @param {unknown} v - Value.
124
+ * @returns {string} At most 80 characters.
125
+ */
126
+ export function show(v) {
127
+ const s = v === undefined ? "(absent)" : JSON.stringify(v);
128
+ return s.length > 80 ? s.slice(0, 77) + "..." : s;
129
+ }
@@ -0,0 +1,75 @@
1
+ /** Most rows listed on one grouped line before "+N more". */
2
+ const MAX_ROWS_PER_LINE = 20;
3
+ const isNotChecked = (d) => d.code.endsWith(".NOT_CHECKED");
4
+ /** Evidence worth printing: a rule ID, not a generic declaration or spec section. */
5
+ const ruleOf = (d) => (/^(declaration|spec |extensions_policy|Extensions)/.test(d.evidence) ? "" : ` [${d.evidence}]`);
6
+ const place = (...parts) => parts.filter(p => p !== "*" && p !== "-").join(" ");
7
+ /**
8
+ * Renders diagnostics as compact text lines for agents: one line per finding,
9
+ * findings that differ only by row grouped onto one line, rules not checked
10
+ * yet on one line, and each fix hint once per code.
11
+ *
12
+ * @param {Diagnostic[]} diags - Sorted diagnostics.
13
+ * @returns {string[]} The lines.
14
+ *
15
+ * @example
16
+ * formatDiagnostics(result.diagnostics);
17
+ * // ["FAIL C0.BAD_VALUE Facts Class ×2: F-2=Other, F-5=Lim; expected limit, other",
18
+ * // "fix C0.BAD_VALUE: Use one of the allowed values, spelled exactly."]
19
+ */
20
+ export function formatDiagnostics(diags) {
21
+ const lines = [];
22
+ const groups = new Map();
23
+ for (const d of diags.filter(d => !isNotChecked(d))) {
24
+ const key = [d.severity, d.code, d.table, d.column, d.expected, d.evidence].join("\u0000");
25
+ groups.set(key, [...(groups.get(key) ?? []), d]);
26
+ }
27
+ for (const [d, ...more] of groups.values()) {
28
+ if (!more.length) {
29
+ lines.push(`${d.severity} ${d.code} ${place(d.table, d.row_id, d.column)}: ${d.message}; expected ${d.expected}${ruleOf(d)}`);
30
+ continue;
31
+ }
32
+ const all = [d, ...more];
33
+ const rows = all.slice(0, MAX_ROWS_PER_LINE).map(x => `${x.row_id}=${x.found}`).join(", ");
34
+ const extra = all.length > MAX_ROWS_PER_LINE ? ` +${all.length - MAX_ROWS_PER_LINE} more` : "";
35
+ lines.push(`${d.severity} ${d.code} ${place(d.table, d.column)} ×${all.length}: ${rows}${extra}; expected ${d.expected}${ruleOf(d)}`);
36
+ }
37
+ const notChecked = diags.filter(isNotChecked);
38
+ if (notChecked.length) {
39
+ lines.push(`not checked yet, check by hand: ${notChecked.map(d => `${d.evidence} (${d.found})`).join(", ")}`);
40
+ }
41
+ const hints = new Map(diags.filter(d => !isNotChecked(d) && d.fix_hint).map(d => [d.code, d.fix_hint]));
42
+ for (const [codeName, hint] of hints)
43
+ lines.push(`fix ${codeName}: ${hint}`);
44
+ return lines;
45
+ }
46
+ /**
47
+ * Compact text for a table_check result.
48
+ *
49
+ * @param {TableCheckResult} r - The result.
50
+ * @returns {string} Status line, then the diagnostics.
51
+ */
52
+ export function formatTableCheck(r) {
53
+ const s = r.summary;
54
+ const pin = r.contract ? `${r.contract.contract_id}@${r.contract.version}` : "-";
55
+ const notes = r.diagnostics.filter(d => d.severity === "NOTE" && !isNotChecked(d)).length;
56
+ const head = `${r.status} ${pin}: ${s.tables_checked} tables, ${s.rows_checked} rows, ${s.fail_count} FAIL`
57
+ + (notes ? `, ${notes} NOTE` : "");
58
+ return [head, ...formatDiagnostics(r.diagnostics)].join("\n") + "\n";
59
+ }
60
+ /**
61
+ * Compact text for a contract_check result (also used for contract_describe errors).
62
+ *
63
+ * @param {ContractCheckResult} r - The result.
64
+ * @returns {string} Status line, cross-stage edges, then the diagnostics.
65
+ */
66
+ export function formatContractCheck(r) {
67
+ const pin = r.contract_id ? `${r.contract_id}@${r.version}` : "-";
68
+ const fails = r.diagnostics.filter(d => d.severity === "FAIL").length;
69
+ const checked = r.checked_contracts ? `${r.checked_contracts.length} contract(s), ` : "";
70
+ return [
71
+ `${r.status} ${pin}: ${checked}${fails} FAIL`,
72
+ ...(r.graph_edges ?? []).map(e => `edge ${e.from_contract} ${e.table}.${e.column} -> ${e.to_contract} ${e.target_table}`),
73
+ ...formatDiagnostics(r.diagnostics),
74
+ ].join("\n") + "\n";
75
+ }