fwdloop 0.28.0 → 0.30.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 (74) hide show
  1. package/README.md +1 -1
  2. package/bin/fwdloop +27 -5
  3. package/package.json +3 -3
  4. package/src/added-end.js +60 -0
  5. package/src/ask.js +1 -1
  6. package/src/audit-fold.js +9 -1
  7. package/src/authoring.js +18 -7
  8. package/src/checked.js +14 -9
  9. package/src/checkpick.js +318 -0
  10. package/src/checkwords.js +29 -0
  11. package/src/citedcheck.js +14 -0
  12. package/src/closers.js +40 -3
  13. package/src/declaration.js +102 -5
  14. package/src/draft-steps.js +3 -3
  15. package/src/drafter.js +151 -38
  16. package/src/jobkey.js +3 -1
  17. package/src/learn.js +1 -1
  18. package/src/learnstore.js +6 -6
  19. package/src/memo.js +120 -0
  20. package/src/model-step.js +103 -25
  21. package/src/pageask.js +12 -6
  22. package/src/pagedropwords.js +9 -0
  23. package/src/panel/author.js +33 -10
  24. package/src/panel/authorcard.js +59 -6
  25. package/src/panel/data.js +16 -10
  26. package/src/panel/index.html +151 -59
  27. package/src/panel/result.js +28 -7
  28. package/src/panel/server.js +2 -1
  29. package/src/pickrecord.js +146 -0
  30. package/src/plain-checks.js +16 -3
  31. package/src/provider.js +4 -1
  32. package/src/repairs.js +38 -0
  33. package/src/runfile.js +4 -2
  34. package/src/runner.js +129 -40
  35. package/src/send.js +71 -4
  36. package/src/setup.js +13 -1
  37. package/src/sheetblock.js +2 -1
  38. package/src/ticket-draft.js +2 -2
  39. package/src/ticket-labels.js +2 -2
  40. package/src/try-checks.js +13 -3
  41. package/src/whole-job.js +71 -0
  42. package/types/added-end.d.ts +62 -0
  43. package/types/ask.d.ts +2 -1
  44. package/types/audit-fold.d.ts +13 -2
  45. package/types/authoring.d.ts +6 -2
  46. package/types/checked.d.ts +7 -2
  47. package/types/checkpick.d.ts +183 -0
  48. package/types/checkwords.d.ts +18 -0
  49. package/types/citedcheck.d.ts +6 -0
  50. package/types/closers.d.ts +6 -3
  51. package/types/declaration.d.ts +12 -0
  52. package/types/drafter.d.ts +28 -25
  53. package/types/learn.d.ts +1 -0
  54. package/types/learnstore.d.ts +2 -3
  55. package/types/memo.d.ts +15 -0
  56. package/types/model-step.d.ts +23 -3
  57. package/types/pageask.d.ts +9 -2
  58. package/types/pagedropwords.d.ts +1 -0
  59. package/types/panel/author.d.ts +1 -1
  60. package/types/panel/authorcard.d.ts +41 -0
  61. package/types/panel/data.d.ts +1 -1
  62. package/types/panel/jobgrid.d.ts +1 -1
  63. package/types/panel/result.d.ts +9 -3
  64. package/types/pickrecord.d.ts +88 -0
  65. package/types/plain-checks.d.ts +9 -1
  66. package/types/repairs.d.ts +13 -0
  67. package/types/runfile.d.ts +7 -2
  68. package/types/runner.d.ts +16 -5
  69. package/types/send.d.ts +10 -2
  70. package/types/setup.d.ts +1 -56
  71. package/types/try-checks.d.ts +1 -7
  72. package/types/whole-job.d.ts +70 -0
  73. package/src/attemptdiff.js +0 -118
  74. package/types/attemptdiff.d.ts +0 -38
@@ -42,6 +42,7 @@ import { factPartReds } from './citedcheck.js';
42
42
  import { numberRuleReds, countReds, citedWordReds } from './citedwords.js';
43
43
  import { SHEET_RULES, MAX_SHEET_CHECKS, sheetCheckColumns, sheetCheckReds, sheetCheckWordReds, sheetNoClaimReds, sheetCoversReds } from './sheetchecks.js';
44
44
  import { lineRules } from './pagebits.js';
45
+ import { OFFERED as OFFERED_RULES } from './checkwords.js';
45
46
  import { isColumnChoiceRule } from './sheetoffer.js';
46
47
 
47
48
  /** @typedef {import('./types.js').Arbiter} Arbiter */
@@ -63,6 +64,7 @@ export const DECLARATION_FIELDS = Object.freeze([
63
64
  'flowType',
64
65
  'ticketFilter',
65
66
  'ticketWatch',
67
+ 'pickedLines',
66
68
  // step level
67
69
  'goal',
68
70
  'primitives',
@@ -78,6 +80,7 @@ export const DECLARATION_FIELDS = Object.freeze([
78
80
  'cited',
79
81
  'columns',
80
82
  'sheet',
83
+ 'picked',
81
84
  ]);
82
85
 
83
86
  const VALID_CLASSES = Object.freeze(['green', 'softgreen', 'hitl']);
@@ -88,9 +91,9 @@ const VALID_CLASSES = Object.freeze(['green', 'softgreen', 'hitl']);
88
91
  // an ask's position, an ask's TTL, the egress allow-list...").
89
92
  const ARBITER_KEYS = Object.freeze(['cap', 'ask', 'ttl', 'send', 'source', 'trigger', 'skills']);
90
93
 
91
- const TOP_LEVEL_ALLOWED = Object.freeze(['steps', 'guardrailClasses', 'unjudgeable', 'refused', 'inputFacts', 'mcp', 'flowType', 'ticketFilter', 'ticketWatch']);
94
+ const TOP_LEVEL_ALLOWED = Object.freeze(['steps', 'guardrailClasses', 'unjudgeable', 'refused', 'inputFacts', 'mcp', 'flowType', 'ticketFilter', 'ticketWatch', 'pickedLines']);
92
95
  const STEP_ALLOWED = Object.freeze(['goal', 'primitives', 'reads', 'emits', 'fromLine', 'close', 'picks', 'mcpTools']);
93
- const CLOSE_ALLOWED = Object.freeze(['class', 'shape', 'cited', 'columns', 'sheet']);
96
+ const CLOSE_ALLOWED = Object.freeze(['class', 'shape', 'cited', 'columns', 'sheet', 'picked']);
94
97
 
95
98
  /** M13 piece 4 (signed item 4): the job's flow type, set by code from the job card, signed with the job. */
96
99
  export const FLOW_TYPES = Object.freeze(['plain', 'mcp', 'tickets']);
@@ -217,9 +220,14 @@ function checkOwnKeys(obj, allowed, path, reds) {
217
220
  export const SHAPE_KEYS = Object.freeze(['maxWords', 'sections', 'linesPerInvoice', 'mustCarry']);
218
221
 
219
222
  /** Shape keys only the MACHINE sets (M4e amendment 15): read from the line's guardrail, never offered to the drafter's model. */
220
- export const MACHINE_SHAPE_KEYS = Object.freeze(['wordsPerSection']);
223
+ export const MACHINE_SHAPE_KEYS = Object.freeze(['wordsPerSection', 'picked']);
221
224
 
222
225
  const SHAPE_TYPE_CHECKS = Object.freeze({
226
+ // M10 am16: the checks the person picked, set by code (src/checkpick.js applyPicks), each one a bareguard rule with only that rule's own fields
227
+ picked: {
228
+ expected: 'a non-empty array of checks, each an object with a text rule of bareguard\'s list',
229
+ check: (v) => Array.isArray(v) && v.length > 0 && v.every((c) => isPlainObject(c) && typeof c.rule === 'string' && OFFERED_RULES.includes(c.rule)),
230
+ },
223
231
  wordsPerSection: {
224
232
  expected: 'a positive integer',
225
233
  check: (v) => Number.isInteger(v) && v > 0,
@@ -377,6 +385,25 @@ export function guardrailWordNumbers(guardrail) {
377
385
  return [...guardrail.matchAll(/(?<![\d,])(\d{1,3}(?:,\d{3})+|\d+)\s*words?\b(?!\s*(?:each|per\s+section)\b)/gi)].map((m) => readNumber(m[1]));
378
386
  }
379
387
 
388
+ /** M10 amendment 14 item 2: every standalone number in a guardrail's own text (digits not joined to letters: "P1" and "250ish" are not one; "1,000" and "2.5" are one number each). */
389
+ export function guardrailStandaloneNumbers(guardrail) {
390
+ if (typeof guardrail !== 'string') return [];
391
+ return [...guardrail.matchAll(/(?<![A-Za-z0-9_.,])(\d{1,3}(?:,\d{3})+|\d+(?:\.\d+)?)(?![A-Za-z0-9_])/g)].map((m) => Number(m[1].replace(/,/g, '')));
392
+ }
393
+
394
+ /** M10 amendment 14 item 1: the send line (a signed send) is where the accepted result is written out and no AI runs, so a guardrail under it is refused at $0, naming the line.
395
+ * Pure; the card (src/panel/authorcard.js checkCard) and the drafter's pre-flight both call it. @param {any[]} lines `parseSignedText`'s lines @param {{sends?: {line: number}[]}} arbiter */
396
+ export function checkSendLineGuardrail(lines, arbiter) {
397
+ const reds = [];
398
+ for (const s of Array.isArray(arbiter?.sends) ? arbiter.sends : []) {
399
+ const l = (Array.isArray(lines) ? lines : []).find((x) => x?.n === s.line);
400
+ if (l && typeof l.guardrail === 'string' && l.guardrail.trim() !== '') {
401
+ reds.push(`line ${s.line} is the send line (it writes out what you accepted at the Ask before it, and no AI runs there), so it cannot carry the guardrail "${l.guardrail.trim()}". Put the guardrail on the line that makes the result.`);
402
+ }
403
+ }
404
+ return reds;
405
+ }
406
+
380
407
  /** M4e amendment 15 item 1: the "<n> words each" / "<n> words per section" size in a guardrail ("about 250 words each", "250ish each" -> 250), or null. */
381
408
  export function guardrailWordsPerSection(guardrail) {
382
409
  const m = typeof guardrail === 'string' ? /(?<![\d,])(\d{1,3}(?:,\d{3})+|\d+)(?:\s*words?|ish(?:\s+words?)?)\s+(?:each|per\s+section)\b/i.exec(guardrail) : null;
@@ -391,6 +418,16 @@ export function guardrailSectionCount(guardrail) {
391
418
  return /^\d+$/.test(m[1]) ? Number(m[1]) : NUMBER_WORDS[m[1].toLowerCase()];
392
419
  }
393
420
 
421
+ /** M10 amendment 23: the first "<N> bullets / list items / items / lines / points" in a guardrail (N digits, or the words one..ten; not a price like "$5 per item"), or null. */
422
+ export function guardrailItemCount(guardrail) {
423
+ const m = typeof guardrail === 'string' ? /(?<![$€£\d.,])\b(\d+|one|two|three|four|five|six|seven|eight|nine|ten)\s+(?:\w+\s+)?(?:bullets?|list items?|items?|lines?|points?)\b/i.exec(guardrail) : null;
424
+ if (!m) return null;
425
+ return /^\d+$/.test(m[1]) ? Number(m[1]) : NUMBER_WORDS[m[1].toLowerCase()];
426
+ }
427
+
428
+ /** M10 amendment 23: the ONE place that says a guardrail is a count code can check: N words, N bullets / list items / items / lines / points, or N sections. */
429
+ export const isCountGuardrail = (guardrail) => guardrailWordNumbers(guardrail).length > 0 || guardrailItemCount(guardrail) !== null || guardrailSectionCount(guardrail) !== null;
430
+
394
431
  /** M4e amendment 15 item 2: for each line whose guardrail gives a size for each section, a section count AND a word number,
395
432
  * size x count more than the LARGEST word number (no possible pick fits) is a red naming the line and the numbers. $0; run before any model
396
433
  * call, when there is no AI pick yet (amendment 29). After the draft the AI's `maxWords` is checked in checkShapeFitsJobLine. */
@@ -464,7 +501,8 @@ export function checkShapeFitsJobLine(step, i, lines, reds) {
464
501
  const wantPer = guardrailWordsPerSection(line?.guardrail);
465
502
  if (shape.wordsPerSection !== undefined && shape.wordsPerSection !== wantPer) {
466
503
  reds.push(`declaration: ${label} the check has wordsPerSection ${shape.wordsPerSection}; the guardrail says ${wantPer === null ? 'no size for each section' : `${wantPer} words each`} — change the guardrail on the card to change it`);
467
- } else if (shape.wordsPerSection === undefined && wantPer !== null) {
504
+ } else if (shape.wordsPerSection === undefined && wantPer !== null && !Array.isArray(shape.picked)) {
505
+ // (a shape of picked checks, M10 am16, was kept by code and chosen by the person: the guardrail's size is a check only if it was picked)
468
506
  reds.push(`declaration: ${label} the guardrail says ${wantPer} words each; the check has no wordsPerSection`);
469
507
  }
470
508
  // M4e amendment 16 C13: a size for each section needs the section names to be checked against.
@@ -518,6 +556,36 @@ function checkShapeBuilds(shape, label, reds, redsBefore) {
518
556
  }
519
557
  }
520
558
 
559
+ /**
560
+ * M10 am22 (3): `pickedLines` is the record of the fact lines that carry the person's picks: a list of line numbers. Code writes it (src/checkpick.js applyPicks).
561
+ * @param {Record<string, any>} declaration @param {string[]} reds
562
+ */
563
+ function checkPickedLines(declaration, reds) {
564
+ if (!Object.hasOwn(declaration, 'pickedLines')) return;
565
+ const v = declaration.pickedLines;
566
+ if (!Array.isArray(v) || v.length === 0 || !v.every((n) => Number.isInteger(n) && n > 0)) reds.push('declaration: "pickedLines" must be a non-empty list of line numbers');
567
+ }
568
+
569
+ /**
570
+ * M10 am22: `close.picked` is the checks the person picked for a fact line, kept beside its fact check and run on the answer's `text`. Code sets it (src/checkpick.js
571
+ * applyPicks); here it must be a green step's, a list of bareguard text rules that builds into a check.
572
+ * It is allowed ONLY on a line the signed plan records in `pickedLines` (written by code from the person's picks); a count on any other fact line is refused.
573
+ * @param {any} step @param {string} label @param {string} effectiveClass @param {string[]} reds @param {Record<string, any>} declaration
574
+ */
575
+ function checkPickedKey(step, label, effectiveClass, reds, declaration) {
576
+ const at = `declaration: ${label}.close.picked`;
577
+ if (step.close.class !== 'green' || effectiveClass !== 'green' || !(isPlainObject(step.close.cited) || Array.isArray(step.close.sheet))) {
578
+ reds.push(`${at} is for a step that checks facts (quotes or a sheet) only; this step's check is "${step.close.class ?? effectiveClass}"`);
579
+ return;
580
+ }
581
+ if (!Array.isArray(declaration.pickedLines) || !declaration.pickedLines.includes(step.fromLine)) {
582
+ reds.push(`${at}: line ${step.fromLine} is not one of the lines you picked checks for (pickedLines), so a count check cannot sit beside its fact check`);
583
+ return;
584
+ }
585
+ if (!SHAPE_TYPE_CHECKS.picked.check(step.close.picked)) { reds.push(`${at} must be ${SHAPE_TYPE_CHECKS.picked.expected}`); return; }
586
+ try { buildSoftgreenRubric({ picked: step.close.picked }); } catch (err) { reds.push(`${at} cannot be built into a check - ${String(err.message).replace(/^invalid rubric: /, '')}`); }
587
+ }
588
+
521
589
  /**
522
590
  * M10 amendment 7 item 1: `close.cited` is the facts a green step checks its quotes against, written by the drafter (a fact part:
523
591
  * `{source, facts, count?}`, src/citedcheck.js). Its SHAPE is checked in every mode (a signed flow is read the same way). With `fitJobLine` the number rules
@@ -625,6 +693,15 @@ function checkSheetKey(step, label, c, reds) {
625
693
  for (const r of sheetCheckReds(list, step.fromLine, tables)) reds.push(r);
626
694
  }
627
695
 
696
+ /** M10 am19: the tools that serve an input's kind (src/primitives.js rolePrimitiveFor): a page or ticket is frozen as text. */
697
+ function inputReachVerbs(source) {
698
+ if (source?.kind === 'page') return ['read', 'grep'];
699
+ const p = String(source?.path ?? '').toLowerCase();
700
+ if (p.endsWith('.docx')) return ['readDocx'];
701
+ if (isCellsPath(source?.path)) return ['addressCells'];
702
+ return ['read', 'grep'];
703
+ }
704
+
628
705
  /**
629
706
  * Validate a drafter declaration against the M1 closed schema. `arbiter`
630
707
  * and `lines` are `parseSignedText`'s output; `catalogue` is a plain array
@@ -689,6 +766,7 @@ export function validateDeclaration(declaration, context = {}) {
689
766
 
690
767
  // --- top level: unknown / arbiter keys -----------------------------------
691
768
  checkOwnKeys(declaration, TOP_LEVEL_ALLOWED, 'declaration', reds);
769
+ checkPickedLines(declaration, reds);
692
770
 
693
771
  // --- steps: must be a non-empty array, or nothing else here is meaningful
694
772
  if (!Array.isArray(declaration.steps) || declaration.steps.length === 0) {
@@ -890,7 +968,9 @@ export function validateDeclaration(declaration, context = {}) {
890
968
  if (cellsRoles.includes(readId) && !declaredEmits.has(readId)) continue; // an input with cells, frozen at run start (M4d amendment 8)
891
969
  if (pageRoles.includes(readId) && !declaredEmits.has(readId)) continue; // a web page, frozen at run start (M10 am7 item 3)
892
970
  if (docRoles.includes(readId) && !declaredEmits.has(readId) && step.close?.cited?.source === readId) continue; // a document the step quotes (M10 piece 5)
893
- if (readId === emits || !declaredEmits.has(readId)) {
971
+ if (docRoles.includes(readId) && !declaredEmits.has(readId)) {
972
+ reds.push(`declaration: ${label} reads document input "${readId}" — leave it out of reads and grant "read" ("readDocx" for .docx); only a step that quotes it lists it`);
973
+ } else if (readId === emits || !declaredEmits.has(readId)) {
894
974
  reds.push(`declaration: ${label} reads artifact "${readId}" that no earlier step declared`);
895
975
  }
896
976
  }
@@ -943,6 +1023,10 @@ export function validateDeclaration(declaration, context = {}) {
943
1023
  if (fitJobLine === true) checkShapeFitsJobLine(step, i, safeLines, reds);
944
1024
  }
945
1025
  }
1026
+ if (step.close.picked !== undefined) checkPickedKey(step, label, effectiveClass, reds, declaration);
1027
+ else if (fitJobLine === true && effectiveClass === 'green' && step.close.shape !== undefined && step.close.shape !== null) {
1028
+ reds.push(`declaration: ${label}.close.shape: a step that checks facts carries no count check of the drafter's own; only a check you picked (close.picked, on a line recorded in pickedLines) can sit beside its fact check`);
1029
+ }
946
1030
  if (step.close.cited !== undefined) checkCitedKey(step, label, { sourceRoles, reads, effectiveClass, lines: safeLines, fitJobLine, pageWords }, reds);
947
1031
  if (step.close.sheet !== undefined) checkSheetKey(step, label, { cellsRoles, reads, effectiveClass, lines: safeLines, fitJobLine, sheetWords }, reds);
948
1032
  if (step.close.columns !== undefined || (fitJobLine === true && sheetWords)) checkColumnsKey(step, label, { cellsRoles, reads, effectiveClass, lines: safeLines, sheetWords }, reds);
@@ -1162,6 +1246,19 @@ export function validateDeclaration(declaration, context = {}) {
1162
1246
  }
1163
1247
  }
1164
1248
 
1249
+ // --- check 7 (M10 am19): every input must be reachable by a model step (not an ask step, not the send step).
1250
+ // Ruling A, hamr 2026-11-04: md/txt/page/ticket -> read or grep; docx -> readDocx; a sheet -> addressCells; or the role in the step's `reads`.
1251
+ // `picks` / `inputFacts` name headings only and are not a grant. Plan-fit check: draft, revise and sign turn `fitJobLine` on; signed flows keep running.
1252
+ if (fitJobLine === true) {
1253
+ const modelSteps = stepInfo.filter((st) => st.fromLine === null || (!askLines.includes(st.fromLine) && !sendLines.includes(st.fromLine)));
1254
+ for (const s of Array.isArray(safeArbiter.sources) ? safeArbiter.sources : []) {
1255
+ const verbs = inputReachVerbs(s);
1256
+ if (!modelSteps.some((st) => st.reads.includes(s.role) || st.primitives.some((v) => verbs.includes(v)))) {
1257
+ reds.push(`Input "${s.role}" is read by no step.`);
1258
+ }
1259
+ }
1260
+ }
1261
+
1165
1262
  if (reds.length > 0) return deepFreeze({ ok: false, reds });
1166
1263
 
1167
1264
  const classes = {};
@@ -7,7 +7,7 @@
7
7
  // Throws away: the log's per-round tokens, the model's replies, the questions, and every try but the count of refused ones.
8
8
  // Third outcomes: no log -> null (nothing to list); a cost that is null reads "cost unknown", an incomplete sum reads "at least $X", never 0.
9
9
 
10
- import { plainPlanCheck } from './plain-checks.js';
10
+ import { plainPlanCheck, pickPlanRed } from './plain-checks.js';
11
11
 
12
12
  const REBUILD_RE = /^declaration: steps\[(\d+)\]\.close\.shape cannot be built into a check — (.*)$/s;
13
13
 
@@ -88,7 +88,7 @@ export function draftStepList({ log, declaration, questionOpen = false }) {
88
88
  out.push({ id: 'checks', label: 'plan checks · a question for you', status: 'waiting', details: [] });
89
89
  } else {
90
90
  // one plain reason and its one Fix line (every rule has fix wording): the first refusal
91
- const pick = checkReds.map(plainPlanCheck)[0];
91
+ const pick = checkReds.length > 0 ? plainPlanCheck(pickPlanRed(checkReds)) : undefined;
92
92
  out.push({ id: 'checks', label: pick ? `plan checks · ${pick.reason}` : 'plan checks', status: 'failed', details: [] });
93
93
  if (pick) out.push({ id: 'checks-fix', label: `Fix: ${pick.fix}`, status: 'done', details: [], note: true });
94
94
  }
@@ -130,7 +130,7 @@ export function reviseStepList({ log, name }) {
130
130
  if (reds.length > 0) facts.push(reds[0]);
131
131
  return [{ id: 'plan', label: facts.join(' · '), status: 'failed', details: [] }];
132
132
  }
133
- const pick = plainPlanCheck(checkReds[0]);
133
+ const pick = plainPlanCheck(pickPlanRed(checkReds));
134
134
  return [
135
135
  { id: 'plan', label: [name, pick.reason].join(' · '), status: 'failed', details: [] },
136
136
  { id: 'plan-fix', label: `Fix: ${pick.fix}`, status: 'done', details: [], note: true },
package/src/drafter.js CHANGED
@@ -18,7 +18,8 @@
18
18
  import { Loop, HaltError } from 'bare-agent';
19
19
  import { capTooSmallText, usdText } from './draftspend.js';
20
20
  import { parseSignedText, unsignedAskTtls } from './signed-text.js';
21
- import { validateDeclaration, SHAPE_KEYS, checkGuardrailSums, guardrailWordsPerSection } from './declaration.js';
21
+ import { validateDeclaration, checkGuardrailSums, checkSendLineGuardrail } from './declaration.js';
22
+ import { readEveryStep } from './whole-job.js';
22
23
  import { loadCatalogue } from './catalogue.js';
23
24
  import { findMcpPlanRed } from './canrun.js';
24
25
  import { WIRED_VERBS, wiredMenu } from './primitives.js';
@@ -28,10 +29,16 @@ import { freezePage } from './runner.js';
28
29
  import { removeFrozenPages } from './flow.js';
29
30
  import { lookAtPage, pageInfoLines } from './pagelook.js';
30
31
  import { lookAtSheet, sheetPrompt } from './sheetlook.js';
31
- import { leftRuleLine, dropRows, dropLine } from './pagedropwords.js';
32
+ import { leftRuleLine, dropRows, dropLine, dropSentence, pickNoteLine } from './pagedropwords.js';
33
+ import {
34
+ offerRules, rowsFromAnswer, checkAsks, settleRules, applyPicks, retentionOf, SUGGEST_SYSTEM, SUGGEST_TOOL, SUGGEST_SCHEMA, suggestUserText,
35
+ } from './checkpick.js';
36
+ import { matchRecord, entriesFromAnswers, sameWords, KEPT_WORDS } from './pickrecord.js';
32
37
  import { MAP_SYSTEM, mapPrompt } from './pagemap.js';
33
38
  import { askableFromLook, tooManyAsksText, MAX_LOOK_ASKS } from './pageask.js';
34
39
  import { lineRules } from './pagebits.js';
40
+ import { isCountGuardrail } from './declaration.js';
41
+ import { repairDeclaration } from './repairs.js';
35
42
  import path from 'node:path';
36
43
  import { isCellsPath } from './closers.js';
37
44
  import { parseCsv, sheetTable } from './csv.js';
@@ -121,13 +128,6 @@ const CITED_PROP = Object.freeze({
121
128
  additionalProperties: false,
122
129
  });
123
130
 
124
- const SHAPE_PROPS = Object.freeze({
125
- maxWords: { type: 'integer', minimum: 1, description: `the whole output's word ceiling; ${WHOLE_OUTPUT_CEILING_RULE}` },
126
- sections: { type: 'array', minItems: 1, items: { type: 'string', minLength: 1 }, description: 'required section headings, in order' },
127
- linesPerInvoice: { type: 'integer', minimum: 1, description: 'lines the output must carry per invoice' },
128
- mustCarry: { type: 'array', minItems: 1, items: { type: 'string', minLength: 1 }, description: 'named fields every line must carry' },
129
- });
130
-
131
131
  /**
132
132
  * The forced tool's parameter schema. `menu` = wiredMenu(). `sheets` (M10b piece 3, optional) = the drafting copy's table of each CSV input role: with it a step may carry
133
133
  * `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.
@@ -137,11 +137,6 @@ const SHAPE_PROPS = Object.freeze({
137
137
  export function buildDeclarationSchema(menu, { sheets, ticket } = {}) {
138
138
  const sheetProp = sheets ? sheetChecksProp(sheets) : null;
139
139
  const ticketParts = ticket ? ticketSchemaParts(ticket) : null;
140
- const shapeProps = {};
141
- for (const key of SHAPE_KEYS) {
142
- if (!SHAPE_PROPS[key]) throw new Error(`schema: SHAPE_KEYS gained "${key}" — add its type to SHAPE_PROPS`);
143
- shapeProps[key] = SHAPE_PROPS[key];
144
- }
145
140
  return {
146
141
  type: 'object',
147
142
  properties: {
@@ -157,7 +152,7 @@ export function buildDeclarationSchema(menu, { sheets, ticket } = {}) {
157
152
  description: 'verbs this step is granted, from the menu only; [] for a pure stop',
158
153
  },
159
154
  ...(ticketParts ? ticketParts.step : {}),
160
- reads: { type: 'array', items: { type: 'string' }, description: 'artifact ids emitted by EARLIER steps only (an ask step lists the earlier output to be checked FIRST), or the role of a CSV input (a step whose line has a green guardrail must list a CSV input role here)' },
155
+ reads: { type: 'array', items: { type: 'string' }, description: 'artifact ids emitted by EARLIER steps only (an ask step lists the earlier output to be checked FIRST), or the role of a CSV input (a step whose line has a green guardrail must list a CSV input role here); never a .docx/.md/.txt input role unless the step quotes it (close.cited.source), otherwise grant read/readDocx instead' },
161
156
  emits: { type: 'string', minLength: 1, description: 'the ONE new artifact id this step declares (unique)' },
162
157
  fromLine: { type: ['integer', 'null'], description: 'the ONE numbered job line this step serves' },
163
158
  picks: {
@@ -169,12 +164,6 @@ export function buildDeclarationSchema(menu, { sheets, ticket } = {}) {
169
164
  type: 'object',
170
165
  properties: {
171
166
  class: { type: 'string', enum: [...CLASSES], description: "MUST equal the class of fromLine's guardrail in guardrailClasses; hitl when that line has no guardrail" },
172
- shape: {
173
- type: 'object',
174
- properties: shapeProps,
175
- additionalProperties: false,
176
- description: `only when class is softgreen; keys limited to ${SHAPE_KEYS.join(', ')}`,
177
- },
178
167
  cited: CITED_PROP,
179
168
  columns: COLUMNS_PROP,
180
169
  ...(sheetProp ? { sheet: sheetProp } : {}),
@@ -305,11 +294,29 @@ function cleanNotChecked(raw) {
305
294
  return Array.isArray(raw) ? raw.filter((x) => typeof x === 'string' && x.trim() !== '').map((x) => x.trim()) : [];
306
295
  }
307
296
 
297
+ // M10 am27 (1): at draft time a count guardrail is hidden from the AI (the page look and the drafter); code keeps the ORIGINAL rule numbers and text.
298
+ const shownRules = (/** @type {string} */ guardrail) => lineRules({ rule: guardrail }).filter((r) => !isCountGuardrail(r)).join('; ');
299
+
300
+ /**
301
+ * The job lines as the page look may see them (no count rule), and `toOriginal`, which takes a look fact's / dropped entry's visible rule number back to the guardrail's own number.
302
+ * @param {{n: number, text: string, rule?: string}[]} jobLines
303
+ */
304
+ export function hideCounts(jobLines) {
305
+ const seenLines = jobLines.map((l) => { const kept = lineRules(l).filter((r) => !isCountGuardrail(r)); return { n: l.n, text: l.text, ...(kept.length ? { rule: kept.join('; ') } : {}) }; });
306
+ const ruleMap = (/** @type {number} */ line, /** @type {number|undefined} */ vis) => {
307
+ if (vis === undefined) return undefined;
308
+ const orig = lineRules(jobLines.find((x) => x.n === line)).map((r, i) => ({ r, no: i + 1 })).filter((x) => !isCountGuardrail(x.r));
309
+ return orig[vis - 1]?.no ?? vis;
310
+ };
311
+ const toOriginal = (/** @type {any} */ f) => (f.forRule !== undefined ? { ...f, forRule: ruleMap(f.line, f.forRule) } : f.rule !== undefined ? { ...f, rule: ruleMap(f.line, f.rule) } : f);
312
+ return { seenLines, toOriginal };
313
+ }
314
+
308
315
  function jobLinesText(lines, asks) {
309
316
  const askLines = new Set(asks.map((a) => a.line));
310
317
  return lines
311
318
  .map((l) => `${l.n}. ${l.text}${askLines.has(l.n) ? ' [SIGNED ASK — a human stop]' : ''}`
312
- + `${l.guardrail ? ` [guardrail: ${l.guardrail}]` : ' [no guardrail]'}`)
319
+ + `${l.guardrail && shownRules(l.guardrail) ? ` [guardrail: ${shownRules(l.guardrail)}]` : ' [no guardrail]'}`)
313
320
  .join('\n');
314
321
  }
315
322
 
@@ -324,6 +331,9 @@ function greenReadRule(sources) {
324
331
  const out = [csvRoles.length
325
332
  ? `${rule} CSV inputs in this job: ${csvRoles.join(', ')}. close.columns = [{source, column}] names the exact column(s) of the CSV header that the step's values come from. Where the Inputs list says a line "is column 'X'", that line's step must name that column. A step that has close.sheet is not held to close.columns by a word that merely matches a header (such as a bucket name); but when a line carries a rule "use the column 'X' for ...", at least one of that line's close.sheet checks must use that column. Leave close.columns out when the line names no column.`
326
333
  : `${rule} This job signs no CSV input, so a guardrail that needs a sheet check cannot be classed green here: class it "hitl"${pageRoles.length ? ' (unless it is about a web page, below)' : ''}.`];
334
+ if (docRoles.length) {
335
+ out.push(`- A document input (${docRoles.join(', ')}) is never listed in reads by a step that does not quote it (only a green step with close.cited.source = that role lists it). A step that needs the document is granted "read" ("readDocx" for a .docx) and reads it by its role through that tool; its reads stay empty or hold only earlier outputs.`);
336
+ }
327
337
  if (csvRoles.length) out.push(...sheetOfferRules(csvRoles)); // M10b piece 3: close.sheet and every rule the validator enforces on it
328
338
  if (pageRoles.length || docRoles.length) {
329
339
  out.push(
@@ -359,8 +369,8 @@ function whenToUse(menu) {
359
369
  function sheetRuleNumbers(lines, arbiter) {
360
370
  const csvRoles = (arbiter.sources ?? []).filter((s) => s.kind === 'file' && isCellsPath(s.path));
361
371
  if (csvRoles.length === 0) return [];
362
- const rows = lines.map((l) => ({ n: l.n, rules: lineRules(l.guardrail ? { rule: l.guardrail } : {}) })).filter((x) => x.rules.length > 0);
363
- return rows.length === 0 ? [] : ['', 'The guardrail rules by number (what "covers" counts):', ...rows.map((x) => `- line ${x.n}: ${x.rules.map((r, i) => `${i + 1}) ${r}`).join(' ')}`)];
372
+ 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);
373
+ 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(' ')}`)];
364
374
  }
365
375
 
366
376
  export function buildSystemPrompt({ menu, lines, arbiter, factsInfo }) {
@@ -379,7 +389,8 @@ export function buildSystemPrompt({ menu, lines, arbiter, factsInfo }) {
379
389
  '- guardrailClasses: for each job line that HAS a guardrail, classify its wording once: "green" (every figure must be checkable against its source: a sheet figure by the bareguard checks of the sheet), "softgreen" (the human declared a SHAPE the output must take), "hitl" (an ask/accept/review gate, or anything you are not sure of). When unsure, "hitl".',
380
390
  '- 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.',
381
391
  ...greenReadRule(arbiter.sources),
382
- '- close.shape only on a softgreen step; it is the human\'s declared shape in structured form.',
392
+ '- 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.',
393
+ '- 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.',
383
394
  '- 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.',
384
395
  `- 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.`,
385
396
  `- 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.`,
@@ -434,6 +445,9 @@ export async function draft({
434
445
  proseText, slot, model, provider: injected, rates: injectedRates, modelId: injectedModelId, env,
435
446
  priorSpend = /** @type {((ceilingUsd: number) => number)|null} */ (null), skills = DRAFT_SKILLS, makeProviderFn = makeProvider, onBook, offerQuestions = true, draftThinking = /** @type {'on'|'off'} */ ('off'),
436
447
  draftDir = /** @type {string|null} */ (null), fetchPage = undefined, leftRules = /** @type {{line: number, rule: number}[]} */ ([]),
448
+ checkPicks = /** @type {import('./checkpick.js').Pick[]} */ ([]),
449
+ // M10 am17/am18: the picks of the plan this one follows (src/pickrecord.js entries), and a callback that is handed this draft's record (kept + newly answered) for the one writer
450
+ carriedPicks = /** @type {import('./pickrecord.js').Entry[]} */ ([]), onPickRecord = /** @type {((r: {picks: import('./pickrecord.js').Entry[], kept: {line: number, rule: number, ruleText: string, check: Record<string, any>|null}[]}) => void)|null} */ (null),
437
451
  learnHints = /** @type {{text: string, ids: string[]}|null} */ (null),
438
452
  mcpServers = /** @type {string[]|undefined} */ (undefined),
439
453
  // 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
@@ -459,6 +473,9 @@ export async function draft({
459
473
  // M4e amendment 15 item 2: a guardrail that fights itself on words is red at $0, before any provider is built or called.
460
474
  const sumReds = checkGuardrailSums(lines);
461
475
  if (sumReds.length) return fail(sumReds);
476
+ // 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).
477
+ const sendReds = checkSendLineGuardrail(lines, arbiter);
478
+ if (sendReds.length) return fail(sendReds);
462
479
  const menu = wiredMenu(skills);
463
480
  // 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).
464
481
  const fileFacts = readInputFacts((arbiter.sources ?? []).filter((s) => s.kind !== 'page'));
@@ -509,6 +526,14 @@ export async function draft({
509
526
  inFlight, calls, unmetered, metered: sumMeterings(meterings), modelId, price: priceRecord(prices, rates),
510
527
  });
511
528
 
529
+ /** 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 */
530
+ const earlyStop = (/** @type {string[]} */ reds, /** @type {string} */ why) => {
531
+ const m = sumMeterings(meterings);
532
+ return {
533
+ 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,
534
+ };
535
+ };
536
+
512
537
  // 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
513
538
  // (`freezeInputs`), so a run is never checked against this one. Only now, after the $0 price and cap gates: a draft refused for money fetches nothing.
514
539
  const pageSources = (arbiter.sources ?? []).filter((s) => s.kind === 'page' && !ticketSources.includes(s));
@@ -537,6 +562,8 @@ export async function draft({
537
562
  const pageExtras = pageSources.length ? { look, pageLooks } : {};
538
563
  let mapCut = null;
539
564
  const jobLines = lines.map((l) => ({ n: l.n, text: l.text, ...(l.guardrail ? { rule: l.guardrail } : {}) }));
565
+ // M10 am27 (1): the page look sees only the non-count rules; `toOriginal` takes a visible rule number back to the original one
566
+ const { seenLines, toOriginal } = hideCounts(jobLines);
540
567
  const pageInfo = [];
541
568
  /** one map call (a page's or a sheet's): its hold, its metering and its book are the drafting round's own (the `kind` names it in the round log) */
542
569
  const makeCallModel = (kind) => async (content, attempt) => {
@@ -568,13 +595,14 @@ export async function draft({
568
595
  for (const s of pageSources) {
569
596
  const pg = pages[s.role];
570
597
  // The hold of the map call is sized from its own prompt (the saved page is in it): one that cannot fit what is left of the cap is refused here, at $0.
571
- const mapCeiling = ceilingCostUsd(rates, mapPrompt({ jobLines, label: s.role, text: pg.text }).length + MAP_SYSTEM.length);
598
+ const mapCeiling = ceilingCostUsd(rates, mapPrompt({ jobLines: seenLines, label: s.role, text: pg.text }).length + MAP_SYSTEM.length);
572
599
  const spentBefore = meterings.reduce((sum, ev) => sum + (ev.costUsd ?? roundCeiling), 0);
573
600
  if (spentBefore + mapCeiling > budgetUsd) {
574
601
  if (meterings.length === 0 && calls === 0) { removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); return fail([tooSmall(mapCeiling)]); }
575
602
  }
576
603
  const callModel = makeCallModel('page-map');
577
- const got = await lookAtPage({ label: s.role, text: pg.text, jobLines, callModel });
604
+ const got0 = await lookAtPage({ label: s.role, text: pg.text, jobLines: seenLines, callModel });
605
+ const got = got0.ok ? { ...got0, look: { ...got0.look, facts: got0.look.facts.map(toOriginal), dropped: got0.look.dropped.map(toOriginal) } } : got0;
578
606
  if (!got.ok) {
579
607
  const m = sumMeterings(meterings);
580
608
  return {
@@ -650,26 +678,103 @@ export async function draft({
650
678
  );
651
679
  }
652
680
  if (sheetLooks.length) pageExtras.sheetLooks = sheetLooks; // kept beside the page looks (src/authoring.js writes both into page-look.json)
681
+ // M10 am16 (1): ONE suggestion call, only when a guardrail on a step line is one this call settles (scope by code, src/checkpick.js). It suggests a check from bareguard's own list
682
+ // per guardrail, or none; code keeps what passes keep-or-drop. The call is metered, held and booked as a drafting round (the same `meterings`). The redraft after the answers
683
+ // (offerQuestions false) makes no call: it settles every rule against the person's picks instead.
684
+ // a rule a kept page or sheet fact already serves (the look tied it: line + rule number) is settled by that fact and is not asked here
685
+ const shapeRules = offerRules(lines, arbiter, [...look.facts, ...sheetFacts]);
686
+ // M10 am17/am18: a guardrail whose pick is kept from the last draft skips the suggestion call and the asks; only the rest is suggested and asked. The model never sees a pick.
687
+ const carried = matchRecord(carriedPicks, lines, shapeRules);
688
+ const keptView = carried.kept.map((k) => ({ line: k.line, rule: k.rule, ruleText: k.entry.ruleText, check: k.entry.check, added: k.entry.added, left: k.entry.left }));
689
+ onPickRecord?.({ picks: carried.kept.map((k) => k.entry), kept: keptView });
690
+ const askRules = carried.askRules;
691
+ /** @type {ReturnType<typeof checkAsks>} */
692
+ let shapeAsks = [];
693
+ if (askRules.length && offerQuestions) {
694
+ const content = suggestUserText(lines, askRules);
695
+ let args = null;
696
+ for (let attempt = 1; attempt <= 2 && args === null; attempt += 1) {
697
+ const spentBefore = meterings.reduce((sum, ev) => sum + (ev.costUsd ?? roundCeiling), 0);
698
+ if (spentBefore + ceilingCostUsd(rates, SUGGEST_SYSTEM.length + content.length + JSON.stringify(SUGGEST_SCHEMA).length) > budgetUsd) {
699
+ if (meterings.length === 0 && calls === 0) { removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); return fail([tooSmall(roundCeiling)]); }
700
+ return earlyStop(['the draft budget is spent'], 'budget');
701
+ }
702
+ /** @type {any} */
703
+ let captured;
704
+ const roundEvents = [];
705
+ const tool = { name: SUGGEST_TOOL, description: 'Suggest one check (or none) per guardrail.', parameters: SUGGEST_SCHEMA, execute: async (/** @type {any} */ a) => { captured = a; throw new HaltError('suggestion captured', { rule: 'captured' }); } };
706
+ const suggestLoop = new Loop({ provider, rates, onLlmResult: async (ev) => { roundEvents.push(ev); meterings.push(ev); } });
707
+ calls += 1;
708
+ book(true);
709
+ let res;
710
+ let threw = null;
711
+ try {
712
+ // thinking is off: on cannot combine with a forced tool call (the answer is one typed call, there is nothing to think through)
713
+ res = await suggestLoop.run([{ role: 'system', content: SUGGEST_SYSTEM }, { role: 'user', content }], [tool], { maxTokens: DRAFT_MAX_TOKENS, thinkingMode: 'off', toolChoice: { name: SUGGEST_TOOL } });
714
+ } catch (err) {
715
+ threw = err;
716
+ if (roundEvents.length === 0) unmetered += 1;
717
+ }
718
+ book(false);
719
+ const entry = /** @type {Record<string, any>} */ ({ round: log.length + 1, kind: 'check-suggest' });
720
+ if (res?.thinkingApplied !== undefined) entry.thinkingApplied = res.thinkingApplied;
721
+ if (res?.thinkingStatus !== undefined) entry.thinkingStatus = res.thinkingStatus;
722
+ if (threw && !(isPlainObject(captured) && threw instanceof HaltError)) {
723
+ entry.outcome = `provider-red: ${threw.message}`;
724
+ log.push(entry);
725
+ return earlyStop([`provider-red: ${threw.message}`], 'provider-red');
726
+ }
727
+ if (!isPlainObject(captured)) {
728
+ // the raw answer is kept (log.json), the cut-off said out loud; one more try, then every guardrail is "I can't check this" (never a guessed check)
729
+ entry.outcome = res?.stopReason === 'max_tokens' ? 'structure: truncated: the round hit the output cap with no completed tool call' : 'structure: no usable tool call (text instead of the tool)';
730
+ const malformed = provider?.lastMalformedToolCall ?? null;
731
+ if (typeof malformed?.rawArguments === 'string') entry.rawArguments = malformed.rawArguments;
732
+ else if (typeof res?.text === 'string' && res.text !== '') entry.rawText = res.text;
733
+ log.push(entry);
734
+ continue;
735
+ }
736
+ entry.outcome = 'answered';
737
+ entry.args = captured;
738
+ log.push(entry);
739
+ args = captured;
740
+ }
741
+ shapeAsks = checkAsks(rowsFromAnswer(askRules, args));
742
+ }
653
743
  // 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
654
744
  // 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.
655
745
  // 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.
656
- if ((pageSources.length || sheetAsks.length) && offerQuestions) {
746
+ if ((pageSources.length || sheetAsks.length || shapeAsks.length) && offerQuestions) {
657
747
  const pageAsks = pageSources.length ? askableFromLook({ facts: [...look.facts, ...sheetFacts] }, jobLines.filter((l) => !askLines.has(l.n))) : [];
658
- const asks = [...[...pageAsks.filter((a) => a.ask === 'reading'), ...sheetAsks].sort((a, b) => a.line - b.line), ...pageAsks.filter((a) => a.ask !== 'reading')];
748
+ const lookAsks = [...[...pageAsks.filter((a) => a.ask === 'reading'), ...sheetAsks].sort((a, b) => a.line - b.line), ...pageAsks.filter((a) => a.ask !== 'reading')];
749
+ // am16 (3): a shape guardrail's ask follows, in line order. (5): a proposal is not an ask under am1; only a `can't check` ask counts toward the cap (the 4th stops drafting at $0).
750
+ const asks = [...lookAsks, ...shapeAsks];
659
751
  if (asks.length > 0) {
660
752
  const m = sumMeterings(meterings);
661
753
  const spent = m.costUsd === null || unmetered > 0 ? (m.costUsd === null ? 'unknown' : `at least ${usdText(m.costUsd)}`) : usdText(m.costUsd);
662
- const tooMany = asks.length > MAX_LOOK_ASKS;
754
+ const counted = [...lookAsks, ...shapeAsks.filter((a) => a.counted).map((a) => ({ ...a, reading: "I can't check this" }))];
755
+ const tooMany = counted.length > MAX_LOOK_ASKS;
663
756
  if (tooMany && pageSources.length) removeFrozenPages(/** @type {string} */ (draftDir), Object.values(pages).map((q) => q.entry.frozen)); // a refused draft keeps no page copy
664
757
  return {
665
- ok: false, declaration: null, reds: tooMany ? [`${tooManyAsksText(asks)} 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,
758
+ 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,
666
759
  questions: tooMany ? [] : asks.map((a) => ({
667
- line: a.line, question: a.question, source: a.source, ask: a.ask, ruleNo: a.rule, ruleText: a.ruleText, proposal: a.reading ?? null,
760
+ 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 } : {}),
668
761
  })),
669
762
  droppedQuestions: [], notChecked: pageNotChecked, ...pageExtras,
670
763
  };
671
764
  }
672
765
  }
766
+ // 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
767
+ // (shown on the plan card and carried as `unjudgeable`); the drafter writes no check of its own, whatever it sends is overwritten below.
768
+ const allPicks = [...checkPicks, ...carried.picks];
769
+ const allLeft = [...leftRules, ...carried.left];
770
+ const settled = shapeRules.length ? settleRules(shapeRules, allPicks, allLeft) : null;
771
+ // the record this draft hands on: what it kept plus what the person just answered (numbered on this card)
772
+ onPickRecord?.({ picks: [...carried.kept.map((k) => k.entry), ...entriesFromAnswers(lines, shapeRules, checkPicks, leftRules)], kept: keptView });
773
+ const keptNote = (/** @type {{line: number, rule: number, text: string}} */ n) => (carried.kept.some((k) => k.line === n.line && (k.rule === n.rule || (k.entry.added !== null && sameWords(k.entry.added, n.text)))) ? ` (${KEPT_WORDS})` : '');
774
+ for (const n of settled?.notes ?? []) {
775
+ const line = (n.reason === 'person-left' ? leftRuleLine(n.text) : pickNoteLine(n.text, n.reason)) + keptNote(n);
776
+ if (!pageNotChecked.includes(line)) pageNotChecked.push(line);
777
+ }
673
778
  // 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.
674
779
  const factsBase = pageInfo.length ? [...facts.info.filter((l) => !pageSources.some((s) => l.startsWith(`- ${s.role}: a web page`))), ...pageInfo] : facts.info;
675
780
  const factsInfo = [...factsBase, ...ticketSources.flatMap((s) => ticketFactsLines(s.role)), ...(flowType === 'mcp' ? mcpFactsLines(mcp.server, mcp.tools) : [])];
@@ -792,16 +897,24 @@ export async function draft({
792
897
  if (Array.isArray(declaration.steps)) {
793
898
  declaration.steps = declaration.steps.map((st) => (isPlainObject(st) ? { ...st, goal: goalForLine(st.fromLine, lines) } : st));
794
899
  }
795
- // M4e amendment 15 item 1: `wordsPerSection` is the guardrail's number, set by the machine. If the model sent one it is overwritten
796
- // (or dropped when the guardrail gives none), so it can never differ from the guardrail.
900
+ // M13 am9 item 4: the last Ask before the added `write it out` reads every step; code sets it, whatever the model sent
901
+ if (Array.isArray(declaration.steps)) declaration.steps = readEveryStep(declaration.steps, arbiter);
902
+ // 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).
903
+ delete declaration.pickedLines; // the record of picked fact lines is code's too (applyPicks)
797
904
  if (Array.isArray(declaration.steps)) {
798
905
  declaration.steps = declaration.steps.map((st) => {
799
- if (!isPlainObject(st) || !isPlainObject(st.close) || !isPlainObject(st.close.shape)) return st;
800
- const { wordsPerSection: _drop, ...shape } = st.close.shape;
801
- const per = guardrailWordsPerSection(lines.find((l) => l.n === st.fromLine)?.guardrail);
802
- return { ...st, close: { ...st.close, shape: per === null ? shape : { ...shape, wordsPerSection: per } } };
906
+ if (!isPlainObject(st) || !isPlainObject(st.close) || (st.close.shape === undefined && st.close.picked === undefined)) return st;
907
+ // M10 am22 (3): `close.picked` is code's from the person's picks (applyPicks, next); one the drafter sent is dropped here too
908
+ const { shape: _drop, picked: _dropPicked, ...close } = st.close;
909
+ return { ...st, close };
803
910
  });
804
911
  }
912
+ // M10 am16 (4): code sets the check of every line it settled, from the picks only; the drafter's own `close.shape` and class for such a line are gone
913
+ if (settled) Object.assign(declaration, applyPicks(declaration, shapeRules, settled, (n) => dropSentence({ line: n.line, fact: '', reason: n.reason })));
914
+ // M10 am27 (2): the two mechanical plan mistakes (cited page not in reads; unjudgeable note on a green line) are repaired by code and logged on the round
915
+ { const fixed = repairDeclaration(declaration, arbiter); if (fixed.repaired.length) { Object.assign(declaration, fixed.declaration); entry.repaired = fixed.repaired; } }
916
+ // M10 am27 (4): what the drafter wrote vs what the final plan keeps, per job line (record only); drafted = the declaration as sent, before any code change
917
+ entry.retention = retentionOf(captured, declaration, jobLines, [...(settled?.checks.keys() ?? [])]);
805
918
  // 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
806
919
  const verdict1 = validateDeclaration(declaration, {
807
920
  arbiter, lines, catalogue: validationCatalogue, wired: WIRED_VERBS, verbatimGoals: true, fitJobLine: true,
package/src/jobkey.js CHANGED
@@ -5,6 +5,7 @@
5
5
  // TWO producers, ONE canonical form: the signed flow (parseSignedText's lines + arbiter) and the card's job box (parseJobBox).
6
6
  import { createHash } from 'node:crypto';
7
7
 
8
+ import { typedLinesOf } from './added-end.js';
8
9
  import { joinGuardrails, parseJobBox } from './panel/authorcard.js';
9
10
 
10
11
  /** @param {{ask: boolean, text: string, guardrail: string}[]} steps */
@@ -21,5 +22,6 @@ export function jobKeyOfCard(job) {
21
22
  /** The key of a signed job. @param {{ lines: {n: number, text: string, guardrail: string}[], arbiter: any }} signed `parseSignedText`'s ok result */
22
23
  export function jobKeyOfSigned({ lines, arbiter }) {
23
24
  const asks = new Set((arbiter.asks ?? []).map((a) => a.line));
24
- return keyOf(lines.map((l) => ({ ask: asks.has(l.n), text: String(l.text).trim(), guardrail: String(l.guardrail ?? '').trim() })));
25
+ // M13 am8: the end code adds (and an old job's send line) is not part of the job the person typed
26
+ return keyOf(typedLinesOf(lines, arbiter).map((l) => ({ ask: asks.has(l.n), text: String(l.text).trim(), guardrail: String(l.guardrail ?? '').trim() })));
25
27
  }
package/src/learn.js CHANGED
@@ -234,7 +234,7 @@ export function cardKey(c) {
234
234
  }
235
235
 
236
236
  /** the check name inside a gap text */
237
- const nameOf = (/** @type {string} */ g) => (g.match(/check "([^"]+)"/)?.[1] ?? g.match(/close stage "([^"]+)"/)?.[1] ?? 'close');
237
+ export const nameOf = (/** @type {string} */ g) => (g.match(/check "([^"]+)"/)?.[1] ?? g.match(/close stage "([^"]+)"/)?.[1] ?? 'close');
238
238
  const CODE = /\bTS\d+\b|\[[a-z][a-z-]+\]|\bE[A-Z]{2,}\b|\bERR_[A-Z_0-9]+\b/g;
239
239
 
240
240
  /**