fwdloop 0.36.0 → 0.38.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 (107) hide show
  1. package/README.md +6 -20
  2. package/bin/fwdloop +35 -12
  3. package/package.json +3 -3
  4. package/src/action-stop.js +1 -1
  5. package/src/auditchecks.js +41 -9
  6. package/src/authoring.js +78 -20
  7. package/src/blockasks.js +10 -12
  8. package/src/blockassemble.js +49 -46
  9. package/src/blockdraft.js +4 -2
  10. package/src/blockpick.js +10 -0
  11. package/src/canrun.js +2 -1
  12. package/src/cardlist.js +28 -5
  13. package/src/checkblock.js +598 -61
  14. package/src/checked.js +27 -33
  15. package/src/checklistsign.js +3 -3
  16. package/src/checklook.js +45 -0
  17. package/src/checkrows.js +202 -0
  18. package/src/cited-record.js +2 -2
  19. package/src/citedcheck.js +53 -12
  20. package/src/citedwords.js +7 -4
  21. package/src/closers.js +49 -2
  22. package/src/declaration.js +34 -10
  23. package/src/drafter.js +99 -74
  24. package/src/factwords.js +7 -4
  25. package/src/globprefix.js +26 -0
  26. package/src/isrec.js +2 -0
  27. package/src/line-checks.js +1 -2
  28. package/src/minrule.js +16 -0
  29. package/src/model-step.js +22 -4
  30. package/src/pageask.js +0 -3
  31. package/src/pagedropwords.js +3 -11
  32. package/src/pagedry.js +75 -1
  33. package/src/pagefetch.js +11 -6
  34. package/src/pagelook.js +2 -1
  35. package/src/pagerules.js +8 -2
  36. package/src/panel/author.js +33 -8
  37. package/src/panel/data.js +3 -2
  38. package/src/panel/index.html +177 -37
  39. package/src/panel/result.js +34 -1
  40. package/src/pickrecord.js +14 -0
  41. package/src/planrebuild.js +55 -19
  42. package/src/ratelimit.js +117 -0
  43. package/src/report.js +14 -2
  44. package/src/rowresults.js +111 -0
  45. package/src/rubricstep.js +65 -2
  46. package/src/runner.js +38 -5
  47. package/src/shapebuild.js +281 -0
  48. package/src/shapelook.js +91 -0
  49. package/src/shapemenu.js +64 -0
  50. package/src/shaperesult.js +104 -0
  51. package/src/shaperows.js +263 -0
  52. package/src/shapewords.js +140 -0
  53. package/src/sheet-record.js +1 -2
  54. package/src/sheetblock.js +1 -2
  55. package/src/sheetbuild.js +41 -29
  56. package/src/sheetchecks.js +1 -2
  57. package/src/sheetclaims.js +1 -2
  58. package/src/sheetoffer.js +1 -1
  59. package/src/sheetrows.js +10 -64
  60. package/src/sheetrun.js +1 -2
  61. package/src/ticketrows.js +2 -3
  62. package/src/try-checks.js +39 -6
  63. package/src/types.js +1 -0
  64. package/src/whole-job.js +24 -8
  65. package/types/action-stop.d.ts +1 -1
  66. package/types/auditchecks.d.ts +13 -2
  67. package/types/authoring.d.ts +21 -2
  68. package/types/blockasks.d.ts +6 -10
  69. package/types/blockassemble.d.ts +12 -13
  70. package/types/blockdraft.d.ts +3 -2
  71. package/types/blockpick.d.ts +4 -0
  72. package/types/cardlist.d.ts +18 -2
  73. package/types/checkblock.d.ts +276 -27
  74. package/types/checked.d.ts +15 -6
  75. package/types/checklook.d.ts +36 -0
  76. package/types/checkrows.d.ts +119 -0
  77. package/types/citedcheck.d.ts +4 -2
  78. package/types/closers.d.ts +10 -1
  79. package/types/drafter.d.ts +9 -4
  80. package/types/globprefix.d.ts +5 -0
  81. package/types/isrec.d.ts +1 -0
  82. package/types/minrule.d.ts +6 -0
  83. package/types/model-step.d.ts +43 -2
  84. package/types/pageask.d.ts +0 -1
  85. package/types/pagedropwords.d.ts +0 -1
  86. package/types/pagedry.d.ts +27 -0
  87. package/types/pagefetch.d.ts +3 -2
  88. package/types/pagerules.d.ts +4 -0
  89. package/types/panel/result.d.ts +16 -1
  90. package/types/pickrecord.d.ts +10 -0
  91. package/types/ratelimit.d.ts +59 -0
  92. package/types/report.d.ts +2 -1
  93. package/types/rowresults.d.ts +28 -0
  94. package/types/rubricstep.d.ts +21 -0
  95. package/types/runner.d.ts +3 -1
  96. package/types/shapebuild.d.ts +97 -0
  97. package/types/shapelook.d.ts +76 -0
  98. package/types/shapemenu.d.ts +40 -0
  99. package/types/shaperesult.d.ts +40 -0
  100. package/types/shaperows.d.ts +102 -0
  101. package/types/shapewords.d.ts +43 -0
  102. package/types/sheetbuild.d.ts +31 -13
  103. package/types/sheetrows.d.ts +5 -36
  104. package/types/ticketrows.d.ts +1 -1
  105. package/types/try-checks.d.ts +2 -1
  106. package/types/types.d.ts +4 -0
  107. package/types/whole-job.d.ts +20 -4
package/README.md CHANGED
@@ -36,7 +36,7 @@ Like a CNC machine, fwdloop builds the thing that does the work, then lets a gau
36
36
 
37
37
  **Guide rails, not just guardrails.** Guardrails stop the agent going off the road: a money cap per run, a monthly limit, a time limit on every Ask, and a send destination you signed that it can't move. Nothing leaves the machine without that signed destination and your accept in the same run. Guide rails keep it on the road: each new try hears what earlier tries in the run did; lessons from past runs go to the drafter and to retries; a rule it can't settle comes back as a question with buttons (Agree, Drop it, or your own words), not a guess.
38
38
 
39
- **Verification.** The check sits outside the agent's loop: code decides, built on bareguard. Anything code can't check is listed as Not checked, and you judge it at the Ask. A red step goes back with the real gap to be fixed, up to four tries a step; the same miss twice stops it.
39
+ **Verification.** The check sits outside the agent's loop: code decides, built on bareguard. For a list of items (one per flight, resume or topic), code checks each item's fields against the limits your rules give, and how many items there are when you said. Anything code can't check is listed as Not checked, and you judge it at the Ask. A red step goes back with the real gap to be fixed, up to four tries a step; the same miss twice stops it.
40
40
 
41
41
  **Evidence.** Every try, its cost and its check result is recorded, and the books balance to the cent. You can read it all in the Audit tab, including exactly what each try was told. Page facts are quoted from a saved copy of the page.
42
42
 
@@ -57,27 +57,13 @@ last word, and how to make cost and outcome honest. It borrows those solved prob
57
57
  primitives directly, as a sibling of the suite, and adds the part that was missing: the
58
58
  pauses, the checks, and the people.
59
59
 
60
- ## The bare ecosystem
60
+ ## bare suite
61
61
 
62
- Local-first, composable agent infrastructure. Same patterns throughout, each module works
63
- standalone.
62
+ - **Hands** · [barebrowse](https://github.com/hamr0/barebrowse) · [baremobile](https://github.com/hamr0/baremobile) · [beeperbox](https://github.com/hamr0/beeperbox)
63
+ - **Rails** · [bareagent](https://github.com/hamr0/bareagent) · [bareguard](https://github.com/hamr0/bareguard) · [barebox](https://github.com/hamr0/barebox) · [litectx](https://github.com/hamr0/litectx)
64
+ - **Apps** · **fwdloop** · [bareloop](https://github.com/hamr0/bareloop)
64
65
 
65
- **Core** — the brain, the gate, the memory.
66
-
67
- - **[bareagent](https://npmjs.com/package/bare-agent)** — the think→act→observe loop. *Goal in → coordinated actions out.*
68
- - **[bareguard](https://npmjs.com/package/bareguard)** — the single gate every action passes through. *Action in → allow / deny / ask-a-human out.*
69
- - **[litectx](https://npmjs.com/package/litectx)** — memory and context engineering (write · select · compress · isolate). *Query in → ranked context out.*
70
-
71
- **Optional reach** — give the agent hands.
72
-
73
- - **[barebrowse](https://npmjs.com/package/barebrowse)** — a real browser for agents.
74
- - **[baremobile](https://npmjs.com/package/baremobile)** — Android + iOS device control.
75
- - **[beeperbox](https://github.com/hamr0/beeperbox)** — 50+ messaging networks via one MCP server.
76
-
77
- **Siblings** — workflows on top of the rails.
78
-
79
- - **[bareloop](https://github.com/hamr0/bareloop)** — workflows that earn their own design, for repeated, verifiable jobs. Closed loop.
80
- - **fwdloop** — workflows with people in them. Open loop.
66
+ Built from [bareagent](https://github.com/hamr0/bareagent), [barebrowse](https://github.com/hamr0/barebrowse), [bareguard](https://github.com/hamr0/bareguard) and [litectx](https://github.com/hamr0/litectx). → [The whole suite](https://github.com/hamr0)
81
67
 
82
68
  ## Status
83
69
 
package/bin/fwdloop CHANGED
@@ -52,7 +52,8 @@ import { panelMain } from '../src/panel/server.js';
52
52
  import { launcherMain } from '../src/launcher.js';
53
53
  import { isInteractive, confirmTypedName, NEEDS_TTY } from '../src/sign-confirm.js';
54
54
  import { draftToDir, draftKeyRefusal, signDraft, SIGN_LINE, costText, questionsRefusal } from '../src/authoring.js';
55
- import { readRecordFile, readRowChoices, readSheetDropped, readColumns } from '../src/pickrecord.js';
55
+ import { minRuleRefusal } from '../src/minrule.js';
56
+ import { readRecordFile, readRowChoices, readSheetDropped, readShapeDropped, readColumns } from '../src/pickrecord.js';
56
57
  import { userInfo } from 'node:os';
57
58
  import { pageAddressesOf, pageAddressRefusal } from '../src/pagefetch.js';
58
59
  import { ticketListsOf, isTicketNumber, TICKET_NUMBER_WORDS } from '../src/ticket-shape.js';
@@ -110,9 +111,15 @@ function takeMonthlyHold({ what, flow, runId, runDir, holdUsd, spentAtHold = 0 }
110
111
  });
111
112
  } catch (err) {
112
113
  if (!(err instanceof ConfigError)) throw err;
113
- fail(`${err.message} — refusing to start rather than guess the monthly limit. Nothing spent.`);
114
+ const words = `${err.message} — refusing to start rather than guess the monthly limit. Nothing spent.`;
115
+ if (what === 'draft') refuseDraft('capUsd', words, words);
116
+ fail(words);
117
+ }
118
+ if (!claim.ok) {
119
+ const words = monthlyRefusalText(claim.room);
120
+ if (what === 'draft') refuseDraft('capUsd', words, words);
121
+ fail(words);
114
122
  }
115
- if (!claim.ok) fail(monthlyRefusalText(claim.room));
116
123
  let settled = false;
117
124
  const settle = (why) => {
118
125
  if (settled || claim.holdId === null) return;
@@ -142,6 +149,14 @@ function fail(message) {
142
149
  process.exit(1);
143
150
  }
144
151
 
152
+ // F262: the ONE writer of a draft refusal's typed record. `box` is named by the refusing check's own call site (job | capUsd | model | inputs | null), never read from words.
153
+ // The human line is printed first, unchanged; the record is the last line of the log, one JSON line (so words with a newline stay one line).
154
+ function refuseDraft(box, words, printed = `draft refused at $0 — ${words}`) {
155
+ process.stderr.write(`fwdloop: ${printed}\n`);
156
+ process.stderr.write(`fwdloop: refusal-record ${JSON.stringify({ box, words })}\n`);
157
+ process.exit(1);
158
+ }
159
+
145
160
  /**
146
161
  * The ONE place a human-typed `--root` becomes a path (hamr ruling
147
162
  * 2026-09-29): resolved to its real path once, at command start. Nothing
@@ -939,11 +954,13 @@ async function cmdDraft(rest) {
939
954
  let carriedChoices;
940
955
  /** @type {any[]|undefined} */
941
956
  let carriedSheetDropped;
957
+ /** @type {any[]|undefined} */
958
+ let carriedShapeDropped;
942
959
  let carriedColumns;
943
960
  if (values.carry !== undefined) {
944
961
  const abs = resolve(values.carry);
945
962
  const g = readFileInside(dirname(abs), basename(abs));
946
- if (g.ok) { carriedPicks = readRecordFile(abs) ?? undefined; carriedChoices = readRowChoices(abs) ?? undefined; carriedSheetDropped = readSheetDropped(abs) ?? undefined; carriedColumns = readColumns(abs) ?? undefined; } // a missing or unreadable record is no record: every guardrail is asked, as before
963
+ if (g.ok) { carriedPicks = readRecordFile(abs) ?? undefined; carriedChoices = readRowChoices(abs) ?? undefined; carriedSheetDropped = readSheetDropped(abs) ?? undefined; carriedShapeDropped = readShapeDropped(abs) ?? undefined; carriedColumns = readColumns(abs) ?? undefined; } // a missing or unreadable record is no record: every guardrail is asked, as before
947
964
  }
948
965
 
949
966
  let injected = {};
@@ -957,15 +974,16 @@ async function cmdDraft(rest) {
957
974
  if (configDoorHome().skip) fail(NO_CONFIG_HOME_REFUSAL);
958
975
  try {
959
976
  const p = pickTicked(readPriceConfig(), values);
960
- if (!p.ok) fail(`draft refused at $0 — ${p.say}`);
977
+ if (!p.ok) refuseDraft('model', p.say);
961
978
  pick = { slot: p.slot, model: p.model };
962
979
  } catch (err) {
963
980
  if (!(err instanceof ConfigError)) throw err;
964
- fail(`${err.message} — refusing to draft rather than guess the price. Nothing spent.`);
981
+ const words = `${err.message} — refusing to draft rather than guess the price. Nothing spent.`;
982
+ refuseDraft('model', words, words);
965
983
  }
966
984
  // The key preflight (draftToDir repeats it).
967
985
  const refusal = draftKeyRefusal(pick.slot, env);
968
- if (refusal !== null) fail(`draft refused at $0 — ${refusal}`);
986
+ if (refusal !== null) refuseDraft('model', refusal);
969
987
  } else if (values.model !== undefined) pick = { slot: values.provider, model: values.model };
970
988
  // M4d piece 3: the monthly check — one ceiling round, priced from the
971
989
  // picked model's own Settings prices (an injected test provider carries its own rates). A model that is not
@@ -976,13 +994,14 @@ async function cmdDraft(rest) {
976
994
  if (!rates) {
977
995
  if (configDoorHome().skip) fail(NO_CONFIG_HOME_REFUSAL);
978
996
  const usable = resolveUsableModel(pick.slot, { config: readPriceConfig(), model: pick.model });
979
- if (!usable.ok) fail(`draft refused at $0 — ${usable.say}`);
997
+ if (!usable.ok) refuseDraft('model', usable.say);
980
998
  rates = usable.rates;
981
999
  }
982
1000
  ceiling = ceilingCostUsd(rates);
983
1001
  } catch (err) {
984
1002
  if (!(err instanceof ConfigError)) throw err;
985
- fail(`${err.message} — refusing to draft rather than guess the price. Nothing spent.`);
1003
+ const words = `${err.message} — refusing to draft rather than guess the price. Nothing spent.`;
1004
+ refuseDraft('model', words, words);
986
1005
  }
987
1006
  // M4d am19 item 1: the hold is what is left of the cap (cap minus this job's drafting so far), the most the draft may spend, not one round
988
1007
  // the ONE read of the prose file goes through the safe gateway (a symlink or an outside path is refused); draftToDir is handed this read
@@ -991,6 +1010,11 @@ async function cmdDraft(rest) {
991
1010
  const proseRead = gate.ok
992
1011
  ? (gate.text.trim() === '' ? { ok: false, red: `prose: "${proseAbs}" is empty` } : gate)
993
1012
  : { ok: false, red: gate.missing ? `prose: cannot read "${proseAbs}": ENOENT` : `prose: ${gate.red}` };
1013
+ // M19 am13: a job with no `~` rule of the person's is refused here, at $0, before the hold, the draft folder or any provider call (the panel's Start drafting spawns this command and shows these words)
1014
+ if (proseRead.ok) {
1015
+ const noRule = minRuleRefusal(proseRead.text);
1016
+ if (noRule !== null) refuseDraft('job', noRule);
1017
+ }
994
1018
  const hold = takeMonthlyHold({
995
1019
  what: 'draft', flow: values.name, runId: null, runDir: resolve(values.out), holdUsd: draftHoldUsd(proseRead.ok ? proseRead.text : '', resolve(values.out), ceiling),
996
1020
  });
@@ -1010,6 +1034,7 @@ async function cmdDraft(rest) {
1010
1034
  ...(carriedPicks === undefined ? {} : { carriedPicks }),
1011
1035
  ...(carriedChoices === undefined ? {} : { carriedChoices }),
1012
1036
  ...(carriedSheetDropped === undefined ? {} : { carriedSheetDropped }),
1037
+ ...(carriedShapeDropped === undefined ? {} : { carriedShapeDropped }),
1013
1038
  ...(carriedColumns === undefined ? {} : { carriedColumns }),
1014
1039
  draftThinking: values.thinking === true ? 'on' : 'off',
1015
1040
  flowType,
@@ -1021,9 +1046,7 @@ async function cmdDraft(rest) {
1021
1046
  });
1022
1047
  const cost = result.costUsd === null ? 'UNKNOWN' : costText(Number(result.costUsd), result.spendComplete);
1023
1048
  if (!result.wrote) {
1024
- process.stderr.write(`fwdloop: draft refused at $0 — ${result.reds.join('; ')}\n`);
1025
- process.exitCode = 1;
1026
- return;
1049
+ refuseDraft(result.box ?? null, result.reds.join('; '));
1027
1050
  }
1028
1051
  process.stdout.write(`draft dir: ${resolve(values.out)} cost: ${cost}\n`);
1029
1052
  // M10 piece 3: a draft that stopped to ask what the page look raised is not red: it waits for the person's answers (the panel takes them)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fwdloop",
3
- "version": "0.36.0",
3
+ "version": "0.38.0",
4
4
  "description": "Describe a job as steps and guardrails; an agent builds the workflow, pauses for humans where you said, checks every step happened, and reruns it under budgets it cannot touch.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
@@ -50,8 +50,8 @@
50
50
  ],
51
51
  "dependencies": {
52
52
  "bare-agent": "^0.59.0",
53
- "barebrowse": "^0.26.0",
54
- "bareguard": "^0.36.0",
53
+ "barebrowse": "^0.31.0",
54
+ "bareguard": "^0.37.0",
55
55
  "litectx": "^0.32.0"
56
56
  },
57
57
  "devDependencies": {
@@ -32,7 +32,7 @@ export function lastAcceptedSha(steps, i, acceptedAskEmitsThisRun) {
32
32
  }
33
33
 
34
34
  /**
35
- * am11a 1/2: the wait of the stop. The LAST Ask's own wait when the job has an Ask before the action; else the card's Ask wait kept in the run's signed values (`arbiter.actionWaitMs`), else 1h.
35
+ * am11a 1/2: the wait of the stop. The LAST Ask's own wait when the job has an Ask before the action; else the card's Ask wait kept in the run's signed values (`sendSlot.waitMs`, src/runvalues.js), else 1h.
36
36
  * @param {{ fromLine: number }[]} steps @param {number} i @param {Map<number, {ttlMs: number}>} askLines @param {number|undefined} actionWaitMs
37
37
  */
38
38
  export function stopWaitMs(steps, i, askLines, actionWaitMs) {
@@ -1,11 +1,13 @@
1
1
  // M16 item 5 (docs/wiki/the-module-ladder.md, "M16"): the Audit's "Checks" fold, the card's own sections (Checks, Not checked, Always checked), each row with its tag and, after the run, its recorded result.
2
2
  // borrowed-from: bareloop src/panel/jobplan.js@v0.56.0 (3383cce) (auditChecksOf: the sections, the row shape {text, by, result}, a row no verdict was recorded for is "none", never "passed")
3
+ // borrowed-from: bareloop src/panel/jobplan.js@v0.61.0 (fc56e1f3) auditChecksOf: `lines` (one block per job line: its checks and its Not checked rows) and `jobNotChecked` (the Not checked rows no line owns), ported onto fwdloop's diary reader
3
4
  // What a run recorded for a check is read off its diary (`checks` rows: each check numbered with its `ok`, and for a list line its `part`); nothing is re-derived. What this throws away: the checks of a line off the list
4
5
  // (the sheet and the older plans keep their own Audit rows), and the per-try history (the LAST try of a step is the one that closed it).
5
6
  import { listLinesOf } from './checklistsign.js';
6
7
  import { listPartRows, notCheckedView } from './checked.js';
7
8
  import { EVERY_STEP, EVERY_STEP_TEXTS } from './try-checks.js';
8
9
  import { sheetRowsOf } from './sheetrows.js';
10
+ import { splitNotChecked, ncRowsOf } from './checklook.js';
9
11
 
10
12
  /** the words of a row no result was recorded for: never "passed" */
11
13
  export const AUDIT_NO_RESULT = 'no result recorded';
@@ -13,8 +15,9 @@ export const AUDIT_NO_RESULT = 'no result recorded';
13
15
  /**
14
16
  * @param {any} declaration the signed plan @param {any[]} diary the run's `checks` rows (src/diary.js readChecks) @param {{items?: string[], by?: Record<string, string>}|null} notChecked the sign row's Not-checked block
15
17
  * @param {{lines?: any[], csvRoles?: string[]}} [sheet] the signed job lines and CSV roles: a plan whose list has sheet rows (M16 am4) shows them here, tagged by where each comes from (hamr 2026-11-14)
16
- * @returns {{checks: AuditCheckRow[], notChecked: AuditCheckRow[], readNotes: string[], always: AuditCheckRow[]}|null} null for a plan with no list (it keeps its own Audit rows)
17
- * @typedef {{text: string, by: 'you'|'agent'|'default'|null, result: 'passed'|'failed'|'none'|'not-checked'}} AuditCheckRow
18
+ * @returns {{checks: AuditCheckRow[], notChecked: AuditCheckRow[], readNotes: string[], always: AuditCheckRow[], lines: AuditLine[], jobNotChecked: AuditCheckRow[]}|null} null for a plan with no list (it keeps its own Audit rows)
19
+ * @typedef {{n: number, text: string, checks: AuditCheckRow[], notChecked: AuditCheckRow[]}} AuditLine
20
+ * @typedef {{text: string, by: 'you'|'agent'|'default'|null, result: 'passed'|'failed'|'none'|'not-checked', kind?: 'truth'|'shape'|'file', why?: string}} AuditCheckRow
18
21
  */
19
22
  export function auditChecksOf(declaration, diary, notChecked, { lines: jobLines = [], csvRoles = [] } = {}) {
20
23
  const lines = listLinesOf(declaration);
@@ -25,11 +28,25 @@ export function auditChecksOf(declaration, diary, notChecked, { lines: jobLines
25
28
  const lastTry = (/** @type {any} */ st) => (Array.isArray(diary) ? diary : []).filter((d) => d.step === (st.emits ?? st.goal ?? null)).at(-1);
26
29
  /** @type {AuditCheckRow[]} */
27
30
  const checks = [];
31
+ // the same rows by the job line that owns them, their words without the `line N · ` prefix (S7: one block per line)
32
+ /** @type {{line: number, row: AuditCheckRow}[]} */
33
+ const owned = [];
34
+ // a failed row's reason is the words its check recorded (the diary's `result`); a row that passed or has no record carries none
35
+ const whyOf = (/** @type {any} */ got) => (got !== undefined && !got.ok && typeof got.result === 'string' && got.result !== '' ? { why: got.result } : {});
28
36
  for (const st of steps) {
29
37
  const rec = lastTry(st);
30
- for (const r of listPartRows(declaration, st)) {
31
- const got = rec?.checks?.find((/** @type {any} */ c) => c.part === r.part);
32
- checks.push({ text: `line ${st.fromLine} · ${r.text}`, by: r.by, result: got === undefined ? 'none' : got.ok ? 'passed' : 'failed' });
38
+ for (const r of listPartRows(declaration, st, { lines: Array.isArray(jobLines) ? jobLines : [] })) {
39
+ // M19 am11 item 4: a list line's own rows are recorded by their key (each item field, the count rule); any other row, and a record made before, is read by its part
40
+ const got = rec?.checks?.find((/** @type {any} */ c) => c.key === r.key) ?? rec?.checks?.find((/** @type {any} */ c) => c.key === undefined && c.part === r.part);
41
+ const row = /** @type {AuditCheckRow} */ ({ text: r.text, kind: 'truth', by: r.by, result: got === undefined ? 'none' : got.ok ? 'passed' : 'failed', ...whyOf(got) });
42
+ checks.push({ ...row, text: `line ${st.fromLine} · ${r.text}` });
43
+ owned.push({ line: st.fromLine, row });
44
+ }
45
+ // a red no row owns (a whole-list red): told on its own, never left as passed rows
46
+ for (const c of (rec?.checks ?? []).filter((/** @type {any} */ x) => x.unclaimed === true && !x.ok)) {
47
+ const row = /** @type {AuditCheckRow} */ ({ text: c.text, kind: 'truth', by: null, result: 'failed' });
48
+ checks.push({ ...row, text: `line ${st.fromLine} · ${c.text}` });
49
+ owned.push({ line: st.fromLine, row });
33
50
  }
34
51
  }
35
52
  // a sheet row: its check's words and the `by` of its row; what the run recorded is read by the row's `part`, as for any list row
@@ -37,19 +54,34 @@ export function auditChecksOf(declaration, diary, notChecked, { lines: jobLines
37
54
  const st = (Array.isArray(declaration?.steps) ? declaration.steps : []).find((/** @type {any} */ x) => x?.fromLine === r.line && Array.isArray(x?.close?.sheet));
38
55
  const rec = st ? lastTry(st) : undefined;
39
56
  const got = rec?.checks?.find((/** @type {any} */ c) => c.part === sheetRows?.signed[i].part.part && c.by !== undefined);
40
- checks.push({ text: `line ${r.line} \u00b7 ${r.text}`, by: r.by, result: got === undefined ? 'none' : got.ok ? 'passed' : 'failed' });
57
+ const row = /** @type {AuditCheckRow} */ ({ text: r.text, kind: 'truth', by: r.by, result: got === undefined ? 'none' : got.ok ? 'passed' : 'failed', ...whyOf(got) });
58
+ checks.push({ ...row, text: `line ${r.line} \u00b7 ${r.text}` });
59
+ owned.push({ line: r.line, row });
41
60
  }
42
61
  const by = notChecked?.by ?? {};
43
62
  // M17 am4 (C3): the Audit splits a reading note from Not checked as the card and the Job tab do (src/checked.js notCheckedView)
44
63
  const view = notCheckedView(notChecked?.items ?? [], declaration);
45
64
  /** @type {AuditCheckRow[]} */
46
- const notRows = view.items.map((t) => ({ text: t, by: by[t] === 'you' || by[t] === 'agent' || by[t] === 'default' ? /** @type {'you'|'agent'|'default'} */ (by[t]) : null, result: 'not-checked' }));
65
+ const notRows = view.items.map((t) => ({ ...splitNotChecked(t), by: by[t] === 'you' || by[t] === 'agent' || by[t] === 'default' ? /** @type {'you'|'agent'|'default'} */ (by[t]) : null, result: 'not-checked' }));
47
66
  // the two checks every step has (src/try-checks.js #1 and #2): passed when every step that ran them passed, failed when one did not
48
67
  const every = (/** @type {string} */ text) => {
49
68
  const seen = (Array.isArray(diary) ? diary : []).flatMap((d) => (d.checks ?? []).filter((/** @type {any} */ c) => c.source === EVERY_STEP && c.text === text));
50
69
  return seen.length === 0 ? 'none' : seen.every((/** @type {any} */ c) => c.ok) ? 'passed' : 'failed';
51
70
  };
71
+ const everyWhy = (/** @type {string} */ text) => whyOf((Array.isArray(diary) ? diary : []).flatMap((d) => (d.checks ?? []).filter((/** @type {any} */ c) => c.source === EVERY_STEP && c.text === text)).find((/** @type {any} */ c) => !c.ok));
52
72
  /** @type {AuditCheckRow[]} */
53
- const always = EVERY_STEP_TEXTS.map((text) => ({ text, by: /** @type {'default'} */ ('default'), result: every(text) }));
54
- return { checks, notChecked: notRows, readNotes: view.readNotes, always };
73
+ const always = EVERY_STEP_TEXTS.map((text) => ({ text, kind: 'file', by: /** @type {'default'} */ ('default'), result: every(text), ...everyWhy(text) }));
74
+ // M19 S7: one block per job line (its checks, its Not checked rows) and the Not checked rows no line owns; the two every-step rows are the page's "Every line" block (a one-line job's Line 1 block)
75
+ // a row owned by a line the job text does not carry would be lost from the blocks: then no blocks (`lines` empty) and the page draws the flat groups
76
+ const known = new Set(jobLines.map((/** @type {any} */ l) => l.n));
77
+ const ncAll = ncRowsOf(view.items, by);
78
+ const ncOf = (/** @type {any} */ n) => ({ text: n.text, by: n.by ?? null, result: /** @type {'not-checked'} */ ('not-checked'), ...(n.why ? { why: n.why } : {}) });
79
+ /** @type {AuditLine[]} */
80
+ const lineBlocks = owned.some((o) => !known.has(o.line)) ? [] : jobLines.map((/** @type {any} */ l) => ({
81
+ n: l.n, text: l.text,
82
+ checks: owned.filter((o) => o.line === l.n).map((o) => o.row),
83
+ notChecked: ncAll.filter((n) => n.line === l.n).map(ncOf),
84
+ }));
85
+ const jobNotChecked = ncAll.filter((n) => !known.has(n.line)).map(ncOf);
86
+ return { checks, notChecked: notRows, readNotes: view.readNotes, always, lines: lineBlocks, jobNotChecked };
55
87
  }
package/src/authoring.js CHANGED
@@ -23,9 +23,10 @@ import { draft } from './drafter.js';
23
23
  import { parseSignedText, unsignedAskTtls } from './signed-text.js';
24
24
  import { validateDeclaration, flowTypeOf } from './declaration.js';
25
25
  import { factRows, factSentence, countSentence } from './citedcheck.js';
26
- import { plainWords, labelled, tagged } from './checkwords.js';
27
- import { listLinesOf, partByOf, factByOf, countByOf } from './checklistsign.js';
28
- import { CARD_T } from './checkblock.js';
26
+ import { plainWords, labelled } from './checkwords.js';
27
+ import { listLinesOf, cardLinesOf, partByOf, factByOf, countByOf } from './checklistsign.js';
28
+ import { LOOK, ncRowsOf } from './checklook.js';
29
+ import { EVERY_STEP_TEXTS } from './try-checks.js';
29
30
  import { sheetLineBlocks } from './sheetblock.js';
30
31
  import { loadCatalogue } from './catalogue.js';
31
32
  import { WIRED_VERBS } from './primitives.js';
@@ -42,8 +43,10 @@ import { redactSecrets } from './redact.js';
42
43
  import { sessionPriorSpend, writeDraftSpend } from './draftspend.js';
43
44
  import { writeSetup } from './setup.js';
44
45
  import { RECORD_FILE } from './pickrecord.js';
46
+ import { planMatchesCard, numbersWords } from './checkrows.js';
47
+ import { csvRolesOf } from './sheetblock.js';
45
48
  import { mcpPickHere } from './mcp-pick.js';
46
- import { hitlWords } from './checked.js';
49
+ import { hitlWords, notCheckedView } from './checked.js';
47
50
 
48
51
  export const SPEC_HASH_FILE = 'spec.hash';
49
52
  /** The one folder under the flows root where the panel keeps its draft folders (M4e). Starts with a dot, so it is never a flow name. */
@@ -193,9 +196,21 @@ export function readoutHeadIndexes(text) {
193
196
  return idx;
194
197
  }
195
198
 
199
+ // borrowed-from: bareloop src/authorreadout.js@v0.61.0 (fc56e1f3) readoutGroups (the signed look's groups as readout rows, section 3.7): tag column first, kind word second; an empty group is not told
200
+ /** @param {{checks: {text: string, by?: string|null, kind?: string}[], nc: {text: string, why?: string, by?: string}[], suggested: {text: string, key?: string, dropped?: boolean}[]}} g @returns {string[]} */
201
+ function readoutGroups({ checks, nc, suggested }) {
202
+ const row = (by, kind, text) => ` ${`[${by ?? 'default'}]`.padEnd(9)} ${kind.padEnd(5)} ${text}`;
203
+ const out = [];
204
+ if (checks.length) out.push(` ${LOOK.checked} \u00B7 ${checks.length}`, ...checks.map((c) => row(c.by, c.kind ?? 'truth', c.text)));
205
+ if (nc.length) out.push(` ${LOOK.notChecked} \u00B7 ${nc.length} \u00B7 ${LOOK.notCheckedTail}`, ...nc.map((n) => row(n.by, '', `${n.text}${n.why ? ` \u2014 ${n.why}` : ''}`)));
206
+ if (suggested.length) out.push(` ${LOOK.suggested}`, ...suggested.map((x) => row('agent', /\.shape\./.test(x.key ?? '') ? 'shape' : 'truth', `${x.text}${x.dropped ? ' (you dropped it)' : ''}`)));
207
+ return out;
208
+ }
209
+
196
210
  /** Plain-text readout of what the human is about to sign. Pure. */
197
211
  export function buildReadout({
198
- declaration, arbiter, lines, name, modelId, costUsd, rounds, spendComplete, root,
212
+ declaration, arbiter, lines, name, modelId, costUsd, rounds, spendComplete, root, notChecked = /** @type {string[]} */ ([]), notCheckedBy = /** @type {Record<string, string>} */ ({}), suggested = /** @type {{line: number, text: string, key?: string, dropped?: boolean}[]} */ ([]),
213
+ checkCard = /** @type {{rows: {line: number, by: string, state: string, text: string, kind?: string}[]}|null} */ (null),
199
214
  }) {
200
215
  const out = [];
201
216
  out.push(`${READOUT_HEADER_PREFIX}"${name}"`, '');
@@ -224,11 +239,23 @@ export function buildReadout({
224
239
  out.push('', READOUT_HEADS.steps);
225
240
  const sheetBlocks = sheetLineBlocks({ declaration, lines });
226
241
  const onList = listLinesOf(declaration);
242
+ // borrowed-from: bareloop src/authorreadout.js@v0.61.0 (fc56e1f3) buildReadout (the check rows of a line are the card's rows, one model): M19 am4. A line the card draws a list on takes its CHECKED rows from the saved card (`checkCard`, the page's planOfState rule: the line's built rows in the card's order); a plan with no card keeps the readout's own rows
243
+ const onCard = checkCard !== null && Array.isArray(checkCard.rows) ? cardLinesOf(declaration) : new Set();
227
244
  // display only: a hitl step that is not an Ask line prints the card's words (src/checked.js hitlWords); an Ask line (pure stop) keeps `hitl`
228
245
  const askLineNos = (arbiter.asks ?? []).map((a) => a.line);
229
246
  const lastAskIdx = declaration.steps.reduce((m, st, i) => (askLineNos.includes(st.fromLine) ? i : m), -1);
230
247
  const checkText = (st, i) => (st.close?.class === 'hitl' && !askLineNos.includes(st.fromLine) ? hitlWords(askLineNos.length > 0, lastAskIdx !== -1 && i > lastAskIdx) : st.close?.class);
248
+ // M19 S6 (section 3.7): the rows of a list line and the Not checked items are told in the signed look's groups; the rows no one line owns are one `EVERY LINE` block (a one-line job's join its line)
249
+ // M19 am4: the Not checked rows are the card's (src/checked.js notCheckedView, the one split): a note about a written form the page did not use is "How the page was read", not a Not checked row
250
+ // a plan with no card list (drafted before M16) keeps today's readout (signed am4 item 2): the split is for a plan the card draws a list on
251
+ const ncRows = ncRowsOf(onCard.size > 0 ? notCheckedView(notChecked, declaration).items : notChecked, notCheckedBy);
252
+ const many = lines.length > 1;
253
+ const alwaysRows = onList.size > 0 ? EVERY_STEP_TEXTS.map((text) => ({ text, by: 'default', kind: 'file' })) : [];
254
+ const owned = new Set(declaration.steps.map((st) => st.fromLine));
255
+ const told = new Set();
231
256
  declaration.steps.forEach((st, i) => {
257
+ /** @type {{text: string, by: string, kind?: string}[]} */
258
+ const rows = [];
232
259
  out.push(` ${i + 1}. (line ${st.fromLine}) ${st.goal}`);
233
260
  out.push(` grants: ${st.primitives?.length ? st.primitives.join(', ') : 'none (pure stop)'}`
234
261
  + ` | reads: ${st.reads?.length ? st.reads.join(', ') : '-'} | emits: ${st.emits} | check: ${checkText(st, i)}`);
@@ -236,23 +263,24 @@ export function buildReadout({
236
263
  // M10 am7 item 1: the facts a cited step checks its quotes against, signed with the readout (typed fields, never model prose)
237
264
  // M16: a list line's checks carry the tag of the row that built each (`[you]`, `[agent]`, `[default]`); any other line keeps today's words
238
265
  const listed = onList.has(st.fromLine);
239
- if (listed && st.close?.cited && typeof st.close.cited === 'object') {
266
+ const cardLine = onCard.has(st.fromLine);
267
+ if (cardLine) { /* M19 am4: the card's rows stand in for the hand-built ones (below) */ } else if (listed && st.close?.cited && typeof st.close.cited === 'object') {
240
268
  const c = st.close.cited;
241
- for (const f of Array.isArray(c.facts) ? c.facts : []) out.push(` ${tagged(factSentence(f, c.source), factByOf(declaration, st.fromLine, f.name) ?? 'agent')}`);
242
- if (countSentence(c)) out.push(` ${tagged(/** @type {string} */ (countSentence(c)), countByOf(declaration, st.fromLine) ?? 'agent')}`);
269
+ for (const f of Array.isArray(c.facts) ? c.facts : []) rows.push({ text: factSentence(f, c.source), by: factByOf(declaration, st.fromLine, f.name) ?? 'agent' });
270
+ if (countSentence(c)) rows.push({ text: /** @type {string} */ (countSentence(c)), by: countByOf(declaration, st.fromLine) ?? 'agent' });
243
271
  } else if (st.close?.cited && typeof st.close.cited === 'object') for (const row of factRows(st.close.cited)) out.push(` ${labelled(row, 'agent')}`);
244
272
  // M10b piece 1: the signed sheet checks, one row each, written by code from the typed fields
245
- if (Array.isArray(st.close?.sheet)) for (const row of sheetBlocks.find((b) => b.line === st.fromLine)?.checked ?? []) out.push(` sheet check: ${row.text}`);
273
+ if (!cardLine && Array.isArray(st.close?.sheet)) for (const row of sheetBlocks.find((b) => b.line === st.fromLine)?.checked ?? []) out.push(` sheet check: ${row.text}`);
246
274
  // M10 am8 item 2: the column lock, signed with the readout (typed fields)
247
275
  if (Array.isArray(st.close?.columns)) for (const c of st.close.columns) if (typeof c?.column === 'string' && typeof c?.source === 'string') out.push(` cells only from column '${c.column}' of ${c.source}`);
248
276
  // M10 am16: the checks the person picked, signed with the readout, each in the one set of plain words (typed fields, never model prose)
249
- if (Array.isArray(st.close?.shape?.picked)) st.close.shape.picked.forEach((c, j) => out.push(listed ? ` ${tagged(plainWords(c), partByOf(declaration, st.fromLine, j) ?? 'agent')}` : ` ${labelled(`you picked: ${plainWords(c)}`, 'picked')}`));
277
+ if (!cardLine && Array.isArray(st.close?.shape?.picked)) st.close.shape.picked.forEach((c, j) => (listed ? rows.push({ text: plainWords(c), by: partByOf(declaration, st.fromLine, j) ?? 'agent' }) : out.push(` ${labelled(`you picked: ${plainWords(c)}`, 'picked')}`)));
250
278
  // M10 am22 (1): the checks the person picked for a fact line are signed with the readout too, in the same words
251
- if (st.close?.class === 'green' && Array.isArray(st.close.picked)) st.close.picked.forEach((c, j) => out.push(listed ? ` ${tagged(plainWords(c), partByOf(declaration, st.fromLine, (st.close.cited && typeof st.close.cited === 'object' ? 1 : 0) + j) ?? 'agent')}` : ` ${labelled(`you picked: ${plainWords(c)}`, 'picked')}`));
279
+ if (!cardLine && st.close?.class === 'green' && Array.isArray(st.close.picked)) st.close.picked.forEach((c, j) => (listed ? rows.push({ text: plainWords(c), by: partByOf(declaration, st.fromLine, (st.close.cited && typeof st.close.cited === 'object' ? 1 : 0) + j) ?? 'agent' }) : out.push(` ${labelled(`you picked: ${plainWords(c)}`, 'picked')}`)));
252
280
  // M16 R7: the numbers tie of a list line (the `$` row)
253
- if (listed && Array.isArray(st.close?.numbersFrom) && st.close.numbersFrom.length > 0) {
281
+ if (!cardLine && listed && Array.isArray(st.close?.numbersFrom) && st.close.numbersFrom.length > 0) {
254
282
  const before = (st.close.cited && typeof st.close.cited === 'object' ? 1 : 0) + (Array.isArray(st.close.picked) ? st.close.picked.length : Array.isArray(st.close.shape?.picked) ? st.close.shape.picked.length : 0);
255
- out.push(` ${tagged(`${CARD_T.numbers} ${st.close.numbersFrom.join(', ')}`, partByOf(declaration, st.fromLine, before) ?? 'default')}`);
283
+ rows.push({ text: numbersWords(st.close.numbersFrom), by: partByOf(declaration, st.fromLine, before) ?? 'default' });
256
284
  }
257
285
  // M4e amendment 14 item 5: the check's sections in its order (+ word limit); fixed text from typed fields, never model prose.
258
286
  const shape = st.close?.shape;
@@ -261,7 +289,20 @@ export function buildReadout({
261
289
  const lim = Number.isInteger(shape.maxWords) ? ` · under ${shape.maxWords} words` : '';
262
290
  out.push(` ${labelled(`sections: ${shape.sections.join(' · ')}${per}${lim}`, 'agent')}`);
263
291
  }
292
+ const first = !told.has(st.fromLine);
293
+ told.add(st.fromLine);
294
+ const joins = !many && first;
295
+ if (cardLine && first) rows.push(...(checkCard?.rows ?? []).filter((r) => r.line === st.fromLine && r.state === 'built').map((r) => ({ text: r.text, by: r.by, kind: r.kind || 'truth' })));
296
+ out.push(...readoutGroups({
297
+ checks: [...rows, ...(joins ? alwaysRows : [])],
298
+ nc: first ? ncRows.filter((n) => n.line === st.fromLine || (joins && !owned.has(n.line))) : [],
299
+ suggested: first ? suggested.filter((x) => x.line === st.fromLine || (joins && !owned.has(x.line))) : [],
300
+ }));
264
301
  });
302
+ if (many) {
303
+ const rest = readoutGroups({ checks: alwaysRows, nc: ncRows.filter((n) => !owned.has(n.line)), suggested: [] });
304
+ if (rest.length) out.push(` ${LOOK.everyLine.toUpperCase()}`, ...rest);
305
+ }
265
306
  out.push('', READOUT_HEADS.asks);
266
307
  for (const a of arbiter.asks) out.push(` line ${a.line}: "${a.question}" (ttl ${fmtTtl(a.ttlMs)})`);
267
308
  if (arbiter.asks.length === 0) out.push(' none');
@@ -344,14 +385,14 @@ export function writePlanFiles(dir, files, opts = {}) {
344
385
  * `onResult({ ok })` (M4d am32): called once, after the spend is booked and just before the result files are written (the CLI gives its monthly hold back there).
345
386
  */
346
387
  export async function draftToDir({
347
- proseFile, dir, root, name, slot, model, draftThinking = /** @type {'on'|'off'} */ ('off'), keyNames, env = process.env, provider, rates, modelId, noQuestions = false, onResult, fetchPage, leftRules, columnAnswers, carriedColumns, checkPicks, carriedPicks, carriedChoices, carriedSheetDropped, proseRead,
388
+ proseFile, dir, root, name, slot, model, draftThinking = /** @type {'on'|'off'} */ ('off'), keyNames, env = process.env, provider, rates, modelId, noQuestions = false, onResult, fetchPage, leftRules, columnAnswers, carriedColumns, checkPicks, carriedPicks, carriedChoices, carriedSheetDropped, carriedShapeDropped, proseRead,
348
389
  flowType = /** @type {'plain'|'mcp'|'tickets'} */ ('plain'), mcpServer = /** @type {string|undefined} */ (undefined), mcpPick = /** @type {any} */ (undefined), mcpServers = /** @type {string[]|undefined} */ (undefined),
349
390
  // M13 am11: what the card's tentative send line is (see draft()); null = the prose file is the truth
350
391
  actionMode = /** @type {null|'check'|'known'} */ (null),
351
392
  }) {
352
- const refuse = (reds) => ({ ok: false, wrote: false, reds, costUsd: 0 });
393
+ const refuse = (reds, box = /** @type {string|null} */ (null)) => ({ ok: false, wrote: false, reds, costUsd: 0, box });
353
394
  const nameCheck = checkFlowName(name);
354
- if (!nameCheck.ok) return refuse([nameCheck.red]);
395
+ if (!nameCheck.ok) return refuse([nameCheck.red], 'flowName');
355
396
  if (typeof root !== 'string' || root === '') return refuse(['draft: --root <flows dir> is required']);
356
397
  // An unsigned draft folder inside the flows root would list as a flow in the panel and Inbox (checked by realpath, at use time).
357
398
  const realRoot = realpathOfNew(root);
@@ -369,7 +410,7 @@ export async function draftToDir({
369
410
  const injected = provider != null;
370
411
  if (!injected) {
371
412
  const refusal = draftKeyRefusal(slot, env);
372
- if (refusal !== null) return refuse([refusal]);
413
+ if (refusal !== null) return refuse([refusal], 'model');
373
414
  }
374
415
  const secrets = keyValues(env, [...new Set([...(keyNames ?? []), ...(typeof slot === 'string' ? [slot] : [])])]);
375
416
  if (secrets.some((s) => s.length >= 8 && prose.text.includes(s))) return refuse(['prose: contains an API key value — refused']);
@@ -428,15 +469,16 @@ export async function draftToDir({
428
469
  /** @type {any[]} */
429
470
  let columnRecord = []; // the agreed columns of this plan (fresh and carried), kept in the same record (M17 ruling 2)
430
471
  let sheetDropped = []; // the sheet checks this plan has dropped (a Revise's carried ones, applied by draft()), kept in the same record
472
+ let shapeDropped = []; // the shape fields this plan has dropped, kept beside them in the same record (no new file)
431
473
  /** @type {any} */
432
474
  let pickRecord = null; // M10 am17: handed by draft() as it learns it; the last one handed is this draft's (written below, the one writer)
433
475
  const result = await draft({
434
- proseText: prose.text, slot, model, provider, rates, modelId, env, onBook, priorSpend, offerQuestions: !noQuestions, draftThinking, draftDir: path.join(dir, PAGES_DIR), fetchPage, learnHints, ...(leftRules === undefined ? {} : { leftRules }), ...(columnAnswers === undefined ? {} : { columnAnswers }), ...(carriedColumns === undefined ? {} : { carriedColumns }), onColumns: (rec) => { columnRecord = rec; }, ...(checkPicks === undefined ? {} : { checkPicks }), ...(carriedPicks === undefined ? {} : { carriedPicks }), ...(carriedChoices === undefined ? {} : { carriedChoices, onChoices: (rec) => { rowChoices = rec; } }), ...(carriedSheetDropped === undefined ? {} : { carriedSheetDropped }), onSheetDropped: (rec) => { sheetDropped = rec; }, onPickRecord: (r) => { pickRecord = r; },
476
+ proseText: prose.text, slot, model, provider, rates, modelId, env, onBook, priorSpend, offerQuestions: !noQuestions, draftThinking, draftDir: path.join(dir, PAGES_DIR), fetchPage, learnHints, ...(leftRules === undefined ? {} : { leftRules }), ...(columnAnswers === undefined ? {} : { columnAnswers }), ...(carriedColumns === undefined ? {} : { carriedColumns }), onColumns: (rec) => { columnRecord = rec; }, ...(checkPicks === undefined ? {} : { checkPicks }), ...(carriedPicks === undefined ? {} : { carriedPicks }), ...(carriedChoices === undefined ? {} : { carriedChoices, onChoices: (rec) => { rowChoices = rec; } }), ...(carriedSheetDropped === undefined ? {} : { carriedSheetDropped }), onSheetDropped: (rec) => { sheetDropped = rec; }, ...(carriedShapeDropped === undefined ? {} : { carriedShapeDropped }), onShapeDropped: (rec) => { shapeDropped = rec; }, onPickRecord: (r) => { pickRecord = r; },
435
477
  flowType, mcp, ...(mcpServers === undefined ? {} : { mcpServers }), actionMode,
436
478
  });
437
479
  if (result.stop === 'pre-flight') {
438
480
  try { rmdirSync(dir); } catch { /* the claimed dir is still empty; leave it rather than mask the refusal */ }
439
- return refuse(cleanReds(result.reds));
481
+ return refuse(cleanReds(result.reds), result.box ?? null);
440
482
  }
441
483
  // M8 item 5a: what was handed is kept once beside the draft (only when a round was actually sent with it); a failure is recorded, never raised.
442
484
  try {
@@ -466,7 +508,7 @@ export async function draftToDir({
466
508
  // Amendments 24/25: the questions and the drafter's own "not checked" reading are written BEFORE log.json/spec.hash (the panel reads those
467
509
  // two as "the draft finished"), as their own files: never in the readout, so never in the hash.
468
510
  if (result.questions?.length) files[QUESTIONS_FILE] = scrub(dj({ questions: result.questions }), secrets);
469
- if (pickRecord !== null) files[RECORD_FILE] = scrub(dj({ ...pickRecord, ...(rowChoices === null ? {} : { rowChoices }), ...(sheetDropped.length ? { sheetDropped } : {}), ...(columnRecord.length ? { columns: columnRecord } : {}) }), secrets); // M10 am17: the picks carried to the next plan (this drafting folder only, never a run folder)
511
+ if (pickRecord !== null) files[RECORD_FILE] = scrub(dj({ ...pickRecord, ...(rowChoices === null ? {} : { rowChoices }), ...(sheetDropped.length ? { sheetDropped } : {}), ...(shapeDropped.length ? { shapeDropped } : {}), ...(columnRecord.length ? { columns: columnRecord } : {}) }), secrets); // M10 am17: the picks carried to the next plan (this drafting folder only, never a run folder)
470
512
  files[NOT_CHECKED_FILE] = scrub(dj({ notChecked: result.notChecked ?? [], ...(result.notCheckedBy && Object.keys(result.notCheckedBy).length ? { by: result.notCheckedBy } : {}) }), secrets); // M16 item 5: the tag of each line that tells a row
471
513
  if (result.pageLooks || result.sheetLooks) files[PAGE_LOOK_FILE] = scrub(dj({ pages: result.pageLooks ?? [], ...(result.sheetLooks ? { sheets: result.sheetLooks } : {}), look: result.look ?? { facts: [], dropped: [] } }), secrets);
472
514
  files['log.json'] = scrub(dj({
@@ -475,6 +517,8 @@ export async function draftToDir({
475
517
  revisions: result.revisions, thinking: result.thinking, inputs: result.inputs, log: result.log,
476
518
  // M16 P4: what the plan card shows of the list (rows with tags and reasons, the suggestions), drawn by the page; Drop and Add rebuild it
477
519
  ...(result.checkCard ? { checkCard: result.checkCard } : {}),
520
+ // M19 S3: what code built from the AI's sheet suggestions (the block's `setSheet` input): Drop and Add rebuild the block from it at $0, never by asking again
521
+ ...(result.sheetBuilt ? { sheetBuilt: result.sheetBuilt } : {}),
478
522
  // M13 am11: the job's action (the last line the AI named, or the person agreed or typed), or null: the plan card's row `› line <n> writes everything before it`
479
523
  action: result.action ?? null,
480
524
  }), secrets);
@@ -484,6 +528,7 @@ export async function draftToDir({
484
528
  const inputFactsText = scrub(dj(result.declaration.inputFacts), secrets);
485
529
  const readoutText = scrub(buildReadout({
486
530
  declaration: result.declaration, arbiter: parsed.arbiter, lines: parsed.lines, name, modelId: result.modelId, costUsd: result.costUsd, rounds: result.rounds, spendComplete: result.spendComplete, root,
531
+ notChecked: result.notChecked ?? [], notCheckedBy: result.notCheckedBy ?? {}, suggested: result.checkCard?.suggested ?? [], checkCard: result.checkCard ?? null,
487
532
  }), secrets);
488
533
  files['declaration.json'] = declarationText;
489
534
  files['input-facts.json'] = inputFactsText;
@@ -590,6 +635,19 @@ export function signDraft({
590
635
  arbiter: signed.arbiter, lines: signed.lines, catalogue: cat.primitives, wired: WIRED_VERBS, verbatimGoals: true, fitJobLine: true,
591
636
  });
592
637
  if (!verdict.ok) return { ok: false, reds: verdict.reds };
638
+ // M19 am6 item 3 (bareloop `planMatchesClose`): the card a draft saved must equal the checks the signed plan runs, line by line; a difference refuses the sign at $0, naming the line.
639
+ // Only a card saved with its own Not checked list (this build) is compared; an older saved card is drawn from the plan and not held to it.
640
+ const cardReds = (() => {
641
+ if (!Array.isArray(declaration.checkList)) return [];
642
+ const lg = read('log.json');
643
+ const rec = read(RECORD_FILE);
644
+ /** @type {any} */ let log = null; /** @type {any} */ let record = null;
645
+ try { log = lg.ok ? JSON.parse(lg.text) : null; record = rec.ok ? JSON.parse(rec.text) : null; } catch { return []; }
646
+ if (!log?.checkCard || !Array.isArray(log.checkCard.notChecked)) return [];
647
+ const kept = Array.isArray(record?.kept) ? record.kept.filter((/** @type {any} */ k) => k && Number.isInteger(k.line)) : [];
648
+ return planMatchesCard({ declaration, lines: signed.lines, csvRoles: csvRolesOf(signed.arbiter), kept, log: log.log }, log.checkCard);
649
+ })();
650
+ if (cardReds.length) return { ok: false, reds: cardReds };
593
651
 
594
652
  const reds = [];
595
653
  for (const s of signed.arbiter.sources) {
package/src/blockasks.js CHANGED
@@ -1,20 +1,19 @@
1
1
  // borrowed-from: bareloop src/blockasks.js@v0.57.0 (c18df406)
2
2
  // borrowed-from: bareloop src/blockasks.js@v0.56.0 (3383cce)
3
3
  // The questions of the check block, as the answer gate reads them (`answerQuestions`, src/questionbox.js): ONE spelling of the question words, written by code from a row that
4
- // code could not settle (reading | cant-check | check). The block's `open` list is the source; the person's CHOICE (agree | drop | rule) goes back through `block.applyAnswer`.
5
- import { readingQuestion, cantCheckQuestion } from './pageask.js';
6
- import { plainWords, HOW_TO_ANSWER, CANT_CHECK_WORDS } from './checkpick.js';
4
+ // code could not settle (reading | check). The block's `open` list is the source; the person's CHOICE (agree | drop | rule) goes back through `block.applyAnswer`.
5
+ import { readingQuestion } from './pageask.js';
6
+ import { plainWords, HOW_TO_ANSWER } from './checkpick.js';
7
7
 
8
- /** @typedef {{key: string, rowKey: string, line: number, rule: number, source: 'look', ask: 'reading'|'cant-check'|'no-check'|'check', ruleText: string, question: string, counted: boolean, reading?: string, check?: Record<string, any>}} BlockAsk */
8
+ /** @typedef {{key: string, rowKey: string, line: number, rule: number, source: 'look', ask: 'reading'|'check', ruleText: string, question: string, counted: boolean, reading?: string, check?: Record<string, any>}} BlockAsk */
9
9
 
10
10
  /**
11
- * The questions the block has open, in the order the person meets them: the look's readings, then the look's can't-checks, then the pick path's asks (a proposal or a can't-check about a rule the pick path owns) in rule order (a proposal is not counted toward the 3-ask cap).
12
- * A can't-check about a rule the PICK path owns (`scoped`: src/checkpick.js scopedRules, every `~` rule of a file job) is the pick path's own ask, `no-check`, in fwd's words (a "Line N, guardrail ...: I can't check this" ask
13
- * whose answer the panel records as a pick, so Revise carries it: am17/am18/am21); any other can't-check is the look's own ask about a page.
14
- * @param {import('./checkblock.js').CheckBlock} block @param {{line: number, rule: number}[]} [scoped] @returns {BlockAsk[]}
11
+ * The questions the block has open, in the order the person meets them: the look's readings, then the pick path's proposals (a proposal is not counted toward the 3-ask cap).
12
+ * M19 am3: a rule no check can settle is no longer asked, so `block.open` holds only `reading` and `check` asks; any other kind is a bug and throws.
13
+ * @param {import('./checkblock.js').CheckBlock} block @returns {BlockAsk[]}
15
14
  */
16
- export function questionsOfBlock(block, scoped = []) {
17
- const rank = { reading: 0, 'cant-check': 1, 'no-check': 2, check: 2 };
15
+ export function questionsOfBlock(block) {
16
+ const rank = { reading: 0, check: 1 };
18
17
  return block.open.map((/** @type {any} */ q) => {
19
18
  const row = block.rows.find((r) => r.key === q.rowKey);
20
19
  const rule = Number(row?.rule);
@@ -24,8 +23,7 @@ export function questionsOfBlock(block, scoped = []) {
24
23
  const words = plainWords(q.proposal);
25
24
  return { ...base, ask: /** @type {'check'} */ ('check'), counted: false, reading: words, check: q.proposal, question: `Line ${q.line}, guardrail "${q.ruleText}": I propose ${words}. ${HOW_TO_ANSWER(q.line, true)}` };
26
25
  }
27
- if (scoped.some((x) => x.line === q.line && x.rule === rule)) return { ...base, ask: /** @type {'no-check'} */ ('no-check'), counted: true, question: `Line ${q.line}, guardrail "${q.ruleText}": ${CANT_CHECK_WORDS} ${HOW_TO_ANSWER(q.line, false)}` };
28
- return { ...base, ask: /** @type {'cant-check'} */ ('cant-check'), counted: true, question: cantCheckQuestion(q.line, String(q.ruleText)) };
26
+ throw new Error(`questionsOfBlock: unexpected ask kind "${q.ask}" on row ${q.rowKey}`);
29
27
  }).sort((a, b) => rank[a.ask] - rank[b.ask]);
30
28
  }
31
29