fwdloop 0.33.0 → 0.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/bin/fwdloop +14 -2
  2. package/package.json +1 -1
  3. package/src/auditchecks.js +6 -4
  4. package/src/authoring.js +4 -3
  5. package/src/blockasks.js +3 -2
  6. package/src/blockassemble.js +40 -21
  7. package/src/blockdraft.js +8 -13
  8. package/src/blockpick.js +11 -1
  9. package/src/checkblock.js +95 -56
  10. package/src/checklist.js +1 -1
  11. package/src/checklistsign.js +1 -1
  12. package/src/checkpick.js +7 -73
  13. package/src/declaration.js +9 -7
  14. package/src/drafter.js +152 -130
  15. package/src/noteask.js +62 -0
  16. package/src/pageask.js +5 -68
  17. package/src/pagedry.js +27 -4
  18. package/src/pagerules.js +19 -3
  19. package/src/panel/author.js +3 -3
  20. package/src/panel/authorcard.js +34 -11
  21. package/src/panel/index.html +7 -1
  22. package/src/pickrecord.js +42 -54
  23. package/src/planrebuild.js +16 -6
  24. package/src/rowedit.js +35 -5
  25. package/src/rubricstep.js +9 -1
  26. package/src/setup.js +1 -1
  27. package/src/sheetblock.js +17 -7
  28. package/src/sheetbuild.js +151 -0
  29. package/src/sheetchecks.js +3 -2
  30. package/src/sheetfind.js +4 -4
  31. package/src/sheetlook.js +14 -3
  32. package/src/sheetoffer.js +50 -5
  33. package/src/sheetrows.js +18 -2
  34. package/src/ticket-draft.js +4 -21
  35. package/src/ticketrows.js +100 -0
  36. package/types/auditchecks.d.ts +2 -1
  37. package/types/authoring.d.ts +4 -2
  38. package/types/blockasks.d.ts +1 -2
  39. package/types/blockassemble.d.ts +20 -3
  40. package/types/blockdraft.d.ts +4 -12
  41. package/types/blockpick.d.ts +5 -0
  42. package/types/checkblock.d.ts +32 -17
  43. package/types/checklist.d.ts +3 -3
  44. package/types/checkpick.d.ts +4 -34
  45. package/types/declaration.d.ts +7 -0
  46. package/types/drafter.d.ts +15 -355
  47. package/types/noteask.d.ts +52 -0
  48. package/types/pageask.d.ts +0 -35
  49. package/types/pagedry.d.ts +13 -0
  50. package/types/pagerules.d.ts +7 -0
  51. package/types/panel/authorcard.d.ts +13 -8
  52. package/types/panel/authorflows.d.ts +4 -4
  53. package/types/panel/data.d.ts +1 -1
  54. package/types/pickrecord.d.ts +47 -13
  55. package/types/rowedit.d.ts +16 -1
  56. package/types/rubricstep.d.ts +3 -0
  57. package/types/sheetblock.d.ts +11 -4
  58. package/types/sheetbuild.d.ts +84 -0
  59. package/types/sheetchecks.d.ts +2 -1
  60. package/types/sheetfind.d.ts +2 -2
  61. package/types/sheetoffer.d.ts +26 -1
  62. package/types/sheetrows.d.ts +8 -0
  63. package/types/ticket-draft.d.ts +3 -49
  64. package/types/ticketrows.d.ts +61 -0
  65. package/src/repairs.js +0 -38
  66. package/types/repairs.d.ts +0 -13
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,30 +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, codeScope,
34
+ offerRules, rowsFromAnswer, retentionOf, SUGGEST_SYSTEM, SUGGEST_TOOL, SUGGEST_SCHEMA, suggestUserText, codeScope,
36
35
  } from './checkpick.js';
37
36
  // M16 (docs/wiki/the-module-ladder.md, "M16"): the check block's turns, wired beside the declaration path
38
37
  import { blockJobLines } from './blocklines.js';
39
38
  import { setUpBlock, ticketLeaveOut, pickEdits, ledgerEdits, repairedEditsReadable, editRecord, renderRejectBlock, buildFaultWords, isBuildFault } from './blockdraft.js';
40
- import { assembleFromBlock } from './blockassemble.js';
39
+ import { assembleFromBlock, closeUnbuiltSheetSteps } from './blockassemble.js';
41
40
  import { cardOfBlock } from './cardlist.js';
42
41
  import { questionsOfBlock } from './blockasks.js';
42
+ import { NOTE_KIND, NOTE_TOOL, NOTE_SYSTEM, NOTE_SCHEMA, notePrompt, noteAnswers } from './noteask.js';
43
43
  import { ledgerRecord, LEDGER_SYSTEM, LEDGER_SCHEMA, LEDGER_TOOL, ledgerUserText } from './checklist.js';
44
- import { ROW_EDIT_SYSTEM, ROW_EDIT_REVISE, rowEditUserText, rowEditChannel, editsOf } from './rowedit.js';
45
- import { matchRecord, entriesFromAnswers, sameWords, KEPT_WORDS } from './pickrecord.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';
46
46
  import { MAP_SYSTEM, mapPrompt } from './pagemap.js';
47
- import { askableFromLook, tooManyAsksText, MAX_LOOK_ASKS } from './pageask.js';
47
+ import { tooManyAsksText, MAX_LOOK_ASKS } from './pageask.js';
48
48
  import { lineRules } from './pagebits.js';
49
49
  import { isCountGuardrail } from './declaration.js';
50
- import { repairDeclaration } from './repairs.js';
51
50
  import path from 'node:path';
52
51
  import { isCellsPath } from './closers.js';
53
52
  import { parseCsv, sheetTable } from './csv.js';
54
- import { sheetChecksProp, sheetOfferRules } from './sheetoffer.js';
53
+ import { sheetSuggestProp, sheetOfferRules, agreedColumnWords } from './sheetoffer.js';
55
54
  import { uncoveredRules, csvRolesOf } from './sheetblock.js';
56
- import { withSheetRows, withSheetCard, sheetChoice } from './sheetrows.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';
57
58
  import {
58
59
  makeProvider, ModelRefusal, sumMeterings, ceilingCostUsd, priceRecord,
59
60
  } from './provider.js';
@@ -96,14 +97,12 @@ const COLUMNS_PROP = Object.freeze({
96
97
  });
97
98
 
98
99
  /**
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.
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).
101
101
  * M13 piece 4: `ticket` = `{flowType, tools}` for MCP (generic) and Tickets; then a step may carry `mcpTools` (an enum of the job's tools) and, for Tickets, the tool carries `ticketFilter` and `ticketWatch` (src/ticket-draft.js). The job's `mcp` block and `flowType` are set by code, never offered.
102
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 {{sheets?: Record<string, {header: string[]}>, ticket?: {flowType: 'mcp'|'tickets', tools: string[]}}} [o]
103
+ * @param {any[]} menu @param {{ticket?: {flowType: 'mcp'|'tickets', tools: string[]}}} [o]
104
104
  */
105
- export function buildDeclarationSchema(menu, { sheets, ticket } = {}) {
106
- const sheetProp = sheets ? sheetChecksProp(sheets) : null;
105
+ export function buildDeclarationSchema(menu, { ticket } = {}) {
107
106
  const ticketParts = ticket ? ticketSchemaParts(ticket) : null;
108
107
  return {
109
108
  type: 'object',
@@ -133,7 +132,6 @@ export function buildDeclarationSchema(menu, { sheets, ticket } = {}) {
133
132
  properties: {
134
133
  class: { type: 'string', enum: [...CLASSES], description: "MUST equal the class of fromLine's guardrail in guardrailClasses; hitl when that line has no guardrail" },
135
134
  columns: COLUMNS_PROP,
136
- ...(sheetProp ? { sheet: sheetProp } : {}),
137
135
  },
138
136
  required: ['class'],
139
137
  additionalProperties: false,
@@ -149,11 +147,6 @@ export function buildDeclarationSchema(menu, { sheets, ticket } = {}) {
149
147
  additionalProperties: { type: 'string', enum: [...CLASSES] },
150
148
  description: 'one class per job line that HAS a guardrail, keyed by line number as a string',
151
149
  },
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
150
  refused: {
158
151
  type: 'array',
159
152
  items: {
@@ -165,33 +158,17 @@ export function buildDeclarationSchema(menu, { sheets, ticket } = {}) {
165
158
  description: 'job lines that cannot be served at all, with a reason; [] if none',
166
159
  },
167
160
  },
168
- required: ['steps', 'guardrailClasses', 'unjudgeable', 'refused'],
161
+ required: ['steps', 'guardrailClasses', 'refused'],
169
162
  additionalProperties: false,
170
163
  };
171
164
  }
172
165
 
173
166
  const TOOL = 'emit_declaration';
174
167
 
175
- // ---- 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) ---------------------------------
176
169
  // borrowed-from: fwdloop poc/am24-questions/draft.mjs@dda0e0f (prompts, linesNamedByReds, normalizeQuestions), adjusted to the product drafter.
177
170
  export const MAX_QUESTIONS = 2;
178
171
 
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
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. */
196
173
  export const QUESTIONS_PROMPT = [
197
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',
@@ -200,11 +177,12 @@ export const QUESTIONS_PROMPT = [
200
177
  'Still emit the complete corrected declaration.',
201
178
  ].join('\n');
202
179
 
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' } };
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 = {};
208
186
  if (questions) {
209
187
  extra.questions = {
210
188
  type: 'array',
@@ -256,11 +234,6 @@ export function normalizeQuestions(raw, failedLines) {
256
234
  return { kept, dropped };
257
235
  }
258
236
 
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
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.
265
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)
266
239
  const shownRules = (/** @type {string} */ guardrail, all = false) => lineRules({ rule: guardrail }).filter((r) => all || !isCountGuardrail(r)).join('; ');
@@ -301,7 +274,6 @@ function greenReadRule(sources) {
301
274
  : `${rule} This job signs no CSV input, so a guardrail that needs a sheet check cannot be classed green here: class it "hitl".`];
302
275
  // M16 S5: the check block builds the quote checks of its lines; the drafter is told nothing of close.cited and offers none
303
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.`);
304
- if (csvRoles.length) out.push(...sheetOfferRules(csvRoles)); // M10b piece 3: close.sheet and every rule the validator enforces on it
305
277
  return out;
306
278
  }
307
279
 
@@ -320,14 +292,6 @@ function whenToUse(menu) {
320
292
  return Object.entries(WHEN_TO_USE).filter(([verb]) => on.has(verb)).map(([, line]) => line);
321
293
  }
322
294
 
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
295
  export function buildSystemPrompt({ menu, lines, arbiter, factsInfo, blockLines = /** @type {Set<number>} */ (new Set()) }) {
332
296
  const askLines = arbiter.asks.map((a) => a.line);
333
297
  const sendLines = arbiter.sends.map((s) => s.line);
@@ -358,7 +322,6 @@ export function buildSystemPrompt({ menu, lines, arbiter, factsInfo, blockLines
358
322
  '',
359
323
  'The numbered job lines:',
360
324
  jobLinesText(lines, arbiter.asks, blockLines),
361
- ...sheetRuleNumbers(lines, arbiter),
362
325
  ].join('\n');
363
326
  }
364
327
 
@@ -399,7 +362,7 @@ function isPlainObject(v) { return !!v && typeof v === 'object' && !Array.isArra
399
362
  export async function draft({
400
363
  proseText, slot, model, provider: injected, rates: injectedRates, modelId: injectedModelId, env,
401
364
  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}[]} */ ([]),
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} */ (() => {}),
403
366
  checkPicks = /** @type {import('./checkpick.js').Pick[]} */ ([]),
404
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
405
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),
@@ -511,8 +474,6 @@ export async function draft({
511
474
  const look = { facts: [], dropped: [] };
512
475
  /** @type {string[]} */
513
476
  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
477
  /** @type {any[]} */
517
478
  const pageLooks = [];
518
479
  /** @type {Record<string, any>} */
@@ -593,7 +554,6 @@ export async function draft({
593
554
  if (left.length) {
594
555
  look.dropped.push(...left);
595
556
  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
557
  pageInfo.push(' You chose to leave these Not checked; never claim them as checked:', ...lines.map((x) => ` - ${x}`));
598
558
  }
599
559
  }
@@ -606,6 +566,9 @@ export async function draft({
606
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);
607
567
  const sheetRoles = sheetJobLines.some((l) => lineRules(l).length > 0) ? [...Object.keys(facts.sheets ?? {}), ...docxRoles] : [];
608
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));
609
572
  const sheetAsks = [];
610
573
  /** @type {any[]} */
611
574
  const sheetFacts = [];
@@ -625,11 +588,12 @@ export async function draft({
625
588
  };
626
589
  }
627
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).
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 }));
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 }));
629
593
  const dropped = [...got.dropped, ...declined];
630
- 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)
631
595
  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 });
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 });
633
597
  const lost = dropRows(dropped).map((row) => dropLine(row, jobLines, lineRules));
634
598
  for (const l of lost) if (!pageNotChecked.includes(l)) pageNotChecked.push(l);
635
599
  pageInfo.push(
@@ -706,17 +670,18 @@ export async function draft({
706
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
707
671
  // (offerQuestions false) makes no call: it settles every rule against the person's picks instead.
708
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
709
- const allShape = offerRules(lines, arbiter, [...look.facts, ...sheetFacts]);
673
+ const shapeEverywhere = offerRules(lines, arbiter, [...look.facts, ...sheetFacts]);
710
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.
711
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)
712
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) : [];
713
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]);
714
678
  if (blockPlan && !blockPlan.ok) return fail(blockPlan.reds.map((r) => `signed-text: ${r}`));
715
679
  const blockLineNums = new Set(blockPlan ? blockPlan.jobLines.map((l) => l.n) : []);
716
- const blockScoped = allShape.filter((r) => blockLineNums.has(r.line));
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));
717
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.
718
683
  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 }));
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 }));
720
685
  onPickRecord?.({ picks: carried.kept.map((k) => k.entry), kept: keptView });
721
686
  const askRules = carried.askRules;
722
687
  /** the block (M16 S1): the person's rules, the look, the picks kept and just answered, reconciled once */
@@ -727,19 +692,16 @@ export async function draft({
727
692
  block = setUpBlock({
728
693
  texts: { ...(facts.docs ?? {}), ...Object.fromEntries(Object.entries(pages).map(([role, pg]) => [role, pg.text])) }, jobLines: blockPlan.jobLines, look,
729
694
  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]),
695
+ fresh: { picks: checkPicks.filter(inBlock), left: leftRules.filter(inBlock) }, asks: offerQuestions, countScope: (t) => codeScope(arbiter.sources, t) === 'in', leaveOut: ticketLeaveOut(flowType, blockPlan.jobLines),
731
696
  });
732
697
  }
733
- /** @type {ReturnType<typeof checkAsks>} */
734
- let shapeAsks = [];
735
698
  if (askRules.length && offerQuestions) {
736
699
  const content = suggestUserText(lines, askRules);
737
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 } });
738
701
  if (got.early) return got.early;
739
702
  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
703
+ // M16 S2 (R1): a kept check is a `pick` edit of the block, before any asks
741
704
  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
705
  }
744
706
  if (block && blockPlan?.ok && blockPlan.jobLines.length > 0 && Object.keys(block.texts).length > 0) {
745
707
  const texts = block.texts;
@@ -753,57 +715,57 @@ export async function draft({
753
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
754
716
  if (block && Array.isArray(carriedChoices)) { block.carryChoices(carriedChoices); onChoices(block.choicesRecord()); block.reconcile(); }
755
717
  /** 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) : [];
718
+ const blockAsks = block && offerQuestions ? questionsOfBlock(block, allShape) : [];
757
719
  if (block) pageExtras.checkRows = ledgerRecord(/** @type {any} */ (block.rows));
758
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
759
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.
760
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.
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')];
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')];
765
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).
766
727
  const blockShape = blockAsks.filter((a) => a.ask === 'no-check' || a.ask === 'check');
767
- const asks = [...lookAsks, ...shapeAsks, ...blockShape];
728
+ const asks = [...lookAsks, ...blockShape];
768
729
  if (asks.length > 0) {
769
730
  const m = sumMeterings(meterings);
770
731
  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" }))];
732
+ const counted = [...lookAsks, ...blockShape.filter((a) => a.counted).map((a) => ({ ...a, reading: "I can't check this" }))];
772
733
  const tooMany = counted.length > MAX_LOOK_ASKS;
773
734
  if (tooMany && pageSources.length) removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); // a refused draft keeps no page copy
774
735
  return {
775
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,
776
737
  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 } : {}),
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 } : {}),
778
739
  })),
779
740
  droppedQuestions: [], notChecked: pageNotChecked, ...pageExtras,
780
741
  };
781
742
  }
782
743
  }
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
744
+ // the record this draft hands on: what it kept plus what the person just answered (numbered on this card)
791
745
  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
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).
799
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")
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;
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;
802
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
803
765
  const lookReport = pageSources.length ? { prose: [], notFound: [], facts: look.facts, dropped: look.dropped } : null;
804
766
  /** @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: [] });
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: [] });
807
769
  for (let rev = 0; ; rev += 1) {
808
770
  const got = await forcedTurn({
809
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 },
@@ -811,6 +773,12 @@ export async function draft({
811
773
  });
812
774
  if (got.early) return got.early;
813
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));
814
782
  const rec = block.applyDelta({ label: `row-edit-${rev + 1}`, edits: editsOf(got.args) });
815
783
  block.reconcile();
816
784
  got.entry.edits = editRecord(rec);
@@ -820,17 +788,29 @@ export async function draft({
820
788
  }
821
789
  pageExtras.checkRows = ledgerRecord(/** @type {any} */ (block.rows));
822
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
+ }
804
+ }
823
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.
824
806
  const factsBase = pageInfo.length ? [...facts.info.filter((l) => !pageSources.some((s) => l.startsWith(`- ${s.role}: a web page`))), ...pageInfo] : facts.info;
825
807
  const factsInfo = [...factsBase, ...ticketSources.flatMap((s) => ticketFactsLines(s.role)), ...(flowType === 'mcp' ? mcpFactsLines(mcp.server, mcp.tools) : [])];
826
808
 
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;
809
+ // `questions` only on try 3 (below).
830
810
  const baseSystem = buildSystemPrompt({ menu, lines, arbiter, factsInfo, blockLines: blockLineNums });
831
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).
832
812
  // 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}` : ''}`;
813
+ const system = `${baseSystem}${learnHints?.text ? `\n\n${learnHints.text}` : ''}`;
834
814
  let structureRetries = 0;
835
815
  let revisions = 0;
836
816
  let lastReds = [];
@@ -855,7 +835,7 @@ export async function draft({
855
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
856
836
  // validator's refusals fed back), gets the `questions` property; the redraft after an answer passes offerQuestions:false and never does.
857
837
  const askOpen = offerQuestions && revisions === MAX_REVISIONS;
858
- 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 } });
859
839
  const tool = {
860
840
  name: TOOL,
861
841
  description: 'Emit the flow declaration over the granted primitives, or refuse lines you cannot serve.',
@@ -944,58 +924,96 @@ export async function draft({
944
924
  entry.braceRepair = { dropped: fixed.dropped, used: true };
945
925
  }
946
926
 
947
- // `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
948
928
  // 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);
929
+ const { questions: rawQuestions, notChecked: _aiNotes, ...captureRest } = /** @type {Record<string, any>} */ (captured);
950
930
  /** @type {Record<string, any>} */
951
931
  const declaration = { ...(askOpen ? captureRest : { ...captureRest, ...(rawQuestions === undefined ? {} : { questions: rawQuestions }) }), inputFacts: facts.inputFacts };
952
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.
953
933
  declaration.flowType = flowType;
954
934
  if (flowType === 'plain') delete declaration.mcp;
955
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
+ }
956
944
  // M6a amendment 1 (F50): the goal is the signed line, set by the machine; whatever the model sent is overwritten.
957
945
  if (Array.isArray(declaration.steps)) {
958
946
  declaration.steps = declaration.steps.map((st) => (isPlainObject(st) ? { ...st, goal: goalForLine(st.fromLine, lines) } : st));
959
947
  }
960
948
  // M13 am9 item 4: the last Ask before the added `write it out` reads every step; code sets it, whatever the model sent
961
949
  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)
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)
964
953
  if (Array.isArray(declaration.steps)) {
965
954
  declaration.steps = declaration.steps.map((st) => {
966
955
  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
956
+ // M10 am22 (3): `close.picked` is code's from the list (assembleFromBlock, next); one the drafter sent is dropped here too
968
957
  const { shape: _drop, picked: _dropPicked, ...close } = st.close;
969
958
  return { ...st, close };
970
959
  });
971
960
  }
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
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
975
962
  delete declaration.checkList;
976
963
  let assembled = null;
977
964
  if (block && blockPlan?.ok) {
978
- assembled = assembleFromBlock({ declaration, block, lines, lineSet: blockLineNums });
965
+ assembled = assembleFromBlock({ declaration, block, lines, lineSet: blockLineNums, askLines });
979
966
  Object.assign(declaration, assembled.declaration);
980
967
  if (assembled.declaration.pickedLines === undefined) delete declaration.pickedLines;
981
968
  }
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)
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)
985
997
  let sheetOnList = null;
986
998
  /** @type {any[]} */
987
999
  let sheetDroppedNow = [];
988
1000
  if (block) {
989
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)
990
1002
  for (const d of carriedSheetDropped) {
991
- const r = sheetChoice({ declaration, lines, csvRoles: csvRolesOf(arbiter), op: 'drop', key: d.key, dropped: sheetDroppedNow });
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 });
992
1007
  if (r.ok) { Object.assign(declaration, { steps: r.declaration.steps }); sheetDroppedNow = r.dropped; }
993
1008
  }
994
1009
  onSheetDropped(sheetDroppedNow);
995
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 }); }
996
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 }); }
997
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
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) : [])]);
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) : [])]);
999
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
1000
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)
1001
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;
@@ -1003,7 +1021,7 @@ export async function draft({
1003
1021
  const verdict1 = validateDeclaration(declaration, {
1004
1022
  arbiter, lines, catalogue: validationCatalogue, wired: WIRED_VERBS, verbatimGoals: true, fitJobLine: true,
1005
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
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,
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,
1007
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) },
1008
1026
  });
1009
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)
@@ -1016,18 +1034,22 @@ export async function draft({
1016
1034
  continue;
1017
1035
  }
1018
1036
  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;
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;
1022
1039
  lastDecl = declaration;
1023
1040
  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 } } : {}) };
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 } } : {}) };
1031
1053
  if (asked.dropped.length) entry.droppedQuestions = asked.dropped;
1032
1054
  // the declaration the model sent, as parsed, before any code overwrite (log.json keeps it per try)
1033
1055
  entry.args = captured;
@@ -1046,7 +1068,7 @@ export async function draft({
1046
1068
  log.push(entry);
1047
1069
  const m = sumMeterings(meterings);
1048
1070
  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) } : {}),
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; })() } : {}),
1050
1072
  };
1051
1073
  }
1052
1074
  lastReds = [...verdict.reds];