fwdloop 0.31.0 → 0.33.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 (96) hide show
  1. package/bin/fwdloop +8 -2
  2. package/package.json +2 -2
  3. package/src/auditchecks.js +53 -0
  4. package/src/authoring.js +52 -12
  5. package/src/blockasks.js +44 -0
  6. package/src/blockassemble.js +140 -0
  7. package/src/blockdraft.js +91 -0
  8. package/src/blocklines.js +30 -0
  9. package/src/blockpick.js +165 -0
  10. package/src/cardlist.js +19 -0
  11. package/src/checkblock.js +804 -0
  12. package/src/checked.js +48 -9
  13. package/src/checklist.js +99 -0
  14. package/src/checklistsign.js +93 -0
  15. package/src/checkwords.js +20 -1
  16. package/src/cited-record.js +21 -1
  17. package/src/citedcheck.js +162 -7
  18. package/src/closers.js +41 -3
  19. package/src/declaration.js +25 -2
  20. package/src/declaredclose.js +4 -0
  21. package/src/draft-steps.js +3 -1
  22. package/src/drafter.js +244 -134
  23. package/src/factwords.js +112 -0
  24. package/src/inputlook.js +53 -0
  25. package/src/jsonbrace.js +21 -0
  26. package/src/labelscan.js +162 -0
  27. package/src/pageask.js +4 -1
  28. package/src/pagedropwords.js +11 -1
  29. package/src/panel/author.js +76 -5
  30. package/src/panel/authorcard.js +9 -6
  31. package/src/panel/data.js +41 -9
  32. package/src/panel/index.html +202 -13
  33. package/src/panel/result.js +4 -3
  34. package/src/panel/server.js +3 -1
  35. package/src/pickrecord.js +28 -0
  36. package/src/placerule.js +398 -0
  37. package/src/planrebuild.js +206 -0
  38. package/src/rowedit.js +118 -0
  39. package/src/rubricstep.js +264 -0
  40. package/src/runfile.js +4 -2
  41. package/src/runner.js +67 -10
  42. package/src/setup.js +10 -4
  43. package/src/sheetblock.js +6 -2
  44. package/src/sheetchecks.js +49 -64
  45. package/src/sheetclaims.js +12 -32
  46. package/src/sheetlook.js +2 -2
  47. package/src/sheetoffer.js +25 -53
  48. package/src/sheetrows.js +107 -0
  49. package/src/sheetrun.js +31 -1
  50. package/src/summary-words.js +3 -3
  51. package/src/try-checks.js +31 -12
  52. package/src/types.js +1 -0
  53. package/types/auditchecks.d.ts +24 -0
  54. package/types/authoring.d.ts +18 -1
  55. package/types/blockasks.d.ts +37 -0
  56. package/types/blockassemble.d.ts +33 -0
  57. package/types/blockdraft.d.ts +83 -0
  58. package/types/blocklines.d.ts +31 -0
  59. package/types/blockpick.d.ts +41 -0
  60. package/types/cardlist.d.ts +21 -0
  61. package/types/checkblock.d.ts +363 -0
  62. package/types/checked.d.ts +16 -2
  63. package/types/checklist.d.ts +115 -0
  64. package/types/checklistsign.d.ts +27 -0
  65. package/types/checkwords.d.ts +5 -0
  66. package/types/cited-record.d.ts +9 -0
  67. package/types/citedcheck.d.ts +33 -2
  68. package/types/closers.d.ts +24 -2
  69. package/types/declaredclose.d.ts +2 -0
  70. package/types/drafter.d.ts +15 -361
  71. package/types/factwords.d.ts +38 -0
  72. package/types/inputlook.d.ts +49 -0
  73. package/types/jsonbrace.d.ts +8 -0
  74. package/types/labelscan.d.ts +35 -0
  75. package/types/pageask.d.ts +2 -0
  76. package/types/panel/author.d.ts +41 -0
  77. package/types/panel/authorcard.d.ts +1 -1
  78. package/types/panel/data.d.ts +4 -2
  79. package/types/panel/jobgrid.d.ts +1 -1
  80. package/types/pickrecord.d.ts +22 -0
  81. package/types/placerule.d.ts +208 -0
  82. package/types/planrebuild.d.ts +52 -0
  83. package/types/provider.d.ts +1 -1
  84. package/types/rowedit.d.ts +33 -0
  85. package/types/rubricstep.d.ts +60 -0
  86. package/types/runfile.d.ts +5 -2
  87. package/types/runner.d.ts +45 -1
  88. package/types/sheetblock.d.ts +1 -0
  89. package/types/sheetchecks.d.ts +10 -17
  90. package/types/sheetclaims.d.ts +2 -1
  91. package/types/sheetoffer.d.ts +5 -5
  92. package/types/sheetrows.d.ts +73 -0
  93. package/types/sheetrun.d.ts +12 -0
  94. package/types/summary-words.d.ts +2 -1
  95. package/types/try-checks.d.ts +4 -2
  96. package/types/types.d.ts +8 -0
package/src/setup.js CHANGED
@@ -56,7 +56,8 @@ function planRow(sessionDir, rel, kind, n) {
56
56
  structureRetries: Number.isInteger(log?.structureRetries) ? log.structureRetries : null,
57
57
  verdict, hash, gap,
58
58
  // M4d am15: every try of this plan (label, passed, the checker's raw refusals, the round's words), for the Audit Draft group; only when a retry happened
59
- ...(Array.isArray(log?.log) && log.log.length > 1 ? { tries: triesOf(log.log) } : {}),
59
+ // M16: tries are the declaration rounds only (triesOf), so the list's own turns do not make a one-try draft look retried
60
+ ...(Array.isArray(log?.log) && triesOf(log.log).length > 1 ? { tries: triesOf(log.log) } : {}),
60
61
  };
61
62
  }
62
63
 
@@ -111,8 +112,11 @@ export function buildSetupRows({
111
112
  const card = readJson(sessionDir, `card-${n}.json`);
112
113
  if (card) rows.push({ kind: 'card', n, at: mtimeIso(sessionDir, `card-${n}.json`), card });
113
114
  // M4e amendment 24 item 4: a plan drafted again after the human's answers is booked as `redraft`, not `revise` (it uses none of the 2 revises)
114
- rows.push(planRow(sessionDir, `draft-${n}`, readJson(sessionDir, `redraft-${n}.json`) ? 'redraft' : 'revise', n));
115
- rows.push(...humanRows(sessionDir, `draft-${n}`));
115
+ // M16 item 5: a plan made by a Drop or an Add of the person is booked as that, not as a redraft; it asked nothing, and what it kept is the earlier plan's row, not its own
116
+ const marker = readJson(sessionDir, `redraft-${n}.json`);
117
+ const rowEdit = marker && marker.rowEdit && typeof marker.rowEdit === 'object' ? marker.rowEdit : null;
118
+ rows.push({ ...planRow(sessionDir, `draft-${n}`, rowEdit ? 'rowedit' : marker ? 'redraft' : 'revise', n), ...(rowEdit ? { op: rowEdit.op, key: rowEdit.key } : {}) });
119
+ if (!rowEdit) rows.push(...humanRows(sessionDir, `draft-${n}`));
116
120
  }
117
121
  } else {
118
122
  const r = planRow(planDir, '.', 'draft', 0);
@@ -120,7 +124,9 @@ export function buildSetupRows({
120
124
  }
121
125
  // M4e amendment 36: the drafter's own "Not checked" list (the green plan folder's not-checked.json), kept word for word with its label. Not signed,
122
126
  // not in any hash. An unreadable or missing file is an empty list (a plan from before amendment 25 has none).
123
- const notChecked = notCheckedBlock(readJson(planDir, 'not-checked.json')?.notChecked);
127
+ const ncFile = readJson(planDir, 'not-checked.json');
128
+ // M16 item 5: the tag of each line that tells a list row rides the sign row (the Audit's Checks fold draws it); a plan with no list has none
129
+ const notChecked = { ...notCheckedBlock(ncFile?.notChecked), ...(ncFile?.by && typeof ncFile.by === 'object' && !Array.isArray(ncFile.by) ? { by: ncFile.by } : {}) };
124
130
  rows.push({
125
131
  kind: 'sign', n: 0, at: signedAt, signedBy, hash, flowHash: flowHash ?? null, notChecked,
126
132
  });
package/src/sheetblock.js CHANGED
@@ -7,7 +7,7 @@
7
7
  // A green "found" is the step's OWN claimed value in plain words (a number, or a count of rows / days / bands / groups); a string claim (a looked-up cell) is never
8
8
  // repeated, because it is cell text. A red "found" is bareguard's gap words (row numbers and counts), never a cell's text.
9
9
  // Third outcomes, named: a line the run never reached (no record) carries no verdict; a check the record lacks carries none (the page shows no mark).
10
- import { labelled } from './checkwords.js';
10
+ import { labelled, tagged, sheetByOf } from './checkwords.js';
11
11
  import { isDeepStrictEqual } from 'node:util';
12
12
  import { rubricVocabulary } from 'bareguard';
13
13
  import { lineRules } from './pagebits.js';
@@ -59,6 +59,9 @@ export function sheetFoundWords(check, claims) {
59
59
  /** @param {any} l a job line `{rules?, guardrail?, rule?}` @returns {string[]} its `~` rules, numbered from 1 by position */
60
60
  export const rulesOfLine = (l) => lineRules({ ...(Array.isArray(l?.rules) ? { rules: l.rules } : {}), rule: l?.guardrail ?? l?.rule });
61
61
 
62
+ /** M16 am4: the words of one sheet check without its tag - the ONE composition (the block's `text` and the list row both use it) @param {string} name @param {string} words @param {string} cw @returns {string} */
63
+ export const sheetPlainText = (name, words, cw) => [name, ...(words === name ? [] : [words]), ...(cw ? [cw] : [])].join(' \u2014 ');
64
+
62
65
  /** the "covers ..." words of one check @param {string[]} rules @returns {string} "" when it covers none */
63
66
  export const coversWords = (rules) => rules.map((r) => `covers "${r}"`).join(' · ');
64
67
 
@@ -73,6 +76,7 @@ export function sheetLineBlocks({ declaration, lines, csvRoles = [], record }) {
73
76
  const out = [];
74
77
  if (!isRec(declaration) || !Array.isArray(declaration.steps)) return out;
75
78
  const seen = new Set();
79
+ const onList = Array.isArray(declaration.checkList) && declaration.checkList.some((/** @type {any} */ r) => isRec(r) && r.kind === 'sheet');
76
80
  for (const st of declaration.steps) {
77
81
  if (!isRec(st) || !isRec(st.close) || st.close.class !== 'green' || !Number.isInteger(st.fromLine) || seen.has(st.fromLine)) continue;
78
82
  const hasSheet = Array.isArray(st.close.sheet) && st.close.sheet.length > 0;
@@ -91,7 +95,7 @@ export function sheetLineBlocks({ declaration, lines, csvRoles = [], record }) {
91
95
  const words = sheetCheckSentence(c);
92
96
  const cw = coversWords(rules);
93
97
  /** @type {any} */
94
- const e = { id: typeof c.id === 'string' ? c.id : '', name, words, covers: rules, coversWords: cw, text: labelled([name, ...(words === name ? [] : [words]), ...(cw ? [cw] : [])].join(' — '), 'agent') }; // M10 am22 (4): the AI wrote every sheet check
98
+ const e = { id: typeof c.id === 'string' ? c.id : '', name, words, covers: rules, coversWords: cw, text: onList ? tagged(sheetPlainText(name, words, cw), sheetByOf(rules)) : labelled(sheetPlainText(name, words, cw), 'agent') }; // hamr 2026-11-14: a plan whose list has sheet rows tags a check by where it comes from; an older plan keeps M10 am22 (4)'s `[agent]`
95
99
  const res = newest && Array.isArray(newest.results) ? newest.results.find((/** @type {any} */ r) => isRec(r) && r.id === c.id) : undefined;
96
100
  if (isRec(res) && typeof res.ok === 'boolean') {
97
101
  e.ok = res.ok;
@@ -1,16 +1,15 @@
1
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
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
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;
4
+ // - `sheetCheckColumns` every column name a check holds, read from bareguard's vocabulary (`columnAt` on each field; the code proves each is an exact header of the sheet);
5
+ // - `sheetCheckReds` the $0 sign-time test: bareguard's `checkTables` judges the checks over the drafting copy's tables, and each problem it returns comes back
6
+ // as a red naming the job line, in fwdloop's words;
7
7
  // - `sheetCheckSentence` the plain words of one check, written from its typed fields, for the plan card and the readout.
8
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
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
10
  // a repeated header), a role with no drafting copy, a refusal by `createRubric`.
11
11
 
12
- import { createRubric, tableSha } from 'bareguard';
13
- import { numbersSaid } from './citedwords.js';
12
+ import { checkTables, tableSha, groundedLiterals, rubricVocabulary } from 'bareguard';
14
13
  import { wordsSaidOn, lineRules } from './pagebits.js';
15
14
 
16
15
  /** the bareguard rules a sheet check may use (`diff` is out of scope for M10b) */
@@ -20,26 +19,22 @@ export const MAX_SHEET_CHECKS = 20;
20
19
 
21
20
  const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
22
21
 
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']);
22
+ const V = /** @type {any} */ (rubricVocabulary);
31
23
 
32
24
  /**
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.
25
+ * Every column name one check holds, read from bareguard's own vocabulary: each field of the check's rule that carries `columnAt` ("self": a name; "self.column": a cell
26
+ * `{column, row}`; "each.column": a list of `{column}`; "each": a list of names). A row-math `b` of `{const}` is no column. bareguard owns which fields these are.
35
27
  * @param {any} check @returns {string[]}
36
28
  */
37
29
  export function sheetCheckColumns(check) {
38
30
  if (!isRec(check)) return [];
39
31
  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);
32
+ for (const [k, f] of Object.entries(V.rules[check.rule]?.fields ?? {})) {
33
+ const at = /** @type {any} */ (f).columnAt;
34
+ const v = check[k];
35
+ if (!at || v === undefined) continue;
36
+ if (at === 'self') { if (typeof v === 'string') out.push(v); } else if (at === 'self.column') { if (isRec(v) && typeof v.column === 'string') out.push(v.column); } else if (Array.isArray(v)) for (const e of v) { if (at === 'each.column' ? isRec(e) && typeof e.column === 'string' : typeof e === 'string') out.push(at === 'each.column' ? e.column : e); }
37
+ }
43
38
  return out;
44
39
  }
45
40
 
@@ -124,73 +119,63 @@ export function sheetCheckRows(sheet) {
124
119
  }
125
120
 
126
121
  /**
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.
122
+ * The $0 sign-time test of one step's sheet checks (M10b item 4): bareguard's `checkTables` is given the checks and the signed fingerprint of each sheet they read
123
+ * (`tableSha` of the drafting copy's table) and returns every problem; each becomes a red that names the job line (and the check) in fwdloop's words. A sheet with no
124
+ * saved copy, a sheet bareguard cannot read as a table, or a column that is no header of its sheet is reported first; a check bareguard refuses only when none of those is.
125
+ * Never throws.
130
126
  * @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
127
  * @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
128
  */
133
129
  export function sheetCheckReds(checks, line, tables) {
134
- const reds = [];
135
130
  const at = `declaration: line ${line}:`;
136
- /** @type {Map<string, string|null>} */
131
+ /** @type {Map<string, string>} */
137
132
  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.`);
133
+ for (const c of checks) if (isRec(c) && typeof c.table === 'string' && !shas.has(c.table)) shas.set(c.table, (tables[c.table] ? tableSha(tables[c.table]) : null) ?? '0'.repeat(64));
134
+ const inputs = [...shas].map(([name, sha256]) => ({ name, sha256 }));
135
+ const problems = checkTables({ schema: 1, goal: `line ${line}`, inputs, checkpoints: { sheet: { gating: true, checks: bareguardChecks(checks) } }, maxReds: 3 }, tables);
136
+ const reds = [];
137
+ const seen = new Set();
138
+ /** @param {string} name @param {string} table */
139
+ const columnRed = (name, table) => `${at} '${name}' is not a real column of "${table}" (its columns: ${tables[table].header.map((h) => `'${h}'`).join(', ')}). Copy a column name exactly.`;
140
+ for (const p of problems) {
141
+ const key = `${p.kind}\u0000${p.table}`;
142
+ if (p.kind === 'no-table' && !seen.has(key)) reds.push(`${at} the sheet check reads "${p.table}", which has no saved copy to test against`);
143
+ else if (p.kind === 'unreadable-table' && !seen.has(key)) reds.push(`${at} bareguard cannot read "${p.table}" as a table (a row with more or fewer cells than the header, or a repeated column name); fix the sheet`);
144
+ else if (p.kind === 'not-a-column') reds.push(columnRed(String(p.column), String(p.table)));
145
+ else if (p.kind === 'refused' && typeof p.index === 'number' && isRec(checks[p.index]) && tables[checks[p.index].table]) {
146
+ // bareguard names no column of a check it refuses; the person is told the wrong column first, as before
147
+ for (const name of sheetCheckColumns(checks[p.index])) if (!tables[checks[p.index].table].header.includes(name)) reds.push(columnRed(name, checks[p.index].table));
150
148
  }
149
+ seen.add(key);
151
150
  }
152
151
  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}`);
152
+ const refused = problems.find((p) => p.kind === 'refused' || p.kind === 'sha-mismatch');
153
+ if (refused) {
154
+ const msg = String(refused.message ?? refused.kind).replace(/^invalid rubric: /, '');
155
+ reds.push(`${at} bareguard refuses the sheet check${typeof refused.id === 'string' ? ` '${refused.id}'` : ''}: ${msg}`);
161
156
  }
162
157
  return reds;
163
158
  }
164
159
 
165
- const NUMBER_CMPS = Object.freeze(['gt', 'gte', 'lt', 'lte', 'eq', 'between']);
166
- const DATE_CMPS = Object.freeze(['before', 'after', 'dateOn', 'dateBetween']);
167
-
168
160
  /**
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).
161
+ * M10b piece 3: a number or a date in a check comes from the job, never from the model. bareguard's `groundedLiterals` judges every number and date the check carries
162
+ * against the person's words on the job line or its `~` rules (one string, `wordsSaidOn`); each literal it reports missing becomes a red in fwdloop's words. A literal of the
163
+ * wrong type or an unreadable condition is not "not in your words": `createRubric` refuses it (sheetCheckReds), so it is no red here.
164
+ * Throws away: a text value (`equals`, `needle`), band bounds, `n`, `tolerance`, `range` are not read (bareguard does not read them either).
173
165
  * @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
166
  */
175
167
  export function sheetCheckWordReds(checks, jobLine) {
176
- const said = numbersSaid(wordsSaidOn(jobLine));
168
+ const text = wordsSaidOn(jobLine);
177
169
  const reds = [];
178
170
  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
171
  for (const c of checks) {
187
172
  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);
173
+ const who = typeof c.id === 'string' ? ` '${c.id}'` : '';
174
+ for (const m of groundedLiterals(bareguardChecks([c])[0], text).missing) {
175
+ const w = /^where\[(\d+)\]/.exec(m.path);
176
+ const where = m.path === 'asOf' ? 'as of' : m.path === 'b.const' ? 'row math b' : w ? `where ${String(c.where[Number(w[1])].column)}` : m.path;
177
+ if (m.kind === 'number' && typeof m.value === 'number') reds.push(`declaration: line ${n}: the sheet check${who} has the number ${m.value} (${where}), but ${m.value} 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.`);
178
+ else if (m.kind === 'date' && typeof m.value === 'string') reds.push(`declaration: line ${n}: the sheet check${who} has the date ${m.value} (${where}), but ${m.value} 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.`);
194
179
  }
195
180
  }
196
181
  return reds;
@@ -1,33 +1,13 @@
1
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
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 schema of every box is
3
+ // bareguard's `claimSchema` of the check; the box the step is TOLD is 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
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
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';
6
+ import { rubricVocabulary, claimSchema } from 'bareguard';
7
+ import { bareguardChecks } from './sheetchecks.js';
7
8
 
8
9
  const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
9
10
 
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
11
  /**
32
12
  * 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
13
  * with example values). A check bareguard has no example for, and a `table` check, add nothing.
@@ -49,19 +29,19 @@ export function sheetClaims(checks) {
49
29
  }
50
30
 
51
31
  /**
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.)
32
+ * The `emit_artifact` tool's properties for a step that reads a sheet: one typed box per claim, each required, the box's schema bareguard's `claimSchema` of the check
33
+ * (two checks that share a claim name share one box: their keys merge). `covers` is fwdloop's own and is stripped before bareguard reads the check. (`done` is added by the caller.)
53
34
  * @param {any[]} checks @returns {{properties: Record<string, any>, required: string[]}}
54
35
  */
55
36
  export function sheetAnswerProps(checks) {
56
37
  /** @type {Record<string, any>} */
57
38
  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
- };
39
+ for (const c of Array.isArray(checks) ? checks : []) {
40
+ if (!isRec(c) || c.rule !== 'cells' || typeof c.claim !== 'string') continue;
41
+ const box = /** @type {any} */ (claimSchema(bareguardChecks([c])[0]));
42
+ if (box === null) continue;
43
+ const have = properties[c.claim];
44
+ properties[c.claim] = have === undefined ? box : { ...have, ...box, properties: { ...have.properties, ...box.properties }, required: [...new Set([...(have.required ?? []), ...(box.required ?? [])])] };
65
45
  }
66
46
  return { properties, required: Object.keys(properties) };
67
47
  }
package/src/sheetlook.js CHANGED
@@ -104,8 +104,8 @@ export function applySheetWords(text, words, jobLines, label) {
104
104
  if (w.kind !== 'number') { dropped.push({ ...rec, reason: 'no-column' }); continue; }
105
105
  if (found.kind === 'tie') { dropped.push({ ...rec, reason: 'column-tie', other: found.columns.map((c) => `"${c}"`).join(', ') }); continue; }
106
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; }
107
+ // the person already named this column in a 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) => countPhrase(r, found.column) > 0)) { facts.push(fact(found.column)); continue; }
109
109
  asks.push({
110
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
111
  });
package/src/sheetoffer.js CHANGED
@@ -1,5 +1,5 @@
1
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
2
+ // - `sheetChecksProp` the tool schema of `close.sheet`: bareguard's `checkSchema` (fields, ops, date formats), never hand-copied, plus fwdloop's own `covers`. Every field that
3
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
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
5
  // - `isColumnChoiceRule` the agreed-column rule, covered by the column lock.
@@ -7,80 +7,52 @@
7
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
8
  // THROWS at build time (a bareguard upgrade fails loud, it never silently drops a field).
9
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';
10
+ import { rubricVocabulary, checkSchema } from 'bareguard';
11
+ import { SHEET_RULES, MAX_SHEET_CHECKS } from './sheetchecks.js';
14
12
  import { columnRuleWords } from './sheetlook.js';
15
13
 
16
14
  const V = /** @type {any} */ (rubricVocabulary);
17
15
  const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
18
16
 
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']);
17
+ /** The comparisons of a `where` condition, as bareguard's vocabulary lists them. */
18
+ export const WHERE_CMPS = Object.freeze([...V.rules.cells.fields.where.cmps]);
21
19
 
22
20
  /** @param {Record<string, {header: string[]}>} tables @returns {string[]} the exact header strings of every sheet, once each, in order */
23
21
  const headerUnion = (tables) => [...new Set(Object.values(tables).flatMap((t) => t.header))];
24
22
 
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
- }
23
+ /** what the drafter is told about a field, in fwdloop's words where they steer a draft better than bareguard's */
24
+ const DRAFTER_WORDS = Object.freeze({
25
+ id: 'a short unique name for this check',
26
+ rule: 'cells: the step gives a value that bareguard recomputes; table: bareguard judges the sheet itself',
27
+ table: 'the role of the CSV input this check reads (also in the step\'s reads)',
28
+ claim: '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',
29
+ op: 'a cells op goes with rule "cells", a table op with rule "table" (listed in the system prompt)',
30
+ });
51
31
 
52
32
  /**
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.
33
+ * The tool schema of `close.sheet`: a list of bareguard cells / table checks. The check's schema is bareguard's `checkSchema` (every column-bearing field an enum of the sheet's
34
+ * exact header, `table` an enum of the roles, one `op` enum); fwdloop drops what a check must not carry (the free-text `explanation` fields: a check carries no prose), puts its
35
+ * own words on id / rule / table / claim / op, and adds `covers` (which `~` rules of the job line the check covers), kept and signed.
56
36
  * @param {Record<string, {header: string[]}>} tables the drafting copy's table of each CSV input role
57
37
  * @returns {Record<string, any>|null} null when there is no sheet with a header to pick from
58
38
  */
59
39
  export function sheetChecksProp(tables) {
60
40
  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 };
41
+ const schema = /** @type {any} */ (checkSchema({ rules: /** @type {('cells'|'table')[]} */ ([...SHEET_RULES]), columns: headerUnion(tables), tables: roles }));
42
+ if (roles.length === 0 || schema === null) return null;
64
43
  /** @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)' };
44
+ const props = { ...schema.properties };
45
+ for (const r of SHEET_RULES) for (const [k, f] of Object.entries(V.rules[r].fields)) if (/** @type {any} */ (f).type === 'explanation') delete props[k];
46
+ for (const [k, d] of Object.entries(DRAFTER_WORDS)) if (props[k]) props[k] = { ...props[k], description: d };
47
+ // the left operand `a` is offered the same two shapes as `b` (bareguard's own `b` schema; a `{const}` there is refused by createRubric, as before)
48
+ if (props.a && props.b?.anyOf) props.a = { ...props.b, description: props.a.description, anyOf: [props.a, props.b.anyOf[1]] };
77
49
  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
50
  return {
79
51
  type: 'array',
80
52
  minItems: 1,
81
53
  maxItems: MAX_SHEET_CHECKS,
82
54
  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 },
55
+ items: { type: 'object', properties: props, required: [...schema.required, 'covers'], additionalProperties: false },
84
56
  };
85
57
  }
86
58
 
@@ -111,7 +83,7 @@ export function sheetOfferRules(roles) {
111
83
  `- 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
84
  '- 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
85
  '- 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.',
86
+ '- 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 input sheet itself, so it must already hold on that sheet (one that fails on it is refused); to check what a step gives, use a cells check. 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
87
  '- "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
88
  ...sheetOpsBrief(),
117
89
  ];
@@ -0,0 +1,107 @@
1
+ // M16 am4 (docs/wiki/the-module-ladder.md, "M16 amendment 4" (2)): a sheet line's checks (`close.sheet`) are rows on the plan's list, beside every other check.
2
+ // The AI writes the sheet checks (M10b); code only READS them as rows: this file is the ONE writer of a sheet row, of its tag and of its card text, and of the Drop and Add of one.
3
+ // tag a check whose `covers` names one of the person's `~` rules is `[you]`; a check that covers none (the AI added it) is `[agent]`. (A `[default]` sheet check does not exist: no code adds one.)
4
+ // Drop only an `[agent]` row; the check leaves `close.sheet` and is kept in the picks record (`sheetDropped`) so Add can put it back. A `[you]` row has no Drop.
5
+ // Add puts a dropped check back at the place it had.
6
+ // Words are fwd's existing sheet-check words (src/sheetblock.js `sheetPlainText`); nothing here words a check. What this throws away: the check's fields (id, claim, range ...); a row keeps its line, tag, part and key.
7
+ import { sheetLineBlocks, sheetPlainText } from './sheetblock.js';
8
+ import { closePartsOf } from './checklistsign.js';
9
+ import { sheetByOf } from './checkwords.js';
10
+
11
+ const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
12
+
13
+ /** the key of a sheet row: the block's `L<line>.<tail>` shape, tail `sheet.<check id>` @param {number} line @param {string} id */
14
+ export const sheetRowKey = (line, id) => `L${line}.sheet.${id}`;
15
+ /** @param {unknown} key @returns {boolean} the key is a sheet row's */
16
+ export const isSheetKey = (key) => typeof key === 'string' && key.startsWith('L') && key.includes('.sheet.');
17
+
18
+ /**
19
+ * The sheet rows of a declaration, read from its steps' `close.sheet`: the signed rows (for `declaration.checkList`) and the card rows (words, tag, whether a Drop is offered).
20
+ * @param {{declaration: any, lines: any[], csvRoles: string[]}} o
21
+ * @returns {{signed: Record<string, any>[], card: {key: string, line: number, by: 'you'|'agent', state: 'built', text: string, reason: null, drop: boolean}[]}}
22
+ */
23
+ export function sheetRowsOf({ declaration, lines, csvRoles }) {
24
+ /** @type {Record<string, any>[]} */
25
+ const signed = [];
26
+ /** @type {any[]} */
27
+ const card = [];
28
+ const steps = isRec(declaration) && Array.isArray(declaration.steps) ? declaration.steps : [];
29
+ steps.forEach((st, i) => {
30
+ if (!isRec(st) || !isRec(st.close) || st.close.class !== 'green' || !Array.isArray(st.close.sheet) || st.close.sheet.length === 0 || !Number.isInteger(st.fromLine)) return;
31
+ // the parts the earlier steps of this line have, then this step's own (the fact, the picks, the tie) come before its sheet checks (src/checklistsign.js `closePartsOf`)
32
+ const before = steps.slice(0, i).filter((x) => isRec(x) && x.fromLine === st.fromLine).reduce((n, x) => n + closePartsOf(x, true).length, 0);
33
+ const own = closePartsOf({ ...st, close: { ...st.close, sheet: undefined } }).length;
34
+ const block = sheetLineBlocks({ declaration: { steps: [st] }, lines, csvRoles })[0];
35
+ if (!block) return;
36
+ block.checked.forEach((e, j) => {
37
+ const by = sheetByOf(e.covers);
38
+ const key = sheetRowKey(st.fromLine, e.id);
39
+ const nums = Array.isArray(st.close.sheet[j]?.covers) ? st.close.sheet[j].covers.filter((/** @type {unknown} */ x) => Number.isInteger(x) && /** @type {number} */ (x) >= 1 && /** @type {number} */ (x) <= block.guardrails.length) : [];
40
+ signed.push({
41
+ line: st.fromLine, key, from: by === 'you' ? 'rule' : 'agent', by, kind: 'sheet', state: 'built',
42
+ ...(by === 'you' ? { rule: Math.min(...nums) } : {}), part: { line: st.fromLine, part: before + own + j },
43
+ });
44
+ card.push({ key, line: st.fromLine, by, state: 'built', text: sheetPlainText(e.name, e.words, e.coversWords), reason: null, drop: by === 'agent' });
45
+ });
46
+ });
47
+ return { signed, card };
48
+ }
49
+
50
+ /**
51
+ * The plan's card with the sheet rows on it: the sheet rows after the block's rows, a dropped sheet check among the suggestions (Add), as the block's dropped suggestions are.
52
+ * @param {{rows: any[], suggested: any[]}} card the block's card (src/cardlist.js) @param {{card: any[]}} sheet `sheetRowsOf` @param {{key: string, line: number, text: string}[]} [dropped]
53
+ */
54
+ export function withSheetCard(card, sheet, dropped = []) {
55
+ return { ...card, rows: [...card.rows, ...sheet.card], suggested: [...card.suggested, ...dropped.map((d) => ({ key: d.key, line: d.line, text: d.text, dropped: true }))] };
56
+ }
57
+
58
+ /** the dropped sheet checks the picks record keeps: `{key, line, index, check, text}` @returns {any[]} */
59
+ export const droppedSheetOf = (/** @type {any} */ record) => (isRec(record) && Array.isArray(record.sheetDropped) ? record.sheetDropped.filter((d) => isRec(d) && typeof d.key === 'string' && isRec(d.check) && Number.isInteger(d.line)) : []);
60
+
61
+ /**
62
+ * The person's Drop or Add on a sheet row, applied to the declaration (a copy). Same words as the block's own refusals (src/checkblock.js `rowChoice`).
63
+ * @param {{declaration: any, lines: any[], csvRoles: string[], op: 'drop'|'add', key: string, dropped: any[]}} o
64
+ * @returns {{ok: true, declaration: any, dropped: any[]}|{ok: false, why: string}}
65
+ */
66
+ export function sheetChoice({ declaration, lines, csvRoles, op, key, dropped }) {
67
+ if (op === 'drop') {
68
+ const row = sheetRowsOf({ declaration, lines, csvRoles }).card.find((r) => r.key === key);
69
+ if (!row) return { ok: false, why: 'there is no such check on the list' };
70
+ if (row.by === 'you') return { ok: false, why: 'that check comes from a rule you wrote; edit the job to change it' };
71
+ let gone = null;
72
+ const steps = declaration.steps.map((/** @type {any} */ st) => {
73
+ if (gone !== null || !isRec(st) || st.fromLine !== row.line || !isRec(st.close) || !Array.isArray(st.close.sheet)) return st;
74
+ const index = st.close.sheet.findIndex((/** @type {any} */ c) => isRec(c) && sheetRowKey(row.line, String(c.id)) === key);
75
+ if (index === -1) return st;
76
+ gone = { key, line: row.line, index, check: st.close.sheet[index], text: row.text };
77
+ const sheet = st.close.sheet.filter((/** @type {unknown} */ _c, /** @type {number} */ k) => k !== index);
78
+ const { sheet: _s, ...close } = st.close;
79
+ return { ...st, close: sheet.length > 0 ? { ...close, sheet } : close };
80
+ });
81
+ if (gone === null) return { ok: false, why: 'there is no such check on the list' };
82
+ return { ok: true, declaration: { ...declaration, steps }, dropped: [...dropped.filter((d) => d.key !== key), gone] };
83
+ }
84
+ const was = dropped.find((d) => d.key === key);
85
+ if (!was) return { ok: false, why: 'only a suggested check can be added' };
86
+ let put = false;
87
+ const steps = declaration.steps.map((/** @type {any} */ st) => {
88
+ if (put || !isRec(st) || st.fromLine !== was.line || !isRec(st.close) || st.close.class !== 'green') return st;
89
+ put = true;
90
+ const sheet = Array.isArray(st.close.sheet) ? [...st.close.sheet] : [];
91
+ sheet.splice(Math.min(was.index, sheet.length), 0, was.check);
92
+ return { ...st, close: { ...st.close, sheet } };
93
+ });
94
+ if (!put) return { ok: false, why: 'only a suggested check can be added' };
95
+ return { ok: true, declaration: { ...declaration, steps }, dropped: dropped.filter((d) => d.key !== key) };
96
+ }
97
+
98
+ /**
99
+ * The list of a declaration with its sheet rows: the block's rows first, then the sheet rows. A declaration with no sheet check keeps the list exactly as it was.
100
+ * @param {{declaration: any, lines: any[], csvRoles: string[]}} o @returns {{declaration: any, sheet: ReturnType<typeof sheetRowsOf>}}
101
+ */
102
+ export function withSheetRows({ declaration, lines, csvRoles }) {
103
+ const { checkList: _old, ...rest } = declaration;
104
+ const base = Array.isArray(declaration.checkList) ? declaration.checkList.filter((/** @type {any} */ r) => !(isRec(r) && r.kind === 'sheet')) : [];
105
+ const sheet = sheetRowsOf({ declaration: rest, lines, csvRoles });
106
+ return { declaration: sheet.signed.length === 0 ? declaration : { ...declaration, checkList: [...base, ...sheet.signed] }, sheet };
107
+ }