fwdloop 0.33.0 → 0.34.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 (66) hide show
  1. package/bin/fwdloop +14 -2
  2. package/package.json +1 -1
  3. package/src/auditchecks.js +6 -4
  4. package/src/authoring.js +4 -3
  5. package/src/blockasks.js +3 -2
  6. package/src/blockassemble.js +40 -21
  7. package/src/blockdraft.js +8 -13
  8. package/src/blockpick.js +11 -1
  9. package/src/checkblock.js +95 -56
  10. package/src/checklist.js +1 -1
  11. package/src/checklistsign.js +1 -1
  12. package/src/checkpick.js +7 -73
  13. package/src/declaration.js +9 -7
  14. package/src/drafter.js +152 -130
  15. package/src/noteask.js +62 -0
  16. package/src/pageask.js +5 -68
  17. package/src/pagedry.js +27 -4
  18. package/src/pagerules.js +19 -3
  19. package/src/panel/author.js +3 -3
  20. package/src/panel/authorcard.js +34 -11
  21. package/src/panel/index.html +7 -1
  22. package/src/pickrecord.js +42 -54
  23. package/src/planrebuild.js +16 -6
  24. package/src/rowedit.js +35 -5
  25. package/src/rubricstep.js +9 -1
  26. package/src/setup.js +1 -1
  27. package/src/sheetblock.js +17 -7
  28. package/src/sheetbuild.js +151 -0
  29. package/src/sheetchecks.js +3 -2
  30. package/src/sheetfind.js +4 -4
  31. package/src/sheetlook.js +14 -3
  32. package/src/sheetoffer.js +50 -5
  33. package/src/sheetrows.js +18 -2
  34. package/src/ticket-draft.js +4 -21
  35. package/src/ticketrows.js +100 -0
  36. package/types/auditchecks.d.ts +2 -1
  37. package/types/authoring.d.ts +4 -2
  38. package/types/blockasks.d.ts +1 -2
  39. package/types/blockassemble.d.ts +20 -3
  40. package/types/blockdraft.d.ts +4 -12
  41. package/types/blockpick.d.ts +5 -0
  42. package/types/checkblock.d.ts +32 -17
  43. package/types/checklist.d.ts +3 -3
  44. package/types/checkpick.d.ts +4 -34
  45. package/types/declaration.d.ts +7 -0
  46. package/types/drafter.d.ts +15 -355
  47. package/types/noteask.d.ts +52 -0
  48. package/types/pageask.d.ts +0 -35
  49. package/types/pagedry.d.ts +13 -0
  50. package/types/pagerules.d.ts +7 -0
  51. package/types/panel/authorcard.d.ts +13 -8
  52. package/types/panel/authorflows.d.ts +4 -4
  53. package/types/panel/data.d.ts +1 -1
  54. package/types/pickrecord.d.ts +47 -13
  55. package/types/rowedit.d.ts +16 -1
  56. package/types/rubricstep.d.ts +3 -0
  57. package/types/sheetblock.d.ts +11 -4
  58. package/types/sheetbuild.d.ts +84 -0
  59. package/types/sheetchecks.d.ts +2 -1
  60. package/types/sheetfind.d.ts +2 -2
  61. package/types/sheetoffer.d.ts +26 -1
  62. package/types/sheetrows.d.ts +8 -0
  63. package/types/ticket-draft.d.ts +3 -49
  64. package/types/ticketrows.d.ts +61 -0
  65. package/src/repairs.js +0 -38
  66. package/types/repairs.d.ts +0 -13
@@ -14,10 +14,12 @@ import { setUpBlock, ticketLeaveOut, pickEdits, ledgerEdits } from './blockdraft
14
14
  import { assembleFromBlock } from './blockassemble.js';
15
15
  import { cardOfBlock } from './cardlist.js';
16
16
  import { editsOf } from './rowedit.js';
17
+ import { NOTE_KIND } from './noteask.js';
17
18
  import { offerRules, rowsFromAnswer, codeScope } from './checkpick.js';
18
19
  import { matchRecord, readRowChoices, RECORD_FILE } from './pickrecord.js';
19
20
  import { listLinesOf, cardLinesOf } from './checklistsign.js';
20
21
  import { csvRolesOf } from './sheetblock.js';
22
+ import { withTicketRows } from './ticketrows.js';
21
23
  import { isSheetKey, sheetChoice, withSheetRows, withSheetCard, droppedSheetOf } from './sheetrows.js';
22
24
  import { validateDeclaration } from './declaration.js';
23
25
  import { loadCatalogue } from './catalogue.js';
@@ -84,11 +86,13 @@ export function rebuildBlock({ planDir, asks }) {
84
86
  texts, jobLines: plan.jobLines, look,
85
87
  kept: { picks: matched.picks.filter(inBlock).filter(isKept), left: matched.left.filter(inBlock).filter(isKept), askRules: matched.askRules.filter(inBlock) },
86
88
  fresh: { picks: matched.picks.filter(inBlock).filter((x) => !isKept(x)), left: leftFresh },
87
- asks, countScope: (t) => codeScope(parsed.arbiter.sources, t) === 'in', scoped: allShape.filter(inBlock), leaveOut: ticketLeaveOut(declaration.flowType, plan.jobLines, look.facts),
89
+ asks, countScope: (t) => codeScope(parsed.arbiter.sources, t) === 'in', leaveOut: ticketLeaveOut(declaration.flowType, plan.jobLines),
88
90
  });
89
91
  // the AI's replies, in the order the draft took them (log.json keeps each reply as sent)
90
92
  const askRules = allShape.filter((r) => !isKept(r));
91
93
  for (const e of Array.isArray(log?.log) ? log.log : []) {
94
+ // the note question's answers ride its entry, a failed turn's too (a `failed` answer is a Not checked row, so it must replay)
95
+ if (isRec(e) && e.kind === NOTE_KIND) { block.setNotes(notesOfEntry(e)); continue; }
92
96
  if (!isRec(e) || e.outcome !== 'answered' || !isRec(e.args)) continue;
93
97
  if (e.kind === 'check-suggest') block.applyDelta({ label: 'pre:check-suggest', pre: true, edits: pickEdits(rowsFromAnswer(askRules, e.args), blockLineNums) });
94
98
  else if (e.kind === 'ledger-suggest') block.applyDelta({ label: 'pre:ledger-suggest', pre: true, edits: ledgerEdits(e.args.extra) });
@@ -106,7 +110,7 @@ export function rebuildBlock({ planDir, asks }) {
106
110
  /**
107
111
  * The checks of a rebuilt block put back into the saved plan's declaration (the same assembly the draft used), re-proved by the validator.
108
112
  * @param {any} b @param {any} [from] the declaration to assemble over (a sheet Drop or Add changes its `close.sheet`); the saved one by default
109
- * @returns {{ok: true, declaration: any, notChecked: string[], notCheckedBy: Record<string, string>, sheet: ReturnType<typeof withSheetRows>['sheet']}|{ok: false, say: string}}
113
+ * @returns {{ok: true, declaration: any, notChecked: string[], notCheckedBy: Record<string, string>, sheet: ReturnType<typeof withSheetRows>['sheet'], tickets: ReturnType<typeof withTicketRows>['tickets']}|{ok: false, say: string}}
110
114
  */
111
115
  function assembleAgain(b, from = b.declaration) {
112
116
  const { checkList: _c, pickedLines: _p, ...saved } = from;
@@ -116,10 +120,13 @@ function assembleAgain(b, from = b.declaration) {
116
120
  const src = b.lineSet.has(st?.fromLine) && isRec(st.close) && isRec(st.close.cited) ? st.close.cited.source : undefined;
117
121
  return typeof src === 'string' && docs.has(src) && Array.isArray(st.reads) ? { ...st, reads: st.reads.filter((/** @type {string} */ r) => r !== src) } : st;
118
122
  }) };
119
- const built = assembleFromBlock({ declaration: rest, block: b.block, lines: b.lines, lineSet: b.lineSet });
123
+ const built = assembleFromBlock({ declaration: rest, block: b.block, lines: b.lines, lineSet: b.lineSet, askLines: new Set(b.parsed.arbiter.asks.map((/** @type {any} */ a) => a.line)) });
120
124
  // M16 am4: the sheet checks are rows on the list too, read from the steps the same way the draft read them
121
125
  const withSheet = withSheetRows({ declaration: built.declaration, lines: b.lines, csvRoles: csvRolesOf(b.parsed.arbiter) });
122
- const a = { ...built, declaration: withSheet.declaration };
126
+ // M17 am6: the Tickets filter and watch are rows on the list too, read from the declaration's fields the same way the draft read them
127
+ const withTickets = withTicketRows({ declaration: withSheet.declaration, lines: b.lines });
128
+ const ticketLines = withTickets.tickets.notChecked.map((t) => `not checked · "${t.rule}" — ${t.reason}`);
129
+ const a = { ...built, declaration: withTickets.declaration, notChecked: [...built.notChecked, ...ticketLines], notCheckedBy: { ...built.notCheckedBy, ...Object.fromEntries(ticketLines.map((t) => [t, 'you'])) } };
123
130
  const cat = loadCatalogue();
124
131
  if (!cat.ok) return { ok: false, say: 'The catalogue could not be read. Nothing was changed.' };
125
132
  const inPlan = new Set(b.block.rows.filter((r) => r.state === 'built').flatMap((r) => (r.factNames ?? []).map((/** @type {string} */ nm) => `${r.line}:${nm}`)));
@@ -130,9 +137,12 @@ function assembleAgain(b, from = b.declaration) {
130
137
  pageWords: { texts: b.texts, look: pageSources ? { facts: planFacts, dropped: b.look.dropped } : null, docs: docRolesOf(b.parsed.arbiter.sources) },
131
138
  });
132
139
  if (!verdict.ok) return { ok: false, say: `The changed list did not pass the plan's checks (${String(verdict.reds[0])}). Nothing was changed.` };
133
- return { ok: true, declaration: a.declaration, notChecked: a.notChecked, notCheckedBy: a.notCheckedBy, sheet: withSheet.sheet };
140
+ return { ok: true, declaration: a.declaration, notChecked: a.notChecked, notCheckedBy: a.notCheckedBy, sheet: withSheet.sheet, tickets: withTickets.tickets };
134
141
  }
135
142
 
143
+ /** the answers a note-question entry of the draft's log recorded; only well-formed ones (a line, yes|no|failed) @param {any} e @returns {{line: number, answer: 'yes'|'no'|'failed'}[]} */
144
+ const notesOfEntry = (e) => (Array.isArray(e.notes) ? e.notes.filter((/** @type {any} */ a) => isRec(a) && Number.isInteger(a.line) && (a.answer === 'yes' || a.answer === 'no' || a.answer === 'failed')) : []);
145
+
136
146
  /** the plan's list and the closes it checks, as one comparable string (the proof that the rebuild is the saved plan) @param {any} d */
137
147
  const fingerprint = (d) => JSON.stringify([d.checkList ?? null, (d.steps ?? []).map((/** @type {any} */ s) => [s?.fromLine, s?.close])]);
138
148
 
@@ -199,7 +209,7 @@ export function rowEditPlan({ planDir, op, key, asks = true }) {
199
209
  'readout.txt': readoutText,
200
210
  [NOT_CHECKED_FILE]: dj({ notChecked, ...(Object.keys(by).length ? { by } : {}) }),
201
211
  [RECORD_FILE]: dj({ ...record, rowChoices: b.block.choicesRecord(), ...(droppedNow.length ? { sheetDropped: droppedNow } : {}) }),
202
- 'log.json': dj({ ...(isRec(b.log) ? b.log : {}), log: [...(Array.isArray(b.log?.log) ? b.log.log : []), logRow], checkCard: withSheetCard(cardOfBlock(b.block), after.sheet, droppedNow) }),
212
+ 'log.json': dj({ ...(isRec(b.log) ? b.log : {}), log: [...(Array.isArray(b.log?.log) ? b.log.log : []), logRow], checkCard: (() => { const c = withSheetCard(cardOfBlock(b.block), after.sheet, droppedNow); return after.tickets.card.length ? withSheetCard(c, { card: after.tickets.card }) : c; })() }),
203
213
  'spec.hash': `${h.hash}\n`,
204
214
  },
205
215
  };
package/src/rowedit.js CHANGED
@@ -12,6 +12,34 @@ import { rubricVocabulary } from 'bareguard';
12
12
  // borrowed-from: bareloop src/ticketfilter.js@v0.56.0 (3383cce) (TICKET_FILTER_SCHEMA_WORDS only: the one sentence; fwd's own ticketFilter schema, src/ticket-draft.js, words it another way)
13
13
  export const TICKET_FILTER_SCHEMA_WORDS = 'REQUIRED when a job line names a priority or a label (leave it out only when none does). The person signs it; code decides at run start. Listing the line under "refused" does not filter anything: only this key does';
14
14
 
15
+ // borrowed-from: bareloop src/ticketfilter.js@v0.57.0 (c18df406) (TICKET_FILTER_EXAMPLE, ticketPerRunFacts, TICKET_READ_FACT, ticketFilterBlock: verbatim)
16
+ /** a legal filter, as the drafter is shown it */
17
+ export const TICKET_FILTER_EXAMPLE = '{"priority": ["P1"], "labels": ["bug"]}';
18
+
19
+ /**
20
+ * The facts a person-facing turn must not ask about (R5 finding F285): the confirm turn asked "which ticket, and is it P1?" in 5 of 10 live drafts. ONE owner of these words;
21
+ * the confirm prompt and the drafting prompt both carry them, for a Tickets job only.
22
+ * @returns {string}
23
+ */
24
+ export function ticketPerRunFacts() {
25
+ return 'THIS JOB READS A TICKET. The ticket is picked per run (typed on the run card, later the newest new ticket) and is never known when the job is drafted, so NEVER ask the person which ticket it is, or what its priority or labels are. '
26
+ + 'A job line that names a priority or a label (for example "only priority P1 tickets") is decided by code at run start from the ticket\'s own labels, through the job\'s ticketFilter: it is not a question for the person and not something you can check, so do not turn it into a question.';
27
+ }
28
+
29
+
30
+ export const TICKET_READ_FACT = 'A step that reads the ticket input still lists "read" in its tools: the ticket is already frozen at run start, but reading it is a grant, so a step without "read" cannot see it.';
31
+
32
+ /**
33
+ * What the drafter is told when the job reads tickets (appended to the authoring prompt only then; a plain job's prompt is untouched).
34
+ * Adapted from fwd's `ticketFactsLines` (v0.29.0): the same MUST, the same "never invent a label".
35
+ * @returns {string}
36
+ */
37
+ export function ticketFilterBlock() {
38
+ return `${ticketPerRunFacts()} ${TICKET_READ_FACT}\n\nTHE TICKET FILTER — this job reads one ticket per run. Code, not you, decides at run start whether a ticket runs or is skipped, from the ticket's labels and state; a closed ticket always skips.
39
+ When a job line (or its ~ rule) names a priority or a label (for example "only priority P1 tickets", "only tickets with priority P1 count", "only issues labelled bug"), you MUST add a top-level "ticketFilter" beside "stages": ${TICKET_FILTER_EXAMPLE}. "priority" is a list of values from P0 to P3, "labels" is a list of label names; each key is optional, and at least one is required. Never invent a label: use only the names the job lines give. Leave "ticketFilter" out entirely when no job line names a priority or a label.
40
+ The filter decides whether a run starts, not whether the work is good, so it is not a check. The job line that names the priority or label has no stage: list it under "refused" with the reason "decided by the ticket filter before the run starts" AND add the ticketFilter: the refused entry alone does not filter anything, only the ticketFilter does. A person reads and signs the filter; you never set the job's server or tools.`;
41
+ }
42
+
15
43
  /** the tool a row-edit reply is delivered through */
16
44
  export const ROW_EDIT_TOOL = 'submit_edits';
17
45
  /** what an acknowledged reply returns (the loop ends the call the moment the tool fires) */
@@ -77,8 +105,8 @@ export function rowEditUserText({ jobLines, look, texts }) {
77
105
  return out.join('\n');
78
106
  }
79
107
 
80
- /** @param {boolean} ticket @returns {Record<string, any>} the tool's schema: the edits list (each edit judged by code, so an item is any object), and for a Tickets job the optional ticketFilter */
81
- const rowEditSchema = (ticket) => ({
108
+ /** @param {boolean} ticket @param {Record<string, any>|null} [sheetChecks] M17 am2: with a CSV input, the optional `sheetChecks` suggestions (src/sheetoffer.js `sheetSuggestProp`) @returns {Record<string, any>} the tool's schema: the edits list (each edit judged by code, so an item is any object), and for a Tickets job the optional ticketFilter */
109
+ const rowEditSchema = (ticket, sheetChecks = null) => ({
82
110
  type: 'object',
83
111
  properties: {
84
112
  edits: { type: 'array', items: { type: 'object', properties: { op: { enum: ['add', 'reading', 'pick', 'not-checkable'] } }, required: ['op'] }, description: 'row edits; each is judged on its own' },
@@ -92,21 +120,23 @@ const rowEditSchema = (ticket) => ({
92
120
  additionalProperties: false,
93
121
  description: TICKET_FILTER_SCHEMA_WORDS,
94
122
  },
123
+ ticketWatch: { type: 'array', items: { type: 'string', enum: ['state', 'labels'] }, description: 'REQUIRED when a job line says to run a ticket again when its state or its labels change (the fields that change); leave it out otherwise. The person signs it; code runs the look' },
95
124
  } : {}),
125
+ ...(sheetChecks ? { sheetChecks } : {}),
96
126
  },
97
127
  required: ['edits'],
98
128
  additionalProperties: false,
99
129
  });
100
130
 
101
- /** @param {boolean} ticket the channel `askStructured` reads (src/authorflow.js) */
102
- export const rowEditChannel = (ticket = false) => ({
131
+ /** @param {boolean} ticket the channel `askStructured` reads (src/authorflow.js) @param {Record<string, any>|null} [sheetChecks] */
132
+ export const rowEditChannel = (ticket = false, sheetChecks = null) => ({
103
133
  name: ROW_EDIT_TOOL,
104
134
  instruction: `Your reply did not deliver exactly one ${ROW_EDIT_TOOL} call. Call ${ROW_EDIT_TOOL} exactly once, with the edits list as its arguments. Do not write the answer as text.`,
105
135
  textPath: 'edits',
106
136
  tool: (/** @type {{calls: any[]}} */ box) => ({
107
137
  name: ROW_EDIT_TOOL,
108
138
  description: 'Deliver your row edits (or an empty list). Call this exactly once.',
109
- parameters: rowEditSchema(ticket),
139
+ parameters: rowEditSchema(ticket, sheetChecks),
110
140
  execute: async (/** @type {any} */ args) => { box.calls.push(args); return ROW_EDIT_ACK; },
111
141
  }),
112
142
  });
package/src/rubricstep.js CHANGED
@@ -197,6 +197,10 @@ export function holdsManyBounds(shape, text) {
197
197
  return false;
198
198
  }
199
199
 
200
+ // borrowed-from: bareloop src/rubricstep.js@v0.57.0 (c18df406) (WHY_OTHER_CURRENCY, fd943e49)
201
+ /** the plain reason a rule's amount is in a currency the page fact does not use; `readLimit` gives it and the check list reads it, one spelling */
202
+ export const WHY_OTHER_CURRENCY = 'the amount is in another currency than the page fact';
203
+
200
204
  /**
201
205
  * The limit the person's own words give a fact of this shape: `{reading}` or `{why}` (a plain reason; the rule then stays Not checked).
202
206
  * @param {string} shape money or time @param {string} text the `~` rule's words @param {any} [fact] the look fact (its currency and unit lists must fit)
@@ -219,7 +223,7 @@ export function readLimit(shape, text, fact = {}) {
219
223
  if (/\b(?:not|never|outside|except|without)\b/i.test(t)) return { why: 'a negated limit (not, except, without) is not read' };
220
224
  const amts = [...t.matchAll(AMOUNT_ALL_RE)];
221
225
  if (!amts.length) return { why: 'no amount with a currency sign or word in the rule' };
222
- for (const a of amts) if (!currencyFits(a[0], fact)) return { why: 'the amount is in another currency than the page fact' };
226
+ for (const a of amts) if (!currencyFits(a[0], fact)) return { why: WHY_OTHER_CURRENCY };
223
227
  if (holdsManyBounds('money', t)) return { why: 'more than one amount in the rule' };
224
228
  const b = MONEY_BETWEEN_RE.exec(t);
225
229
  if (b) { const lo = num(b[1], b[2]), hi = num(b[3], b[4]); return lo < hi ? { reading: { op: 'between', lo, hi } } : { why: 'a range whose end is not above its start is not read' }; }
@@ -235,6 +239,10 @@ export function readLimit(shape, text, fact = {}) {
235
239
  /** the words of the default cited check code adds to a text line of a one-input job (the one list's `$` row); the card reads a part with exactly these words as `[default]` @param {string} label @returns {string} */
236
240
  export const defaultCitedText = (label) => `every claim is backed by a quote copied from "${label}"`;
237
241
 
242
+ // borrowed-from: bareloop src/rubricstep.js@v0.57.0 (c18df406) (defaultNoteText)
243
+ /** the words of the default note check code adds to a facts line that also asks for written words (the one list's `$` row); the card reads a part with exactly these words as `[default]` @param {number} n the job line @returns {string} */
244
+ export const defaultNoteText = (n) => `line ${n} writes a note — the note must be there`;
245
+
238
246
 
239
247
  // borrowed-from: bareloop src/rubricstep.js@v0.56.0 (3383cce) (listMatchesClose: the signing door's test of the list against the close; bareloop's stages shape, the block's own closeCache.stages; fwd's close is shaped differently, so wiring it to fwd's close is a later piece)
240
248
  /**
package/src/setup.js CHANGED
@@ -84,7 +84,7 @@ function humanRows(sessionDir, rel) {
84
84
  const [ask] = checkAsks([{ line: k.line, rule: k.rule, text: k.ruleText, check: k.check ?? null, why: null }]);
85
85
  return {
86
86
  kind: 'human', n: lookAnswered + i + 1, at: null, source: 'look', ask: ask.ask, question: ask.question, answer: KEPT_WORDS, line: k.line,
87
- ruleNo: k.rule, ruleText: k.ruleText, proposal: ask.reading ?? null, rule: k.added ?? null,
87
+ ruleNo: k.rule, ruleText: k.ruleText, proposal: ask.reading ?? null, rule: k.ruleText ?? null,
88
88
  };
89
89
  });
90
90
  return [...answered, ...keptRows];
package/src/sheetblock.js CHANGED
@@ -13,6 +13,7 @@ import { rubricVocabulary } from 'bareguard';
13
13
  import { lineRules } from './pagebits.js';
14
14
  import { sheetCheckSentence } from './sheetchecks.js';
15
15
  import { isColumnChoiceRule } from './sheetoffer.js';
16
+ import { NO_VALUE_WHY } from './ticketrows.js';
16
17
 
17
18
  const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
18
19
 
@@ -56,6 +57,12 @@ export function sheetFoundWords(check, claims) {
56
57
  return null;
57
58
  }
58
59
 
60
+ /** M17 am2: a check code built has code's own name: `l<line>r<rules>` (a rule row's) or `l<line>a<k>` (an `[agent]` row's); a plan whose checks all have one is an M17 plan (its card shows the list only) @param {unknown} id */
61
+ export const isCodeBuiltId = (id) => typeof id === 'string' && /^l\d+[ra]\d+(_\d+)*$/.test(id);
62
+
63
+ /** M17 am3: who a sheet check comes from: code's `row: 'agent'` (a second check on a rule, its own `[agent]` row) is `agent` whatever it shows; else the one rule (`sheetByOf`) @param {any} c @param {string[]} rules */
64
+ export const sheetByCheck = (c, rules) => (c?.row === 'agent' ? 'agent' : sheetByOf(rules));
65
+
59
66
  /** @param {any} l a job line `{rules?, guardrail?, rule?}` @returns {string[]} its `~` rules, numbered from 1 by position */
60
67
  export const rulesOfLine = (l) => lineRules({ ...(Array.isArray(l?.rules) ? { rules: l.rules } : {}), rule: l?.guardrail ?? l?.rule });
61
68
 
@@ -70,7 +77,7 @@ export const coversWords = (rules) => rules.map((r) => `covers "${r}"`).join('
70
77
  * older `close.columns` / `close.cited` check (then every guardrail is Not checked).
71
78
  * @param {{declaration: any, lines: Array<{n: number, rules?: string[], guardrail?: string, rule?: string}>, csvRoles?: string[], record?: any}} o
72
79
  * `record` = the `sheet` section of `line-checks.json` (`{lines: [...]}`), only after a run
73
- * @returns {Array<{line: number, guardrails: string[], checked: Array<{id: string, name: string, words: string, covers: string[], coversWords: string, text: string, ok?: boolean, found?: string}>, notChecked: string[]|'none'}>}
80
+ * @returns {Array<{line: number, codeBuilt: boolean, guardrails: string[], checked: Array<{id: string, name: string, words: string, covers: string[], coversWords: string, by: 'you'|'agent', text: string, ok?: boolean, found?: string}>, notChecked: string[]|'none'}>}
74
81
  */
75
82
  export function sheetLineBlocks({ declaration, lines, csvRoles = [], record }) {
76
83
  const out = [];
@@ -95,7 +102,8 @@ export function sheetLineBlocks({ declaration, lines, csvRoles = [], record }) {
95
102
  const words = sheetCheckSentence(c);
96
103
  const cw = coversWords(rules);
97
104
  /** @type {any} */
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]`
105
+ const by = sheetByCheck(c, rules);
106
+ const e = { id: typeof c.id === 'string' ? c.id : '', name, words, covers: rules, coversWords: cw, by, text: onList ? tagged(sheetPlainText(name, words, cw), by) : 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]`
99
107
  const res = newest && Array.isArray(newest.results) ? newest.results.find((/** @type {any} */ r) => isRec(r) && r.id === c.id) : undefined;
100
108
  if (isRec(res) && typeof res.ok === 'boolean') {
101
109
  e.ok = res.ok;
@@ -110,19 +118,21 @@ export function sheetLineBlocks({ declaration, lines, csvRoles = [], record }) {
110
118
  return e;
111
119
  });
112
120
  const notChecked = guardrails.filter((r, i) => !isColumnChoiceRule(r) && !covered.has(i + 1));
113
- out.push({ line: st.fromLine, guardrails, checked, notChecked: notChecked.length === 0 ? /** @type {'none'} */ ('none') : notChecked });
121
+ out.push({ line: st.fromLine, guardrails, checked, codeBuilt: hasSheet && st.close.sheet.every((/** @type {any} */ c) => isCodeBuiltId(c?.id)), notChecked: notChecked.length === 0 ? /** @type {'none'} */ ('none') : notChecked });
114
122
  }
115
123
  return out;
116
124
  }
117
125
 
118
126
  /**
119
- * The guardrail rules of a sheet step that no check covers, as the drafter's Not-checked lines (`line N: "rule" - no sheet check covers it`): the block's own
127
+ * The guardrail rules of a sheet step that no check covers, as the drafter's Not-checked lines (`line N: "rule" - <reason>`): the block's own
120
128
  * `notChecked`, one list for the plan card and the drafter's saved record.
121
- * @param {any} declaration @param {Array<{n: number, rules?: string[], guardrail?: string, rule?: string}>} lines @param {string[]} csvRoles @returns {string[]}
129
+ * M17 am2: `built` (the builder's answer, src/sheetbuild.js) gives the reason a rule is Not checked (the refusal that named it).
130
+ * @param {any} declaration @param {Array<{n: number, rules?: string[], guardrail?: string, rule?: string}>} lines @param {string[]} csvRoles @param {{notChecked: Record<string, string>}} [built] @returns {string[]}
122
131
  */
123
- export function uncoveredRules(declaration, lines, csvRoles) {
132
+ export function uncoveredRules(declaration, lines, csvRoles, built) {
124
133
  if (csvRoles.length === 0) return [];
125
- return sheetLineBlocks({ declaration, lines, csvRoles }).flatMap((b) => (b.notChecked === 'none' ? [] : b.notChecked.map((r) => `line ${b.line}: "${r}" \u2014 no sheet check covers it`)));
134
+ return sheetLineBlocks({ declaration, lines, csvRoles }).flatMap((b) => (b.notChecked === 'none' ? [] : b.notChecked
135
+ .map((r) => `line ${b.line}: "${r}" \u2014 ${built?.notChecked[`line ${b.line}: "${r}"`] ?? NO_VALUE_WHY}`)));
126
136
  }
127
137
 
128
138
  /** @param {any} arbiter @returns {string[]} the roles of the signed sources that are a CSV file (the sheets a check reads) */
@@ -0,0 +1,151 @@
1
+ // M17 am2 + am3 (docs/wiki/the-module-ladder.md "M17 am2", "M17 am3"): the ONE builder of the sheet checks of a line. The AI never writes a sheet check: what it sends in the declaration round's
2
+ // `close.sheet` is read here only as a typed SUGGESTION (bareguard's rule fields plus the `covers` numbers); code refuses or builds every one on bareguard's shapes and writes the check itself.
3
+ // Ported from poc/f195-agentrows/build.mjs (F195 PASS, $0); no class code, no send-back loop, no word-to-column guess, no per-case validator patch.
4
+ // refusals (each by bareguard, in this order): the vocabulary (rule, op), the line's sheets, the schema (a field of the rule), `columnAt` (a column of the sheet's header), `checkTables`
5
+ // (and its problems), `groundedLiterals` (a number or date in the person's own words), `claimSchema` (an answer box), and for a `table` check `runTableChecks` on the sheet frozen at draft time.
6
+ // placement (am3 item 1): every suggestion that passes all of them is BUILT. A cells (answer) check is placed before a table check, then in the order sent. A cells check is a RULE ROW's check when none of the
7
+ // rules it covers is held by an earlier rule row, else (or when it covers no rule) its own `[agent]` row. M17 am7: a `table` check reads only the input sheet, so it is never a rule row: it is always
8
+ // its own `[agent]` row, on by default, and covers no rule (a rule only a table check named is Not checked). Nothing is hidden; nothing sits beside a rule's row.
9
+ // One writer per field: `id`, `claim`, `covers` and `table` (when absent and the line reads one sheet) are assigned here. A rule row's id is `l<line>r<rules>`, an agent row's `l<line>a<k>`; the claim is the id.
10
+ // What this throws away: a suggestion's `id`, `claim`, `text` (and its `covers`: an agent row's is only the rule no rule row holds); a refused suggestion's check (only its reason is kept, on the rules it named).
11
+ // Third outcomes, named: a suggestion that is not an object, names no rule or op bareguard has, a table it cannot read, a column that is no header: refused with that helper's words; a rule that no
12
+ // check holds is Not checked with the last refusal that named it, or the no-pick sentence (`NO_SUGGESTION`).
13
+ import { rubricVocabulary, claimSchema, groundedLiterals } from 'bareguard';
14
+ import { SHEET_RULES, sheetCheckColumns, sheetCheckReds, bareguardChecks } from './sheetchecks.js';
15
+ import { tableChecksFailingOnInput } from './sheetrun.js';
16
+ import { isColumnChoiceRule } from './sheetoffer.js';
17
+ import { rulesOfLine } from './sheetblock.js';
18
+ import { wordsSaidOn } from './pagebits.js';
19
+ import { NO_VALUE_WHY } from './ticketrows.js';
20
+
21
+ const V = /** @type {any} */ (rubricVocabulary);
22
+ const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
23
+
24
+ /** the fields of a suggestion code does not read: it names every check itself */
25
+ export const SUGGESTION_DROPPED = Object.freeze(['id', 'claim', 'text', 'covers']);
26
+
27
+ /** M17 am7 item 2: the words of a rule no check holds and nothing refused: the one no-pick sentence (src/ticketrows.js), not a third copy */
28
+ export const NO_SUGGESTION = NO_VALUE_WHY;
29
+
30
+ /**
31
+ * @param {any} ai a suggestion as the AI sent it @returns {{covers: number[], fields: Record<string, any>}}
32
+ */
33
+ export function toSuggestion(ai) {
34
+ /** @type {Record<string, any>} */
35
+ const fields = {};
36
+ if (isRec(ai)) for (const [k, v] of Object.entries(ai)) if (!SUGGESTION_DROPPED.includes(k)) fields[k] = v;
37
+ return { covers: isRec(ai) && Array.isArray(ai.covers) ? ai.covers : [], fields };
38
+ }
39
+
40
+ /**
41
+ * @typedef {{check: any, covers: number[]}} Placed
42
+ * @typedef {{rule: number, text: string, state: 'built'|'column'|'agent-row'|'not-checked', reason: string|null, id: string|null}} RuleState
43
+ * @param {{line: {n: number, text?: string, rules?: string[], guardrail?: string, rule?: string}, tables: Record<string, {header: string[], rows: any[]}>, suggestions: any[]}} o
44
+ * @returns {Promise<{rows: RuleState[], ruleRows: Placed[], agentRows: Placed[], checks: any[], refused: {helper: string, why: string}[]}>}
45
+ */
46
+ export async function buildSheetLine({ line, tables, suggestions }) {
47
+ const rules = rulesOfLine(line);
48
+ const roles = Object.keys(tables);
49
+ const words = wordsSaidOn({ text: line.text, rules });
50
+ /** @type {{helper: string, why: string}[]} */
51
+ const refused = [];
52
+ /** @type {Map<number, string>} */
53
+ const refusedFor = new Map();
54
+ /** @type {{nums: number[], fields: Record<string, any>}[]} */
55
+ const buildable = [];
56
+ for (const src of suggestions) {
57
+ const s = toSuggestion(src);
58
+ const nums = [...new Set(s.covers)].filter((n) => Number.isInteger(n) && n >= 1 && n <= rules.length && !isColumnChoiceRule(rules[n - 1])).sort((a, b) => a - b);
59
+ const refuse = (/** @type {string} */ helper, /** @type {string} */ why) => { refused.push({ helper, why }); for (const n of nums) if (!refusedFor.has(n)) refusedFor.set(n, `suggestion refused: ${helper}: ${why}`); };
60
+ const f = s.fields;
61
+ if (!SHEET_RULES.includes(f.rule) || !isRec(V.rules[f.rule]?.ops) || !Object.hasOwn(V.rules[f.rule].ops, f.op)) { refuse('vocabulary', `no ${String(f.rule)} op "${String(f.op)}"`); continue; }
62
+ const role = typeof f.table === 'string' ? f.table : roles.length === 1 ? roles[0] : null;
63
+ if (role === null || !roles.includes(role)) { refuse('tables', `"${String(f.table)}" is not one of the line's sheets`); continue; }
64
+ const check = { ...f, table: role };
65
+ const bad = Object.keys(check).filter((k) => k !== 'rule' && !Object.hasOwn(V.rules[f.rule].fields, k));
66
+ if (bad.length > 0) { refuse('schema', `field ${bad.join(', ')} is not a ${f.rule} field`); continue; }
67
+ const probe = { id: 'probe', ...check, ...(f.rule === 'cells' ? { claim: 'probe' } : {}) };
68
+ const cols = sheetCheckColumns(probe).filter((c) => !tables[role].header.includes(c));
69
+ if (cols.length > 0) { refuse('columnAt', `'${cols[0]}' is not a column of "${role}"`); continue; }
70
+ const reds = sheetCheckReds([probe], line.n, tables);
71
+ if (reds.length > 0) { refuse('checkTables', reds[0].replace(/^declaration: line \d+: /, '')); continue; }
72
+ const miss = groundedLiterals(bareguardChecks([probe])[0], words).missing;
73
+ if (miss.length > 0) { refuse('groundedLiterals', `${miss[0].kind} ${JSON.stringify(miss[0].value)} (${miss[0].path}) is not in your words`); continue; }
74
+ if (f.rule === 'cells' && claimSchema(bareguardChecks([probe])[0]) === null) { refuse('claimSchema', 'no answer box for this check'); continue; }
75
+ if (f.rule === 'table') {
76
+ const fails = await tableChecksFailingOnInput({ steps: [{ fromLine: line.n, close: { class: 'green', sheet: [probe] } }] }, tables);
77
+ if (fails.length > 0) { refuse('runTableChecks', 'the table check already fails on the sheet'); continue; }
78
+ }
79
+ buildable.push({ nums, fields: check });
80
+ }
81
+ // placement: answer (cells) checks first, then the order sent (a stable sort)
82
+ const order = buildable.map((b, i) => ({ b, i })).sort((x, y) => (x.b.fields.rule === 'cells' ? 0 : 1) - (y.b.fields.rule === 'cells' ? 0 : 1) || x.i - y.i).map((x) => x.b);
83
+ /** @type {Map<number, string>} */
84
+ const held = new Map();
85
+ /** @type {Map<number, string>} */
86
+ const coveredByAgent = new Map();
87
+ /** @type {Placed[]} */
88
+ const ruleRows = [];
89
+ /** @type {Placed[]} */
90
+ const agentRows = [];
91
+ for (const b of order) {
92
+ const asRule = b.fields.rule !== 'table' && b.nums.length > 0 && b.nums.every((n) => !held.has(n) && !coveredByAgent.has(n));
93
+ const id = asRule ? `l${line.n}r${b.nums.join('_')}` : `l${line.n}a${agentRows.length + 1}`;
94
+ // an [agent] row shows only a rule no rule row holds and no earlier [agent] row shows (F195's rule: never shown nowhere, never two rows); `row: 'agent'` is the tag's own typed field (src/sheetblock.js)
95
+ const shown = asRule ? b.nums : b.fields.rule === 'table' ? [] : b.nums.filter((n) => !held.has(n) && !coveredByAgent.has(n));
96
+ const check = { id, ...b.fields, ...(b.fields.rule === 'cells' ? { claim: id } : {}), covers: shown, ...(asRule ? {} : { row: 'agent' }) };
97
+ if (asRule) { for (const n of b.nums) held.set(n, id); ruleRows.push({ check, covers: b.nums }); } else { for (const n of shown) coveredByAgent.set(n, id); agentRows.push({ check, covers: shown }); }
98
+ }
99
+ /** @type {RuleState[]} */
100
+ const rows = rules.map((text, i) => {
101
+ const n = i + 1;
102
+ if (isColumnChoiceRule(text)) return { rule: n, text, state: 'column', reason: null, id: null };
103
+ if (held.has(n)) return { rule: n, text, state: 'built', reason: null, id: /** @type {string} */ (held.get(n)) };
104
+ if (coveredByAgent.has(n)) return { rule: n, text, state: 'agent-row', reason: null, id: /** @type {string} */ (coveredByAgent.get(n)) };
105
+ return { rule: n, text, state: 'not-checked', reason: refusedFor.get(n) ?? NO_SUGGESTION, id: null };
106
+ });
107
+ return { rows, ruleRows, agentRows, checks: [...ruleRows, ...agentRows].map((p) => p.check), refused };
108
+ }
109
+
110
+ /**
111
+ * The declaration with every green sheet step's `close.sheet` REWRITTEN by code from what the AI suggested there (`buildSheetLine`). A step with no suggestion is left alone; a step none of whose
112
+ * suggestions can be built loses `close.sheet` (its rules are Not checked with their reasons). Pure over the declaration it is given (a copy is returned).
113
+ * @param {{declaration: any, lines: {n: number, text?: string, rules?: string[], guardrail?: string, rule?: string}[], tables: Record<string, {header: string[], rows: any[]}>}} o
114
+ * @returns {Promise<{declaration: any, notChecked: Record<string, string>, refused: {line: number, helper: string, why: string}[], unbuilt: {line: number, lost: string[]}[]}>} `unbuilt`: the green sheet steps left with no check, each with its rules as Not-checked lines. `notChecked`: `line N: "rule"` -> the refusal that named it (or `NO_SUGGESTION`), for each rule of a
115
+ * rewritten line that no check holds
116
+ */
117
+ export async function buildSheetChecks({ declaration, lines, tables }) {
118
+ /** @type {Record<string, string>} */
119
+ const notChecked = {};
120
+ /** @type {{line: number, helper: string, why: string}[]} */
121
+ const refused = [];
122
+ if (!isRec(declaration) || !Array.isArray(declaration.steps)) return { declaration, notChecked, refused, unbuilt: [] };
123
+ /** @type {Set<number>} */
124
+ const done = new Set();
125
+ const steps = [];
126
+ for (const st of declaration.steps) {
127
+ if (!isRec(st) || !isRec(st.close) || st.close.class !== 'green' || !Array.isArray(st.close.sheet) || !Number.isInteger(st.fromLine) || done.has(st.fromLine)) { steps.push(st); continue; }
128
+ done.add(st.fromLine);
129
+ const line = lines.find((l) => l.n === st.fromLine);
130
+ if (!line) { steps.push(st); continue; }
131
+ const built = await buildSheetLine({ line, tables, suggestions: st.close.sheet });
132
+ for (const x of built.refused) refused.push({ line: st.fromLine, ...x });
133
+ for (const r of built.rows) if (r.state === 'not-checked') notChecked[`line ${st.fromLine}: "${r.text}"`] = /** @type {string} */ (r.reason);
134
+ const { sheet: _suggested, ...close } = st.close;
135
+ steps.push({ ...st, close: built.checks.length > 0 ? { ...close, sheet: built.checks } : close });
136
+ }
137
+ // M17 am5 / P5: a green step that reads a sheet and holds no check after the build (no suggestion, or none code could build) is REPORTED here, with each of its rules and the refusal that named it
138
+ // (else the no-pick sentence). What class such a step gets is the caller's to decide (src/blockassemble.js closeUnbuiltSheetSteps); this file writes no class.
139
+ /** @type {{line: number, lost: string[]}[]} */
140
+ const unbuilt = [];
141
+ const roles = Object.keys(tables);
142
+ for (const st of steps) {
143
+ if (!isRec(st) || !isRec(st.close) || st.close.class !== 'green' || (Array.isArray(st.close.sheet) && st.close.sheet.length > 0) || isRec(st.close.cited) || !Number.isInteger(st.fromLine)) continue;
144
+ if (!Array.isArray(st.reads) || !st.reads.some((/** @type {string} */ r) => roles.includes(r)) || unbuilt.some((u) => u.line === st.fromLine)) continue;
145
+ const line = lines.find((l) => l.n === st.fromLine);
146
+ const rules = line ? rulesOfLine(line).filter((r) => !isColumnChoiceRule(r)) : [];
147
+ if (rules.length === 0) continue;
148
+ unbuilt.push({ line: st.fromLine, lost: rules.map((r) => `line ${st.fromLine}: "${r}" \u2014 ${notChecked[`line ${st.fromLine}: "${r}"`] ?? NO_SUGGESTION}`) });
149
+ }
150
+ return { declaration: { ...declaration, steps }, notChecked, refused, unbuilt };
151
+ }
@@ -91,10 +91,11 @@ export function sheetCheckSentence(check) {
91
91
  /**
92
92
  * 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).
93
93
  * 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).
94
- * @param {any[]} checks @returns {any[]} a copy without `covers`
94
+ * M17 am3: `row` (fwdloop's own typed tag of a check code made an `[agent]` row) is cleaned here too.
95
+ * @param {any[]} checks @returns {any[]} a copy without `covers` and `row`
95
96
  */
96
97
  export function bareguardChecks(checks) {
97
- return checks.map((c) => { if (!isRec(c) || !('covers' in c)) return c; const { covers: _kept, ...rest } = c; return rest; });
98
+ return checks.map((c) => { if (!isRec(c) || !('covers' in c || 'row' in c)) return c; const { covers: _kept, row: _row, ...rest } = c; return rest; });
98
99
  }
99
100
 
100
101
  /**
package/src/sheetfind.js CHANGED
@@ -44,9 +44,9 @@ export function findColumn(csvText, word) {
44
44
 
45
45
  /**
46
46
  * The question, as signed (item 7's example, then am8 item 1's answer words):
47
- * `no column 'Price'; 'Amount' has numbers in 40 of 40 rows. Use it? Answer "agree", or type your own words (your answer is added as a new ~ rule on line N).`
47
+ * `no column 'Price'; 'Amount' has numbers in 40 of 40 rows. Use it? Answer "agree", or type your own words (your answer becomes the agent's check on line N).`
48
48
  * @param {string} word @param {FoundAsk} found @param {number} line @returns {string}
49
49
  */
50
- export const columnQuestion = (word, found, line) => `no column '${word}'; '${found.column}' has numbers in ${found.numbers} of ${found.rows} rows. Use it?${columnTail(line)}`;
51
- /** @param {number} line @returns {string} the answer words the column question ends with (M10 am29: the panel cuts exactly this) */
52
- export const columnTail = (line) => ` Answer "agree", or type your own words (your answer is added as a new ~ rule on line ${line}).`;
50
+ export const columnQuestion = (word, found, line, tied = false) => `no column '${word}'; '${found.column}' has numbers in ${found.numbers} of ${found.rows} rows. Use it?${columnTail(line, tied)}`;
51
+ /** @param {number} line @param {boolean} [tied] the question is about one of the person's `~` rules (M17 ruling 1: the answer replaces that rule; the words are the page asks' own) @returns {string} the answer words the column question ends with (M10 am29: the panel cuts exactly this) */
52
+ export const columnTail = (line, tied = false) => (tied ? ` Answer "agree", or type your own words (your answer replaces that ~ rule on line ${line}).` : ` Answer "agree", or type your own words (your answer becomes the agent's check on line ${line}).`);
package/src/sheetlook.js CHANGED
@@ -83,6 +83,13 @@ export function applySheetWords(text, words, jobLines, label) {
83
83
  /** @type {import('./pagerules.js').Dropped[]} */
84
84
  const dropped = [];
85
85
  const seen = new Set();
86
+ // the person's word is a header of the sheet: the word is theirs when the line or its `~` rules say it (a header the model picked in the person's place is not)
87
+ const isYours = (/** @type {any} */ jl, /** @type {string} */ word) => jl !== undefined && wordForms(word).some((f) => countPhrase(wordsSaidOn(jl), f) > 0);
88
+ // F196: a `~` rule whose own words contain a header of the sheet is tied to it by CODE (not by what the model returned): none of its words is asked (M10 am32, F180)
89
+ const headers = parseCsv(text).header;
90
+ const tiedRules = new Set(jobLines.flatMap((l) => lineRules(l).flatMap((r, i) => (headers.some((h) => h.trim() !== '' && countPhrase(r, h) > 0) ? [`${l.n}\u0000${i + 1}`] : []))));
91
+ /** the words (line + word) a `~` rule asked about or settled: the line's own prose never asks that word again (one word, one question; the rule's ask wins) */
92
+ const ruleWords = new Set();
86
93
  for (const w of words) {
87
94
  const at = tieOf(w.from, jobLines);
88
95
  const key = `${at.line}\u0000${at.rule ?? ''}\u0000${w.word.toLowerCase()}`;
@@ -97,7 +104,7 @@ export function applySheetWords(text, words, jobLines, label) {
97
104
  if (found.kind === 'header') {
98
105
  // a real header is kept only when the word is the PERSON'S: in the line or its ~ rules. A header the model picked in the person's place is not a check the person
99
106
  // asked for (live walk 2026-10-21: "Price over 500" kept as "Amount", nothing asked)
100
- if (jl === undefined || !wordForms(w.word).some((f) => countPhrase(wordsSaidOn(jl), f) > 0)) dropped.push({ ...rec, reason: 'word-not-yours' });
107
+ if (!isYours(jl, w.word)) dropped.push({ ...rec, reason: 'word-not-yours' });
101
108
  else facts.push(fact(found.column));
102
109
  continue;
103
110
  }
@@ -106,11 +113,15 @@ export function applySheetWords(text, words, jobLines, label) {
106
113
  if (found.kind === 'none') { dropped.push({ ...rec, reason: 'no-fit', other: String(found.rows) }); continue; }
107
114
  // 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
115
  if (rules.some((r, i) => countPhrase(r, found.column) > 0)) { facts.push(fact(found.column)); continue; }
116
+ if (at.rule !== undefined) ruleWords.add(`${at.line}\u0000${w.word.toLowerCase()}`);
117
+ if (at.rule !== undefined && tiedRules.has(`${at.line}\u0000${at.rule}`)) continue;
118
+ // F196: the line's prose word that a tied `~` rule of the line also says is settled by that rule (one word, one question, whichever the look tied the ask to)
119
+ if (at.rule === undefined && rules.some((r, i) => tiedRules.has(`${at.line}\u0000${i + 1}`) && wordForms(w.word).some((f) => countPhrase(r, f) > 0))) continue;
109
120
  asks.push({
110
- line: at.line, rule: at.rule ?? null, source: 'look', ask: 'reading', ruleText, question: columnQuestion(w.word, found, at.line), reading: columnRuleWords(w.word, found.column), word: w.word, column: found.column,
121
+ line: at.line, rule: at.rule ?? null, source: 'look', ask: 'reading', ruleText, question: columnQuestion(w.word, found, at.line, at.rule !== undefined), reading: columnRuleWords(w.word, found.column), word: w.word, column: found.column,
111
122
  });
112
123
  }
113
- return { facts, asks, dropped };
124
+ return { facts, asks: asks.filter((a) => a.rule !== null || !ruleWords.has(`${a.line}\u0000${a.word.toLowerCase()}`)), dropped };
114
125
  }
115
126
 
116
127
  /**
package/src/sheetoffer.js CHANGED
@@ -78,20 +78,65 @@ export function sheetOpsBrief() {
78
78
  * 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).
79
79
  * @param {string[]} roles the CSV input roles @returns {string[]}
80
80
  */
81
- export function sheetOfferRules(roles) {
81
+ export function sheetOfferRules(roles, lineNums = /** @type {number[]} */ ([])) {
82
82
  return [
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.`,
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.',
83
+ ...(lineNums.length ? [`- The job's sheet lines are ${lineNums.join(', ')} (the lines shown with their ~ rules that are not on the list's own rows): "line" in a sheetChecks suggestion is one of those numbers, exactly as shown. The checks of a sheet line are sent only in sheetChecks: an edit that names a sheet line is refused.`] : []),
84
+ `- M17: you write NO sheet check in the declaration (it has no "close.sheet"). A job line whose step reads a CSV input (${roles.join(', ')}) and has a guardrail about values in it lists that input's role in the step's reads and gets its checks from your row-edit reply: "sheetChecks", 1 to ${MAX_SHEET_CHECKS} suggestions, each a bareguard check object from the ops below with "line" = the job line's number and "table" = the CSV input's role. Suggest the checks the line's guardrail needs and nothing else; code builds each one on bareguard or refuses it with its reason, and the person sees every one and can drop it.`,
85
+ '- A column name in a suggestion is picked from the sheet\'s header, spelled exactly; the tool only lets you pick a header name.',
85
86
  '- 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.',
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.',
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.',
87
+ '- A "cells" check names "claim", any short name (code renames it); 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; 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: suggest at least one cells check too.',
88
+ '- "covers" on each suggestion 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.',
88
89
  ...sheetOpsBrief(),
89
90
  ];
90
91
  }
91
92
 
93
+ /**
94
+ * M17 am2 item 2: the row-edit reply's `sheetChecks` property: bareguard's `checkSchema` items (src/sheetoffer.js `sheetChecksProp`) plus the job line each suggestion is for. Typed suggestions only; code builds or refuses each.
95
+ * @param {Record<string, {header: string[]}>} tables @param {number[]} [lineNums] the job's sheet lines: `line` can only name one of them @returns {Record<string, any>|null}
96
+ */
97
+ export function sheetSuggestProp(tables, lineNums = /** @type {number[]} */ ([])) {
98
+ const p = sheetChecksProp(tables);
99
+ if (p === null) return null;
100
+ return { ...p, description: 'suggested sheet checks, only for a job line whose step reads a CSV input: code builds or refuses each one on bareguard; you never write a check into the plan', items: { ...p.items, properties: { line: { type: 'integer', ...(lineNums.length ? { enum: lineNums } : { minimum: 1 }), description: 'the number of the job line this check is for (one of the sheet lines shown)' }, ...p.items.properties }, required: ['line', ...p.items.required] } };
101
+ }
102
+
92
103
  /** @param {unknown} rule @returns {boolean} true for the `use the column 'X' for 'Y'` rule an agreed column ask writes ({@link columnRuleWords}) */
93
104
  export function isColumnChoiceRule(rule) {
94
105
  const r = String(rule);
95
106
  const head = columnRuleWords('', '').split("''")[0]; // "use the column '"
96
107
  return r.startsWith(head) && r.endsWith("'") && r.includes("' for '");
97
108
  }
109
+
110
+ /**
111
+ * M17 ruling 1 (hamr 2026-11-14): the parts of an agreed column rule (`use the column 'Amount' for 'Price'`), read from the words code wrote ({@link columnRuleWords}); null for any other text.
112
+ * @param {unknown} rule @returns {{column: string, word: string}|null}
113
+ */
114
+ export function columnChoiceParts(rule) {
115
+ if (!isColumnChoiceRule(rule)) return null;
116
+ const r = String(rule);
117
+ const head = "use the column '";
118
+ const mid = r.indexOf("' for '", head.length);
119
+ if (mid < 0) return null;
120
+ return { column: r.slice(head.length, mid), word: r.slice(mid + "' for '".length, r.length - 1) };
121
+ }
122
+
123
+ /**
124
+ * M17 ruling 1: the rule's own words with the job's word (case aside, whole word) swapped for the agreed column: "Price over 500" + Amount -> "Amount over 500". Null when the word is not in the rule.
125
+ * @param {string} text @param {string} word @param {string} column @returns {string|null}
126
+ */
127
+ export function swapColumnWord(text, word, column) {
128
+ const w = word.trim().toLowerCase();
129
+ if (w === '') return null;
130
+ const low = text.toLowerCase();
131
+ const isWordChar = (/** @type {string|undefined} */ c) => c !== undefined && c.toLowerCase() !== c.toUpperCase() || (c !== undefined && c >= '0' && c <= '9');
132
+ let from = 0;
133
+ for (;;) {
134
+ const at = low.indexOf(w, from);
135
+ if (at < 0) return null;
136
+ if (!isWordChar(text[at - 1]) && !isWordChar(text[at + w.length])) return `${text.slice(0, at)}${column}${text.slice(at + w.length)}`;
137
+ from = at + 1;
138
+ }
139
+ }
140
+
141
+ /** M17 ruling 2: what the AI is told of a column the person agreed for a word of the job's prose (no `~` rule): the word and the column, typed @param {{line: number, word: string, column: string}} c @returns {string} */
142
+ export const agreedColumnWords = (c) => `- The person agreed that on line ${c.line} the word '${c.word}' means the column '${c.column}'. If a check on that line needs it, suggest it on that column.`;