fwdloop 0.21.0 → 0.23.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 (104) hide show
  1. package/bin/fwdloop +85 -34
  2. package/package.json +4 -3
  3. package/src/ask.js +20 -4
  4. package/src/audit-fold.js +5 -1
  5. package/src/authoring.js +36 -6
  6. package/src/canrun.js +5 -0
  7. package/src/checked.js +32 -4
  8. package/src/cited-record.js +138 -0
  9. package/src/cited-source.js +49 -0
  10. package/src/citedcheck.js +321 -0
  11. package/src/citedwords.js +197 -0
  12. package/src/closers.js +37 -198
  13. package/src/csv.js +69 -12
  14. package/src/ctx-tools.js +2 -14
  15. package/src/declaration.js +143 -5
  16. package/src/diary.js +2 -2
  17. package/src/docx.js +16 -2
  18. package/src/draft-steps.js +1 -1
  19. package/src/drafter.js +322 -33
  20. package/src/flow.js +33 -7
  21. package/src/flowmodel.js +21 -0
  22. package/src/input-facts.js +20 -3
  23. package/src/model-step.js +38 -21
  24. package/src/pageask.js +136 -0
  25. package/src/pagebits.js +107 -0
  26. package/src/pagedropwords.js +171 -0
  27. package/src/pagedry.js +120 -0
  28. package/src/pagefetch.js +164 -0
  29. package/src/pagelook.js +155 -0
  30. package/src/pagemap.js +55 -0
  31. package/src/pageplace.js +103 -0
  32. package/src/pagerules.js +318 -0
  33. package/src/panel/author.js +43 -21
  34. package/src/panel/authorcard.js +20 -3
  35. package/src/panel/authorflows.js +21 -15
  36. package/src/panel/authorstart.js +2 -4
  37. package/src/panel/authortrigger.js +14 -4
  38. package/src/panel/data.js +102 -6
  39. package/src/panel/index.html +321 -12
  40. package/src/panel/result.js +301 -0
  41. package/src/panel/server.js +27 -3
  42. package/src/primitives.js +2 -3
  43. package/src/provider.js +5 -2
  44. package/src/redact.js +17 -0
  45. package/src/runner.js +102 -14
  46. package/src/schedule.js +3 -3
  47. package/src/setup.js +16 -1
  48. package/src/sheet-record.js +57 -0
  49. package/src/sheetblock.js +170 -0
  50. package/src/sheetchecks.js +206 -0
  51. package/src/sheetclaims.js +78 -0
  52. package/src/sheetfind.js +50 -0
  53. package/src/sheetlook.js +157 -0
  54. package/src/sheetoffer.js +125 -0
  55. package/src/sheetrun.js +105 -0
  56. package/src/signed-text.js +11 -1
  57. package/src/thinking.js +1 -1
  58. package/src/try-checks.js +12 -0
  59. package/src/types.js +4 -11
  60. package/types/ask.d.ts +2 -1
  61. package/types/authoring.d.ts +19 -2
  62. package/types/checked.d.ts +19 -3
  63. package/types/cited-record.d.ts +21 -0
  64. package/types/cited-source.d.ts +18 -0
  65. package/types/citedcheck.d.ts +95 -0
  66. package/types/citedwords.d.ts +97 -0
  67. package/types/closers.d.ts +37 -10
  68. package/types/csv.d.ts +25 -4
  69. package/types/ctx-tools.d.ts +0 -1
  70. package/types/declaration.d.ts +20 -1
  71. package/types/docx.d.ts +14 -0
  72. package/types/drafter.d.ts +264 -8
  73. package/types/flow.d.ts +21 -0
  74. package/types/flowmodel.d.ts +15 -0
  75. package/types/input-facts.d.ts +12 -2
  76. package/types/model-step.d.ts +40 -19
  77. package/types/pageask.d.ts +75 -0
  78. package/types/pagebits.d.ts +32 -0
  79. package/types/pagedropwords.d.ts +40 -0
  80. package/types/pagedry.d.ts +38 -0
  81. package/types/pagefetch.d.ts +86 -0
  82. package/types/pagelook.d.ts +75 -0
  83. package/types/pagemap.d.ts +31 -0
  84. package/types/pageplace.d.ts +22 -0
  85. package/types/pagerules.d.ts +86 -0
  86. package/types/panel/authorcard.d.ts +4 -1
  87. package/types/panel/authorflows.d.ts +2 -0
  88. package/types/panel/data.d.ts +26 -0
  89. package/types/panel/result.d.ts +156 -0
  90. package/types/provider.d.ts +3 -1
  91. package/types/redact.d.ts +1 -0
  92. package/types/runner.d.ts +162 -9
  93. package/types/schedule.d.ts +0 -11
  94. package/types/setup.d.ts +13 -0
  95. package/types/sheet-record.d.ts +24 -0
  96. package/types/sheetblock.d.ts +116 -0
  97. package/types/sheetchecks.d.ts +70 -0
  98. package/types/sheetclaims.d.ts +26 -0
  99. package/types/sheetfind.d.ts +46 -0
  100. package/types/sheetlook.d.ts +120 -0
  101. package/types/sheetoffer.d.ts +25 -0
  102. package/types/sheetrun.d.ts +35 -0
  103. package/types/thinking.d.ts +1 -1
  104. package/types/types.d.ts +27 -14
package/src/runner.js CHANGED
@@ -58,6 +58,10 @@ import {
58
58
  } from './canrun.js'; // M4e am7 item 7: the ONE decider (F46 refusal lives there)
59
59
  import { configHome, configDoorHome } from './config.js';
60
60
  import { closeByClass, isCellsPath } from './closers.js';
61
+ import { readRunSource } from './cited-source.js';
62
+ import { citedLineOf, writeCitedLine } from './cited-record.js';
63
+ import { sheetRolesOf, tableShaOfFrozen, readRunSheets } from './sheetrun.js';
64
+ import { writeSheetLine } from './sheet-record.js';
61
65
  import {
62
66
  appendAudit, appendHistory, readAudit, readHistory, endRow, HALT_OUTCOMES,
63
67
  } from './books.js';
@@ -67,7 +71,8 @@ import { appendChecks, nextRound } from './diary.js';
67
71
  import {
68
72
  doneRecord, happenedRecord, outputRecord, closeRecords,
69
73
  } from './try-checks.js';
70
- import { readJobThinking, writeRunThinking } from './flowmodel.js';
74
+ import { readJobThinking, writeRunThinking, writeRunModel } from './flowmodel.js';
75
+ import { fetchPageText, isWebUrl } from './pagefetch.js';
71
76
  import {
72
77
  readResumeLock, recordPid, writeLockHolder, procStartOf, LOCK_NO_HOLDER,
73
78
  } from './liveness.js';
@@ -390,14 +395,41 @@ export function checkFreshRunDir(runDir) {
390
395
  return { ok: true };
391
396
  }
392
397
 
398
+ /** M10 item 1: fetch a web page and freeze its text as `<dir>/<id>.txt`; the sha256 is of the FROZEN bytes, like a file input. The ONE writer of a
399
+ * page's frozen copy: drafting calls it with its draft folder, a run start (via `freezeInputs`) with the run's `inputs/`, so the two are
400
+ * separate files and a run is only ever checked against its own. The fetch is tried once; a refusal names the input and says why in plain words.
401
+ * @param {string} dir @param {string} id @param {string} url
402
+ * @param {{fetchPage?: (url: string) => Promise<{ok: true, text: string, url: string}|{ok: false, error: string}>}} [o]
403
+ * @returns {Promise<{ok: true, text: string, entry: {id: string, source: string, frozen: string, sha256: string, bytes: number}}|{ok: false, red: string}>} `text` = the frozen text itself, for the caller that reads it (drafting) */
404
+ export async function freezePage(dir, id, url, { fetchPage = fetchPageText } = {}) {
405
+ const got = await fetchPage(url);
406
+ if (!got.ok) return { ok: false, red: `freeze: input "${id}": ${got.error}` };
407
+ mkdirSync(dir, { recursive: true });
408
+ const frozen = join(dir, `${id}.txt`);
409
+ writeFileSync(frozen, got.text, 'utf8');
410
+ return { ok: true, text: got.text, entry: { id, source: url, frozen, sha256: hashFile(frozen), bytes: statSync(frozen).size } };
411
+ }
412
+
393
413
  /** Copy each named source into `<runDir>/inputs/`, hash the FROZEN copy
394
414
  * (never the original again after this), write `inputs.json`. An
395
- * unreadable source refuses by name. */
396
- export function freezeInputs(runDir, sources) {
415
+ * unreadable source refuses by name. A source that is a web address
416
+ * (M10 item 1) is fetched and frozen by `freezePage`, in the same manifest.
417
+ * @param {string} runDir @param {Array<{id: string, path: string}>} sources
418
+ * M10b amendment 1: a CSV input named in `tableRoles` (the sheets a step's `close.sheet` reads) also gets its `tableSha` (bareguard's fingerprint of the table made
419
+ * from the FROZEN copy) in its manifest entry - the ONE place it is written, once, with the run's inputs; every sheet check of the run uses this recorded value.
420
+ * A sheet bareguard cannot read as a table refuses the run here, naming the input.
421
+ * @param {{fetchPage?: (url: string) => Promise<{ok: true, text: string, url: string}|{ok: false, error: string}>, tableRoles?: string[]}} [o] */
422
+ export async function freezeInputs(runDir, sources, { fetchPage, tableRoles = [] } = {}) {
397
423
  const inputsDir = join(runDir, 'inputs');
398
424
  mkdirSync(inputsDir, { recursive: true });
399
425
  const manifest = [];
400
426
  for (const { id, path: sourcePath } of sources ?? []) {
427
+ if (isWebUrl(sourcePath)) {
428
+ const page = await freezePage(inputsDir, id, sourcePath, { fetchPage });
429
+ if (!page.ok) return page;
430
+ manifest.push(page.entry);
431
+ continue;
432
+ }
401
433
  if (!existsSync(sourcePath)) {
402
434
  return { ok: false, red: `freeze: input "${id}" is unreadable at ${sourcePath}` };
403
435
  }
@@ -405,9 +437,16 @@ export function freezeInputs(runDir, sources) {
405
437
  copyFileSync(sourcePath, frozenPath);
406
438
  const sha256 = hashFile(frozenPath);
407
439
  const { size: bytes } = statSync(frozenPath);
408
- manifest.push({
440
+ /** @type {Record<string, any>} */
441
+ const entry = {
409
442
  id, source: sourcePath, frozen: frozenPath, sha256, bytes,
410
- });
443
+ };
444
+ if (tableRoles.includes(id)) {
445
+ const tsha = isCellsPath(frozenPath) ? tableShaOfFrozen(runDir, basename(frozenPath)) : null;
446
+ if (tsha === null) return { ok: false, red: `freeze: input "${id}" cannot be read as a table (a row with more or fewer cells than the header, or a repeated column name); fix the sheet` };
447
+ entry.tableSha = tsha;
448
+ }
449
+ manifest.push(entry);
411
450
  }
412
451
  writeFileSync(join(runDir, 'inputs.json'), JSON.stringify(manifest, null, 2));
413
452
  return { ok: true, manifest };
@@ -569,7 +608,7 @@ export function readArtifact(runDir, id) {
569
608
  * indistinguishable from "not written yet") into a step.
570
609
  * @returns {{ok:true, map:Record<string,any>} | {ok:false, red:string}}
571
610
  */
572
- function readArtifactsMapChecked(runDir, ids) {
611
+ export function readArtifactsMapChecked(runDir, ids, { docxRoles = /** @type {string[]} */ ([]) } = {}) {
573
612
  const map = {};
574
613
  for (const id of ids ?? []) {
575
614
  const result = readArtifactResult(runDir, id);
@@ -581,12 +620,21 @@ function readArtifactsMapChecked(runDir, ids) {
581
620
  const input = readInputCells(runDir, id);
582
621
  if (!input.ok && !input.missing) return { ok: false, red: `input "${id}" — ${input.red}` };
583
622
  if (input.ok) { map[id] = input.value; continue; }
623
+ // M10 am7 item 3: an id that names a saved web page (or a text file) is read as its text, from the RUN'S OWN frozen copy, sha-checked, through the one safe
624
+ // read gateway (`readFileInside`, in `readRunSource`). By role, text only: a copy that is missing or changed refuses the step; an id that is no text input
625
+ // of this run is left as it was (undefined).
626
+ const page = readRunSource(runDir, id, { docx: docxRoles.includes(id) });
627
+ if (page.ok) { map[id] = { kind: 'text', text: page.text }; continue; }
628
+ if (page.code === 'unreadable') return { ok: false, red: page.red };
584
629
  }
585
630
  map[id] = result.ok ? result.value : undefined;
586
631
  }
587
632
  return { ok: true, map };
588
633
  }
589
634
 
635
+ /** M10 piece 5 (item 2): the role a green step quotes from - the one input whose .docx text its check (and so the step itself) may be handed. @param {any} step @returns {string[]} */
636
+ const citedRolesOf = (step) => (step?.close?.class === 'green' && typeof step.close.cited?.source === 'string' ? [step.close.cited.source] : []);
637
+
590
638
  /** A frozen CSV input as `{kind:'cells', header, rows}` (the shape `addressCells` gives), checked against the sha256 recorded at freeze.
591
639
  * Same three outcomes as `readArtifactResult`: not an input of this run (`missing`), refused (`red`), or the cells. */
592
640
  function readInputCells(runDir, id) {
@@ -727,7 +775,7 @@ function makeAuditRow({
727
775
  * @param {string|null} [opts.runDir] - M4d am29 item 2: the run's folder, where each try saves its checks
728
776
  * @returns {Promise<{ok:true, artifact:any, attempts:number, hitl?:boolean} | {ok:false, outcome:string, red:string, stop?:{where:string, book:Record<string, any>, step?:string|null}}>}
729
777
  */
730
- async function runStepRalph({
778
+ export async function runStepRalph({
731
779
  step, primitivesMap, readsMap, businessDate, modelStep, spent, capUsd, ceilingUsd, recordAudit, initialGap = null, attemptOffset = 0,
732
780
  // M4d am25: the job's "Thinking on" box as the run's own copy keeps it; read once by the caller (`readJobThinking`), decided per try below by `stepThinkingMode`.
733
781
  thinkingBox = false,
@@ -798,7 +846,9 @@ async function runStepRalph({
798
846
  // scope item 3's own invariant: the schema is class-only, and the
799
847
  // construction test below proves the context itself stays clean).
800
848
  // M4d am25: `thinkingMode` is the ONE decision of what this try asks of thinking (`stepThinkingMode`); the model step only passes it on.
801
- const stepMeta = Object.freeze({ class: step.close?.class ?? null, attempt, step: step?.emits ?? step?.goal ?? null, thinkingMode: stepThinkingMode({ boxOn: thinkingBox, attempt }) });
849
+ // M10 am7 item 3: `cited` is the fact part of a green step that quotes a saved page - the form of its ANSWER ({results: [{quote, values}]}) and the facts it must hold,
850
+ // told to the step in plain words by the model step. It is not the check: the quotes are checked by `closeCited` against the run's own copy.
851
+ const stepMeta = Object.freeze({ class: step.close?.class ?? null, cited: step.close?.class === 'green' && step.close.cited ? step.close.cited : null, sheet: step.close?.class === 'green' && Array.isArray(step.close.sheet) ? step.close.sheet : null, attempt, step: step?.emits ?? step?.goal ?? null, thinkingMode: stepThinkingMode({ boxOn: thinkingBox, attempt }) });
802
852
 
803
853
  const stopSeam = readStop ? Object.freeze({ stopRequested: readStop }) : undefined;
804
854
 
@@ -865,6 +915,9 @@ async function runStepRalph({
865
915
  // step's own failure to produce, not a system halt), strike-eligible
866
916
  // like any other close red.
867
917
  const red = result?.red ?? 'model step failed with no artifact';
918
+ // The try may have cost money (a length stop: "truncated: N tokens, no tool call"). Its row carries that cost below, so the run's spend
919
+ // - the cap check, the history total - takes it here, the same one add as the stop and transport branches (books must balance).
920
+ if (typeof result?.costUsd === 'number') spent.value += result.costUsd;
868
921
  const normalised = normaliseGap(red);
869
922
  const strike = seenGaps.has(normalised);
870
923
  seenGaps.add(normalised);
@@ -934,7 +987,21 @@ async function runStepRalph({
934
987
  continue;
935
988
  }
936
989
 
937
- const closed = await closeByClass(step, artifact, { reads: readsMap, businessDate });
990
+ // M10 piece 4: a step that cites quotes reads the run's OWN frozen copy of its source (never the drafting copy); the record of what the check said is
991
+ // written by the one writer, `writeCitedLine`, whatever the verdict - the Result tab says why a line did not pass.
992
+ const citedPart = step?.close?.class === 'green' ? step?.close?.cited : undefined;
993
+ const source = citedPart && runDir !== null ? readRunSource(runDir, citedPart.source, { docx: true }) : undefined;
994
+ // M10b piece 2: a step with `close.sheet` is checked by bareguard on the run's own frozen copy and the `tableSha` recorded at its start; the record of what it
995
+ // said is written by the one writer, `writeSheetLine`, whatever the verdict.
996
+ const sheetPart = step?.close?.class === 'green' && Array.isArray(step?.close?.sheet) ? step.close.sheet : undefined;
997
+ const sheet = sheetPart && runDir !== null ? readRunSheets(runDir, sheetPart) : undefined;
998
+ const closed = await closeByClass(step, artifact, { reads: readsMap, businessDate, source, sheet });
999
+ if (sheetPart && runDir !== null && closed.sheetRecord) writeSheetLine(runDir, { n: step.fromLine, try: attempt, checks: sheetPart, closed });
1000
+ if (citedPart && runDir !== null && closed.cited) {
1001
+ writeCitedLine(runDir, citedLineOf({
1002
+ n: step.fromLine, part: closed.cited.part, results: closed.cited.results, check: closed.cited.check,
1003
+ }));
1004
+ }
938
1005
  tryChecks.push(...closeRecords(step, artifact, closed));
939
1006
  saveTry();
940
1007
 
@@ -991,16 +1058,20 @@ async function runStepRalph({
991
1058
  * @param {() => string} [opts.clock] - returns the current ISO timestamp; defaults to the wall clock.
992
1059
  * @param {string} opts.businessDate - the run's explicit "as of today", never the wall clock.
993
1060
  * @param {number} [opts.ceilingUsd] - per-attempt ceiling override; the model's hold from Settings prices (`ceilingCostUsd`); absent = no hold.
1061
+ * @param {{slot: string, model: string}} [opts.runModel] - M4d am33: the model this run started on; recorded once in the run folder (run-model.json) and kept by every resume/continue.
994
1062
  * @param {string|null} [opts.initialGap] - M3 scope item 7 (rerun as a fresh
995
1063
  * run): a human's rerun reason, carried as the FIRST ordinary step's
996
1064
  * starting gap. Never used by a plain `runFlow` call outside `resumeRun`'s
997
1065
  * own rerun path.
1066
+ * @param {(url: string) => Promise<{ok: true, text: string, url: string}|{ok: false, error: string}>} [opts.fetchPage] - M10: the web-page fetch (default barebrowse via src/pagefetch.js); a test injects one.
998
1067
  * @param {() => number} [opts.nowMs] - F45 finding 3: returns the current
999
1068
  * epoch ms; defaults to the wall clock. Mirrors `clock` (ISO) so a test
1000
1069
  * can advance wall time across a park/resume boundary without a real wait.
1001
1070
  */
1002
1071
  export async function runFlow({
1003
- root, name, runId, sources, catalogue, modelStep, askStep, sendStep, primitives, primitiveReds, clock, businessDate, ceilingUsd, initialGap,
1072
+ root, name, runId, sources, catalogue, modelStep, askStep, sendStep, primitives, primitiveReds, clock, businessDate, ceilingUsd, initialGap, fetchPage,
1073
+ // M4d am33: the model this run STARTED on ({ slot, model }); recorded once beside the run, kept by every resume/continue. Absent = nothing recorded.
1074
+ runModel,
1004
1075
  // F45 finding 3's test needs to advance wall time across a park/resume
1005
1076
  // boundary without a real wait, exactly like `clock` already does for ISO
1006
1077
  // timestamps — `nowMs` is the same idea for epoch-ms wall-clock reads.
@@ -1107,8 +1178,9 @@ export async function runFlow({
1107
1178
 
1108
1179
  // M4d am25: the run keeps the job's "Thinking on" box as it is now (read by `readJobThinking` on every try and every resume)
1109
1180
  writeRunThinking(flowDir, runDir);
1181
+ if (runModel) writeRunModel(runDir, runModel); // M4d am33: the one record of the model this run started on
1110
1182
 
1111
- const frozen = freezeInputs(runDir, sources ?? []);
1183
+ const frozen = await freezeInputs(runDir, sources ?? [], { fetchPage, tableRoles: sheetRolesOf(declaration.steps) });
1112
1184
  if (!frozen.ok) {
1113
1185
  return haltRun({
1114
1186
  flowDir, runDir, runId, capUsd, startedAt, now, nowMs: getNowMs, signatureHash: signature.flow, outcome: 'preflight-red', red: frozen.red, spent: { value: 0 },
@@ -1259,6 +1331,19 @@ function makeOneShotThenParkAskStep({ decision, reason, artifactSha256 }) {
1259
1331
  };
1260
1332
  }
1261
1333
 
1334
+ /**
1335
+ * M4d am30: the highest try number a step has used in this run, read from the books (audit.jsonl, the source of truth). A Redo's re-run is
1336
+ * numbered after it, so a number is used once per step. Only the NUMBER moves: the limit counts the re-run's own tries (`n` in `runStepRalph`).
1337
+ * @param {string} runDir @param {string|null} stepId
1338
+ */
1339
+ function lastTryNumber(runDir, stepId) {
1340
+ let last = 0;
1341
+ for (const r of readAudit(runDir)) {
1342
+ if (r.step === stepId && Number.isInteger(r.attempt) && r.verdict !== 'cap-halt' && r.verdict !== 'stop-asked' && r.verdict !== 'stop-not-honoured' && r.attempt > last) last = r.attempt;
1343
+ }
1344
+ return last;
1345
+ }
1346
+
1262
1347
  /**
1263
1348
  * One signed ask slot's own loop (M2's ask branch, unchanged in spirit,
1264
1349
  * extracted so `resumeRun` can re-enter the SAME logic mid-ask instead of
@@ -1453,13 +1538,13 @@ async function runAskSlot({
1453
1538
  // swap / unparseable JSON) is tampering, never "not written yet", and
1454
1539
  // must halt the redo rather than silently feed forged/garbage content
1455
1540
  // into the model step that is about to re-run.
1456
- const priorReadsResult = readArtifactsMapChecked(runDir, priorStep.reads);
1541
+ const priorReadsResult = readArtifactsMapChecked(runDir, priorStep.reads, { docxRoles: citedRolesOf(priorStep) });
1457
1542
  if (!priorReadsResult.ok) {
1458
1543
  return { type: 'halted', outcome: 'red', red: `redo: step "${priorStep.goal}" ${priorReadsResult.red}` };
1459
1544
  }
1460
1545
  // eslint-disable-next-line no-await-in-loop
1461
1546
  const redoResult = await runStepRalph({
1462
- step: priorStep, primitivesMap: primitives, readsMap: priorReadsResult.map, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, initialGap: reason, attemptOffset: redone, thinkingBox: readJobThinking(flowDir, runDir), now, runDir,
1547
+ step: priorStep, primitivesMap: primitives, readsMap: priorReadsResult.map, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, initialGap: reason, attemptOffset: lastTryNumber(runDir, priorStep.emits ?? priorStep.goal ?? null), thinkingBox: readJobThinking(flowDir, runDir), now, runDir,
1463
1548
  readStop: () => stopPending(runDir), stepNo: priorStepNo, prevStepId: priorPrevStepId,
1464
1549
  });
1465
1550
  if (!redoResult.ok) {
@@ -1700,7 +1785,7 @@ async function foldFromStep({
1700
1785
  // F48 round 4: every id in `step.reads` names an earlier step in THIS
1701
1786
  // same fold pass, already run and already written — a `red` read here
1702
1787
  // halts rather than silently feeding tampered/unreadable content in.
1703
- const readsMapResult = readArtifactsMapChecked(runDir, step.reads);
1788
+ const readsMapResult = readArtifactsMapChecked(runDir, step.reads, { docxRoles: citedRolesOf(step) });
1704
1789
  if (!readsMapResult.ok) {
1705
1790
  return haltRun({
1706
1791
  flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts,
@@ -1890,11 +1975,13 @@ function sameRoot(recorded, requested) {
1890
1975
  * @param {() => string} [opts.clock]
1891
1976
  * @param {string} opts.businessDate
1892
1977
  * @param {number} [opts.ceilingUsd]
1978
+ * @param {{slot: string, model: string}} [opts.runModel] - M4d am33: the model this run started on; recorded once in the run folder (run-model.json) and kept by every resume/continue.
1893
1979
  * @param {() => number} [opts.nowMs] - F45 finding 3; see `runFlow`'s own.
1894
1980
  * @param {(newRunDir:string) => void} [opts.onRerunStart] - amendment 16 C2: called with the new run's folder just before a `rerun` starts it.
1895
1981
  */
1896
1982
  export async function resumeRun({
1897
1983
  root, name, runId, catalogue, modelStep, sendStep, primitives, primitiveReds, clock, businessDate, ceilingUsd,
1984
+ runModel, // M4d am33: the model the resumed run keeps; a rerun (a new run) records it too
1898
1985
  // F45 finding 3 (see `runFlow`'s own `nowMs`): additive, defaults to the
1899
1986
  // real `Date.now` for every existing caller.
1900
1987
  nowMs,
@@ -2237,6 +2324,7 @@ export async function resumeRun({
2237
2324
  clock,
2238
2325
  businessDate,
2239
2326
  ceilingUsd,
2327
+ runModel,
2240
2328
  // Item 7: the reason becomes the new run's FIRST step's starting gap.
2241
2329
  initialGap: reason,
2242
2330
  });
package/src/schedule.js CHANGED
@@ -28,10 +28,10 @@ import { triggerHash } from './trigger-line.js';
28
28
  * }} Schedule
29
29
  */
30
30
 
31
- export const SCHEDULE_FILE = 'schedule.json';
32
- export const LEDGER_FILE = 'schedule-ledger.jsonl';
31
+ const SCHEDULE_FILE = 'schedule.json';
32
+ const LEDGER_FILE = 'schedule-ledger.jsonl';
33
33
  /** The words of the am16 row (also for a Cancel): signed text, M9 am16. @param {string} name */
34
- export const droppedSay = (name) => `${name} was waiting when the schedule changed, so it will not run. Drop it in again to run it.`;
34
+ const droppedSay = (name) => `${name} was waiting when the schedule changed, so it will not run. Drop it in again to run it.`;
35
35
 
36
36
  /** @param {string} flowDir */
37
37
  export const scheduleFileOf = (flowDir) => join(flowDir, SCHEDULE_FILE);
package/src/setup.js CHANGED
@@ -11,7 +11,7 @@ import { lstatSync, writeFileSync } from 'node:fs';
11
11
  import { triesOf } from './draft-steps.js';
12
12
  import { join } from 'node:path';
13
13
 
14
- import { scrub } from './authoring.js';
14
+ import { readQuestions, scrub } from './authoring.js';
15
15
  import { notCheckedBlock } from './checked.js';
16
16
  import { readDraftSpend } from './draftspend.js';
17
17
  import { readFileInside, readdirInside } from './flow.js';
@@ -58,6 +58,19 @@ function planRow(sessionDir, rel, kind, n) {
58
58
  };
59
59
  }
60
60
 
61
+ /**
62
+ * M10 am2 item 4: one row per question the page look raised and the person answered, in the plan folder that raised it (the draft log's human rows, read
63
+ * from the answer files). The question, the answer, the line and the time, plus the proposal and the rule the answer added as their own fields (never cut
64
+ * out of the question text). A question nobody answered leaves no row.
65
+ * @param {string} sessionDir @param {string} rel
66
+ */
67
+ function humanRows(sessionDir, rel) {
68
+ return readQuestions(join(sessionDir, rel)).questions.filter((q) => q.source === 'look' && q.answer !== null).map((q) => ({
69
+ kind: 'human', n: q.k, at: q.at ?? null, source: 'look', ask: q.ask, question: q.question, answer: q.answer, line: q.line,
70
+ ruleNo: q.ruleNo, ruleText: q.ruleText, proposal: q.proposal ?? null, rule: q.rule ?? null,
71
+ }));
72
+ }
73
+
61
74
  /**
62
75
  * The rows of a draft's record, oldest first. `sessionDir` is the panel's draft folder (card.json, draft/, card-<n>.json, draft-<n>/); a CLI
63
76
  * draft has none, so its record is its one plan folder (`planDir`, read as `draft`) plus the sign.
@@ -73,6 +86,7 @@ export function buildSetupRows({
73
86
  // amendment 14 item 6: a draft begun by Start over says so (written once by the panel's start); its row reads `start over`
74
87
  const so = readJson(sessionDir, 'started-over-from.json');
75
88
  rows.push(planRow(sessionDir, 'draft', typeof so?.startedOverFrom === 'string' ? 'startover' : 'draft', 0));
89
+ rows.push(...humanRows(sessionDir, 'draft'));
76
90
  // amendment 14 item 6: each revise is the card as submitted, then its plan row (model, cost, verdict, hash); there is no note row
77
91
  const ns = readdirInside(sessionDir, '.').map((f) => CARD_RE.exec(f)?.[1]).filter((x) => x !== undefined).map(Number).sort((a, b) => a - b);
78
92
  for (const n of ns) {
@@ -80,6 +94,7 @@ export function buildSetupRows({
80
94
  if (card) rows.push({ kind: 'card', n, at: mtimeIso(sessionDir, `card-${n}.json`), card });
81
95
  // M4e amendment 24 item 4: a plan drafted again after the human's answers is booked as `redraft`, not `revise` (it uses none of the 2 revises)
82
96
  rows.push(planRow(sessionDir, `draft-${n}`, readJson(sessionDir, `redraft-${n}.json`) ? 'redraft' : 'revise', n));
97
+ rows.push(...humanRows(sessionDir, `draft-${n}`));
83
98
  }
84
99
  } else {
85
100
  const r = planRow(planDir, '.', 'draft', 0);
@@ -0,0 +1,57 @@
1
+ // M10b piece 2: the ONE writer of `<run>/sheet-checks.json`, the record of what each sheet check said in this run, for the separate checker that re-runs a run's
2
+ // signed checks against its saved sheet (M10b "Done when"). Append-only: one entry per (job line, try), written the moment that try's check has run, never replaced.
3
+ // Shape: { lines: [ { n, try, passed, tables: [{name, tableSha}], checks: [the signed check objects], claims: <the step's answer>, results: [{id, text, ok, result}], red } ] }.
4
+ // `tables[].tableSha` is the one recorded at the run's start (inputs.json), the one the check used. Throws away: nothing the check saw; no cell text is kept here.
5
+ import { writeFileSync, renameSync } from 'node:fs';
6
+ import { join } from 'node:path';
7
+ import { readFileInside } from './flow.js';
8
+
9
+ /** the record's name in the run's own folder */
10
+ export const SHEET_CHECKS_FILE = 'sheet-checks.json';
11
+
12
+ const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
13
+
14
+ /**
15
+ * @param {string} runDir @param {{n: number, try: number, checks: any[], closed: {verdict: string, red?: string|null, sheetRecord?: any}}} o
16
+ * @returns {void}
17
+ */
18
+ export function writeSheetLine(runDir, { n, try: attempt, checks, closed }) {
19
+ const rec = closed.sheetRecord;
20
+ if (!rec) return;
21
+ /** @type {any[]} */
22
+ let lines = [];
23
+ const had = readFileInside(runDir, SHEET_CHECKS_FILE);
24
+ if (had.ok) {
25
+ try {
26
+ const parsed = JSON.parse(had.text);
27
+ if (isRec(parsed) && Array.isArray(parsed.lines)) lines = parsed.lines;
28
+ } catch { lines = []; }
29
+ }
30
+ if (lines.some((l) => isRec(l) && l.n === n && l.try === attempt)) return;
31
+ lines.push({
32
+ n, try: attempt, passed: closed.verdict === 'green',
33
+ tables: rec.inputs.map((/** @type {any} */ i) => ({ name: i.name, tableSha: i.sha256 })),
34
+ checks: JSON.parse(JSON.stringify(checks)),
35
+ claims: rec.claims,
36
+ results: rec.checks,
37
+ red: closed.verdict === 'green' ? null : (closed.red ?? null),
38
+ });
39
+ const file = join(runDir, SHEET_CHECKS_FILE);
40
+ const tmp = `${file}.tmp`;
41
+ writeFileSync(tmp, `${JSON.stringify({ lines }, null, 2)}\n`);
42
+ renameSync(tmp, file);
43
+ }
44
+
45
+ /**
46
+ * The reader of the record, for the Result tab and the separate checker: `{lines: [...]}`, or null when the file is missing or is not that shape (the page then
47
+ * shows no verdicts, never a half-read record). Read through the safe gateway.
48
+ * @param {string} runDir @returns {{lines: any[]}|null}
49
+ */
50
+ export function readSheetChecks(runDir) {
51
+ const got = readFileInside(runDir, SHEET_CHECKS_FILE);
52
+ if (!got.ok) return null;
53
+ try {
54
+ const parsed = JSON.parse(got.text);
55
+ return isRec(parsed) && Array.isArray(parsed.lines) ? { lines: parsed.lines } : null;
56
+ } catch { return null; }
57
+ }
@@ -0,0 +1,170 @@
1
+ // M10b piece 4 (docs/wiki/the-module-ladder.md "M10b amendment 2", items 4 and 7): the ONE builder of what a job line that reads a sheet shows -
2
+ // { guardrails, checked: [{id, name, words, covers, text}], notChecked: [guardrail, ...] | 'none' }
3
+ // from the signed declaration (the step's `close.sheet`, each check's `covers` tag) and the job line's own `~` rules. After a run, `record` (the
4
+ // `sheet-checks.json` lines, src/sheet-record.js) adds to each check its verdict and what was found: `{ok, found}`. Every surface (the Chat plan card, the Job tab, the
5
+ // Result tab, the Audit's check rows) shows this block's strings; none of them words a check itself.
6
+ // Throws away: the check's id, claim, range and the other typed fields that do not change what it says (src/sheetchecks.js `sheetCheckSentence` drops them too).
7
+ // A green "found" is the step's OWN claimed value in plain words (a number, or a count of rows / days / bands / groups); a string claim (a looked-up cell) is never
8
+ // repeated, because it is cell text. A red "found" is bareguard's gap words (row numbers and counts), never a cell's text.
9
+ // Third outcomes, named: a line the run never reached (no record) carries no verdict; a check the record lacks carries none (the page shows no mark).
10
+ import { isDeepStrictEqual } from 'node:util';
11
+ import { rubricVocabulary } from 'bareguard';
12
+ import { lineRules } from './pagebits.js';
13
+ import { sheetCheckSentence } from './sheetchecks.js';
14
+ import { isColumnChoiceRule } from './sheetoffer.js';
15
+
16
+ const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
17
+
18
+ /** the short plain name of each bareguard op (the ONE table; a test fails when bareguard gains an op this table does not name). `noDuplicates` and `noEmpty` add the column. */
19
+ export const SHEET_OP_NAMES = Object.freeze({
20
+ count: 'count', countEmpty: 'empty count', countIf: 'count', uniqueCount: 'unique count',
21
+ sum: 'sum', sumIf: 'sum', average: 'average', averageIf: 'average', median: 'median', min: 'min', max: 'max',
22
+ found: 'found', lookup: 'lookup', rows: 'rows', topN: 'top', duplicates: 'duplicates', groupTotals: 'group totals', percentOfTotal: 'percent of total',
23
+ band: 'bucket', daysBetween: 'days between', daysSince: 'date', earliest: 'earliest date', latest: 'latest date',
24
+ allNumbers: 'all numbers', allDates: 'all dates', noEmpty: 'no empty', noDuplicates: 'no duplicate', rowCount: 'row count', rowMath: 'row math',
25
+ });
26
+
27
+ /** the ops of bareguard that a name is needed for @returns {string[]} */
28
+ export function vocabularyOps() {
29
+ const V = /** @type {any} */ (rubricVocabulary);
30
+ return [...new Set(['cells', 'table'].flatMap((r) => Object.keys(V.rules[r].ops)))];
31
+ }
32
+
33
+ /** @param {any} check a bareguard cells / table check @returns {string} the short name: `rows`, `count`, `sum`, `no duplicate Invoice #` ... */
34
+ export function sheetCheckName(check) {
35
+ if (!isRec(check)) return 'a check';
36
+ const base = Object.hasOwn(SHEET_OP_NAMES, check.op) ? /** @type {Record<string, string>} */ (SHEET_OP_NAMES)[check.op] : String(check.op);
37
+ return (check.op === 'noDuplicates' || check.op === 'noEmpty') && typeof check.column === 'string' ? `${base} ${check.column}` : base;
38
+ }
39
+
40
+ /**
41
+ * What the step claimed for one check, in plain words (a green check's "found"). Null when the claim has nothing to say (a `table` check, a missing box, a string).
42
+ * @param {any} check @param {unknown} claims the step's answer @returns {string|null}
43
+ */
44
+ export function sheetFoundWords(check, claims) {
45
+ if (!isRec(check) || typeof check.claim !== 'string' || !isRec(claims) || !isRec(/** @type {any} */ (claims)[check.claim])) return null;
46
+ const box = /** @type {Record<string, any>} */ (/** @type {any} */ (claims)[check.claim]);
47
+ const plural = (/** @type {number} */ n, /** @type {string} */ one, /** @type {string} */ many) => `${n} ${n === 1 ? one : many}`;
48
+ if (typeof box.value === 'number' || typeof box.value === 'boolean') return typeof box.value === 'boolean' ? (box.value ? 'yes' : 'no') : String(box.value);
49
+ if (Array.isArray(box.rows)) return plural(box.rows.length, 'row', 'rows');
50
+ if (Array.isArray(box.keys)) return plural(box.keys.length, 'row', 'rows');
51
+ if (Array.isArray(box.values)) return plural(box.values.length, 'value', 'values');
52
+ if (Array.isArray(box.totals)) return plural(box.totals.length, 'group', 'groups');
53
+ if (isRec(box.days)) return plural(Object.keys(box.days).length, 'row', 'rows');
54
+ if (isRec(box.bands)) return plural(Object.keys(box.bands).length, 'row', 'rows');
55
+ return null;
56
+ }
57
+
58
+ /** @param {any} l a job line `{rules?, guardrail?, rule?}` @returns {string[]} its `~` rules, numbered from 1 by position */
59
+ export const rulesOfLine = (l) => lineRules({ ...(Array.isArray(l?.rules) ? { rules: l.rules } : {}), rule: l?.guardrail ?? l?.rule });
60
+
61
+ /** the "covers ..." words of one check @param {string[]} rules @returns {string} "" when it covers none */
62
+ export const coversWords = (rules) => rules.map((r) => `covers "${r}"`).join(' · ');
63
+
64
+ /**
65
+ * The block of every job line whose step reads a sheet. A line qualifies when its green step carries `close.sheet`, or (with `csvRoles`) reads a CSV input and carries no
66
+ * older `close.columns` / `close.cited` check (then every guardrail is Not checked).
67
+ * @param {{declaration: any, lines: Array<{n: number, rules?: string[], guardrail?: string, rule?: string}>, csvRoles?: string[], record?: any}} o
68
+ * `record` = the parsed `sheet-checks.json` (`{lines: [...]}`), only after a run
69
+ * @returns {Array<{line: number, guardrails: string[], checked: Array<{id: string, name: string, words: string, covers: string[], coversWords: string, text: string, ok?: boolean, found?: string}>, notChecked: string[]|'none'}>}
70
+ */
71
+ export function sheetLineBlocks({ declaration, lines, csvRoles = [], record }) {
72
+ const out = [];
73
+ if (!isRec(declaration) || !Array.isArray(declaration.steps)) return out;
74
+ const seen = new Set();
75
+ for (const st of declaration.steps) {
76
+ if (!isRec(st) || !isRec(st.close) || st.close.class !== 'green' || !Number.isInteger(st.fromLine) || seen.has(st.fromLine)) continue;
77
+ const hasSheet = Array.isArray(st.close.sheet) && st.close.sheet.length > 0;
78
+ const readsCsv = Array.isArray(st.reads) && st.reads.some((/** @type {string} */ r) => csvRoles.includes(r));
79
+ if (!hasSheet && (!readsCsv || st.close.columns !== undefined || st.close.cited !== undefined)) continue;
80
+ seen.add(st.fromLine);
81
+ const guardrails = rulesOfLine((Array.isArray(lines) ? lines : []).find((l) => l.n === st.fromLine));
82
+ const covered = new Set();
83
+ const tried = Array.isArray(record?.lines) ? record.lines.filter((/** @type {any} */ l) => isRec(l) && l.n === st.fromLine && Number.isInteger(l.try)) : [];
84
+ const newest = tried.reduce((/** @type {any} */ m, /** @type {any} */ l) => (m === null || l.try >= m.try ? l : m), null);
85
+ const checked = (hasSheet ? st.close.sheet : []).map((/** @type {any} */ c) => {
86
+ const nums = Array.isArray(c.covers) ? c.covers.filter((/** @type {unknown} */ x) => Number.isInteger(x) && /** @type {number} */ (x) >= 1 && /** @type {number} */ (x) <= guardrails.length) : [];
87
+ for (const x of nums) covered.add(x);
88
+ const rules = [...new Set(nums)].sort((a, b) => a - b).map((x) => guardrails[x - 1]);
89
+ const name = sheetCheckName(c);
90
+ const words = sheetCheckSentence(c);
91
+ const cw = coversWords(rules);
92
+ /** @type {any} */
93
+ const e = { id: typeof c.id === 'string' ? c.id : '', name, words, covers: rules, coversWords: cw, text: [name, ...(words === name ? [] : [words]), ...(cw ? [cw] : [])].join(' — ') };
94
+ const res = newest && Array.isArray(newest.results) ? newest.results.find((/** @type {any} */ r) => isRec(r) && r.id === c.id) : undefined;
95
+ if (isRec(res) && typeof res.ok === 'boolean') {
96
+ e.ok = res.ok;
97
+ if (res.ok) {
98
+ const f = sheetFoundWords(c, newest.claims);
99
+ e.found = f === null ? `${name} checked` : `${name} checked — ${f}`;
100
+ } else {
101
+ const gap = typeof res.result === 'string' ? res.result.split('\n').map((/** @type {string} */ x) => x.trim().replace(`${e.id}: `, '')).filter(Boolean).join('; ') : '';
102
+ e.found = `${name} — ${gap || 'did not pass'}`;
103
+ }
104
+ }
105
+ return e;
106
+ });
107
+ const notChecked = guardrails.filter((r, i) => !isColumnChoiceRule(r) && !covered.has(i + 1));
108
+ out.push({ line: st.fromLine, guardrails, checked, notChecked: notChecked.length === 0 ? /** @type {'none'} */ ('none') : notChecked });
109
+ }
110
+ return out;
111
+ }
112
+
113
+ /**
114
+ * The guardrail rules of a sheet step that no check covers, as the drafter's Not-checked lines (`line N: "rule" - no sheet check covers it`): the block's own
115
+ * `notChecked`, one list for the plan card and the drafter's saved record.
116
+ * @param {any} declaration @param {Array<{n: number, rules?: string[], guardrail?: string, rule?: string}>} lines @param {string[]} csvRoles @returns {string[]}
117
+ */
118
+ export function uncoveredRules(declaration, lines, csvRoles) {
119
+ if (csvRoles.length === 0) return [];
120
+ return sheetLineBlocks({ declaration, lines, csvRoles }).flatMap((b) => (b.notChecked === 'none' ? [] : b.notChecked.map((r) => `line ${b.line}: "${r}" \u2014 no sheet check covers it`)));
121
+ }
122
+
123
+ /** @param {any} arbiter @returns {string[]} the roles of the signed sources that are a CSV file (the sheets a check reads) */
124
+ export function csvRolesOf(arbiter) {
125
+ return (Array.isArray(arbiter?.sources) ? arbiter.sources : [])
126
+ .filter((/** @type {any} */ s) => isRec(s) && s.kind !== 'page' && typeof s.path === 'string' && s.path.toLowerCase().endsWith('.csv') && typeof s.role === 'string')
127
+ .map((/** @type {any} */ s) => s.role);
128
+ }
129
+
130
+ /** one value of a claim in the words of a line: text as it is, anything else as JSON */
131
+ const claimShow = (/** @type {unknown} */ v) => (typeof v === 'string' ? v : JSON.stringify(v));
132
+
133
+ /**
134
+ * M10b am4: the step's answer (its claim boxes) value by value, one line each: `invoiceCount: 8`, `daysPastDue: row 2 -> 124`. A list is one line per entry (a list of row
135
+ * numbers reads `row N`); a map is one line per key (`row <key> -> <value>`). An empty list or map reads `<name>: none`, never no line.
136
+ * Throws away: nothing but the box's own key (`value`, `rows`, `days`...), which the line's words already say.
137
+ * @param {unknown} claims the step's answer @returns {string[]}
138
+ */
139
+ export function claimLines(claims) {
140
+ const out = [];
141
+ if (!isRec(claims)) return out;
142
+ for (const [name, box] of Object.entries(/** @type {Record<string, any>} */ (claims))) {
143
+ if (!isRec(box)) { out.push(`${name}: ${claimShow(box)}`); continue; }
144
+ for (const [key, v] of Object.entries(box)) {
145
+ if (Array.isArray(v)) {
146
+ if (v.length === 0) out.push(`${name}: none`);
147
+ for (const e of v) out.push(`${name}: ${key === 'rows' || key === 'keys' ? 'row ' : ''}${claimShow(e)}`);
148
+ } else if (isRec(v)) {
149
+ if (Object.keys(v).length === 0) out.push(`${name}: none`);
150
+ for (const [k, e] of Object.entries(v)) out.push(`${name}: row ${k} \u2192 ${claimShow(e)}`);
151
+ } else out.push(`${name}: ${claimShow(v)}`);
152
+ }
153
+ }
154
+ return out;
155
+ }
156
+
157
+ /**
158
+ * M10b am4: what an ask card shows for the claim boxes it was given. The step is the sheet step whose saved try (`sheet-checks.json`) holds exactly these claims; its block is
159
+ * the Result tab's own (`sheetLineBlocks`, that try's verdicts), and `answer` is the claims value by value. Null when no saved try matches: the caller then keeps the old line.
160
+ * @param {{claims: unknown, declaration: any, lines: Array<{n: number, rules?: string[], guardrail?: string, rule?: string}>, csvRoles?: string[], record?: any}} o
161
+ * @returns {{block: ReturnType<typeof sheetLineBlocks>[number], answer: string[]}|null}
162
+ */
163
+ export function askSheetCard({ claims, declaration, lines, csvRoles = [], record }) {
164
+ if (!isRec(claims) || !Array.isArray(record?.lines)) return null;
165
+ const same = record.lines.filter((/** @type {any} */ l) => isRec(l) && Number.isInteger(l.try) && Number.isInteger(l.n) && isDeepStrictEqual(l.claims, claims));
166
+ const newest = same.reduce((/** @type {any} */ m, /** @type {any} */ l) => (m === null || l.try >= m.try ? l : m), null);
167
+ if (newest === null) return null;
168
+ const block = sheetLineBlocks({ declaration, lines, csvRoles, record: { lines: [newest] } }).find((b) => b.line === newest.n);
169
+ return block ? { block, answer: claimLines(claims) } : null;
170
+ }