fwdloop 0.32.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 (93) 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 +205 -122
  23. package/src/factwords.js +112 -0
  24. package/src/inputlook.js +53 -0
  25. package/src/labelscan.js +162 -0
  26. package/src/pageask.js +4 -1
  27. package/src/pagedropwords.js +11 -1
  28. package/src/panel/author.js +73 -4
  29. package/src/panel/authorcard.js +9 -6
  30. package/src/panel/data.js +41 -9
  31. package/src/panel/index.html +202 -13
  32. package/src/panel/result.js +4 -3
  33. package/src/panel/server.js +3 -1
  34. package/src/pickrecord.js +28 -0
  35. package/src/placerule.js +398 -0
  36. package/src/planrebuild.js +206 -0
  37. package/src/rowedit.js +118 -0
  38. package/src/rubricstep.js +264 -0
  39. package/src/runfile.js +4 -2
  40. package/src/runner.js +67 -10
  41. package/src/setup.js +10 -4
  42. package/src/sheetblock.js +6 -2
  43. package/src/sheetchecks.js +49 -64
  44. package/src/sheetclaims.js +12 -32
  45. package/src/sheetoffer.js +24 -52
  46. package/src/sheetrows.js +107 -0
  47. package/src/sheetrun.js +13 -10
  48. package/src/summary-words.js +3 -3
  49. package/src/try-checks.js +31 -12
  50. package/src/types.js +1 -0
  51. package/types/auditchecks.d.ts +24 -0
  52. package/types/authoring.d.ts +18 -1
  53. package/types/blockasks.d.ts +37 -0
  54. package/types/blockassemble.d.ts +33 -0
  55. package/types/blockdraft.d.ts +83 -0
  56. package/types/blocklines.d.ts +31 -0
  57. package/types/blockpick.d.ts +41 -0
  58. package/types/cardlist.d.ts +21 -0
  59. package/types/checkblock.d.ts +363 -0
  60. package/types/checked.d.ts +16 -2
  61. package/types/checklist.d.ts +115 -0
  62. package/types/checklistsign.d.ts +27 -0
  63. package/types/checkwords.d.ts +5 -0
  64. package/types/cited-record.d.ts +9 -0
  65. package/types/citedcheck.d.ts +33 -2
  66. package/types/closers.d.ts +24 -2
  67. package/types/declaredclose.d.ts +2 -0
  68. package/types/drafter.d.ts +15 -361
  69. package/types/factwords.d.ts +38 -0
  70. package/types/inputlook.d.ts +49 -0
  71. package/types/labelscan.d.ts +35 -0
  72. package/types/pageask.d.ts +2 -0
  73. package/types/panel/author.d.ts +41 -0
  74. package/types/panel/authorcard.d.ts +1 -1
  75. package/types/panel/data.d.ts +4 -2
  76. package/types/panel/jobgrid.d.ts +1 -1
  77. package/types/pickrecord.d.ts +22 -0
  78. package/types/placerule.d.ts +208 -0
  79. package/types/planrebuild.d.ts +52 -0
  80. package/types/provider.d.ts +1 -1
  81. package/types/rowedit.d.ts +33 -0
  82. package/types/rubricstep.d.ts +60 -0
  83. package/types/runfile.d.ts +5 -2
  84. package/types/runner.d.ts +45 -1
  85. package/types/sheetblock.d.ts +1 -0
  86. package/types/sheetchecks.d.ts +10 -17
  87. package/types/sheetclaims.d.ts +2 -1
  88. package/types/sheetoffer.d.ts +5 -5
  89. package/types/sheetrows.d.ts +73 -0
  90. package/types/sheetrun.d.ts +4 -4
  91. package/types/summary-words.d.ts +2 -1
  92. package/types/try-checks.d.ts +4 -2
  93. package/types/types.d.ts +8 -0
package/src/drafter.js CHANGED
@@ -32,8 +32,16 @@ import { lookAtPage, pageInfoLines } from './pagelook.js';
32
32
  import { lookAtSheet, sheetPrompt } from './sheetlook.js';
33
33
  import { leftRuleLine, dropRows, dropLine, dropSentence, pickNoteLine } from './pagedropwords.js';
34
34
  import {
35
- offerRules, rowsFromAnswer, checkAsks, settleRules, applyPicks, retentionOf, SUGGEST_SYSTEM, SUGGEST_TOOL, SUGGEST_SCHEMA, suggestUserText,
35
+ offerRules, rowsFromAnswer, checkAsks, settleRules, applyPicks, retentionOf, SUGGEST_SYSTEM, SUGGEST_TOOL, SUGGEST_SCHEMA, suggestUserText, codeScope,
36
36
  } from './checkpick.js';
37
+ // M16 (docs/wiki/the-module-ladder.md, "M16"): the check block's turns, wired beside the declaration path
38
+ import { blockJobLines } from './blocklines.js';
39
+ import { setUpBlock, ticketLeaveOut, pickEdits, ledgerEdits, repairedEditsReadable, editRecord, renderRejectBlock, buildFaultWords, isBuildFault } from './blockdraft.js';
40
+ import { assembleFromBlock } from './blockassemble.js';
41
+ import { cardOfBlock } from './cardlist.js';
42
+ import { questionsOfBlock } from './blockasks.js';
43
+ import { ledgerRecord, LEDGER_SYSTEM, LEDGER_SCHEMA, LEDGER_TOOL, ledgerUserText } from './checklist.js';
44
+ import { ROW_EDIT_SYSTEM, ROW_EDIT_REVISE, rowEditUserText, rowEditChannel, editsOf } from './rowedit.js';
37
45
  import { matchRecord, entriesFromAnswers, sameWords, KEPT_WORDS } from './pickrecord.js';
38
46
  import { MAP_SYSTEM, mapPrompt } from './pagemap.js';
39
47
  import { askableFromLook, tooManyAsksText, MAX_LOOK_ASKS } from './pageask.js';
@@ -44,7 +52,8 @@ import path from 'node:path';
44
52
  import { isCellsPath } from './closers.js';
45
53
  import { parseCsv, sheetTable } from './csv.js';
46
54
  import { sheetChecksProp, sheetOfferRules } from './sheetoffer.js';
47
- import { uncoveredRules } from './sheetblock.js';
55
+ import { uncoveredRules, csvRolesOf } from './sheetblock.js';
56
+ import { withSheetRows, withSheetCard, sheetChoice } from './sheetrows.js';
48
57
  import {
49
58
  makeProvider, ModelRefusal, sumMeterings, ceilingCostUsd, priceRecord,
50
59
  } from './provider.js';
@@ -64,7 +73,7 @@ export const CLASSES = Object.freeze(['green', 'softgreen', 'hitl']);
64
73
  export const WHOLE_OUTPUT_CEILING_RULE = "use the guardrail's ceiling for the whole output";
65
74
 
66
75
  /** @param {any[]|undefined} sources @returns {string[]} the roles of the document inputs (.docx / .md / .txt) */
67
- const docRolesOf = (sources) => (sources ?? []).filter((s) => s.kind === 'file' && DOC_EXTS.some((x) => String(s.path).toLowerCase().endsWith(x))).map((s) => s.role);
76
+ export const docRolesOf = (sources) => (sources ?? []).filter((s) => s.kind === 'file' && DOC_EXTS.some((x) => String(s.path).toLowerCase().endsWith(x))).map((s) => s.role);
68
77
 
69
78
  /** the document inputs a quote can come from (M10 piece 5, item 2) */
70
79
  const DOC_EXTS = Object.freeze(['.docx', '.md', '.txt']);
@@ -86,54 +95,11 @@ const COLUMNS_PROP = Object.freeze({
86
95
  },
87
96
  });
88
97
 
89
- /** M10 am7 item 1: the facts of a green step that cites quotes from a web page (`close.cited`); the same fields src/citedcheck.js checks. */
90
- const CITED_PROP = Object.freeze({
91
- type: 'object',
92
- description: 'only on a green step that checks quotes from a web page or a document input: the facts every result must hold. Omit on any other step',
93
- properties: {
94
- source: { type: 'string', description: "the role of the web page input the quotes come from (also in the step's reads)" },
95
- facts: {
96
- type: 'array',
97
- minItems: 1,
98
- maxItems: 10,
99
- description: 'one fact per thing a result must hold; at most 10',
100
- items: {
101
- type: 'object',
102
- properties: {
103
- name: { type: 'string', description: 'letters and spaces only, no digits' },
104
- shape: { type: 'string', enum: ['money', 'number', 'date', 'time', 'phrase', 'text'] },
105
- unit: { type: ['string', 'array'], items: { type: 'string' }, description: 'money only: the words the page writes after the amount, copied from the page' },
106
- currency: { type: ['string', 'array'], items: { type: 'string' }, description: 'money only: $, € or £' },
107
- phrase: { type: 'string', description: 'phrase only: the fixed words every result must say, copied from the page' },
108
- anchor: { type: 'string', description: 'the label right before the value, picked from the kept labels listed under Inputs; never typed' },
109
- until: { type: 'string', description: 'text only: the words that close the value' },
110
- rule: {
111
- type: 'object',
112
- description: 'under (lt, lte), over (gt, gte) or between: only a number that is in the person\'s own words on the job line',
113
- properties: { op: { type: 'string', enum: ['lt', 'lte', 'gt', 'gte', 'between'] }, value: {}, lo: {}, hi: {} },
114
- required: ['op'],
115
- additionalProperties: false,
116
- },
117
- },
118
- required: ['name', 'shape'],
119
- additionalProperties: false,
120
- },
121
- },
122
- count: {
123
- type: 'object',
124
- description: 'how many results the job line asks for ("List 3" is min 3, max 3)',
125
- properties: { min: { type: 'integer', minimum: 1 }, max: { type: 'integer', minimum: 1 } },
126
- additionalProperties: false,
127
- },
128
- },
129
- required: ['source', 'facts'],
130
- additionalProperties: false,
131
- });
132
-
133
98
  /**
134
99
  * The forced tool's parameter schema. `menu` = wiredMenu(). `sheets` (M10b piece 3, optional) = the drafting copy's table of each CSV input role: with it a step may carry
135
100
  * `close.sheet`, and every column a check names is an enum of that sheet's exact header (src/sheetoffer.js); without it (no CSV input) no sheet property exists.
136
101
  * M13 piece 4: `ticket` = `{flowType, tools}` for MCP (generic) and Tickets; then a step may carry `mcpTools` (an enum of the job's tools) and, for Tickets, the tool carries `ticketFilter` and `ticketWatch` (src/ticket-draft.js). The job's `mcp` block and `flowType` are set by code, never offered.
102
+ * M16 item 5: the AI is offered no `close.cited` (the list owns the facts; code builds them from its rows).
137
103
  * @param {any[]} menu @param {{sheets?: Record<string, {header: string[]}>, ticket?: {flowType: 'mcp'|'tickets', tools: string[]}}} [o]
138
104
  */
139
105
  export function buildDeclarationSchema(menu, { sheets, ticket } = {}) {
@@ -166,7 +132,6 @@ export function buildDeclarationSchema(menu, { sheets, ticket } = {}) {
166
132
  type: 'object',
167
133
  properties: {
168
134
  class: { type: 'string', enum: [...CLASSES], description: "MUST equal the class of fromLine's guardrail in guardrailClasses; hitl when that line has no guardrail" },
169
- cited: CITED_PROP,
170
135
  columns: COLUMNS_PROP,
171
136
  ...(sheetProp ? { sheet: sheetProp } : {}),
172
137
  },
@@ -297,16 +262,18 @@ function cleanNotChecked(raw) {
297
262
  }
298
263
 
299
264
  // M10 am27 (1): at draft time a count guardrail is hidden from the AI (the page look and the drafter); code keeps the ORIGINAL rule numbers and text.
300
- const shownRules = (/** @type {string} */ guardrail) => lineRules({ rule: guardrail }).filter((r) => !isCountGuardrail(r)).join('; ');
265
+ // M16 S5: not on a line the check block is given (`all`): its count rules are shown like any other (am27 (1) is replaced for the lines of the list)
266
+ const shownRules = (/** @type {string} */ guardrail, all = false) => lineRules({ rule: guardrail }).filter((r) => all || !isCountGuardrail(r)).join('; ');
301
267
 
302
268
  /**
303
269
  * The job lines as the page look may see them (no count rule), and `toOriginal`, which takes a look fact's / dropped entry's visible rule number back to the guardrail's own number.
304
- * @param {{n: number, text: string, rule?: string}[]} jobLines
270
+ * @param {{n: number, text: string, rule?: string}[]} jobLines @param {Set<number>} [shown] lines whose count rules the look may see (M16: the block's lines)
305
271
  */
306
- export function hideCounts(jobLines) {
307
- const seenLines = jobLines.map((l) => { const kept = lineRules(l).filter((r) => !isCountGuardrail(r)); return { n: l.n, text: l.text, ...(kept.length ? { rule: kept.join('; ') } : {}) }; });
272
+ export function hideCounts(jobLines, shown = /** @type {Set<number>} */ (new Set())) {
273
+ // M16 item 5: the lines the check block is given show their count rules to the look (`shown`); every other line is as before
274
+ const seenLines = jobLines.map((l) => { const kept = lineRules(l).filter((r) => shown.has(l.n) || !isCountGuardrail(r)); return { n: l.n, text: l.text, ...(kept.length ? { rule: kept.join('; ') } : {}) }; });
308
275
  const ruleMap = (/** @type {number} */ line, /** @type {number|undefined} */ vis) => {
309
- if (vis === undefined) return undefined;
276
+ if (vis === undefined || shown.has(line)) return vis;
310
277
  const orig = lineRules(jobLines.find((x) => x.n === line)).map((r, i) => ({ r, no: i + 1 })).filter((x) => !isCountGuardrail(x.r));
311
278
  return orig[vis - 1]?.no ?? vis;
312
279
  };
@@ -314,11 +281,11 @@ export function hideCounts(jobLines) {
314
281
  return { seenLines, toOriginal };
315
282
  }
316
283
 
317
- function jobLinesText(lines, asks) {
284
+ function jobLinesText(lines, asks, blockLines = /** @type {Set<number>} */ (new Set())) {
318
285
  const askLines = new Set(asks.map((a) => a.line));
319
286
  return lines
320
287
  .map((l) => `${l.n}. ${l.text}${askLines.has(l.n) ? ' [SIGNED ASK — a human stop]' : ''}`
321
- + `${l.guardrail && shownRules(l.guardrail) ? ` [guardrail: ${shownRules(l.guardrail)}]` : ' [no guardrail]'}`)
288
+ + `${l.guardrail && shownRules(l.guardrail, blockLines.has(l.n)) ? ` [guardrail: ${shownRules(l.guardrail, blockLines.has(l.n))}]` : ' [no guardrail]'}`)
322
289
  .join('\n');
323
290
  }
324
291
 
@@ -326,29 +293,15 @@ function jobLinesText(lines, asks) {
326
293
  * M10 am7: and when the job signs a web page, how a green step checks quotes from it - every rule below is one the validator enforces at $0. */
327
294
  function greenReadRule(sources) {
328
295
  const csvRoles = (sources ?? []).filter((s) => s.kind === 'file' && isCellsPath(s.path)).map((s) => s.role);
329
- const pageRoles = (sources ?? []).filter((s) => s.kind === 'page').map((s) => s.role);
330
296
  // M10 piece 5 (item 2): a quote in a doc - a .docx / .md / .txt input is quoted the way a page is
331
297
  const docRoles = docRolesOf(sources);
332
298
  const rule = '- A step whose line has a "green" guardrail must list the CSV input\'s role in its reads (for example reads: ["aging"]), because only an input with cells can be checked against its sheet; a text output of an earlier step has no cells. A green step that reads only other steps is refused.';
333
299
  const out = [csvRoles.length
334
300
  ? `${rule} CSV inputs in this job: ${csvRoles.join(', ')}. close.columns = [{source, column}] names the exact column(s) of the CSV header that the step's values come from. Where the Inputs list says a line "is column 'X'", that line's step must name that column. A step that has close.sheet is not held to close.columns by a word that merely matches a header (such as a bucket name); but when a line carries a rule "use the column 'X' for ...", at least one of that line's close.sheet checks must use that column. Leave close.columns out when the line names no column.`
335
- : `${rule} This job signs no CSV input, so a guardrail that needs a sheet check cannot be classed green here: class it "hitl"${pageRoles.length ? ' (unless it is about a web page, below)' : ''}.`];
336
- if (docRoles.length) {
337
- out.push(`- A document input (${docRoles.join(', ')}) is never listed in reads by a step that does not quote it (only a green step with close.cited.source = that role lists it). A step that needs the document is granted "read" ("readDocx" for a .docx) and reads it by its role through that tool; its reads stay empty or hold only earlier outputs.`);
338
- }
301
+ : `${rule} This job signs no CSV input, so a guardrail that needs a sheet check cannot be classed green here: class it "hitl".`];
302
+ // M16 S5: the check block builds the quote checks of its lines; the drafter is told nothing of close.cited and offers none
303
+ if (docRoles.length) out.push(`- A document input (${docRoles.join(', ')}) is never listed in reads. A step that needs the document is granted "read" ("readDocx" for a .docx) and reads it by its role through that tool; its reads stay empty or hold only earlier outputs.`);
339
304
  if (csvRoles.length) out.push(...sheetOfferRules(csvRoles)); // M10b piece 3: close.sheet and every rule the validator enforces on it
340
- if (pageRoles.length || docRoles.length) {
341
- out.push(
342
- `- ${[pageRoles.length ? `Web page inputs in this job: ${pageRoles.join(', ')}.` : '', docRoles.length ? `Document inputs in this job: ${docRoles.join(', ')}.` : ''].filter(Boolean).join(' ')} A step whose line asks for things found in one of them, and whose guardrail is about them, is "green" and checks quotes: it lists that input's role in its reads and carries close.cited = {source, facts, count}. close.cited is for a green step only.`,
343
- '- close.cited.count is how many results the line asks for ("List 3" is {min: 3, max: 3}); the number must be one the person said on the line or its guardrail, as digits or a word. close.cited.facts is one fact per thing every result must hold, at most 10; a fact name is letters and spaces only (no digit).',
344
- '- Fact shapes: money takes unit or currency, rule, anchor; number, date and time take rule, anchor; text takes anchor and until (until needs an anchor); phrase takes only phrase (fixed words every result must say). Never put a field on a shape that does not take it.',
345
- '- A label (anchor, until) is PICKED from the kept labels listed under Inputs for that page, never typed. A phrase, a unit or a currency is copied from the page words listed there. A word listed as Not checked or dropped can never be used.',
346
- '- A place listed under Inputs as "place phrases" must have EVERY one of its phrases as its own phrase fact (one fact per phrase, the phrase word for word). A place name alone does not tell a result that leaves the other way.',
347
- '- A fact\'s rule (under, over, between) may only use a number that is in the person\'s own words on that job line (the line or its guardrail). Never make a number up; leave the rule out if the person gave none. When the Kept list says "limit read from your words" for a fact, the fact that reads that value MUST carry that rule (same kind, op and bound), or the line is refused.',
348
- '- A label or a phrase that sits in each result must appear on the page at least as many times as close.cited.count.min, or the line is refused.',
349
- ...(docRoles.length ? ['- For a document input there is no list of kept labels: a label (anchor) or a phrase is words the document really says, copied from it, and each must be in the document at least as many times as close.cited.count.min.'] : []),
350
- );
351
- }
352
305
  return out;
353
306
  }
354
307
 
@@ -375,7 +328,7 @@ function sheetRuleNumbers(lines, arbiter) {
375
328
  return rows.length === 0 ? [] : ['', 'The guardrail rules by number (what "covers" counts):', ...rows.map((x) => `- line ${x.n}: ${x.rules.map((q) => `${q.no}) ${q.r}`).join(' ')}`)];
376
329
  }
377
330
 
378
- export function buildSystemPrompt({ menu, lines, arbiter, factsInfo }) {
331
+ export function buildSystemPrompt({ menu, lines, arbiter, factsInfo, blockLines = /** @type {Set<number>} */ (new Set()) }) {
379
332
  const askLines = arbiter.asks.map((a) => a.line);
380
333
  const sendLines = arbiter.sends.map((s) => s.line);
381
334
  return [
@@ -404,7 +357,7 @@ export function buildSystemPrompt({ menu, lines, arbiter, factsInfo }) {
404
357
  ...(factsInfo.length ? factsInfo : ['- (none)']),
405
358
  '',
406
359
  'The numbered job lines:',
407
- jobLinesText(lines, arbiter.asks),
360
+ jobLinesText(lines, arbiter.asks, blockLines),
408
361
  ...sheetRuleNumbers(lines, arbiter),
409
362
  ].join('\n');
410
363
  }
@@ -439,7 +392,7 @@ function isPlainObject(v) { return !!v && typeof v === 'object' && !Array.isArra
439
392
  * @returns {Promise<{ok:boolean, declaration:object|null, reds:string[], rounds:number, calls:number, spendComplete:boolean,
440
393
  * costUsd:number|null, modelReturned:string|null, modelId?:string, price?:object|null, tokens?:object|null, structureRetries:number, revisions:number, stop:string|null, log:object[],
441
394
  * questions?:{line:number, question:string}[], droppedQuestions?:object[], notChecked?:string[], thinking?:{asked:string, status:string|null, say:string|null}, inputs?:{role:string, detail:string}[],
442
- * look?:{facts:any[], dropped:any[]}, pageLooks?:{role:string, address:string, sha256:string, bytes:number, frozen:string, attempts:number, mapping:any}[], sheetLooks?:any[]}>}
395
+ * checkCard?:ReturnType<typeof cardOfBlock>, notCheckedBy?:Record<string,'you'|'agent'|'default'>, look?:{facts:any[], dropped:any[]}, pageLooks?:{role:string, address:string, sha256:string, bytes:number, frozen:string, attempts:number, mapping:any}[], sheetLooks?:any[]}>}
443
396
  * `learnHints` (M8 item 5a): the earlier runs' notes block (src/learnstore.js hintsForRun), appended to the drafter's system prompt; null = nothing.
444
397
  * `look` / `pageLooks` (M10 item 3) are there when the job signs a web page: the kept facts (with their `reading`, the input a later ask reads), every drop, and per page its address, sha256 and the AI's map. Each drop is also a line in `notChecked`.
445
398
  */
@@ -449,7 +402,7 @@ export async function draft({
449
402
  draftDir = /** @type {string|null} */ (null), fetchPage = undefined, leftRules = /** @type {{line: number, rule: number}[]} */ ([]),
450
403
  checkPicks = /** @type {import('./checkpick.js').Pick[]} */ ([]),
451
404
  // M10 am17/am18: the picks of the plan this one follows (src/pickrecord.js entries), and a callback that is handed this draft's record (kept + newly answered) for the one writer
452
- carriedPicks = /** @type {import('./pickrecord.js').Entry[]} */ ([]), onPickRecord = /** @type {((r: {picks: import('./pickrecord.js').Entry[], kept: {line: number, rule: number, ruleText: string, check: Record<string, any>|null}[]}) => void)|null} */ (null),
405
+ carriedPicks = /** @type {import('./pickrecord.js').Entry[]} */ ([]), carriedChoices = /** @type {any[]|null} */ (null), carriedSheetDropped = /** @type {any[]} */ ([]), onSheetDropped = /** @type {(rec: any[]) => void} */ (() => {}), onChoices = /** @type {(rec: any[]) => void} */ (() => {}), onPickRecord = /** @type {((r: {picks: import('./pickrecord.js').Entry[], kept: {line: number, rule: number, ruleText: string, check: Record<string, any>|null}[]}) => void)|null} */ (null),
453
406
  learnHints = /** @type {{text: string, ids: string[]}|null} */ (null),
454
407
  mcpServers = /** @type {string[]|undefined} */ (undefined),
455
408
  // M13 piece 4: the job's flow type and its MCP pick (`mcpPickFor`: `{ok, server, tools}`), both set by code from the card; the drafter is told them, never asked for them
@@ -558,6 +511,8 @@ export async function draft({
558
511
  const look = { facts: [], dropped: [] };
559
512
  /** @type {string[]} */
560
513
  const pageNotChecked = [];
514
+ /** the notes in `pageNotChecked` that answer the person's own choice (left, own words, no pick): tagged [you]; every other note code writes is [default] (hamr 2026-11-14) */
515
+ const personNotChecked = new Set();
561
516
  /** @type {any[]} */
562
517
  const pageLooks = [];
563
518
  /** @type {Record<string, any>} */
@@ -565,7 +520,10 @@ export async function draft({
565
520
  let mapCut = null;
566
521
  const jobLines = lines.map((l) => ({ n: l.n, text: l.text, ...(l.guardrail ? { rule: l.guardrail } : {}) }));
567
522
  // M10 am27 (1): the page look sees only the non-count rules; `toOriginal` takes a visible rule number back to the original one
568
- const { seenLines, toOriginal } = hideCounts(jobLines);
523
+ // M16: the page look sees the count rules of every line the block takes (not an ask or send line; a job with a CSV or a .docx keeps them all hidden, as the sheet path owns its lines)
524
+ const askOrSend = new Set([...arbiter.asks.map((a) => a.line), ...arbiter.sends.map((x) => x.line)]);
525
+ const sheetPath = (arbiter.sources ?? []).some((s) => s.kind === 'file' && (isCellsPath(s.path) || String(s.path).toLowerCase().endsWith('.docx')));
526
+ const { seenLines, toOriginal } = hideCounts(jobLines, !sheetPath ? new Set(lineNums.filter((n) => !askOrSend.has(n))) : new Set());
569
527
  const pageInfo = [];
570
528
  /** one map call (a page's or a sheet's): its hold, its metering and its book are the drafting round's own (the `kind` names it in the round log) */
571
529
  const makeCallModel = (kind) => async (content, attempt) => {
@@ -635,7 +593,7 @@ export async function draft({
635
593
  if (left.length) {
636
594
  look.dropped.push(...left);
637
595
  const lines = left.map((d) => leftRuleLine(d.fact));
638
- for (const x of lines) if (!pageNotChecked.includes(x)) pageNotChecked.push(x);
596
+ for (const x of lines) { personNotChecked.add(x); if (!pageNotChecked.includes(x)) pageNotChecked.push(x); }
639
597
  pageInfo.push(' You chose to leave these Not checked; never claim them as checked:', ...lines.map((x) => ` - ${x}`));
640
598
  }
641
599
  }
@@ -680,80 +638,137 @@ export async function draft({
680
638
  );
681
639
  }
682
640
  if (sheetLooks.length) pageExtras.sheetLooks = sheetLooks; // kept beside the page looks (src/authoring.js writes both into page-look.json)
683
- // M10 am16 (1): ONE suggestion call, only when a guardrail on a step line is one this call settles (scope by code, src/checkpick.js). It suggests a check from bareguard's own list
684
- // per guardrail, or none; code keeps what passes keep-or-drop. The call is metered, held and booked as a drafting round (the same `meterings`). The redraft after the answers
685
- // (offerQuestions false) makes no call: it settles every rule against the person's picks instead.
686
- // a rule a kept page or sheet fact already serves (the look tied it: line + rule number) is settled by that fact and is not asked here
687
- const shapeRules = offerRules(lines, arbiter, [...look.facts, ...sheetFacts]);
688
- // M10 am17/am18: a guardrail whose pick is kept from the last draft skips the suggestion call and the asks; only the rest is suggested and asked. The model never sees a pick.
689
- const carried = matchRecord(carriedPicks, lines, shapeRules);
690
- const keptView = carried.kept.map((k) => ({ line: k.line, rule: k.rule, ruleText: k.entry.ruleText, check: k.entry.check, added: k.entry.added, left: k.entry.left }));
691
- onPickRecord?.({ picks: carried.kept.map((k) => k.entry), kept: keptView });
692
- const askRules = carried.askRules;
693
- /** @type {ReturnType<typeof checkAsks>} */
694
- let shapeAsks = [];
695
- if (askRules.length && offerQuestions) {
696
- const content = suggestUserText(lines, askRules);
697
- let args = null;
698
- for (let attempt = 1; attempt <= 2 && args === null; attempt += 1) {
641
+ /**
642
+ * ONE forced-tool turn, for every turn that is an answer in one typed call (the suggest call, the ledger call, the row-edit turn): the hold against what is left of the cap, Loop's metering of the round,
643
+ * the book before and after, the tool that captures the arguments and halts (no wrap-up round), thinking off (on cannot combine with a forced call), the raw answer kept when the call failed.
644
+ * `repair` (M4d am39): a malformed reply that is a complete object plus trailing `}` is repaired, and used only when `usable(value)` says the caller can read it.
645
+ * Returns `{early}` (a provider red or the budget: the draft's own stop) or `{args, entry}` (`args` null = no usable call in any attempt; `entry` is the last round's log entry).
646
+ * @param {{kind: string, system: string, messages: {role: string, content: string}[], tool: {name: string, description: string, schema: any}, attempts?: number, repair?: boolean, usable?: (v: any) => boolean}} o
647
+ */
648
+ const forcedTurn = async ({ kind, system: sys, messages, tool: spec, attempts = 2, repair = false, usable = () => true }) => {
649
+ /** @type {any} */
650
+ let entry = null;
651
+ for (let attempt = 1; attempt <= attempts; attempt += 1) {
699
652
  const spentBefore = meterings.reduce((sum, ev) => sum + (ev.costUsd ?? roundCeiling), 0);
700
- if (spentBefore + ceilingCostUsd(rates, SUGGEST_SYSTEM.length + content.length + JSON.stringify(SUGGEST_SCHEMA).length) > budgetUsd) {
701
- if (meterings.length === 0 && calls === 0) { removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); return fail([tooSmall(roundCeiling)]); }
702
- return earlyStop(['the draft budget is spent'], 'budget');
653
+ if (spentBefore + ceilingCostUsd(rates, sys.length + messages.reduce((n, m) => n + m.content.length, 0) + JSON.stringify(spec.schema).length) > budgetUsd) {
654
+ if (meterings.length === 0 && calls === 0) { removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); return { early: fail([tooSmall(roundCeiling)]) }; }
655
+ return { early: earlyStop(['the draft budget is spent'], 'budget') };
703
656
  }
704
657
  /** @type {any} */
705
658
  let captured;
706
659
  const roundEvents = [];
707
- const tool = { name: SUGGEST_TOOL, description: 'Suggest one check (or none) per guardrail.', parameters: SUGGEST_SCHEMA, execute: async (/** @type {any} */ a) => { captured = a; throw new HaltError('suggestion captured', { rule: 'captured' }); } };
708
- const suggestLoop = new Loop({ provider, rates, onLlmResult: async (ev) => { roundEvents.push(ev); meterings.push(ev); } });
660
+ const tool = { name: spec.name, description: spec.description, parameters: spec.schema, execute: async (/** @type {any} */ a) => { captured = a; throw new HaltError(`${kind} captured`, { rule: 'captured' }); } };
661
+ const forcedLoop = new Loop({ provider, rates, onLlmResult: async (ev) => { roundEvents.push(ev); meterings.push(ev); } });
709
662
  calls += 1;
710
663
  book(true);
711
664
  let res;
712
665
  let threw = null;
713
666
  try {
714
- // thinking is off: on cannot combine with a forced tool call (the answer is one typed call, there is nothing to think through)
715
- res = await suggestLoop.run([{ role: 'system', content: SUGGEST_SYSTEM }, { role: 'user', content }], [tool], { maxTokens: DRAFT_MAX_TOKENS, thinkingMode: 'off', toolChoice: { name: SUGGEST_TOOL } });
667
+ res = await forcedLoop.run([{ role: 'system', content: sys }, ...messages], [tool], { maxTokens: DRAFT_MAX_TOKENS, thinkingMode: 'off', toolChoice: { name: spec.name } });
716
668
  } catch (err) {
717
669
  threw = err;
718
670
  if (roundEvents.length === 0) unmetered += 1;
719
671
  }
720
672
  book(false);
721
- const entry = /** @type {Record<string, any>} */ ({ round: log.length + 1, kind: 'check-suggest' });
673
+ entry = /** @type {Record<string, any>} */ ({ round: log.length + 1, kind });
722
674
  if (res?.thinkingApplied !== undefined) entry.thinkingApplied = res.thinkingApplied;
723
675
  if (res?.thinkingStatus !== undefined) entry.thinkingStatus = res.thinkingStatus;
724
676
  if (threw && !(isPlainObject(captured) && threw instanceof HaltError)) {
725
677
  entry.outcome = `provider-red: ${threw.message}`;
726
678
  log.push(entry);
727
- return earlyStop([`provider-red: ${threw.message}`], 'provider-red');
679
+ return { early: earlyStop([`provider-red: ${threw.message}`], 'provider-red') };
728
680
  }
729
681
  if (!isPlainObject(captured)) {
730
- // the raw answer is kept (log.json), the cut-off said out loud; one more try, then every guardrail is "I can't check this" (never a guessed check)
731
- entry.outcome = res?.stopReason === 'max_tokens' ? 'structure: truncated: the round hit the output cap with no completed tool call' : 'structure: no usable tool call (text instead of the tool)';
682
+ // the raw answer is kept (log.json), the cut-off said out loud
732
683
  const malformed = provider?.lastMalformedToolCall ?? null;
684
+ entry.outcome = res?.stopReason === 'max_tokens' ? 'structure: truncated: the round hit the output cap with no completed tool call' : 'structure: no usable tool call (text instead of the tool)';
733
685
  if (typeof malformed?.rawArguments === 'string') entry.rawArguments = malformed.rawArguments;
734
686
  else if (typeof res?.text === 'string' && res.text !== '') entry.rawText = res.text;
687
+ // M4d am39: only a malformed-JSON round (never a cut-off, never text) whose answer is a complete object plus trailing `}` is repaired
688
+ const fixed = repair && malformed && res?.stopReason !== 'max_tokens' ? repairTrailingBraces(malformed.rawArguments) : null;
689
+ if (fixed) {
690
+ const ok = usable(fixed.value);
691
+ entry.braceRepair = { dropped: fixed.dropped, used: ok };
692
+ if (ok) { entry.outcome = 'answered'; entry.args = fixed.value; log.push(entry); return { args: fixed.value, entry }; }
693
+ }
735
694
  log.push(entry);
736
695
  continue;
737
696
  }
738
697
  entry.outcome = 'answered';
739
698
  entry.args = captured;
740
699
  log.push(entry);
741
- args = captured;
700
+ return { args: captured, entry };
742
701
  }
743
- shapeAsks = checkAsks(rowsFromAnswer(askRules, args));
702
+ return { args: null, entry };
703
+ };
704
+
705
+ // M10 am16 (1): ONE suggestion call, only when a guardrail on a step line is one this call settles (scope by code, src/checkpick.js). It suggests a check from bareguard's own list
706
+ // per guardrail, or none; code keeps what passes keep-or-drop. The call is metered, held and booked as a drafting round (the same `meterings`). The redraft after the answers
707
+ // (offerQuestions false) makes no call: it settles every rule against the person's picks instead.
708
+ // a rule a kept page or sheet fact already serves (the look tied it: line + rule number) is settled by that fact and is not asked here
709
+ const allShape = offerRules(lines, arbiter, [...look.facts, ...sheetFacts]);
710
+ // M16 S1: the lines the block is given (step lines; a sheet line the sheet look tied to a column stays on the sheet path, R6). Their rules go to the block; every other shape rule keeps today's path.
711
+ // a job with a CSV input: a line with a rule that is not a count belongs to the sheet path even when the sheet look tied none of its words (its sheet checks are the drafter's, M10b, which the list leaves as they are; the declaration is not there yet to say it)
712
+ const csvRuleLines = Object.keys(facts.sheets ?? {}).length ? jobLines.filter((l) => !askLines.has(l.n) && lineRules(l).some((r) => !isCountGuardrail(r))).map((l) => l.n) : [];
713
+ const blockPlan = blockJobLines(proseText, undefined, [...new Set([...sheetFacts.filter((f) => f.forRule !== undefined), ...sheetAsks, ...sheetLooks.flatMap((l) => l.dropped)].map((x) => x.line)), ...csvRuleLines]);
714
+ if (blockPlan && !blockPlan.ok) return fail(blockPlan.reds.map((r) => `signed-text: ${r}`));
715
+ const blockLineNums = new Set(blockPlan ? blockPlan.jobLines.map((l) => l.n) : []);
716
+ const blockScoped = allShape.filter((r) => blockLineNums.has(r.line));
717
+ // M10 am17/am18: a guardrail whose pick is kept from the last draft skips the suggestion call and the asks; only the rest is suggested and asked. The model never sees a pick.
718
+ const carried = matchRecord(carriedPicks, lines, allShape);
719
+ const keptView = carried.kept.map((k) => ({ line: k.line, rule: k.rule, ruleText: k.entry.ruleText, check: k.entry.check, added: k.entry.added, left: k.entry.left }));
720
+ onPickRecord?.({ picks: carried.kept.map((k) => k.entry), kept: keptView });
721
+ const askRules = carried.askRules;
722
+ /** the block (M16 S1): the person's rules, the look, the picks kept and just answered, reconciled once */
723
+ /** @type {import('./checkblock.js').CheckBlock|null} */
724
+ let block = null;
725
+ if (blockPlan?.ok) {
726
+ const inBlock = (/** @type {{line: number}} */ x) => blockLineNums.has(x.line);
727
+ block = setUpBlock({
728
+ texts: { ...(facts.docs ?? {}), ...Object.fromEntries(Object.entries(pages).map(([role, pg]) => [role, pg.text])) }, jobLines: blockPlan.jobLines, look,
729
+ kept: { picks: carried.picks.filter(inBlock), left: carried.left.filter(inBlock), askRules: carried.askRules.filter(inBlock) },
730
+ fresh: { picks: checkPicks.filter(inBlock), left: leftRules.filter(inBlock) }, asks: offerQuestions, countScope: (t) => codeScope(arbiter.sources, t) === 'in', scoped: blockScoped, leaveOut: ticketLeaveOut(flowType, blockPlan.jobLines, [...look.facts, ...sheetFacts]),
731
+ });
732
+ }
733
+ /** @type {ReturnType<typeof checkAsks>} */
734
+ let shapeAsks = [];
735
+ if (askRules.length && offerQuestions) {
736
+ const content = suggestUserText(lines, askRules);
737
+ const got = await forcedTurn({ kind: 'check-suggest', system: SUGGEST_SYSTEM, messages: [{ role: 'user', content }], tool: { name: SUGGEST_TOOL, description: 'Suggest one check (or none) per guardrail.', schema: SUGGEST_SCHEMA } });
738
+ if (got.early) return got.early;
739
+ const sugRows = rowsFromAnswer(askRules, got.args);
740
+ // M16 S2 (R1): a kept check on a block line is a `pick` edit of the block, before any asks; the other rules keep today's path
741
+ if (block) { block.applyDelta({ label: 'pre:check-suggest', pre: true, edits: pickEdits(sugRows, blockLineNums) }); block.reconcile(); }
742
+ shapeAsks = checkAsks(sugRows.filter((r) => !blockLineNums.has(r.line)));
743
+ }
744
+ if (block && blockPlan?.ok && blockPlan.jobLines.length > 0 && Object.keys(block.texts).length > 0) {
745
+ const texts = block.texts;
746
+ // the ledger-suggest call, after the pick call and before the asks (bareloop authorjob.js@v0.56.0 order, R3): extra `!` checks the inputs support, as `add` edits
747
+ const lg = await forcedTurn({ kind: 'ledger-suggest', system: LEDGER_SYSTEM, messages: [{ role: 'user', content: ledgerUserText(blockPlan.jobLines, texts) }], tool: { name: LEDGER_TOOL, description: 'Deliver the extra checks the inputs support (or an empty list). Call this exactly once.', schema: LEDGER_SCHEMA } });
748
+ if (lg.early) return lg.early;
749
+ block.applyDelta({ label: 'pre:ledger-suggest', pre: true, edits: ledgerEdits(lg.args?.extra) });
750
+ block.reconcile();
744
751
  }
752
+ // borrowed-from: bareloop src/authorjob.js@v0.56.0 (3383cce)
753
+ // a Revise keeps the last draft's Drop/Add choices (the suggestions exist now); code still judges every one when the list is reconciled
754
+ if (block && Array.isArray(carriedChoices)) { block.carryChoices(carriedChoices); onChoices(block.choicesRecord()); block.reconcile(); }
755
+ /** the questions of the block, merged below with the sheet's and the look's own, under one cap (M16 S3) */
756
+ const blockAsks = block && offerQuestions ? questionsOfBlock(block, blockScoped) : [];
757
+ if (block) pageExtras.checkRows = ledgerRecord(/** @type {any} */ (block.rows));
745
758
  // M10 piece 3 (item 4, am1, am2): CODE decides the early asks from the look, after the one map call and BEFORE any drafting round. A signed ask line's own
746
759
  // guardrail is a human stop, not a page check, so it is not asked. More than MAX_LOOK_ASKS is a job to rewrite: nothing is asked, nothing more is spent.
747
760
  // The redraft after the answers (offerQuestions false) never asks. A sheet's offers are reading asks: they come first with the page's, in line order.
748
- if ((pageSources.length || sheetAsks.length || shapeAsks.length) && offerQuestions) {
749
- const pageAsks = pageSources.length ? askableFromLook({ facts: [...look.facts, ...sheetFacts] }, jobLines.filter((l) => !askLines.has(l.n))) : [];
750
- const lookAsks = [...[...pageAsks.filter((a) => a.ask === 'reading'), ...sheetAsks].sort((a, b) => a.line - b.line), ...pageAsks.filter((a) => a.ask !== 'reading')];
761
+ if ((pageSources.length || sheetAsks.length || shapeAsks.length || blockAsks.length) && offerQuestions) {
762
+ // M16 S3: a block line's asks come from the block (questionsOfBlock); the page's own asks are for the lines the block is not given
763
+ const pageAsks = pageSources.length ? askableFromLook({ facts: [...look.facts, ...sheetFacts] }, jobLines.filter((l) => !askLines.has(l.n) && !blockLineNums.has(l.n))) : [];
764
+ const lookAsks = [...[...pageAsks.filter((a) => a.ask === 'reading'), ...sheetAsks, ...blockAsks.filter((a) => a.ask === 'reading')].sort((a, b) => a.line - b.line), ...pageAsks.filter((a) => a.ask !== 'reading'), ...blockAsks.filter((a) => a.ask === 'cant-check')];
751
765
  // am16 (3): a shape guardrail's ask follows, in line order. (5): a proposal is not an ask under am1; only a `can't check` ask counts toward the cap (the 4th stops drafting at $0).
752
- const asks = [...lookAsks, ...shapeAsks];
766
+ const blockShape = blockAsks.filter((a) => a.ask === 'no-check' || a.ask === 'check');
767
+ const asks = [...lookAsks, ...shapeAsks, ...blockShape];
753
768
  if (asks.length > 0) {
754
769
  const m = sumMeterings(meterings);
755
770
  const spent = m.costUsd === null || unmetered > 0 ? (m.costUsd === null ? 'unknown' : `at least ${usdText(m.costUsd)}`) : usdText(m.costUsd);
756
- const counted = [...lookAsks, ...shapeAsks.filter((a) => a.counted).map((a) => ({ ...a, reading: "I can't check this" }))];
771
+ const counted = [...lookAsks, ...[...shapeAsks, ...blockShape].filter((a) => a.counted).map((a) => ({ ...a, reading: "I can't check this" }))];
757
772
  const tooMany = counted.length > MAX_LOOK_ASKS;
758
773
  if (tooMany && pageSources.length) removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); // a refused draft keeps no page copy
759
774
  return {
@@ -769,14 +784,42 @@ export async function draft({
769
784
  // (shown on the plan card and carried as `unjudgeable`); the drafter writes no check of its own, whatever it sends is overwritten below.
770
785
  const allPicks = [...checkPicks, ...carried.picks];
771
786
  const allLeft = [...leftRules, ...carried.left];
772
- const settled = shapeRules.length ? settleRules(shapeRules, allPicks, allLeft) : null;
773
- // the record this draft hands on: what it kept plus what the person just answered (numbered on this card)
774
- onPickRecord?.({ picks: [...carried.kept.map((k) => k.entry), ...entriesFromAnswers(lines, shapeRules, checkPicks, leftRules)], kept: keptView });
787
+ // the old path settles the shape rules of the lines the block is NOT given; a block line's checks come from the block's rows (assembleFromBlock, below)
788
+ const oldShape = block ? allShape.filter((r) => !blockLineNums.has(r.line)) : allShape;
789
+ const settled = oldShape.length ? settleRules(oldShape, allPicks, allLeft) : null;
790
+ // the record this draft hands on: what it kept plus what the person just answered (numbered on this card); the block's rules and the other shape rules are one record
791
+ onPickRecord?.({ picks: [...carried.kept.map((k) => k.entry), ...entriesFromAnswers(lines, allShape, checkPicks, leftRules)], kept: keptView });
775
792
  const keptNote = (/** @type {{line: number, rule: number, text: string}} */ n) => (carried.kept.some((k) => k.line === n.line && (k.rule === n.rule || (k.entry.added !== null && sameWords(k.entry.added, n.text)))) ? ` (${KEPT_WORDS})` : '');
776
793
  for (const n of settled?.notes ?? []) {
777
794
  const line = (n.reason === 'person-left' ? leftRuleLine(n.text) : pickNoteLine(n.text, n.reason)) + keptNote(n);
795
+ personNotChecked.add(line);
778
796
  if (!pageNotChecked.includes(line)) pageNotChecked.push(line);
779
797
  }
798
+ // M16 S2 + S4: the AI's two helpers send edits to the list, then the row-edit turn; code judges every edit alone (src/checkblock.js). The declaration path below runs as before (S5 assembles from the rows).
799
+ // a line with nothing to check (no `~` rule of the person's, no input text for a `!` row to be built from) has no list to edit: no turn is paid for it (M16 item 2, "every job line with checks")
800
+ if (block && blockPlan?.ok && blockPlan.jobLines.length > 0 && (Object.keys(block.texts).length > 0 || block.rows.some((r) => r.kind === 'rule'))) {
801
+ const texts = block.texts;
802
+ // the row-edit turn (bareloop ROW_EDIT_SYSTEM / rowEditUserText as copied): a revise only when an edit was refused, at most MAX_REVISIONS; a refused edit costs the others nothing
803
+ const lookReport = pageSources.length ? { prose: [], notFound: [], facts: look.facts, dropped: look.dropped } : null;
804
+ /** @type {{role: string, content: string}[]} */
805
+ let turn = [{ role: 'user', content: rowEditUserText({ jobLines: blockPlan.jobLines, look: lookReport, texts }) }];
806
+ const channel = rowEditChannel(false).tool({ calls: [] });
807
+ for (let rev = 0; ; rev += 1) {
808
+ const got = await forcedTurn({
809
+ kind: rev === 0 ? 'row-edit' : 'row-edit-revision', system: ROW_EDIT_SYSTEM, messages: turn, tool: { name: channel.name, description: channel.description, schema: channel.parameters },
810
+ attempts: 1 + MAX_STRUCTURE_RETRIES, repair: true, usable: repairedEditsReadable,
811
+ });
812
+ if (got.early) return got.early;
813
+ if (got.args === null) return earlyStop([String(got.entry?.outcome ?? 'structure').replace(/^structure: /, '')], 'structure');
814
+ const rec = block.applyDelta({ label: `row-edit-${rev + 1}`, edits: editsOf(got.args) });
815
+ block.reconcile();
816
+ got.entry.edits = editRecord(rec);
817
+ const refused = rec.edits.filter((e) => e.accepted !== true);
818
+ if (refused.length === 0 || rev >= MAX_REVISIONS) break;
819
+ turn = [...turn, { role: 'assistant', content: JSON.stringify(got.args) }, { role: 'user', content: `${renderRejectBlock(refused.map((e) => `edit ${String(e?.op)}: ${String(e.refusedBecause)}`))}\n\n${ROW_EDIT_REVISE}` }];
820
+ }
821
+ pageExtras.checkRows = ledgerRecord(/** @type {any} */ (block.rows));
822
+ }
780
823
  // The page lines go on the drafter's list of inputs: the first line of a page's block replaces the plain line readInputFacts wrote for it.
781
824
  const factsBase = pageInfo.length ? [...facts.info.filter((l) => !pageSources.some((s) => l.startsWith(`- ${s.role}: a web page`))), ...pageInfo] : facts.info;
782
825
  const factsInfo = [...factsBase, ...ticketSources.flatMap((s) => ticketFactsLines(s.role)), ...(flowType === 'mcp' ? mcpFactsLines(mcp.server, mcp.tools) : [])];
@@ -784,7 +827,7 @@ export async function draft({
784
827
  // `notChecked` is offered on every try (information, not asking); `questions` only on try 3 (below).
785
828
  // M10b piece 3: the drafting copy's table of each CSV input - the header the drafter may pick from, the table bareguard's sign-time test runs over
786
829
  const sheetTables = Object.keys(facts.sheets ?? {}).length ? Object.fromEntries(Object.entries(facts.sheets).map(([role, t]) => [role, sheetTable(parseCsv(t))])) : undefined;
787
- const baseSystem = buildSystemPrompt({ menu, lines, arbiter, factsInfo });
830
+ const baseSystem = buildSystemPrompt({ menu, lines, arbiter, factsInfo, blockLines: blockLineNums });
788
831
  // M8 item 5a: the earlier runs' notes go on the DRAFTER's system prompt only (F81's B arm), the one `system` every round of this draft uses (revise and structure retries too).
789
832
  // Absent or empty: the prompt is byte-identical to what it was.
790
833
  const system = `${baseSystem}\n\n${NOTCHECKED_PROMPT}${learnHints?.text ? `\n\n${learnHints.text}` : ''}`;
@@ -797,7 +840,7 @@ export async function draft({
797
840
  let validatorReds = []; // the last validator refusal; a structure retry after a revision must not drop it
798
841
  let stop = null;
799
842
  let failedLines = []; // the job lines try 2's reds named: a question is kept only about one of these (amendment 25)
800
- /** @type {{questions:{line:number, question:string}[], droppedQuestions:object[], notChecked:string[]}} */
843
+ /** @type {{questions:{line:number, question:string}[], droppedQuestions:object[], notChecked:string[], notCheckedBy?: Record<string, 'you'|'agent'|'default'>}} */
801
844
  let extras = { questions: [], droppedQuestions: [], notChecked: pageNotChecked }; // from the round that produced `lastDecl`, never an earlier one
802
845
 
803
846
  for (;;) {
@@ -927,17 +970,41 @@ export async function draft({
927
970
  });
928
971
  }
929
972
  // M10 am16 (4): code sets the check of every line it settled, from the picks only; the drafter's own `close.shape` and class for such a line are gone
930
- if (settled) Object.assign(declaration, applyPicks(declaration, shapeRules, settled, (n) => dropSentence({ line: n.line, fact: '', reason: n.reason })));
973
+ if (settled) Object.assign(declaration, applyPicks(declaration, oldShape, settled, (n) => dropSentence({ line: n.line, fact: '', reason: n.reason })));
974
+ // M16 S6: the checks of the block's lines are the block's built parts; whatever the AI wrote for them is gone, and the list that proves it is signed with the plan
975
+ delete declaration.checkList;
976
+ let assembled = null;
977
+ if (block && blockPlan?.ok) {
978
+ assembled = assembleFromBlock({ declaration, block, lines, lineSet: blockLineNums });
979
+ Object.assign(declaration, assembled.declaration);
980
+ if (assembled.declaration.pickedLines === undefined) delete declaration.pickedLines;
981
+ }
931
982
  // M10 am27 (2): the two mechanical plan mistakes (cited page not in reads; unjudgeable note on a green line) are repaired by code and logged on the round
932
983
  { const fixed = repairDeclaration(declaration, arbiter); if (fixed.repaired.length) { Object.assign(declaration, fixed.declaration); entry.repaired = fixed.repaired; } }
984
+ // M16 am4 (2): a sheet line's checks are rows on the same list (the AI wrote them; code only reads them as rows, src/sheetrows.js)
985
+ let sheetOnList = null;
986
+ /** @type {any[]} */
987
+ let sheetDroppedNow = [];
988
+ if (block) {
989
+ // hamr 2026-11-14: a Revise keeps a sheet Drop - a new check with the id of a carried dropped one starts dropped again (only an `[agent]` row can be dropped; one that now covers a `~` rule stays)
990
+ for (const d of carriedSheetDropped) {
991
+ const r = sheetChoice({ declaration, lines, csvRoles: csvRolesOf(arbiter), op: 'drop', key: d.key, dropped: sheetDroppedNow });
992
+ if (r.ok) { Object.assign(declaration, { steps: r.declaration.steps }); sheetDroppedNow = r.dropped; }
993
+ }
994
+ onSheetDropped(sheetDroppedNow);
995
+ }
996
+ if (block) { const w = withSheetRows({ declaration, lines, csvRoles: csvRolesOf(arbiter) }); sheetOnList = w.sheet; if (w.sheet.signed.length) Object.assign(declaration, { checkList: w.declaration.checkList }); }
933
997
  // M10 am27 (4): what the drafter wrote vs what the final plan keeps, per job line (record only); drafted = the declaration as sent, before any code change
934
- entry.retention = retentionOf(captured, declaration, jobLines, [...(settled?.checks.keys() ?? [])]);
998
+ entry.retention = retentionOf(captured, declaration, jobLines, [...(settled?.checks.keys() ?? []), ...(assembled ? declaration.steps.filter((/** @type {any} */ st) => Array.isArray(st?.close?.picked) || Array.isArray(st?.close?.shape?.picked)).map((/** @type {any} */ st) => st.fromLine) : [])]);
935
999
  // M10b piece 4: `covers` (which ~ rules a check verifies) stays on the check and is signed; the validator checks it, the plan card shows it
1000
+ // M16: a look fact the list did not build (a Suggested `!` row, a Not-checked one) is not in the plan, so the words gate does not hold the plan to it (R2c asks every place phrase of the facts the plan checks)
1001
+ const inPlan = block ? new Set(block.rows.filter((r) => r.state === 'built').flatMap((r) => (r.factNames ?? []).map((/** @type {string} */ nm) => `${r.line}:${nm}`))) : null;
1002
+ const planLookFacts = inPlan ? look.facts.filter((f) => !blockLineNums.has(f.line) || inPlan.has(`${f.line}:${f.name}`)) : look.facts;
936
1003
  const verdict1 = validateDeclaration(declaration, {
937
1004
  arbiter, lines, catalogue: validationCatalogue, wired: WIRED_VERBS, verbatimGoals: true, fitJobLine: true,
938
1005
  // M10 am7 item 1: the words of every cited fact are proved on the drafting copy of the page, against what the page-word map kept
939
1006
  sheetWords: sheetTables ? { headers: Object.fromEntries(Object.entries(sheetTables).map(([role, t]) => [role, t.header])), facts: sheetFacts.filter((f) => f.shape === 'column'), tables: sheetTables } : undefined,
940
- pageWords: { texts: { ...(facts.docs ?? {}), ...Object.fromEntries(Object.entries(pages).map(([role, pg]) => [role, pg.text])) }, look: pageSources.length ? { facts: look.facts, dropped: look.dropped } : null, docs: docRolesOf(arbiter.sources) },
1007
+ pageWords: { texts: { ...(facts.docs ?? {}), ...Object.fromEntries(Object.entries(pages).map(([role, pg]) => [role, pg.text])) }, look: pageSources.length ? { facts: planLookFacts, dropped: look.dropped } : null, docs: docRolesOf(arbiter.sources) },
941
1008
  });
942
1009
  // M13 piece 4 (F105 rewritten): a generic MCP job whose steps call none of its tools is fed back like any validator red (the run would refuse it at $0, by the same sentence)
943
1010
  // M4d am39: a brace-repaired answer the validator finds an unknown key in is not used; the round is a structure failure, as today
@@ -954,16 +1021,32 @@ export async function draft({
954
1021
  const verdict = planRed ? { ok: false, reds: [planRed] } : tableReds.length ? { ok: false, reds: tableReds } : verdict1;
955
1022
  lastDecl = declaration;
956
1023
  const asked = askOpen ? normalizeQuestions(rawQuestions, failedLines) : { kept: [], dropped: [] };
957
- extras = { questions: asked.kept, droppedQuestions: asked.dropped, notChecked: [...new Set([...pageNotChecked, ...cleanNotChecked(rawNotChecked), ...uncoveredRules(declaration, jobLines, Object.keys(facts.sheets ?? {}))])] };
1024
+ // M16: the AI's own `notChecked` is kept beside the rows' reasons (M4e am24/am25 stand; M16 item 5 does not name them)
1025
+ // P4c (hamr 2026-11-14): the AI's own note is an [agent] line (`!` = agent); it never overrides a tag a row already gave the same words
1026
+ const aiNotes = cleanNotChecked(rawNotChecked);
1027
+ const uncovered = uncoveredRules(declaration, jobLines, Object.keys(facts.sheets ?? {}));
1028
+ // the tag of a note no row tells: the person's own choice [you], the AI's own note [agent], any other note code writes [default]; a row's own tag wins
1029
+ const noteBy = Object.fromEntries([...pageNotChecked, ...uncovered].map((t) => [t, personNotChecked.has(t) ? 'you' : 'default']).concat(aiNotes.map((t) => [t, 'agent'])));
1030
+ extras = { questions: asked.kept, droppedQuestions: asked.dropped, notChecked: [...new Set([...pageNotChecked, ...(assembled ? assembled.notChecked : []), ...aiNotes, ...uncovered])], ...(assembled ? { notCheckedBy: { ...noteBy, ...assembled.notCheckedBy } } : {}) };
958
1031
  if (asked.dropped.length) entry.droppedQuestions = asked.dropped;
959
1032
  // the declaration the model sent, as parsed, before any code overwrite (log.json keeps it per try)
960
1033
  entry.args = captured;
1034
+ // M16 S7: a red on a check the BLOCK built is a fault of the build, not of the job: the draft stops in plain words, the AI is never asked to fix it (R2); reds on steps, reads, asks, send stay a revise
1035
+ const faults = !verdict.ok && assembled ? /** @type {string[]} */ (/** @type {any} */ (verdict).reds).filter((r) => isBuildFault(r, linesNamedByReds([r], declaration, lineNums).filter((n) => assembled.built.has(n)))) : [];
1036
+ if (faults.length) {
1037
+ entry.outcome = 'plan-red';
1038
+ entry.reds = [.../** @type {any} */ (verdict).reds];
1039
+ log.push(entry);
1040
+ lastReds = [buildFaultWords(faults)];
1041
+ stop = 'plan-red';
1042
+ break;
1043
+ }
961
1044
  if (verdict.ok) {
962
1045
  entry.outcome = 'valid';
963
1046
  log.push(entry);
964
1047
  const m = sumMeterings(meterings);
965
1048
  return {
966
- ok: true, declaration, reds: [], rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, price: priceRecord(prices, rates), tokens: m.tokens, structureRetries, revisions, stop: null, log, thinking: thinkingOf(), inputs: facts.list, ...extras, ...pageExtras,
1049
+ ok: true, declaration, reds: [], rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, price: priceRecord(prices, rates), tokens: m.tokens, structureRetries, revisions, stop: null, log, thinking: thinkingOf(), inputs: facts.list, ...extras, ...pageExtras, ...(block ? { checkCard: sheetOnList ? withSheetCard(cardOfBlock(block), sheetOnList, sheetDroppedNow) : cardOfBlock(block) } : {}),
967
1050
  };
968
1051
  }
969
1052
  lastReds = [...verdict.reds];