fwdloop 0.32.0 → 0.33.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 (93) hide show
  1. package/bin/fwdloop +8 -2
  2. package/package.json +2 -2
  3. package/src/auditchecks.js +53 -0
  4. package/src/authoring.js +52 -12
  5. package/src/blockasks.js +44 -0
  6. package/src/blockassemble.js +140 -0
  7. package/src/blockdraft.js +91 -0
  8. package/src/blocklines.js +30 -0
  9. package/src/blockpick.js +165 -0
  10. package/src/cardlist.js +19 -0
  11. package/src/checkblock.js +804 -0
  12. package/src/checked.js +48 -9
  13. package/src/checklist.js +99 -0
  14. package/src/checklistsign.js +93 -0
  15. package/src/checkwords.js +20 -1
  16. package/src/cited-record.js +21 -1
  17. package/src/citedcheck.js +162 -7
  18. package/src/closers.js +41 -3
  19. package/src/declaration.js +25 -2
  20. package/src/declaredclose.js +4 -0
  21. package/src/draft-steps.js +3 -1
  22. package/src/drafter.js +205 -122
  23. package/src/factwords.js +112 -0
  24. package/src/inputlook.js +53 -0
  25. package/src/labelscan.js +162 -0
  26. package/src/pageask.js +4 -1
  27. package/src/pagedropwords.js +11 -1
  28. package/src/panel/author.js +73 -4
  29. package/src/panel/authorcard.js +9 -6
  30. package/src/panel/data.js +41 -9
  31. package/src/panel/index.html +202 -13
  32. package/src/panel/result.js +4 -3
  33. package/src/panel/server.js +3 -1
  34. package/src/pickrecord.js +28 -0
  35. package/src/placerule.js +398 -0
  36. package/src/planrebuild.js +206 -0
  37. package/src/rowedit.js +118 -0
  38. package/src/rubricstep.js +264 -0
  39. package/src/runfile.js +4 -2
  40. package/src/runner.js +67 -10
  41. package/src/setup.js +10 -4
  42. package/src/sheetblock.js +6 -2
  43. package/src/sheetchecks.js +49 -64
  44. package/src/sheetclaims.js +12 -32
  45. package/src/sheetoffer.js +24 -52
  46. package/src/sheetrows.js +107 -0
  47. package/src/sheetrun.js +13 -10
  48. package/src/summary-words.js +3 -3
  49. package/src/try-checks.js +31 -12
  50. package/src/types.js +1 -0
  51. package/types/auditchecks.d.ts +24 -0
  52. package/types/authoring.d.ts +18 -1
  53. package/types/blockasks.d.ts +37 -0
  54. package/types/blockassemble.d.ts +33 -0
  55. package/types/blockdraft.d.ts +83 -0
  56. package/types/blocklines.d.ts +31 -0
  57. package/types/blockpick.d.ts +41 -0
  58. package/types/cardlist.d.ts +21 -0
  59. package/types/checkblock.d.ts +363 -0
  60. package/types/checked.d.ts +16 -2
  61. package/types/checklist.d.ts +115 -0
  62. package/types/checklistsign.d.ts +27 -0
  63. package/types/checkwords.d.ts +5 -0
  64. package/types/cited-record.d.ts +9 -0
  65. package/types/citedcheck.d.ts +33 -2
  66. package/types/closers.d.ts +24 -2
  67. package/types/declaredclose.d.ts +2 -0
  68. package/types/drafter.d.ts +15 -361
  69. package/types/factwords.d.ts +38 -0
  70. package/types/inputlook.d.ts +49 -0
  71. package/types/labelscan.d.ts +35 -0
  72. package/types/pageask.d.ts +2 -0
  73. package/types/panel/author.d.ts +41 -0
  74. package/types/panel/authorcard.d.ts +1 -1
  75. package/types/panel/data.d.ts +4 -2
  76. package/types/panel/jobgrid.d.ts +1 -1
  77. package/types/pickrecord.d.ts +22 -0
  78. package/types/placerule.d.ts +208 -0
  79. package/types/planrebuild.d.ts +52 -0
  80. package/types/provider.d.ts +1 -1
  81. package/types/rowedit.d.ts +33 -0
  82. package/types/rubricstep.d.ts +60 -0
  83. package/types/runfile.d.ts +5 -2
  84. package/types/runner.d.ts +45 -1
  85. package/types/sheetblock.d.ts +1 -0
  86. package/types/sheetchecks.d.ts +10 -17
  87. package/types/sheetclaims.d.ts +2 -1
  88. package/types/sheetoffer.d.ts +5 -5
  89. package/types/sheetrows.d.ts +73 -0
  90. package/types/sheetrun.d.ts +4 -4
  91. package/types/summary-words.d.ts +2 -1
  92. package/types/try-checks.d.ts +4 -2
  93. package/types/types.d.ts +8 -0
package/bin/fwdloop CHANGED
@@ -52,7 +52,7 @@ 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 } from '../src/pickrecord.js';
55
+ import { readRecordFile, readRowChoices, readSheetDropped } from '../src/pickrecord.js';
56
56
  import { userInfo } from 'node:os';
57
57
  import { pageAddressesOf, pageAddressRefusal } from '../src/pagefetch.js';
58
58
  import { ticketListsOf, isTicketNumber, TICKET_NUMBER_WORDS } from '../src/ticket-shape.js';
@@ -923,10 +923,14 @@ async function cmdDraft(rest) {
923
923
 
924
924
  /** @type {any[]|undefined} */
925
925
  let carriedPicks;
926
+ /** @type {any[]|undefined} */
927
+ let carriedChoices;
928
+ /** @type {any[]|undefined} */
929
+ let carriedSheetDropped;
926
930
  if (values.carry !== undefined) {
927
931
  const abs = resolve(values.carry);
928
932
  const g = readFileInside(dirname(abs), basename(abs));
929
- if (g.ok) carriedPicks = readRecordFile(abs) ?? undefined; // a missing or unreadable record is no record: every guardrail is asked, as before
933
+ if (g.ok) { carriedPicks = readRecordFile(abs) ?? undefined; carriedChoices = readRowChoices(abs) ?? undefined; carriedSheetDropped = readSheetDropped(abs) ?? undefined; } // a missing or unreadable record is no record: every guardrail is asked, as before
930
934
  }
931
935
 
932
936
  let injected = {};
@@ -989,6 +993,8 @@ async function cmdDraft(rest) {
989
993
  ...(leftRules.length ? { leftRules } : {}),
990
994
  ...(checkPicks === undefined ? {} : { checkPicks }),
991
995
  ...(carriedPicks === undefined ? {} : { carriedPicks }),
996
+ ...(carriedChoices === undefined ? {} : { carriedChoices }),
997
+ ...(carriedSheetDropped === undefined ? {} : { carriedSheetDropped }),
992
998
  draftThinking: values.thinking === true ? 'on' : 'off',
993
999
  flowType,
994
1000
  ...(values.mcp ? { mcpServer: values.mcp } : {}),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fwdloop",
3
- "version": "0.32.0",
3
+ "version": "0.33.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",
@@ -51,7 +51,7 @@
51
51
  "dependencies": {
52
52
  "bare-agent": "^0.59.0",
53
53
  "barebrowse": "^0.26.0",
54
- "bareguard": "^0.34.1",
54
+ "bareguard": "^0.36.0",
55
55
  "litectx": "^0.32.0"
56
56
  },
57
57
  "devDependencies": {
@@ -0,0 +1,53 @@
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
+ // 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
+ // 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
+ // (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
+ import { listLinesOf } from './checklistsign.js';
6
+ import { listPartRows } from './checked.js';
7
+ import { EVERY_STEP, EVERY_STEP_TEXTS } from './try-checks.js';
8
+ import { sheetRowsOf } from './sheetrows.js';
9
+
10
+ /** the words of a row no result was recorded for: never "passed" */
11
+ export const AUDIT_NO_RESULT = 'no result recorded';
12
+
13
+ /**
14
+ * @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
+ * @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[], 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
+ */
19
+ export function auditChecksOf(declaration, diary, notChecked, { lines: jobLines = [], csvRoles = [] } = {}) {
20
+ const lines = listLinesOf(declaration);
21
+ const sheetOn = Array.isArray(declaration?.checkList) && declaration.checkList.some((/** @type {any} */ r) => r?.kind === 'sheet');
22
+ const sheetRows = sheetOn ? sheetRowsOf({ declaration, lines: jobLines, csvRoles }) : null;
23
+ if (lines.size === 0 && !(sheetRows && sheetRows.card.length > 0)) return null;
24
+ const steps = (Array.isArray(declaration?.steps) ? declaration.steps : []).filter((/** @type {any} */ st) => lines.has(st?.fromLine));
25
+ const lastTry = (/** @type {any} */ st) => (Array.isArray(diary) ? diary : []).filter((d) => d.step === (st.emits ?? st.goal ?? null)).at(-1);
26
+ /** @type {AuditCheckRow[]} */
27
+ const checks = [];
28
+ for (const st of steps) {
29
+ 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' });
33
+ }
34
+ }
35
+ // 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
36
+ for (const [i, r] of (sheetRows?.card ?? []).entries()) {
37
+ const st = (Array.isArray(declaration?.steps) ? declaration.steps : []).find((/** @type {any} */ x) => x?.fromLine === r.line && Array.isArray(x?.close?.sheet));
38
+ const rec = st ? lastTry(st) : undefined;
39
+ 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' });
41
+ }
42
+ const by = notChecked?.by ?? {};
43
+ /** @type {AuditCheckRow[]} */
44
+ const notRows = (notChecked?.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' }));
45
+ // 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
46
+ const every = (/** @type {string} */ text) => {
47
+ const seen = (Array.isArray(diary) ? diary : []).flatMap((d) => (d.checks ?? []).filter((/** @type {any} */ c) => c.source === EVERY_STEP && c.text === text));
48
+ return seen.length === 0 ? 'none' : seen.every((/** @type {any} */ c) => c.ok) ? 'passed' : 'failed';
49
+ };
50
+ /** @type {AuditCheckRow[]} */
51
+ const always = EVERY_STEP_TEXTS.map((text) => ({ text, by: /** @type {'default'} */ ('default'), result: every(text) }));
52
+ return { checks, notChecked: notRows, always };
53
+ }
package/src/authoring.js CHANGED
@@ -23,8 +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 { addedLinesOf } from './added-end.js';
26
- import { factRows } from './citedcheck.js';
27
- import { plainWords, labelled } from './checkwords.js';
26
+ import { factRows, factSentence, countSentence } from './citedcheck.js';
27
+ import { plainWords, labelled, tagged } from './checkwords.js';
28
+ import { listLinesOf, partByOf, factByOf, countByOf } from './checklistsign.js';
29
+ import { CARD_T } from './checkblock.js';
28
30
  import { sheetLineBlocks } from './sheetblock.js';
29
31
  import { loadCatalogue } from './catalogue.js';
30
32
  import { WIRED_VERBS } from './primitives.js';
@@ -217,6 +219,7 @@ export function buildReadout({
217
219
  if (Array.isArray(declaration.ticketWatch) && declaration.ticketWatch.length) out.push(` ticket watch: ${declaration.ticketWatch.join(', ')}`);
218
220
  out.push('', READOUT_HEADS.steps);
219
221
  const sheetBlocks = sheetLineBlocks({ declaration, lines });
222
+ const onList = listLinesOf(declaration);
220
223
  const addedLines = addedLinesOf(lines, arbiter); // M13 am8: the lines code added at the end are marked `added`
221
224
  declaration.steps.forEach((st, i) => {
222
225
  out.push(` ${i + 1}. (line ${st.fromLine}) ${st.goal}${addedLines.has(st.fromLine) ? ' [added]' : ''}`);
@@ -224,15 +227,26 @@ export function buildReadout({
224
227
  + ` | reads: ${st.reads?.length ? st.reads.join(', ') : '-'} | emits: ${st.emits} | check: ${st.close?.class}`);
225
228
  if (Array.isArray(st.mcpTools) && st.mcpTools.length) out.push(` tools: ${st.mcpTools.join(', ')}`);
226
229
  // M10 am7 item 1: the facts a cited step checks its quotes against, signed with the readout (typed fields, never model prose)
227
- if (st.close?.cited && typeof st.close.cited === 'object') for (const row of factRows(st.close.cited)) out.push(` ${labelled(row, 'agent')}`);
230
+ // 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
231
+ const listed = onList.has(st.fromLine);
232
+ if (listed && st.close?.cited && typeof st.close.cited === 'object') {
233
+ const c = st.close.cited;
234
+ for (const f of Array.isArray(c.facts) ? c.facts : []) out.push(` ${tagged(factSentence(f, c.source), factByOf(declaration, st.fromLine, f.name) ?? 'agent')}`);
235
+ if (countSentence(c)) out.push(` ${tagged(/** @type {string} */ (countSentence(c)), countByOf(declaration, st.fromLine) ?? 'agent')}`);
236
+ } else if (st.close?.cited && typeof st.close.cited === 'object') for (const row of factRows(st.close.cited)) out.push(` ${labelled(row, 'agent')}`);
228
237
  // M10b piece 1: the signed sheet checks, one row each, written by code from the typed fields
229
238
  if (Array.isArray(st.close?.sheet)) for (const row of sheetBlocks.find((b) => b.line === st.fromLine)?.checked ?? []) out.push(` sheet check: ${row.text}`);
230
239
  // M10 am8 item 2: the column lock, signed with the readout (typed fields)
231
240
  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}`);
232
241
  // M10 am16: the checks the person picked, signed with the readout, each in the one set of plain words (typed fields, never model prose)
233
- if (Array.isArray(st.close?.shape?.picked)) for (const c of st.close.shape.picked) out.push(` ${labelled(`you picked: ${plainWords(c)}`, 'picked')}`);
242
+ 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')}`));
234
243
  // M10 am22 (1): the checks the person picked for a fact line are signed with the readout too, in the same words
235
- if (st.close?.class === 'green' && Array.isArray(st.close.picked)) for (const c of st.close.picked) out.push(` ${labelled(`you picked: ${plainWords(c)}`, 'picked')}`);
244
+ 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')}`));
245
+ // M16 R7: the numbers tie of a list line (the `$` row)
246
+ if (listed && Array.isArray(st.close?.numbersFrom) && st.close.numbersFrom.length > 0) {
247
+ 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);
248
+ out.push(` ${tagged(`${CARD_T.numbers} ${st.close.numbersFrom.join(', ')}`, partByOf(declaration, st.fromLine, before) ?? 'default')}`);
249
+ }
236
250
  // M4e amendment 14 item 5: the check's sections in its order (+ word limit); fixed text from typed fields, never model prose.
237
251
  const shape = st.close?.shape;
238
252
  if (Array.isArray(shape?.sections) && shape.sections.length > 0) {
@@ -293,6 +307,25 @@ export function draftKeyRefusal(slot, env) {
293
307
  return key.ok ? null : String(key.message);
294
308
  }
295
309
 
310
+ /**
311
+ * The ONE place a plan folder is claimed: its parent made if needed, then the folder itself, exclusively (an existing path throws EEXIST). `draftToDir` claims the folder of a draft with it and the
312
+ * panel claims the folder of a plan made by a Drop or an Add (src/planrebuild.js).
313
+ * @param {string} dir
314
+ */
315
+ export function claimPlanDir(dir) {
316
+ mkdirSync(path.dirname(path.resolve(dir)), { recursive: true });
317
+ mkdirSync(dir);
318
+ }
319
+
320
+ /**
321
+ * The ONE writer of a plan folder's files: each `name` -> text, in the order given (a draft writes `spec.hash` last, so a folder with one is whole). `opts` is `writeFileSync`'s own
322
+ * (the panel's session files are exclusive, 0600).
323
+ * @param {string} dir @param {Record<string, string>} files @param {{flag?: string, mode?: number}} [opts]
324
+ */
325
+ export function writePlanFiles(dir, files, opts = {}) {
326
+ for (const [f, text] of Object.entries(files)) writeFileSync(path.join(dir, f), text, opts);
327
+ }
328
+
296
329
  /**
297
330
  * Draft into `dir`. $0 refusals (return {ok:false, wrote:false}, nothing on disk): bad key,
298
331
  * unreadable/blank prose, prose that contains the key, missing inputs / bad signed text, dir
@@ -304,7 +337,7 @@ export function draftKeyRefusal(slot, env) {
304
337
  * `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).
305
338
  */
306
339
  export async function draftToDir({
307
- proseFile, dir, root, name, slot, model, draftThinking = /** @type {'on'|'off'} */ ('off'), keyNames, env = process.env, provider, rates, modelId, noQuestions = false, onResult, fetchPage, leftRules, checkPicks, carriedPicks, proseRead,
340
+ proseFile, dir, root, name, slot, model, draftThinking = /** @type {'on'|'off'} */ ('off'), keyNames, env = process.env, provider, rates, modelId, noQuestions = false, onResult, fetchPage, leftRules, checkPicks, carriedPicks, carriedChoices, carriedSheetDropped, proseRead,
308
341
  flowType = /** @type {'plain'|'mcp'|'tickets'} */ ('plain'), mcpServer = /** @type {string|undefined} */ (undefined), mcpPick = /** @type {any} */ (undefined), mcpServers = /** @type {string[]|undefined} */ (undefined),
309
342
  }) {
310
343
  const refuse = (reds) => ({ ok: false, wrote: false, reds, costUsd: 0 });
@@ -337,8 +370,7 @@ export async function draftToDir({
337
370
  const exists = () => refuse([`draft: "${dir}" already exists — never overwritten, use a new dir`]);
338
371
  if (existsSync(dir)) return exists();
339
372
  try {
340
- mkdirSync(path.dirname(path.resolve(dir)), { recursive: true });
341
- mkdirSync(dir);
373
+ claimPlanDir(dir);
342
374
  } catch (e) {
343
375
  return e.code === 'EEXIST' ? exists() : refuse([`draft: cannot create "${dir}": ${e.code ?? e.message}`]);
344
376
  }
@@ -382,9 +414,14 @@ export async function draftToDir({
382
414
  // M13 piece 4 (R1): the job's MCP is every tool of that server's newest OK check, read here by code (the server is never started); never checked = a $0 refusal in the drafter's pre-flight
383
415
  const mcp = flowType === 'plain' ? null : (mcpPick ?? (typeof mcpServer === 'string' ? mcpPickHere(mcpServer) : { ok: false, say: 'pick an MCP for this flow type' }));
384
416
  /** @type {{picks: object[], kept: object[]}|null} */
417
+ /** @type {any[]|null} */
418
+ let rowChoices = null; // a Revise's carried Drop/Add choices, handed back by draft() and kept in the same record
419
+ /** @type {any[]} */
420
+ let sheetDropped = []; // the sheet checks this plan has dropped (a Revise's carried ones, applied by draft()), kept in the same record
421
+ /** @type {any} */
385
422
  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)
386
423
  const result = await draft({
387
- 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 }), ...(checkPicks === undefined ? {} : { checkPicks }), ...(carriedPicks === undefined ? {} : { carriedPicks }), onPickRecord: (r) => { pickRecord = r; },
424
+ 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 }), ...(checkPicks === undefined ? {} : { checkPicks }), ...(carriedPicks === undefined ? {} : { carriedPicks }), ...(carriedChoices === undefined ? {} : { carriedChoices, onChoices: (rec) => { rowChoices = rec; } }), ...(carriedSheetDropped === undefined ? {} : { carriedSheetDropped }), onSheetDropped: (rec) => { sheetDropped = rec; }, onPickRecord: (r) => { pickRecord = r; },
388
425
  flowType, mcp, ...(mcpServers === undefined ? {} : { mcpServers }),
389
426
  });
390
427
  if (result.stop === 'pre-flight') {
@@ -406,6 +443,7 @@ export async function draftToDir({
406
443
  const parsed = parseSignedText(prose.text); // the drafter already proved it parses
407
444
  if (!parsed.ok) return paidFail(`parse: ${parsed.reds.join('; ')}`);
408
445
  const dj = (o) => `${JSON.stringify(o, null, 2)}\n`;
446
+ /** @type {Record<string, string>} */
409
447
  const files = {};
410
448
  files['prose.txt'] = prose.text; // verbatim
411
449
  const targetText = dj({ root, name });
@@ -416,13 +454,15 @@ export async function draftToDir({
416
454
  // Amendments 24/25: the questions and the drafter's own "not checked" reading are written BEFORE log.json/spec.hash (the panel reads those
417
455
  // two as "the draft finished"), as their own files: never in the readout, so never in the hash.
418
456
  if (result.questions?.length) files[QUESTIONS_FILE] = scrub(dj({ questions: result.questions }), secrets);
419
- if (pickRecord !== null) files[RECORD_FILE] = scrub(dj(pickRecord), secrets); // M10 am17: the picks carried to the next plan (this drafting folder only, never a run folder)
420
- files[NOT_CHECKED_FILE] = scrub(dj({ notChecked: result.notChecked ?? [] }), secrets);
457
+ if (pickRecord !== null) files[RECORD_FILE] = scrub(dj({ ...pickRecord, ...(rowChoices === null ? {} : { rowChoices }), ...(sheetDropped.length ? { sheetDropped } : {}) }), secrets); // M10 am17: the picks carried to the next plan (this drafting folder only, never a run folder)
458
+ 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
421
459
  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);
422
460
  files['log.json'] = scrub(dj({
423
461
  ok: result.ok, stop: result.stop, reds: result.reds, rounds: result.rounds, calls: result.calls, costUsd: result.costUsd, spendComplete: result.spendComplete,
424
462
  modelId: result.modelId, modelReturned: result.modelReturned, structureRetries: result.structureRetries,
425
463
  revisions: result.revisions, thinking: result.thinking, inputs: result.inputs, log: result.log,
464
+ // 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
465
+ ...(result.checkCard ? { checkCard: result.checkCard } : {}),
426
466
  }), secrets);
427
467
  let hash = null;
428
468
  if (result.ok) {
@@ -465,7 +505,7 @@ export async function draftToDir({
465
505
  });
466
506
  // M4d am32: the spend is booked, and the result files are about to be written: the monthly hold is given back now, so a draft never reads done while its hold is still held
467
507
  if (typeof onResult === 'function') onResult({ ok: result.ok });
468
- for (const [f, text] of Object.entries(files)) writeFileSync(path.join(dir, f), text);
508
+ writePlanFiles(dir, files);
469
509
  if (pick !== null) writeModelRecord(dir, pick);
470
510
  leaks = sweepForSecrets(dir, secrets);
471
511
  if (leaks > 0) {
@@ -0,0 +1,44 @@
1
+ // borrowed-from: bareloop src/blockasks.js@v0.56.0 (3383cce)
2
+ // 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
3
+ // 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`.
4
+ import { readingQuestion, cantCheckQuestion } from './pageask.js';
5
+ import { plainWords, HOW_TO_ANSWER, CANT_CHECK_WORDS } from './checkpick.js';
6
+
7
+ /** @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>, pairRule?: number}} BlockAsk */
8
+
9
+ /**
10
+ * 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).
11
+ * 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
12
+ * 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.
13
+ * @param {import('./checkblock.js').CheckBlock} block @param {{line: number, rule: number}[]} [scoped] @returns {BlockAsk[]}
14
+ */
15
+ export function questionsOfBlock(block, scoped = []) {
16
+ const rank = { reading: 0, 'cant-check': 1, 'no-check': 2, check: 2 };
17
+ return block.open.map((/** @type {any} */ q) => {
18
+ const row = block.rows.find((r) => r.key === q.rowKey);
19
+ const rule = Number(row?.rule);
20
+ const base = { key: q.key, rowKey: q.rowKey, line: q.line, rule, source: /** @type {'look'} */ ('look'), ruleText: String(q.ruleText), ...(row?.pairWith !== undefined ? { pairRule: row.pairWith } : {}) };
21
+ if (q.ask === 'reading') return { ...base, ask: /** @type {'reading'} */ ('reading'), counted: true, reading: String(q.proposal), question: readingQuestion(q.line, String(q.ruleText), String(q.proposal)) };
22
+ if (q.ask === 'check') {
23
+ const words = plainWords(q.proposal);
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)}` };
25
+ }
26
+ 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)}` };
27
+ return { ...base, ask: /** @type {'cant-check'} */ ('cant-check'), counted: true, question: cantCheckQuestion(q.line, String(q.ruleText)) };
28
+ }).sort((a, b) => rank[a.ask] - rank[b.ask]);
29
+ }
30
+
31
+ /**
32
+ * The person's choices back into the block, one by one (the choice decides, never the words). A choice the block refuses is returned with its plain reason; the question stays open.
33
+ * @param {import('./checkblock.js').CheckBlock} block @param {{key: string, choice: string, text?: string}[]} choices @returns {{key: string, why: string}[]}
34
+ */
35
+ export function applyChoices(block, choices) {
36
+ /** @type {{key: string, why: string}[]} */
37
+ const refused = [];
38
+ for (const c of choices) {
39
+ const r = block.applyAnswer(c.key, c.choice, c.text);
40
+ if (!r.ok) refused.push({ key: c.key, why: r.why });
41
+ }
42
+ block.reconcile();
43
+ return refused;
44
+ }
@@ -0,0 +1,140 @@
1
+ // M16 item 2 (docs/wiki/the-module-ladder.md, "M16"): "the AI sends only edits to that list; code proves each one and builds every check. The AI never writes a check."
2
+ // The declaration of a draft with the list on keeps the AI's steps, reads, primitives and asks, and takes the CHECKS of every line the block was given from the block's built parts:
3
+ // a fact part -> close.cited = {source, facts, count}, class green; the source is added to the step's reads by code
4
+ // a countable part -> a picked check (M10 am22 (1)-(3)): close.shape.picked on a softgreen step, close.picked on a fact (or sheet) step with the line in pickedLines
5
+ // the numbers tie -> close.numbersFrom (M16 am3 (2), R7)
6
+ // no part -> hitl, and `unjudgeable` carries the rows' Not-checked reasons
7
+ // Whatever the AI wrote for these checks (close.cited, close.shape, close.picked, close.class) is dropped. The block's signed rows become the declaration's `checkList`, which the sign and the
8
+ // run-start gate prove (src/checklistsign.js). A fwd line keeps ONE close per line, whose class must equal the class its guardrail earns (signed, M4d): so a line with no guardrail of the
9
+ // person's own can carry only the numbers tie; any other check the list built there cannot be signed on it and its rows are signed Not checked, with that reason.
10
+
11
+ /** what a row says when its check cannot ride a line that has no guardrail of its own (the class of a line comes from its guardrail) */
12
+ export const NO_GUARDRAIL_WORDS = 'This line has no guardrail of yours, so a check on it cannot be signed; you judge it at the Ask.';
13
+
14
+ import { factsOfLook } from './citedcheck.js';
15
+ import { REASON, renderCard } from './checkblock.js';
16
+ import { dropSentence } from './pagedropwords.js';
17
+ import { KEPT_WORDS } from './pickrecord.js';
18
+
19
+ const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
20
+
21
+ /** the words the card draws a row with, without its `~` / `!` / `$` mark (the one renderer, src/checkblock.js renderCard) @param {Record<string, any>} row */
22
+ const rowWords = (row) => String(renderCard([{ ...row, hidden: false, state: row.state === 'suggested' || row.state === 'dropped' ? 'not-checked' : row.state }])[0]?.text ?? '').slice(2);
23
+
24
+ /**
25
+ * The words a Not-checked row says. A rule the person left, wrote in their own words, or left with no pick keeps fwd's signed table (M10 am16 (5): src/pagedropwords.js), the words the plan card and the
26
+ * Audit already had; any other reason is the block's own (what code could not build and why).
27
+ * @param {string|null|undefined} reason @param {{cantAsked?: boolean}} [row]
28
+ */
29
+ export function notCheckedWords(reason, row = undefined) {
30
+ // a rule the person answered with their own words says so, whatever bareguard-free reason the block holds for it (a countable one reads "no rule can check this")
31
+ if (row?.cantAsked === true && (reason === REASON.noRule || reason === REASON.nothingOnPage)) return dropSentence({ line: 0, fact: '', reason: 'own-words' });
32
+ if (reason === REASON.left) return dropSentence({ line: 0, fact: '', reason: 'person-left' });
33
+ if (reason === REASON.nothingOnPage) return dropSentence({ line: 0, fact: '', reason: 'own-words' });
34
+ if (reason === REASON.noRule || reason === REASON.noPick || reason === REASON.cantCheck) return dropSentence({ line: 0, fact: '', reason: 'no-pick' });
35
+ return String(reason ?? 'not checked');
36
+ }
37
+
38
+ /** a countable part as the picked check the softgreen close runs: its own fields, the rule named `rule` (the inverse of the block's partOfPick) @param {Record<string, any>} part */
39
+ export function pickedOf(part) {
40
+ const { text: _t, class: _c, check, rules: _r, source: _s, from: _f, oldIndex: _o, ...fields } = part;
41
+ return { rule: check, ...fields };
42
+ }
43
+
44
+ /**
45
+ * @param {{declaration: Record<string, any>, block: import('./checkblock.js').CheckBlock, lines: {n: number, guardrail?: string|null}[], lineSet: Set<number>}} o
46
+ * `lineSet` = the lines the block was given; `lines` = the signed lines (a guardrail decides the class)
47
+ * @returns {{declaration: Record<string, any>, notChecked: string[], notCheckedBy: Record<string, 'you'|'agent'|'default'>, built: Set<number>}} `built` = the lines that got a check from the block (a red naming one of them is a fault of the build)
48
+ */
49
+ export function assembleFromBlock({ declaration, block, lines, lineSet }) {
50
+ if (!isRec(declaration) || !Array.isArray(declaration.steps)) return { declaration, notChecked: [], notCheckedBy: {}, built: new Set() };
51
+ const c = block.reconcile();
52
+ // fwd's signed R2c (M10 am7 item 2; bareloop v0.56.0 has no such rule, M16 am3 (1): fwd's rule stays): a place the page-read grew to phrases is checked with EVERY phrase, one phrase fact each,
53
+ // not with the one word the block built it from
54
+ const placeFactsOf = (/** @type {any} */ part, /** @type {number} */ n) => {
55
+ const places = /** @type {any[]} */ (block.lookFacts).filter((k) => k.line === n && Array.isArray(k.phrases) && (k.source === undefined || k.source === part.source));
56
+ return part.facts.flatMap((/** @type {any} */ f) => { const k = f.shape === 'phrase' ? places.find((x) => String(x.name) === f.name) : undefined; return k ? factsOfLook(k) : [f]; });
57
+ };
58
+ const partsOf = (/** @type {number} */ n) => c.map.filter((m) => m.line === n).map((m) => ({ ...c.parts[m.part], oldIndex: c.map.filter((x) => x.line === n).findIndex((x) => x.part === m.part) }));
59
+ const guarded = (/** @type {number} */ n) => typeof lines.find((l) => l.n === n)?.guardrail === 'string' && String(lines.find((l) => l.n === n)?.guardrail).trim() !== '';
60
+ /** @type {Set<number>} */ const built = new Set();
61
+ /** @type {Map<number, Map<number, number|null>>} old part index -> new close-part index (null = the part is not in the close), per line */
62
+ const remap = new Map();
63
+ /** @type {Set<number>} */ const notSignable = new Set();
64
+ /** @type {Set<number>} */ const pickedLines = new Set(Array.isArray(declaration.pickedLines) ? declaration.pickedLines : []);
65
+ const guardrailClasses = isRec(declaration.guardrailClasses) ? { ...declaration.guardrailClasses } : {};
66
+ const unjudgeable = isRec(declaration.unjudgeable) ? { ...declaration.unjudgeable } : {};
67
+ const rowsOn = (/** @type {number} */ n) => block.rows.filter((r) => r.line === n && r.kind !== 'floor' && !r.hidden && r.state === 'not-checked');
68
+ const steps = declaration.steps.map((/** @type {any} */ st) => {
69
+ const n = st?.fromLine;
70
+ if (!isRec(st) || !Number.isInteger(n) || !lineSet.has(n)) return st;
71
+ const parts = partsOf(n);
72
+ const signable = guarded(n);
73
+ const fact = signable ? parts.find((p) => p.class === 'fact') : undefined;
74
+ const picks = signable ? parts.filter((p) => p.class === 'countable' && p.check !== 'cited' && p.check !== 'numbersFromFacts') : [];
75
+ const tie = parts.find((p) => p.class === 'countable' && p.check === 'numbersFromFacts');
76
+ const old = isRec(st.close) ? st.close : {};
77
+ const sheet = Array.isArray(old.sheet) ? old.sheet : null;
78
+ // the part order the close lists them in (src/checklistsign.js closePartsOf): the fact part, each pick, the tie
79
+ const keptOrder = [...(fact ? [fact] : []), ...picks, ...(tie ? [tie] : [])];
80
+ const map = remap.get(n) ?? new Map();
81
+ for (const p of parts) map.set(p.oldIndex, keptOrder.includes(p) ? keptOrder.indexOf(p) : null);
82
+ remap.set(n, map);
83
+ if (!signable && parts.some((p) => p !== tie)) notSignable.add(n);
84
+ /** @type {Record<string, any>} */
85
+ const close = { ...(sheet ? { sheet } : {}), ...(Array.isArray(old.columns) ? { columns: old.columns } : {}) };
86
+ if (fact) {
87
+ close.class = 'green';
88
+ close.cited = { source: fact.source, facts: placeFactsOf(fact, n), ...(isRec(fact.count) ? { count: fact.count } : {}) };
89
+ } else close.class = sheet ? 'green' : picks.length ? 'softgreen' : 'hitl';
90
+ if (picks.length) {
91
+ const checks = picks.map(pickedOf);
92
+ if (close.class === 'green') { close.picked = checks; pickedLines.add(n); } else close.shape = { picked: checks };
93
+ }
94
+ if (tie) close.numbersFrom = [...tie.from];
95
+ if (fact || picks.length || tie) built.add(n);
96
+ const reads = Array.isArray(st.reads) && fact && !st.reads.includes(fact.source) ? [...st.reads, fact.source] : st.reads;
97
+ return { ...st, reads, close };
98
+ });
99
+ // the class of a line with a guardrail is the class its close ended in; a hitl one says why in the rows' own Not-checked reasons
100
+ for (const n of lineSet) {
101
+ const mine = steps.find((/** @type {any} */ st) => isRec(st) && st.fromLine === n);
102
+ // the classes of a list line are code's: a line with no guardrail of the person's has no class entry and no unjudgeable note, whatever the AI sent
103
+ if (!guarded(n)) { delete guardrailClasses[String(n)]; delete unjudgeable[String(n)]; continue; }
104
+ if (!mine) continue;
105
+ guardrailClasses[String(n)] = mine.close.class;
106
+ if (mine.close.class === 'hitl') unjudgeable[String(n)] = [...new Set(rowsOn(n).map((r) => notCheckedWords(r.reason, r)).filter(Boolean))].join(' ') || 'No check was picked for it, so you judge it at the Ask.';
107
+ else delete unjudgeable[String(n)];
108
+ }
109
+ const served = new Set(steps.filter((/** @type {any} */ st) => isRec(st)).map((/** @type {any} */ st) => st.fromLine));
110
+ /** the signed list: the block's signed fields per row, the parts renumbered to the close's order, a row whose check cannot ride its line signed Not checked @type {any[]} */
111
+ const checkList = block.signedRows().map((/** @type {any} */ r) => {
112
+ const m = remap.get(r.line);
113
+ const idx = isRec(r.part) && m ? m.get(r.part.part) : undefined;
114
+ if (r.state === 'built' && r.kind !== 'floor' && (idx === null || idx === undefined)) {
115
+ const { part: _p, ...rest } = r;
116
+ return { ...rest, state: 'not-checked', reason: notSignable.has(r.line) ? NO_GUARDRAIL_WORDS : String(r.reason ?? 'not checked') };
117
+ }
118
+ return isRec(r.part) && typeof idx === 'number' ? { ...r, part: { line: r.part.line, part: idx } } : r;
119
+ });
120
+ /** @type {Record<string, 'you'|'agent'|'default'>} the tag of each Not-checked line, by the row it tells (M16 item 5: one tag per row) */
121
+ const notCheckedBy = {};
122
+ const notChecked = checkList.filter((r) => r.state === 'not-checked' && r.kind !== 'floor').map((r) => {
123
+ const own = block.rows.find((x) => x.key === r.key);
124
+ if (own?.hidden) return null;
125
+ // an agreed or carried `~` line shares its source's answer (a follower is told as the rule it follows)
126
+ const row = own?.parent ? { ...own, cantAsked: block.rows.find((x) => x.key === own.parent)?.cantAsked === true, keptFromLast: own.keptFromLast ?? block.rows.find((x) => x.key === own.parent)?.keptFromLast } : own;
127
+ // any other row is told in the words the card draws it with (renderCard; never the row's key)
128
+ // a `~` rule is told in the signed table's form, `not checked · "<rule>" — <reason>` (M10 am16 (5)); any other row names its line
129
+ const kept = row?.keptFromLast === true ? ` (${KEPT_WORDS})` : ''; // M10 am17 (6)
130
+ const line = r.kind === 'rule' && row?.text ? `not checked · "${row.text}" — ${notCheckedWords(r.reason, row)}${kept}` : `line ${r.line}: ${rowWords(own ?? r)} - ${notCheckedWords(r.reason, row)}${kept}`;
131
+ if (r.by === 'you' || r.by === 'agent' || r.by === 'default') notCheckedBy[line] = r.by;
132
+ return line;
133
+ }).filter((x) => x !== null);
134
+ /** @type {Record<string, any>} */
135
+ const listed = checkList.filter((r) => served.has(r.line)); // a line no step serves is refused as a line; its rows are not signed
136
+ /** @type {Record<string, any>} */
137
+ const out = { ...declaration, steps, guardrailClasses, ...(Object.keys(unjudgeable).length || isRec(declaration.unjudgeable) ? { unjudgeable } : {}), checkList: listed };
138
+ if (pickedLines.size) out.pickedLines = [...pickedLines].sort((a, b) => a - b); else delete out.pickedLines;
139
+ return { declaration: out, notChecked: /** @type {string[]} */ (notChecked), notCheckedBy, built };
140
+ }
@@ -0,0 +1,91 @@
1
+ // M16 (docs/wiki/the-module-ladder.md, "M16"): the pieces of the drafter that touch the check block, in one place. src/drafter.js calls them in bareloop's order (authorjob.js@v0.56.0:
2
+ // build the block after the look, carry the last picks, the AI's pre-edits, the asks; then authorflow.js@v0.56.0: the row-edit turn, a revise only when an edit was refused, at most twice).
3
+ // borrowed-from: bareloop src/authorflow.js@v0.56.0 (3383cce) (renderRejectBlock, 'edits' kind only; MAX_REVISIONS; the plan-red words)
4
+ import { redactSecrets } from './redact.js';
5
+ import { newJobBlock } from './blocklines.js';
6
+ import { EDIT_OPS } from './checkblock.js';
7
+ import { isCountGuardrail } from './declaration.js';
8
+
9
+ /** the cap of refusals one revise turn carries (bareloop REVISE_RED_CAP) */
10
+ export const REVISE_RED_CAP = 20;
11
+
12
+ /** the tail of a revise turn that follows refused edits: each refusal's own reason and nothing else (bareloop renderRejectBlock) @param {string[]} reds */
13
+ export function renderRejectBlock(reds, cap = REVISE_RED_CAP) {
14
+ const shown = reds.slice(0, cap);
15
+ const tail = reds.length > shown.length ? [` [${reds.length - shown.length} of ${reds.length} reds withheld — the cap is ${cap}]`] : [];
16
+ return redactSecrets(['MEASURED EDITS — some of your edits were refused; each refusal is its own and your other edits stand:', ...shown.map((r) => ` ${r}`), ...tail].join('\n'));
17
+ }
18
+
19
+ /** the words a plan-red on a part the block built stops with (bareloop authorflow.js@v0.56.0): our fault, never sent to the AI @param {string[]} reds */
20
+ export const buildFaultWords = (reds) => `The plan code built from your checks did not pass its own gate (${reds.slice(0, 2).join('; ')}). That is a fault in the build, not in your job: nothing was spent on a close.`;
21
+
22
+ /**
23
+ * Is this validator red about a check the BLOCK built (R2)? It names a line the block gave a check to (`builtLines`, from the red's own line number) and is about a close the code wrote: the quote check, a
24
+ * picked check, the numbers tie, the class, the list or the picked-lines record; or it is the cited words' own `line N:` red. A red on a step's primitives, reads, emits or an ask names none of those.
25
+ * @param {string} red @param {number[]} builtLines the lines the red names that the block built a check on
26
+ */
27
+ export function isBuildFault(red, builtLines) {
28
+ if (builtLines.length === 0) return false;
29
+ return /close\.(?:cited|picked|shape|numbersFrom|class)|checkList|pickedLines/.test(red) || /^declaration: line \d+:/.test(red);
30
+ }
31
+
32
+ /**
33
+ * The block of a draft (M16 item 2): the person's `~` rules and `$` defaults, then the look's facts, then the picks the person made (kept from the last draft, and just answered), reconciled once.
34
+ * Fresh answers go through `carry` like the kept ones (the draft is a child process: the answer comes back as a pick or a left rule), and are not marked "kept".
35
+ * `scoped`: the rules the pick path owns (src/checkpick.js offerRules over the block's lines); one the record folded into another ask (a broken pair's partner) is neither asked nor given the old check (bareloop authorjob.js@v0.56.0).
36
+ * @param {{leaveOut?: {line: number, rule: number}[], texts: Record<string, string>, jobLines: any[], look: {facts: any[], dropped: any[]}, kept: {picks: any[], left: any[], askRules: any[]}, fresh: {picks: any[], left: {line: number, rule: number}[]}, asks: boolean, countScope: (t: string) => boolean, scoped?: {line: number, rule: number}[]}} o
37
+ */
38
+ export function setUpBlock({ texts, jobLines, look, kept, fresh, asks, countScope, scoped = [], leaveOut = [] }) {
39
+ const block = newJobBlock({ texts, jobLines, asks, countScope });
40
+ // M16 item 4: a Tickets job's own guardrails (the signed ticketFilter / ticketWatch) are not rows of the list; the rule numbers of the other rules stay as written
41
+ if (leaveOut.length) block.rows = block.rows.filter((r) => !(r.kind === 'rule' && leaveOut.some((x) => x.line === r.line && x.rule === r.rule)));
42
+ // a rule the person left is the block's own `left` row (carry, below); the look's person-left drop would say it twice
43
+ block.addLook(look.facts, look.dropped.filter((d) => d.reason !== 'person-left'));
44
+ block.carry({ picks: kept.picks, left: kept.left }, kept.askRules);
45
+ const rowOf = (/** @type {number} */ line, /** @type {number} */ rule) => block.ruleRows(line).find((x) => x.rule === rule);
46
+ block.carry({ picks: fresh.picks, left: fresh.left });
47
+ for (const x of [...fresh.picks, ...fresh.left]) { const r = rowOf(x.line, x.rule); if (r && !kept.picks.some((k) => k.line === x.line && k.rule === x.rule) && !kept.left.some((k) => k.line === x.line && k.rule === x.rule)) delete r.keptFromLast; }
48
+ block.reconcile();
49
+ for (const r of scoped) {
50
+ const row = rowOf(r.line, r.rule);
51
+ if (row && !kept.askRules.some((a) => a.line === r.line && a.rule === r.rule) && !row.pick && !row.cantAsked && !row.left && !row.parent) row.folded = true;
52
+ }
53
+ block.reconcile();
54
+ return block;
55
+ }
56
+
57
+ /** the `pick` pre-edits of the one suggest call: a kept check on a block line, as the block's own edit (R1; bareloop authorjob.js@v0.56.0) @param {{line: number, rule: number, check: Record<string, any>|null}[]} rows @param {Set<number>} blockLines */
58
+ export const pickEdits = (rows, blockLines) => rows.filter((r) => r.check && blockLines.has(r.line)).map((r) => ({ op: 'pick', line: r.line, rules: [r.rule], check: r.check }));
59
+
60
+ /** the `add` pre-edits of the ledger-suggest call (bareloop authorjob.js@v0.56.0: a count or a phrase; anything else is not an edit) @param {any[]} extra */
61
+ export function ledgerEdits(extra) {
62
+ /** @type {any[]} */
63
+ const adds = [];
64
+ for (const e of Array.isArray(extra) ? extra : []) {
65
+ const line = Number.isInteger(e?.line) ? e.line : 1;
66
+ if (e?.kind === 'count') adds.push({ op: 'add', kind: 'count', line, min: e.min, max: e.max });
67
+ else if (e?.kind === 'phrase' && typeof e.phrase === 'string') adds.push({ op: 'add', kind: 'phrase', line, name: e.phrase, words: [e.phrase], source: e.source });
68
+ }
69
+ return adds;
70
+ }
71
+
72
+ /**
73
+ * M4d am39 on the row-edit turn: a brace-repaired reply is used only when the block can read every edit in it (an `edits` list of objects with a known op). A reply the block would refuse as unreadable
74
+ * is a structure failure instead, as the declaration turn does for an unknown key.
75
+ * @param {any} value
76
+ */
77
+ export const repairedEditsReadable = (value) => Array.isArray(value?.edits) && value.edits.every((/** @type {any} */ e) => e && typeof e === 'object' && !Array.isArray(e) && EDIT_OPS.includes(e.op));
78
+
79
+ /** one applied reply as the round log keeps it: each edit, kept or refused with its own reason @param {{edits: any[]}} rec */
80
+ export const editRecord = (rec) => rec.edits.map((e) => ({ op: e?.op, accepted: e.accepted === true, ...(e.accepted === true ? {} : { refusedBecause: e.refusedBecause }) }));
81
+
82
+ /**
83
+ * M16 item 4 ("Tickets `ticketFilter` and `ticketWatch` stay as they are"): the rules of a Tickets job that are not the block's. Before M16 only a count guardrail of such a job (it signs a
84
+ * ticket page input, which routes its guardrails: src/checkpick.js codeScope) was picked or asked; every other rule ("priority P1 only", "run a ticket again when its state changes") was the
85
+ * declaration's own typed ticketFilter / ticketWatch, never asked and never listed as Not checked. A rule the look tied to a fact is still the block's.
86
+ * @param {string} flowType @param {{n: number, rules?: string[]}[]} jobLines @param {{line: number, forRule?: number}[]} facts @returns {{line: number, rule: number}[]}
87
+ */
88
+ export function ticketLeaveOut(flowType, jobLines, facts) {
89
+ if (flowType !== 'tickets') return [];
90
+ return jobLines.flatMap((l) => (l.rules ?? []).map((t, i) => ({ line: l.n, rule: i + 1, t })).filter((x) => !isCountGuardrail(x.t) && !facts.some((f) => f.line === x.line && f.forRule === x.rule)).map((x) => ({ line: x.line, rule: x.rule })));
91
+ }
@@ -0,0 +1,30 @@
1
+ // M16 am1 (docs/wiki/the-module-ladder.md, "M16"): the lines the check block is given. STEP lines only: an ask line, a send line and a sheet line get no row.
2
+ // Kinds come from fwd's own code: parseSignedText (asks, sends), csvRolesOf + sheetLineBlocks (sheet lines). No classifier of its own.
3
+ import { parseSignedText } from './signed-text.js';
4
+ import { csvRolesOf, sheetLineBlocks, rulesOfLine } from './sheetblock.js';
5
+ import { CheckBlock } from './checkblock.js';
6
+
7
+ /**
8
+ * @param {string} prose the job's signed text (or the draft's prose)
9
+ * @param {any} [declaration] the declaration, once there is one. Before it exists nothing in fwd says which line reads a sheet (sheetLineBlocks reads the steps' `reads` / `close.sheet`),
10
+ * so a sheet line is then given as a step line; the caller passes the declaration whenever it has one.
11
+ * @param {number[]} [tiedSheetLines] lines whose `~` rule the sheet look (src/sheetlook.js) tied to a real column: sheet lines before there is a declaration (M16 R6); they stay on fwd's sheet path
12
+ * @returns {{ok: true, jobLines: {n: number, text: string, rules: string[]}[], skipped: {ask: number[], send: number[], sheet: number[]}}|{ok: false, reds: string[]}}
13
+ */
14
+ export function blockJobLines(prose, declaration, tiedSheetLines = []) {
15
+ const p = parseSignedText(prose);
16
+ if (!p.ok) return { ok: false, reds: p.reds };
17
+ const ask = p.arbiter.asks.map((a) => a.line);
18
+ const send = p.arbiter.sends.map((s) => s.line);
19
+ const lines = p.lines.map((l) => ({ n: l.n, guardrail: l.guardrail }));
20
+ const sheet = [...new Set([...(declaration ? sheetLineBlocks({ declaration, lines, csvRoles: csvRolesOf(p.arbiter) }).map((b) => b.line) : []), ...tiedSheetLines])];
21
+ const jobLines = p.lines.filter((l) => !ask.includes(l.n) && !send.includes(l.n) && !sheet.includes(l.n)).map((l) => ({ n: l.n, text: l.text, rules: rulesOfLine(l) }));
22
+ return { ok: true, jobLines, skipped: { ask, send, sheet } };
23
+ }
24
+
25
+ /** a block over step lines only, with no `$` cited default (M16 am1). `texts`: label -> frozen text. */
26
+ export function newJobBlock({ texts, jobLines, asks = true, countScope = /** @type {((t: string) => boolean)|undefined} */ (undefined) }) {
27
+ const block = new CheckBlock({ texts, labels: Object.keys(texts), asks, split: true, cited: false, ...(countScope ? { countScope } : {}) });
28
+ block.fromJob(jobLines);
29
+ return block;
30
+ }