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
package/src/closers.js CHANGED
@@ -2,40 +2,21 @@
2
2
  // SIGNED", scope item 4): `closeByClass(step, artifact, ctx)` — the
3
3
  // deterministic, $0 close, dispatched on the step's declared `close.class`.
4
4
  //
5
- // borrowed-from: fwdloop poc/m0/close.mjs@29caa83 (the closed formula
6
- // grammar sum/count/min/max/sub/daysBetween; `parseNumeric`/`roundTo` —
7
- // compare a stated figure to its source at the SOURCE's own decimal
8
- // precision, never the stated figure's) and fwdloop poc/m0/shape.mjs@29caa83
5
+ // borrowed-from: fwdloop poc/m0/shape.mjs@29caa83
9
6
  // (`closeWordsAndSections`, F38 version — every failing check reported, not
10
7
  // just the first). Rewritten against M2's own typed artifact contract below
11
8
  // — src/ never imports from poc/ (CLAUDE.md: "borrow, never import").
9
+ // (The M0 cell-cite grammar - sum/count/min/max/sub/daysBetween over `<input>!C3` cites - retired in M10b piece 5, item 8.)
12
10
  //
13
11
  // ---------------------------------------------------------------------------
14
12
  // Artifact contracts (M2 scope item 4's own docblock requirement).
15
13
  // ---------------------------------------------------------------------------
16
14
  //
17
- // GREEN step artifact: `{ fields: { <name>: { value, cite } } }`
18
- // - `value`: the number, ISO date (`YYYY-MM-DD`) string, or exact text the
19
- // step claims for this field.
20
- // - `cite`: a string in one of two forms:
21
- // "<artifactId>!<COL><ROW>" a cell in a 'cells'/'csv'-kind
22
- // artifact already in `ctx.reads`
23
- // (e.g. "aging_cells!E2").
24
- // "<formula>(<arg>[,<arg>...])" formula ∈ {sum,count,min,max,sub,
25
- // daysBetween}; each <arg> is a cell
26
- // cite OR "#<fieldName>" naming an
27
- // EARLIER field of this SAME
28
- // artifact (fields resolve in
29
- // declared order, never forward —
30
- // same flat shape M0's citation-id
31
- // inputs used; formulas never
32
- // nest inside one string).
33
- // `daysBetween(cite)` (one arg) computes days between that date and
34
- // `ctx.businessDate`; `daysBetween(cite,cite)` (two args) computes days
35
- // between the two — never a third form.
36
- // A malformed field or an artifact shaped wrong is `unparseable` (a
37
- // casualty, never a red — bareloop F17); an internal error while
38
- // resolving is `crash`.
15
+ // GREEN step artifact: one of two forms, each with its own closer.
16
+ // - a page or document quote: `{ results: [...] }` (`closeCited`, bareguard's `cited` check);
17
+ // - a sheet: one typed claim box per `cells` check (`closeSheet`, src/sheetrun.js, bareguard's `cells` / `table` checks).
18
+ // A green step with neither `close.cited` nor `close.sheet` is the retired cell cite: `closeByClass` answers `crash`, and a job signed that way is refused
19
+ // at start (src/canrun.js `findUnbuildableCheckStep`) before it can get here.
39
20
  //
40
21
  // SOFTGREEN (compose) step artifact: `{ text: string }`
41
22
  // - `text` is the whole composed text; `maxWords`/`sections`/`wordsPerSection` run over it directly. Since M4e amendment 18 these
@@ -64,208 +45,15 @@
64
45
 
65
46
  import { createRubric, checkStep } from 'bareguard';
66
47
  import { checkCited } from './citedcheck.js';
48
+ import { closeSheet } from './sheetrun.js';
67
49
 
68
50
  /** @typedef {import('./types.js').CloseVerdict} CloseVerdict */
69
51
 
70
- export const FORMULAS = Object.freeze({
71
- sum: (vals) => vals.reduce((a, b) => a + b, 0),
72
- count: (vals) => vals.length,
73
- min: (vals) => Math.min(...vals),
74
- max: (vals) => Math.max(...vals),
75
- sub: (vals) => vals[0] - vals[1],
76
- });
77
-
78
- /**
79
- * M10 am10: the one description of the cite forms, told to a step whose check cites cells and named in the red when a cite fits none.
80
- * Built from the checker's own formula list (FORMULAS keys + daysBetween, which is handled apart), so the text cannot drift from what is accepted.
81
- */
82
- export function citeForms(names = [...Object.keys(FORMULAS), 'daysBetween']) {
83
- return `one cell (\`<input>!C3\`), a field above it (\`#name\`), or ${names.join(', ')} over those`;
84
- }
85
-
86
52
  /** An input with cells (M4d amendment 8): a file whose name ends `.csv`. The one decider for "this input can be cited". */
87
53
  export function isCellsPath(p) {
88
54
  return typeof p === 'string' && p.toLowerCase().endsWith('.csv');
89
55
  }
90
56
 
91
- const CELL_RE = /^([a-zA-Z0-9_-]+)!([A-Za-z]+)(\d+)$/;
92
- const FORMULA_RE = /^(sum|count|min|max|sub|daysBetween)\((.*)\)$/;
93
- const FIELD_REF_RE = /^#([A-Za-z0-9_]+)$/;
94
- const ISO_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
95
-
96
- function colIndexOf(col) {
97
- let n = 0;
98
- for (const ch of col.toUpperCase()) n = n * 26 + (ch.charCodeAt(0) - 64);
99
- return n - 1;
100
- }
101
-
102
- /** Strip thousands separators / currency symbols; report the value and the source's own decimal precision. */
103
- function parseNumeric(raw) {
104
- const cleaned = String(raw).replace(/[$,]/g, '').trim();
105
- const value = Number(cleaned);
106
- const dot = cleaned.indexOf('.');
107
- const decimals = dot === -1 ? 0 : cleaned.length - dot - 1;
108
- return { value, decimals };
109
- }
110
-
111
- function roundTo(n, decimals) {
112
- const f = 10 ** decimals;
113
- return Math.round(n * f) / f;
114
- }
115
-
116
- function getCellRaw(artifact, col, row) {
117
- const found = (artifact.rows ?? []).find((r) => r.rowNumber === row);
118
- if (!found) return null;
119
- return found.cells?.[col.toUpperCase()] ?? null;
120
- }
121
-
122
- /**
123
- * Resolve one `cite` string against `ctx.reads` (artifacts already read by
124
- * this step) and `fieldsSoFar` (fields of THIS artifact already resolved, in
125
- * declared order). Returns `{ ok:true, raw }` (a raw cell value still to be
126
- * type-compared) or `{ ok:true, computed }` (a formula's already-numeric
127
- * result) or `{ ok:false, red }`. Never throws on a malformed cite — that is
128
- * a red the caller renders, not an exception.
129
- */
130
- function resolveCite(cite, ctx) {
131
- if (typeof cite !== 'string' || cite.length === 0) {
132
- return { ok: false, red: `cite must be a non-empty string, got ${JSON.stringify(cite)}` };
133
- }
134
-
135
- const cellMatch = CELL_RE.exec(cite);
136
- if (cellMatch) {
137
- const [, artifactId, col, rowStr] = cellMatch;
138
- const artifact = ctx.reads?.[artifactId];
139
- if (!artifact) return { ok: false, red: `cite "${cite}": unknown artifact "${artifactId}"` };
140
- if (artifact.kind !== 'cells' && artifact.kind !== 'csv') {
141
- return { ok: false, red: `cite "${cite}": artifact "${artifactId}" is not a cells/csv-kind read` };
142
- }
143
- if (colIndexOf(col) < 0) return { ok: false, red: `cite "${cite}": "${col}" is not a valid column` };
144
- const row = Number(rowStr);
145
- const raw = getCellRaw(artifact, col, row);
146
- if (raw === null) return { ok: false, red: `cite "${cite}": cell ${col}${row} does not exist in "${artifactId}"` };
147
- // M10 am8 item 2: the step's check names the column(s) its facts come from; a cell from any other column is red, naming it
148
- const locked = (Array.isArray(ctx.lock) ? ctx.lock : []).filter((l) => l?.source === artifactId).map((l) => l.column);
149
- if (locked.length > 0) {
150
- const name = artifact.header?.[colIndexOf(col)];
151
- if (!locked.includes(name)) return { ok: false, red: `cite "${cite}": the cell ${col}${row} is in column '${name ?? col}', but this step is locked to column ${locked.map((c) => `'${c}'`).join(' and ')}` };
152
- }
153
- return { ok: true, raw };
154
- }
155
-
156
- const fieldMatch = FIELD_REF_RE.exec(cite);
157
- if (fieldMatch) {
158
- const name = fieldMatch[1];
159
- if (!Object.prototype.hasOwnProperty.call(ctx.fieldsSoFar ?? {}, name)) {
160
- return { ok: false, red: `cite "${cite}": field "${name}" is not resolved yet (fields resolve top to bottom, never forward)` };
161
- }
162
- return { ok: true, raw: ctx.fieldsSoFar[name].value };
163
- }
164
-
165
- const formulaMatch = FORMULA_RE.exec(cite);
166
- if (formulaMatch) {
167
- const [, op, argsRaw] = formulaMatch;
168
- const argCites = argsRaw.split(',').map((s) => s.trim()).filter((s) => s.length > 0);
169
-
170
- if (op === 'daysBetween') {
171
- if (argCites.length < 1 || argCites.length > 2) {
172
- return { ok: false, red: `cite "${cite}": daysBetween takes 1 or 2 args, got ${argCites.length}` };
173
- }
174
- const resolved = [];
175
- for (const arg of argCites) {
176
- const r = resolveCite(arg, ctx);
177
- if (!r.ok) return r;
178
- resolved.push(r.raw);
179
- }
180
- const fromDate = resolved[0];
181
- const toDate = argCites.length === 2 ? resolved[1] : ctx.businessDate;
182
- if (!ISO_DATE_RE.test(String(fromDate)) || !ISO_DATE_RE.test(String(toDate))) {
183
- return { ok: false, red: `cite "${cite}": daysBetween needs ISO (YYYY-MM-DD) dates, got "${fromDate}"/"${toDate}"` };
184
- }
185
- const days = Math.round((Date.parse(`${toDate}T00:00:00Z`) - Date.parse(`${fromDate}T00:00:00Z`)) / 86400000);
186
- return { ok: true, computed: days };
187
- }
188
-
189
- const fn = FORMULAS[op];
190
- if (!fn) return { ok: false, red: `cite "${cite}": unknown formula "${op}" (closed grammar: sum,count,min,max,sub,daysBetween)` };
191
- const vals = [];
192
- for (const arg of argCites) {
193
- const r = resolveCite(arg, ctx);
194
- if (!r.ok) return r;
195
- const num = r.computed !== undefined ? r.computed : parseNumeric(r.raw).value;
196
- if (Number.isNaN(num)) return { ok: false, red: `cite "${cite}": arg "${arg}" does not resolve to a number` };
197
- vals.push(num);
198
- }
199
- return { ok: true, computed: fn(vals) };
200
- }
201
-
202
- return { ok: false, red: `cite "${cite}" does not match the cell or formula grammar - the forms are: ${citeForms()}` };
203
- }
204
-
205
- function checkField(name, field, ctx) {
206
- if (!field || typeof field !== 'object' || field.value === undefined || typeof field.cite !== 'string') {
207
- return { verdict: 'red', red: `field "${name}" must be an object {value, cite:string}, got ${JSON.stringify(field)}` };
208
- }
209
- const resolved = resolveCite(field.cite, ctx);
210
- if (!resolved.ok) return { verdict: 'red', red: `field "${name}": ${resolved.red}` };
211
-
212
- if (resolved.computed !== undefined) {
213
- if (Number(field.value) !== resolved.computed) {
214
- return { verdict: 'red', red: `field "${name}" ${field.value} ≠ ${field.cite} = ${resolved.computed}` };
215
- }
216
- return { verdict: 'green' };
217
- }
218
-
219
- const raw = resolved.raw;
220
- if (ISO_DATE_RE.test(String(field.value))) {
221
- if (String(field.value) !== String(raw)) {
222
- return { verdict: 'red', red: `field "${name}" ${field.value} ≠ cite ${field.cite} = ${raw}` };
223
- }
224
- return { verdict: 'green' };
225
- }
226
- const { value: numVal, decimals } = parseNumeric(raw);
227
- if (Number.isNaN(numVal)) {
228
- if (String(field.value).trim() !== String(raw).trim()) {
229
- return { verdict: 'red', red: `field "${name}" ${field.value} ≠ cite ${field.cite} = ${raw}` };
230
- }
231
- return { verdict: 'green' };
232
- }
233
- if (roundTo(Number(field.value), decimals) !== roundTo(numVal, decimals)) {
234
- return { verdict: 'red', red: `field "${name}" ${field.value} ≠ cite ${field.cite} = ${numVal}` };
235
- }
236
- return { verdict: 'green' };
237
- }
238
-
239
- /**
240
- * `green` close: every field in `artifact.fields`, in declared order,
241
- * resolves and matches its cite. First red wins.
242
- *
243
- * @param {any} artifact
244
- * @param {{ reads: Record<string, any>, businessDate: string, lock?: {source: string, column: string}[] }} ctx `lock` (M10 am8): the columns the step's check names
245
- * @returns {CloseVerdict}
246
- */
247
- export function closeGreen(artifact, ctx) {
248
- try {
249
- if (!artifact || typeof artifact !== 'object' || !artifact.fields || typeof artifact.fields !== 'object') {
250
- return /** @type {CloseVerdict} */ ({ verdict: 'unparseable', red: 'green artifact must be an object shaped {fields: {...}}' });
251
- }
252
- const names = Object.keys(artifact.fields);
253
- if (names.length === 0) {
254
- return /** @type {CloseVerdict} */ ({ verdict: 'unparseable', red: 'green artifact has no fields' });
255
- }
256
- /** @type {Record<string, any>} */
257
- const fieldsSoFar = {};
258
- for (const name of names) {
259
- const result = checkField(name, artifact.fields[name], { reads: ctx.reads, fieldsSoFar, businessDate: ctx.businessDate, lock: ctx.lock });
260
- if (result.verdict === 'red') return /** @type {CloseVerdict} */ (result);
261
- fieldsSoFar[name] = artifact.fields[name];
262
- }
263
- return { verdict: 'green', red: null };
264
- } catch (err) {
265
- return { verdict: 'crash', red: `green close crashed: ${err.message}` };
266
- }
267
- }
268
-
269
57
  /**
270
58
  * M10 piece 4 (item 2, "green grows"): the green close of a step that cites quotes instead of cells. `part` is the step's fact part (`close.cited`, set by
271
59
  * code from the page look's kept facts, never by the model); `source` is the run's OWN frozen copy of the page or doc (`readRunSource`); the artifact is
@@ -476,16 +264,18 @@ export async function closeSoftgreen(artifact, shape) {
476
264
  /**
477
265
  * The one dispatcher — `close by declared class` (M2 scope item 4).
478
266
  *
479
- * @param {{ close?: { class?: string, shape?: Record<string, any>, cited?: any, columns?: {source: string, column: string}[] } }} step
267
+ * @param {{ close?: { class?: string, shape?: Record<string, any>, cited?: any, columns?: {source: string, column: string}[], sheet?: any[] } }} step
480
268
  * @param {unknown} artifact
481
- * @param {{ reads: Record<string, any>, businessDate: string, source?: {ok: true, text: string, sha256: string}|{ok: false, red: string}|null }} ctx
269
+ * @param {{ reads: Record<string, any>, businessDate: string, source?: {ok: true, text: string, sha256: string}|{ok: false, red: string}|null, sheet?: any }} ctx
482
270
  * `source` (M10 piece 4) = the run's own frozen copy a cited step reads, from `readRunSource`; only a step whose close carries `cited` reads it
271
+ * `sheet` (M10b piece 2) = the run's own tables and recorded `tableSha`s a step with `close.sheet` is checked on, from `readRunSheets`
483
272
  * @returns {Promise<CloseVerdict>}
484
273
  */
485
274
  export async function closeByClass(step, artifact, ctx) {
486
275
  const cls = step?.close?.class;
487
276
  if (cls === 'green' && step?.close?.cited) return await closeCited(step.close.cited, artifact, ctx.source);
488
- if (cls === 'green') return closeGreen(artifact, { ...ctx, lock: step?.close?.columns });
277
+ if (cls === 'green' && Array.isArray(step?.close?.sheet)) return await closeSheet(step.close.sheet, artifact, ctx.sheet);
278
+ if (cls === 'green') return { verdict: 'crash', red: 'closeByClass: a green step with no close.sheet or close.cited is the retired cell cite' };
489
279
  if (cls === 'softgreen') return await closeSoftgreen(artifact, step?.close?.shape ?? {});
490
280
  if (cls === 'hitl') return { verdict: 'hitl', red: null };
491
281
  return { verdict: 'crash', red: `closeByClass: unknown close class ${JSON.stringify(cls)}` };
package/src/config.js CHANGED
@@ -5,7 +5,8 @@
5
5
  // { "monthlyLimitUsd": <number > 0>, // absent = no limit (piece 3 reads it)
6
6
  // "prices": { "<slot>": { "inPerM": n, "cachedInPerM": n, "outPerM": n } }, // USD per 1M tokens, each optional; a saved "cachedInPerM" is tolerated, never read (M4d amendment 2)
7
7
  // "providers": { "<KEY_NAME>": { "shape": "<shape id>", "baseUrl": "http(s)://…", "legacyMaxTokens": true|false } }, // each optional; a row is a key name from the keys file (M4d amendment 6). An older file's "model" is tolerated and read by nothing.
8
- // "models": { "<KEY_NAME>": [ { "model": "<id>", "use": true|false, "inPerM": n, "outPerM": n } ] } } // M4d amendment 3 C: a price per model
8
+ // "models": { "<KEY_NAME>": [ { "model": "<id>", "use": true|false, "inPerM": n, "outPerM": n } ] }, // M4d amendment 3 C: a price per model
9
+ // "learningHints": true|false } // M8 am1: absent = false; the drafter is handed earlier runs' notes only when true (src/learnstore.js learningHintsOn). No control on the Settings page.
9
10
  // A models line's price is a PAIR or nothing (`modelsProblem` is the one rule): 0 / 0 typed is a chosen price, a
10
11
  // ticked line needs both, a half pair is refused. A slot with no list is migrated on READ (`effectiveModels` in
11
12
  // src/provider.js); the file is only rewritten when the person saves.
@@ -173,6 +174,9 @@ function validateDoc(doc) {
173
174
  if (doc.monthlyLimitUsd !== undefined && !isPrice(doc.monthlyLimitUsd)) {
174
175
  throw new ConfigError('monthlyLimitUsd must be a number above 0 (remove the limit to have none)');
175
176
  }
177
+ if (doc.learningHints !== undefined && typeof doc.learningHints !== 'boolean') {
178
+ throw new ConfigError('learningHints must be true or false');
179
+ }
176
180
  validateProviders(doc.providers);
177
181
  validateModels(doc.models);
178
182
  if (doc.prices === undefined) return;
package/src/csv.js CHANGED
@@ -1,6 +1,5 @@
1
- // borrowed-from: fwdloop poc/m0/csv.mjs@76a3607 (verbatim logic). Tiny CSV
2
- // parser — never quoted-field aware, which every fixture this project reads
3
- // doesn't need (dependency hierarchy: stdlib/vanilla first). The addressable
1
+ // borrowed-from: fwdloop poc/m0/csv.mjs@76a3607 (the first reader; M10b item 2 rewrote it to RFC 4180 quoting). Tiny CSV
2
+ // parser (dependency hierarchy: stdlib/vanilla first). The addressable
4
3
  // -cells contract (`parseCellRef`/`colLetter`) is fwdloop's own citation
5
4
  // grammar (F13, ruled 2026-09-09 — not a baresuite primitive), so it lives
6
5
  // with the reader that produces those addresses.
@@ -32,17 +31,61 @@ export function parseCellRef(cell) {
32
31
  }
33
32
 
34
33
  /**
35
- * Parse CSV text with no quoted fields into { header, rows }.
36
- * `rows[i]` is `{ rowNumber, cells: { A: '...', B: '...' }, byName: { Customer: '...' } }`
37
- * where `rowNumber` is the 1-based sheet row (header is row 1, first data row is row 2).
34
+ * Split CSV text into records (RFC 4180): a cell may be quoted ("1,200.50" is one cell, "" inside quotes is one quote, a comma or a line break inside quotes
35
+ * stays in the cell); LF and CRLF both end a record. Each record carries `line`, the 1-based line of the text it starts on, so a line break inside a quoted
36
+ * cell still counts. A blank line (nothing, not even quotes) is no record, but its line is counted. A quote inside an unquoted cell is just a character.
37
+ * @param {string} text @returns {{line: number, fields: string[]}[]}
38
+ */
39
+ function records(text) {
40
+ /** @type {{line: number, fields: string[]}[]} */
41
+ const out = [];
42
+ let line = 1;
43
+ let startLine = 1;
44
+ /** @type {string[]} */ let fields = [];
45
+ let cell = '';
46
+ let inQuotes = false;
47
+ let quoted = false; // the current record used a quote: an empty cell then is a real cell, not a blank line
48
+ const endCell = () => { fields.push(cell); cell = ''; };
49
+ const endRecord = () => {
50
+ endCell();
51
+ if (!(fields.length === 1 && fields[0] === '' && !quoted)) out.push({ line: startLine, fields });
52
+ fields = [];
53
+ quoted = false;
54
+ };
55
+ for (let i = 0; i < text.length; i += 1) {
56
+ const ch = text[i];
57
+ if (inQuotes) {
58
+ if (ch === '"') {
59
+ if (text[i + 1] === '"') { cell += '"'; i += 1; } else inQuotes = false;
60
+ } else {
61
+ if (ch === '\n') line += 1;
62
+ cell += ch;
63
+ }
64
+ } else if (ch === '"' && cell === '') { inQuotes = true; quoted = true; }
65
+ else if (ch === ',') endCell();
66
+ else if (ch === '\n' || (ch === '\r' && text[i + 1] === '\n')) {
67
+ if (ch === '\r') i += 1;
68
+ endRecord();
69
+ line += 1;
70
+ startLine = line;
71
+ } else cell += ch;
72
+ }
73
+ if (cell !== '' || fields.length > 0 || quoted) endRecord();
74
+ return out;
75
+ }
76
+
77
+ /**
78
+ * Parse CSV text into { header, rows } (RFC 4180 quoting, see `records`).
79
+ * `rows[i]` is `{ rowNumber, cells: { A: '...', B: '...' }, byName: { Customer: '...' }, raw: ['...', '...'] }` (`raw` is the row's cells exactly as the file has them: no padding, nothing cut)
80
+ * where `rowNumber` is the real sheet line the row starts on (header is row 1; a blank line is skipped but still counted, so it never shifts the rows below).
38
81
  */
39
82
  export function parseCsv(text) {
40
- const lines = text.split(/\r?\n/).filter((l) => l.length > 0);
41
- if (lines.length === 0) return { header: [], rows: [] };
42
- const header = lines[0].split(',');
83
+ const recs = records(text);
84
+ if (recs.length === 0) return { header: [], rows: [] };
85
+ const header = recs[0].fields;
43
86
  const rows = [];
44
- for (let i = 1; i < lines.length; i += 1) {
45
- const fields = lines[i].split(',');
87
+ for (let i = 1; i < recs.length; i += 1) {
88
+ const fields = recs[i].fields;
46
89
  const cells = {};
47
90
  const byName = {};
48
91
  header.forEach((name, col) => {
@@ -51,7 +94,21 @@ export function parseCsv(text) {
51
94
  cells[letter] = val;
52
95
  byName[name] = val;
53
96
  });
54
- rows.push({ rowNumber: i + 1, cells, byName });
97
+ rows.push({ rowNumber: recs[i].line, cells, byName, raw: [...fields] });
55
98
  }
56
99
  return { header, rows };
57
100
  }
101
+
102
+ /**
103
+ * A parsed sheet as bareguard's table shape: `{ header: string[], rows: [{ rowNumber, cells: string[] }] }`. Each row's cells are the row exactly as the file
104
+ * has it (`raw`): a short or a long row is NOT padded or cut here, so bareguard itself stops it (`tableSha` gives null for a ragged row, and the table is
105
+ * refused). The header strings are exactly as the file has them. The one writer of this shape (M10b item 2).
106
+ * @param {{header: string[], rows: {rowNumber: number, raw: string[]}[]}} sheet from `parseCsv`
107
+ * @returns {{header: string[], rows: {rowNumber: number, cells: string[]}[]}}
108
+ */
109
+ export function sheetTable(sheet) {
110
+ return {
111
+ header: [...sheet.header],
112
+ rows: sheet.rows.map((r) => ({ rowNumber: r.rowNumber, cells: [...r.raw] })),
113
+ };
114
+ }
@@ -39,6 +39,9 @@
39
39
  import { buildSoftgreenRubric, isCellsPath } from './closers.js';
40
40
  import { factPartReds } from './citedcheck.js';
41
41
  import { numberRuleReds, countReds, citedWordReds } from './citedwords.js';
42
+ import { SHEET_RULES, MAX_SHEET_CHECKS, sheetCheckColumns, sheetCheckReds, sheetCheckWordReds, sheetNoClaimReds, sheetCoversReds } from './sheetchecks.js';
43
+ import { lineRules } from './pagebits.js';
44
+ import { isColumnChoiceRule } from './sheetoffer.js';
42
45
 
43
46
  /** @typedef {import('./types.js').Arbiter} Arbiter */
44
47
  /** @typedef {import('./types.js').SignedLine} SignedLine */
@@ -68,6 +71,7 @@ export const DECLARATION_FIELDS = Object.freeze([
68
71
  'shape',
69
72
  'cited',
70
73
  'columns',
74
+ 'sheet',
71
75
  ]);
72
76
 
73
77
  const VALID_CLASSES = Object.freeze(['green', 'softgreen', 'hitl']);
@@ -80,7 +84,7 @@ const ARBITER_KEYS = Object.freeze(['cap', 'ask', 'ttl', 'send', 'source', 'trig
80
84
 
81
85
  const TOP_LEVEL_ALLOWED = Object.freeze(['steps', 'guardrailClasses', 'unjudgeable', 'refused', 'inputFacts']);
82
86
  const STEP_ALLOWED = Object.freeze(['goal', 'primitives', 'reads', 'emits', 'fromLine', 'close', 'picks']);
83
- const CLOSE_ALLOWED = Object.freeze(['class', 'shape', 'cited', 'columns']);
87
+ const CLOSE_ALLOWED = Object.freeze(['class', 'shape', 'cited', 'columns', 'sheet']);
84
88
 
85
89
  /** @returns {value is Record<string, any>} */
86
90
  function isPlainObject(value) {
@@ -435,10 +439,10 @@ function checkCitedKey(step, label, c, reds) {
435
439
  }
436
440
 
437
441
  /**
438
- * M10 am8 item 2: `close.columns` is the column lock of a green step that cites cells: `[{source, column}]`, written by the drafter and checked by code. Its SHAPE is
442
+ * M10 am8 item 2: `close.columns` is the column choice of a green step that reads a sheet: `[{source, column}]`, written by the drafter and checked by code (the old cell-cite check that enforced it at run time retired in M10b piece 5; a job signed with it still reads). Its SHAPE is
439
443
  * checked in every mode; with `sheetWords` (draft time) every column is proved to be a real column of its sheet and a column the sheet look kept for this step's
440
- * line must be in the list. At run time every cited cell must come from one of these columns (src/closers.js).
441
- * @param {any} step @param {string} label @param {{cellsRoles: string[], reads: string[]|null, effectiveClass: string, sheetWords?: {headers: Record<string, string[]>, facts: any[]}}} c @param {string[]} reds
444
+ * line must be in the list. M10b am3: a step with `close.sheet` is exempt from the list; an AGREED column must instead be used by one of its checks.
445
+ * @param {any} step @param {string} label @param {{cellsRoles: string[], reads: string[]|null, effectiveClass: string, lines?: SignedLine[], sheetWords?: {headers: Record<string, string[]>, facts: any[]}}} c @param {string[]} reds
442
446
  */
443
447
  function checkColumnsKey(step, label, c, reds) {
444
448
  const at = `declaration: ${label}.close.columns`;
@@ -463,12 +467,57 @@ function checkColumnsKey(step, label, c, reds) {
463
467
  const header = sw.headers?.[e.source];
464
468
  if (Array.isArray(header) && !header.includes(e.column)) reds.push(`declaration: line ${step.fromLine}: '${e.column}' is not a real column of "${e.source}" (its columns: ${header.map((h) => `'${h}'`).join(', ')}). Copy a column name exactly.`);
465
469
  }
470
+ const sheet = Array.isArray(step.close.sheet) ? step.close.sheet : null;
471
+ const covLine = (c.lines ?? []).find((l) => l.n === step.fromLine);
466
472
  for (const f of sw.facts ?? []) {
467
473
  if (f.line !== step.fromLine || f.shape !== 'column') continue;
474
+ if (sheet !== null) {
475
+ // M10b am3: with sheet checks a job word that matches a header does nothing by itself; only a column the person AGREED to (a column ask wrote
476
+ // "use the column 'X' for 'Y'" on the line) must be used by at least one of this line's checks
477
+ const agreed = f.agreed === true || lineRules(covLine).some((r) => isColumnChoiceRule(r) && r.startsWith(`use the column '${f.column}' for '`));
478
+ if (agreed && !sheet.some((chk) => chk?.table === f.source && sheetCheckColumns(chk).includes(f.column))) reds.push(`declaration: line ${step.fromLine}: a check must use the column '${f.column}' of "${f.source}" - the column you agreed to for this line.`);
479
+ continue;
480
+ }
468
481
  if (!list.some((e) => e.source === f.source && e.column === f.column)) reds.push(`declaration: line ${step.fromLine}: the check must name the column '${f.column}' of "${f.source}" in close.columns - the code kept it for this line${f.agreed ? ' (the column you agreed to)' : ''}, and every cell must come from it.`);
469
482
  }
470
483
  }
471
484
 
485
+ /**
486
+ * M10b piece 1: `close.sheet` is the signed bareguard checks of a green step that reads a CSV sheet: a list of bareguard `cells` / `table` check objects
487
+ * (src/sheetchecks.js), each naming the step's sheet input in `table`. The drafter will offer them (piece 3); fwdloop stores them as data. Its SHAPE is checked in
488
+ * every mode (a signed flow is read the same way). With `sheetWords.tables` (the drafting copy's table of each sheet, draft time) every column is proved an exact
489
+ * header of its sheet and bareguard's own sign-time test (`createRubric` over the sheet's `tableSha`) must accept the list; each red names the job line.
490
+ * @param {any} step @param {string} label @param {{cellsRoles: string[], reads: string[]|null, effectiveClass: string, lines?: SignedLine[], fitJobLine?: boolean, sheetWords?: {tables?: Record<string, {header: string[], rows: any[]}>}}} c @param {string[]} reds
491
+ * M10b piece 3: with `fitJobLine` a number or a date in a check must be in the person's own words on the job line (src/sheetchecks.js `sheetCheckWordReds`), and a list of
492
+ * only `table` checks (nothing for the step to answer) is refused; each red names the line.
493
+ */
494
+ function checkSheetKey(step, label, c, reds) {
495
+ const at = `declaration: ${label}.close.sheet`;
496
+ const list = step.close.sheet;
497
+ if (step.close.class !== 'green' || c.effectiveClass !== 'green') reds.push(`${at} is for a green step only (its sheet is checked by bareguard); this step's check is "${step.close.class ?? c.effectiveClass}"`);
498
+ if (!Array.isArray(list) || list.length === 0 || list.length > MAX_SHEET_CHECKS) { reds.push(`${at} must be a list of 1 to ${MAX_SHEET_CHECKS} bareguard checks`); return; }
499
+ let shapeOk = true;
500
+ for (const [j, e] of list.entries()) {
501
+ if (!isPlainObject(e)) { reds.push(`${at}[${j}] must be a check object`); shapeOk = false; continue; }
502
+ scanForArbiterKeys(e, `${at}[${j}]`, reds);
503
+ if (!SHEET_RULES.includes(e.rule)) { reds.push(`${at}[${j}].rule must be one of ${SHEET_RULES.join(', ')}`); shapeOk = false; }
504
+ if (typeof e.table !== 'string' || !c.cellsRoles.includes(e.table)) { reds.push(`${at}[${j}].table ${JSON.stringify(e.table)} is not a signed spreadsheet input`); shapeOk = false; }
505
+ else if (c.reads !== null && !c.reads.includes(e.table)) { reds.push(`${at}[${j}].table "${e.table}" is not in ${label}.reads - the step must read the sheet its checks come from`); shapeOk = false; }
506
+ }
507
+ if (shapeOk && Number.isInteger(step.fromLine)) {
508
+ const covLine = (c.lines ?? []).find((l) => l.n === step.fromLine);
509
+ if (covLine) for (const r of sheetCoversReds(list, { n: covLine.n, ...(covLine.guardrail ? { rule: covLine.guardrail } : {}) })) reds.push(r);
510
+ }
511
+ if (shapeOk && c.fitJobLine === true && Number.isInteger(step.fromLine)) {
512
+ const jobLine = (c.lines ?? []).find((l) => l.n === step.fromLine);
513
+ if (jobLine) for (const r of sheetCheckWordReds(list, { n: jobLine.n, text: jobLine.text, ...(jobLine.guardrail ? { rule: jobLine.guardrail } : {}) })) reds.push(r);
514
+ for (const r of sheetNoClaimReds(list, step.fromLine)) reds.push(r);
515
+ }
516
+ const tables = c.sheetWords?.tables;
517
+ if (!shapeOk || !tables || !Number.isInteger(step.fromLine)) return;
518
+ for (const r of sheetCheckReds(list, step.fromLine, tables)) reds.push(r);
519
+ }
520
+
472
521
  /**
473
522
  * Validate a drafter declaration against the M1 closed schema. `arbiter`
474
523
  * and `lines` are `parseSignedText`'s output; `catalogue` is a plain array
@@ -488,7 +537,8 @@ function checkColumnsKey(step, label, c, reds) {
488
537
  * `pageWords.docs` (M10 piece 5): the roles that are documents (.docx / .md / .txt): their words are proved on their text alone, with no page-word map.
489
538
  * `sheetWords` (optional; M10 am8 item 2): `{headers: {role: header names}, facts: the columns the sheet look kept}`. With `fitJobLine`, every column a step's `close.columns` names
490
539
  * is proved a real column of its sheet, and a column the code kept for the step's line (an agreed one included) must be in it.
491
- * @param {{ arbiter?: unknown, lines?: unknown, catalogue?: unknown, wired?: Set<string>, verbatimGoals?: boolean, fitJobLine?: boolean, pageWords?: {texts: Record<string, string>, look: any, docs?: string[]}, sheetWords?: {headers: Record<string, string[]>, facts: any[]} }} [context]
540
+ * `sheetWords.tables` (optional; M10b piece 1): `{role: bareguard table}` of the drafting copy. With it, every `close.sheet` check passes bareguard's sign-time test at $0.
541
+ * @param {{ arbiter?: unknown, lines?: unknown, catalogue?: unknown, wired?: Set<string>, verbatimGoals?: boolean, fitJobLine?: boolean, pageWords?: {texts: Record<string, string>, look: any, docs?: string[]}, sheetWords?: {headers: Record<string, string[]>, facts: any[], tables?: Record<string, {header: string[], rows: any[]}>} }} [context]
492
542
  * @returns {ValidateDeclarationResult}
493
543
  */
494
544
  export function validateDeclaration(declaration, context = {}) {
@@ -768,7 +818,8 @@ export function validateDeclaration(declaration, context = {}) {
768
818
  }
769
819
  }
770
820
  if (step.close.cited !== undefined) checkCitedKey(step, label, { sourceRoles, reads, effectiveClass, lines: safeLines, fitJobLine, pageWords }, reds);
771
- if (step.close.columns !== undefined || (fitJobLine === true && sheetWords)) checkColumnsKey(step, label, { cellsRoles, reads, effectiveClass, sheetWords }, reds);
821
+ if (step.close.sheet !== undefined) checkSheetKey(step, label, { cellsRoles, reads, effectiveClass, lines: safeLines, fitJobLine, sheetWords }, reds);
822
+ if (step.close.columns !== undefined || (fitJobLine === true && sheetWords)) checkColumnsKey(step, label, { cellsRoles, reads, effectiveClass, lines: safeLines, sheetWords }, reds);
772
823
  }
773
824
  }
774
825
 
@@ -788,6 +839,13 @@ export function validateDeclaration(declaration, context = {}) {
788
839
  reds.push(`declaration: Line ${n}'s check needs cells, but ${reading}. Line ${n} must read ${want}.`);
789
840
  }
790
841
 
842
+ // M10b piece 5 (item 8): the old cell cite retires for CSV. A green step that reads a spreadsheet answers in bareguard's claim boxes (`close.sheet`);
843
+ // one with neither `close.sheet` nor `close.cited` would be the old cite close, which a new plan no longer offers. Signed flows keep running (fitJobLine only).
844
+ if (fitJobLine === true && effectiveClass === 'green' && reads !== null && reads.some((r) => cellsRoles.includes(r))
845
+ && !isPlainObject(step.close?.cited) && !Array.isArray(step.close?.sheet)) {
846
+ reds.push(`declaration: Line ${fromLine}'s check cannot cite cells any more. Line ${fromLine} must carry close.sheet: bareguard's checks of ${reads.filter((r) => cellsRoles.includes(r)).join(' or ')}.`);
847
+ }
848
+
791
849
  // M4d amendment 9: an ask step shows you something: its FIRST read must be the output of an earlier step. A read is not a
792
850
  // grant (the ask stays a pure stop); the check is for the plan checker only (fitJobLine), so signed flows still run.
793
851
  if (fitJobLine === true && reads !== null && fromLine !== null && askLines.includes(fromLine)