fwdloop 0.32.0 → 0.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/bin/fwdloop +20 -2
  2. package/package.json +2 -2
  3. package/src/auditchecks.js +55 -0
  4. package/src/authoring.js +53 -12
  5. package/src/blockasks.js +45 -0
  6. package/src/blockassemble.js +159 -0
  7. package/src/blockdraft.js +86 -0
  8. package/src/blocklines.js +30 -0
  9. package/src/blockpick.js +175 -0
  10. package/src/cardlist.js +19 -0
  11. package/src/checkblock.js +843 -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/checkpick.js +7 -73
  16. package/src/checkwords.js +20 -1
  17. package/src/cited-record.js +21 -1
  18. package/src/citedcheck.js +162 -7
  19. package/src/closers.js +41 -3
  20. package/src/declaration.js +34 -9
  21. package/src/declaredclose.js +4 -0
  22. package/src/draft-steps.js +3 -1
  23. package/src/drafter.js +311 -206
  24. package/src/factwords.js +112 -0
  25. package/src/inputlook.js +53 -0
  26. package/src/labelscan.js +162 -0
  27. package/src/noteask.js +62 -0
  28. package/src/pageask.js +9 -69
  29. package/src/pagedropwords.js +11 -1
  30. package/src/pagedry.js +27 -4
  31. package/src/pagerules.js +19 -3
  32. package/src/panel/author.js +76 -7
  33. package/src/panel/authorcard.js +43 -17
  34. package/src/panel/data.js +41 -9
  35. package/src/panel/index.html +208 -13
  36. package/src/panel/result.js +4 -3
  37. package/src/panel/server.js +3 -1
  38. package/src/pickrecord.js +70 -54
  39. package/src/placerule.js +398 -0
  40. package/src/planrebuild.js +216 -0
  41. package/src/rowedit.js +148 -0
  42. package/src/rubricstep.js +272 -0
  43. package/src/runfile.js +4 -2
  44. package/src/runner.js +67 -10
  45. package/src/setup.js +11 -5
  46. package/src/sheetblock.js +22 -8
  47. package/src/sheetbuild.js +151 -0
  48. package/src/sheetchecks.js +52 -66
  49. package/src/sheetclaims.js +12 -32
  50. package/src/sheetfind.js +4 -4
  51. package/src/sheetlook.js +14 -3
  52. package/src/sheetoffer.js +74 -57
  53. package/src/sheetrows.js +123 -0
  54. package/src/sheetrun.js +13 -10
  55. package/src/summary-words.js +3 -3
  56. package/src/ticket-draft.js +4 -21
  57. package/src/ticketrows.js +100 -0
  58. package/src/try-checks.js +31 -12
  59. package/src/types.js +1 -0
  60. package/types/auditchecks.d.ts +25 -0
  61. package/types/authoring.d.ts +21 -2
  62. package/types/blockasks.d.ts +36 -0
  63. package/types/blockassemble.d.ts +50 -0
  64. package/types/blockdraft.d.ts +75 -0
  65. package/types/blocklines.d.ts +31 -0
  66. package/types/blockpick.d.ts +46 -0
  67. package/types/cardlist.d.ts +21 -0
  68. package/types/checkblock.d.ts +378 -0
  69. package/types/checked.d.ts +16 -2
  70. package/types/checklist.d.ts +115 -0
  71. package/types/checklistsign.d.ts +27 -0
  72. package/types/checkpick.d.ts +4 -34
  73. package/types/checkwords.d.ts +5 -0
  74. package/types/cited-record.d.ts +9 -0
  75. package/types/citedcheck.d.ts +33 -2
  76. package/types/closers.d.ts +24 -2
  77. package/types/declaration.d.ts +7 -0
  78. package/types/declaredclose.d.ts +2 -0
  79. package/types/drafter.d.ts +29 -715
  80. package/types/factwords.d.ts +38 -0
  81. package/types/inputlook.d.ts +49 -0
  82. package/types/labelscan.d.ts +35 -0
  83. package/types/noteask.d.ts +52 -0
  84. package/types/pageask.d.ts +2 -35
  85. package/types/pagedry.d.ts +13 -0
  86. package/types/pagerules.d.ts +7 -0
  87. package/types/panel/author.d.ts +41 -0
  88. package/types/panel/authorcard.d.ts +14 -9
  89. package/types/panel/authorflows.d.ts +4 -4
  90. package/types/panel/data.d.ts +5 -3
  91. package/types/panel/jobgrid.d.ts +1 -1
  92. package/types/pickrecord.d.ts +69 -13
  93. package/types/placerule.d.ts +208 -0
  94. package/types/planrebuild.d.ts +52 -0
  95. package/types/provider.d.ts +1 -1
  96. package/types/rowedit.d.ts +48 -0
  97. package/types/rubricstep.d.ts +63 -0
  98. package/types/runfile.d.ts +5 -2
  99. package/types/runner.d.ts +45 -1
  100. package/types/sheetblock.d.ts +12 -4
  101. package/types/sheetbuild.d.ts +84 -0
  102. package/types/sheetchecks.d.ts +12 -18
  103. package/types/sheetclaims.d.ts +2 -1
  104. package/types/sheetfind.d.ts +2 -2
  105. package/types/sheetoffer.d.ts +31 -6
  106. package/types/sheetrows.d.ts +81 -0
  107. package/types/sheetrun.d.ts +4 -4
  108. package/types/summary-words.d.ts +2 -1
  109. package/types/ticket-draft.d.ts +3 -49
  110. package/types/ticketrows.d.ts +61 -0
  111. package/types/try-checks.d.ts +4 -2
  112. package/types/types.d.ts +8 -0
  113. package/src/repairs.js +0 -38
  114. package/types/repairs.d.ts +0 -13
package/src/drafter.js CHANGED
@@ -22,7 +22,6 @@ 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';
26
25
  import { WIRED_VERBS, wiredMenu } from './primitives.js';
27
26
  import { ticketSourcesOf, ticketFactsLines, mcpFactsLines, ticketSchemaParts, ticketReds, userMcpServers } from './ticket-draft.js';
28
27
  import { readInputFacts } from './input-facts.js';
@@ -30,21 +29,32 @@ import { freezePage } from './runner.js';
30
29
  import { removeFrozenPages } from './flow.js';
31
30
  import { lookAtPage, pageInfoLines } from './pagelook.js';
32
31
  import { lookAtSheet, sheetPrompt } from './sheetlook.js';
33
- import { leftRuleLine, dropRows, dropLine, dropSentence, pickNoteLine } from './pagedropwords.js';
32
+ import { leftRuleLine, dropRows, dropLine } from './pagedropwords.js';
34
33
  import {
35
- offerRules, rowsFromAnswer, checkAsks, settleRules, applyPicks, retentionOf, SUGGEST_SYSTEM, SUGGEST_TOOL, SUGGEST_SCHEMA, suggestUserText,
34
+ offerRules, rowsFromAnswer, retentionOf, SUGGEST_SYSTEM, SUGGEST_TOOL, SUGGEST_SCHEMA, suggestUserText, codeScope,
36
35
  } from './checkpick.js';
37
- import { matchRecord, entriesFromAnswers, sameWords, KEPT_WORDS } from './pickrecord.js';
36
+ // M16 (docs/wiki/the-module-ladder.md, "M16"): the check block's turns, wired beside the declaration path
37
+ import { blockJobLines } from './blocklines.js';
38
+ import { setUpBlock, ticketLeaveOut, pickEdits, ledgerEdits, repairedEditsReadable, editRecord, renderRejectBlock, buildFaultWords, isBuildFault } from './blockdraft.js';
39
+ import { assembleFromBlock, closeUnbuiltSheetSteps } from './blockassemble.js';
40
+ import { cardOfBlock } from './cardlist.js';
41
+ import { questionsOfBlock } from './blockasks.js';
42
+ import { NOTE_KIND, NOTE_TOOL, NOTE_SYSTEM, NOTE_SCHEMA, notePrompt, noteAnswers } from './noteask.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, ticketFilterBlock } from './rowedit.js';
45
+ import { matchRecord, entriesFromAnswers, columnEntries, columnsOnLines } from './pickrecord.js';
38
46
  import { MAP_SYSTEM, mapPrompt } from './pagemap.js';
39
- import { askableFromLook, tooManyAsksText, MAX_LOOK_ASKS } from './pageask.js';
47
+ import { tooManyAsksText, MAX_LOOK_ASKS } from './pageask.js';
40
48
  import { lineRules } from './pagebits.js';
41
49
  import { isCountGuardrail } from './declaration.js';
42
- import { repairDeclaration } from './repairs.js';
43
50
  import path from 'node:path';
44
51
  import { isCellsPath } from './closers.js';
45
52
  import { parseCsv, sheetTable } from './csv.js';
46
- import { sheetChecksProp, sheetOfferRules } from './sheetoffer.js';
47
- import { uncoveredRules } from './sheetblock.js';
53
+ import { sheetSuggestProp, sheetOfferRules, agreedColumnWords } from './sheetoffer.js';
54
+ import { uncoveredRules, csvRolesOf } from './sheetblock.js';
55
+ import { withSheetRows, withSheetCard, sheetChoice, keyOfSameCheck } from './sheetrows.js';
56
+ import { buildSheetChecks } from './sheetbuild.js';
57
+ import { TICKET_FIELDS, ticketRuleField, proposalReds, withTicketRows } from './ticketrows.js';
48
58
  import {
49
59
  makeProvider, ModelRefusal, sumMeterings, ceilingCostUsd, priceRecord,
50
60
  } from './provider.js';
@@ -64,7 +74,7 @@ export const CLASSES = Object.freeze(['green', 'softgreen', 'hitl']);
64
74
  export const WHOLE_OUTPUT_CEILING_RULE = "use the guardrail's ceiling for the whole output";
65
75
 
66
76
  /** @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);
77
+ 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
78
 
69
79
  /** the document inputs a quote can come from (M10 piece 5, item 2) */
70
80
  const DOC_EXTS = Object.freeze(['.docx', '.md', '.txt']);
@@ -86,58 +96,13 @@ const COLUMNS_PROP = Object.freeze({
86
96
  },
87
97
  });
88
98
 
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
99
  /**
134
- * 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
- * `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.
100
+ * The forced tool's parameter schema. `menu` = wiredMenu(). M17 am2: the AI is offered no `close.sheet` (it suggests sheet checks on the row-edit reply, src/rowedit.js; code builds them, src/sheetbuild.js).
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.
137
- * @param {any[]} menu @param {{sheets?: Record<string, {header: string[]}>, ticket?: {flowType: 'mcp'|'tickets', tools: string[]}}} [o]
102
+ * M16 item 5: the AI is offered no `close.cited` (the list owns the facts; code builds them from its rows).
103
+ * @param {any[]} menu @param {{ticket?: {flowType: 'mcp'|'tickets', tools: string[]}}} [o]
138
104
  */
139
- export function buildDeclarationSchema(menu, { sheets, ticket } = {}) {
140
- const sheetProp = sheets ? sheetChecksProp(sheets) : null;
105
+ export function buildDeclarationSchema(menu, { ticket } = {}) {
141
106
  const ticketParts = ticket ? ticketSchemaParts(ticket) : null;
142
107
  return {
143
108
  type: 'object',
@@ -166,9 +131,7 @@ export function buildDeclarationSchema(menu, { sheets, ticket } = {}) {
166
131
  type: 'object',
167
132
  properties: {
168
133
  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
134
  columns: COLUMNS_PROP,
171
- ...(sheetProp ? { sheet: sheetProp } : {}),
172
135
  },
173
136
  required: ['class'],
174
137
  additionalProperties: false,
@@ -184,11 +147,6 @@ export function buildDeclarationSchema(menu, { sheets, ticket } = {}) {
184
147
  additionalProperties: { type: 'string', enum: [...CLASSES] },
185
148
  description: 'one class per job line that HAS a guardrail, keyed by line number as a string',
186
149
  },
187
- unjudgeable: {
188
- type: 'object',
189
- additionalProperties: { type: 'string' },
190
- description: 'line number -> reason, only for a guardrail whose wording resisted judgment (its class stays hitl); {} if none',
191
- },
192
150
  refused: {
193
151
  type: 'array',
194
152
  items: {
@@ -200,33 +158,17 @@ export function buildDeclarationSchema(menu, { sheets, ticket } = {}) {
200
158
  description: 'job lines that cannot be served at all, with a reason; [] if none',
201
159
  },
202
160
  },
203
- required: ['steps', 'guardrailClasses', 'unjudgeable', 'refused'],
161
+ required: ['steps', 'guardrailClasses', 'refused'],
204
162
  additionalProperties: false,
205
163
  };
206
164
  }
207
165
 
208
166
  const TOOL = 'emit_declaration';
209
167
 
210
- // ---- M4e amendments 24 + 25: questions (try 3 only) and "not checked" (every try) ---------------------------------
168
+ // ---- M4e amendments 24 + 25: questions (try 3 only); the AI's own "not checked" notes are gone (M17 am4, C1) ---------------------------------
211
169
  // borrowed-from: fwdloop poc/am24-questions/draft.mjs@dda0e0f (prompts, linesNamedByReds, normalizeQuestions), adjusted to the product drafter.
212
170
  export const MAX_QUESTIONS = 2;
213
171
 
214
- /** What fwdloop's typed checks can really check (bareloop F174: give the model the real list, or "Not checked" is invented). */
215
- export const CHECKABLE = Object.freeze([
216
- 'green: a sheet figure is recomputed by bareguard from the saved sheet',
217
- 'softgreen: the output carries named section headings (sections), in order',
218
- `softgreen: a word ceiling for the whole output (maxWords; ${WHOLE_OUTPUT_CEILING_RULE}) and per section (wordsPerSection)`,
219
- 'softgreen: a line count per invoice (linesPerInvoice) and fields every line must carry (mustCarry)',
220
- 'hitl: a human accepts or reviews at a signed ask — the machine checks only that the step happened',
221
- ]);
222
-
223
- /** Offered on EVERY try (it is information, not asking). */
224
- export const NOTCHECKED_PROMPT = [
225
- 'notChecked (optional): a short list of things about the job that no check below will verify. These are the ONLY things fwdloop can check:',
226
- ...CHECKABLE.map((c) => `- ${c}`),
227
- 'Anything the job asks for beyond those (tone, correctness of prose, completeness, matching a taste) is NOT checked: list it in "notChecked", a plain short phrase each. [] or leave out if nothing.',
228
- ].join('\n');
229
-
230
172
  /** Try 3 only, and only after tries 1 and 2 both failed validation. No digit and no number word anywhere (a test greps this): the machine, not the prompt, bounds the count. */
231
173
  export const QUESTIONS_PROMPT = [
232
174
  'You may add "questions" to this reply. Ask only about a job line named in the refusals above, and only if that line cannot be drafted without the answer',
@@ -235,11 +177,12 @@ export const QUESTIONS_PROMPT = [
235
177
  'Still emit the complete corrected declaration.',
236
178
  ].join('\n');
237
179
 
238
- /** The declaration schema plus the optional `notChecked` (every try) and, on try 3 only, `questions`. Neither is in `required`. */
239
- /** @param {any[]} menu @param {{questions?: boolean, sheets?: Record<string, {header: string[]}>|undefined, ticket?: {flowType: 'mcp'|'tickets', tools: string[]}}} [o] */
240
- export function buildRoundSchema(menu, { questions = false, sheets = undefined, ticket = undefined } = {}) {
241
- const s = buildDeclarationSchema(menu, { sheets, ticket });
242
- const extra = { notChecked: { type: 'array', items: { type: 'string' }, description: 'what the job asks for that no typed check verifies' } };
180
+ /** The declaration schema plus, on try 3 only, `questions` (not in `required`). */
181
+ /** @param {any[]} menu @param {{questions?: boolean, ticket?: {flowType: 'mcp'|'tickets', tools: string[]}}} [o] */
182
+ export function buildRoundSchema(menu, { questions = false, ticket = undefined } = {}) {
183
+ const s = buildDeclarationSchema(menu, { ticket });
184
+ /** @type {Record<string, any>} */
185
+ const extra = {};
243
186
  if (questions) {
244
187
  extra.questions = {
245
188
  type: 'array',
@@ -291,22 +234,19 @@ export function normalizeQuestions(raw, failedLines) {
291
234
  return { kept, dropped };
292
235
  }
293
236
 
294
- /** `notChecked` as the model sent it: non-blank strings only, trimmed. Anything else is an empty list. */
295
- function cleanNotChecked(raw) {
296
- return Array.isArray(raw) ? raw.filter((x) => typeof x === 'string' && x.trim() !== '').map((x) => x.trim()) : [];
297
- }
298
-
299
237
  // 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('; ');
238
+ // 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)
239
+ const shownRules = (/** @type {string} */ guardrail, all = false) => lineRules({ rule: guardrail }).filter((r) => all || !isCountGuardrail(r)).join('; ');
301
240
 
302
241
  /**
303
242
  * 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
243
+ * @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
244
  */
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('; ') } : {}) }; });
245
+ export function hideCounts(jobLines, shown = /** @type {Set<number>} */ (new Set())) {
246
+ // M16 item 5: the lines the check block is given show their count rules to the look (`shown`); every other line is as before
247
+ 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
248
  const ruleMap = (/** @type {number} */ line, /** @type {number|undefined} */ vis) => {
309
- if (vis === undefined) return undefined;
249
+ if (vis === undefined || shown.has(line)) return vis;
310
250
  const orig = lineRules(jobLines.find((x) => x.n === line)).map((r, i) => ({ r, no: i + 1 })).filter((x) => !isCountGuardrail(x.r));
311
251
  return orig[vis - 1]?.no ?? vis;
312
252
  };
@@ -314,11 +254,11 @@ export function hideCounts(jobLines) {
314
254
  return { seenLines, toOriginal };
315
255
  }
316
256
 
317
- function jobLinesText(lines, asks) {
257
+ function jobLinesText(lines, asks, blockLines = /** @type {Set<number>} */ (new Set())) {
318
258
  const askLines = new Set(asks.map((a) => a.line));
319
259
  return lines
320
260
  .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]'}`)
261
+ + `${l.guardrail && shownRules(l.guardrail, blockLines.has(l.n)) ? ` [guardrail: ${shownRules(l.guardrail, blockLines.has(l.n))}]` : ' [no guardrail]'}`)
322
262
  .join('\n');
323
263
  }
324
264
 
@@ -326,29 +266,14 @@ function jobLinesText(lines, asks) {
326
266
  * 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
267
  function greenReadRule(sources) {
328
268
  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
269
  // M10 piece 5 (item 2): a quote in a doc - a .docx / .md / .txt input is quoted the way a page is
331
270
  const docRoles = docRolesOf(sources);
332
271
  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
272
  const out = [csvRoles.length
334
273
  ? `${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
- }
339
- 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
- }
274
+ : `${rule} This job signs no CSV input, so a guardrail that needs a sheet check cannot be classed green here: class it "hitl".`];
275
+ // M16 S5: the check block builds the quote checks of its lines; the drafter is told nothing of close.cited and offers none
276
+ 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.`);
352
277
  return out;
353
278
  }
354
279
 
@@ -367,15 +292,7 @@ function whenToUse(menu) {
367
292
  return Object.entries(WHEN_TO_USE).filter(([verb]) => on.has(verb)).map(([, line]) => line);
368
293
  }
369
294
 
370
- /** M10b piece 3: with a CSV input, the guardrail rules of each line by number (the numbers `covers` names), in the order the validator counts them. Otherwise nothing. */
371
- function sheetRuleNumbers(lines, arbiter) {
372
- const csvRoles = (arbiter.sources ?? []).filter((s) => s.kind === 'file' && isCellsPath(s.path));
373
- if (csvRoles.length === 0) return [];
374
- const rows = lines.map((l) => ({ n: l.n, rules: lineRules(l.guardrail ? { rule: l.guardrail } : {}).map((r, i) => ({ r, no: i + 1 })).filter((x) => !isCountGuardrail(x.r)) })).filter((x) => x.rules.length > 0);
375
- 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
- }
377
-
378
- export function buildSystemPrompt({ menu, lines, arbiter, factsInfo }) {
295
+ export function buildSystemPrompt({ menu, lines, arbiter, factsInfo, blockLines = /** @type {Set<number>} */ (new Set()) }) {
379
296
  const askLines = arbiter.asks.map((a) => a.line);
380
297
  const sendLines = arbiter.sends.map((s) => s.line);
381
298
  return [
@@ -404,8 +321,7 @@ export function buildSystemPrompt({ menu, lines, arbiter, factsInfo }) {
404
321
  ...(factsInfo.length ? factsInfo : ['- (none)']),
405
322
  '',
406
323
  'The numbered job lines:',
407
- jobLinesText(lines, arbiter.asks),
408
- ...sheetRuleNumbers(lines, arbiter),
324
+ jobLinesText(lines, arbiter.asks, blockLines),
409
325
  ].join('\n');
410
326
  }
411
327
 
@@ -439,17 +355,17 @@ function isPlainObject(v) { return !!v && typeof v === 'object' && !Array.isArra
439
355
  * @returns {Promise<{ok:boolean, declaration:object|null, reds:string[], rounds:number, calls:number, spendComplete:boolean,
440
356
  * costUsd:number|null, modelReturned:string|null, modelId?:string, price?:object|null, tokens?:object|null, structureRetries:number, revisions:number, stop:string|null, log:object[],
441
357
  * 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[]}>}
358
+ * 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
359
  * `learnHints` (M8 item 5a): the earlier runs' notes block (src/learnstore.js hintsForRun), appended to the drafter's system prompt; null = nothing.
444
360
  * `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
361
  */
446
362
  export async function draft({
447
363
  proseText, slot, model, provider: injected, rates: injectedRates, modelId: injectedModelId, env,
448
364
  priorSpend = /** @type {((ceilingUsd: number) => number)|null} */ (null), skills = DRAFT_SKILLS, makeProviderFn = makeProvider, onBook, offerQuestions = true, draftThinking = /** @type {'on'|'off'} */ ('off'),
449
- draftDir = /** @type {string|null} */ (null), fetchPage = undefined, leftRules = /** @type {{line: number, rule: number}[]} */ ([]),
365
+ draftDir = /** @type {string|null} */ (null), fetchPage = undefined, leftRules = /** @type {{line: number, rule: number}[]} */ ([]), columnAnswers = /** @type {{line: number, word: string, column: string}[]} */ ([]), carriedColumns = /** @type {any[]} */ ([]), onColumns = /** @type {(rec: any[]) => void} */ (() => {}),
450
366
  checkPicks = /** @type {import('./checkpick.js').Pick[]} */ ([]),
451
367
  // 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),
368
+ 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
369
  learnHints = /** @type {{text: string, ids: string[]}|null} */ (null),
454
370
  mcpServers = /** @type {string[]|undefined} */ (undefined),
455
371
  // 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
@@ -565,7 +481,10 @@ export async function draft({
565
481
  let mapCut = null;
566
482
  const jobLines = lines.map((l) => ({ n: l.n, text: l.text, ...(l.guardrail ? { rule: l.guardrail } : {}) }));
567
483
  // 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);
484
+ // 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)
485
+ const askOrSend = new Set([...arbiter.asks.map((a) => a.line), ...arbiter.sends.map((x) => x.line)]);
486
+ const sheetPath = (arbiter.sources ?? []).some((s) => s.kind === 'file' && (isCellsPath(s.path) || String(s.path).toLowerCase().endsWith('.docx')));
487
+ const { seenLines, toOriginal } = hideCounts(jobLines, !sheetPath ? new Set(lineNums.filter((n) => !askOrSend.has(n))) : new Set());
569
488
  const pageInfo = [];
570
489
  /** 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
490
  const makeCallModel = (kind) => async (content, attempt) => {
@@ -635,7 +554,6 @@ export async function draft({
635
554
  if (left.length) {
636
555
  look.dropped.push(...left);
637
556
  const lines = left.map((d) => leftRuleLine(d.fact));
638
- for (const x of lines) if (!pageNotChecked.includes(x)) pageNotChecked.push(x);
639
557
  pageInfo.push(' You chose to leave these Not checked; never claim them as checked:', ...lines.map((x) => ` - ${x}`));
640
558
  }
641
559
  }
@@ -648,6 +566,9 @@ export async function draft({
648
566
  const docxRoles = (arbiter.sources ?? []).filter((s) => s.kind === 'file' && String(s.path).toLowerCase().endsWith('.docx') && Array.isArray(facts.inputFacts[s.role])).map((s) => s.role);
649
567
  const sheetRoles = sheetJobLines.some((l) => lineRules(l).length > 0) ? [...Object.keys(facts.sheets ?? {}), ...docxRoles] : [];
650
568
  /** @type {any[]} */
569
+ // M17 ruling 2: the columns the person agreed for a word (just now, or kept in the record from the last draft, tied to the line's words); such a word is never asked or declined again, and is told to the AI
570
+ const effColumns = [...columnAnswers, ...columnsOnLines(carriedColumns, lines).filter((c) => !columnAnswers.some((f) => f.line === c.line && f.word.toLowerCase() === c.word.toLowerCase()))];
571
+ onColumns(columnEntries(lines, effColumns));
651
572
  const sheetAsks = [];
652
573
  /** @type {any[]} */
653
574
  const sheetFacts = [];
@@ -667,11 +588,12 @@ export async function draft({
667
588
  };
668
589
  }
669
590
  // The redraft after the answers never asks: an offer the person's words did not take is Not checked, with that reason (never dropped silently).
670
- const declined = offerQuestions ? [] : got.asks.map((a) => ({ line: a.line, ...(a.rule === null ? {} : { rule: a.rule }), fact: a.word, reason: 'column-declined', other: `"${a.column}"`, source: role }));
591
+ const asksNow = got.asks.filter((a) => !effColumns.some((c) => c.line === a.line && c.word.toLowerCase() === a.word.toLowerCase()));
592
+ const declined = offerQuestions ? [] : asksNow.map((a) => ({ line: a.line, ...(a.rule === null ? {} : { rule: a.rule }), fact: a.word, reason: 'column-declined', other: `"${a.column}"`, source: role }));
671
593
  const dropped = [...got.dropped, ...declined];
672
- sheetAsks.push(...got.asks); // asked only when the asks block below is open (offerQuestions)
594
+ sheetAsks.push(...asksNow); // asked only when the asks block below is open (offerQuestions)
673
595
  sheetFacts.push(...got.facts);
674
- sheetLooks.push({ role, attempts: got.attempts, facts: got.facts, asks: got.asks.map((a) => ({ line: a.line, rule: a.rule, word: a.word, column: a.column })), dropped });
596
+ sheetLooks.push({ role, attempts: got.attempts, facts: got.facts, asks: asksNow.map((a) => ({ line: a.line, rule: a.rule, word: a.word, column: a.column })), dropped });
675
597
  const lost = dropRows(dropped).map((row) => dropLine(row, jobLines, lineRules));
676
598
  for (const l of lost) if (!pageNotChecked.includes(l)) pageNotChecked.push(l);
677
599
  pageInfo.push(
@@ -680,114 +602,215 @@ export async function draft({
680
602
  );
681
603
  }
682
604
  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) {
605
+ /**
606
+ * 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,
607
+ * 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.
608
+ * `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.
609
+ * 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).
610
+ * @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
611
+ */
612
+ const forcedTurn = async ({ kind, system: sys, messages, tool: spec, attempts = 2, repair = false, usable = () => true }) => {
613
+ /** @type {any} */
614
+ let entry = null;
615
+ for (let attempt = 1; attempt <= attempts; attempt += 1) {
699
616
  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');
617
+ if (spentBefore + ceilingCostUsd(rates, sys.length + messages.reduce((n, m) => n + m.content.length, 0) + JSON.stringify(spec.schema).length) > budgetUsd) {
618
+ if (meterings.length === 0 && calls === 0) { removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); return { early: fail([tooSmall(roundCeiling)]) }; }
619
+ return { early: earlyStop(['the draft budget is spent'], 'budget') };
703
620
  }
704
621
  /** @type {any} */
705
622
  let captured;
706
623
  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); } });
624
+ 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' }); } };
625
+ const forcedLoop = new Loop({ provider, rates, onLlmResult: async (ev) => { roundEvents.push(ev); meterings.push(ev); } });
709
626
  calls += 1;
710
627
  book(true);
711
628
  let res;
712
629
  let threw = null;
713
630
  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 } });
631
+ res = await forcedLoop.run([{ role: 'system', content: sys }, ...messages], [tool], { maxTokens: DRAFT_MAX_TOKENS, thinkingMode: 'off', toolChoice: { name: spec.name } });
716
632
  } catch (err) {
717
633
  threw = err;
718
634
  if (roundEvents.length === 0) unmetered += 1;
719
635
  }
720
636
  book(false);
721
- const entry = /** @type {Record<string, any>} */ ({ round: log.length + 1, kind: 'check-suggest' });
637
+ entry = /** @type {Record<string, any>} */ ({ round: log.length + 1, kind });
722
638
  if (res?.thinkingApplied !== undefined) entry.thinkingApplied = res.thinkingApplied;
723
639
  if (res?.thinkingStatus !== undefined) entry.thinkingStatus = res.thinkingStatus;
724
640
  if (threw && !(isPlainObject(captured) && threw instanceof HaltError)) {
725
641
  entry.outcome = `provider-red: ${threw.message}`;
726
642
  log.push(entry);
727
- return earlyStop([`provider-red: ${threw.message}`], 'provider-red');
643
+ return { early: earlyStop([`provider-red: ${threw.message}`], 'provider-red') };
728
644
  }
729
645
  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)';
646
+ // the raw answer is kept (log.json), the cut-off said out loud
732
647
  const malformed = provider?.lastMalformedToolCall ?? null;
648
+ 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
649
  if (typeof malformed?.rawArguments === 'string') entry.rawArguments = malformed.rawArguments;
734
650
  else if (typeof res?.text === 'string' && res.text !== '') entry.rawText = res.text;
651
+ // M4d am39: only a malformed-JSON round (never a cut-off, never text) whose answer is a complete object plus trailing `}` is repaired
652
+ const fixed = repair && malformed && res?.stopReason !== 'max_tokens' ? repairTrailingBraces(malformed.rawArguments) : null;
653
+ if (fixed) {
654
+ const ok = usable(fixed.value);
655
+ entry.braceRepair = { dropped: fixed.dropped, used: ok };
656
+ if (ok) { entry.outcome = 'answered'; entry.args = fixed.value; log.push(entry); return { args: fixed.value, entry }; }
657
+ }
735
658
  log.push(entry);
736
659
  continue;
737
660
  }
738
661
  entry.outcome = 'answered';
739
662
  entry.args = captured;
740
663
  log.push(entry);
741
- args = captured;
664
+ return { args: captured, entry };
742
665
  }
743
- shapeAsks = checkAsks(rowsFromAnswer(askRules, args));
666
+ return { args: null, entry };
667
+ };
668
+
669
+ // 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
670
+ // 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
671
+ // (offerQuestions false) makes no call: it settles every rule against the person's picks instead.
672
+ // 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
673
+ const shapeEverywhere = offerRules(lines, arbiter, [...look.facts, ...sheetFacts]);
674
+ // 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.
675
+ // 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)
676
+ const csvRuleLines = Object.keys(facts.sheets ?? {}).length ? jobLines.filter((l) => !askLines.has(l.n) && lineRules(l).some((r) => !isCountGuardrail(r))).map((l) => l.n) : [];
677
+ const blockPlan = blockJobLines(proseText, undefined, [...new Set([...sheetFacts.filter((f) => f.forRule !== undefined), ...sheetAsks, ...sheetLooks.flatMap((l) => l.dropped)].map((x) => x.line)), ...csvRuleLines]);
678
+ if (blockPlan && !blockPlan.ok) return fail(blockPlan.reds.map((r) => `signed-text: ${r}`));
679
+ const blockLineNums = new Set(blockPlan ? blockPlan.jobLines.map((l) => l.n) : []);
680
+ // M17 am4 (A3, B5): the list is the one place a shape rule is asked and picked; a line the list is not given (a sheet line) has no pick path of its own
681
+ const allShape = shapeEverywhere.filter((r) => blockLineNums.has(r.line));
682
+ // 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.
683
+ const carried = matchRecord(carriedPicks, lines, allShape);
684
+ const keptView = carried.kept.map((k) => ({ line: k.line, rule: k.rule, ruleText: k.entry.ruleText, check: k.entry.check, left: k.entry.left }));
685
+ onPickRecord?.({ picks: carried.kept.map((k) => k.entry), kept: keptView });
686
+ const askRules = carried.askRules;
687
+ /** the block (M16 S1): the person's rules, the look, the picks kept and just answered, reconciled once */
688
+ /** @type {import('./checkblock.js').CheckBlock|null} */
689
+ let block = null;
690
+ if (blockPlan?.ok) {
691
+ const inBlock = (/** @type {{line: number}} */ x) => blockLineNums.has(x.line);
692
+ block = setUpBlock({
693
+ texts: { ...(facts.docs ?? {}), ...Object.fromEntries(Object.entries(pages).map(([role, pg]) => [role, pg.text])) }, jobLines: blockPlan.jobLines, look,
694
+ kept: { picks: carried.picks.filter(inBlock), left: carried.left.filter(inBlock), askRules: carried.askRules.filter(inBlock) },
695
+ fresh: { picks: checkPicks.filter(inBlock), left: leftRules.filter(inBlock) }, asks: offerQuestions, countScope: (t) => codeScope(arbiter.sources, t) === 'in', leaveOut: ticketLeaveOut(flowType, blockPlan.jobLines),
696
+ });
697
+ }
698
+ if (askRules.length && offerQuestions) {
699
+ const content = suggestUserText(lines, askRules);
700
+ 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 } });
701
+ if (got.early) return got.early;
702
+ const sugRows = rowsFromAnswer(askRules, got.args);
703
+ // M16 S2 (R1): a kept check is a `pick` edit of the block, before any asks
704
+ if (block) { block.applyDelta({ label: 'pre:check-suggest', pre: true, edits: pickEdits(sugRows, blockLineNums) }); block.reconcile(); }
744
705
  }
706
+ if (block && blockPlan?.ok && blockPlan.jobLines.length > 0 && Object.keys(block.texts).length > 0) {
707
+ const texts = block.texts;
708
+ // 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
709
+ 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 } });
710
+ if (lg.early) return lg.early;
711
+ block.applyDelta({ label: 'pre:ledger-suggest', pre: true, edits: ledgerEdits(lg.args?.extra) });
712
+ block.reconcile();
713
+ }
714
+ // borrowed-from: bareloop src/authorjob.js@v0.56.0 (3383cce)
715
+ // a Revise keeps the last draft's Drop/Add choices (the suggestions exist now); code still judges every one when the list is reconciled
716
+ if (block && Array.isArray(carriedChoices)) { block.carryChoices(carriedChoices); onChoices(block.choicesRecord()); block.reconcile(); }
717
+ /** the questions of the block, merged below with the sheet's and the look's own, under one cap (M16 S3) */
718
+ const blockAsks = block && offerQuestions ? questionsOfBlock(block, allShape) : [];
719
+ if (block) pageExtras.checkRows = ledgerRecord(/** @type {any} */ (block.rows));
745
720
  // 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
721
  // 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
722
  // 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')];
723
+ if ((sheetAsks.length || blockAsks.length) && offerQuestions) {
724
+ // M17 am4 (A1): a question comes from the list (questionsOfBlock) or is the sheet's column offer (M17 am1 1(a)); no question is asked outside the list
725
+ const lookAsks = [...[...sheetAsks, ...blockAsks.filter((a) => a.ask === 'reading')].sort((a, b) => a.line - b.line), ...blockAsks.filter((a) => a.ask === 'cant-check')];
751
726
  // 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];
727
+ const blockShape = blockAsks.filter((a) => a.ask === 'no-check' || a.ask === 'check');
728
+ const asks = [...lookAsks, ...blockShape];
753
729
  if (asks.length > 0) {
754
730
  const m = sumMeterings(meterings);
755
731
  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" }))];
732
+ const counted = [...lookAsks, ...blockShape.filter((a) => a.counted).map((a) => ({ ...a, reading: "I can't check this" }))];
757
733
  const tooMany = counted.length > MAX_LOOK_ASKS;
758
734
  if (tooMany && pageSources.length) removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); // a refused draft keeps no page copy
759
735
  return {
760
736
  ok: false, declaration: null, reds: tooMany ? [`${tooManyAsksText(counted)} Spent so far: ${spent}.`] : [], 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: 0, revisions: 0, stop: tooMany ? 'look-asks-too-many' : 'look-asks', log, thinking: thinkingOf(), inputs: facts.list,
761
737
  questions: tooMany ? [] : asks.map((a) => ({
762
- line: a.line, question: a.question, source: a.source, ask: a.ask, ruleNo: a.rule, ruleText: a.ruleText, proposal: a.reading ?? null, ...('check' in a && a.check ? { check: a.check } : {}), ...('pairRule' in a && typeof a.pairRule === 'number' ? { pairRule: a.pairRule } : {}),
738
+ line: a.line, question: a.question, source: a.source, ask: a.ask, ruleNo: a.rule, ruleText: a.ruleText, proposal: a.reading ?? null, ...('check' in a && a.check ? { check: a.check } : {}),
763
739
  })),
764
740
  droppedQuestions: [], notChecked: pageNotChecked, ...pageExtras,
765
741
  };
766
742
  }
767
743
  }
768
- // M10 am16 (4, 5): the plan carries only the checks the person picked. Every shape rule this call settles is either checked by a pick or Not checked with its reason
769
- // (shown on the plan card and carried as `unjudgeable`); the drafter writes no check of its own, whatever it sends is overwritten below.
770
- const allPicks = [...checkPicks, ...carried.picks];
771
- const allLeft = [...leftRules, ...carried.left];
772
- const settled = shapeRules.length ? settleRules(shapeRules, allPicks, allLeft) : null;
773
744
  // 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 });
775
- 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
- for (const n of settled?.notes ?? []) {
777
- const line = (n.reason === 'person-left' ? leftRuleLine(n.text) : pickNoteLine(n.text, n.reason)) + keptNote(n);
778
- if (!pageNotChecked.includes(line)) pageNotChecked.push(line);
745
+ onPickRecord?.({ picks: [...carried.kept.map((k) => k.entry), ...entriesFromAnswers(lines, allShape, checkPicks, leftRules)], kept: keptView });
746
+ // 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).
747
+ // 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")
748
+ // M10b piece 3: the drafting copy's table of each CSV input - the header the AI may pick from in its suggestions, the table bareguard's build and sign-time tests run over
749
+ const sheetTables = Object.keys(facts.sheets ?? {}).length ? Object.fromEntries(Object.entries(facts.sheets).map(([role, t]) => [role, sheetTable(parseCsv(t))])) : undefined;
750
+ /** M17 am2: the sheet checks the AI suggested on the row-edit reply (typed, each with its job line); code builds or refuses each (src/sheetbuild.js) @type {any[]} */
751
+ let sheetSuggested = [];
752
+ /** M17 am6: the Tickets filter and watch the AI suggested as an edit of the list: the last legal value of each, and what was refused (code proves each, src/ticketrows.js) @type {{ticketFilter?: any, ticketWatch?: any, refused: Record<string, string>}} */
753
+ const ticketProposal = { refused: {} };
754
+ const ticketRuleOnJob = flowType === 'tickets' && blockPlan?.ok === true && blockPlan.jobLines.some((l) => (l.rules ?? []).some((t) => ticketRuleField(t) !== null));
755
+ const sheetRoleList = sheetTables ? Object.keys(sheetTables) : [];
756
+ // the sheet lines: a line with `~` rules the list's own rows do not take (and no ask or send line); the AI names a sheet line by its job number, and only one of these
757
+ const sendLines = new Set(arbiter.sends.map((x) => x.line));
758
+ const sheetLineNums = sheetRoleList.length > 0 ? jobLines.filter((l) => !askLines.has(l.n) && !sendLines.has(l.n) && !blockLineNums.has(l.n) && lineRules(l).length > 0).map((l) => l.n) : [];
759
+ const sheetTurn = sheetLineNums.length > 0;
760
+ if (block && blockPlan?.ok && (blockPlan.jobLines.length > 0 || sheetTurn) && (Object.keys(block.texts).length > 0 || block.rows.some((r) => r.kind === 'rule') || ticketRuleOnJob || sheetTurn)) {
761
+ // M17 am2: with a CSV input the turn also shows the sheet lines and the sheets; the sheet checks come back as typed suggestions
762
+ const texts = { ...block.texts, ...(facts.sheets ?? {}) };
763
+ const shownLines = sheetTurn ? jobLines.filter((l) => blockLineNums.has(l.n) || sheetLineNums.includes(l.n)) : blockPlan.jobLines;
764
+ // 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
765
+ const lookReport = pageSources.length ? { prose: [], notFound: [], facts: look.facts, dropped: look.dropped } : null;
766
+ /** @type {{role: string, content: string}[]} */
767
+ let turn = [{ role: 'user', content: rowEditUserText({ jobLines: shownLines, look: lookReport, texts }) + (flowType === 'tickets' ? `\n\n${ticketFilterBlock()}` : '') + (sheetTurn ? `\n\nTHE SHEET CHECKS\n${sheetOfferRules(sheetRoleList, sheetLineNums).join('\n')}${effColumns.length ? `\n${effColumns.map((c) => agreedColumnWords(c)).join('\n')}` : ''}` : '') }];
768
+ const channel = rowEditChannel(flowType === 'tickets', sheetTurn ? sheetSuggestProp(sheetTables ?? {}, sheetLineNums) : null).tool({ calls: [] });
769
+ for (let rev = 0; ; rev += 1) {
770
+ const got = await forcedTurn({
771
+ kind: rev === 0 ? 'row-edit' : 'row-edit-revision', system: ROW_EDIT_SYSTEM, messages: turn, tool: { name: channel.name, description: channel.description, schema: channel.parameters },
772
+ attempts: 1 + MAX_STRUCTURE_RETRIES, repair: true, usable: repairedEditsReadable,
773
+ });
774
+ if (got.early) return got.early;
775
+ if (got.args === null) return earlyStop([String(got.entry?.outcome ?? 'structure').replace(/^structure: /, '')], 'structure');
776
+ for (const f of TICKET_FIELDS) {
777
+ if (flowType !== 'tickets' || got.args[f] === undefined) continue;
778
+ const reds = proposalReds(f, got.args[f]);
779
+ if (reds.length === 0) { ticketProposal[f] = got.args[f]; delete ticketProposal.refused[f]; } else ticketProposal.refused[f] = reds[0];
780
+ }
781
+ if (sheetTurn && Array.isArray(got.args.sheetChecks)) sheetSuggested = got.args.sheetChecks.filter((/** @type {any} */ x) => x && typeof x === 'object' && !Array.isArray(x));
782
+ const rec = block.applyDelta({ label: `row-edit-${rev + 1}`, edits: editsOf(got.args) });
783
+ block.reconcile();
784
+ got.entry.edits = editRecord(rec);
785
+ const refused = rec.edits.filter((e) => e.accepted !== true);
786
+ if (refused.length === 0 || rev >= MAX_REVISIONS) break;
787
+ 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}` }];
788
+ }
789
+ pageExtras.checkRows = ledgerRecord(/** @type {any} */ (block.rows));
790
+ }
791
+ // M17 am1 1(e): the note question, ONE forced turn, only when a line of the list is facts-only after the AI's edits (src/noteask.js). The typed answer goes to the block; code decides what it means.
792
+ // The answers ride the turn's log entry (`notes`), the one place the replay (src/planrebuild.js) reads them from, a failed turn included.
793
+ if (block && blockPlan?.ok) {
794
+ const asked = block.factOnlyLines();
795
+ if (asked.length > 0) {
796
+ const askedLines = blockPlan.jobLines.filter((l) => asked.includes(l.n)).map((l) => ({ n: l.n, text: l.text }));
797
+ const nq = await forcedTurn({ kind: NOTE_KIND, system: NOTE_SYSTEM, messages: [{ role: 'user', content: notePrompt(askedLines) }], tool: { name: NOTE_TOOL, description: 'Say, for each line, whether it also asks for written words.', schema: NOTE_SCHEMA } });
798
+ if (nq.early) return nq.early;
799
+ const answers = noteAnswers(asked, nq.args, askedLines);
800
+ nq.entry.notes = answers;
801
+ block.setNotes(answers);
802
+ pageExtras.checkRows = ledgerRecord(/** @type {any} */ (block.rows));
803
+ }
779
804
  }
780
805
  // 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
806
  const factsBase = pageInfo.length ? [...facts.info.filter((l) => !pageSources.some((s) => l.startsWith(`- ${s.role}: a web page`))), ...pageInfo] : facts.info;
782
807
  const factsInfo = [...factsBase, ...ticketSources.flatMap((s) => ticketFactsLines(s.role)), ...(flowType === 'mcp' ? mcpFactsLines(mcp.server, mcp.tools) : [])];
783
808
 
784
- // `notChecked` is offered on every try (information, not asking); `questions` only on try 3 (below).
785
- // 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
- 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 });
809
+ // `questions` only on try 3 (below).
810
+ const baseSystem = buildSystemPrompt({ menu, lines, arbiter, factsInfo, blockLines: blockLineNums });
788
811
  // 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
812
  // Absent or empty: the prompt is byte-identical to what it was.
790
- const system = `${baseSystem}\n\n${NOTCHECKED_PROMPT}${learnHints?.text ? `\n\n${learnHints.text}` : ''}`;
813
+ const system = `${baseSystem}${learnHints?.text ? `\n\n${learnHints.text}` : ''}`;
791
814
  let structureRetries = 0;
792
815
  let revisions = 0;
793
816
  let lastReds = [];
@@ -797,7 +820,7 @@ export async function draft({
797
820
  let validatorReds = []; // the last validator refusal; a structure retry after a revision must not drop it
798
821
  let stop = null;
799
822
  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[]}} */
823
+ /** @type {{questions:{line:number, question:string}[], droppedQuestions:object[], notChecked:string[], notCheckedBy?: Record<string, 'you'|'agent'|'default'>}} */
801
824
  let extras = { questions: [], droppedQuestions: [], notChecked: pageNotChecked }; // from the round that produced `lastDecl`, never an earlier one
802
825
 
803
826
  for (;;) {
@@ -812,7 +835,7 @@ export async function draft({
812
835
  // Amendment 25: a lock is a mechanism. Only try 3 of 3, and only when tries 1 and 2 BOTH failed validation (`revisions` counts the
813
836
  // validator's refusals fed back), gets the `questions` property; the redraft after an answer passes offerQuestions:false and never does.
814
837
  const askOpen = offerQuestions && revisions === MAX_REVISIONS;
815
- const schema = buildRoundSchema(menu, { questions: askOpen, sheets: sheetTables, ticket: flowType === 'plain' ? undefined : { flowType, tools: mcp.tools } });
838
+ const schema = buildRoundSchema(menu, { questions: askOpen, ticket: flowType === 'plain' ? undefined : { flowType, tools: mcp.tools } });
816
839
  const tool = {
817
840
  name: TOOL,
818
841
  description: 'Emit the flow declaration over the granted primitives, or refuse lines you cannot serve.',
@@ -901,43 +924,105 @@ export async function draft({
901
924
  entry.braceRepair = { dropped: fixed.dropped, used: true };
902
925
  }
903
926
 
904
- // `notChecked` was offered on every try, so it is information and never reaches the validator. `questions` is stripped only where it was
927
+ // `notChecked` is offered on no try (M17 am4, C1): whatever the model sends for it is dropped here. `questions` is stripped only where it was
905
928
  // offered; sent when not offered it stays, and the validator reds it as an unknown key (a stray key, never a silent pass).
906
- const { questions: rawQuestions, notChecked: rawNotChecked, ...captureRest } = /** @type {Record<string, any>} */ (captured);
929
+ const { questions: rawQuestions, notChecked: _aiNotes, ...captureRest } = /** @type {Record<string, any>} */ (captured);
907
930
  /** @type {Record<string, any>} */
908
931
  const declaration = { ...(askOpen ? captureRest : { ...captureRest, ...(rawQuestions === undefined ? {} : { questions: rawQuestions }) }), inputFacts: facts.inputFacts };
909
932
  // M13 piece 4: the flow type and the job's MCP (server + every tool of the newest OK check, R1) are set by code; whatever the model sent for them is overwritten.
910
933
  declaration.flowType = flowType;
911
934
  if (flowType === 'plain') delete declaration.mcp;
912
935
  else declaration.mcp = { server: mcp.server, tools: [...mcp.tools] };
936
+ // M17 am6: the Tickets filter and watch are checks on the list. A draft that carries one is refused (a red naming the field, $0); code writes each from the value the AI suggested on the list,
937
+ // proved by src/ticketrows.js, and only when a rule of that kind is on the job
938
+ const carriedTicketFields = TICKET_FIELDS.filter((f) => Object.hasOwn(captureRest, f));
939
+ for (const f of TICKET_FIELDS) delete declaration[f];
940
+ if (flowType === 'tickets') {
941
+ const kinds = new Set(lines.flatMap((l) => (typeof l.guardrail === 'string' ? l.guardrail.split('; ') : []).map((t) => ticketRuleField(t.trim()))));
942
+ for (const f of TICKET_FIELDS) if (kinds.has(f) && ticketProposal[f] !== undefined) declaration[f] = ticketProposal[f];
943
+ }
913
944
  // M6a amendment 1 (F50): the goal is the signed line, set by the machine; whatever the model sent is overwritten.
914
945
  if (Array.isArray(declaration.steps)) {
915
946
  declaration.steps = declaration.steps.map((st) => (isPlainObject(st) ? { ...st, goal: goalForLine(st.fromLine, lines) } : st));
916
947
  }
917
948
  // M13 am9 item 4: the last Ask before the added `write it out` reads every step; code sets it, whatever the model sent
918
949
  if (Array.isArray(declaration.steps)) declaration.steps = readEveryStep(declaration.steps, arbiter);
919
- // M10 am16 (4): the drafter writes no check. Whatever `close.shape` it sent (the schema offers none) is dropped here; a check reaches the plan only from the person's picks (applyPicks, next).
920
- delete declaration.pickedLines; // the record of picked fact lines is code's too (applyPicks)
950
+ // M10 am16 (4): the drafter writes no check. Whatever `close.shape` it sent (the schema offers none) is dropped here; a check reaches the plan only from the list's built rows (assembleFromBlock).
951
+ delete declaration.unjudgeable; // M17 am4 (C8): the hidden can't-judge record is gone; a line's Not checked reasons are the list's rows
952
+ delete declaration.pickedLines; // the record of picked fact lines is code's too (assembleFromBlock)
921
953
  if (Array.isArray(declaration.steps)) {
922
954
  declaration.steps = declaration.steps.map((st) => {
923
955
  if (!isPlainObject(st) || !isPlainObject(st.close) || (st.close.shape === undefined && st.close.picked === undefined)) return st;
924
- // M10 am22 (3): `close.picked` is code's from the person's picks (applyPicks, next); one the drafter sent is dropped here too
956
+ // M10 am22 (3): `close.picked` is code's from the list (assembleFromBlock, next); one the drafter sent is dropped here too
925
957
  const { shape: _drop, picked: _dropPicked, ...close } = st.close;
926
958
  return { ...st, close };
927
959
  });
928
960
  }
929
- // 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 })));
931
- // 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
- { const fixed = repairDeclaration(declaration, arbiter); if (fixed.repaired.length) { Object.assign(declaration, fixed.declaration); entry.repaired = fixed.repaired; } }
961
+ // 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
962
+ delete declaration.checkList;
963
+ let assembled = null;
964
+ if (block && blockPlan?.ok) {
965
+ assembled = assembleFromBlock({ declaration, block, lines, lineSet: blockLineNums, askLines });
966
+ Object.assign(declaration, assembled.declaration);
967
+ if (assembled.declaration.pickedLines === undefined) delete declaration.pickedLines;
968
+ }
969
+ // M17 am2: the AI writes no sheet check. What it sent as `close.sheet` is a typed suggestion; code refuses or builds each one on bareguard (src/sheetbuild.js) and writes the checks, with its own ids
970
+ /** @type {Awaited<ReturnType<typeof buildSheetChecks>>|null} */
971
+ let sheetBuilt = null;
972
+ let carriedSheet = false;
973
+ /** @type {ReturnType<typeof closeUnbuiltSheetSteps>|null} */
974
+ let sheetHitl = null;
975
+ if (sheetTables) {
976
+ // M17 am2 item 2: a declaration that carries `close.sheet` is refused (a red naming the field, no check run); the suggestions are the row-edit reply's, put on the step that reads the sheet by code
977
+ const roles = Object.keys(sheetTables);
978
+ const given = new Set();
979
+ declaration.steps = (Array.isArray(declaration.steps) ? declaration.steps : []).map((/** @type {any} */ st) => {
980
+ if (!isPlainObject(st) || !isPlainObject(st.close)) return st;
981
+ const { sheet: carried, ...close } = st.close;
982
+ if (carried !== undefined) carriedSheet = true;
983
+ const mine = close.class === 'green' && Array.isArray(st.reads) && st.reads.some((/** @type {string} */ r) => roles.includes(r)) && !given.has(st.fromLine) ? sheetSuggested.filter((x) => x.line === st.fromLine).map(({ line: _l, ...x }) => x) : [];
984
+ if (mine.length) given.add(st.fromLine);
985
+ return { ...st, close: mine.length ? { ...close, sheet: mine } : close };
986
+ });
987
+ const unplaced = sheetSuggested.filter((x) => !given.has(x.line)).map((x) => ({ line: x.line, helper: 'line', why: `line ${String(x.line)} has no green step that reads a sheet` }));
988
+ sheetBuilt = await buildSheetChecks({ declaration, lines, tables: sheetTables });
989
+ Object.assign(declaration, { steps: sheetBuilt.declaration.steps });
990
+ // M17 am5 / P5: a sheet step the builder built no check for is closed here (its class is the assembly's decision), its rules Not checked below
991
+ const closed = closeUnbuiltSheetSteps(declaration, sheetBuilt.unbuilt);
992
+ Object.assign(declaration, closed.declaration);
993
+ sheetHitl = closed;
994
+ if (sheetBuilt.refused.length || unplaced.length) entry.sheetRefused = [...unplaced, ...sheetBuilt.refused];
995
+ }
996
+ // M16 am4 (2): a sheet line's checks are rows on the same list (code builds them, src/sheetbuild.js; src/sheetrows.js reads them as rows)
997
+ let sheetOnList = null;
998
+ /** @type {any[]} */
999
+ let sheetDroppedNow = [];
1000
+ if (block) {
1001
+ // 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)
1002
+ for (const d of carriedSheetDropped) {
1003
+ // M17 am3: code names every check, so the Drop is kept for the very same check (its typed fields), never for an id that may name another one now
1004
+ const key = keyOfSameCheck(declaration, d);
1005
+ if (key === null) continue;
1006
+ const r = sheetChoice({ declaration, lines, csvRoles: csvRolesOf(arbiter), op: 'drop', key, dropped: sheetDroppedNow });
1007
+ if (r.ok) { Object.assign(declaration, { steps: r.declaration.steps }); sheetDroppedNow = r.dropped; }
1008
+ }
1009
+ onSheetDropped(sheetDroppedNow);
1010
+ }
1011
+ /** @type {ReturnType<typeof withTicketRows>['tickets']|null} */
1012
+ let ticketOnList = null;
1013
+ if (block && flowType === 'tickets') { const w = withTicketRows({ declaration, lines }); ticketOnList = w.tickets; if (w.tickets.signed.length) Object.assign(declaration, { checkList: w.declaration.checkList }); }
1014
+ 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
1015
  // 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() ?? [])]);
1016
+ entry.retention = retentionOf(captured, declaration, jobLines, [...(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
1017
  // 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
1018
+ // 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)
1019
+ const inPlan = block ? new Set(block.rows.filter((r) => r.state === 'built').flatMap((r) => (r.factNames ?? []).map((/** @type {string} */ nm) => `${r.line}:${nm}`))) : null;
1020
+ const planLookFacts = inPlan ? look.facts.filter((f) => !blockLineNums.has(f.line) || inPlan.has(`${f.line}:${f.name}`)) : look.facts;
936
1021
  const verdict1 = validateDeclaration(declaration, {
937
1022
  arbiter, lines, catalogue: validationCatalogue, wired: WIRED_VERBS, verbatimGoals: true, fitJobLine: true,
938
1023
  // 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
- 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) },
1024
+ sheetWords: sheetTables ? { headers: Object.fromEntries(Object.entries(sheetTables).map(([role, t]) => [role, t.header])), facts: sheetFacts.filter((f) => f.shape === 'column' && !(sheetHitl?.lines ?? []).includes(f.line)), tables: sheetTables } : undefined,
1025
+ 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
1026
  });
942
1027
  // 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
1028
  // M4d am39: a brace-repaired answer the validator finds an unknown key in is not used; the round is a structure failure, as today
@@ -949,21 +1034,41 @@ export async function draft({
949
1034
  continue;
950
1035
  }
951
1036
  const planRed = verdict1.ok ? findMcpPlanRed(declaration) : null;
952
- // 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)
953
- const tableReds = verdict1.ok && sheetTables ? await tableChecksFailingOnInput(declaration, sheetTables) : [];
954
- const verdict = planRed ? { ok: false, reds: [planRed] } : tableReds.length ? { ok: false, reds: tableReds } : verdict1;
1037
+ const carriedRed = carriedTicketFields.length ? `declaration: the draft carries ${carriedTicketFields.map((f) => `"${f}"`).join(' and ')}, which code sets from the check on the list. Remove the field from the draft` : carriedSheet ? 'declaration: the draft carries "close.sheet", which code builds from the checks suggested on the list. Remove the field from the draft' : null;
1038
+ const verdict = carriedRed ? { ok: false, reds: [carriedRed] } : planRed ? { ok: false, reds: [planRed] } : verdict1;
955
1039
  lastDecl = declaration;
956
1040
  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 ?? {}))])] };
1041
+ const uncovered = [...uncoveredRules(declaration, jobLines, Object.keys(facts.sheets ?? {}), sheetBuilt ?? undefined), ...(sheetHitl?.lost ?? [])];
1042
+ // the tag of a note no row tells: any note code writes is [default]; a row's own tag wins
1043
+ // M17 am2 / am4: a sheet look's column drop of a word inside a `~` rule never makes a Not checked line of its own. A rule a check row holds shows nowhere here; a rule none holds shows ONCE, with the build's reason
1044
+ // (`uncovered`). A drop of a prose word is no rule and stays.
1045
+ const ruleKey = (/** @type {string} */ t) => t.split(' \u2014 ')[0];
1046
+ const sheetRuleKeys = new Set(jobLines.filter((l) => sheetLineNums.includes(l.n)).flatMap((l) => lineRules(l).map((r) => `line ${l.n}: "${r}"`)));
1047
+ const lookNotChecked = pageNotChecked.filter((t) => !sheetRuleKeys.has(ruleKey(t)));
1048
+ /** @type {Record<string, 'you'|'agent'|'default'>} */
1049
+ const noteBy = Object.fromEntries([...lookNotChecked, ...uncovered].map((t) => [t, 'default']));
1050
+ const ticketNotChecked = (ticketOnList?.notChecked ?? []).map((t) => `not checked · "${t.rule}" — ${t.reason}`);
1051
+ for (const t of ticketNotChecked) noteBy[t] = 'you';
1052
+ extras = { questions: asked.kept, droppedQuestions: asked.dropped, notChecked: [...new Set([...lookNotChecked, ...(assembled ? assembled.notChecked : []), ...ticketNotChecked, ...uncovered])], ...(assembled ? { notCheckedBy: { ...noteBy, ...assembled.notCheckedBy } } : {}) };
958
1053
  if (asked.dropped.length) entry.droppedQuestions = asked.dropped;
959
1054
  // the declaration the model sent, as parsed, before any code overwrite (log.json keeps it per try)
960
1055
  entry.args = captured;
1056
+ // 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
1057
+ 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)))) : [];
1058
+ if (faults.length) {
1059
+ entry.outcome = 'plan-red';
1060
+ entry.reds = [.../** @type {any} */ (verdict).reds];
1061
+ log.push(entry);
1062
+ lastReds = [buildFaultWords(faults)];
1063
+ stop = 'plan-red';
1064
+ break;
1065
+ }
961
1066
  if (verdict.ok) {
962
1067
  entry.outcome = 'valid';
963
1068
  log.push(entry);
964
1069
  const m = sumMeterings(meterings);
965
1070
  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,
1071
+ 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: (() => { const c = sheetOnList ? withSheetCard(cardOfBlock(block), sheetOnList, sheetDroppedNow) : cardOfBlock(block); return ticketOnList?.card.length ? withSheetCard(c, { card: ticketOnList.card }) : c; })() } : {}),
967
1072
  };
968
1073
  }
969
1074
  lastReds = [...verdict.reds];