fwdloop 0.22.0 → 0.24.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 (63) hide show
  1. package/bin/fwdloop +31 -8
  2. package/package.json +2 -2
  3. package/src/ask.js +34 -4
  4. package/src/attemptdiff.js +118 -0
  5. package/src/audit-fold.js +2 -0
  6. package/src/authoring.js +36 -2
  7. package/src/canrun.js +5 -0
  8. package/src/checked.js +14 -3
  9. package/src/citedcheck.js +16 -1
  10. package/src/citedwords.js +36 -2
  11. package/src/closers.js +13 -223
  12. package/src/config.js +5 -1
  13. package/src/csv.js +69 -12
  14. package/src/declaration.js +64 -6
  15. package/src/drafter.js +43 -17
  16. package/src/flowmodel.js +56 -1
  17. package/src/learn.js +952 -0
  18. package/src/learnstore.js +346 -0
  19. package/src/model-step.js +15 -21
  20. package/src/pagedry.js +3 -4
  21. package/src/pagefetch.js +9 -2
  22. package/src/pagerules.js +28 -5
  23. package/src/panel/author.js +2 -1
  24. package/src/panel/authorcard.js +9 -2
  25. package/src/panel/data.js +80 -17
  26. package/src/panel/index.html +186 -12
  27. package/src/panel/result.js +6 -0
  28. package/src/redact.js +6 -6
  29. package/src/runner.js +151 -24
  30. package/src/sheet-record.js +57 -0
  31. package/src/sheetblock.js +170 -0
  32. package/src/sheetchecks.js +206 -0
  33. package/src/sheetclaims.js +78 -0
  34. package/src/sheetoffer.js +125 -0
  35. package/src/sheetrun.js +105 -0
  36. package/src/thinking.js +11 -0
  37. package/src/try-checks.js +6 -0
  38. package/src/types.js +1 -9
  39. package/types/ask.d.ts +8 -2
  40. package/types/attemptdiff.d.ts +38 -0
  41. package/types/checked.d.ts +9 -3
  42. package/types/citedwords.d.ts +14 -0
  43. package/types/closers.d.ts +6 -31
  44. package/types/csv.d.ts +25 -4
  45. package/types/declaration.d.ts +6 -1
  46. package/types/drafter.d.ts +28 -9
  47. package/types/flowmodel.d.ts +36 -0
  48. package/types/learn.d.ts +576 -0
  49. package/types/learnstore.d.ts +168 -0
  50. package/types/model-step.d.ts +19 -30
  51. package/types/pagerules.d.ts +7 -0
  52. package/types/panel/authorcard.d.ts +2 -1
  53. package/types/panel/data.d.ts +2 -1
  54. package/types/panel/result.d.ts +1 -1
  55. package/types/runner.d.ts +19 -6
  56. package/types/sheet-record.d.ts +24 -0
  57. package/types/sheetblock.d.ts +116 -0
  58. package/types/sheetchecks.d.ts +70 -0
  59. package/types/sheetclaims.d.ts +26 -0
  60. package/types/sheetoffer.d.ts +25 -0
  61. package/types/sheetrun.d.ts +35 -0
  62. package/types/thinking.d.ts +11 -0
  63. package/types/types.d.ts +16 -11
@@ -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,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
+ }
@@ -0,0 +1,105 @@
1
+ // M10b piece 2 (docs/wiki/the-module-ladder.md "M10b scope" items 5-6 and amendment 1): a sheet check at RUN time.
2
+ // - the lock: at run start each CSV input a step's `close.sheet` names gets its `tableSha` (bareguard's fingerprint of the table made from the run's frozen copy)
3
+ // written down once with that run's inputs (`freezeInputs` is the one writer of inputs.json and calls `tableShaOfFile`); here is how it is read back;
4
+ // - the judge: `closeSheet` hands the signed checks, the step's typed answer and the run's table to bareguard's `checkStep`. No model grades.
5
+ // Third outcomes, each named, never green: a sheet the run recorded no fingerprint for, a frozen copy that is missing, a table that no longer gives the recorded
6
+ // `tableSha` (bareguard stops the check; the red names the input), any other stopped check.
7
+ // Throws away: bareguard's `full` (expected values, evidence) is not kept - the red keeps the gaps, which name rows and counts and never a cell's text.
8
+ import { basename } from 'node:path';
9
+ import { createRubric, checkStep, renderGaps, tableSha } from 'bareguard';
10
+ import { parseCsv, sheetTable } from './csv.js';
11
+ import { readFileInside } from './flow.js';
12
+ import { sheetCheckSentence, bareguardChecks } from './sheetchecks.js';
13
+ import { sheetCheckName, sheetFoundWords } from './sheetblock.js';
14
+
15
+ const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
16
+
17
+ /** The sheet inputs any step's `close.sheet` reads, once each, in order. @param {any[]} steps @returns {string[]} */
18
+ export function sheetRolesOf(steps) {
19
+ const roles = [];
20
+ for (const s of Array.isArray(steps) ? steps : []) {
21
+ const list = s?.close?.class === 'green' && Array.isArray(s.close.sheet) ? s.close.sheet : [];
22
+ for (const c of list) if (isRec(c) && typeof c.table === 'string' && !roles.includes(c.table)) roles.push(c.table);
23
+ }
24
+ return roles;
25
+ }
26
+
27
+ /**
28
+ * bareguard's `tableSha` of the run's frozen CSV `<runDir>/inputs/<name>` (its table from src/csv.js `sheetTable`), read through the one safe gateway; null when the copy
29
+ * cannot be read or bareguard cannot read it as a table (a ragged row, a repeated header).
30
+ * @param {string} runDir @param {string} name the frozen file's name @returns {string|null}
31
+ */
32
+ export function tableShaOfFrozen(runDir, name) {
33
+ const file = readFileInside(runDir, `inputs/${name}`);
34
+ return file.ok ? tableSha(sheetTable(parseCsv(file.text))) : null;
35
+ }
36
+
37
+ const SHA_RE = /^[0-9a-f]{64}$/;
38
+
39
+ /**
40
+ * What a sheet check reads in a run: the run's OWN frozen copy of each sheet its checks name, as bareguard's table, and the `tableSha` recorded in `inputs.json` at
41
+ * the run's start. The table is NOT compared here: bareguard compares it to the recorded sha when it checks (and stops if it differs).
42
+ * @param {string} runDir @param {any[]} checks the step's `close.sheet`
43
+ * @returns {{ok: true, tables: Record<string, {header: string[], rows: any[]}>, inputs: Array<{name: string, sha256: string}>}|{ok: false, red: string}}
44
+ */
45
+ export function readRunSheets(runDir, checks) {
46
+ const manifest = readFileInside(runDir, 'inputs.json');
47
+ if (!manifest.ok) return { ok: false, red: manifest.missing ? 'this run has no frozen inputs' : `inputs.json: ${manifest.red}` };
48
+ let entries;
49
+ try { entries = JSON.parse(manifest.text); } catch (err) { return { ok: false, red: `inputs.json is not valid JSON - ${/** @type {any} */ (err).message}` }; }
50
+ /** @type {Record<string, any>} */
51
+ const tables = {};
52
+ const inputs = [];
53
+ for (const c of checks) {
54
+ const role = isRec(c) ? c.table : undefined;
55
+ if (typeof role !== 'string' || role in tables) continue;
56
+ const entry = Array.isArray(entries) ? entries.find((e) => e?.id === role) : undefined;
57
+ if (!entry || typeof entry.frozen !== 'string') return { ok: false, red: `input "${role}": this run froze no input with that name` };
58
+ if (typeof entry.tableSha !== 'string' || !SHA_RE.test(entry.tableSha)) return { ok: false, red: `input "${role}": this run recorded no table fingerprint for it at its start` };
59
+ const file = readFileInside(runDir, `inputs/${basename(entry.frozen)}`);
60
+ if (!file.ok) return { ok: false, red: file.missing ? `input "${role}": the frozen copy is missing` : `input "${role}": ${file.red}` };
61
+ tables[role] = sheetTable(parseCsv(file.text));
62
+ inputs.push({ name: role, sha256: entry.tableSha });
63
+ }
64
+ return { ok: true, tables, inputs };
65
+ }
66
+
67
+ /**
68
+ * The close of a green step that reads a sheet. `sheet` = `readRunSheets`' answer. `artifact` is the step's typed answer (its claim boxes). Gaps come from bareguard
69
+ * (`renderGaps`: row numbers and counts, a data problem first); each signed check is also listed with its own pass or fail for the Checked list.
70
+ * @param {any[]} checks the step's `close.sheet` @param {unknown} artifact @param {ReturnType<typeof readRunSheets>|null|undefined} sheet
71
+ * @returns {Promise<import('./types.js').CloseVerdict>}
72
+ */
73
+ export async function closeSheet(checks, artifact, sheet) {
74
+ try {
75
+ if (!sheet || sheet.ok !== true) {
76
+ const red = sheet && sheet.ok === false ? sheet.red : 'the run gave the check no saved sheet to read';
77
+ return /** @type {any} */ ({ verdict: 'unparseable', red: `sheet close: ${red}` });
78
+ }
79
+ if (!isRec(artifact)) return /** @type {any} */ ({ verdict: 'unparseable', red: 'a sheet step must answer with an object, one field per check named in its job' });
80
+ const rubric = createRubric({ schema: 1, goal: 'sheet', inputs: sheet.inputs, checkpoints: { sheet: { gating: true, checks: bareguardChecks(checks) } }, maxReds: 3 });
81
+ const res = await checkStep(rubric, 'sheet', artifact, { tables: sheet.tables });
82
+ if (res.verdict === 'stopped') {
83
+ const moved = sheet.inputs.filter((i) => tableSha(sheet.tables[i.name]) !== i.sha256).map((i) => i.name);
84
+ if (moved.length > 0) {
85
+ return /** @type {any} */ ({ verdict: 'crash', red: `sheet close stopped: input ${moved.map((n) => `"${n}"`).join(', ')} - the saved sheet no longer gives the table this run recorded at its start` });
86
+ }
87
+ const fault = res.fault;
88
+ return /** @type {any} */ ({ verdict: 'crash', red: `sheet close stopped: the ${fault?.id ?? 'sheet'} check stopped (${fault?.kind ?? 'no detail'}${fault?.detail ? `: ${fault.detail}` : ''})` });
89
+ }
90
+ const gaps = res.verdict === 'red' ? res.gaps : [];
91
+ const rows = checks.map((c) => {
92
+ const mine = gaps.filter((g) => g.id === c.id);
93
+ // M10b piece 4: the Audit / Checked row is `<short name> — <plain words>`, with what the step claimed (green) or bareguard's gap words (red) as its result
94
+ return { id: c.id, text: `${sheetCheckName(c)} \u2014 ${sheetCheckSentence(c)}`, ok: mine.length === 0, result: mine.length === 0 ? sheetFoundWords(c, artifact) : renderGaps(mine) };
95
+ });
96
+ const sheetRecord = { inputs: sheet.inputs, claims: artifact, checks: rows.map((r) => ({ id: r.id, text: r.text, ok: r.ok, result: r.ok ? null : r.result })) };
97
+ if (res.verdict === 'red') {
98
+ const red = renderGaps(gaps) || 'a sheet check failed';
99
+ return /** @type {any} */ ({ verdict: 'red', red, reds: [red], checks: rows, sheetRecord });
100
+ }
101
+ return /** @type {any} */ ({ verdict: 'green', red: null, reds: [], checks: rows, sheetRecord });
102
+ } catch (err) {
103
+ return /** @type {any} */ ({ verdict: 'crash', red: `sheet close crashed: ${/** @type {any} */ (err).message}` });
104
+ }
105
+ }
package/src/thinking.js CHANGED
@@ -92,3 +92,14 @@ export function thinkingRuleWords(boxOn) {
92
92
  export function stepThinkingMode({ boxOn, attempt }) {
93
93
  return boxOn === true || (Number.isInteger(attempt) && attempt >= 2) ? 'on' : 'off';
94
94
  }
95
+
96
+ /**
97
+ * M8 am7 item 2: the ONE owner of whether a step's try is handed the earlier runs' block. The places thinking switches on, but NOT the Chat "Thinking on" box:
98
+ * a retry (2nd or later try), a redo at an ask (numbered after the step's last try, so 2nd or later), and a rerun (the fresh run's first step, which starts
99
+ * from the human's rerun reason). A step's plain first try never gets it, whatever the box says.
100
+ * @param {{attempt: number, rerunReason: string|null}} a `rerunReason`: the reason this try starts from when it is a fresh run's first try, else null
101
+ * @returns {boolean}
102
+ */
103
+ export function stepHintsWanted({ attempt, rerunReason }) {
104
+ return (Number.isInteger(attempt) && attempt >= 2) || (typeof rerunReason === 'string' && rerunReason !== '');
105
+ }
package/src/try-checks.js CHANGED
@@ -50,6 +50,12 @@ export function closeRecords(step, artifact, closed) {
50
50
  n: 3, text: 'the close could run', ok: false, result: closed.verdict, source,
51
51
  }];
52
52
  }
53
+ if (step?.close?.class === 'green' && Array.isArray(step?.close?.sheet) && Array.isArray(closed.checks)) {
54
+ // M10b piece 2: each signed sheet check is its own row, worded by `sheetCheckSentence`, judged by bareguard
55
+ return closed.checks.map((c, i) => ({
56
+ n: 3 + i, text: c.text, ok: c.ok, result: c.result, source,
57
+ }));
58
+ }
53
59
  if (step?.close?.class === 'green' && step?.close?.cited) {
54
60
  const n = Array.isArray(artifact?.results) ? artifact.results.length : 0;
55
61
  return [{
package/src/types.js CHANGED
@@ -244,15 +244,6 @@
244
244
  * @property {string|null} gap
245
245
  */
246
246
 
247
- /**
248
- * A green-class field value: `value` is the number/ISO-date/text claimed;
249
- * `cite` resolves it (src/closers.js's own grammar).
250
- * @typedef {object} GreenField
251
- * @property {string|number} value
252
- * @property {string} cite
253
- */
254
-
255
- /** @typedef {{ fields: Record<string, GreenField> }} GreenArtifact */
256
247
  /** @typedef {{ text: string, lines?: string[] }} SoftgreenArtifact */
257
248
 
258
249
  /**
@@ -263,6 +254,7 @@
263
254
  * @property {string[]} [reds]
264
255
  * @property {Array<{id:string, text:string, ok:boolean, result:string|null}>} [checks] a softgreen close: every check it ran (M4d am29 item 2)
265
256
  * @property {{part: any, check: any, results?: unknown}} [cited] a cited green close (M10 piece 4): the fact part and the check's own answer, for the run's cited-check record
257
+ * @property {{inputs: Array<{name:string, sha256:string}>, claims: unknown, checks: Array<{id:string, text:string, ok:boolean, result:string|null}>}} [sheetRecord] a sheet close (M10b piece 2): what the run's sheet-check record keeps
266
258
  */
267
259
 
268
260
  /**
package/types/ask.d.ts CHANGED
@@ -51,7 +51,7 @@ export function makeFileAskStep({ timeoutMs, pollMs, clock, writeLine, }?: {
51
51
  * @param {any} ask the parsed ask.json object (or its `evidence` field's
52
52
  * container — pass the whole ask so a missing `evidence` key is itself a
53
53
  * handled case, not the caller's problem).
54
- * @returns {{ draft: {step?: string, text: string} | null, unjudged: Array<{step: string, emits?: string, text: string}>, why?: string }}
54
+ * @returns {{ draft: {step?: string, text: string} | null, unjudged: Array<{step: string, emits?: string, text?: string, cells?: Record<string, unknown>}>, why?: string, claims?: Record<string, any>, results?: Array<{quote: string, values: Record<string, unknown>}> }}
55
55
  */
56
56
  export function readAskEvidence(ask: any): {
57
57
  draft: {
@@ -61,9 +61,15 @@ export function readAskEvidence(ask: any): {
61
61
  unjudged: Array<{
62
62
  step: string;
63
63
  emits?: string;
64
- text: string;
64
+ text?: string;
65
+ cells?: Record<string, unknown>;
65
66
  }>;
66
67
  why?: string;
68
+ claims?: Record<string, any>;
69
+ results?: Array<{
70
+ quote: string;
71
+ values: Record<string, unknown>;
72
+ }>;
67
73
  };
68
74
  /**
69
75
  * M4b piece 3: the ONE serialisation of an artifact's bytes — what