@turingcode/cli 0.1.1 → 0.2.1

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.
Files changed (32) hide show
  1. package/README.md +123 -0
  2. package/dist/cli/create-cli.js +7 -1
  3. package/dist/core/bound-error.js +14 -0
  4. package/dist/{features/table/ast.js → core/exact/expression.js} +22 -14
  5. package/dist/{features/table → core/exact}/fraction.js +62 -0
  6. package/dist/core/files.js +26 -0
  7. package/dist/{features/table/shape.js → core/json-shape.js} +45 -40
  8. package/dist/core/query.js +226 -0
  9. package/dist/core/report.js +14 -0
  10. package/dist/core/tables/csv.js +95 -0
  11. package/dist/core/tables/markdown.js +107 -0
  12. package/dist/core/tables/types.js +1 -0
  13. package/dist/features/contract/check.js +31 -0
  14. package/dist/features/contract/command.js +79 -0
  15. package/dist/features/contract/describe.js +86 -0
  16. package/dist/features/contract/diagnostics.js +109 -0
  17. package/dist/features/contract/load.js +200 -0
  18. package/dist/features/contract/model.js +31 -0
  19. package/dist/features/contract/rules.js +298 -0
  20. package/dist/features/table/check.js +341 -0
  21. package/dist/features/table/command.js +22 -75
  22. package/dist/features/table/read.js +33 -0
  23. package/package.json +3 -2
  24. package/dist/features/table/contract.js +0 -487
  25. package/dist/features/table/contract_check.js +0 -265
  26. package/dist/features/table/describe.js +0 -200
  27. package/dist/features/table/diagnostics.js +0 -129
  28. package/dist/features/table/format.js +0 -75
  29. package/dist/features/table/primitives.js +0 -268
  30. package/dist/features/table/source_kinds.js +0 -41
  31. package/dist/features/table/table_check.js +0 -538
  32. package/dist/features/table/tables.js +0 -223
@@ -1,487 +0,0 @@
1
- import { AstError, BoundError, evaluate, parseExpression } from "./ast.js";
2
- import { contractDiag, show } from "./diagnostics.js";
3
- import { NEEDS_SOURCE_ORDER, NEEDS_UNIT_TABLE, PARAM_REFS, PRIMITIVES } from "./primitives.js";
4
- import { checkShape } from "./shape.js";
5
- /** The engine schema version this engine implements. */
6
- export const ENGINE_SCHEMA_VERSION = "1.0.0";
7
- /** Column types a contract may declare (closed; taken from spec §3.2). */
8
- export const COLUMN_TYPES = ["id", "enum", "text", "number_or_text", "unit", "id_ref", "id_ref_list", "quote"];
9
- const STRICT_TYPES = ["text", "numeral", "id_ref", "table"];
10
- const STRICT_SOURCES = ["call_quote", "calc", "premise"];
11
- const EXTENSION_COLUMNS = ["Table", "Column", "Type", "Source", "Reader"];
12
- /** Names a contract-embedded factor expression may use; pi is irrational, so it evaluates to null. */
13
- const FACTOR_NAMES = new Set(["pi"]);
14
- const SL = { list: "string" };
15
- const RULE = {
16
- obj: {
17
- rule_id: "string",
18
- check_group: { enum: ["C0", "C1", "C2", "C3", "C4", "C5"] },
19
- primitive: "string",
20
- params: { map: "any" },
21
- severity: { enum: ["FAIL", "NOTE"] },
22
- "when?": { map: "string_or_list" },
23
- "mutation_strategy?": "string",
24
- citation: "string",
25
- },
26
- };
27
- const TABLE = {
28
- obj: {
29
- name: "string",
30
- required: "bool",
31
- id_column: { nullable: "string" },
32
- "id_pattern?": "regex",
33
- columns: {
34
- list: {
35
- obj: {
36
- name: "string", type: { enum: COLUMN_TYPES }, required: "bool", allow_dash: "bool",
37
- "allowed_values?": SL, "ref_target?": "string",
38
- },
39
- },
40
- min: 1,
41
- },
42
- "sentinel_rows?": { list: { obj: { id_prefix: "string", min_count: "int", max_count: "int" } } },
43
- rules: { list: RULE },
44
- },
45
- };
46
- const CONTRACT = {
47
- obj: {
48
- contract_id: "string",
49
- version: "version",
50
- engine_schema_version: "version",
51
- source_kinds_version: "version",
52
- upstream_contracts: { list: "pin" },
53
- input_format: { enum: ["markdown_tables", "csv"] },
54
- stage_id: "string",
55
- prose_rules: { list: { obj: { id: "string", section: "string", text: "string" } } },
56
- "golden_fixture?": {
57
- obj: { output_path: "string", offline_replies_dir: "string", "upstream_outputs?": { map: "any" } },
58
- },
59
- "source_order?": { list: "string", min: 1 },
60
- "unit_table?": {
61
- obj: {
62
- kept_units: SL,
63
- convert_units: { map: "any" },
64
- "scale_families?": { map: { map: "any" } },
65
- "count_per_time?": {
66
- obj: { per_symbols: SL, per_words: SL, count_units: SL, time_units: SL, rate_units: SL },
67
- },
68
- "unit_factors?": { list: "any" },
69
- },
70
- },
71
- id_token_regex: "regex",
72
- stage_name_regex: "regex",
73
- bounds: {
74
- obj: Object.fromEntries([
75
- "max_ast_nodes", "max_table_rows", "max_header_backtrack_lines", "max_page_intervals", "max_oracle_points",
76
- "max_mutations_per_contract", "max_cross_stage_depth", "max_words_per_quote", "max_helper_files",
77
- ].map(k => [k, "pos_int"])),
78
- },
79
- tables: { list: TABLE, min: 1 },
80
- cross_table_rules: { list: RULE },
81
- extensions_policy: { map: "any" },
82
- },
83
- };
84
- const EXTENSIONS_ON = {
85
- obj: {
86
- allowed: { literal: true },
87
- mode: { enum: ["strict", "legacy_v1"] },
88
- table_name: "string",
89
- required_columns: SL,
90
- "allowed_types?": SL,
91
- "allowed_sources?": SL,
92
- reader_pattern: "regex",
93
- "legacy_reader_pattern?": "regex",
94
- },
95
- };
96
- const EXTENSIONS_OFF = { obj: { allowed: { literal: false } } };
97
- /**
98
- * Pushes a DUPLICATE diagnostic for every repeated name.
99
- *
100
- * @param {string[]} names - Names that must be unique.
101
- * @param {string} what - What they are, for the message.
102
- * @param {string} table - Diagnostic table field.
103
- * @param {Diagnostic[]} out - Receives diagnostics.
104
- */
105
- function checkUnique(names, what, table, out) {
106
- const seen = new Set();
107
- for (const n of names) {
108
- if (seen.has(n)) {
109
- out.push(contractDiag("CONTRACT.DUPLICATE", `duplicate ${what} '${n}'`, { table }, n, `unique ${what}`));
110
- }
111
- seen.add(n);
112
- }
113
- }
114
- /**
115
- * Parses and exactly evaluates one contract-embedded factor (spec §3.4, T0 boundary).
116
- *
117
- * @param {unknown} value - A factor: a string expression, or an integer when `allowInt`.
118
- * @param {string} path - JSON path for the diagnostic.
119
- * @param {number} maxNodes - `bounds.max_ast_nodes`.
120
- * @param {boolean} allowInt - Whether a bare JSON integer is accepted (scale exponents).
121
- * @param {Diagnostic[]} out - Receives diagnostics.
122
- */
123
- function checkFactor(value, path, maxNodes, allowInt, out) {
124
- const at = { table: "unit_table", column: path };
125
- if (typeof value === "number") {
126
- if (!(allowInt && Number.isInteger(value))) {
127
- out.push(contractDiag("CONTRACT.FLOAT_LITERAL", `${path}: numeric factor must be a string`, at, show(value), "a string such as \"0.001\""));
128
- }
129
- return;
130
- }
131
- if (typeof value !== "string") {
132
- out.push(contractDiag("CONTRACT.BAD_TYPE", `${path}: expected a factor string`, at, show(value), "string"));
133
- return;
134
- }
135
- try {
136
- const factor = evaluate(parseExpression(value, maxNodes, FACTOR_NAMES), { pi: null });
137
- if (factor?.isZero()) {
138
- throw new AstError("factor is zero");
139
- }
140
- }
141
- catch (e) {
142
- if (e instanceof BoundError) {
143
- out.push(contractDiag("CONTRACT.BOUND_EXCEEDED", `${path}: ${e.message}`, at, show(value), `<= ${e.limit} nodes`));
144
- }
145
- else if (e instanceof AstError) {
146
- out.push(contractDiag("CONTRACT.AST_ERROR", `${path}: ${e.message}`, at, show(value), "an exact expression"));
147
- }
148
- else {
149
- throw e;
150
- }
151
- }
152
- }
153
- /**
154
- * Checks every factor in `unit_table` (convert_units, scale_families, unit_factors).
155
- *
156
- * @param {Contract} c - A shape-valid contract.
157
- * @param {Diagnostic[]} out - Receives diagnostics.
158
- */
159
- function checkUnitTable(c, out) {
160
- const ut = c.unit_table;
161
- if (!ut) {
162
- return;
163
- }
164
- const maxNodes = c.bounds.max_ast_nodes;
165
- for (const [unit, entry] of Object.entries(ut.convert_units)) {
166
- const path = `$.unit_table.convert_units.${unit}`;
167
- if (!Array.isArray(entry) || entry.length !== 2 || typeof entry[0] !== "string" || entry[0] === "") {
168
- out.push(contractDiag("CONTRACT.BAD_TYPE", `${path}: expected [base_unit, factor]`, { table: "unit_table", column: path }, show(entry), "[\"<base unit>\", \"<factor>\"]"));
169
- continue;
170
- }
171
- checkFactor(entry[1], `${path}[1]`, maxNodes, false, out);
172
- }
173
- for (const [family, units] of Object.entries(ut.scale_families ?? {})) {
174
- for (const [unit, scale] of Object.entries(units)) {
175
- checkFactor(scale, `$.unit_table.scale_families.${family}.${unit}`, maxNodes, true, out);
176
- }
177
- }
178
- (ut.unit_factors ?? []).forEach((f, i) => checkFactor(f, `$.unit_table.unit_factors[${i}]`, maxNodes, false, out));
179
- }
180
- /**
181
- * Checks `extensions_policy` (spec §3.1 item 5, §3.6).
182
- *
183
- * @param {Record<string, unknown>} policy - The policy object.
184
- * @param {Diagnostic[]} out - Receives diagnostics.
185
- */
186
- function checkExtensionsPolicy(policy, out) {
187
- const at = { table: "extensions_policy" };
188
- const path = "$.extensions_policy";
189
- if (typeof policy.allowed !== "boolean") {
190
- out.push(contractDiag(policy.allowed === undefined ? "CONTRACT.MISSING_FIELD" : "CONTRACT.BAD_TYPE", `${path}: 'allowed' must be a boolean`, { ...at, column: `${path}.allowed` }, show(policy.allowed), "bool"));
191
- return;
192
- }
193
- if (!checkShape(policy, policy.allowed ? EXTENSIONS_ON : EXTENSIONS_OFF, path, at, out) || !policy.allowed) {
194
- return;
195
- }
196
- const missingCols = EXTENSION_COLUMNS.filter(c => !policy.required_columns.includes(c));
197
- if (missingCols.length) {
198
- out.push(contractDiag("CONTRACT.BAD_VALUE", `${path}.required_columns lacks ${missingCols.join(", ")}`, { ...at, column: `${path}.required_columns` }, show(policy.required_columns), EXTENSION_COLUMNS.join(", ")));
199
- }
200
- if (policy.mode === "strict") {
201
- for (const [key, allowed] of [["allowed_types", STRICT_TYPES], ["allowed_sources", STRICT_SOURCES]]) {
202
- const value = policy[key];
203
- const column = `${path}.${key}`;
204
- if (value === undefined) {
205
- out.push(contractDiag("CONTRACT.MISSING_FIELD", `${column} is required in strict mode`, { ...at, column }, "(absent)", `subset of ${allowed.join(", ")}`));
206
- }
207
- else if (value.some(v => !allowed.includes(v))) {
208
- out.push(contractDiag("CONTRACT.BAD_VALUE", `${column} has values outside the strict set`, { ...at, column }, show(value), `subset of ${allowed.join(", ")}`));
209
- }
210
- }
211
- }
212
- else if (policy.legacy_reader_pattern === undefined) {
213
- out.push(contractDiag("CONTRACT.MISSING_FIELD", `${path}.legacy_reader_pattern is required in legacy_v1 mode`, { ...at, column: `${path}.legacy_reader_pattern` }, "(absent)", "regex"));
214
- }
215
- }
216
- /**
217
- * Checks one rule: known primitive, matching group, params signature, and
218
- * the intra-stage references a rule makes.
219
- *
220
- * @param {Rule} rule - A shape-valid rule.
221
- * @param {Table | null} table - The table the rule belongs to (null for cross_table_rules).
222
- * @param {Contract} c - The contract.
223
- * @param {SourceKinds | null} registry - The pinned registry, when valid.
224
- * @param {Diagnostic[]} out - Receives diagnostics.
225
- */
226
- function checkRule(rule, table, c, registry, out) {
227
- const at = { table: table?.name ?? "*", row_id: rule.rule_id };
228
- const primitive = PRIMITIVES[rule.primitive];
229
- if (!primitive) {
230
- out.push(contractDiag("CONTRACT.UNKNOWN_PRIMITIVE", `unknown primitive '${rule.primitive}'`, { ...at, column: "primitive" }, rule.primitive, "a primitive from spec §3.3"));
231
- return;
232
- }
233
- if (primitive.group !== rule.check_group) {
234
- out.push(contractDiag("CONTRACT.GROUP_MISMATCH", `${rule.primitive} belongs to ${primitive.group}`, { ...at, column: "check_group" }, rule.check_group, primitive.group));
235
- }
236
- if (!primitive.params) {
237
- out.push(contractDiag("CONTRACT.UNSPECIFIED_PARAMS_SIGNATURE", `${rule.primitive} has no settled params signature`, { ...at, column: "params" }, show(rule.params), "see spec §9", "NOTE"));
238
- return;
239
- }
240
- if (!checkShape(rule.params, { obj: primitive.params }, "params", at, out, "CONTRACT.INVALID_RULE_PARAMS")) {
241
- return;
242
- }
243
- const p = rule.params;
244
- const tableNames = new Map(c.tables.map(t => [t.name, t]));
245
- checkParamRefs(rule, table, tableNames, out);
246
- const redundant = redundantReason(rule, table);
247
- if (redundant) {
248
- out.push(contractDiag("CONTRACT.REDUNDANT_RULE", `${rule.primitive} repeats ${redundant}`, { ...at, column: "primitive" }, rule.primitive, "no rule (the declaration enforces it)"));
249
- }
250
- const upstreamIds = c.upstream_contracts.map(pin => pin.split("@")[0]);
251
- for (const param of ["target_contracts", "upstream_stages"]) {
252
- for (const id of p[param] ?? []) {
253
- if (!upstreamIds.includes(id)) {
254
- out.push(contractDiag("CONTRACT.ORPHAN_REF", `contract '${id}' is not pinned in upstream_contracts`, { ...at, column: `params.${param}` }, id, upstreamIds.join(", ") || "(none pinned)"));
255
- }
256
- }
257
- }
258
- if (rule.primitive === "foreign_key") {
259
- if (p.target_contracts === undefined) {
260
- if (p.target_table === undefined) {
261
- out.push(contractDiag("CONTRACT.INVALID_RULE_PARAMS", "foreign_key needs target_table or target_contracts", { ...at, column: "params" }, show(p), "target_table or target_contracts"));
262
- }
263
- else {
264
- checkTableColumn(String(p.target_table), p.target_column, tableNames, at, out);
265
- }
266
- }
267
- }
268
- if (rule.primitive === "page_span_coverage" && registry) {
269
- const known = new Set(registry.kinds.map(k => k.kind_id));
270
- for (const id of p.source_kind_ids ?? []) {
271
- if (!known.has(id)) {
272
- out.push(contractDiag("CONTRACT.ORPHAN_REF", `source kind '${id}' is not in source_kinds@${registry.source_kinds_version}`, { ...at, column: "params.source_kind_ids" }, id, [...known].join(", ")));
273
- }
274
- }
275
- }
276
- }
277
- /**
278
- * Resolves every table/column name a rule's params (and `when` filters) use
279
- * against this contract's tables, per PARAM_REFS.
280
- *
281
- * @param {Rule} rule - A rule whose params match its signature.
282
- * @param {Table | null} table - The rule's table (null for cross_table_rules).
283
- * @param {Map<string, Table>} tables - Tables of the contract.
284
- * @param {Diagnostic[]} out - Receives diagnostics.
285
- */
286
- function checkParamRefs(rule, table, tables, out) {
287
- const at = { table: table?.name ?? "*", row_id: rule.rule_id };
288
- const p = rule.params;
289
- const columnsOf = (t) => t.columns.map(col => col.name);
290
- const needTable = (param) => out.push(contractDiag("CONTRACT.BAD_VALUE", `${param} names a column of the rule's own table, so the rule must sit under a table, not in cross_table_rules`, { ...at, column: param }, show(p[param] ?? rule.when), "the rule under tables[].rules"));
291
- const refs = { ...PARAM_REFS[rule.primitive], ...(rule.primitive === "foreign_key" ? { column: "self" } : {}) };
292
- for (const [param, ref] of Object.entries(refs)) {
293
- const value = p[param];
294
- if (value === undefined)
295
- continue;
296
- const names = Array.isArray(value) ? value : [String(value)];
297
- const column = `params.${param}`;
298
- if (ref === "table") {
299
- for (const n of names.filter(n => !tables.has(n))) {
300
- out.push(contractDiag("CONTRACT.ORPHAN_REF", `${column}: table '${n}' does not exist`, { ...at, column }, n, [...tables.keys()].join(", ")));
301
- }
302
- continue;
303
- }
304
- if (ref === "self" && !table) {
305
- needTable(column);
306
- continue;
307
- }
308
- const holder = ref === "self" ? table : tables.get(String(p[ref]));
309
- if (ref !== "self" && p[ref] === undefined) {
310
- out.push(contractDiag("CONTRACT.INVALID_RULE_PARAMS", `${column} needs params.${ref} to say which table it is in`, { ...at, column }, show(value), `params.${ref}`));
311
- continue;
312
- }
313
- if (!holder)
314
- continue; // the missing table is reported under its own param
315
- for (const n of names.filter(n => !columnsOf(holder).includes(n))) {
316
- out.push(contractDiag("CONTRACT.ORPHAN_REF", `${column}: column '${n}' is not in table ${holder.name}`, { ...at, column }, n, columnsOf(holder).join(", ")));
317
- }
318
- }
319
- for (const [where, when] of [["when", rule.when], ["params.when", p.when]]) {
320
- if (!when || typeof when !== "object")
321
- continue;
322
- if (!table) {
323
- needTable(where);
324
- continue;
325
- }
326
- for (const n of Object.keys(when).filter(n => !columnsOf(table).includes(n))) {
327
- out.push(contractDiag("CONTRACT.ORPHAN_REF", `${where}: column '${n}' is not in table ${table.name}`, { ...at, column: where }, n, columnsOf(table).join(", ")));
328
- }
329
- }
330
- }
331
- /**
332
- * Says what declaration a rule merely repeats. Table declarations enforce
333
- * presence, column order, ID format and uniqueness, enum values, filled
334
- * cells, sentinel rows, ref_target and the Extensions schema by themselves,
335
- * so a rule that only restates one of them is redundant.
336
- *
337
- * @param {Rule} rule - A rule whose params match its signature.
338
- * @param {Table | null} table - The rule's table (null for cross_table_rules).
339
- * @returns {string | null} What it repeats, or null when the rule adds a check.
340
- */
341
- function redundantReason(rule, table) {
342
- const p = rule.params;
343
- switch (rule.primitive) {
344
- case "required_tables":
345
- return "the tables[].required declarations";
346
- case "column_order":
347
- return "the tables[].columns declarations";
348
- case "extension_schema":
349
- return "extensions_policy";
350
- }
351
- if (!table)
352
- return null;
353
- const col = (name) => table.columns.find(c => c.name === name);
354
- switch (rule.primitive) {
355
- case "id_pattern":
356
- return p.id_col === table.id_column && p.pattern === table.id_pattern ? `${table.name}.id_pattern` : null;
357
- case "unique_id":
358
- return p.id_col === table.id_column ? `${table.name}.id_column (IDs are unique)` : null;
359
- case "allowed_values": {
360
- const c = col(p.column);
361
- if (c?.type !== "enum" || p.multi_valued_sep !== undefined
362
- || (p.allow_dash !== undefined && p.allow_dash !== c.allow_dash)) {
363
- return null;
364
- }
365
- const declared = new Set((c.allowed_values ?? []).filter(v => v !== "-"));
366
- const given = new Set(p.values.filter(v => v !== "-"));
367
- const same = declared.size === given.size && [...given].every(v => declared.has(v));
368
- return same ? `${table.name}.${c.name}.allowed_values` : null;
369
- }
370
- case "non_empty":
371
- return p.columns.every(n => col(n)?.required) ? `the columns' required: true` : null;
372
- case "sentinel_row":
373
- return (table.sentinel_rows ?? []).some(s => s.id_prefix === p.id_value && p.id_col === table.id_column
374
- && s.min_count === p.min_count && s.max_count === p.max_count) ? `${table.name}.sentinel_rows` : null;
375
- case "foreign_key": {
376
- const c = col(p.column);
377
- const target = `${p.target_table}.${p.target_column ?? ""}`;
378
- return p.target_contracts === undefined && c?.ref_target !== undefined
379
- && (c.ref_target === target || c.ref_target.startsWith(`${p.target_table}.`) && p.target_column === undefined)
380
- ? `${table.name}.${c.name}.ref_target` : null;
381
- }
382
- }
383
- return null;
384
- }
385
- /**
386
- * Checks that `table[.column]` exists in this contract (column defaults to the id column).
387
- *
388
- * @param {string} tableName - Target table.
389
- * @param {string | undefined} column - Target column.
390
- * @param {Map<string, Table>} tables - Tables of the contract.
391
- * @param {object} at - Diagnostic location.
392
- * @param {Diagnostic[]} out - Receives diagnostics.
393
- */
394
- function checkTableColumn(tableName, column, tables, at, out) {
395
- const target = tables.get(tableName);
396
- if (!target) {
397
- out.push(contractDiag("CONTRACT.ORPHAN_REF", `table '${tableName}' does not exist`, at, tableName, [...tables.keys()].join(", ")));
398
- return;
399
- }
400
- const col = column ?? target.id_column;
401
- if (!col || !target.columns.some(c => c.name === col)) {
402
- out.push(contractDiag("CONTRACT.ORPHAN_REF", `column '${tableName}.${col ?? "(no id column)"}' does not exist`, at, `${tableName}.${col}`, target.columns.map(c => `${tableName}.${c.name}`).join(", ")));
403
- }
404
- }
405
- /**
406
- * Validates one contract on its own (spec §3.1-§3.4): shape, tables,
407
- * rules, factors, extensions policy and the pinned registry/engine versions.
408
- * Cross-stage resolution is done by contract_check.
409
- *
410
- * @param {unknown} data - Parsed contract JSON.
411
- * @param {SourceKinds | null} registry - The registry given to contract_check, or null when invalid.
412
- * @returns {Diagnostic[]} All findings; FAIL entries make the contract invalid.
413
- */
414
- export function validateContract(data, registry) {
415
- const out = [];
416
- if (!checkShape(data, CONTRACT, "$", {}, out)) {
417
- // Semantic checks need a well-formed contract; the shape errors already say what to fix.
418
- return out;
419
- }
420
- const c = data;
421
- if (c.engine_schema_version !== ENGINE_SCHEMA_VERSION) {
422
- out.push(contractDiag("CONTRACT.VERSION_MISMATCH", "engine_schema_version is not implemented by this engine", { column: "$.engine_schema_version" }, c.engine_schema_version, ENGINE_SCHEMA_VERSION));
423
- }
424
- if (registry && c.source_kinds_version !== registry.source_kinds_version) {
425
- out.push(contractDiag("CONTRACT.VERSION_MISMATCH", "source_kinds_version does not match the given registry", { column: "$.source_kinds_version" }, c.source_kinds_version, registry.source_kinds_version));
426
- }
427
- checkUnique(c.tables.map(t => t.name), "table", "*", out);
428
- checkUnique(c.upstream_contracts, "upstream pin", "*", out);
429
- checkUnique(c.prose_rules.map(r => r.id), "prose rule id", "*", out);
430
- checkUnique([...c.tables.flatMap(t => t.rules), ...c.cross_table_rules].map(r => r.rule_id), "rule_id", "*", out);
431
- if (c.source_order) {
432
- checkUnique(c.source_order, "source_order entry", "*", out);
433
- for (const kind of registry?.kinds ?? []) {
434
- if (!c.source_order.includes(kind.doc_kind)) {
435
- out.push(contractDiag("CONTRACT.ORPHAN_REF", `doc_kind '${kind.doc_kind}' of ${kind.kind_id} is not ranked in source_order`, { column: "$.source_order" }, show(c.source_order), `contains ${kind.doc_kind}`));
436
- }
437
- }
438
- }
439
- const tableNames = new Map(c.tables.map(t => [t.name, t]));
440
- for (const t of c.tables) {
441
- const at = { table: t.name };
442
- checkUnique(t.columns.map(col => col.name), "column", t.name, out);
443
- if (t.id_column !== null) {
444
- if (!t.columns.some(col => col.name === t.id_column)) {
445
- out.push(contractDiag("CONTRACT.ORPHAN_REF", `id_column '${t.id_column}' is not a column`, { ...at, column: "id_column" }, t.id_column, t.columns.map(col => col.name).join(", ")));
446
- }
447
- if (t.id_pattern === undefined) {
448
- out.push(contractDiag("CONTRACT.MISSING_FIELD", "id_pattern is required when id_column is set", { ...at, column: "id_pattern" }, "(absent)", "regex"));
449
- }
450
- }
451
- for (const col of t.columns) {
452
- const colAt = { ...at, column: col.name };
453
- if (col.type === "enum" && !col.allowed_values) {
454
- out.push(contractDiag("CONTRACT.MISSING_FIELD", `enum column ${col.name} needs allowed_values`, colAt, "(absent)", "array of strings"));
455
- }
456
- if (col.ref_target !== undefined) {
457
- if (col.type !== "id_ref" && col.type !== "id_ref_list") {
458
- out.push(contractDiag("CONTRACT.BAD_VALUE", `ref_target on a ${col.type} column`, colAt, col.type, "id_ref or id_ref_list"));
459
- }
460
- const [refTable, refCol, ...rest] = col.ref_target.split(".");
461
- if (!refCol || rest.length) {
462
- out.push(contractDiag("CONTRACT.BAD_VALUE", "ref_target must be '<Table>.<Column>'", colAt, col.ref_target, "<Table>.<Column>"));
463
- }
464
- else {
465
- checkTableColumn(refTable, refCol, tableNames, colAt, out);
466
- }
467
- }
468
- }
469
- for (const s of t.sentinel_rows ?? []) {
470
- if (s.min_count > s.max_count) {
471
- out.push(contractDiag("CONTRACT.BAD_VALUE", `sentinel ${s.id_prefix}: min_count > max_count`, { ...at, column: "sentinel_rows" }, `${s.min_count} > ${s.max_count}`, "min_count <= max_count"));
472
- }
473
- }
474
- t.rules.forEach(rule => checkRule(rule, t, c, registry, out));
475
- }
476
- c.cross_table_rules.forEach(rule => checkRule(rule, null, c, registry, out));
477
- const primitivesUsed = new Set([...c.tables.flatMap(t => t.rules), ...c.cross_table_rules].map(r => r.primitive));
478
- for (const [field, needs] of [["unit_table", NEEDS_UNIT_TABLE], ["source_order", NEEDS_SOURCE_ORDER]]) {
479
- const users = [...primitivesUsed].filter(p => needs.has(p));
480
- if (users.length && c[field] === undefined) {
481
- out.push(contractDiag("CONTRACT.REQUIRES_FIELD", `${users.join(", ")} need(s) top-level '${field}'`, { column: `$.${field}` }, "(absent)", field));
482
- }
483
- }
484
- checkUnitTable(c, out);
485
- checkExtensionsPolicy(c.extensions_policy, out);
486
- return out;
487
- }