fwdloop 0.21.0 → 0.23.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.
Files changed (104) hide show
  1. package/bin/fwdloop +85 -34
  2. package/package.json +4 -3
  3. package/src/ask.js +20 -4
  4. package/src/audit-fold.js +5 -1
  5. package/src/authoring.js +36 -6
  6. package/src/canrun.js +5 -0
  7. package/src/checked.js +32 -4
  8. package/src/cited-record.js +138 -0
  9. package/src/cited-source.js +49 -0
  10. package/src/citedcheck.js +321 -0
  11. package/src/citedwords.js +197 -0
  12. package/src/closers.js +37 -198
  13. package/src/csv.js +69 -12
  14. package/src/ctx-tools.js +2 -14
  15. package/src/declaration.js +143 -5
  16. package/src/diary.js +2 -2
  17. package/src/docx.js +16 -2
  18. package/src/draft-steps.js +1 -1
  19. package/src/drafter.js +322 -33
  20. package/src/flow.js +33 -7
  21. package/src/flowmodel.js +21 -0
  22. package/src/input-facts.js +20 -3
  23. package/src/model-step.js +38 -21
  24. package/src/pageask.js +136 -0
  25. package/src/pagebits.js +107 -0
  26. package/src/pagedropwords.js +171 -0
  27. package/src/pagedry.js +120 -0
  28. package/src/pagefetch.js +164 -0
  29. package/src/pagelook.js +155 -0
  30. package/src/pagemap.js +55 -0
  31. package/src/pageplace.js +103 -0
  32. package/src/pagerules.js +318 -0
  33. package/src/panel/author.js +43 -21
  34. package/src/panel/authorcard.js +20 -3
  35. package/src/panel/authorflows.js +21 -15
  36. package/src/panel/authorstart.js +2 -4
  37. package/src/panel/authortrigger.js +14 -4
  38. package/src/panel/data.js +102 -6
  39. package/src/panel/index.html +321 -12
  40. package/src/panel/result.js +301 -0
  41. package/src/panel/server.js +27 -3
  42. package/src/primitives.js +2 -3
  43. package/src/provider.js +5 -2
  44. package/src/redact.js +17 -0
  45. package/src/runner.js +102 -14
  46. package/src/schedule.js +3 -3
  47. package/src/setup.js +16 -1
  48. package/src/sheet-record.js +57 -0
  49. package/src/sheetblock.js +170 -0
  50. package/src/sheetchecks.js +206 -0
  51. package/src/sheetclaims.js +78 -0
  52. package/src/sheetfind.js +50 -0
  53. package/src/sheetlook.js +157 -0
  54. package/src/sheetoffer.js +125 -0
  55. package/src/sheetrun.js +105 -0
  56. package/src/signed-text.js +11 -1
  57. package/src/thinking.js +1 -1
  58. package/src/try-checks.js +12 -0
  59. package/src/types.js +4 -11
  60. package/types/ask.d.ts +2 -1
  61. package/types/authoring.d.ts +19 -2
  62. package/types/checked.d.ts +19 -3
  63. package/types/cited-record.d.ts +21 -0
  64. package/types/cited-source.d.ts +18 -0
  65. package/types/citedcheck.d.ts +95 -0
  66. package/types/citedwords.d.ts +97 -0
  67. package/types/closers.d.ts +37 -10
  68. package/types/csv.d.ts +25 -4
  69. package/types/ctx-tools.d.ts +0 -1
  70. package/types/declaration.d.ts +20 -1
  71. package/types/docx.d.ts +14 -0
  72. package/types/drafter.d.ts +264 -8
  73. package/types/flow.d.ts +21 -0
  74. package/types/flowmodel.d.ts +15 -0
  75. package/types/input-facts.d.ts +12 -2
  76. package/types/model-step.d.ts +40 -19
  77. package/types/pageask.d.ts +75 -0
  78. package/types/pagebits.d.ts +32 -0
  79. package/types/pagedropwords.d.ts +40 -0
  80. package/types/pagedry.d.ts +38 -0
  81. package/types/pagefetch.d.ts +86 -0
  82. package/types/pagelook.d.ts +75 -0
  83. package/types/pagemap.d.ts +31 -0
  84. package/types/pageplace.d.ts +22 -0
  85. package/types/pagerules.d.ts +86 -0
  86. package/types/panel/authorcard.d.ts +4 -1
  87. package/types/panel/authorflows.d.ts +2 -0
  88. package/types/panel/data.d.ts +26 -0
  89. package/types/panel/result.d.ts +156 -0
  90. package/types/provider.d.ts +3 -1
  91. package/types/redact.d.ts +1 -0
  92. package/types/runner.d.ts +162 -9
  93. package/types/schedule.d.ts +0 -11
  94. package/types/setup.d.ts +13 -0
  95. package/types/sheet-record.d.ts +24 -0
  96. package/types/sheetblock.d.ts +116 -0
  97. package/types/sheetchecks.d.ts +70 -0
  98. package/types/sheetclaims.d.ts +26 -0
  99. package/types/sheetfind.d.ts +46 -0
  100. package/types/sheetlook.d.ts +120 -0
  101. package/types/sheetoffer.d.ts +25 -0
  102. package/types/sheetrun.d.ts +35 -0
  103. package/types/thinking.d.ts +1 -1
  104. package/types/types.d.ts +27 -14
@@ -0,0 +1,206 @@
1
+ // M10b piece 1 (docs/wiki/the-module-ladder.md "M10b scope" item 4 and amendment 1): the signed checks of a sheet live in the job, in the step's close
2
+ // (`close.sheet`). Each entry is a bareguard `cells` / `table` check object, kept as DATA exactly as bareguard defines it (src/primitives/rubric.js
3
+ // `rubricVocabulary`); fwdloop has no check language of its own. Three things live here, each once:
4
+ // - `sheetCheckColumns` every column name a check holds, wherever bareguard puts one (the code proves each is an exact header of the sheet);
5
+ // - `sheetCheckReds` the $0 sign-time test: the checks are built into a bareguard rubric over the drafting copy's table (its `tableSha`), and a
6
+ // refusal comes back as a red naming the job line;
7
+ // - `sheetCheckSentence` the plain words of one check, written from its typed fields, for the plan card and the readout.
8
+ // Throws away: nothing is stored here; the sentence leaves out fields that do not change what the check says (id, claim, range, tolerance, valueKind).
9
+ // Third outcomes, each named, never silently fine: a sheet bareguard cannot read as a table (`tableSha` null: a row with another cell count than the header,
10
+ // a repeated header), a role with no drafting copy, a refusal by `createRubric`.
11
+
12
+ import { createRubric, tableSha } from 'bareguard';
13
+ import { numbersSaid } from './citedwords.js';
14
+ import { wordsSaidOn, lineRules } from './pagebits.js';
15
+
16
+ /** the bareguard rules a sheet check may use (`diff` is out of scope for M10b) */
17
+ export const SHEET_RULES = Object.freeze(['cells', 'table']);
18
+ /** most checks one step may carry */
19
+ export const MAX_SHEET_CHECKS = 20;
20
+
21
+ const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
22
+
23
+ /** the fields of a check that hold a column name as a plain string (the ONE list: {@link sheetCheckColumns} reads it, the drafter's tool schema offers a header enum on each) */
24
+ export const COLUMN_STRING_FIELDS = Object.freeze(['column', 'keyColumn', 'groupColumn', 'result']);
25
+ /** the row-math operands: a column name, or (for `b`) `{const}` */
26
+ export const COLUMN_OPERAND_FIELDS = Object.freeze(['a', 'b']);
27
+ /** the date-cell fields: `{column, row}` */
28
+ export const COLUMN_CELL_FIELDS = Object.freeze(['from', 'to', 'cell']);
29
+ /** the list fields whose entries hold a `column` */
30
+ export const COLUMN_LIST_FIELDS = Object.freeze(['where', 'dateFormats']);
31
+
32
+ /**
33
+ * Every column name one check holds: its own `column`, `keyColumn`, `groupColumn`, `result`, a row-math operand `a` / `b` (a name; `{const}` is no column), the
34
+ * date cells `from` / `to` / `cell`, and the column of each `where` condition and `dateFormats` entry.
35
+ * @param {any} check @returns {string[]}
36
+ */
37
+ export function sheetCheckColumns(check) {
38
+ if (!isRec(check)) return [];
39
+ const out = [];
40
+ for (const k of [...COLUMN_STRING_FIELDS, ...COLUMN_OPERAND_FIELDS]) if (typeof check[k] === 'string') out.push(check[k]);
41
+ for (const k of COLUMN_CELL_FIELDS) if (isRec(check[k]) && typeof check[k].column === 'string') out.push(check[k].column);
42
+ for (const k of COLUMN_LIST_FIELDS) if (Array.isArray(check[k])) for (const e of check[k]) if (isRec(e) && typeof e.column === 'string') out.push(e.column);
43
+ return out;
44
+ }
45
+
46
+ const CMP_WORDS = Object.freeze({
47
+ gt: '>', gte: '>=', lt: '<', lte: '<=', eq: '=', before: 'before', after: 'after', dateOn: 'on', equals: 'is',
48
+ });
49
+
50
+ /** @param {any} w one `where` condition @returns {string} */
51
+ function conditionWords(w) {
52
+ if (!isRec(w)) return '?';
53
+ const col = String(w.column);
54
+ const v = (/** @type {unknown} */ x) => (typeof x === 'string' ? `"${x}"` : String(x));
55
+ if (w.cmp === 'between' || w.cmp === 'dateBetween') return `${col} between ${v(w.lo)} and ${v(w.hi)}`;
56
+ if (w.cmp === 'empty') return `${col} is empty`;
57
+ if (w.cmp === 'notEmpty') return `${col} is not empty`;
58
+ const sym = /** @type {Record<string, string>} */ (CMP_WORDS)[w.cmp];
59
+ return `${col} ${sym ?? String(w.cmp)} ${v(w.value)}`;
60
+ }
61
+
62
+ /** @param {any} check @returns {string} " where A > 1 and B is empty", or "" */
63
+ const whereWords = (check) => (Array.isArray(check.where) && check.where.length > 0 ? ` where ${check.where.map(conditionWords).join(' and ')}` : '');
64
+
65
+ /** @param {any} b one band @returns {string} */
66
+ const bandName = (b) => (isRec(b) ? String(b.name) : '?');
67
+
68
+ /**
69
+ * The plain words of ONE sheet check, written from its typed fields (never from model text). The ONE function; the plan card, the readout and the Checked
70
+ * list all call it. An op with no sentence of its own reads `<rule> <op> on <column>` plus its conditions, so a check can never be shown as nothing.
71
+ * @param {any} check a bareguard cells / table check object @returns {string}
72
+ */
73
+ export function sheetCheckSentence(check) {
74
+ if (!isRec(check)) return 'a check that is not readable';
75
+ const col = typeof check.column === 'string' ? check.column : '';
76
+ const asOf = typeof check.asOf === 'string' ? ` as of ${check.asOf}` : '';
77
+ switch (check.op) {
78
+ case 'rows': return `rows${whereWords(check)}`;
79
+ case 'countIf': return `count of rows${whereWords(check)}`;
80
+ case 'count': return `count of ${col}`;
81
+ case 'sumIf': return `sum of ${col}${whereWords(check)}`;
82
+ case 'sum': return `sum of ${col}`;
83
+ case 'averageIf': return `average of ${col}${whereWords(check)}`;
84
+ case 'average': return `average of ${col}`;
85
+ case 'band': return `band on ${col}${asOf}: ${(Array.isArray(check.bands) ? check.bands : []).map(bandName).join(', ')}${whereWords(check)}`;
86
+ case 'daysSince': return `days since ${col || 'a date cell'}${asOf}${whereWords(check)}`;
87
+ case 'noDuplicates': return `no duplicate ${col}`;
88
+ case 'noEmpty': return `no empty ${col}`;
89
+ case 'allNumbers': return `every ${col} is a number`;
90
+ case 'allDates': return `every ${col} is a date`;
91
+ case 'rowCount': return `the sheet has ${check.n} rows`;
92
+ default: return `${check.rule} ${check.op}${col ? ` on ${col}` : ''}${whereWords(check)}`;
93
+ }
94
+ }
95
+
96
+ /**
97
+ * M10b piece 4: a signed check may carry fwdloop's own `covers` (the numbers of the job line's `~` rules the drafter tagged it to; signed, so the person sees it).
98
+ * bareguard does not know it, so the checks are cleaned HERE, the ONE place, on the way into bareguard (`createRubric` at sign time and at run time).
99
+ * @param {any[]} checks @returns {any[]} a copy without `covers`
100
+ */
101
+ export function bareguardChecks(checks) {
102
+ return checks.map((c) => { if (!isRec(c) || !('covers' in c)) return c; const { covers: _kept, ...rest } = c; return rest; });
103
+ }
104
+
105
+ /**
106
+ * M10b piece 4: `covers`, when a check has it, is a list of rule numbers of its job line (counted from 1 over the line's `~` rules). A check without it is fine (an old draft).
107
+ * @param {any[]} checks @param {{n: number, rule?: string, rules?: string[]}} jobLine @returns {string[]} reds, each naming the line and the check
108
+ */
109
+ export function sheetCoversReds(checks, jobLine) {
110
+ const reds = [];
111
+ const nRules = lineRules(jobLine).length;
112
+ for (const c of checks) {
113
+ if (!isRec(c) || c.covers === undefined) continue;
114
+ if (!Array.isArray(c.covers) || c.covers.some((x) => !Number.isInteger(x) || x < 1 || x > nRules)) {
115
+ reds.push(`declaration: line ${jobLine.n}: the sheet check${typeof c.id === 'string' ? ` '${c.id}'` : ''} "covers" must list rule numbers of line ${jobLine.n}'s guardrail (it has ${nRules} rule${nRules === 1 ? '' : 's'}, counted from 1)`);
116
+ }
117
+ }
118
+ return reds;
119
+ }
120
+
121
+ /** The rows for a step's `close.sheet`, one per check, in order. @param {unknown} sheet @returns {string[]} */
122
+ export function sheetCheckRows(sheet) {
123
+ return Array.isArray(sheet) ? sheet.map(sheetCheckSentence) : [];
124
+ }
125
+
126
+ /**
127
+ * The $0 sign-time test of one step's sheet checks (M10b item 4): bareguard's `createRubric` is given the checks and the signed fingerprint of each sheet
128
+ * they read (`tableSha` of the drafting copy's table). A refusal is a red that names the job line (and the check). A column that is no header of its sheet is
129
+ * a red naming the line and the column. Never throws.
130
+ * @param {any[]} checks the step's `close.sheet` (already known to be a list of objects) @param {number} line the job line the step comes from
131
+ * @param {Record<string, {header: string[], rows: any[]}>} tables the drafting copy's table of each sheet role @returns {string[]} reds, each naming the line
132
+ */
133
+ export function sheetCheckReds(checks, line, tables) {
134
+ const reds = [];
135
+ const at = `declaration: line ${line}:`;
136
+ /** @type {Map<string, string|null>} */
137
+ const shas = new Map();
138
+ for (const c of checks) {
139
+ if (!isRec(c) || typeof c.table !== 'string' || shas.has(c.table)) continue;
140
+ const t = tables[c.table];
141
+ if (!t) { shas.set(c.table, null); reds.push(`${at} the sheet check reads "${c.table}", which has no saved copy to test against`); continue; }
142
+ shas.set(c.table, tableSha(t));
143
+ if (shas.get(c.table) === null) reds.push(`${at} bareguard cannot read "${c.table}" as a table (a row with more or fewer cells than the header, or a repeated column name); fix the sheet`);
144
+ }
145
+ for (const c of checks) {
146
+ const t = isRec(c) && typeof c.table === 'string' ? tables[c.table] : undefined;
147
+ if (!t) continue;
148
+ for (const name of sheetCheckColumns(c)) {
149
+ if (!t.header.includes(name)) reds.push(`${at} '${name}' is not a real column of "${c.table}" (its columns: ${t.header.map((h) => `'${h}'`).join(', ')}). Copy a column name exactly.`);
150
+ }
151
+ }
152
+ if (reds.length > 0) return reds;
153
+ const inputs = [...shas].map(([name, sha256]) => ({ name, sha256 }));
154
+ try {
155
+ createRubric({ schema: 1, goal: `line ${line}`, inputs, checkpoints: { sheet: { gating: true, checks: bareguardChecks(checks) } }, maxReds: 3 });
156
+ } catch (err) {
157
+ const msg = String(/** @type {any} */ (err).message).replace(/^invalid rubric: /, '');
158
+ const idx = /checks\[(\d+)\]/.exec(String(/** @type {any} */ (err).path ?? msg));
159
+ const who = idx && isRec(checks[Number(idx[1])]) && typeof checks[Number(idx[1])].id === 'string' ? ` '${checks[Number(idx[1])].id}'` : '';
160
+ reds.push(`${at} bareguard refuses the sheet check${who}: ${msg}`);
161
+ }
162
+ return reds;
163
+ }
164
+
165
+ const NUMBER_CMPS = Object.freeze(['gt', 'gte', 'lt', 'lte', 'eq', 'between']);
166
+ const DATE_CMPS = Object.freeze(['before', 'after', 'dateOn', 'dateBetween']);
167
+
168
+ /**
169
+ * M10b piece 3: a number or a date in a check comes from the job, never from the model. Every number in a `where` condition (gt gte lt lte eq between) must be a
170
+ * number the person said on the job line or its `~` rules (the SAME reader as the page number rules, src/citedwords.js `numbersSaid`: a bare number or an amount,
171
+ * not a piece of a time, a date or another amount), and every date (`asOf`, and the values of before / after / dateOn / dateBetween) must be a date they wrote
172
+ * exactly. Throws away: a text value (`equals`, `needle`), band bounds, `n`, `tolerance`, `range` are not read here (the job's words do not have to carry them).
173
+ * @param {any[]} checks the step's `close.sheet` @param {{n: number, text?: string, rule?: string, rules?: string[]}} jobLine @returns {string[]} reds, each naming the line
174
+ */
175
+ export function sheetCheckWordReds(checks, jobLine) {
176
+ const said = numbersSaid(wordsSaidOn(jobLine));
177
+ const reds = [];
178
+ const n = jobLine.n;
179
+ const who = (/** @type {any} */ c) => (isRec(c) && typeof c.id === 'string' ? ` '${c.id}'` : '');
180
+ const num = (/** @type {any} */ c, /** @type {unknown} */ v, /** @type {string} */ where) => {
181
+ if (typeof v === 'number' && !said.bare.has(v) && !said.amount.has(v)) reds.push(`declaration: line ${n}: the sheet check${who(c)} has the number ${v} (${where}), but ${v} is not in your words on line ${n}. A number in a check must come from the job line or a ~ rule you wrote. Say it there, or leave the condition out.`);
182
+ };
183
+ const date = (/** @type {any} */ c, /** @type {unknown} */ v, /** @type {string} */ where) => {
184
+ if (typeof v === 'string' && !said.date.has(v)) reds.push(`declaration: line ${n}: the sheet check${who(c)} has the date ${v} (${where}), but ${v} is not a date in your words on line ${n}. A date in a check must be written on the job line or a ~ rule, as YYYY-MM-DD. Say it there, or leave it out.`);
185
+ };
186
+ for (const c of checks) {
187
+ if (!isRec(c)) continue;
188
+ if (c.asOf !== undefined) date(c, c.asOf, 'as of');
189
+ for (const w of Array.isArray(c.where) ? c.where : []) {
190
+ if (!isRec(w)) continue;
191
+ const at = `where ${String(w.column)}`;
192
+ if (NUMBER_CMPS.includes(w.cmp)) for (const k of w.cmp === 'between' ? ['lo', 'hi'] : ['value']) num(c, w[k], at);
193
+ else if (DATE_CMPS.includes(w.cmp)) for (const k of w.cmp === 'dateBetween' ? ['lo', 'hi'] : ['value']) date(c, w[k], at);
194
+ }
195
+ }
196
+ return reds;
197
+ }
198
+
199
+ /**
200
+ * M10b piece 3: a step whose sheet checks are ALL `table` checks has nothing to answer (a table check judges the sheet itself and carries no claim), so the
201
+ * step would be asked for nothing. Refused at $0, naming the line. @param {any[]} checks @param {number} line @returns {string[]}
202
+ */
203
+ export function sheetNoClaimReds(checks, line) {
204
+ if (checks.length === 0 || !checks.every((c) => isRec(c) && c.rule === 'table')) return [];
205
+ return [`declaration: line ${line}: every sheet check on this step is a table check, which judges the sheet itself and leaves the step nothing to answer. Pair it with at least one cells check that has a claim (for example rows, countIf, sumIf or band).`];
206
+ }
@@ -0,0 +1,78 @@
1
+ // M10b piece 2 (docs/wiki/the-module-ladder.md "M10b scope" item 5): what a step that reads a sheet is told and what box it answers in.
2
+ // A step answers each `cells` check's CLAIM in bareguard's typed box ({value}, {rows}, {days}, {bands}, ...), never a cite or a formula. The shape of every box is
3
+ // generated from bareguard's own worked example for the op (`rubricVocabulary.rules.cells.ops.<op>.example`), never hand-copied here. The step is told the box, not the
4
+ // check: no op, no condition, no bound, no column ever reaches it (the construction test in test/m10b-sheet-run.test.js proves the request carries none).
5
+ // Throws away: a check with no claim (a `table` check judges the sheet itself) adds no box; two checks with the same claim name share one box.
6
+ import { rubricVocabulary } from 'bareguard';
7
+
8
+ const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
9
+
10
+ /** whole-number boxes: a row number list, and a days map (bareguard compares these as integers) */
11
+ const INTEGER_KEYS = Object.freeze(['rows', 'days']);
12
+
13
+ /**
14
+ * The JSON schema of one value in a worked example. Typed from the example's own value; `intKey` = the box key it sits under.
15
+ * @param {any} v @param {string} [intKey] @returns {Record<string, any>}
16
+ */
17
+ function schemaOf(v, intKey = '') {
18
+ if (typeof v === 'boolean') return { type: 'boolean' };
19
+ if (typeof v === 'number') return { type: INTEGER_KEYS.includes(intKey) ? 'integer' : 'number' };
20
+ if (typeof v === 'string') return { type: 'string' };
21
+ if (Array.isArray(v)) return v.length > 0 ? { type: 'array', items: schemaOf(v[0], intKey) } : { type: 'array' };
22
+ if (isRec(v)) {
23
+ const keys = Object.keys(v);
24
+ // a map keyed by row number (days, bands): every value has the first one's type
25
+ if (keys.length > 0 && keys.every((k) => /^\d+$/.test(k))) return { type: 'object', additionalProperties: schemaOf(v[keys[0]], intKey) };
26
+ return { type: 'object', properties: Object.fromEntries(keys.map((k) => [k, schemaOf(v[k], k)])), required: keys };
27
+ }
28
+ return {};
29
+ }
30
+
31
+ /**
32
+ * The claim box of every `cells` check in the list: `[{claim, example}]`, one per claim name, in order. `example` is the op's worked-example answer (the box's shape
33
+ * with example values). A check bareguard has no example for, and a `table` check, add nothing.
34
+ * @param {any[]} checks a step's `close.sheet` @returns {Array<{claim: string, example: Record<string, any>, ops: string[]}>}
35
+ */
36
+ export function sheetClaims(checks) {
37
+ /** @type {Map<string, {claim: string, example: Record<string, any>, ops: string[]}>} */
38
+ const out = new Map();
39
+ const ops = /** @type {any} */ (rubricVocabulary).rules?.cells?.ops ?? {};
40
+ for (const c of Array.isArray(checks) ? checks : []) {
41
+ if (!isRec(c) || c.rule !== 'cells' || typeof c.claim !== 'string' || typeof c.op !== 'string') continue;
42
+ const ex = ops[c.op]?.example;
43
+ const shape = isRec(ex) && isRec(ex.output) && isRec(ex.check) ? ex.output[ex.check.claim] : undefined;
44
+ if (!isRec(shape)) continue;
45
+ const have = out.get(c.claim);
46
+ if (have) { Object.assign(have.example, shape); have.ops.push(c.op); } else out.set(c.claim, { claim: c.claim, example: { ...shape }, ops: [c.op] });
47
+ }
48
+ return [...out.values()];
49
+ }
50
+
51
+ /**
52
+ * The `emit_artifact` tool's properties for a step that reads a sheet: one typed box per claim, each required. (`done` is added by the caller, as for every step.)
53
+ * @param {any[]} checks @returns {{properties: Record<string, any>, required: string[]}}
54
+ */
55
+ export function sheetAnswerProps(checks) {
56
+ /** @type {Record<string, any>} */
57
+ const properties = {};
58
+ for (const { claim, example, ops } of sheetClaims(checks)) {
59
+ const keys = Object.keys(example);
60
+ properties[claim] = {
61
+ type: 'object',
62
+ properties: Object.fromEntries(keys.map((k) => [k, ops.includes('lookup') && k === 'value' ? { type: ['string', 'number'] } : schemaOf(example[k], k)])),
63
+ required: keys,
64
+ };
65
+ }
66
+ return { properties, required: Object.keys(properties) };
67
+ }
68
+
69
+ /**
70
+ * What the step is told about its answer (one key of its request): the name and the shape of each box, with the worked example's values. Never the check.
71
+ * @param {any[]} checks @returns {{answer: string, fields: Record<string, Record<string, any>>}}
72
+ */
73
+ export function sheetBrief(checks) {
74
+ return {
75
+ answer: 'Answer with one field for each name in "fields", in the shape shown for it. Give the values themselves, worked out from the input - never a cell reference and never a formula. The values shown only illustrate the shape; use the real ones from the input and the job line.',
76
+ fields: Object.fromEntries(sheetClaims(checks).map(({ claim, example }) => [claim, example])),
77
+ };
78
+ }
@@ -0,0 +1,50 @@
1
+ // M10 piece 5 (docs/wiki/the-module-ladder.md "M10", item 7): when a job's word is not a column of the sheet, CODE finds the column that passes the same test
2
+ // the page words pass - a value of the right kind in the rows - and builds the ask. The model names a word and nothing else; it never names a column to offer and
3
+ // never decides an ask (test/m10-sheetfind.test.js, test/m10-sheetask.test.js).
4
+ // The finder is fwdloop's own (F71 Test 3, C1-C4, $0): bareloop reads "label then value on the same line", and a header sits on line 1, so the discipline
5
+ // transfers, not the code (docs/product/fwd-borrow-from-bareloop-rubric-2026-10-18.md section 3).
6
+ // A column FITS when a plain number fills at least FIT_RATIO of the rows (F71 (b)). A plain number is the whole cell: optional sign, digits, thousands commas,
7
+ // optional decimals. One fitting column with the most rows is the one ask. Two or more fitting columns with equal rows offer nothing (F71 C2, hamr 2026-10-19).
8
+ // Throws away: every column but the winner, the cells' values, and everything but the header and the count of number cells.
9
+ import { parseCsv } from './csv.js';
10
+ import { wordForms } from './pagebits.js';
11
+
12
+ /** a column fits when a plain number fills at least this share of the rows (F71 (b)) */
13
+ export const FIT_RATIO = 0.9;
14
+ const PLAIN_NUMBER = /^[-+]?\d[\d,]*(\.\d+)?$/;
15
+
16
+ /** @param {string} h @returns {string} a header as it is compared: trimmed, white space made one space, lower case */
17
+ const norm = (h) => String(h ?? '').trim().replace(/\s+/g, ' ').toLowerCase();
18
+
19
+ /**
20
+ * @typedef {{kind: 'header', column: string}} FoundHeader the word IS a column (nothing to ask)
21
+ * @typedef {{kind: 'ask', column: string, numbers: number, rows: number}} FoundAsk exactly one column fits: the one ask
22
+ * @typedef {{kind: 'tie', columns: string[], rows: number}} FoundTie two or more columns fit equally: no ask
23
+ * @typedef {{kind: 'none', rows: number}} FoundNone no column fits: no ask
24
+ */
25
+
26
+ /**
27
+ * Where a job word lands in a sheet's columns.
28
+ * @param {string} csvText the sheet's text @param {string} word the job's word
29
+ * @returns {FoundHeader|FoundAsk|FoundTie|FoundNone}
30
+ */
31
+ export function findColumn(csvText, word) {
32
+ const { header, rows } = parseCsv(csvText);
33
+ const hit = header.find((h) => norm(h) === norm(word) && norm(h) !== '') ?? header.find((h) => norm(h) !== '' && wordForms(word).includes(norm(h)));
34
+ if (hit !== undefined) return { kind: 'header', column: hit };
35
+ const n = rows.length;
36
+ const cols = header.map((h) => ({ h, n: rows.filter((r) => PLAIN_NUMBER.test(String(r.byName[h] ?? '').trim())).length }));
37
+ const fit = cols.filter((c) => n > 0 && c.n / n >= FIT_RATIO);
38
+ if (fit.length === 0) return { kind: 'none', rows: n };
39
+ const best = Math.max(...fit.map((c) => c.n));
40
+ const top = fit.filter((c) => c.n === best);
41
+ if (top.length > 1) return { kind: 'tie', columns: top.map((c) => c.h), rows: n };
42
+ return { kind: 'ask', column: top[0].h, numbers: top[0].n, rows: n };
43
+ }
44
+
45
+ /**
46
+ * The question, as signed (item 7's example, then am8 item 1's answer words):
47
+ * `no column 'Price'; 'Amount' has numbers in 40 of 40 rows. Use it? Answer "agree", or type your own words (your answer is added as a new ~ rule on line N).`
48
+ * @param {string} word @param {FoundAsk} found @param {number} line @returns {string}
49
+ */
50
+ export const columnQuestion = (word, found, line) => `no column '${word}'; '${found.column}' has numbers in ${found.numbers} of ${found.rows} rows. Use it? Answer "agree", or type your own words (your answer is added as a new ~ rule on line ${line}).`;
@@ -0,0 +1,157 @@
1
+ // M10 piece 5 (item 3 + item 7, for a sheet): the sheet-word look for ONE CSV input. One AI call names the job's own word for each rule (the column it means);
2
+ // CODE keeps a word only when it is a real column of the sheet, and when it is not, finds the column to offer (src/sheetfind.js) and builds the ask. The model
3
+ // names a word and a kind and nothing else: it never names a column to offer, never decides an ask, and never writes a question (the words are code's).
4
+ // The page look's call shape is reused (src/pagelook.js `lookAtPage`): the same system words, one retry on an unreadable answer, the same stop words.
5
+ //
6
+ // Throws away: nothing silently. A word that is no column and gets no offer comes back in `dropped` with its reason code (src/pagedropwords.js, the one table)
7
+ // and as a Not-checked line. Third outcomes: an unreadable answer twice (stop), a cut-off answer (unreadable), a failed call (stop, its reason).
8
+ // A rule the model gave no word for is left alone: a cells guardrail is checked by the cells close as it always was (this look adds checks, it removes none).
9
+ import { parseCsv } from './csv.js';
10
+ import { MAP_UNREADABLE } from './pagemap.js';
11
+ import { tieOf } from './pagerules.js';
12
+ import { lineRules, countPhrase, wordsSaidOn, wordForms } from './pagebits.js';
13
+ import { findColumn, columnQuestion } from './sheetfind.js';
14
+
15
+ /** how many data rows the prompt shows (the header is always shown): enough to see what a column holds, never the whole sheet */
16
+ export const SHEET_PROMPT_ROWS = 5;
17
+ /** the line every sheet prompt carries, so a test provider can tell a sheet call from a page call (the system words are the same) */
18
+ export const SHEET_MARK = 'THE SHEET OR DOCUMENT:';
19
+
20
+ /**
21
+ * The `~` rule an `agree` writes (signed, am8 item 1); a person's own words replace it.
22
+ * @param {string} word @param {string} column @returns {string}
23
+ */
24
+ export const columnRuleWords = (word, column) => `use the column '${column}' for '${word}'`;
25
+
26
+ /**
27
+ * What the AI is told for ONE sheet: the job, and the sheet's header and first rows. It names the job's word for each rule; it does not pick a column to offer.
28
+ * With `headings` (a .docx input, am8 item 3) the document's headings stand where a sheet's columns do and no data rows are shown.
29
+ * @param {{jobLines: {n: number, text: string, rule?: string, rules?: string[]}[], label: string, text: string, headings?: string[]}} o @returns {string}
30
+ */
31
+ export function sheetPrompt({ jobLines, label, text, headings }) {
32
+ const job = jobLines.map((l) => `LINE ${l.n}: ${l.text}${lineRules(l).map((r, i) => `\n~ rule ${i + 1}: ${r}`).join('')}`).join('\n');
33
+ if (headings !== undefined) {
34
+ return `THE JOB (each ~ rule applies to the line above it):\n${job}\n\n`
35
+ + `${SHEET_MARK} the input "${label}" is a document. Its headings:\n${headings.map((h) => `- ${h}`).join('\n') || '(none)'}\n\n`
36
+ + 'For each job line and each ~ rule that is about a part of the document, give the JOB\'S OWN WORD for the heading it means. If the document has a heading for it, copy that heading exactly. '
37
+ + 'If it has none, give the word the job uses. Say "other" for the kind. Leave out a rule that is not about a heading.\n\n'
38
+ + 'Return ONLY a JSON object, no prose, no code fence:\n'
39
+ + '{"facts":[{"from":"<line N | line N rule M>","word":"<the heading, or the job\'s own word>","kind":"other"}]}';
40
+ }
41
+ const { header, rows } = parseCsv(text);
42
+ const shown = rows.slice(0, SHEET_PROMPT_ROWS).map((r) => header.map((h) => r.byName[h] ?? '').join(' | '));
43
+ return `THE JOB (each ~ rule applies to the line above it):\n${job}\n\n`
44
+ + `${SHEET_MARK} the input "${label}" is a spreadsheet. Its columns, then its first rows:\n${header.join(' | ')}\n${shown.join('\n')}\n\n`
45
+ + 'For each job line and each ~ rule that is about a value in the sheet, give the JOB\'S OWN WORD for the column it means, exactly as the job writes it. '
46
+ + 'Never replace the job\'s word with a column name from the sheet, even when the sheet has a column that seems to mean the same: code matches the word to the sheet. Say whether the word means a column of numbers ("number") or anything else ("other"). Leave out a rule that is not about a column.\n\n'
47
+ + 'Return ONLY a JSON object, no prose, no code fence:\n'
48
+ + '{"facts":[{"from":"<line N | line N rule M>","word":"<the column name, or the job\'s own word>","kind":"number|other"}]}';
49
+ }
50
+
51
+ /**
52
+ * Read the AI's answer: ONE JSON object of the answer form, nothing else. No repair: text that is not JSON, or a fact without a `from`, a `word` or a kind of
53
+ * "number" / "other", is a malformed answer.
54
+ * @param {unknown} text @returns {{ok: true, words: {from: string, word: string, kind: 'number'|'other'}[]}|{ok: false}}
55
+ */
56
+ export function parseSheetAnswer(text) {
57
+ /** @type {any} */
58
+ let m;
59
+ try { m = JSON.parse(String(text ?? '').trim()); } catch { return { ok: false }; }
60
+ if (m === null || typeof m !== 'object' || Array.isArray(m) || !Array.isArray(m.facts)) return { ok: false };
61
+ /** @type {{from: string, word: string, kind: 'number'|'other'}[]} */
62
+ const words = [];
63
+ for (const f of m.facts) {
64
+ if (f === null || typeof f !== 'object' || Array.isArray(f)) return { ok: false };
65
+ if (typeof f.from !== 'string' || typeof f.word !== 'string' || f.word.trim() === '' || f.word.length > 100) return { ok: false };
66
+ if (f.kind !== 'number' && f.kind !== 'other') return { ok: false };
67
+ words.push({ from: f.from, word: f.word.trim(), kind: f.kind });
68
+ }
69
+ return { ok: true, words };
70
+ }
71
+
72
+ /**
73
+ * Keep the words that are real columns; for the rest, find the column to offer (or say why none is). Decided by code from the word, the rule and the sheet.
74
+ * @param {string} text the sheet's text @param {{from: string, word: string, kind: 'number'|'other'}[]} words
75
+ * @param {{n: number, text?: string, rule?: string, rules?: string[]}[]} jobLines @param {string} label the input's role
76
+ * @returns {{facts: {line: number, forRule?: number, name: string, shape: 'column', column: string, words: string[], source: string}[], asks: {line: number, rule: number|null, source: 'look', ask: 'reading', ruleText: string, question: string, reading: string, word: string, column: string}[], dropped: import('./pagerules.js').Dropped[]}}
77
+ */
78
+ export function applySheetWords(text, words, jobLines, label) {
79
+ /** @type {any[]} */
80
+ const facts = [];
81
+ /** @type {any[]} */
82
+ const asks = [];
83
+ /** @type {import('./pagerules.js').Dropped[]} */
84
+ const dropped = [];
85
+ const seen = new Set();
86
+ for (const w of words) {
87
+ const at = tieOf(w.from, jobLines);
88
+ const key = `${at.line}\u0000${at.rule ?? ''}\u0000${w.word.toLowerCase()}`;
89
+ if (seen.has(key)) continue;
90
+ seen.add(key);
91
+ const jl = jobLines.find((l) => l.n === at.line);
92
+ const rules = lineRules(jl);
93
+ const ruleText = at.rule === undefined ? String(jl?.text ?? '') : rules[at.rule - 1];
94
+ const fact = (/** @type {string} */ column) => ({ line: at.line, ...(at.rule === undefined ? {} : { forRule: at.rule }), name: column, shape: /** @type {const} */ ('column'), column, words: [column], source: label });
95
+ const rec = { line: at.line, ...(at.rule === undefined ? {} : { rule: at.rule }), fact: w.word, source: label };
96
+ const found = findColumn(text, w.word);
97
+ if (found.kind === 'header') {
98
+ // a real header is kept only when the word is the PERSON'S: in the line or its ~ rules. A header the model picked in the person's place is not a check the person
99
+ // asked for (live walk 2026-10-21: "Price over 500" kept as "Amount", nothing asked)
100
+ if (jl === undefined || !wordForms(w.word).some((f) => countPhrase(wordsSaidOn(jl), f) > 0)) dropped.push({ ...rec, reason: 'word-not-yours' });
101
+ else facts.push(fact(found.column));
102
+ continue;
103
+ }
104
+ if (w.kind !== 'number') { dropped.push({ ...rec, reason: 'no-column' }); continue; }
105
+ if (found.kind === 'tie') { dropped.push({ ...rec, reason: 'column-tie', other: found.columns.map((c) => `"${c}"`).join(', ') }); continue; }
106
+ if (found.kind === 'none') { dropped.push({ ...rec, reason: 'no-fit', other: String(found.rows) }); continue; }
107
+ // the person already named this column in ANOTHER rule of the line (an answer they gave, or their own words): the word is that column, asked no more
108
+ if (rules.some((r, i) => i + 1 !== at.rule && countPhrase(r, found.column) > 0)) { facts.push(fact(found.column)); continue; }
109
+ asks.push({
110
+ line: at.line, rule: at.rule ?? null, source: 'look', ask: 'reading', ruleText, question: columnQuestion(w.word, found, at.line), reading: columnRuleWords(w.word, found.column), word: w.word, column: found.column,
111
+ });
112
+ }
113
+ return { facts, asks, dropped };
114
+ }
115
+
116
+ /**
117
+ * am8 item 3: a .docx's words. A job word that is a heading is kept (the next steps' quotes are still checked word for word on the run's own copy); one that is not is
118
+ * Not checked with its reason, and NOTHING is asked. Same shape as {@link applySheetWords}, with no asks.
119
+ * @param {string[]} headings @param {{from: string, word: string, kind: 'number'|'other'}[]} words
120
+ * @param {{n: number, text?: string, rule?: string, rules?: string[]}[]} jobLines @param {string} label
121
+ * @returns {ReturnType<typeof applySheetWords>}
122
+ */
123
+ export function applyDocWords(headings, words, jobLines, label) {
124
+ const facts = /** @type {any[]} */ ([]);
125
+ const dropped = /** @type {import('./pagerules.js').Dropped[]} */ ([]);
126
+ const seen = new Set();
127
+ const norm = (/** @type {string} */ h) => h.trim().replace(/\s+/g, ' ').toLowerCase();
128
+ for (const w of words) {
129
+ const at = tieOf(w.from, jobLines);
130
+ const key = `${at.line}\u0000${at.rule ?? ''}\u0000${w.word.toLowerCase()}`;
131
+ if (seen.has(key)) continue;
132
+ seen.add(key);
133
+ const hit = headings.find((h) => norm(h) === norm(w.word)) ?? headings.find((h) => wordForms(w.word).includes(norm(h)));
134
+ if (hit !== undefined) facts.push({ line: at.line, ...(at.rule === undefined ? {} : { forRule: at.rule }), name: hit, shape: 'heading', column: hit, words: [hit], source: label });
135
+ else dropped.push(/** @type {any} */ ({ line: at.line, ...(at.rule === undefined ? {} : { rule: at.rule }), fact: w.word, source: label, reason: 'no-heading' }));
136
+ }
137
+ return { facts, asks: [], dropped };
138
+ }
139
+
140
+ /**
141
+ * Look at ONE sheet input: the call (once; once more if the answer is unreadable), then the rules.
142
+ * `callModel(content, attempt)` makes and meters ONE model round and returns `{text}`, `{text, cutOff: true}` or `{error}` (the same seam as `lookAtPage`).
143
+ * @param {{label: string, text: string, jobLines: {n: number, text: string, rule?: string, rules?: string[]}[], callModel: (content: string, attempt: number) => Promise<{text?: string, cutOff?: boolean, error?: string}>, headings?: string[]}} o
144
+ * @returns {Promise<({ok: true, attempts: number} & ReturnType<typeof applySheetWords>)|{ok: false, reason: string, attempts: number}>}
145
+ */
146
+ export async function lookAtSheet({ label, text, jobLines, callModel, headings }) {
147
+ const content = sheetPrompt({ jobLines, label, text, headings });
148
+ let attempts = 0;
149
+ for (;;) {
150
+ attempts += 1;
151
+ const r = await callModel(content, attempts);
152
+ if (r.error !== undefined) return { ok: false, reason: `the call about the sheet failed: ${r.error}`, attempts };
153
+ const parsed = r.cutOff === true ? { ok: false } : parseSheetAnswer(r.text);
154
+ if (parsed.ok) return { ok: true, attempts, ...(headings === undefined ? applySheetWords(text, /** @type {any} */ (parsed).words, jobLines, label) : applyDocWords(headings, /** @type {any} */ (parsed).words, jobLines, label)) };
155
+ if (attempts >= 2) return { ok: false, reason: MAP_UNREADABLE.replace('about the page', 'about the sheet'), attempts };
156
+ }
157
+ }
@@ -0,0 +1,125 @@
1
+ // M10b piece 3 (docs/wiki/the-module-ladder.md "M10b scope" item 4): what the drafter is OFFERED for a sheet. Things, each once:
2
+ // - `sheetChecksProp` the tool schema of `close.sheet`, GENERATED from bareguard's `rubricVocabulary` (fields, ops, date formats), never hand-copied. Every field that
3
+ // names a column is a JSON-schema `enum` of the sheet's exact header strings, so the model can only pick one (code still re-checks, piece 1);
4
+ // - `sheetOpsBrief` the plain list of every op with its summary, what it requires and allows, and bareguard's worked example check, generated the same way;
5
+ // - `isColumnChoiceRule` the agreed-column rule, covered by the column lock.
6
+ // `covers` (which `~` rules of a job line a check verifies, the drafter's typed field) is KEPT on the check and signed (M10b am2: you see it before you sign); it is
7
+ // stripped only on the way into bareguard (src/sheetchecks.js `bareguardChecks`) and read by src/sheetblock.js. A field type the vocabulary gains that this file does not know
8
+ // THROWS at build time (a bareguard upgrade fails loud, it never silently drops a field).
9
+ // Third outcomes, named: a sheet with no header (no enum can be built: no sheet schema is offered).
10
+ import { rubricVocabulary } from 'bareguard';
11
+ import {
12
+ SHEET_RULES, MAX_SHEET_CHECKS, COLUMN_STRING_FIELDS, COLUMN_OPERAND_FIELDS, COLUMN_CELL_FIELDS, COLUMN_LIST_FIELDS,
13
+ } from './sheetchecks.js';
14
+ import { columnRuleWords } from './sheetlook.js';
15
+
16
+ const V = /** @type {any} */ (rubricVocabulary);
17
+ const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
18
+
19
+ /** The comparisons of a `where` condition. bareguard publishes them only inside the `where` description (no list), so this is the one copy; a test proves each is named there. */
20
+ export const WHERE_CMPS = Object.freeze(['gt', 'gte', 'lt', 'lte', 'eq', 'between', 'before', 'after', 'dateBetween', 'dateOn', 'equals', 'empty', 'notEmpty']);
21
+
22
+ /** @param {Record<string, {header: string[]}>} tables @returns {string[]} the exact header strings of every sheet, once each, in order */
23
+ const headerUnion = (tables) => [...new Set(Object.values(tables).flatMap((t) => t.header))];
24
+
25
+ /**
26
+ * The JSON schema of one vocabulary field. `col` = the schema every column name uses (an enum of the header).
27
+ * @param {string} key @param {any} f @param {Record<string, any>} col @param {string[]} roles @returns {Record<string, any>|null} null = not offered
28
+ */
29
+ function fieldSchema(key, f, col, roles) {
30
+ const d = f.description ? { description: f.description } : {};
31
+ if (key === 'table') return { type: 'string', enum: roles, description: 'the role of the CSV input this check reads (also in the step\'s reads)' };
32
+ if (key === 'claim') return { type: 'string', minLength: 1, maxLength: 128, description: 'a cells check only: a short name for the field that holds the step\'s answer to this check; the step is told the shape of the answer, never the check', };
33
+ if (COLUMN_STRING_FIELDS.includes(key)) return { ...col, ...d };
34
+ if (COLUMN_OPERAND_FIELDS.includes(key)) return { anyOf: [col, { type: 'object', properties: { const: { type: 'number' } }, required: ['const'], additionalProperties: false }], ...d };
35
+ switch (f.type) {
36
+ case 'name': case 'string': return { type: 'string', ...d };
37
+ case 'explanation': return null; // free text: never offered (a check carries no prose)
38
+ case 'date': return { type: 'string', ...d };
39
+ case 'integer': return { type: 'integer', ...d };
40
+ case 'number': return { type: 'number', ...d };
41
+ case 'boolean': return { type: 'boolean', ...d };
42
+ case 'enum': return { type: 'string', enum: f.enum, ...d };
43
+ case 'range': return { type: 'object', properties: { from: { type: 'integer' }, to: { type: 'integer' } }, required: ['from', 'to'], additionalProperties: false, ...d };
44
+ case 'cell': return { type: 'object', properties: { column: col, row: { type: 'integer' } }, required: ['column', 'row'], additionalProperties: false, ...d };
45
+ case 'condition-list': return { type: 'array', items: { type: 'object', properties: { column: col, cmp: { type: 'string', enum: [...WHERE_CMPS] }, value: {}, lo: {}, hi: {} }, required: ['column', 'cmp'], additionalProperties: false }, ...d };
46
+ case 'date-format-list': return { type: 'array', items: { type: 'object', properties: { column: col, format: { type: 'string', enum: V.cells.dateFormats } }, required: ['column', 'format'], additionalProperties: false }, ...d };
47
+ case 'band-list': return { type: 'array', items: { type: 'object', properties: { name: { type: 'string' }, gt: { type: 'number' }, gte: { type: 'number' }, lt: { type: 'number' }, lte: { type: 'number' } }, required: ['name'], additionalProperties: false }, ...d };
48
+ default: throw new Error(`sheetoffer: bareguard's rubricVocabulary has a field type "${f.type}" (${key}) this file does not know - add it before offering sheet checks`);
49
+ }
50
+ }
51
+
52
+ /**
53
+ * The tool schema of `close.sheet`: a list of bareguard cells / table checks. Every field is a field of bareguard's vocabulary; every column-bearing field
54
+ * (`column keyColumn groupColumn result a b from to cell where[].column dateFormats[].column`) is an enum of the sheet's exact header. `covers` is fwdloop's own field
55
+ * (which `~` rules of the job line the check covers), kept and signed.
56
+ * @param {Record<string, {header: string[]}>} tables the drafting copy's table of each CSV input role
57
+ * @returns {Record<string, any>|null} null when there is no sheet with a header to pick from
58
+ */
59
+ export function sheetChecksProp(tables) {
60
+ const roles = Object.keys(tables);
61
+ const headers = headerUnion(tables);
62
+ if (roles.length === 0 || headers.length === 0) return null;
63
+ const col = { type: 'string', enum: headers };
64
+ /** @type {Record<string, any>} */
65
+ const props = {
66
+ id: { type: 'string', minLength: 1, description: 'a short unique name for this check' },
67
+ rule: { type: 'string', enum: [...SHEET_RULES], description: 'cells: the step gives a value that bareguard recomputes; table: bareguard judges the sheet itself' },
68
+ };
69
+ for (const r of SHEET_RULES) {
70
+ for (const [k, f] of Object.entries(V.rules[r].fields)) {
71
+ if (k === 'op' || props[k] !== undefined) continue;
72
+ const s = fieldSchema(k, f, col, roles);
73
+ if (s !== null) props[k] = s;
74
+ }
75
+ }
76
+ props.op = { type: 'string', enum: [...new Set(SHEET_RULES.flatMap((r) => Object.keys(V.rules[r].ops)))], description: 'a cells op goes with rule "cells", a table op with rule "table" (listed in the system prompt)' };
77
+ props.covers = { type: 'array', items: { type: 'integer', minimum: 1 }, description: 'the numbers of the line\'s ~ guardrail rules this check verifies (1 is its first rule); [] when it verifies none of them' };
78
+ return {
79
+ type: 'array',
80
+ minItems: 1,
81
+ maxItems: MAX_SHEET_CHECKS,
82
+ description: 'only on a green step that reads a CSV input: the checks bareguard runs on the step\'s answer. Omit on any other step',
83
+ items: { type: 'object', properties: props, required: ['id', 'rule', 'table', 'op', 'covers'], additionalProperties: false },
84
+ };
85
+ }
86
+
87
+ /**
88
+ * Every op of the cells and table rules with its summary, what it requires and allows, its claim shape and bareguard's worked example check. Generated from the
89
+ * vocabulary; a new op bareguard adds shows up here by itself.
90
+ * @returns {string[]} lines for the system prompt
91
+ */
92
+ export function sheetOpsBrief() {
93
+ const out = [];
94
+ for (const rule of SHEET_RULES) {
95
+ out.push(`Rule "${rule}" ops (each line: op, what it does, requires / allows, then bareguard's worked example check; the column names in the examples are only illustrations):`);
96
+ for (const [op, o] of Object.entries(V.rules[rule].ops)) {
97
+ out.push(`- ${op}: ${o.summary}. requires: ${(o.requires ?? []).join(', ') || 'nothing'}; allows: ${(o.allows ?? []).join(', ') || 'nothing'}${o.claim ? `; the step's answer: ${o.claim}` : ''}. Example: ${JSON.stringify(o.example.check)}`);
98
+ }
99
+ }
100
+ out.push(`- The example table those checks run against: ${JSON.stringify(V.cells.exampleTables.t)}`);
101
+ out.push(`- A date column needs a dateFormats entry, its format one of ${V.cells.dateFormats.join(' | ')}. Where conditions: ${V.rules.cells.fields.where.description}`);
102
+ return out;
103
+ }
104
+
105
+ /**
106
+ * The rules the validator enforces on `close.sheet`, as lines for the drafter (every one of them is a refusal at $0 in src/declaration.js / src/sheetchecks.js).
107
+ * @param {string[]} roles the CSV input roles @returns {string[]}
108
+ */
109
+ export function sheetOfferRules(roles) {
110
+ return [
111
+ `- A green step whose line has a guardrail about values in a CSV input (${roles.join(', ')}) lists that input's role in its reads and carries close.sheet = a list of 1 to ${MAX_SHEET_CHECKS} checks, each a bareguard check object from the ops below, with "table" = the CSV input's role. Write the checks the line's guardrail needs and nothing else; the person signs them. close.sheet is for a green step only.`,
112
+ '- A column name in a check is picked from the sheet\'s header, spelled exactly; the tool only lets you pick a header name. A check that bareguard refuses (a wrong field for the op, overlapping bands, a missing dateFormats entry) is refused at $0 naming the job line.',
113
+ '- A number in a where condition (gt, gte, lt, lte, eq, between) must be a number the person wrote on that job line or its guardrail; a date (asOf, and the values of before, after, dateOn, dateBetween) must be a date they wrote there as YYYY-MM-DD. Never make a number or a date up: if the person gave none, leave that condition out.',
114
+ '- A "cells" check names "claim", a short name for the answer the step gives; the step is told only the shape of the answer, never the check. A "table" check has no claim and judges the sheet itself. If every check of a step is a table check the step has nothing to answer and the line is refused: pair a table check with at least one cells check.',
115
+ '- "covers" on each check lists the numbers of the line\'s guardrail rules (the ~ parts, counted from 1 in the order shown) that this check really verifies; [] if none. A guardrail rule that no check covers is shown to the person as Not checked, so cover every rule you can with a real check, and never claim a rule a check does not verify. A rule shaped like "use the column \'X\' for \'Y\'" is a column choice, not a rule to cover.',
116
+ ...sheetOpsBrief(),
117
+ ];
118
+ }
119
+
120
+ /** @param {unknown} rule @returns {boolean} true for the `use the column 'X' for 'Y'` rule an agreed column ask writes ({@link columnRuleWords}) */
121
+ export function isColumnChoiceRule(rule) {
122
+ const r = String(rule);
123
+ const head = columnRuleWords('', '').split("''")[0]; // "use the column '"
124
+ return r.startsWith(head) && r.endsWith("'") && r.includes("' for '");
125
+ }