@turingcode/cli 0.2.0 → 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.
@@ -1,11 +1,13 @@
1
1
  import { BoundError } from "../../core/bound-error.js";
2
2
  import { Fraction } from "../../core/exact/fraction.js";
3
+ import { compileQuery, prepareQuery } from "../../core/query.js";
3
4
  import { diag, formatDiagnostics, sortDiagnostics } from "../contract/diagnostics.js";
4
- import { loadContract, parseRef } from "../contract/load.js";
5
+ import { loadContract, parseRef, parseTableRef } from "../contract/load.js";
5
6
  import { keyColumns } from "../contract/model.js";
6
- import { listItems, RULE_KINDS } from "../contract/rules.js";
7
+ import { evaluateCalc, explain, listItems, mentions, numberColumns, parseCalc, renderCondition, splitQuery, } from "../contract/rules.js";
7
8
  import { readTables } from "./read.js";
8
9
  const DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
10
+ const plain = (v) => String(v);
9
11
  /**
10
12
  * Why a value does not fit its column's type, or null when it fits.
11
13
  *
@@ -30,19 +32,39 @@ function typeProblem(v, col) {
30
32
  return null;
31
33
  }
32
34
  }
35
+ /**
36
+ * A cell as a query sees it: null when missing, items for a list, true/false for a boolean, else the text.
37
+ *
38
+ * @param {string | undefined} v - The cell.
39
+ * @param {Column | undefined} col - Its column, when declared.
40
+ * @param {Missing} missing - Missing-value test.
41
+ * @returns {Value} The value.
42
+ */
43
+ function valueOf(v, col, missing) {
44
+ if (missing(v))
45
+ return null;
46
+ if (col?.type === "list")
47
+ return listItems(v, col.separator);
48
+ if (col?.type === "boolean" && (v === "true" || v === "false"))
49
+ return v === "true";
50
+ return v;
51
+ }
33
52
  /** Rows of a table keyed by its header; the label is the primary key, or `#n`. */
34
53
  function rowsOf(t, table, name, missing) {
35
54
  const parsed = t.tables.get(name);
36
55
  const key = table ? keyColumns(table) : [];
56
+ const columns = new Map((table?.columns ?? []).map(c => [c.name, c]));
37
57
  return parsed.rows.filter(r => r.length === parsed.header.length).map((r, k) => {
38
58
  const cells = Object.fromEntries(parsed.header.map((h, i) => [h, r[i]]));
59
+ const names = new Set([...parsed.header, ...columns.keys()]);
60
+ const doc = Object.fromEntries([...names].map(n => [n, valueOf(cells[n], columns.get(n), missing)]));
39
61
  const keyValues = key.map(c => cells[c] ?? "");
40
- return { label: key.length && keyValues.every(v => !missing(v)) ? keyValues.join("/") : `#${k + 1}`, cells };
62
+ return { label: key.length && keyValues.every(v => !missing(v)) ? keyValues.join("/") : `#${k + 1}`, cells, doc };
41
63
  });
42
64
  }
43
65
  /**
44
- * Checks tables against a contract: tables and columns, every cell against
45
- * its column, references, then the rules.
66
+ * Checks tables against a contract: tables and columns, every cell's type,
67
+ * every column's `match`, then the rules.
46
68
  *
47
69
  * @param {TableCheckInput} input - Contract, tables and dependency tables.
48
70
  * @returns {TableCheckResult} Status, summary and diagnostics.
@@ -87,7 +109,7 @@ export function tableCheck(input) {
87
109
  };
88
110
  const missingOf = (c) => {
89
111
  const values = new Set(c.missing_values ?? [""]);
90
- return (v) => v === undefined || values.has(v);
112
+ return v => v === undefined || values.has(v);
91
113
  };
92
114
  const deps = new Map();
93
115
  for (const [alias, dep] of loaded.deps) {
@@ -106,78 +128,130 @@ export function tableCheck(input) {
106
128
  if ("status" in text)
107
129
  return text;
108
130
  const missing = missingOf(contract);
109
- const rows = checkStructure(contract, text, missing, diags);
131
+ const { rows, badCells } = checkStructure(contract, text, missing, diags);
110
132
  summary.tables = rows.size;
111
133
  summary.rows = [...rows.values()].reduce((n, r) => n + r.length, 0);
112
134
  const self = { contract, text, rows };
113
- /** Rows, column and owner of a reference. */
114
- const refRows = (ref, owner) => {
135
+ /** Rows and column of a `Table.Column` / `alias:Table.Column` reference; null when its table was not read. */
136
+ const refRows = (ref) => {
115
137
  const p = parseRef(ref);
116
- const doc = p.alias ? deps.get(p.alias) : self;
117
- const tableName = p.table ?? owner.name;
118
- const table = doc?.contract.tables.find(t => t.name === tableName);
119
- const column = table?.columns.find(c => c.name === p.column);
120
- const tableRows = doc?.rows.get(tableName);
121
- return doc && column && tableRows ? { rows: tableRows, column, table: tableName, own: !p.alias } : null;
138
+ const file = p.alias ? deps.get(p.alias) : self;
139
+ const column = file?.contract.tables.find(t => t.name === p.table)?.columns.find(c => c.name === p.column);
140
+ const tableRows = file?.rows.get(p.table);
141
+ return column && tableRows ? { rows: tableRows, column } : null;
122
142
  };
123
143
  /** Non-missing values (list items split) of a reference. */
124
- const refValues = (ref, owner) => {
125
- const r = refRows(ref, owner);
126
- if (!r)
127
- return null;
128
- const docMissing = parseRef(ref).alias ? missingOf(deps.get(parseRef(ref).alias).contract) : missing;
129
- return new Set(r.rows.flatMap(row => {
130
- const v = row.cells[r.column.name];
131
- return docMissing(v) ? [] : r.column.type === "list" ? listItems(v, r.column.separator) : [v];
144
+ const refValues = (ref) => {
145
+ const r = refRows(ref);
146
+ return new Set((r?.rows ?? []).flatMap(row => {
147
+ const v = row.doc[r.column.name];
148
+ return v === null || v === undefined ? [] : Array.isArray(v) ? v : [String(v)];
132
149
  }));
133
150
  };
151
+ /**
152
+ * The query hooks for rows of one table.
153
+ *
154
+ * @param {Table} scope - The table whose rows are tested.
155
+ * @param {boolean} own - Whether it is in the checked document (its text is left out of `"*"`).
156
+ * @returns {CheckHooks} The hooks.
157
+ */
158
+ const hooksFor = (scope, own) => {
159
+ const known = new Map();
160
+ const texts = new Map();
161
+ const numbers = numberColumns(scope);
162
+ const calc = (param) => parseCalc(param, numbers);
163
+ const textOf = (targets) => {
164
+ const key = targets.join("\u0000");
165
+ if (!texts.has(key)) {
166
+ texts.set(key, targets.map(t => {
167
+ if (t === "*")
168
+ return text.textOutside(own ? [scope.name] : []);
169
+ const r = refRows(t);
170
+ return r ? r.rows.map(row => row.cells[r.column.name] ?? "").join("\n") : "";
171
+ }).join("\n"));
172
+ }
173
+ return texts.get(key);
174
+ };
175
+ return {
176
+ ref: (ref, v) => {
177
+ if (!known.has(ref))
178
+ known.set(ref, refValues(ref));
179
+ return known.get(ref).has(v);
180
+ },
181
+ mentioned: (targets, v) => mentions(textOf(targets), v),
182
+ calc: (param, doc) => evaluateCalc(calc(param), doc, numbers)?.holds ?? true,
183
+ calcValues: (param, doc) => evaluateCalc(calc(param), doc, numbers),
184
+ };
185
+ };
186
+ /**
187
+ * Runs each part of a query over rows in order (so `$unique` sees earlier rows) and reports the failures.
188
+ *
189
+ * @param {Query} q - The query.
190
+ * @param {Row[]} tableRows - The rows.
191
+ * @param {CheckHooks} hooks - Its hooks.
192
+ * @param {(r: Row) => boolean} skip - Rows not to test.
193
+ * @param {(f: ReturnType<typeof explain>, r: Row) => void} report - Receives each failure.
194
+ */
195
+ const runParts = (q, tableRows, hooks, skip, report) => {
196
+ for (const part of splitQuery(q)) {
197
+ const test = compileQuery(prepareQuery(part).query, hooks);
198
+ for (const r of tableRows.filter(row => !skip(row) && !test(row.doc)))
199
+ report(explain(part, r.doc, hooks), r);
200
+ }
201
+ };
134
202
  for (const t of contract.tables) {
135
203
  const tableRows = rows.get(t.name);
136
204
  if (!tableRows)
137
205
  continue;
138
- for (const col of t.columns.filter(c => c.references)) {
139
- const known = refValues(col.references, t);
140
- if (!known)
141
- continue; // the referenced table is missing: reported as MISSING_TABLE
142
- for (const r of tableRows) {
143
- const v = r.cells[col.name];
144
- if (missing(v))
145
- continue;
146
- for (const item of (col.type === "list" ? listItems(v, col.separator) : [v]).filter(x => !known.has(x))) {
147
- diags.push(diag("UNKNOWN_REF", `${item} is not a value of ${col.references}`, { table: t.name, row: r.label, column: col.name }, item, `a value of ${col.references}`));
148
- }
149
- }
206
+ const hooks = hooksFor(t, true);
207
+ for (const col of t.columns.filter(c => c.match)) {
208
+ runParts({ [col.name]: col.match }, tableRows, hooks, r => r.doc[col.name] === null || !!badCells.get(r)?.has(col.name), (f, r) => diags.push(diag(f.code, f.message, { table: t.name, row: r.label, column: f.column }, f.found, f.expected)));
150
209
  }
151
- (t.rules ?? []).forEach((rule, i) => {
152
- const when = Object.entries(rule.when ?? {});
153
- const matching = tableRows.filter(r => when.every(([c, v]) => (Array.isArray(v) ? v.includes(r.cells[c]) : r.cells[c] === v)));
154
- const ruleId = rule.id ?? `${t.name}.rules[${i}]`;
155
- const ctx = {
156
- rule, table: t, rows: matching, missing,
157
- refRows: ref => refRows(ref, t),
158
- columnText: ref => {
159
- const r = refRows(ref, t);
160
- return r ? r.rows.map(row => row.cells[r.column.name] ?? "").join("\n") : "";
161
- },
162
- textOutside: names => text.textOutside(names),
163
- fail: (code, message, row, column, found, expected) => diags.push(diag(code, message, { table: t.name, row, column, rule: ruleId }, found, expected, rule.severity === "warning" ? "WARN" : "FAIL")),
164
- };
165
- RULE_KINDS[rule.kind].check(ctx);
166
- });
210
+ (t.rules ?? []).forEach((rule, i) => checkRule(rule, `${t.name}.rules[${i}]`, t));
167
211
  }
168
212
  return finish();
213
+ /**
214
+ * Checks one rule: the rows of its table (or `on`) that match `when`, against `require` or `count`.
215
+ *
216
+ * @param {Rule} rule - The rule.
217
+ * @param {string} fallbackId - Its ID when it has none.
218
+ * @param {Table} owner - The table it is declared in.
219
+ */
220
+ function checkRule(rule, fallbackId, owner) {
221
+ const on = rule.on ? parseTableRef(rule.on) : { alias: null, table: owner.name };
222
+ const file = on.alias ? deps.get(on.alias) : self;
223
+ const scope = file?.contract.tables.find(t => t.name === on.table);
224
+ const scopeRows = file?.rows.get(on.table);
225
+ if (!scope || !scopeRows)
226
+ return; // the table is missing: reported as MISSING_TABLE
227
+ const hooks = hooksFor(scope, !on.alias);
228
+ const when = compileQuery(prepareQuery(rule.when ?? {}).query, hooks);
229
+ const matching = scopeRows.filter(r => when(r.doc));
230
+ const where = { table: rule.on ?? owner.name, rule: rule.id ?? fallbackId };
231
+ const severity = rule.severity === "warning" ? "WARN" : "FAIL";
232
+ if (rule.count) {
233
+ const test = compileQuery(prepareQuery({ _: rule.count }).query, hooks);
234
+ if (!test({ _: String(matching.length) })) {
235
+ diags.push(diag("ROW_COUNT", `${matching.length} matching rows`, where, String(matching.length), renderCondition(rule.count, plain), severity));
236
+ }
237
+ return;
238
+ }
239
+ runParts(rule.require, matching, hooks, () => false, (f, r) => diags.push(diag(f.code, f.message, { ...where, row: r.label, column: f.column }, f.found, rule.description ?? f.expected, severity)));
240
+ }
169
241
  }
170
242
  /**
171
- * Checks tables, columns and every cell against the contract's declarations.
243
+ * Checks tables, columns, required cells, types and primary keys.
172
244
  *
173
245
  * @param {Contract} c - The contract.
174
246
  * @param {TablesDoc} doc - The tables.
175
- * @param {(v: string | undefined) => boolean} missing - Missing-value test.
247
+ * @param {Missing} missing - Missing-value test.
176
248
  * @param {Diagnostic[]} out - Receives diagnostics.
177
- * @returns {Map<string, Row[]>} Rows of every declared table that could be read.
249
+ * @returns {{rows: Map<string, Row[]>, badCells: Map<Row, Set<string>>}} Rows of every declared table that could
250
+ * be read, and the cells of each row whose type is wrong (their `match` is not run).
178
251
  */
179
252
  function checkStructure(c, doc, missing, out) {
180
253
  const rows = new Map();
254
+ const badCells = new Map();
181
255
  for (const name of doc.duplicates) {
182
256
  out.push(diag("DUPLICATE_TABLE", `table ${name} appears more than once`, { table: name }, name, "one table"));
183
257
  }
@@ -224,7 +298,6 @@ function checkStructure(c, doc, missing, out) {
224
298
  });
225
299
  const tableRows = rowsOf(doc, t, t.name, missing);
226
300
  const key = keyColumns(t);
227
- const seen = new Map();
228
301
  const seenKeys = new Set();
229
302
  for (const r of tableRows) {
230
303
  const at = (column) => ({ table: t.name, row: r.label, column });
@@ -238,34 +311,7 @@ function checkStructure(c, doc, missing, out) {
238
311
  const typeIssue = typeProblem(v, col);
239
312
  if (typeIssue) {
240
313
  out.push(diag("BAD_TYPE", `'${v}' is not ${typeIssue}`, at(col.name), v, typeIssue));
241
- continue;
242
- }
243
- const items = col.type === "list" ? listItems(v, col.separator) : [v];
244
- for (const item of items) {
245
- if (col.enum && !col.enum.includes(item)) {
246
- out.push(diag("BAD_VALUE", `'${item}' is not allowed`, at(col.name), item, col.enum.join(", ")));
247
- }
248
- if (col.pattern && !new RegExp(`^(?:${col.pattern})$`).test(item)) {
249
- out.push(diag("PATTERN", `'${item}' does not match the pattern`, at(col.name), item, col.pattern));
250
- }
251
- }
252
- if (col.type === "integer" || col.type === "number") {
253
- const n = Fraction.parseDecimal(v);
254
- const min = col.minimum !== undefined ? Fraction.parseDecimal(String(col.minimum)) : null;
255
- const max = col.maximum !== undefined ? Fraction.parseDecimal(String(col.maximum)) : null;
256
- if ((min && n.cmp(min) < 0) || (max && n.cmp(max) > 0)) {
257
- out.push(diag("OUT_OF_RANGE", `${v} is out of range`, at(col.name), v, min && max ? `${col.minimum}..${col.maximum}` : min ? `>= ${col.minimum}` : `<= ${col.maximum}`));
258
- }
259
- }
260
- const length = col.type === "list" ? items.length : [...v].length;
261
- if ((col.min_length !== undefined && length < col.min_length) || (col.max_length !== undefined && length > col.max_length)) {
262
- out.push(diag("BAD_LENGTH", `length ${length} is out of range`, at(col.name), String(length), `${col.min_length ?? 0}..${col.max_length ?? "any"}`));
263
- }
264
- if (col.unique) {
265
- const values = seen.get(col.name) ?? new Set();
266
- if (values.has(v))
267
- out.push(diag("DUPLICATE_KEY", `${col.name} '${v}' is used twice`, at(col.name), v, "a unique value"));
268
- seen.set(col.name, values.add(v));
314
+ badCells.set(r, (badCells.get(r) ?? new Set()).add(col.name));
269
315
  }
270
316
  }
271
317
  if (key.length && key.every(k => header.includes(k) && !missing(r.cells[k]))) {
@@ -278,7 +324,7 @@ function checkStructure(c, doc, missing, out) {
278
324
  }
279
325
  rows.set(t.name, tableRows);
280
326
  }
281
- return rows;
327
+ return { rows, badCells };
282
328
  }
283
329
  /**
284
330
  * Compact text for a table check result.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@turingcode/cli",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "Turing Code toolkit for AI agents: check Markdown/CSV tables against table contracts, e.g. `turingcode table check`.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -23,6 +23,7 @@
23
23
  "access": "public"
24
24
  },
25
25
  "dependencies": {
26
+ "sift": "17.1.4",
26
27
  "yargs": "17.7.3"
27
28
  },
28
29
  "devDependencies": {