fwdloop 0.33.0 → 0.35.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 (87) hide show
  1. package/README.md +14 -0
  2. package/bin/fwdloop +18 -2
  3. package/package.json +1 -1
  4. package/src/action-line.js +100 -0
  5. package/src/action-stop.js +44 -0
  6. package/src/ask.js +9 -2
  7. package/src/auditchecks.js +6 -4
  8. package/src/authoring.js +28 -14
  9. package/src/blockasks.js +3 -2
  10. package/src/blockassemble.js +40 -21
  11. package/src/blockdraft.js +8 -13
  12. package/src/blockpick.js +11 -1
  13. package/src/checkblock.js +102 -58
  14. package/src/checked.js +7 -2
  15. package/src/checklist.js +1 -3
  16. package/src/checklistsign.js +1 -1
  17. package/src/checkpick.js +7 -73
  18. package/src/declaration.js +20 -35
  19. package/src/drafter.js +281 -208
  20. package/src/jobkey.js +2 -3
  21. package/src/noteask.js +62 -0
  22. package/src/pageask.js +24 -69
  23. package/src/pagedry.js +27 -4
  24. package/src/pagemap.js +8 -2
  25. package/src/pagerules.js +19 -3
  26. package/src/panel/author.js +63 -36
  27. package/src/panel/authorcard.js +36 -20
  28. package/src/panel/data.js +5 -1
  29. package/src/panel/index.html +66 -37
  30. package/src/pickrecord.js +42 -54
  31. package/src/planrebuild.js +16 -6
  32. package/src/rowedit.js +35 -5
  33. package/src/rubricstep.js +9 -1
  34. package/src/runner.js +87 -41
  35. package/src/runvalues.js +9 -1
  36. package/src/setup.js +3 -1
  37. package/src/sheetblock.js +17 -7
  38. package/src/sheetbuild.js +148 -0
  39. package/src/sheetchecks.js +3 -2
  40. package/src/sheetfind.js +4 -4
  41. package/src/sheetlook.js +15 -4
  42. package/src/sheetoffer.js +50 -5
  43. package/src/sheetrows.js +18 -2
  44. package/src/signed-text.js +1 -5
  45. package/src/ticket-draft.js +4 -21
  46. package/src/ticketrows.js +100 -0
  47. package/src/whole-job.js +27 -11
  48. package/types/action-line.d.ts +71 -0
  49. package/types/action-stop.d.ts +36 -0
  50. package/types/ask.d.ts +3 -2
  51. package/types/auditchecks.d.ts +2 -1
  52. package/types/authoring.d.ts +8 -3
  53. package/types/blockasks.d.ts +1 -2
  54. package/types/blockassemble.d.ts +20 -3
  55. package/types/blockdraft.d.ts +4 -12
  56. package/types/blockpick.d.ts +5 -0
  57. package/types/checkblock.d.ts +33 -17
  58. package/types/checked.d.ts +2 -0
  59. package/types/checklist.d.ts +3 -5
  60. package/types/checkpick.d.ts +4 -34
  61. package/types/declaration.d.ts +7 -0
  62. package/types/drafter.d.ts +23 -356
  63. package/types/noteask.d.ts +52 -0
  64. package/types/pageask.d.ts +12 -36
  65. package/types/pagedry.d.ts +13 -0
  66. package/types/pagerules.d.ts +7 -0
  67. package/types/panel/author.d.ts +1 -1
  68. package/types/panel/authorcard.d.ts +13 -8
  69. package/types/panel/authorflows.d.ts +4 -4
  70. package/types/panel/data.d.ts +2 -2
  71. package/types/panel/jobgrid.d.ts +1 -1
  72. package/types/pickrecord.d.ts +47 -13
  73. package/types/rowedit.d.ts +16 -1
  74. package/types/rubricstep.d.ts +3 -0
  75. package/types/sheetblock.d.ts +11 -4
  76. package/types/sheetbuild.d.ts +82 -0
  77. package/types/sheetchecks.d.ts +2 -1
  78. package/types/sheetfind.d.ts +2 -2
  79. package/types/sheetoffer.d.ts +26 -1
  80. package/types/sheetrows.d.ts +8 -0
  81. package/types/ticket-draft.d.ts +3 -49
  82. package/types/ticketrows.d.ts +61 -0
  83. package/types/whole-job.d.ts +3 -3
  84. package/src/added-end.js +0 -60
  85. package/src/repairs.js +0 -38
  86. package/types/added-end.d.ts +0 -62
  87. package/types/repairs.d.ts +0 -13
package/src/drafter.js CHANGED
@@ -20,9 +20,12 @@ import { capTooSmallText, usdText } from './draftspend.js';
20
20
  import { parseSignedText, unsignedAskTtls } from './signed-text.js';
21
21
  import { validateDeclaration, checkGuardrailSums, checkSendLineGuardrail } from './declaration.js';
22
22
  import { readEveryStep } from './whole-job.js';
23
+ import {
24
+ RECOGNISE_SYSTEM, RECOGNISE_SCHEMA, RECOGNISE_TOOL, SUGGEST_SYSTEM as ACTION_SUGGEST_SYSTEM, SUGGEST_SCHEMA as ACTION_SUGGEST_SCHEMA, SUGGEST_TOOL as ACTION_SUGGEST_TOOL,
25
+ jobListing, recognisedIsLast, cleanSuggestion, suggestionQuestion, withoutSend,
26
+ } from './action-line.js';
23
27
  import { loadCatalogue } from './catalogue.js';
24
28
  import { findMcpPlanRed } from './canrun.js';
25
- import { tableChecksFailingOnInput } from './sheetrun.js';
26
29
  import { WIRED_VERBS, wiredMenu } from './primitives.js';
27
30
  import { ticketSourcesOf, ticketFactsLines, mcpFactsLines, ticketSchemaParts, ticketReds, userMcpServers } from './ticket-draft.js';
28
31
  import { readInputFacts } from './input-facts.js';
@@ -30,30 +33,32 @@ import { freezePage } from './runner.js';
30
33
  import { removeFrozenPages } from './flow.js';
31
34
  import { lookAtPage, pageInfoLines } from './pagelook.js';
32
35
  import { lookAtSheet, sheetPrompt } from './sheetlook.js';
33
- import { leftRuleLine, dropRows, dropLine, dropSentence, pickNoteLine } from './pagedropwords.js';
36
+ import { leftRuleLine, dropRows, dropLine } from './pagedropwords.js';
34
37
  import {
35
- offerRules, rowsFromAnswer, checkAsks, settleRules, applyPicks, retentionOf, SUGGEST_SYSTEM, SUGGEST_TOOL, SUGGEST_SCHEMA, suggestUserText, codeScope,
38
+ offerRules, rowsFromAnswer, retentionOf, SUGGEST_SYSTEM, SUGGEST_TOOL, SUGGEST_SCHEMA, suggestUserText, codeScope,
36
39
  } from './checkpick.js';
37
40
  // M16 (docs/wiki/the-module-ladder.md, "M16"): the check block's turns, wired beside the declaration path
38
41
  import { blockJobLines } from './blocklines.js';
39
42
  import { setUpBlock, ticketLeaveOut, pickEdits, ledgerEdits, repairedEditsReadable, editRecord, renderRejectBlock, buildFaultWords, isBuildFault } from './blockdraft.js';
40
- import { assembleFromBlock } from './blockassemble.js';
43
+ import { assembleFromBlock, closeUnbuiltSheetSteps } from './blockassemble.js';
41
44
  import { cardOfBlock } from './cardlist.js';
42
45
  import { questionsOfBlock } from './blockasks.js';
46
+ import { NOTE_KIND, NOTE_TOOL, NOTE_SYSTEM, NOTE_SCHEMA, notePrompt, noteAnswers } from './noteask.js';
43
47
  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';
45
- import { matchRecord, entriesFromAnswers, sameWords, KEPT_WORDS } from './pickrecord.js';
48
+ import { ROW_EDIT_SYSTEM, ROW_EDIT_REVISE, rowEditUserText, rowEditChannel, editsOf, ticketFilterBlock } from './rowedit.js';
49
+ import { matchRecord, entriesFromAnswers, columnEntries, columnsOnLines } from './pickrecord.js';
46
50
  import { MAP_SYSTEM, mapPrompt } from './pagemap.js';
47
- import { askableFromLook, tooManyAsksText, MAX_LOOK_ASKS } from './pageask.js';
51
+ import { tooManyAsksText, MAX_LOOK_ASKS } from './pageask.js';
48
52
  import { lineRules } from './pagebits.js';
49
53
  import { isCountGuardrail } from './declaration.js';
50
- import { repairDeclaration } from './repairs.js';
51
54
  import path from 'node:path';
52
55
  import { isCellsPath } from './closers.js';
53
56
  import { parseCsv, sheetTable } from './csv.js';
54
- import { sheetChecksProp, sheetOfferRules } from './sheetoffer.js';
57
+ import { sheetSuggestProp, sheetOfferRules, agreedColumnWords } from './sheetoffer.js';
55
58
  import { uncoveredRules, csvRolesOf } from './sheetblock.js';
56
- import { withSheetRows, withSheetCard, sheetChoice } from './sheetrows.js';
59
+ import { withSheetRows, withSheetCard, sheetChoice, keyOfSameCheck } from './sheetrows.js';
60
+ import { buildSheetChecks } from './sheetbuild.js';
61
+ import { TICKET_FIELDS, ticketRuleField, proposalReds, withTicketRows } from './ticketrows.js';
57
62
  import {
58
63
  makeProvider, ModelRefusal, sumMeterings, ceilingCostUsd, priceRecord,
59
64
  } from './provider.js';
@@ -96,14 +101,12 @@ const COLUMNS_PROP = Object.freeze({
96
101
  });
97
102
 
98
103
  /**
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
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.
104
+ * 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).
101
105
  * 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
106
  * 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 {{sheets?: Record<string, {header: string[]}>, ticket?: {flowType: 'mcp'|'tickets', tools: string[]}}} [o]
107
+ * @param {any[]} menu @param {{ticket?: {flowType: 'mcp'|'tickets', tools: string[]}}} [o]
104
108
  */
105
- export function buildDeclarationSchema(menu, { sheets, ticket } = {}) {
106
- const sheetProp = sheets ? sheetChecksProp(sheets) : null;
109
+ export function buildDeclarationSchema(menu, { ticket } = {}) {
107
110
  const ticketParts = ticket ? ticketSchemaParts(ticket) : null;
108
111
  return {
109
112
  type: 'object',
@@ -133,7 +136,6 @@ export function buildDeclarationSchema(menu, { sheets, ticket } = {}) {
133
136
  properties: {
134
137
  class: { type: 'string', enum: [...CLASSES], description: "MUST equal the class of fromLine's guardrail in guardrailClasses; hitl when that line has no guardrail" },
135
138
  columns: COLUMNS_PROP,
136
- ...(sheetProp ? { sheet: sheetProp } : {}),
137
139
  },
138
140
  required: ['class'],
139
141
  additionalProperties: false,
@@ -149,11 +151,6 @@ export function buildDeclarationSchema(menu, { sheets, ticket } = {}) {
149
151
  additionalProperties: { type: 'string', enum: [...CLASSES] },
150
152
  description: 'one class per job line that HAS a guardrail, keyed by line number as a string',
151
153
  },
152
- unjudgeable: {
153
- type: 'object',
154
- additionalProperties: { type: 'string' },
155
- description: 'line number -> reason, only for a guardrail whose wording resisted judgment (its class stays hitl); {} if none',
156
- },
157
154
  refused: {
158
155
  type: 'array',
159
156
  items: {
@@ -165,33 +162,17 @@ export function buildDeclarationSchema(menu, { sheets, ticket } = {}) {
165
162
  description: 'job lines that cannot be served at all, with a reason; [] if none',
166
163
  },
167
164
  },
168
- required: ['steps', 'guardrailClasses', 'unjudgeable', 'refused'],
165
+ required: ['steps', 'guardrailClasses', 'refused'],
169
166
  additionalProperties: false,
170
167
  };
171
168
  }
172
169
 
173
170
  const TOOL = 'emit_declaration';
174
171
 
175
- // ---- M4e amendments 24 + 25: questions (try 3 only) and "not checked" (every try) ---------------------------------
172
+ // ---- M4e amendments 24 + 25: questions (try 3 only); the AI's own "not checked" notes are gone (M17 am4, C1) ---------------------------------
176
173
  // borrowed-from: fwdloop poc/am24-questions/draft.mjs@dda0e0f (prompts, linesNamedByReds, normalizeQuestions), adjusted to the product drafter.
177
174
  export const MAX_QUESTIONS = 2;
178
175
 
179
- /** What fwdloop's typed checks can really check (bareloop F174: give the model the real list, or "Not checked" is invented). */
180
- export const CHECKABLE = Object.freeze([
181
- 'green: a sheet figure is recomputed by bareguard from the saved sheet',
182
- 'softgreen: the output carries named section headings (sections), in order',
183
- `softgreen: a word ceiling for the whole output (maxWords; ${WHOLE_OUTPUT_CEILING_RULE}) and per section (wordsPerSection)`,
184
- 'softgreen: a line count per invoice (linesPerInvoice) and fields every line must carry (mustCarry)',
185
- 'hitl: a human accepts or reviews at a signed ask — the machine checks only that the step happened',
186
- ]);
187
-
188
- /** Offered on EVERY try (it is information, not asking). */
189
- export const NOTCHECKED_PROMPT = [
190
- 'notChecked (optional): a short list of things about the job that no check below will verify. These are the ONLY things fwdloop can check:',
191
- ...CHECKABLE.map((c) => `- ${c}`),
192
- '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.',
193
- ].join('\n');
194
-
195
176
  /** 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. */
196
177
  export const QUESTIONS_PROMPT = [
197
178
  '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',
@@ -200,11 +181,12 @@ export const QUESTIONS_PROMPT = [
200
181
  'Still emit the complete corrected declaration.',
201
182
  ].join('\n');
202
183
 
203
- /** The declaration schema plus the optional `notChecked` (every try) and, on try 3 only, `questions`. Neither is in `required`. */
204
- /** @param {any[]} menu @param {{questions?: boolean, sheets?: Record<string, {header: string[]}>|undefined, ticket?: {flowType: 'mcp'|'tickets', tools: string[]}}} [o] */
205
- export function buildRoundSchema(menu, { questions = false, sheets = undefined, ticket = undefined } = {}) {
206
- const s = buildDeclarationSchema(menu, { sheets, ticket });
207
- const extra = { notChecked: { type: 'array', items: { type: 'string' }, description: 'what the job asks for that no typed check verifies' } };
184
+ /** The declaration schema plus, on try 3 only, `questions` (not in `required`). */
185
+ /** @param {any[]} menu @param {{questions?: boolean, ticket?: {flowType: 'mcp'|'tickets', tools: string[]}}} [o] */
186
+ export function buildRoundSchema(menu, { questions = false, ticket = undefined } = {}) {
187
+ const s = buildDeclarationSchema(menu, { ticket });
188
+ /** @type {Record<string, any>} */
189
+ const extra = {};
208
190
  if (questions) {
209
191
  extra.questions = {
210
192
  type: 'array',
@@ -256,11 +238,6 @@ export function normalizeQuestions(raw, failedLines) {
256
238
  return { kept, dropped };
257
239
  }
258
240
 
259
- /** `notChecked` as the model sent it: non-blank strings only, trimmed. Anything else is an empty list. */
260
- function cleanNotChecked(raw) {
261
- return Array.isArray(raw) ? raw.filter((x) => typeof x === 'string' && x.trim() !== '').map((x) => x.trim()) : [];
262
- }
263
-
264
241
  // 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.
265
242
  // 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
243
  const shownRules = (/** @type {string} */ guardrail, all = false) => lineRules({ rule: guardrail }).filter((r) => all || !isCountGuardrail(r)).join('; ');
@@ -301,7 +278,6 @@ function greenReadRule(sources) {
301
278
  : `${rule} This job signs no CSV input, so a guardrail that needs a sheet check cannot be classed green here: class it "hitl".`];
302
279
  // M16 S5: the check block builds the quote checks of its lines; the drafter is told nothing of close.cited and offers none
303
280
  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.`);
304
- if (csvRoles.length) out.push(...sheetOfferRules(csvRoles)); // M10b piece 3: close.sheet and every rule the validator enforces on it
305
281
  return out;
306
282
  }
307
283
 
@@ -320,14 +296,6 @@ function whenToUse(menu) {
320
296
  return Object.entries(WHEN_TO_USE).filter(([verb]) => on.has(verb)).map(([, line]) => line);
321
297
  }
322
298
 
323
- /** 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. */
324
- function sheetRuleNumbers(lines, arbiter) {
325
- const csvRoles = (arbiter.sources ?? []).filter((s) => s.kind === 'file' && isCellsPath(s.path));
326
- if (csvRoles.length === 0) return [];
327
- 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);
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(' ')}`)];
329
- }
330
-
331
299
  export function buildSystemPrompt({ menu, lines, arbiter, factsInfo, blockLines = /** @type {Set<number>} */ (new Set()) }) {
332
300
  const askLines = arbiter.asks.map((a) => a.line);
333
301
  const sendLines = arbiter.sends.map((s) => s.line);
@@ -345,12 +313,12 @@ export function buildSystemPrompt({ menu, lines, arbiter, factsInfo, blockLines
345
313
  '- close.class MUST equal the class of the guardrail on that step\'s fromLine (guardrailClasses[fromLine]); a line with no guardrail is "hitl". A step cannot claim a class its own line does not earn.',
346
314
  ...greenReadRule(arbiter.sources),
347
315
  '- You write no check. A shape guardrail (a word count, a list size, headings) is settled before you draft: the human picks each check from a list and code puts the picked checks in the plan, so there is no close.shape for you to write. Still answer close.class and guardrailClasses as above; code sets the class of a line whose guardrail it settled from what the human picked.',
348
- '- The send line (the last line, when a Destination is set) writes out what the human accepted; it has no guardrail and no check of its own.',
316
+ '- The send line (the job\'s action: its last line, when it writes out everything before it) ships the output of the step right before it; it has no guardrail and no check of its own.',
349
317
  '- A step whose check reads its reply (softgreen) answers in its reply text and is never granted `write`, `edit` or any other write-class verb; only the send step at the end writes files out.',
350
318
  `- Signed ask line(s): ${askLines.length ? askLines.join(', ') : 'none'}. For each, emit EXACTLY ONE step: fromLine = that line, close.class "hitl", primitives []. It is a stop only — never grant a primitive on it, and never emit a pause at any other line.`,
351
- `- Signed send line(s): ${sendLines.length ? sendLines.join(', ') : 'none'}. That step is drafted like any other: grant the write primitive and read the artifact of the ask step that comes before it. Its target and position are signed, not yours.`,
319
+ `- Signed send line(s): ${sendLines.length ? sendLines.join(', ') : 'none'}. That step is drafted like any other: grant the write primitive and read the artifact of the step that comes right before it. Its target and position are signed, not yours.`,
352
320
  '- An ask step must read the output of an earlier step, the thing you are asked to check: its FIRST read is what the human sees at the ask (for example reads: ["bucket_assignment"], the nearest earlier step\'s emits). An ask that reads nothing, or reads something no earlier step makes, is refused. Reading is not a grant: the ask still grants no primitive.',
353
- '- Nothing hitl may come after the last signed ask except the send step.',
321
+ ...(sendLines.length ? [] : ['- Nothing hitl may come after the last signed ask except the send step.']),
354
322
  '- You never author a trigger, cap, ask position or TTL, allow-list, send target, or what "done" means.',
355
323
  '',
356
324
  'Inputs, mechanically read (facts, not guesses):',
@@ -358,7 +326,6 @@ export function buildSystemPrompt({ menu, lines, arbiter, factsInfo, blockLines
358
326
  '',
359
327
  'The numbered job lines:',
360
328
  jobLinesText(lines, arbiter.asks, blockLines),
361
- ...sheetRuleNumbers(lines, arbiter),
362
329
  ].join('\n');
363
330
  }
364
331
 
@@ -391,7 +358,7 @@ function isPlainObject(v) { return !!v && typeof v === 'object' && !Array.isArra
391
358
  *
392
359
  * @returns {Promise<{ok:boolean, declaration:object|null, reds:string[], rounds:number, calls:number, spendComplete:boolean,
393
360
  * costUsd:number|null, modelReturned:string|null, modelId?:string, price?:object|null, tokens?:object|null, structureRetries:number, revisions:number, stop:string|null, log:object[],
394
- * questions?:{line:number, question:string}[], droppedQuestions?:object[], notChecked?:string[], thinking?:{asked:string, status:string|null, say:string|null}, inputs?:{role:string, detail:string}[],
361
+ * questions?:{line:number, question:string}[], proseText?:string, action?:{line:number, by?:'agent'|'you', dropped?:true}|null, droppedQuestions?:object[], notChecked?:string[], thinking?:{asked:string, status:string|null, say:string|null}, inputs?:{role:string, detail:string}[],
395
362
  * 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[]}>}
396
363
  * `learnHints` (M8 item 5a): the earlier runs' notes block (src/learnstore.js hintsForRun), appended to the drafter's system prompt; null = nothing.
397
364
  * `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`.
@@ -399,7 +366,7 @@ function isPlainObject(v) { return !!v && typeof v === 'object' && !Array.isArra
399
366
  export async function draft({
400
367
  proseText, slot, model, provider: injected, rates: injectedRates, modelId: injectedModelId, env,
401
368
  priorSpend = /** @type {((ceilingUsd: number) => number)|null} */ (null), skills = DRAFT_SKILLS, makeProviderFn = makeProvider, onBook, offerQuestions = true, draftThinking = /** @type {'on'|'off'} */ ('off'),
402
- draftDir = /** @type {string|null} */ (null), fetchPage = undefined, leftRules = /** @type {{line: number, rule: number}[]} */ ([]),
369
+ 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} */ (() => {}),
403
370
  checkPicks = /** @type {import('./checkpick.js').Pick[]} */ ([]),
404
371
  // 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
405
372
  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),
@@ -407,6 +374,9 @@ export async function draft({
407
374
  mcpServers = /** @type {string[]|undefined} */ (undefined),
408
375
  // 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
409
376
  flowType = /** @type {'plain'|'mcp'|'tickets'} */ ('plain'), mcp = /** @type {any} */ (null),
377
+ // M13 am11: what the prose's send line is. null = the prose file is the truth (a hand-written send line); 'check' = the card's tentative send on the last line: the AI answers whether
378
+ // it is the action; 'known' = the person agreed or typed the last line (no question)
379
+ actionMode = /** @type {null|'check'|'known'} */ (null),
410
380
  }) {
411
381
  // What was asked of thinking and the WORST status bareagent reported across the rounds (the page says it loudly unless 'applied'). Read from the round log, the one record.
412
382
  const thinkingOf = () => {
@@ -420,16 +390,19 @@ export async function draft({
420
390
  // ---- $0 gates, before any provider is built -------------------------------
421
391
  // `draftThinking` ('on'|'off', M4d am6 item 7 / am7: the Chat tick-box, per job) is an intent only: turning thinking on or off on the wire is bareagent's (am7 item 3).
422
392
  if (draftThinking !== 'on' && draftThinking !== 'off') return fail([`config: draftThinking must be on | off, got ${JSON.stringify(draftThinking)}`]);
393
+ if (actionMode !== null && actionMode !== 'check' && actionMode !== 'known') return fail([`config: actionMode must be check | known, got ${JSON.stringify(actionMode)}`]);
423
394
  const parsed = parseSignedText(proseText);
424
395
  if (!parsed.ok) return fail(parsed.reds.map((r) => `signed-text: ${r}`));
425
- const { lines, arbiter } = parsed;
396
+ const { lines } = parsed;
397
+ let { arbiter } = parsed;
426
398
  const ttlReds = unsignedAskTtls(arbiter);
427
399
  if (ttlReds.length) return fail(ttlReds);
428
400
  // M4e amendment 15 item 2: a guardrail that fights itself on words is red at $0, before any provider is built or called.
429
401
  const sumReds = checkGuardrailSums(lines);
430
402
  if (sumReds.length) return fail(sumReds);
431
403
  // M10 amendment 14 item 1: a guardrail on the send line is refused at $0 (the card says it first; a prose file straight to `fwdloop draft` is caught here).
432
- const sendReds = checkSendLineGuardrail(lines, arbiter);
404
+ // M13 am11: with an actionMode the send is the card's tentative one; the refusal is made after the AI says whether the last line is the action (below)
405
+ const sendReds = actionMode === null ? checkSendLineGuardrail(lines, arbiter) : [];
433
406
  if (sendReds.length) return fail(sendReds);
434
407
  const menu = wiredMenu(skills);
435
408
  // The file inputs are read first, at $0, before a provider is built (a page input is fetched only after the price and cap gates, below).
@@ -484,9 +457,9 @@ export async function draft({
484
457
  /** the result of a draft that stops before any drafting round with what it spent so far (a provider red, the budget); one literal for every such stop */
485
458
  const earlyStop = (/** @type {string[]} */ reds, /** @type {string} */ why) => {
486
459
  const m = sumMeterings(meterings);
487
- return {
460
+ return withAction({
488
461
  ok: false, declaration: null, 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: 0, revisions: 0, stop: why, log, thinking: thinkingOf(), inputs: facts.list, questions: [], droppedQuestions: [], notChecked: [], ...pageExtras,
489
- };
462
+ });
490
463
  };
491
464
 
492
465
  // M10 item 1: a web page input is fetched once and frozen into the DRAFT folder (the drafting copy). A run freezes its own copy at its own start
@@ -511,12 +484,115 @@ export async function draft({
511
484
  const look = { facts: [], dropped: [] };
512
485
  /** @type {string[]} */
513
486
  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();
516
487
  /** @type {any[]} */
517
488
  const pageLooks = [];
518
489
  /** @type {Record<string, any>} */
519
490
  const pageExtras = pageSources.length ? { look, pageLooks } : {};
491
+ /**
492
+ * 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,
493
+ * 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.
494
+ * `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.
495
+ * 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).
496
+ * @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
497
+ */
498
+ const forcedTurn = async ({ kind, system: sys, messages, tool: spec, attempts = 2, repair = false, usable = () => true }) => {
499
+ /** @type {any} */
500
+ let entry = null;
501
+ for (let attempt = 1; attempt <= attempts; attempt += 1) {
502
+ const spentBefore = meterings.reduce((sum, ev) => sum + (ev.costUsd ?? roundCeiling), 0);
503
+ if (spentBefore + ceilingCostUsd(rates, sys.length + messages.reduce((n, m) => n + m.content.length, 0) + JSON.stringify(spec.schema).length) > budgetUsd) {
504
+ if (meterings.length === 0 && calls === 0) { removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); return { early: fail([tooSmall(roundCeiling)]) }; }
505
+ return { early: earlyStop(['the draft budget is spent'], 'budget') };
506
+ }
507
+ /** @type {any} */
508
+ let captured;
509
+ const roundEvents = [];
510
+ 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' }); } };
511
+ const forcedLoop = new Loop({ provider, rates, onLlmResult: async (ev) => { roundEvents.push(ev); meterings.push(ev); } });
512
+ calls += 1;
513
+ book(true);
514
+ let res;
515
+ let threw = null;
516
+ try {
517
+ res = await forcedLoop.run([{ role: 'system', content: sys }, ...messages], [tool], { maxTokens: DRAFT_MAX_TOKENS, thinkingMode: 'off', toolChoice: { name: spec.name } });
518
+ } catch (err) {
519
+ threw = err;
520
+ if (roundEvents.length === 0) unmetered += 1;
521
+ }
522
+ book(false);
523
+ entry = /** @type {Record<string, any>} */ ({ round: log.length + 1, kind });
524
+ if (res?.thinkingApplied !== undefined) entry.thinkingApplied = res.thinkingApplied;
525
+ if (res?.thinkingStatus !== undefined) entry.thinkingStatus = res.thinkingStatus;
526
+ if (threw && !(isPlainObject(captured) && threw instanceof HaltError)) {
527
+ entry.outcome = `provider-red: ${threw.message}`;
528
+ log.push(entry);
529
+ return { early: earlyStop([`provider-red: ${threw.message}`], 'provider-red') };
530
+ }
531
+ if (!isPlainObject(captured)) {
532
+ // the raw answer is kept (log.json), the cut-off said out loud
533
+ const malformed = provider?.lastMalformedToolCall ?? null;
534
+ 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)';
535
+ if (typeof malformed?.rawArguments === 'string') entry.rawArguments = malformed.rawArguments;
536
+ else if (typeof res?.text === 'string' && res.text !== '') entry.rawText = res.text;
537
+ // M4d am39: only a malformed-JSON round (never a cut-off, never text) whose answer is a complete object plus trailing `}` is repaired
538
+ const fixed = repair && malformed && res?.stopReason !== 'max_tokens' ? repairTrailingBraces(malformed.rawArguments) : null;
539
+ if (fixed) {
540
+ const ok = usable(fixed.value);
541
+ entry.braceRepair = { dropped: fixed.dropped, used: ok };
542
+ if (ok) { entry.outcome = 'answered'; entry.args = fixed.value; log.push(entry); return { args: fixed.value, entry }; }
543
+ }
544
+ log.push(entry);
545
+ continue;
546
+ }
547
+ entry.outcome = 'answered';
548
+ entry.args = captured;
549
+ log.push(entry);
550
+ return { args: captured, entry };
551
+ }
552
+ return { args: null, entry };
553
+ };
554
+
555
+ // M13 am11 rules 1 and 2: the job's last line is the action. The AI answers ONE question (record_action); code checks the answer is the LAST line (never an Ask). With none, and the
556
+ // person's answer not yet given, the AI suggests one line and the question carries the signed words. Nothing is added to the job without the person's answer.
557
+ /** the result with what the AI decided about the action: the prose as kept (the send line stays or is taken out) and the action line, or null */
558
+ // M13 am11b: the ONE writer of the log's `action`: { line, by } (who picked: 'agent' = the AI, 'you' = an Agree or typed line), (an old log may hold a `dropped` record; nothing reads it); null when none
559
+ /** @type {null|{line: number, by?: 'agent'|'you'}} */
560
+ let actionRec = null;
561
+ const withAction = (/** @type {any} */ r) => ({ ...r, proseText, action: actionRec ?? (arbiter.sends.length === 1 ? { line: arbiter.sends[0].line } : null) });
562
+ /** @type {null|{line: number, question: string, source: 'look', ask: 'action', ruleNo: undefined, ruleText: string, reading: string, counted: false}} */
563
+ let actionAsk = null;
564
+ if (actionMode !== null && arbiter.sends.length === 1 && arbiter.sends[0].line === lines.length) {
565
+ const last = lines[lines.length - 1];
566
+ const signedAsks = new Set(arbiter.asks.map((a) => a.line));
567
+ let keep = actionMode === 'known';
568
+ if (actionMode === 'check' && !signedAsks.has(last.n)) {
569
+ const rec = await forcedTurn({
570
+ kind: 'action-recognise', system: RECOGNISE_SYSTEM, messages: [{ role: 'user', content: jobListing(lines, signedAsks, String(arbiter.sends[0].target.path)) }],
571
+ tool: { name: RECOGNISE_TOOL, description: 'Say which last step writes or sends everything before it, or none.', schema: RECOGNISE_SCHEMA },
572
+ });
573
+ if (rec.early) return rec.early;
574
+ keep = recognisedIsLast(rec.args, last.n, false);
575
+ }
576
+ if (keep) {
577
+ const reds = checkSendLineGuardrail(lines, arbiter);
578
+ if (reds.length) return earlyStop(reds, 'action');
579
+ actionRec = { line: last.n, by: actionMode === 'known' ? 'you' : 'agent' };
580
+ } else {
581
+ if (actionMode === 'check' && offerQuestions) {
582
+ const sg = await forcedTurn({
583
+ kind: 'action-suggest', system: ACTION_SUGGEST_SYSTEM, messages: [{ role: 'user', content: jobListing(lines, signedAsks, String(arbiter.sends[0].target.path)) }],
584
+ tool: { name: ACTION_SUGGEST_TOOL, description: 'Suggest one last step that writes or sends everything before it.', schema: ACTION_SUGGEST_SCHEMA },
585
+ });
586
+ if (sg.early) return sg.early;
587
+ const suggested = cleanSuggestion(sg.args);
588
+ if (suggested !== null) actionAsk = { line: last.n, question: suggestionQuestion(suggested), source: 'look', ask: 'action', ruleNo: undefined, ruleText: '', reading: suggested, counted: false };
589
+ }
590
+ proseText = withoutSend(proseText);
591
+ const again = parseSignedText(proseText);
592
+ if (!again.ok) return fail(again.reds.map((r) => `signed-text: ${r}`));
593
+ arbiter = again.arbiter;
594
+ }
595
+ }
520
596
  let mapCut = null;
521
597
  const jobLines = lines.map((l) => ({ n: l.n, text: l.text, ...(l.guardrail ? { rule: l.guardrail } : {}) }));
522
598
  // M10 am27 (1): the page look sees only the non-count rules; `toOriginal` takes a visible rule number back to the original one
@@ -593,7 +669,6 @@ export async function draft({
593
669
  if (left.length) {
594
670
  look.dropped.push(...left);
595
671
  const lines = left.map((d) => leftRuleLine(d.fact));
596
- for (const x of lines) { personNotChecked.add(x); if (!pageNotChecked.includes(x)) pageNotChecked.push(x); }
597
672
  pageInfo.push(' You chose to leave these Not checked; never claim them as checked:', ...lines.map((x) => ` - ${x}`));
598
673
  }
599
674
  }
@@ -606,6 +681,9 @@ export async function draft({
606
681
  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);
607
682
  const sheetRoles = sheetJobLines.some((l) => lineRules(l).length > 0) ? [...Object.keys(facts.sheets ?? {}), ...docxRoles] : [];
608
683
  /** @type {any[]} */
684
+ // 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
685
+ const effColumns = [...columnAnswers, ...columnsOnLines(carriedColumns, lines).filter((c) => !columnAnswers.some((f) => f.line === c.line && f.word.toLowerCase() === c.word.toLowerCase()))];
686
+ onColumns(columnEntries(lines, effColumns));
609
687
  const sheetAsks = [];
610
688
  /** @type {any[]} */
611
689
  const sheetFacts = [];
@@ -625,11 +703,12 @@ export async function draft({
625
703
  };
626
704
  }
627
705
  // 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).
628
- 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 }));
706
+ const asksNow = got.asks.filter((a) => !effColumns.some((c) => c.line === a.line && c.word.toLowerCase() === a.word.toLowerCase()));
707
+ 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 }));
629
708
  const dropped = [...got.dropped, ...declined];
630
- sheetAsks.push(...got.asks); // asked only when the asks block below is open (offerQuestions)
709
+ sheetAsks.push(...asksNow); // asked only when the asks block below is open (offerQuestions)
631
710
  sheetFacts.push(...got.facts);
632
- 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 });
711
+ 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 });
633
712
  const lost = dropRows(dropped).map((row) => dropLine(row, jobLines, lineRules));
634
713
  for (const l of lost) if (!pageNotChecked.includes(l)) pageNotChecked.push(l);
635
714
  pageInfo.push(
@@ -638,85 +717,22 @@ export async function draft({
638
717
  );
639
718
  }
640
719
  if (sheetLooks.length) pageExtras.sheetLooks = sheetLooks; // kept beside the page looks (src/authoring.js writes both into page-look.json)
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) {
652
- const spentBefore = meterings.reduce((sum, ev) => sum + (ev.costUsd ?? roundCeiling), 0);
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') };
656
- }
657
- /** @type {any} */
658
- let captured;
659
- const roundEvents = [];
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); } });
662
- calls += 1;
663
- book(true);
664
- let res;
665
- let threw = null;
666
- try {
667
- res = await forcedLoop.run([{ role: 'system', content: sys }, ...messages], [tool], { maxTokens: DRAFT_MAX_TOKENS, thinkingMode: 'off', toolChoice: { name: spec.name } });
668
- } catch (err) {
669
- threw = err;
670
- if (roundEvents.length === 0) unmetered += 1;
671
- }
672
- book(false);
673
- entry = /** @type {Record<string, any>} */ ({ round: log.length + 1, kind });
674
- if (res?.thinkingApplied !== undefined) entry.thinkingApplied = res.thinkingApplied;
675
- if (res?.thinkingStatus !== undefined) entry.thinkingStatus = res.thinkingStatus;
676
- if (threw && !(isPlainObject(captured) && threw instanceof HaltError)) {
677
- entry.outcome = `provider-red: ${threw.message}`;
678
- log.push(entry);
679
- return { early: earlyStop([`provider-red: ${threw.message}`], 'provider-red') };
680
- }
681
- if (!isPlainObject(captured)) {
682
- // the raw answer is kept (log.json), the cut-off said out loud
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)';
685
- if (typeof malformed?.rawArguments === 'string') entry.rawArguments = malformed.rawArguments;
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
- }
694
- log.push(entry);
695
- continue;
696
- }
697
- entry.outcome = 'answered';
698
- entry.args = captured;
699
- log.push(entry);
700
- return { args: captured, entry };
701
- }
702
- return { args: null, entry };
703
- };
704
-
705
720
  // 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
721
  // 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
722
  // (offerQuestions false) makes no call: it settles every rule against the person's picks instead.
708
723
  // 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]);
724
+ const shapeEverywhere = offerRules(lines, arbiter, [...look.facts, ...sheetFacts]);
710
725
  // 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
726
  // 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
727
  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
728
  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
729
  if (blockPlan && !blockPlan.ok) return fail(blockPlan.reds.map((r) => `signed-text: ${r}`));
715
730
  const blockLineNums = new Set(blockPlan ? blockPlan.jobLines.map((l) => l.n) : []);
716
- const blockScoped = allShape.filter((r) => blockLineNums.has(r.line));
731
+ // 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
732
+ const allShape = shapeEverywhere.filter((r) => blockLineNums.has(r.line));
717
733
  // 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
734
  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 }));
735
+ const keptView = carried.kept.map((k) => ({ line: k.line, rule: k.rule, ruleText: k.entry.ruleText, check: k.entry.check, left: k.entry.left }));
720
736
  onPickRecord?.({ picks: carried.kept.map((k) => k.entry), kept: keptView });
721
737
  const askRules = carried.askRules;
722
738
  /** the block (M16 S1): the person's rules, the look, the picks kept and just answered, reconciled once */
@@ -727,19 +743,16 @@ export async function draft({
727
743
  block = setUpBlock({
728
744
  texts: { ...(facts.docs ?? {}), ...Object.fromEntries(Object.entries(pages).map(([role, pg]) => [role, pg.text])) }, jobLines: blockPlan.jobLines, look,
729
745
  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]),
746
+ fresh: { picks: checkPicks.filter(inBlock), left: leftRules.filter(inBlock) }, asks: offerQuestions, countScope: (t) => codeScope(arbiter.sources, t) === 'in', leaveOut: ticketLeaveOut(flowType, blockPlan.jobLines),
731
747
  });
732
748
  }
733
- /** @type {ReturnType<typeof checkAsks>} */
734
- let shapeAsks = [];
735
749
  if (askRules.length && offerQuestions) {
736
750
  const content = suggestUserText(lines, askRules);
737
751
  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
752
  if (got.early) return got.early;
739
753
  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
754
+ // M16 S2 (R1): a kept check is a `pick` edit of the block, before any asks
741
755
  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
756
  }
744
757
  if (block && blockPlan?.ok && blockPlan.jobLines.length > 0 && Object.keys(block.texts).length > 0) {
745
758
  const texts = block.texts;
@@ -753,57 +766,57 @@ export async function draft({
753
766
  // 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
767
  if (block && Array.isArray(carriedChoices)) { block.carryChoices(carriedChoices); onChoices(block.choicesRecord()); block.reconcile(); }
755
768
  /** 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) : [];
769
+ const blockAsks = block && offerQuestions ? questionsOfBlock(block, allShape) : [];
757
770
  if (block) pageExtras.checkRows = ledgerRecord(/** @type {any} */ (block.rows));
758
771
  // 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
759
772
  // 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.
760
773
  // 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.
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')];
774
+ if ((sheetAsks.length || blockAsks.length || actionAsk !== null) && offerQuestions) {
775
+ // 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
776
+ const lookAsks = [...[...sheetAsks, ...blockAsks.filter((a) => a.ask === 'reading')].sort((a, b) => a.line - b.line), ...blockAsks.filter((a) => a.ask === 'cant-check')];
765
777
  // 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).
766
778
  const blockShape = blockAsks.filter((a) => a.ask === 'no-check' || a.ask === 'check');
767
- const asks = [...lookAsks, ...shapeAsks, ...blockShape];
779
+ const asks = [...lookAsks, ...blockShape, ...(actionAsk === null ? [] : [actionAsk])];
768
780
  if (asks.length > 0) {
769
781
  const m = sumMeterings(meterings);
770
782
  const spent = m.costUsd === null || unmetered > 0 ? (m.costUsd === null ? 'unknown' : `at least ${usdText(m.costUsd)}`) : usdText(m.costUsd);
771
- const counted = [...lookAsks, ...[...shapeAsks, ...blockShape].filter((a) => a.counted).map((a) => ({ ...a, reading: "I can't check this" }))];
783
+ const counted = [...lookAsks, ...blockShape.filter((a) => a.counted).map((a) => ({ ...a, reading: "I can't check this" }))];
772
784
  const tooMany = counted.length > MAX_LOOK_ASKS;
773
785
  if (tooMany && pageSources.length) removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); // a refused draft keeps no page copy
774
- return {
786
+ return withAction({
775
787
  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,
776
788
  questions: tooMany ? [] : asks.map((a) => ({
777
- 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 } : {}),
789
+ line: a.line, question: a.question, source: a.source, ask: a.ask, ruleNo: 'rule' in a ? a.rule : undefined, ruleText: a.ruleText, proposal: a.reading ?? null, ...('check' in a && a.check ? { check: a.check } : {}),
778
790
  })),
779
791
  droppedQuestions: [], notChecked: pageNotChecked, ...pageExtras,
780
- };
792
+ });
781
793
  }
782
794
  }
783
- // 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
784
- // (shown on the plan card and carried as `unjudgeable`); the drafter writes no check of its own, whatever it sends is overwritten below.
785
- const allPicks = [...checkPicks, ...carried.picks];
786
- const allLeft = [...leftRules, ...carried.left];
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
795
+ // the record this draft hands on: what it kept plus what the person just answered (numbered on this card)
791
796
  onPickRecord?.({ picks: [...carried.kept.map((k) => k.entry), ...entriesFromAnswers(lines, allShape, checkPicks, leftRules)], kept: keptView });
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})` : '');
793
- for (const n of settled?.notes ?? []) {
794
- const line = (n.reason === 'person-left' ? leftRuleLine(n.text) : pickNoteLine(n.text, n.reason)) + keptNote(n);
795
- personNotChecked.add(line);
796
- if (!pageNotChecked.includes(line)) pageNotChecked.push(line);
797
- }
798
797
  // 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
798
  // 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;
799
+ // 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
800
+ const sheetTables = Object.keys(facts.sheets ?? {}).length ? Object.fromEntries(Object.entries(facts.sheets).map(([role, t]) => [role, sheetTable(parseCsv(t))])) : undefined;
801
+ /** 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[]} */
802
+ let sheetSuggested = [];
803
+ /** 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>}} */
804
+ const ticketProposal = { refused: {} };
805
+ const ticketRuleOnJob = flowType === 'tickets' && blockPlan?.ok === true && blockPlan.jobLines.some((l) => (l.rules ?? []).some((t) => ticketRuleField(t) !== null));
806
+ const sheetRoleList = sheetTables ? Object.keys(sheetTables) : [];
807
+ // 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
808
+ const sendLines = new Set(arbiter.sends.map((x) => x.line));
809
+ 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) : [];
810
+ const sheetTurn = sheetLineNums.length > 0;
811
+ if (block && blockPlan?.ok && (blockPlan.jobLines.length > 0 || sheetTurn) && (Object.keys(block.texts).length > 0 || block.rows.some((r) => r.kind === 'rule') || ticketRuleOnJob || sheetTurn)) {
812
+ // M17 am2: with a CSV input the turn also shows the sheet lines and the sheets; the sheet checks come back as typed suggestions
813
+ const texts = { ...block.texts, ...(facts.sheets ?? {}) };
814
+ const shownLines = sheetTurn ? jobLines.filter((l) => blockLineNums.has(l.n) || sheetLineNums.includes(l.n)) : blockPlan.jobLines;
802
815
  // 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
816
  const lookReport = pageSources.length ? { prose: [], notFound: [], facts: look.facts, dropped: look.dropped } : null;
804
817
  /** @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: [] });
818
+ 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')}` : ''}` : '') }];
819
+ const channel = rowEditChannel(flowType === 'tickets', sheetTurn ? sheetSuggestProp(sheetTables ?? {}, sheetLineNums) : null).tool({ calls: [] });
807
820
  for (let rev = 0; ; rev += 1) {
808
821
  const got = await forcedTurn({
809
822
  kind: rev === 0 ? 'row-edit' : 'row-edit-revision', system: ROW_EDIT_SYSTEM, messages: turn, tool: { name: channel.name, description: channel.description, schema: channel.parameters },
@@ -811,6 +824,12 @@ export async function draft({
811
824
  });
812
825
  if (got.early) return got.early;
813
826
  if (got.args === null) return earlyStop([String(got.entry?.outcome ?? 'structure').replace(/^structure: /, '')], 'structure');
827
+ for (const f of TICKET_FIELDS) {
828
+ if (flowType !== 'tickets' || got.args[f] === undefined) continue;
829
+ const reds = proposalReds(f, got.args[f]);
830
+ if (reds.length === 0) { ticketProposal[f] = got.args[f]; delete ticketProposal.refused[f]; } else ticketProposal.refused[f] = reds[0];
831
+ }
832
+ if (sheetTurn && Array.isArray(got.args.sheetChecks)) sheetSuggested = got.args.sheetChecks.filter((/** @type {any} */ x) => x && typeof x === 'object' && !Array.isArray(x));
814
833
  const rec = block.applyDelta({ label: `row-edit-${rev + 1}`, edits: editsOf(got.args) });
815
834
  block.reconcile();
816
835
  got.entry.edits = editRecord(rec);
@@ -820,17 +839,29 @@ export async function draft({
820
839
  }
821
840
  pageExtras.checkRows = ledgerRecord(/** @type {any} */ (block.rows));
822
841
  }
842
+ // 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.
843
+ // The answers ride the turn's log entry (`notes`), the one place the replay (src/planrebuild.js) reads them from, a failed turn included.
844
+ if (block && blockPlan?.ok) {
845
+ const asked = block.factOnlyLines();
846
+ if (asked.length > 0) {
847
+ const askedLines = blockPlan.jobLines.filter((l) => asked.includes(l.n)).map((l) => ({ n: l.n, text: l.text }));
848
+ 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 } });
849
+ if (nq.early) return nq.early;
850
+ const answers = noteAnswers(asked, nq.args, askedLines);
851
+ nq.entry.notes = answers;
852
+ block.setNotes(answers);
853
+ pageExtras.checkRows = ledgerRecord(/** @type {any} */ (block.rows));
854
+ }
855
+ }
823
856
  // 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.
824
857
  const factsBase = pageInfo.length ? [...facts.info.filter((l) => !pageSources.some((s) => l.startsWith(`- ${s.role}: a web page`))), ...pageInfo] : facts.info;
825
858
  const factsInfo = [...factsBase, ...ticketSources.flatMap((s) => ticketFactsLines(s.role)), ...(flowType === 'mcp' ? mcpFactsLines(mcp.server, mcp.tools) : [])];
826
859
 
827
- // `notChecked` is offered on every try (information, not asking); `questions` only on try 3 (below).
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
829
- const sheetTables = Object.keys(facts.sheets ?? {}).length ? Object.fromEntries(Object.entries(facts.sheets).map(([role, t]) => [role, sheetTable(parseCsv(t))])) : undefined;
860
+ // `questions` only on try 3 (below).
830
861
  const baseSystem = buildSystemPrompt({ menu, lines, arbiter, factsInfo, blockLines: blockLineNums });
831
862
  // 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).
832
863
  // Absent or empty: the prompt is byte-identical to what it was.
833
- const system = `${baseSystem}\n\n${NOTCHECKED_PROMPT}${learnHints?.text ? `\n\n${learnHints.text}` : ''}`;
864
+ const system = `${baseSystem}${learnHints?.text ? `\n\n${learnHints.text}` : ''}`;
834
865
  let structureRetries = 0;
835
866
  let revisions = 0;
836
867
  let lastReds = [];
@@ -855,7 +886,7 @@ export async function draft({
855
886
  // 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
856
887
  // validator's refusals fed back), gets the `questions` property; the redraft after an answer passes offerQuestions:false and never does.
857
888
  const askOpen = offerQuestions && revisions === MAX_REVISIONS;
858
- const schema = buildRoundSchema(menu, { questions: askOpen, sheets: sheetTables, ticket: flowType === 'plain' ? undefined : { flowType, tools: mcp.tools } });
889
+ const schema = buildRoundSchema(menu, { questions: askOpen, ticket: flowType === 'plain' ? undefined : { flowType, tools: mcp.tools } });
859
890
  const tool = {
860
891
  name: TOOL,
861
892
  description: 'Emit the flow declaration over the granted primitives, or refuse lines you cannot serve.',
@@ -944,58 +975,96 @@ export async function draft({
944
975
  entry.braceRepair = { dropped: fixed.dropped, used: true };
945
976
  }
946
977
 
947
- // `notChecked` was offered on every try, so it is information and never reaches the validator. `questions` is stripped only where it was
978
+ // `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
948
979
  // offered; sent when not offered it stays, and the validator reds it as an unknown key (a stray key, never a silent pass).
949
- const { questions: rawQuestions, notChecked: rawNotChecked, ...captureRest } = /** @type {Record<string, any>} */ (captured);
980
+ const { questions: rawQuestions, notChecked: _aiNotes, ...captureRest } = /** @type {Record<string, any>} */ (captured);
950
981
  /** @type {Record<string, any>} */
951
982
  const declaration = { ...(askOpen ? captureRest : { ...captureRest, ...(rawQuestions === undefined ? {} : { questions: rawQuestions }) }), inputFacts: facts.inputFacts };
952
983
  // 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.
953
984
  declaration.flowType = flowType;
954
985
  if (flowType === 'plain') delete declaration.mcp;
955
986
  else declaration.mcp = { server: mcp.server, tools: [...mcp.tools] };
987
+ // 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,
988
+ // proved by src/ticketrows.js, and only when a rule of that kind is on the job
989
+ const carriedTicketFields = TICKET_FIELDS.filter((f) => Object.hasOwn(captureRest, f));
990
+ for (const f of TICKET_FIELDS) delete declaration[f];
991
+ if (flowType === 'tickets') {
992
+ const kinds = new Set(lines.flatMap((l) => (typeof l.guardrail === 'string' ? l.guardrail.split('; ') : []).map((t) => ticketRuleField(t.trim()))));
993
+ for (const f of TICKET_FIELDS) if (kinds.has(f) && ticketProposal[f] !== undefined) declaration[f] = ticketProposal[f];
994
+ }
956
995
  // M6a amendment 1 (F50): the goal is the signed line, set by the machine; whatever the model sent is overwritten.
957
996
  if (Array.isArray(declaration.steps)) {
958
997
  declaration.steps = declaration.steps.map((st) => (isPlainObject(st) ? { ...st, goal: goalForLine(st.fromLine, lines) } : st));
959
998
  }
960
999
  // M13 am9 item 4: the last Ask before the added `write it out` reads every step; code sets it, whatever the model sent
961
1000
  if (Array.isArray(declaration.steps)) declaration.steps = readEveryStep(declaration.steps, arbiter);
962
- // 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).
963
- delete declaration.pickedLines; // the record of picked fact lines is code's too (applyPicks)
1001
+ // 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).
1002
+ 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
1003
+ delete declaration.pickedLines; // the record of picked fact lines is code's too (assembleFromBlock)
964
1004
  if (Array.isArray(declaration.steps)) {
965
1005
  declaration.steps = declaration.steps.map((st) => {
966
1006
  if (!isPlainObject(st) || !isPlainObject(st.close) || (st.close.shape === undefined && st.close.picked === undefined)) return st;
967
- // M10 am22 (3): `close.picked` is code's from the person's picks (applyPicks, next); one the drafter sent is dropped here too
1007
+ // M10 am22 (3): `close.picked` is code's from the list (assembleFromBlock, next); one the drafter sent is dropped here too
968
1008
  const { shape: _drop, picked: _dropPicked, ...close } = st.close;
969
1009
  return { ...st, close };
970
1010
  });
971
1011
  }
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
973
- if (settled) Object.assign(declaration, applyPicks(declaration, oldShape, settled, (n) => dropSentence({ line: n.line, fact: '', reason: n.reason })));
974
1012
  // 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
1013
  delete declaration.checkList;
976
1014
  let assembled = null;
977
1015
  if (block && blockPlan?.ok) {
978
- assembled = assembleFromBlock({ declaration, block, lines, lineSet: blockLineNums });
1016
+ assembled = assembleFromBlock({ declaration, block, lines, lineSet: blockLineNums, askLines });
979
1017
  Object.assign(declaration, assembled.declaration);
980
1018
  if (assembled.declaration.pickedLines === undefined) delete declaration.pickedLines;
981
1019
  }
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
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)
1020
+ // 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
1021
+ /** @type {Awaited<ReturnType<typeof buildSheetChecks>>|null} */
1022
+ let sheetBuilt = null;
1023
+ let carriedSheet = false;
1024
+ /** @type {ReturnType<typeof closeUnbuiltSheetSteps>|null} */
1025
+ let sheetHitl = null;
1026
+ if (sheetTables) {
1027
+ // 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
1028
+ const roles = Object.keys(sheetTables);
1029
+ const given = new Set();
1030
+ declaration.steps = (Array.isArray(declaration.steps) ? declaration.steps : []).map((/** @type {any} */ st) => {
1031
+ if (!isPlainObject(st) || !isPlainObject(st.close)) return st;
1032
+ const { sheet: carried, ...close } = st.close;
1033
+ if (carried !== undefined) carriedSheet = true;
1034
+ 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) : [];
1035
+ if (mine.length) given.add(st.fromLine);
1036
+ return { ...st, close: mine.length ? { ...close, sheet: mine } : close };
1037
+ });
1038
+ 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` }));
1039
+ sheetBuilt = await buildSheetChecks({ declaration, lines, tables: sheetTables });
1040
+ Object.assign(declaration, { steps: sheetBuilt.declaration.steps });
1041
+ // 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
1042
+ const closed = closeUnbuiltSheetSteps(declaration, sheetBuilt.unbuilt);
1043
+ Object.assign(declaration, closed.declaration);
1044
+ sheetHitl = closed;
1045
+ if (sheetBuilt.refused.length || unplaced.length) entry.sheetRefused = [...unplaced, ...sheetBuilt.refused];
1046
+ }
1047
+ // 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)
985
1048
  let sheetOnList = null;
986
1049
  /** @type {any[]} */
987
1050
  let sheetDroppedNow = [];
988
1051
  if (block) {
989
1052
  // 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
1053
  for (const d of carriedSheetDropped) {
991
- const r = sheetChoice({ declaration, lines, csvRoles: csvRolesOf(arbiter), op: 'drop', key: d.key, dropped: sheetDroppedNow });
1054
+ // 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
1055
+ const key = keyOfSameCheck(declaration, d);
1056
+ if (key === null) continue;
1057
+ const r = sheetChoice({ declaration, lines, csvRoles: csvRolesOf(arbiter), op: 'drop', key, dropped: sheetDroppedNow });
992
1058
  if (r.ok) { Object.assign(declaration, { steps: r.declaration.steps }); sheetDroppedNow = r.dropped; }
993
1059
  }
994
1060
  onSheetDropped(sheetDroppedNow);
995
1061
  }
1062
+ /** @type {ReturnType<typeof withTicketRows>['tickets']|null} */
1063
+ let ticketOnList = null;
1064
+ if (block && flowType === 'tickets') { const w = withTicketRows({ declaration, lines }); ticketOnList = w.tickets; if (w.tickets.signed.length) Object.assign(declaration, { checkList: w.declaration.checkList }); }
996
1065
  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 }); }
997
1066
  // 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
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) : [])]);
1067
+ 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) : [])]);
999
1068
  // 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
1069
  // 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
1070
  const inPlan = block ? new Set(block.rows.filter((r) => r.state === 'built').flatMap((r) => (r.factNames ?? []).map((/** @type {string} */ nm) => `${r.line}:${nm}`))) : null;
@@ -1003,7 +1072,7 @@ export async function draft({
1003
1072
  const verdict1 = validateDeclaration(declaration, {
1004
1073
  arbiter, lines, catalogue: validationCatalogue, wired: WIRED_VERBS, verbatimGoals: true, fitJobLine: true,
1005
1074
  // 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
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,
1075
+ 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,
1007
1076
  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) },
1008
1077
  });
1009
1078
  // 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)
@@ -1016,18 +1085,22 @@ export async function draft({
1016
1085
  continue;
1017
1086
  }
1018
1087
  const planRed = verdict1.ok ? findMcpPlanRed(declaration) : null;
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;
1088
+ 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;
1089
+ const verdict = carriedRed ? { ok: false, reds: [carriedRed] } : planRed ? { ok: false, reds: [planRed] } : verdict1;
1022
1090
  lastDecl = declaration;
1023
1091
  const asked = askOpen ? normalizeQuestions(rawQuestions, failedLines) : { kept: [], dropped: [] };
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 } } : {}) };
1092
+ const uncovered = [...uncoveredRules(declaration, jobLines, Object.keys(facts.sheets ?? {}), sheetBuilt ?? undefined), ...(sheetHitl?.lost ?? [])];
1093
+ // the tag of a note no row tells: any note code writes is [default]; a row's own tag wins
1094
+ // 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
1095
+ // (`uncovered`). A drop of a prose word is no rule and stays.
1096
+ const ruleKey = (/** @type {string} */ t) => t.split(' \u2014 ')[0];
1097
+ const sheetRuleKeys = new Set(jobLines.filter((l) => sheetLineNums.includes(l.n)).flatMap((l) => lineRules(l).map((r) => `line ${l.n}: "${r}"`)));
1098
+ const lookNotChecked = pageNotChecked.filter((t) => !sheetRuleKeys.has(ruleKey(t)));
1099
+ /** @type {Record<string, 'you'|'agent'|'default'>} */
1100
+ const noteBy = Object.fromEntries([...lookNotChecked, ...uncovered].map((t) => [t, 'default']));
1101
+ const ticketNotChecked = (ticketOnList?.notChecked ?? []).map((t) => `not checked · "${t.rule}" — ${t.reason}`);
1102
+ for (const t of ticketNotChecked) noteBy[t] = 'you';
1103
+ extras = { questions: asked.kept, droppedQuestions: asked.dropped, notChecked: [...new Set([...lookNotChecked, ...(assembled ? assembled.notChecked : []), ...ticketNotChecked, ...uncovered])], ...(assembled ? { notCheckedBy: { ...noteBy, ...assembled.notCheckedBy } } : {}) };
1031
1104
  if (asked.dropped.length) entry.droppedQuestions = asked.dropped;
1032
1105
  // the declaration the model sent, as parsed, before any code overwrite (log.json keeps it per try)
1033
1106
  entry.args = captured;
@@ -1045,9 +1118,9 @@ export async function draft({
1045
1118
  entry.outcome = 'valid';
1046
1119
  log.push(entry);
1047
1120
  const m = sumMeterings(meterings);
1048
- return {
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) } : {}),
1050
- };
1121
+ return withAction({
1122
+ 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; })() } : {}),
1123
+ });
1051
1124
  }
1052
1125
  lastReds = [...verdict.reds];
1053
1126
  entry.outcome = `validator: ${verdict.reds.length} red(s)`;
@@ -1067,7 +1140,7 @@ export async function draft({
1067
1140
  const m = sumMeterings(meterings);
1068
1141
  // Runner convention: `costUsd` is the priced sum (null when ANY round is unpriced, so the CLI prints UNKNOWN,
1069
1142
  // never a bare number), and `spendComplete:false` marks a call that failed unmetered or a round left unpriced.
1070
- return {
1143
+ return withAction({
1071
1144
  ok: false, declaration: lastDecl, reds: lastReds, 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, log, thinking: thinkingOf(), inputs: facts.list, ...extras, ...pageExtras,
1072
- };
1145
+ });
1073
1146
  }