fwdloop 0.6.0 → 0.7.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.
package/src/runner.js CHANGED
@@ -45,7 +45,11 @@ import {
45
45
  } from 'node:path';
46
46
  import { fileURLToPath } from 'node:url';
47
47
 
48
- import { readFlow } from './flow.js';
48
+ import {
49
+ readFlow, resolveRunDir, readFileInside, resolveInside,
50
+ } from './flow.js';
51
+ import { writeAskArchive } from './ask.js';
52
+ import { WIRED_VERBS } from './primitives.js';
49
53
  import { closeByClass } from './closers.js';
50
54
  import { appendAudit, appendHistory } from './books.js';
51
55
 
@@ -261,6 +265,34 @@ function hashFile(path) {
261
265
  return createHash('sha256').update(readFileSync(path)).digest('hex');
262
266
  }
263
267
 
268
+ /**
269
+ * F46 (docs/logs/FINDINGS.md): a step whose declaration grants a verb the
270
+ * catalogue lists but `resolvePrimitives` has no case for (e.g. litectx's
271
+ * `compress`) must refuse the whole run at preflight, naming the step and
272
+ * the verb — never a warning the run continues (and spends) past. Lives
273
+ * here, not in `bin/fwdloop`, so any caller of `runFlow`/`resumeRun`
274
+ * (the CLI, M4's web panel) gets the same refusal for free — one writer,
275
+ * `src/primitives.js`'s own `WIRED_VERBS`, never a second copy of the list.
276
+ * A verb absent from the catalogue entirely is caught earlier, at
277
+ * declaration-validation time (`readFlow`) — by the time a declaration
278
+ * reaches here every granted verb is already catalogue-present, so
279
+ * `WIRED_VERBS` alone is enough to tell "wired" from "not yet".
280
+ *
281
+ * @param {Record<string, any>} declaration - `readFlow`'s own loosely-typed
282
+ * `ReadFlowOk.declaration` shape (src/types.js) — same idiom as every
283
+ * other reader of it in this file (e.g. `declaration.steps` below); only
284
+ * `steps[].{emits,fromLine,primitives}` are actually read here.
285
+ * @returns {{step: {emits: string, fromLine: number}, verb: string}|null}
286
+ */
287
+ function findUnwiredVerbStep(declaration) {
288
+ for (const step of declaration.steps) {
289
+ for (const verb of step.primitives ?? []) {
290
+ if (!WIRED_VERBS.has(verb)) return { step, verb };
291
+ }
292
+ }
293
+ return null;
294
+ }
295
+
264
296
  /** A run dir that already holds `ask.json`/`answer.json` from an earlier run
265
297
  * is a stale-answer hazard — refuse, never silently proceed or delete. */
266
298
  export function checkFreshRunDir(runDir) {
@@ -357,17 +389,64 @@ export function writeArtifact(runDir, id, artifact, { overwrite = false } = {})
357
389
  writeFileSync(target, JSON.stringify(artifact, null, 2));
358
390
  }
359
391
 
360
- /** Reads one artifact back off disk; `undefined` when it was never written
361
- * (mirrors the in-memory map's own "absent" shape for a not-yet-produced
362
- * read). */
392
+ /**
393
+ * F48 round 4 (redesign, docs/logs/FINDINGS.md): the ONE tri-state reader
394
+ * every artifact-reading call site routes through. Round 3's `readArtifact`
395
+ * collapsed THREE outcomes into one `undefined` — "never written" and
396
+ * "read refused" (symlink escape / outside the run dir / unparseable JSON)
397
+ * were indistinguishable to every caller. That single value with two
398
+ * meanings is exactly what let a swapped/deleted accepted artifact reach
399
+ * the send slot as `undefined`, get `?? null`-ed by `src/send.js`, and ship
400
+ * a 4-byte `null` to the signed destination as a recorded "green" send —
401
+ * the refusal `readFileInside` already computes was thrown away one layer
402
+ * up. Every caller below now sees the real shape and decides, explicitly,
403
+ * whether "missing" is fine (a genuinely not-yet-written read) or whether
404
+ * ANY refusal — missing or red — must halt the run.
405
+ * @returns {{ok:true, value:any} | {ok:false, missing:true} | {ok:false, missing:false, red:string}}
406
+ */
407
+ export function readArtifactResult(runDir, id) {
408
+ const result = readFileInside(runDir, `artifacts/${id}.json`);
409
+ if (!result.ok) return result;
410
+ let value;
411
+ try {
412
+ value = JSON.parse(result.text);
413
+ } catch (err) {
414
+ return { ok: false, missing: false, red: `artifact "${id}" is not valid JSON — ${err.message}` };
415
+ }
416
+ return { ok: true, value };
417
+ }
418
+
419
+ /** Back-compat convenience collapse of `readArtifactResult`: `undefined` for
420
+ * BOTH "never written" and "read refused" — the exact collapse the F48
421
+ * round 4 redesign says a caller must never reach for on its own. Safe to
422
+ * use ONLY where an explicit tri-state check has already refused any `red`
423
+ * for this same id earlier in the same call (documented at each remaining
424
+ * call site) — never add a NEW call site with this function instead of
425
+ * `readArtifactResult`.
426
+ */
363
427
  export function readArtifact(runDir, id) {
364
- const target = artifactPath(runDir, id);
365
- if (!existsSync(target)) return undefined;
366
- return JSON.parse(readFileSync(target, 'utf8'));
428
+ const result = readArtifactResult(runDir, id);
429
+ return result.ok ? result.value : undefined;
367
430
  }
368
431
 
369
- function readArtifactsMap(runDir, ids) {
370
- return Object.fromEntries((ids ?? []).map((id) => [id, readArtifact(runDir, id)]));
432
+ /** `readArtifactResult` for a whole `reads` array. A genuinely-missing read
433
+ * (never written) still renders as `undefined` in the map, unchanged from
434
+ * before — but a REFUSED read (red) is never silently folded in as
435
+ * `undefined` alongside it; the caller gets `{ok:false, red}` instead and
436
+ * must halt rather than feed tampered/unreadable content (or a `undefined`
437
+ * indistinguishable from "not written yet") into a step.
438
+ * @returns {{ok:true, map:Record<string,any>} | {ok:false, red:string}}
439
+ */
440
+ function readArtifactsMapChecked(runDir, ids) {
441
+ const map = {};
442
+ for (const id of ids ?? []) {
443
+ const result = readArtifactResult(runDir, id);
444
+ if (!result.ok && !result.missing) {
445
+ return { ok: false, red: `artifact "${id}" — ${result.red}` };
446
+ }
447
+ map[id] = result.ok ? result.value : undefined;
448
+ }
449
+ return { ok: true, map };
371
450
  }
372
451
 
373
452
  // ---------------------------------------------------------------------------
@@ -377,7 +456,7 @@ function readArtifactsMap(runDir, ids) {
377
456
  // nothing.
378
457
  // ---------------------------------------------------------------------------
379
458
 
380
- function recordLateAnswerIfAny(runDir) {
459
+ function recordLateAnswerIfAny(runDir, now = () => new Date().toISOString()) {
381
460
  const file = join(runDir, 'answer.json');
382
461
  if (!existsSync(file)) return;
383
462
  appendAudit(runDir, {
@@ -392,6 +471,9 @@ function recordLateAnswerIfAny(runDir) {
392
471
  model: null,
393
472
  modelMatch: null,
394
473
  strike: false,
474
+ at: now(),
475
+ tokens: null,
476
+ tools: null,
395
477
  kind: 'answer-after-run',
396
478
  file,
397
479
  });
@@ -416,10 +498,29 @@ function sumKnownUsd(...values) {
416
498
  return known.reduce((a, b) => a + b, 0);
417
499
  }
418
500
 
501
+ // Amendment M4a-2 — SIGNED by hamr 2026-09-27 ("sign mfa2", = M4a-2):
502
+ // `at` (this attempt's own finish time, off the run's injected clock — never
503
+ // the bare wall clock, exactly like every other timestamp this module
504
+ // writes) and `tokens` (threaded straight from `modelStep`'s own result,
505
+ // which sums it at the SAME place it sums `costUsd` across a step's rounds
506
+ // — never re-derived here or anywhere else by position from spend.jsonl).
507
+ // `tokens` defaults to `null`: every call site with no model call (cap-halt,
508
+ // paused, ask-timeout, refused, accept, redo-rejected) leaves it at that
509
+ // default; every call site with a `modelStep` result passes its own
510
+ // `result.tokens` through unchanged.
511
+ // M4a-3 (docs/wiki/the-module-ladder.md, "M4a" section, "Amendment M4a-3 —
512
+ // SIGNED by hamr 2026-09-27"): `tools` (a {toolName: count} tally, threaded
513
+ // straight from `modelStep`'s own result — never re-derived here) and
514
+ // `ungranted` (an array of tool names the model called that this step never
515
+ // granted; omitted entirely when empty, per `src/books.js`'s own contract).
516
+ // Both default the same way `tokens` does: every call site with no model
517
+ // call leaves `tools` at its `null` default; every call site with a
518
+ // `modelStep` result passes `result.tools`/`result.ungranted` through
519
+ // unchanged.
419
520
  function makeAuditRow({
420
- step, attempt, verdict, gap, usd, spendComplete, wallMs, model = null, modelMatch = null, strike,
521
+ step, attempt, verdict, gap, usd, spendComplete, wallMs, model = null, modelMatch = null, strike, at, tokens = null, tools = null, ungranted = /** @type {string[]|undefined} */ (undefined), refused = /** @type {Array<{verb:string,path:string,rule:string}>} */ ([]),
421
522
  }) {
422
- return {
523
+ const row = {
423
524
  step: step?.emits ?? step?.goal ?? null,
424
525
  attempt,
425
526
  class: step?.close?.class ?? null,
@@ -431,7 +532,13 @@ function makeAuditRow({
431
532
  model: model ?? null,
432
533
  modelMatch: modelMatch ?? null,
433
534
  strike: !!strike,
535
+ at,
536
+ tokens,
537
+ tools,
538
+ refused,
434
539
  };
540
+ if (ungranted !== undefined && ungranted.length > 0) row.ungranted = ungranted;
541
+ return row;
435
542
  }
436
543
 
437
544
  /**
@@ -453,10 +560,18 @@ function makeAuditRow({
453
560
  * @param {(row: any, modelOutput?: any) => void} opts.recordAudit
454
561
  * @param {string|null} [opts.initialGap]
455
562
  * @param {number} [opts.attemptOffset]
563
+ * @param {() => string} [opts.now] - M4a-2: stamps each audit row's `at`;
564
+ * defaults to the real wall clock.
456
565
  * @returns {Promise<{ok:true, artifact:any, attempts:number, hitl?:boolean} | {ok:false, outcome:string, red:string}>}
457
566
  */
458
567
  async function runStepRalph({
459
568
  step, primitivesMap, readsMap, businessDate, modelStep, spent, capUsd, ceilingUsd, recordAudit, initialGap = null, attemptOffset = 0,
569
+ // M4a-2: the run's own injected clock (never the bare wall clock) —
570
+ // stamps every audit row's `at` with this attempt's finish time. Defaults
571
+ // to the real wall clock so a caller that doesn't inject one (there are
572
+ // none left in production; a defensive default only) still writes a valid
573
+ // ISO string.
574
+ now = () => new Date().toISOString(),
460
575
  }) {
461
576
  /** @type {string|null} */
462
577
  let gap = initialGap ?? null;
@@ -472,7 +587,7 @@ async function runStepRalph({
472
587
  let attemptFloorUsd = null;
473
588
  if (spent.value + ceilingUsd > capUsd) {
474
589
  recordAudit(makeAuditRow({
475
- step, attempt, verdict: 'cap-halt', gap, usd: null, spendComplete: false, wallMs: 0, strike: false,
590
+ step, attempt, verdict: 'cap-halt', gap, usd: null, spendComplete: false, wallMs: 0, strike: false, at: now(),
476
591
  }));
477
592
  return {
478
593
  ok: false,
@@ -522,7 +637,7 @@ async function runStepRalph({
522
637
  // null second cost never zeroes out a known first floor.
523
638
  const usd = sumKnownUsd(attemptFloorUsd, result.costUsd);
524
639
  recordAudit(makeAuditRow({
525
- step, attempt, verdict: 'provider-red', gap, usd, spendComplete: false, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false,
640
+ step, attempt, verdict: 'provider-red', gap, usd, spendComplete: false, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false, at: now(), tokens: result.tokens ?? null, tools: result.tools ?? null, ungranted: result.ungranted, refused: result.refused,
526
641
  }), result.red ?? 'transport fault twice');
527
642
  return { ok: false, outcome: 'provider-red', red: `provider-red: step "${step.goal}" attempt ${attempt}: ${result.red ?? 'transport fault twice'}` };
528
643
  }
@@ -539,7 +654,7 @@ async function runStepRalph({
539
654
  if (strike) strikes += 1;
540
655
  const usd = sumKnownUsd(attemptFloorUsd, result?.costUsd);
541
656
  recordAudit(makeAuditRow({
542
- step, attempt, verdict: 'red', gap: red, usd, spendComplete: usd !== null, wallMs, model: result?.model, modelMatch: result?.modelMatch, strike,
657
+ step, attempt, verdict: 'red', gap: red, usd, spendComplete: usd !== null, wallMs, model: result?.model, modelMatch: result?.modelMatch, strike, at: now(), tokens: result?.tokens ?? null, tools: result?.tools ?? null, ungranted: result?.ungranted, refused: result?.refused,
543
658
  }), red);
544
659
  if (n === MAX_ATTEMPTS) return { ok: false, outcome: 'attempt-fallback', red: `attempt-fallback: step "${step.goal}" — ${red}` };
545
660
  if (strikes >= STRIKE_LIMIT) return { ok: false, outcome: 'struck-out', red: `struck-out: step "${step.goal}" — ${red}` };
@@ -550,7 +665,7 @@ async function runStepRalph({
550
665
 
551
666
  if (result.costUsd === null || result.costUsd === undefined) {
552
667
  recordAudit(makeAuditRow({
553
- step, attempt, verdict: 'pricing-red', gap, usd: attemptFloorUsd, spendComplete: false, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false,
668
+ step, attempt, verdict: 'pricing-red', gap, usd: attemptFloorUsd, spendComplete: false, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false, at: now(), tokens: result.tokens ?? null, tools: result.tools ?? null, ungranted: result.ungranted, refused: result.refused,
554
669
  }), result.artifact ?? null);
555
670
  return { ok: false, outcome: 'pricing-red', red: `pricing-red: step "${step.goal}" attempt ${attempt} returned no cost (never "?? 0")` };
556
671
  }
@@ -565,7 +680,7 @@ async function runStepRalph({
565
680
  const doneCheck = checkDoneBlocker(step, result.artifact);
566
681
  if (doneCheck.verdict === 'not-done') {
567
682
  recordAudit(makeAuditRow({
568
- step, attempt, verdict: 'not-done', gap: doneCheck.red, usd: attemptUsd, spendComplete: true, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false,
683
+ step, attempt, verdict: 'not-done', gap: doneCheck.red, usd: attemptUsd, spendComplete: true, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false, at: now(), tokens: result.tokens ?? null, tools: result.tools ?? null, ungranted: result.ungranted, refused: result.refused,
569
684
  }), result.artifact ?? null);
570
685
  return { ok: false, outcome: 'not-done', red: doneCheck.red };
571
686
  }
@@ -578,7 +693,7 @@ async function runStepRalph({
578
693
  // failure) — matches poc/m2/gapback.mjs's own rule exactly.
579
694
  strikes += 1;
580
695
  recordAudit(makeAuditRow({
581
- step, attempt, verdict: 'red', gap: happened.red, usd: attemptUsd, spendComplete: true, wallMs, model: result.model, modelMatch: result.modelMatch, strike: true,
696
+ step, attempt, verdict: 'red', gap: happened.red, usd: attemptUsd, spendComplete: true, wallMs, model: result.model, modelMatch: result.modelMatch, strike: true, at: now(), tokens: result.tokens ?? null, tools: result.tools ?? null, ungranted: result.ungranted, refused: result.refused,
582
697
  }), result.artifact ?? null);
583
698
  if (n === MAX_ATTEMPTS) return { ok: false, outcome: 'attempt-fallback', red: `attempt-fallback: ${happened.red}` };
584
699
  if (strikes >= STRIKE_LIMIT) return { ok: false, outcome: 'struck-out', red: `struck-out: ${happened.red}` };
@@ -591,7 +706,7 @@ async function runStepRalph({
591
706
 
592
707
  if (closed.verdict === 'green' || closed.verdict === 'hitl') {
593
708
  recordAudit(makeAuditRow({
594
- step, attempt, verdict: closed.verdict, gap: null, usd: attemptUsd, spendComplete: true, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false,
709
+ step, attempt, verdict: closed.verdict, gap: null, usd: attemptUsd, spendComplete: true, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false, at: now(), tokens: result.tokens ?? null, tools: result.tools ?? null, ungranted: result.ungranted, refused: result.refused,
595
710
  }), result.artifact);
596
711
  return {
597
712
  ok: true, artifact, attempts: attempt, hitl: closed.verdict === 'hitl',
@@ -602,7 +717,7 @@ async function runStepRalph({
602
717
  // A closer that renders no judgment ('unparseable'/'crash') is a
603
718
  // CASUALTY, never a red and never a strike (bareloop F17).
604
719
  recordAudit(makeAuditRow({
605
- step, attempt, verdict: 'close-casualty', gap: closed.red, usd: attemptUsd, spendComplete: true, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false,
720
+ step, attempt, verdict: 'close-casualty', gap: closed.red, usd: attemptUsd, spendComplete: true, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false, at: now(), tokens: result.tokens ?? null, tools: result.tools ?? null, ungranted: result.ungranted, refused: result.refused,
606
721
  }), result.artifact);
607
722
  return { ok: false, outcome: 'close-casualty', red: `close-casualty: step "${step.goal}" — ${closed.red} (${closed.verdict})` };
608
723
  }
@@ -612,7 +727,7 @@ async function runStepRalph({
612
727
  seenGaps.add(normalised);
613
728
  if (strike) strikes += 1;
614
729
  recordAudit(makeAuditRow({
615
- step, attempt, verdict: 'red', gap: closed.red, usd: attemptUsd, spendComplete: true, wallMs, model: result.model, modelMatch: result.modelMatch, strike,
730
+ step, attempt, verdict: 'red', gap: closed.red, usd: attemptUsd, spendComplete: true, wallMs, model: result.model, modelMatch: result.modelMatch, strike, at: now(), tokens: result.tokens ?? null, tools: result.tools ?? null, ungranted: result.ungranted, refused: result.refused,
616
731
  }), result.artifact);
617
732
 
618
733
  if (n === MAX_ATTEMPTS) return { ok: false, outcome: 'attempt-fallback', red: `attempt-fallback: step "${step.goal}" — ${closed.red}` };
@@ -638,6 +753,7 @@ async function runStepRalph({
638
753
  * @param {(opts:{question:string, evidence:unknown, runDir:string}) => Promise<{decision:'accept'|'reject'|'rerun'|'timeout'|'park', reason?:string}>} opts.askStep
639
754
  * @param {(target:string, filename:string, content:unknown) => Promise<{ok:boolean, red?:string, bytes?:number}>} opts.sendStep
640
755
  * @param {Record<string, any>} [opts.primitives] - injected primitive implementations, keyed by catalogue verb.
756
+ * @param {string[]} [opts.primitiveReds] - `resolvePrimitives`'s own `reds` (e.g. bareguard refusing a symlinked file scope); any entry refuses the run at $0 like an unwired verb, before the run dir exists.
641
757
  * @param {() => string} [opts.clock] - returns the current ISO timestamp; defaults to the wall clock.
642
758
  * @param {string} opts.businessDate - the run's explicit "as of today", never the wall clock.
643
759
  * @param {number} [opts.ceilingUsd] - per-attempt ceiling override; defaults to `resolveCeilingUsd(null)`.
@@ -650,7 +766,7 @@ async function runStepRalph({
650
766
  * can advance wall time across a park/resume boundary without a real wait.
651
767
  */
652
768
  export async function runFlow({
653
- root, name, runId, sources, catalogue, modelStep, askStep, sendStep, primitives, clock, businessDate, ceilingUsd, initialGap,
769
+ root, name, runId, sources, catalogue, modelStep, askStep, sendStep, primitives, primitiveReds, clock, businessDate, ceilingUsd, initialGap,
654
770
  // F45 finding 3's test needs to advance wall time across a park/resume
655
771
  // boundary without a real wait, exactly like `clock` already does for ISO
656
772
  // timestamps — `nowMs` is the same idea for epoch-ms wall-clock reads.
@@ -663,6 +779,19 @@ export async function runFlow({
663
779
  const flowDir = join(root, name);
664
780
  const startedAt = getNowMs();
665
781
 
782
+ // Defense in depth alongside `bin/fwdloop`'s own `resolveRunDir` check on
783
+ // `--run-id`: a caller-supplied runId that would escape `flowDir/runs/`
784
+ // (`..`, a `/`/`\` segment, ...) is refused by name, at $0, before any
785
+ // directory for this run is even looked at, let alone created.
786
+ const runIdCheck = resolveRunDir(flowDir, runId);
787
+ if (!runIdCheck.ok) {
788
+ mkdirSync(flowDir, { recursive: true });
789
+ appendHistory(flowDir, {
790
+ runId, at: now(), outcome: 'refused', spentUsd: 0, spendComplete: true, capUsd: null, wallMs: Date.now() - startedAt, signatureHash: null,
791
+ });
792
+ return { outcome: 'refused', red: runIdCheck.red };
793
+ }
794
+
666
795
  const read = readFlow({ root, name, catalogue });
667
796
  if (!read.ok) {
668
797
  // Negative iv: a flow whose files don't hash to the signature (or is
@@ -685,7 +814,30 @@ export async function runFlow({
685
814
  const askLines = new Map((arbiter.asks ?? []).map((a) => [a.line, a]));
686
815
  const sendLines = new Map((arbiter.sends ?? []).map((s) => [s.line, s]));
687
816
 
688
- const runDir = join(flowDir, 'runs', runId);
817
+ const runDir = runIdCheck.runDir;
818
+
819
+ const unwiredVerb = findUnwiredVerbStep(declaration);
820
+ if (unwiredVerb) {
821
+ return haltRun({
822
+ flowDir,
823
+ runDir,
824
+ runId,
825
+ capUsd,
826
+ startedAt,
827
+ now,
828
+ nowMs: getNowMs,
829
+ signatureHash: signature.flow,
830
+ outcome: 'preflight-red',
831
+ red: `preflight: step "${unwiredVerb.step.emits}" (line ${unwiredVerb.step.fromLine}) grants verb "${unwiredVerb.verb}", which has no wired implementation`,
832
+ spent: { value: 0 },
833
+ });
834
+ }
835
+
836
+ if (primitiveReds?.length) {
837
+ return haltRun({
838
+ flowDir, runDir, runId, capUsd, startedAt, now, nowMs: getNowMs, signatureHash: signature.flow, outcome: 'preflight-red', red: primitiveReds[0], spent: { value: 0 },
839
+ });
840
+ }
689
841
 
690
842
  const fresh = checkFreshRunDir(runDir);
691
843
  if (!fresh.ok) {
@@ -727,7 +879,7 @@ export async function runFlow({
727
879
  if (row.spendComplete === false) spendComplete.value = false;
728
880
  if (modelOutput !== undefined) {
729
881
  attemptsLog.push({
730
- step: row.step, attempt: row.attempt, class: row.class, verdict: row.verdict, gap: row.gap, modelOutput,
882
+ step: row.step, attempt: row.attempt, class: row.class, verdict: row.verdict, gap: row.gap, ...(row.refused ? { refused: row.refused } : {}), modelOutput,
731
883
  });
732
884
  }
733
885
  };
@@ -893,6 +1045,23 @@ async function runAskSlot({
893
1045
  writeFileSync(join(runDir, 'ask.json'), JSON.stringify({
894
1046
  askId, question: askSlot?.question ?? step.goal, askedAt, expiresAt, evidence,
895
1047
  }, null, 2));
1048
+ // Amendment M4a-1 — SIGNED by hamr 2026-09-27 ("sign m4a1"): a
1049
+ // PERMANENT copy of this same park, `asks/<askId>.json`, written right
1050
+ // after `ask.json` (never before) — `ask.json`/`state.json` below are
1051
+ // what governs resume, unchanged; the archive is a second, append-only
1052
+ // record of the SAME content. Crash between the two writes leaves
1053
+ // `ask.json` present and no archive entry for this one askId — the run
1054
+ // is still correctly parked and resumable; `listArchivedAsks` only
1055
+ // ever reports what's actually on disk, never invents an entry. A
1056
+ // fresh `askId` per park means a red here (an already-archived askId)
1057
+ // is a genuine invariant violation, not a race to recover from — it
1058
+ // halts the run rather than silently dropping the archive duty.
1059
+ const archived = writeAskArchive({
1060
+ runDir, askId, question: askSlot?.question ?? step.goal, askedAt, expiresAt, evidence,
1061
+ });
1062
+ if (!archived.ok) {
1063
+ throw new Error(archived.red);
1064
+ }
896
1065
  // M3 scope item 2: the minimum the fold needs to resume identically —
897
1066
  // WHERE (stepIndex), WHAT was frozen/signed (signatureHash,
898
1067
  // inputsManifest, to be re-verified before anything runs), WHAT this
@@ -927,7 +1096,7 @@ async function runAskSlot({
927
1096
  };
928
1097
  writeFileSync(join(runDir, 'state.json'), JSON.stringify(state, null, 2));
929
1098
  recordAudit(makeAuditRow({
930
- step, attempt: redone + 1, verdict: 'paused', gap: null, usd: 0, spendComplete: true, wallMs: 0, strike: false,
1099
+ step, attempt: redone + 1, verdict: 'paused', gap: null, usd: 0, spendComplete: true, wallMs: 0, strike: false, at: now(),
931
1100
  }), undefined, unjudgedCount);
932
1101
  // Orchestrator review fix (3): M2 item 9 says history is ONE row per
933
1102
  // run; M3's signed scope item 2 only asks for an AUDIT row "paused"
@@ -948,7 +1117,7 @@ async function runAskSlot({
948
1117
  // A pause spends nothing (M2 scope item 6) — a halt, never a red
949
1118
  // with a fabricated cost, and never re-asked (the run is over).
950
1119
  recordAudit(makeAuditRow({
951
- step, attempt: redone + 1, verdict: 'ask-timeout', gap: null, usd: 0, spendComplete: true, wallMs: 0, strike: false,
1120
+ step, attempt: redone + 1, verdict: 'ask-timeout', gap: null, usd: 0, spendComplete: true, wallMs: 0, strike: false, at: now(),
952
1121
  }), undefined, unjudgedCount);
953
1122
  return {
954
1123
  type: 'halted',
@@ -962,7 +1131,7 @@ async function runAskSlot({
962
1131
 
963
1132
  if (isRedo && reason.length === 0) {
964
1133
  recordAudit(makeAuditRow({
965
- step, attempt: redone + 1, verdict: 'refused', gap: 'a rejection/rerun needs a reason', usd: 0, spendComplete: true, wallMs: 0, strike: false,
1134
+ step, attempt: redone + 1, verdict: 'refused', gap: 'a rejection/rerun needs a reason', usd: 0, spendComplete: true, wallMs: 0, strike: false, at: now(),
966
1135
  }), undefined, unjudgedCount);
967
1136
  // Refused, re-asked for the SAME attempt — never re-runs the step.
968
1137
  // eslint-disable-next-line no-continue
@@ -971,7 +1140,7 @@ async function runAskSlot({
971
1140
 
972
1141
  if (answer.decision === 'accept') {
973
1142
  recordAudit(makeAuditRow({
974
- step, attempt: redone + 1, verdict: 'green', gap: null, usd: 0, spendComplete: true, wallMs: 0, strike: false,
1143
+ step, attempt: redone + 1, verdict: 'green', gap: null, usd: 0, spendComplete: true, wallMs: 0, strike: false, at: now(),
975
1144
  }), undefined, unjudgedCount);
976
1145
  return { type: 'accepted', artifact: currentPrior };
977
1146
  }
@@ -979,7 +1148,7 @@ async function runAskSlot({
979
1148
  if (isRedo) {
980
1149
  redone += 1;
981
1150
  recordAudit(makeAuditRow({
982
- step, attempt: redone, verdict: 'red', gap: reason, usd: 0, spendComplete: true, wallMs: 0, strike: false,
1151
+ step, attempt: redone, verdict: 'red', gap: reason, usd: 0, spendComplete: true, wallMs: 0, strike: false, at: now(),
983
1152
  }), undefined, unjudgedCount);
984
1153
  if (redone > redoCap) {
985
1154
  return {
@@ -988,10 +1157,18 @@ async function runAskSlot({
988
1157
  red: `redo cap ${redoCap} reached at step "${step.goal}" after ${redone} rejections`,
989
1158
  };
990
1159
  }
991
- const priorReads = readArtifactsMap(runDir, priorStep.reads);
1160
+ // F48 round 4: every id in `priorStep.reads` names a STILL EARLIER step
1161
+ // that already ran and wrote its artifact — a `red` here (symlink
1162
+ // swap / unparseable JSON) is tampering, never "not written yet", and
1163
+ // must halt the redo rather than silently feed forged/garbage content
1164
+ // into the model step that is about to re-run.
1165
+ const priorReadsResult = readArtifactsMapChecked(runDir, priorStep.reads);
1166
+ if (!priorReadsResult.ok) {
1167
+ return { type: 'halted', outcome: 'red', red: `redo: step "${priorStep.goal}" ${priorReadsResult.red}` };
1168
+ }
992
1169
  // eslint-disable-next-line no-await-in-loop
993
1170
  const redoResult = await runStepRalph({
994
- step: priorStep, primitivesMap: primitives, readsMap: priorReads, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, initialGap: reason, attemptOffset: redone,
1171
+ step: priorStep, primitivesMap: primitives, readsMap: priorReadsResult.map, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, initialGap: reason, attemptOffset: redone, now,
995
1172
  });
996
1173
  if (!redoResult.ok) {
997
1174
  return { type: 'halted', outcome: redoResult.outcome, red: redoResult.red };
@@ -1078,12 +1255,31 @@ async function foldFromStep({
1078
1255
  outcome: 'red', red: `send: step "${step.goal}" reads ask artifact "${askArtifactId}" that was not accepted this run`,
1079
1256
  });
1080
1257
  }
1081
- const content = readArtifact(runDir, askArtifactId);
1258
+ // F48 round 4 (redesign): ONLY an `ok:true` read ships — a missing OR
1259
+ // refused (symlink swap / outside the run dir / unparseable JSON)
1260
+ // accepted artifact halts the run BY NAME, before `sendStep` is ever
1261
+ // called, so nothing reaches the signed destination. This is the exact
1262
+ // gap the round 3 fix left open: `readArtifact` returning `undefined`
1263
+ // for both shapes let a swapped/deleted artifact reach `sendStep` as
1264
+ // `undefined`, get `?? null`-ed by src/send.js, and ship as a
1265
+ // recorded-green `null` — a silent "success" for content that was
1266
+ // never verified.
1267
+ const contentResult = readArtifactResult(runDir, askArtifactId);
1268
+ if (!contentResult.ok) {
1269
+ return haltRun({
1270
+ flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts,
1271
+ outcome: 'red',
1272
+ red: contentResult.missing
1273
+ ? `send: accepted artifact "${askArtifactId}" is missing for step "${step.goal}" — refusing to send`
1274
+ : `send: accepted artifact "${askArtifactId}" for step "${step.goal}" — ${contentResult.red}`,
1275
+ });
1276
+ }
1277
+ const content = contentResult.value;
1082
1278
  const filename = `${runId}-${step.emits}.json`;
1083
1279
  // eslint-disable-next-line no-await-in-loop
1084
1280
  const sendResult = await sendStep(target, filename, content);
1085
1281
  const sendRow = makeAuditRow({
1086
- step, attempt: 1, verdict: sendResult.ok ? 'green' : 'red', gap: sendResult.ok ? null : sendResult.red, usd: 0, spendComplete: true, wallMs: 0, strike: false,
1282
+ step, attempt: 1, verdict: sendResult.ok ? 'green' : 'red', gap: sendResult.ok ? null : sendResult.red, usd: 0, spendComplete: true, wallMs: 0, strike: false, at: now(),
1087
1283
  });
1088
1284
  recordAudit(sendRow);
1089
1285
  if (!sendResult.ok) {
@@ -1103,7 +1299,21 @@ async function foldFromStep({
1103
1299
  const askSlot = askLines.get(step.fromLine);
1104
1300
  const priorId = (step.reads ?? [])[0];
1105
1301
  const priorStepIndex = steps.findIndex((s) => s.emits === priorId);
1106
- const priorArtifact = readArtifact(runDir, priorId);
1302
+ // F48 round 4: `priorId` names a STILL EARLIER step in this same fold
1303
+ // pass, already run and already written to disk — a `red` here is
1304
+ // tampering (or an outside symlink), never "not written yet", and
1305
+ // must halt before the human is ever shown evidence built from it.
1306
+ const priorArtifactResult = readArtifactResult(runDir, priorId);
1307
+ if (!priorArtifactResult.ok) {
1308
+ return haltRun({
1309
+ flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts,
1310
+ outcome: 'red',
1311
+ red: priorArtifactResult.missing
1312
+ ? `ask: prior artifact "${priorId}" is missing for step "${step.goal}" — refusing`
1313
+ : `ask: prior artifact "${priorId}" for step "${step.goal}" — ${priorArtifactResult.red}`,
1314
+ });
1315
+ }
1316
+ const priorArtifact = priorArtifactResult.value;
1107
1317
 
1108
1318
  // M2 amendment 1 item 2: every hitl artifact carried since the
1109
1319
  // previous ask goes to THIS ask as evidence, alongside the ask step's
@@ -1164,14 +1374,24 @@ async function foldFromStep({
1164
1374
  }
1165
1375
 
1166
1376
  // --- an ordinary step: green / softgreen / a non-ask hitl pass-through. ---
1167
- const readsMap = readArtifactsMap(runDir, step.reads);
1377
+ // F48 round 4: every id in `step.reads` names an earlier step in THIS
1378
+ // same fold pass, already run and already written — a `red` read here
1379
+ // halts rather than silently feeding tampered/unreadable content in.
1380
+ const readsMapResult = readArtifactsMapChecked(runDir, step.reads);
1381
+ if (!readsMapResult.ok) {
1382
+ return haltRun({
1383
+ flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts,
1384
+ outcome: 'red', red: `step "${step.goal}" ${readsMapResult.red}`,
1385
+ });
1386
+ }
1387
+ const readsMap = readsMapResult.map;
1168
1388
  // M3 scope item 7: a fresh rerun's own first step (and only that one —
1169
1389
  // `i === i0` is this fold's own starting point, never any later step)
1170
1390
  // starts with the human's rerun reason as its gap, exactly like a
1171
1391
  // redo's `initialGap` above.
1172
1392
  // eslint-disable-next-line no-await-in-loop
1173
1393
  const stepResult = await runStepRalph({
1174
- step, primitivesMap: primitives, readsMap, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, initialGap: i === i0 ? firstStepGap : null,
1394
+ step, primitivesMap: primitives, readsMap, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, initialGap: i === i0 ? firstStepGap : null, now,
1175
1395
  });
1176
1396
  if (!stepResult.ok) {
1177
1397
  return haltRun({
@@ -1198,7 +1418,7 @@ async function foldFromStep({
1198
1418
  appendHistory(flowDir, {
1199
1419
  runId, at: now(), outcome: 'complete', spentUsd: spent.value, spendComplete: spendComplete.value, capUsd, wallMs, signatureHash,
1200
1420
  });
1201
- recordLateAnswerIfAny(runDir);
1421
+ recordLateAnswerIfAny(runDir, now);
1202
1422
  writeLog(runDir, {
1203
1423
  runId, outcome: 'complete', attempts: attemptsLog, artifacts,
1204
1424
  });
@@ -1221,9 +1441,13 @@ async function foldFromStep({
1221
1441
  * @returns {{ ok: true, total: number } | { ok: false, red: string }}
1222
1442
  */
1223
1443
  function sumAuditUsd(runDir) {
1224
- const auditPath = join(runDir, 'audit.jsonl');
1225
- if (!existsSync(auditPath)) return { ok: true, total: 0 };
1226
- const lines = readFileSync(auditPath, 'utf8').split('\n').filter((line) => line.trim().length > 0);
1444
+ // F48 round 3: goes through `readFileInside` (`src/flow.js`) rather than a
1445
+ // raw `readFileSync` — a symlinked `audit.jsonl` (or a symlinked ancestor
1446
+ // directory) reads as "missing" (total 0), never as some outside file's
1447
+ // content summed into a cap check.
1448
+ const result = readFileInside(runDir, 'audit.jsonl');
1449
+ if (!result.ok) return { ok: true, total: 0 };
1450
+ const lines = result.text.split('\n').filter((line) => line.trim().length > 0);
1227
1451
  let total = 0;
1228
1452
  for (const line of lines) {
1229
1453
  let row;
@@ -1257,13 +1481,14 @@ function sumAuditUsd(runDir) {
1257
1481
  * @param {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class:string|null}) => Promise<any>} opts.modelStep
1258
1482
  * @param {(target:string, filename:string, content:unknown) => Promise<{ok:boolean, red?:string, bytes?:number}>} opts.sendStep
1259
1483
  * @param {Record<string, any>} [opts.primitives]
1484
+ * @param {string[]} [opts.primitiveReds] - see `runFlow`'s own.
1260
1485
  * @param {() => string} [opts.clock]
1261
1486
  * @param {string} opts.businessDate
1262
1487
  * @param {number} [opts.ceilingUsd]
1263
1488
  * @param {() => number} [opts.nowMs] - F45 finding 3; see `runFlow`'s own.
1264
1489
  */
1265
1490
  export async function resumeRun({
1266
- root, name, runId, catalogue, modelStep, sendStep, primitives, clock, businessDate, ceilingUsd,
1491
+ root, name, runId, catalogue, modelStep, sendStep, primitives, primitiveReds, clock, businessDate, ceilingUsd,
1267
1492
  // F45 finding 3 (see `runFlow`'s own `nowMs`): additive, defaults to the
1268
1493
  // real `Date.now` for every existing caller.
1269
1494
  nowMs,
@@ -1271,8 +1496,37 @@ export async function resumeRun({
1271
1496
  const now = typeof clock === 'function' ? clock : () => new Date().toISOString();
1272
1497
  const getNowMs = typeof nowMs === 'function' ? nowMs : Date.now;
1273
1498
  const flowDir = join(root, name);
1274
- const runDir = join(flowDir, 'runs', runId);
1275
1499
  const startedAt = getNowMs();
1500
+
1501
+ // Defense in depth alongside `bin/fwdloop`'s own `resolveRunDir` check on
1502
+ // the resume verb's runId positional — refused by name, at $0, before the
1503
+ // resume lock file (or anything else) is even looked at.
1504
+ const runIdCheck = resolveRunDir(flowDir, runId);
1505
+ if (!runIdCheck.ok) {
1506
+ return { outcome: 'refused', red: runIdCheck.red };
1507
+ }
1508
+ const runDir = runIdCheck.runDir;
1509
+
1510
+ // F46: same refusal `runFlow` carries, moved here so a resume can't spend
1511
+ // against a step whose granted verb has no wired implementation either —
1512
+ // checked before the resume lock (or anything else under `runDir`) is
1513
+ // touched. A separate, lightweight `readFlow` from the definitive one
1514
+ // below (inside the lock): if this pre-read itself fails, that failure is
1515
+ // reported properly by the definitive read further down, under the lock,
1516
+ // exactly as before this check existed.
1517
+ const preflightRead = readFlow({ root, name, catalogue });
1518
+ if (preflightRead.ok) {
1519
+ const unwiredVerb = findUnwiredVerbStep(preflightRead.declaration);
1520
+ if (unwiredVerb) {
1521
+ return {
1522
+ outcome: 'refused',
1523
+ red: `preflight: step "${unwiredVerb.step.emits}" (line ${unwiredVerb.step.fromLine}) grants verb "${unwiredVerb.verb}", which has no wired implementation`,
1524
+ };
1525
+ }
1526
+ }
1527
+
1528
+ if (primitiveReds?.length) return { outcome: 'refused', red: primitiveReds[0] };
1529
+
1276
1530
  const lockPath = join(runDir, 'resume.lock');
1277
1531
 
1278
1532
  let lockFd;
@@ -1287,12 +1541,21 @@ export async function resumeRun({
1287
1541
 
1288
1542
  try {
1289
1543
  const statePath = join(runDir, 'state.json');
1290
- if (!existsSync(statePath)) {
1291
- return { outcome: 'refused', red: `resume: no parked state for run "${runId}" (${statePath})` };
1544
+ // F48 round 3 follow-up: goes through `readFileInside` (`src/flow.js`)
1545
+ // rather than a raw `readFileSync` — a symlinked state.json (or a
1546
+ // symlinked run dir ancestor) is refused by name here, never read
1547
+ // through to an outside file's content (the same class `answer.json`
1548
+ // and `audit.jsonl` above already close).
1549
+ const stateResult = readFileInside(runDir, 'state.json');
1550
+ if (!stateResult.ok) {
1551
+ if (stateResult.missing) {
1552
+ return { outcome: 'refused', red: `resume: no parked state for run "${runId}" (${statePath})` };
1553
+ }
1554
+ return { outcome: 'refused', red: `resume: state.json for run "${runId}" — ${stateResult.red}` };
1292
1555
  }
1293
1556
  let state;
1294
1557
  try {
1295
- state = JSON.parse(readFileSync(statePath, 'utf8'));
1558
+ state = JSON.parse(stateResult.text);
1296
1559
  } catch (err) {
1297
1560
  return { outcome: 'refused', red: `resume: state.json for run "${runId}" is not valid JSON — ${err.message}` };
1298
1561
  }
@@ -1338,10 +1601,26 @@ export async function resumeRun({
1338
1601
  }
1339
1602
  }
1340
1603
 
1604
+ // F48 round 4 (redesign): the "was this step already done" gate — the
1605
+ // one place a resume decides whether an earlier step's artifact is
1606
+ // trustworthy BEFORE the answer is consumed or anything downstream reads
1607
+ // it again (site 6/7/8 below all read the SAME ids, for i < stepIndex,
1608
+ // and rely on this gate having already refused any red for them). A
1609
+ // `red` (symlink swap / unparseable JSON) is refused BY NAME, exactly
1610
+ // like `missing` — never silently treated as "not done yet" and redone,
1611
+ // which could spend money or re-ask a human for a step that already
1612
+ // completed.
1341
1613
  const { steps } = declaration;
1342
1614
  for (let i = 0; i < state.stepIndex; i += 1) {
1343
- if (readArtifact(runDir, steps[i].emits) === undefined) {
1344
- return { outcome: 'refused', red: `resume: artifact "${steps[i].emits}" missing for run "${runId}" — cannot resume` };
1615
+ const artifactResult = readArtifactResult(runDir, steps[i].emits);
1616
+ if (!artifactResult.ok) {
1617
+ return {
1618
+ outcome: 'refused',
1619
+ red: artifactResult.missing
1620
+ ? `resume: artifact "${steps[i].emits}" missing for run "${runId}" — cannot resume`
1621
+ : `resume: artifact "${steps[i].emits}" for run "${runId}" — ${artifactResult.red} — `
1622
+ + 'refusing rather than treating a refused read as "not done" and re-running it',
1623
+ };
1345
1624
  }
1346
1625
  }
1347
1626
 
@@ -1403,8 +1682,16 @@ export async function resumeRun({
1403
1682
  }
1404
1683
 
1405
1684
  const answerPath = join(runDir, 'answer.json');
1406
- if (!existsSync(answerPath)) {
1407
- return { outcome: 'refused', red: `resume: no answer yet for run "${runId}"` };
1685
+ // F48 round 3: `answer.json` goes through `resolveInside` too — a
1686
+ // symlinked answer file (or a symlinked run dir ancestor) is refused by
1687
+ // name here, the same as "no answer yet", never read through to an
1688
+ // outside file's content.
1689
+ const answerResolved = resolveInside(runDir, 'answer.json');
1690
+ if (!answerResolved.ok) {
1691
+ if (answerResolved.missing) {
1692
+ return { outcome: 'refused', red: `resume: no answer yet for run "${runId}"` };
1693
+ }
1694
+ return { outcome: 'refused', red: `resume: answer.json for run "${runId}" — ${answerResolved.red}` };
1408
1695
  }
1409
1696
  let answer;
1410
1697
  try {
@@ -1432,7 +1719,7 @@ export async function resumeRun({
1432
1719
  // review fix 2: "a pause spends nothing" means the pause adds
1433
1720
  // nothing, not that the run's total resets).
1434
1721
  appendAudit(runDir, {
1435
- step: null, attempt: null, class: null, verdict: 'ask-expired', gap: null, usd: 0, spendComplete: true, wallMs: 0, model: null, modelMatch: null, strike: false,
1722
+ step: null, attempt: null, class: null, verdict: 'ask-expired', gap: null, usd: 0, spendComplete: true, wallMs: 0, model: null, modelMatch: null, strike: false, at: now(), tokens: null, tools: null,
1436
1723
  });
1437
1724
  appendHistory(flowDir, {
1438
1725
  runId, at: now(), outcome: 'ask-expired', spentUsd: spent.value, spendComplete: spendComplete.value, capUsd: arbiter.capUsd ?? null, wallMs: getNowMs() - runStartedAt, signatureHash: state.signatureHash,
@@ -1452,6 +1739,11 @@ export async function resumeRun({
1452
1739
  return { outcome: 'refused', red: `resume: rerun answer for run "${runId}" carries a blank reason` };
1453
1740
  }
1454
1741
 
1742
+ // Safe to collapse missing/red to `readArtifact`'s `undefined` here:
1743
+ // the "was this step already done" gate above already refused the
1744
+ // whole resume (before the answer was even consumed) if any
1745
+ // `steps[i].emits` for i < state.stepIndex was red — this loop only
1746
+ // ever runs once every one of those same ids has already read `ok`.
1455
1747
  const priorArtifactsForLog = {};
1456
1748
  for (let i = 0; i < state.stepIndex; i += 1) {
1457
1749
  priorArtifactsForLog[steps[i].emits] = readArtifact(runDir, steps[i].emits);
@@ -1459,7 +1751,7 @@ export async function resumeRun({
1459
1751
  appendHistory(flowDir, {
1460
1752
  runId, at: now(), outcome: 'rerun', spentUsd: spent.value, spendComplete: spendComplete.value, capUsd: arbiter.capUsd ?? null, wallMs: getNowMs() - runStartedAt, signatureHash: state.signatureHash,
1461
1753
  });
1462
- recordLateAnswerIfAny(runDir);
1754
+ recordLateAnswerIfAny(runDir, now);
1463
1755
  writeLog(runDir, { runId, outcome: 'rerun', attempts: [], artifacts: priorArtifactsForLog });
1464
1756
 
1465
1757
  // Deterministic derived id (M3 scope item 7) — refused by name, never
@@ -1509,7 +1801,10 @@ export async function resumeRun({
1509
1801
  }
1510
1802
 
1511
1803
  // Reconstruct the fold's accumulators from disk + state.json — never
1512
- // re-running a step that already went green (M3 scope item 4).
1804
+ // re-running a step that already went green (M3 scope item 4). Every
1805
+ // `readArtifact` call below reads an id already proven `ok` by the "was
1806
+ // this step already done" gate above (i < state.stepIndex, same ids) —
1807
+ // safe to collapse missing/red to `undefined` here for that reason only.
1513
1808
  const artifacts = {};
1514
1809
  for (let i = 0; i < state.stepIndex; i += 1) {
1515
1810
  artifacts[steps[i].emits] = readArtifact(runDir, steps[i].emits);
@@ -1534,7 +1829,7 @@ export async function resumeRun({
1534
1829
  if (row.spendComplete === false) spendComplete.value = false;
1535
1830
  if (modelOutput !== undefined) {
1536
1831
  attemptsLog.push({
1537
- step: row.step, attempt: row.attempt, class: row.class, verdict: row.verdict, gap: row.gap, modelOutput,
1832
+ step: row.step, attempt: row.attempt, class: row.class, verdict: row.verdict, gap: row.gap, ...(row.refused ? { refused: row.refused } : {}), modelOutput,
1538
1833
  });
1539
1834
  }
1540
1835
  };
@@ -1547,6 +1842,9 @@ export async function resumeRun({
1547
1842
  const askSlot = askLines.get(step.fromLine);
1548
1843
  const priorId = (step.reads ?? [])[0];
1549
1844
  const priorStepIndex = steps.findIndex((s) => s.emits === priorId);
1845
+ // `priorId` names a step strictly earlier than the parked ask
1846
+ // (state.stepIndex), so i < state.stepIndex — already proven `ok` by the
1847
+ // "was this step already done" gate above; safe to collapse here.
1550
1848
  const priorArtifact = readArtifact(runDir, priorId);
1551
1849
 
1552
1850
  const oneShotAskStep = makeOneShotThenParkAskStep({ decision: answer.decision, reason: answer.reason });
@@ -1651,6 +1949,47 @@ function writeLog(runDir, payload) {
1651
1949
  writeFileSync(join(runDir, 'log.json'), JSON.stringify(payload, null, 2));
1652
1950
  }
1653
1951
 
1952
+ /**
1953
+ * `writeLog`'s own sibling reader (M4a piece 2, docs/wiki/the-module-
1954
+ * ladder.md M4a scope item 2: "one reader per book") — `null` when the run
1955
+ * hasn't reached an exit path yet (still running, or parked before any
1956
+ * halt/complete), or the file is present but not valid JSON (a torn write),
1957
+ * never a thrown error.
1958
+ * @param {string} runDir
1959
+ * @returns {any|null}
1960
+ */
1961
+ export function readLog(runDir) {
1962
+ const result = readFileInside(runDir, 'log.json');
1963
+ if (!result.ok) return null;
1964
+ try { return JSON.parse(result.text); } catch { return null; }
1965
+ }
1966
+
1967
+ /**
1968
+ * `state.json`'s own sibling reader (same rule as {@link readLog}) — `null`
1969
+ * when the run has never parked, or the file is present but not valid JSON.
1970
+ * @param {string} runDir
1971
+ * @returns {any|null}
1972
+ */
1973
+ export function readRunState(runDir) {
1974
+ const result = readFileInside(runDir, 'state.json');
1975
+ if (!result.ok) return null;
1976
+ try { return JSON.parse(result.text); } catch { return null; }
1977
+ }
1978
+
1979
+ /**
1980
+ * `ask.json`'s own sibling reader (same rule as {@link readLog}) — the
1981
+ * parking ask protocol's own writer lives in {@link runAskSlot} above.
1982
+ * `null` when there is no open ask for this run, or the file is present but
1983
+ * not valid JSON.
1984
+ * @param {string} runDir
1985
+ * @returns {any|null}
1986
+ */
1987
+ export function readAsk(runDir) {
1988
+ const result = readFileInside(runDir, 'ask.json');
1989
+ if (!result.ok) return null;
1990
+ try { return JSON.parse(result.text); } catch { return null; }
1991
+ }
1992
+
1654
1993
  /**
1655
1994
  * @param {object} opts
1656
1995
  * @param {string} opts.flowDir
@@ -1691,7 +2030,7 @@ function haltRun({
1691
2030
  runId, at: now(), outcome, spentUsd: spent.value, spendComplete, capUsd: capUsd ?? null, wallMs, signatureHash,
1692
2031
  });
1693
2032
  if (existsSync(runDir)) {
1694
- recordLateAnswerIfAny(runDir);
2033
+ recordLateAnswerIfAny(runDir, now);
1695
2034
  writeLog(runDir, {
1696
2035
  runId, outcome, red, attempts, artifacts,
1697
2036
  });