fwdloop 0.31.0 → 0.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/bin/fwdloop +8 -2
  2. package/package.json +2 -2
  3. package/src/auditchecks.js +53 -0
  4. package/src/authoring.js +52 -12
  5. package/src/blockasks.js +44 -0
  6. package/src/blockassemble.js +140 -0
  7. package/src/blockdraft.js +91 -0
  8. package/src/blocklines.js +30 -0
  9. package/src/blockpick.js +165 -0
  10. package/src/cardlist.js +19 -0
  11. package/src/checkblock.js +804 -0
  12. package/src/checked.js +48 -9
  13. package/src/checklist.js +99 -0
  14. package/src/checklistsign.js +93 -0
  15. package/src/checkwords.js +20 -1
  16. package/src/cited-record.js +21 -1
  17. package/src/citedcheck.js +162 -7
  18. package/src/closers.js +41 -3
  19. package/src/declaration.js +25 -2
  20. package/src/declaredclose.js +4 -0
  21. package/src/draft-steps.js +3 -1
  22. package/src/drafter.js +244 -134
  23. package/src/factwords.js +112 -0
  24. package/src/inputlook.js +53 -0
  25. package/src/jsonbrace.js +21 -0
  26. package/src/labelscan.js +162 -0
  27. package/src/pageask.js +4 -1
  28. package/src/pagedropwords.js +11 -1
  29. package/src/panel/author.js +76 -5
  30. package/src/panel/authorcard.js +9 -6
  31. package/src/panel/data.js +41 -9
  32. package/src/panel/index.html +202 -13
  33. package/src/panel/result.js +4 -3
  34. package/src/panel/server.js +3 -1
  35. package/src/pickrecord.js +28 -0
  36. package/src/placerule.js +398 -0
  37. package/src/planrebuild.js +206 -0
  38. package/src/rowedit.js +118 -0
  39. package/src/rubricstep.js +264 -0
  40. package/src/runfile.js +4 -2
  41. package/src/runner.js +67 -10
  42. package/src/setup.js +10 -4
  43. package/src/sheetblock.js +6 -2
  44. package/src/sheetchecks.js +49 -64
  45. package/src/sheetclaims.js +12 -32
  46. package/src/sheetlook.js +2 -2
  47. package/src/sheetoffer.js +25 -53
  48. package/src/sheetrows.js +107 -0
  49. package/src/sheetrun.js +31 -1
  50. package/src/summary-words.js +3 -3
  51. package/src/try-checks.js +31 -12
  52. package/src/types.js +1 -0
  53. package/types/auditchecks.d.ts +24 -0
  54. package/types/authoring.d.ts +18 -1
  55. package/types/blockasks.d.ts +37 -0
  56. package/types/blockassemble.d.ts +33 -0
  57. package/types/blockdraft.d.ts +83 -0
  58. package/types/blocklines.d.ts +31 -0
  59. package/types/blockpick.d.ts +41 -0
  60. package/types/cardlist.d.ts +21 -0
  61. package/types/checkblock.d.ts +363 -0
  62. package/types/checked.d.ts +16 -2
  63. package/types/checklist.d.ts +115 -0
  64. package/types/checklistsign.d.ts +27 -0
  65. package/types/checkwords.d.ts +5 -0
  66. package/types/cited-record.d.ts +9 -0
  67. package/types/citedcheck.d.ts +33 -2
  68. package/types/closers.d.ts +24 -2
  69. package/types/declaredclose.d.ts +2 -0
  70. package/types/drafter.d.ts +15 -361
  71. package/types/factwords.d.ts +38 -0
  72. package/types/inputlook.d.ts +49 -0
  73. package/types/jsonbrace.d.ts +8 -0
  74. package/types/labelscan.d.ts +35 -0
  75. package/types/pageask.d.ts +2 -0
  76. package/types/panel/author.d.ts +41 -0
  77. package/types/panel/authorcard.d.ts +1 -1
  78. package/types/panel/data.d.ts +4 -2
  79. package/types/panel/jobgrid.d.ts +1 -1
  80. package/types/pickrecord.d.ts +22 -0
  81. package/types/placerule.d.ts +208 -0
  82. package/types/planrebuild.d.ts +52 -0
  83. package/types/provider.d.ts +1 -1
  84. package/types/rowedit.d.ts +33 -0
  85. package/types/rubricstep.d.ts +60 -0
  86. package/types/runfile.d.ts +5 -2
  87. package/types/runner.d.ts +45 -1
  88. package/types/sheetblock.d.ts +1 -0
  89. package/types/sheetchecks.d.ts +10 -17
  90. package/types/sheetclaims.d.ts +2 -1
  91. package/types/sheetoffer.d.ts +5 -5
  92. package/types/sheetrows.d.ts +73 -0
  93. package/types/sheetrun.d.ts +12 -0
  94. package/types/summary-words.d.ts +2 -1
  95. package/types/try-checks.d.ts +4 -2
  96. package/types/types.d.ts +8 -0
package/src/drafter.js CHANGED
@@ -22,6 +22,7 @@ import { validateDeclaration, checkGuardrailSums, checkSendLineGuardrail } from
22
22
  import { readEveryStep } from './whole-job.js';
23
23
  import { loadCatalogue } from './catalogue.js';
24
24
  import { findMcpPlanRed } from './canrun.js';
25
+ import { tableChecksFailingOnInput } from './sheetrun.js';
25
26
  import { WIRED_VERBS, wiredMenu } from './primitives.js';
26
27
  import { ticketSourcesOf, ticketFactsLines, mcpFactsLines, ticketSchemaParts, ticketReds, userMcpServers } from './ticket-draft.js';
27
28
  import { readInputFacts } from './input-facts.js';
@@ -31,8 +32,16 @@ import { lookAtPage, pageInfoLines } from './pagelook.js';
31
32
  import { lookAtSheet, sheetPrompt } from './sheetlook.js';
32
33
  import { leftRuleLine, dropRows, dropLine, dropSentence, pickNoteLine } from './pagedropwords.js';
33
34
  import {
34
- 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,
35
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';
36
45
  import { matchRecord, entriesFromAnswers, sameWords, KEPT_WORDS } from './pickrecord.js';
37
46
  import { MAP_SYSTEM, mapPrompt } from './pagemap.js';
38
47
  import { askableFromLook, tooManyAsksText, MAX_LOOK_ASKS } from './pageask.js';
@@ -43,13 +52,15 @@ import path from 'node:path';
43
52
  import { isCellsPath } from './closers.js';
44
53
  import { parseCsv, sheetTable } from './csv.js';
45
54
  import { sheetChecksProp, sheetOfferRules } from './sheetoffer.js';
46
- import { uncoveredRules } from './sheetblock.js';
55
+ import { uncoveredRules, csvRolesOf } from './sheetblock.js';
56
+ import { withSheetRows, withSheetCard, sheetChoice } from './sheetrows.js';
47
57
  import {
48
58
  makeProvider, ModelRefusal, sumMeterings, ceilingCostUsd, priceRecord,
49
59
  } from './provider.js';
50
60
  import { LIVE_PROVIDER_OPTIONS } from './model-step.js';
51
61
  import { ConfigError } from './config.js';
52
62
  import { thinkingSay, worstThinkingStatus } from './thinking.js';
63
+ import { repairTrailingBraces } from './jsonbrace.js';
53
64
 
54
65
  export const MAX_STRUCTURE_RETRIES = 2;
55
66
  export const MAX_REVISIONS = 2;
@@ -62,7 +73,7 @@ export const CLASSES = Object.freeze(['green', 'softgreen', 'hitl']);
62
73
  export const WHOLE_OUTPUT_CEILING_RULE = "use the guardrail's ceiling for the whole output";
63
74
 
64
75
  /** @param {any[]|undefined} sources @returns {string[]} the roles of the document inputs (.docx / .md / .txt) */
65
- 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);
66
77
 
67
78
  /** the document inputs a quote can come from (M10 piece 5, item 2) */
68
79
  const DOC_EXTS = Object.freeze(['.docx', '.md', '.txt']);
@@ -84,54 +95,11 @@ const COLUMNS_PROP = Object.freeze({
84
95
  },
85
96
  });
86
97
 
87
- /** 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. */
88
- const CITED_PROP = Object.freeze({
89
- type: 'object',
90
- 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',
91
- properties: {
92
- source: { type: 'string', description: "the role of the web page input the quotes come from (also in the step's reads)" },
93
- facts: {
94
- type: 'array',
95
- minItems: 1,
96
- maxItems: 10,
97
- description: 'one fact per thing a result must hold; at most 10',
98
- items: {
99
- type: 'object',
100
- properties: {
101
- name: { type: 'string', description: 'letters and spaces only, no digits' },
102
- shape: { type: 'string', enum: ['money', 'number', 'date', 'time', 'phrase', 'text'] },
103
- unit: { type: ['string', 'array'], items: { type: 'string' }, description: 'money only: the words the page writes after the amount, copied from the page' },
104
- currency: { type: ['string', 'array'], items: { type: 'string' }, description: 'money only: $, € or £' },
105
- phrase: { type: 'string', description: 'phrase only: the fixed words every result must say, copied from the page' },
106
- anchor: { type: 'string', description: 'the label right before the value, picked from the kept labels listed under Inputs; never typed' },
107
- until: { type: 'string', description: 'text only: the words that close the value' },
108
- rule: {
109
- type: 'object',
110
- description: 'under (lt, lte), over (gt, gte) or between: only a number that is in the person\'s own words on the job line',
111
- properties: { op: { type: 'string', enum: ['lt', 'lte', 'gt', 'gte', 'between'] }, value: {}, lo: {}, hi: {} },
112
- required: ['op'],
113
- additionalProperties: false,
114
- },
115
- },
116
- required: ['name', 'shape'],
117
- additionalProperties: false,
118
- },
119
- },
120
- count: {
121
- type: 'object',
122
- description: 'how many results the job line asks for ("List 3" is min 3, max 3)',
123
- properties: { min: { type: 'integer', minimum: 1 }, max: { type: 'integer', minimum: 1 } },
124
- additionalProperties: false,
125
- },
126
- },
127
- required: ['source', 'facts'],
128
- additionalProperties: false,
129
- });
130
-
131
98
  /**
132
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
133
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.
134
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).
135
103
  * @param {any[]} menu @param {{sheets?: Record<string, {header: string[]}>, ticket?: {flowType: 'mcp'|'tickets', tools: string[]}}} [o]
136
104
  */
137
105
  export function buildDeclarationSchema(menu, { sheets, ticket } = {}) {
@@ -164,7 +132,6 @@ export function buildDeclarationSchema(menu, { sheets, ticket } = {}) {
164
132
  type: 'object',
165
133
  properties: {
166
134
  class: { type: 'string', enum: [...CLASSES], description: "MUST equal the class of fromLine's guardrail in guardrailClasses; hitl when that line has no guardrail" },
167
- cited: CITED_PROP,
168
135
  columns: COLUMNS_PROP,
169
136
  ...(sheetProp ? { sheet: sheetProp } : {}),
170
137
  },
@@ -295,16 +262,18 @@ function cleanNotChecked(raw) {
295
262
  }
296
263
 
297
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.
298
- 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('; ');
299
267
 
300
268
  /**
301
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.
302
- * @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)
303
271
  */
304
- export function hideCounts(jobLines) {
305
- 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('; ') } : {}) }; });
306
275
  const ruleMap = (/** @type {number} */ line, /** @type {number|undefined} */ vis) => {
307
- if (vis === undefined) return undefined;
276
+ if (vis === undefined || shown.has(line)) return vis;
308
277
  const orig = lineRules(jobLines.find((x) => x.n === line)).map((r, i) => ({ r, no: i + 1 })).filter((x) => !isCountGuardrail(x.r));
309
278
  return orig[vis - 1]?.no ?? vis;
310
279
  };
@@ -312,11 +281,11 @@ export function hideCounts(jobLines) {
312
281
  return { seenLines, toOriginal };
313
282
  }
314
283
 
315
- function jobLinesText(lines, asks) {
284
+ function jobLinesText(lines, asks, blockLines = /** @type {Set<number>} */ (new Set())) {
316
285
  const askLines = new Set(asks.map((a) => a.line));
317
286
  return lines
318
287
  .map((l) => `${l.n}. ${l.text}${askLines.has(l.n) ? ' [SIGNED ASK — a human stop]' : ''}`
319
- + `${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]'}`)
320
289
  .join('\n');
321
290
  }
322
291
 
@@ -324,29 +293,15 @@ function jobLinesText(lines, asks) {
324
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. */
325
294
  function greenReadRule(sources) {
326
295
  const csvRoles = (sources ?? []).filter((s) => s.kind === 'file' && isCellsPath(s.path)).map((s) => s.role);
327
- const pageRoles = (sources ?? []).filter((s) => s.kind === 'page').map((s) => s.role);
328
296
  // M10 piece 5 (item 2): a quote in a doc - a .docx / .md / .txt input is quoted the way a page is
329
297
  const docRoles = docRolesOf(sources);
330
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.';
331
299
  const out = [csvRoles.length
332
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.`
333
- : `${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)' : ''}.`];
334
- if (docRoles.length) {
335
- 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.`);
336
- }
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.`);
337
304
  if (csvRoles.length) out.push(...sheetOfferRules(csvRoles)); // M10b piece 3: close.sheet and every rule the validator enforces on it
338
- if (pageRoles.length || docRoles.length) {
339
- out.push(
340
- `- ${[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.`,
341
- '- 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).',
342
- '- 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.',
343
- '- 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.',
344
- '- 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.',
345
- '- 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.',
346
- '- 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.',
347
- ...(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.'] : []),
348
- );
349
- }
350
305
  return out;
351
306
  }
352
307
 
@@ -373,7 +328,7 @@ function sheetRuleNumbers(lines, arbiter) {
373
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(' ')}`)];
374
329
  }
375
330
 
376
- export function buildSystemPrompt({ menu, lines, arbiter, factsInfo }) {
331
+ export function buildSystemPrompt({ menu, lines, arbiter, factsInfo, blockLines = /** @type {Set<number>} */ (new Set()) }) {
377
332
  const askLines = arbiter.asks.map((a) => a.line);
378
333
  const sendLines = arbiter.sends.map((s) => s.line);
379
334
  return [
@@ -402,7 +357,7 @@ export function buildSystemPrompt({ menu, lines, arbiter, factsInfo }) {
402
357
  ...(factsInfo.length ? factsInfo : ['- (none)']),
403
358
  '',
404
359
  'The numbered job lines:',
405
- jobLinesText(lines, arbiter.asks),
360
+ jobLinesText(lines, arbiter.asks, blockLines),
406
361
  ...sheetRuleNumbers(lines, arbiter),
407
362
  ].join('\n');
408
363
  }
@@ -437,7 +392,7 @@ function isPlainObject(v) { return !!v && typeof v === 'object' && !Array.isArra
437
392
  * @returns {Promise<{ok:boolean, declaration:object|null, reds:string[], rounds:number, calls:number, spendComplete:boolean,
438
393
  * costUsd:number|null, modelReturned:string|null, modelId?:string, price?:object|null, tokens?:object|null, structureRetries:number, revisions:number, stop:string|null, log:object[],
439
394
  * questions?:{line:number, question:string}[], droppedQuestions?:object[], notChecked?:string[], thinking?:{asked:string, status:string|null, say:string|null}, inputs?:{role:string, detail:string}[],
440
- * 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[]}>}
441
396
  * `learnHints` (M8 item 5a): the earlier runs' notes block (src/learnstore.js hintsForRun), appended to the drafter's system prompt; null = nothing.
442
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`.
443
398
  */
@@ -447,7 +402,7 @@ export async function draft({
447
402
  draftDir = /** @type {string|null} */ (null), fetchPage = undefined, leftRules = /** @type {{line: number, rule: number}[]} */ ([]),
448
403
  checkPicks = /** @type {import('./checkpick.js').Pick[]} */ ([]),
449
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
450
- 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),
451
406
  learnHints = /** @type {{text: string, ids: string[]}|null} */ (null),
452
407
  mcpServers = /** @type {string[]|undefined} */ (undefined),
453
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
@@ -556,6 +511,8 @@ export async function draft({
556
511
  const look = { facts: [], dropped: [] };
557
512
  /** @type {string[]} */
558
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();
559
516
  /** @type {any[]} */
560
517
  const pageLooks = [];
561
518
  /** @type {Record<string, any>} */
@@ -563,7 +520,10 @@ export async function draft({
563
520
  let mapCut = null;
564
521
  const jobLines = lines.map((l) => ({ n: l.n, text: l.text, ...(l.guardrail ? { rule: l.guardrail } : {}) }));
565
522
  // M10 am27 (1): the page look sees only the non-count rules; `toOriginal` takes a visible rule number back to the original one
566
- 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());
567
527
  const pageInfo = [];
568
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) */
569
529
  const makeCallModel = (kind) => async (content, attempt) => {
@@ -633,7 +593,7 @@ export async function draft({
633
593
  if (left.length) {
634
594
  look.dropped.push(...left);
635
595
  const lines = left.map((d) => leftRuleLine(d.fact));
636
- 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); }
637
597
  pageInfo.push(' You chose to leave these Not checked; never claim them as checked:', ...lines.map((x) => ` - ${x}`));
638
598
  }
639
599
  }
@@ -678,80 +638,137 @@ export async function draft({
678
638
  );
679
639
  }
680
640
  if (sheetLooks.length) pageExtras.sheetLooks = sheetLooks; // kept beside the page looks (src/authoring.js writes both into page-look.json)
681
- // 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
682
- // 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
683
- // (offerQuestions false) makes no call: it settles every rule against the person's picks instead.
684
- // 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
685
- const shapeRules = offerRules(lines, arbiter, [...look.facts, ...sheetFacts]);
686
- // 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.
687
- const carried = matchRecord(carriedPicks, lines, shapeRules);
688
- 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 }));
689
- onPickRecord?.({ picks: carried.kept.map((k) => k.entry), kept: keptView });
690
- const askRules = carried.askRules;
691
- /** @type {ReturnType<typeof checkAsks>} */
692
- let shapeAsks = [];
693
- if (askRules.length && offerQuestions) {
694
- const content = suggestUserText(lines, askRules);
695
- let args = null;
696
- 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) {
697
652
  const spentBefore = meterings.reduce((sum, ev) => sum + (ev.costUsd ?? roundCeiling), 0);
698
- if (spentBefore + ceilingCostUsd(rates, SUGGEST_SYSTEM.length + content.length + JSON.stringify(SUGGEST_SCHEMA).length) > budgetUsd) {
699
- if (meterings.length === 0 && calls === 0) { removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); return fail([tooSmall(roundCeiling)]); }
700
- 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') };
701
656
  }
702
657
  /** @type {any} */
703
658
  let captured;
704
659
  const roundEvents = [];
705
- 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' }); } };
706
- 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); } });
707
662
  calls += 1;
708
663
  book(true);
709
664
  let res;
710
665
  let threw = null;
711
666
  try {
712
- // thinking is off: on cannot combine with a forced tool call (the answer is one typed call, there is nothing to think through)
713
- 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 } });
714
668
  } catch (err) {
715
669
  threw = err;
716
670
  if (roundEvents.length === 0) unmetered += 1;
717
671
  }
718
672
  book(false);
719
- const entry = /** @type {Record<string, any>} */ ({ round: log.length + 1, kind: 'check-suggest' });
673
+ entry = /** @type {Record<string, any>} */ ({ round: log.length + 1, kind });
720
674
  if (res?.thinkingApplied !== undefined) entry.thinkingApplied = res.thinkingApplied;
721
675
  if (res?.thinkingStatus !== undefined) entry.thinkingStatus = res.thinkingStatus;
722
676
  if (threw && !(isPlainObject(captured) && threw instanceof HaltError)) {
723
677
  entry.outcome = `provider-red: ${threw.message}`;
724
678
  log.push(entry);
725
- return earlyStop([`provider-red: ${threw.message}`], 'provider-red');
679
+ return { early: earlyStop([`provider-red: ${threw.message}`], 'provider-red') };
726
680
  }
727
681
  if (!isPlainObject(captured)) {
728
- // 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)
729
- 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
730
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)';
731
685
  if (typeof malformed?.rawArguments === 'string') entry.rawArguments = malformed.rawArguments;
732
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
+ }
733
694
  log.push(entry);
734
695
  continue;
735
696
  }
736
697
  entry.outcome = 'answered';
737
698
  entry.args = captured;
738
699
  log.push(entry);
739
- args = captured;
700
+ return { args: captured, entry };
740
701
  }
741
- 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();
742
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));
743
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
744
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.
745
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.
746
- if ((pageSources.length || sheetAsks.length || shapeAsks.length) && offerQuestions) {
747
- const pageAsks = pageSources.length ? askableFromLook({ facts: [...look.facts, ...sheetFacts] }, jobLines.filter((l) => !askLines.has(l.n))) : [];
748
- 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')];
749
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).
750
- const asks = [...lookAsks, ...shapeAsks];
766
+ const blockShape = blockAsks.filter((a) => a.ask === 'no-check' || a.ask === 'check');
767
+ const asks = [...lookAsks, ...shapeAsks, ...blockShape];
751
768
  if (asks.length > 0) {
752
769
  const m = sumMeterings(meterings);
753
770
  const spent = m.costUsd === null || unmetered > 0 ? (m.costUsd === null ? 'unknown' : `at least ${usdText(m.costUsd)}`) : usdText(m.costUsd);
754
- 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" }))];
755
772
  const tooMany = counted.length > MAX_LOOK_ASKS;
756
773
  if (tooMany && pageSources.length) removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); // a refused draft keeps no page copy
757
774
  return {
@@ -767,14 +784,42 @@ export async function draft({
767
784
  // (shown on the plan card and carried as `unjudgeable`); the drafter writes no check of its own, whatever it sends is overwritten below.
768
785
  const allPicks = [...checkPicks, ...carried.picks];
769
786
  const allLeft = [...leftRules, ...carried.left];
770
- const settled = shapeRules.length ? settleRules(shapeRules, allPicks, allLeft) : null;
771
- // the record this draft hands on: what it kept plus what the person just answered (numbered on this card)
772
- 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 });
773
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})` : '');
774
793
  for (const n of settled?.notes ?? []) {
775
794
  const line = (n.reason === 'person-left' ? leftRuleLine(n.text) : pickNoteLine(n.text, n.reason)) + keptNote(n);
795
+ personNotChecked.add(line);
776
796
  if (!pageNotChecked.includes(line)) pageNotChecked.push(line);
777
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
+ }
778
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.
779
824
  const factsBase = pageInfo.length ? [...facts.info.filter((l) => !pageSources.some((s) => l.startsWith(`- ${s.role}: a web page`))), ...pageInfo] : facts.info;
780
825
  const factsInfo = [...factsBase, ...ticketSources.flatMap((s) => ticketFactsLines(s.role)), ...(flowType === 'mcp' ? mcpFactsLines(mcp.server, mcp.tools) : [])];
@@ -782,7 +827,7 @@ export async function draft({
782
827
  // `notChecked` is offered on every try (information, not asking); `questions` only on try 3 (below).
783
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
784
829
  const sheetTables = Object.keys(facts.sheets ?? {}).length ? Object.fromEntries(Object.entries(facts.sheets).map(([role, t]) => [role, sheetTable(parseCsv(t))])) : undefined;
785
- const baseSystem = buildSystemPrompt({ menu, lines, arbiter, factsInfo });
830
+ const baseSystem = buildSystemPrompt({ menu, lines, arbiter, factsInfo, blockLines: blockLineNums });
786
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).
787
832
  // Absent or empty: the prompt is byte-identical to what it was.
788
833
  const system = `${baseSystem}\n\n${NOTCHECKED_PROMPT}${learnHints?.text ? `\n\n${learnHints.text}` : ''}`;
@@ -795,7 +840,7 @@ export async function draft({
795
840
  let validatorReds = []; // the last validator refusal; a structure retry after a revision must not drop it
796
841
  let stop = null;
797
842
  let failedLines = []; // the job lines try 2's reds named: a question is kept only about one of these (amendment 25)
798
- /** @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'>}} */
799
844
  let extras = { questions: [], droppedQuestions: [], notChecked: pageNotChecked }; // from the round that produced `lastDecl`, never an earlier one
800
845
 
801
846
  for (;;) {
@@ -851,15 +896,9 @@ export async function draft({
851
896
  break;
852
897
  }
853
898
 
854
- if (!isPlainObject(captured)) {
855
- const malformed = provider?.lastMalformedToolCall ?? null;
856
- const why = result?.stopReason === 'max_tokens' ? 'truncated: the round hit the output cap with no completed tool call'
857
- : malformed ? `the tool call's arguments were not valid JSON (${malformed.error})`
858
- : 'no usable tool call (text instead of the tool)';
899
+ // M4d am39: a structure failure is handled by one function, so a brace repair that the validator then refuses takes the very same path.
900
+ const structureFailure = (/** @type {string} */ why) => {
859
901
  entry.outcome = `structure: ${why}`;
860
- // the raw answer is kept (log.json): the unparseable arguments as sent, else the model's text
861
- if (typeof malformed?.rawArguments === 'string') entry.rawArguments = malformed.rawArguments;
862
- else if (typeof result?.text === 'string' && result.text !== '') entry.rawText = result.text;
863
902
  log.push(entry);
864
903
  lastReds = [why];
865
904
  // M4d am3 A3: a round cut off at the output cap before tries 1 and 2 are spent is a FAILED TRY, advancing the same counter a
@@ -873,15 +912,36 @@ export async function draft({
873
912
  failedLines = lineNums;
874
913
  userText += `\n\n${QUESTIONS_PROMPT}`;
875
914
  }
876
- continue;
915
+ return 'continue';
877
916
  }
878
- if (structureRetries >= MAX_STRUCTURE_RETRIES) { stop = 'structure'; break; }
917
+ if (structureRetries >= MAX_STRUCTURE_RETRIES) { stop = 'structure'; return 'break'; }
879
918
  structureRetries += 1;
880
919
  nextKind = 'structure-retry';
881
920
  userText = `Your last reply was not a usable tool call (${why}). Call ${TOOL} now with a complete, valid JSON declaration.`;
882
921
  if (validatorReds.length) userText += `\n\nThe last declaration you emitted was still refused by the validator; keep fixing these too:\n${validatorReds.map((r) => `- ${r}`).join('\n')}`;
883
922
  if (askOpen) userText += `\n\n${QUESTIONS_PROMPT}`;
884
- continue;
923
+ return 'continue';
924
+ };
925
+ /** @type {string | null} the structure reason, kept while a brace-repaired answer waits for the validator */
926
+ let braceWhy = null;
927
+ if (!isPlainObject(captured)) {
928
+ const malformed = provider?.lastMalformedToolCall ?? null;
929
+ const why = result?.stopReason === 'max_tokens' ? 'truncated: the round hit the output cap with no completed tool call'
930
+ : malformed ? `the tool call's arguments were not valid JSON (${malformed.error})`
931
+ : 'no usable tool call (text instead of the tool)';
932
+ // the raw answer is kept (log.json): the unparseable arguments as sent, else the model's text
933
+ if (typeof malformed?.rawArguments === 'string') entry.rawArguments = malformed.rawArguments;
934
+ else if (typeof result?.text === 'string' && result.text !== '') entry.rawText = result.text;
935
+ // M4d am39: only a malformed-JSON round (never a cut-off, never text) whose answer is a complete object plus trailing `}` is repaired
936
+ const fixed = malformed && result?.stopReason !== 'max_tokens' ? repairTrailingBraces(malformed.rawArguments) : null;
937
+ if (!fixed) {
938
+ const next = structureFailure(why);
939
+ if (next === 'break') break;
940
+ continue;
941
+ }
942
+ captured = fixed.value;
943
+ braceWhy = why;
944
+ entry.braceRepair = { dropped: fixed.dropped, used: true };
885
945
  }
886
946
 
887
947
  // `notChecked` was offered on every try, so it is information and never reaches the validator. `questions` is stripped only where it was
@@ -910,33 +970,83 @@ export async function draft({
910
970
  });
911
971
  }
912
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
913
- 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
+ }
914
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
915
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 }); }
916
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
917
- 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) : [])]);
918
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;
919
1003
  const verdict1 = validateDeclaration(declaration, {
920
1004
  arbiter, lines, catalogue: validationCatalogue, wired: WIRED_VERBS, verbatimGoals: true, fitJobLine: true,
921
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
922
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,
923
- 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) },
924
1008
  });
925
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)
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
1011
+ if (braceWhy !== null && !verdict1.ok && verdict1.reds.some((r) => /unknown key/.test(r))) {
1012
+ entry.braceRepair = { ...entry.braceRepair, used: false };
1013
+ delete entry.retention;
1014
+ const next = structureFailure(braceWhy);
1015
+ if (next === 'break') break;
1016
+ continue;
1017
+ }
926
1018
  const planRed = verdict1.ok ? findMcpPlanRed(declaration) : null;
927
- const verdict = planRed ? { ok: false, reds: [planRed] } : verdict1;
1019
+ // M10b am5: a `table` check that already fails on the sheet this draft was made with is a red ($0: bareguard's checkStep on the draft-time table, no model call)
1020
+ const tableReds = verdict1.ok && sheetTables ? await tableChecksFailingOnInput(declaration, sheetTables) : [];
1021
+ const verdict = planRed ? { ok: false, reds: [planRed] } : tableReds.length ? { ok: false, reds: tableReds } : verdict1;
928
1022
  lastDecl = declaration;
929
1023
  const asked = askOpen ? normalizeQuestions(rawQuestions, failedLines) : { kept: [], dropped: [] };
930
- 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 } } : {}) };
931
1031
  if (asked.dropped.length) entry.droppedQuestions = asked.dropped;
932
1032
  // the declaration the model sent, as parsed, before any code overwrite (log.json keeps it per try)
933
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
+ }
934
1044
  if (verdict.ok) {
935
1045
  entry.outcome = 'valid';
936
1046
  log.push(entry);
937
1047
  const m = sumMeterings(meterings);
938
1048
  return {
939
- 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) } : {}),
940
1050
  };
941
1051
  }
942
1052
  lastReds = [...verdict.reds];