fwdloop 0.11.0 → 0.13.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 (62) hide show
  1. package/bin/fwdloop +248 -27
  2. package/package.json +1 -1
  3. package/src/ask.js +3 -0
  4. package/src/authoring.js +103 -13
  5. package/src/books.js +23 -2
  6. package/src/canrun.js +36 -0
  7. package/src/config.js +256 -0
  8. package/src/declaration.js +72 -2
  9. package/src/drafter.js +53 -11
  10. package/src/draftspend.js +70 -0
  11. package/src/flow.js +43 -0
  12. package/src/keysfile.js +180 -0
  13. package/src/liveness.js +1 -1
  14. package/src/model-step.js +43 -8
  15. package/src/monthly.js +276 -0
  16. package/src/panel/author.js +482 -0
  17. package/src/panel/authorcard.js +297 -0
  18. package/src/panel/authorflows.js +312 -0
  19. package/src/panel/authorresume.js +149 -0
  20. package/src/panel/authorstart.js +257 -0
  21. package/src/panel/authorvalues.js +110 -0
  22. package/src/panel/data.js +228 -34
  23. package/src/panel/index.html +2073 -124
  24. package/src/panel/resume.js +14 -11
  25. package/src/panel/server.js +150 -117
  26. package/src/panel/settings.js +270 -0
  27. package/src/panel/spawn.js +77 -0
  28. package/src/provider.js +189 -43
  29. package/src/providershapes.js +19 -0
  30. package/src/runner.js +639 -85
  31. package/src/runvalues.js +178 -0
  32. package/src/send.js +10 -3
  33. package/src/setup.js +120 -0
  34. package/types/authoring.d.ts +24 -2
  35. package/types/books.d.ts +14 -2
  36. package/types/canrun.d.ts +32 -0
  37. package/types/config.d.ts +52 -0
  38. package/types/declaration.d.ts +9 -1
  39. package/types/drafter.d.ts +18 -2
  40. package/types/draftspend.d.ts +21 -0
  41. package/types/flow.d.ts +23 -0
  42. package/types/keysfile.d.ts +90 -0
  43. package/types/liveness.d.ts +2 -2
  44. package/types/model-step.d.ts +6 -2
  45. package/types/monthly.d.ts +130 -0
  46. package/types/panel/author.d.ts +335 -0
  47. package/types/panel/authorcard.d.ts +120 -0
  48. package/types/panel/authorflows.d.ts +175 -0
  49. package/types/panel/authorresume.d.ts +32 -0
  50. package/types/panel/authorstart.d.ts +115 -0
  51. package/types/panel/authorvalues.d.ts +62 -0
  52. package/types/panel/data.d.ts +103 -12
  53. package/types/panel/resume.d.ts +8 -1
  54. package/types/panel/server.d.ts +19 -33
  55. package/types/panel/settings.d.ts +23 -0
  56. package/types/panel/spawn.d.ts +30 -0
  57. package/types/provider.d.ts +123 -70
  58. package/types/providershapes.d.ts +11 -0
  59. package/types/runner.d.ts +120 -5
  60. package/types/runvalues.d.ts +97 -0
  61. package/types/send.d.ts +5 -1
  62. package/types/setup.d.ts +83 -0
package/src/runner.js CHANGED
@@ -41,19 +41,23 @@ import {
41
41
  } from 'node:fs';
42
42
  import { createHash, randomUUID } from 'node:crypto';
43
43
  import {
44
- dirname, extname, join, resolve, sep,
44
+ dirname, extname, isAbsolute, join, resolve, sep,
45
45
  } from 'node:path';
46
46
  import { fileURLToPath } from 'node:url';
47
47
 
48
48
  import {
49
- readFlow, resolveRunDir, readFileInside, resolveInside,
49
+ readFlow, resolveRunDir, readFileInside, readdirInside, resolveInside, FLOW_FILES, PANEL_STARTS_DIR,
50
50
  } from './flow.js';
51
51
  import {
52
- writeAskArchive, readAcceptedHashesByEmits, serializeArtifact, normalizeDecision, answerTiming, effectiveExpiresAt, withReopen,
52
+ writeAskArchive, readAcceptedHashesByEmits, serializeArtifact, normalizeDecision, answerTiming, effectiveExpiresAt, withReopen, setAsideAnswer,
53
53
  } from './ask.js';
54
- import { WIRED_VERBS } from './primitives.js';
54
+ import { findUnwiredVerbStep, unwiredRed } from './canrun.js'; // M4e am7 item 7: the ONE decider (F46 refusal lives there)
55
+ import { configHome, configDoorHome } from './config.js';
55
56
  import { closeByClass } from './closers.js';
56
- import { appendAudit, appendHistory } from './books.js';
57
+ import {
58
+ appendAudit, appendHistory, readAudit, readHistory, endRow, HALT_OUTCOMES,
59
+ } from './books.js';
60
+ import { applyRunValues, pickRunValues } from './runvalues.js';
57
61
  import {
58
62
  readResumeLock, recordPid, writeLockHolder, procStartOf, LOCK_NO_HOLDER,
59
63
  } from './liveness.js';
@@ -80,6 +84,96 @@ export const MAX_ATTEMPTS = 4;
80
84
  * $0.0006+), so nothing a real tamper produces can hide inside it. */
81
85
  export const SPEND_TOLERANCE_USD = 1e-9;
82
86
 
87
+ // ---------------------------------------------------------------------------
88
+ // M4e amendment 4 item 4 (Stop) and the halt record Resume continues from.
89
+ //
90
+ // `stop.request` is written by the panel's Stop door (`requestStop`, its one writer) and read ONLY at the seam at the top of
91
+ // `foldFromStep`'s loop, i.e. after the previous step closed (its artifact written, its audit rows booked): every kind of
92
+ // step (model, a non-ask hitl pass-through, the signed send, an accepted ask) therefore reads it the same way. The reader
93
+ // consumes it (unlink) and the run ends `stopped`. Amendment 13: when the turn leads to an ask (or the run already waits at one) the run
94
+ // stops AT the ask (`stopAtAsk`, the one place; `stopParkedRun` for a waiting run), because a park is not an end; a stop that
95
+ // arrives after the last step closed finds nothing left to stop and the run completes.
96
+ //
97
+ // `halt.json` is the one record a `cap-halt` or `stopped` run leaves for Resume (`continueRun`): where to re-enter (`stepIndex`,
98
+ // the first step whose artifact is not written), what was frozen/signed, and the hitl evidence not yet shown to an ask. Money and
99
+ // the spend-complete floor are NOT in it: the books (audit.jsonl) are the source of truth and `continueRun` re-sums them.
100
+ // Write-once (`wx`); `continueRun` consumes it by rename to `halt.<n>.consumed.json`, so "resumable" = halt.json exists.
101
+ // ---------------------------------------------------------------------------
102
+
103
+ export const STOP_FILE = 'stop.request';
104
+ export const HALT_FILE = 'halt.json';
105
+
106
+ /** The panel's one write of a stop request. `'exists'` = already asked, nothing more to do. @param {string} runDir */
107
+ export function requestStop(runDir) {
108
+ try {
109
+ writeFileSync(join(runDir, STOP_FILE), `${JSON.stringify({ at: new Date().toISOString() })}\n`, { mode: 0o600, flag: 'wx' });
110
+ return 'written';
111
+ } catch (err) {
112
+ if (err.code === 'EEXIST') return 'exists';
113
+ throw err;
114
+ }
115
+ }
116
+
117
+ /** The ONE reader of the stop request: `{at}` (when it was asked; null if unreadable) or `null` when none is pending. @param {string} runDir */
118
+ export function readStopRequest(runDir) {
119
+ const r = readFileInside(runDir, STOP_FILE);
120
+ if (!r.ok) return null;
121
+ try { const at = JSON.parse(r.text)?.at; return { at: typeof at === 'string' ? at : null }; } catch { return { at: null }; }
122
+ }
123
+
124
+ /** Is a stop pending for this run? (read-only) @param {string} runDir */
125
+ export function stopPending(runDir) {
126
+ return readStopRequest(runDir) !== null;
127
+ }
128
+
129
+ /**
130
+ * M4e amendment 7 item 8: the ONE writer of a Stop's audit rows, and the one place a request is cleared — a Stop is never cleared
131
+ * silently. A pending request leaves "stop asked (you) at <time>" and then its outcome: `stop` given = honoured (`verdict:'stopped'`,
132
+ * `stop.where` its words, `stop.book` the cut try's own row fields so the call in flight is booked); otherwise `not honoured: the run
133
+ * ended (<outcome>) first`. No pending request and no `stop` = no rows. The notes cost 0; a booked call's cost rides the `stopped` row.
134
+ *
135
+ * @param {object} o
136
+ * @param {string} o.runDir
137
+ * @param {() => string} o.now
138
+ * @param {string} o.outcome how the run ended (the words of the not-honoured row)
139
+ * Every row names the step it is about (the audit groups by it): the stop's own `step` (the step its words name; null = none, e.g.
140
+ * "stopped before step 1"), else its book's step; with no stop, the step the run ended on (the last row that names one).
141
+ * @param {{where:string, step?:string|null, book?:Record<string, any>}|null} [o.stop]
142
+ */
143
+ function settleStop({
144
+ runDir, now, outcome, stop = null,
145
+ }) {
146
+ const req = readStopRequest(runDir);
147
+ if (!req && !stop) return;
148
+ const lastStep = () => readAudit(runDir).map((r) => r.step).filter((s) => typeof s === 'string' && s.length > 0).pop() ?? null;
149
+ const step = stop ? (stop.step ?? stop.book?.step ?? null) : lastStep();
150
+ const note = {
151
+ step, attempt: null, class: null, usd: 0, spendComplete: true, wallMs: 0, model: null, modelMatch: null, strike: false, tokens: null, tools: null, refused: [],
152
+ };
153
+ appendAudit(runDir, {
154
+ ...note, verdict: 'stop-asked', gap: `stop asked (you) at ${req?.at ?? 'an unrecorded time'}`, at: req?.at ?? now(),
155
+ });
156
+ appendAudit(runDir, stop
157
+ ? {
158
+ ...note, ...stop.book, step, verdict: 'stopped', gap: stop.where, at: now(),
159
+ }
160
+ : {
161
+ ...note, verdict: 'stop-not-honoured', gap: `not honoured: the run ended (${outcome}) first`, at: now(),
162
+ });
163
+ clearStop(runDir);
164
+ }
165
+
166
+ function clearStop(runDir) {
167
+ try { unlinkSync(join(runDir, STOP_FILE)); } catch { /* none pending */ }
168
+ }
169
+
170
+ /** The one reader of halt.json: `{ok:true, halt}`, `{ok:false, missing:true}` (not resumable), or `{ok:false, red}`. @param {string} runDir */
171
+ export function readHaltRecord(runDir) {
172
+ const r = readFileInside(runDir, HALT_FILE);
173
+ if (!r.ok) return r.missing ? { ok: false, missing: true } : { ok: false, red: `halt.json — ${r.red}` };
174
+ try { return { ok: true, halt: JSON.parse(r.text) }; } catch (err) { return { ok: false, red: `halt.json is not valid JSON — ${err.message}` }; }
175
+ }
176
+
83
177
  // ---------------------------------------------------------------------------
84
178
  // Money — piece 2 wires live provider rates; this piece takes a per-attempt
85
179
  // ceiling as injected data, defaulting to a frozen table's highest entry for
@@ -270,34 +364,6 @@ function hashFile(path) {
270
364
  return createHash('sha256').update(readFileSync(path)).digest('hex');
271
365
  }
272
366
 
273
- /**
274
- * F46 (docs/logs/FINDINGS.md): a step whose declaration grants a verb the
275
- * catalogue lists but `resolvePrimitives` has no case for (e.g. litectx's
276
- * `compress`) must refuse the whole run at preflight, naming the step and
277
- * the verb — never a warning the run continues (and spends) past. Lives
278
- * here, not in `bin/fwdloop`, so any caller of `runFlow`/`resumeRun`
279
- * (the CLI, M4's web panel) gets the same refusal for free — one writer,
280
- * `src/primitives.js`'s own `WIRED_VERBS`, never a second copy of the list.
281
- * A verb absent from the catalogue entirely is caught earlier, at
282
- * declaration-validation time (`readFlow`) — by the time a declaration
283
- * reaches here every granted verb is already catalogue-present, so
284
- * `WIRED_VERBS` alone is enough to tell "wired" from "not yet".
285
- *
286
- * @param {Record<string, any>} declaration - `readFlow`'s own loosely-typed
287
- * `ReadFlowOk.declaration` shape (src/types.js) — same idiom as every
288
- * other reader of it in this file (e.g. `declaration.steps` below); only
289
- * `steps[].{emits,fromLine,primitives}` are actually read here.
290
- * @returns {{step: {emits: string, fromLine: number}, verb: string}|null}
291
- */
292
- function findUnwiredVerbStep(declaration) {
293
- for (const step of declaration.steps) {
294
- for (const verb of step.primitives ?? []) {
295
- if (!WIRED_VERBS.has(verb)) return { step, verb };
296
- }
297
- }
298
- return null;
299
- }
300
-
301
367
  /** A run dir that already holds `ask.json`/`answer.json` from an earlier run
302
368
  * is a stale-answer hazard — refuse, never silently proceed or delete. */
303
369
  export function checkFreshRunDir(runDir) {
@@ -332,39 +398,85 @@ export function freezeInputs(runDir, sources) {
332
398
  return { ok: true, manifest };
333
399
  }
334
400
 
335
- /** The send target's directory must resolve (lexically AND after
336
- * realpath — a symlink inside the repo pointing outside it must not pass)
337
- * inside the repo, and be writable. Re-checked at write time, not just at
338
- * preflight (time-of-check vs time-of-use, M0's own fix).
401
+ /** realpath of a path that may not exist (falls back to the lexical resolve). */
402
+ function realOrResolved(p) {
403
+ try { return realpathSync(p); } catch { return resolve(p); }
404
+ }
405
+
406
+ const isInside = (child, base) => child === base || child.startsWith(base + sep);
407
+
408
+ /** The send target's folder (M4e amendment 1, "Destination is any folder").
409
+ * An absolute `file:/abs/path` is that folder, anywhere on the machine. A
410
+ * relative path keeps its M0/M2 meaning: joined onto the install folder and
411
+ * fenced inside it (lexically AND after realpath — a symlink inside the repo
412
+ * pointing outside must not pass). Either way, with `realpathSync` (symlinks
413
+ * followed), the folder must exist, be a folder, be writable, and must NOT be
414
+ * the run's own folder (its records and `inputs/`), the panel/CLI flow root, any flow
415
+ * folder under it (one holding a FLOW_FILES file) or `<root>/.drafts` or `<root>/.starts`, or the fwdloop config folder (holds the keys).
416
+ * Called at sign time and re-called at write time (time-of-check vs
417
+ * time-of-use, M0's own fix) — the one rule for both.
339
418
  * @param {string} target
419
+ * @param {{root?: string, runDir?: string}} [ctx] `root` = the flow root, `runDir` = this run's folder
340
420
  * @returns {{ok:true, dir:string} | {ok:false, red:string}} */
341
- export function checkSendDestination(target) {
421
+ export function checkSendDestination(target, ctx = {}) {
342
422
  const match = /^file:(.+)$/.exec(target ?? '');
343
423
  if (!match) return { ok: false, red: `destination: send target "${target}" is not a "file:<path>" target` };
344
- const dir = join(REPO_ROOT, match[1]);
345
- const resolvedDir = resolve(dir);
346
- const resolvedRoot = resolve(REPO_ROOT);
347
- if (resolvedDir !== resolvedRoot && !resolvedDir.startsWith(resolvedRoot + sep)) {
348
- return { ok: false, red: `destination: send target "${target}" resolves outside the repo (${dir})` };
424
+ const absolute = isAbsolute(match[1]);
425
+ const dir = absolute ? match[1] : join(REPO_ROOT, match[1]);
426
+ if (!absolute) {
427
+ const resolvedDir = resolve(dir);
428
+ const resolvedRoot = resolve(REPO_ROOT);
429
+ if (!isInside(resolvedDir, resolvedRoot)) {
430
+ return { ok: false, red: `destination: send target "${target}" resolves outside the repo (${dir})` };
431
+ }
432
+ try {
433
+ const realDir = realpathSync(dir);
434
+ const realRoot = realpathSync(REPO_ROOT);
435
+ if (!isInside(realDir, realRoot)) {
436
+ return {
437
+ ok: false,
438
+ red: `destination: send target "${target}" is a symlink that resolves outside the repo (${realDir})`,
439
+ };
440
+ }
441
+ } catch {
442
+ // dir doesn't exist — handled by the not-a-folder red below.
443
+ }
349
444
  }
445
+ let realDir;
350
446
  try {
351
- const realDir = realpathSync(dir);
352
- const realRoot = realpathSync(REPO_ROOT);
353
- if (realDir !== realRoot && !realDir.startsWith(realRoot + sep)) {
354
- return {
355
- ok: false,
356
- red: `destination: send target "${target}" is a symlink that resolves outside the repo (${realDir})`,
357
- };
358
- }
447
+ realDir = realpathSync(dir);
448
+ if (!statSync(realDir).isDirectory()) throw new Error('not a directory');
359
449
  } catch {
360
- // dir doesn't exist yet — handled by the accessSync red below.
450
+ return { ok: false, red: `destination: send target "${target}" is not an existing folder (${dir})` };
451
+ }
452
+ const refused = [];
453
+ if (ctx.runDir) refused.push([realOrResolved(ctx.runDir), "the run's own folder (its records and inputs)"]);
454
+ refused.push([realOrResolved(configHome(configDoorHome().home)), 'the fwdloop config folder']);
455
+ if (ctx.root) {
456
+ const realRoot = realOrResolved(ctx.root);
457
+ if (realDir === realRoot) {
458
+ return { ok: false, red: `destination: send target "${target}" is the flow root (${realDir}) — refused` };
459
+ }
460
+ if (isInside(realDir, realRoot)) {
461
+ const child = realDir.slice(realRoot.length + 1).split(sep)[0];
462
+ const childDir = join(realRoot, child);
463
+ // a flow folder = holds any of the flow's own files (the same FLOW_FILES `src/flow.js` writes)
464
+ if (FLOW_FILES.some((f) => existsSync(join(childDir, f)))) refused.push([childDir, 'a flow folder']);
465
+ else if (child === '.drafts') refused.push([childDir, 'the panel drafts folder']);
466
+ else if (child === PANEL_STARTS_DIR) refused.push([childDir, 'the panel starts folder']);
467
+ }
468
+ }
469
+ for (const [base, what] of refused) {
470
+ if (isInside(realDir, base)) {
471
+ return { ok: false, red: `destination: send target "${target}" is ${what} (${realDir}) — refused` };
472
+ }
361
473
  }
362
474
  try {
363
475
  accessSync(dir, fsConstants.W_OK);
364
476
  } catch (err) {
365
477
  return { ok: false, red: `destination: send target directory "${dir}" is not writable (${err.code})` };
366
478
  }
367
- return { ok: true, dir };
479
+ return { ok: true, dir: absolute ? realDir : dir };
368
480
  }
369
481
 
370
482
  // ---------------------------------------------------------------------------
@@ -559,7 +671,7 @@ function makeAuditRow({
559
671
  * @param {Record<string, any>} [opts.primitivesMap]
560
672
  * @param {Record<string, any>} opts.readsMap
561
673
  * @param {string} opts.businessDate
562
- * @param {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class:string|null}) => Promise<any>} opts.modelStep
674
+ * @param {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class:string|null}, seam?:{stopRequested?:() => boolean}) => Promise<any>} opts.modelStep
563
675
  * @param {{ value: number }} opts.spent
564
676
  * @param {number} opts.capUsd
565
677
  * @param {number} opts.ceilingUsd
@@ -568,7 +680,11 @@ function makeAuditRow({
568
680
  * @param {number} [opts.attemptOffset]
569
681
  * @param {() => string} [opts.now] - M4a-2: stamps each audit row's `at`;
570
682
  * defaults to the real wall clock.
571
- * @returns {Promise<{ok:true, artifact:any, attempts:number, hitl?:boolean} | {ok:false, outcome:string, red:string}>}
683
+ * @param {(() => boolean)|null} [opts.readStop] - amendment 7 item 8: the run's stop reader, asked before every try and (via modelStep's seam) every model call
684
+ * @param {number} [opts.stepNo] - this step's 1-based number, for the words of a stop row
685
+ * @param {string|null} [opts.prevStepId] - the id of step stepNo-1 (null for step 1): the step a "stopped after step N-1" row is filed under
686
+ * @param {number} [opts.triesDone] - tries a Stop already closed on this step (they count against its limit)
687
+ * @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}}>}
572
688
  */
573
689
  async function runStepRalph({
574
690
  step, primitivesMap, readsMap, businessDate, modelStep, spent, capUsd, ceilingUsd, recordAudit, initialGap = null, attemptOffset = 0,
@@ -578,14 +694,37 @@ async function runStepRalph({
578
694
  // none left in production; a defensive default only) still writes a valid
579
695
  // ISO string.
580
696
  now = () => new Date().toISOString(),
697
+ // M4e amendment 7 item 8: the Stop seam before every model call. `readStop` is the run's one stop reader (the fold's closure over
698
+ // `readStopRequest`); `stepNo` is this step's 1-based number for the words of the stop row; `triesDone` is the tries a Stop already
699
+ // cut this step short of (their numbering is in `attemptOffset`; a try the Stop cut mid-way is replaced by the new one, never counted
700
+ // against the limit, so Resume always gets at least one new try).
701
+ readStop = null, stepNo = 0, triesDone = 0,
702
+ // the id of step stepNo-1 (null for step 1): a Stop before this step's first call words itself "after step N-1" and is filed under that step
703
+ prevStepId = null,
581
704
  }) {
582
705
  /** @type {string|null} */
583
706
  let gap = initialGap ?? null;
584
707
  let strikes = 0;
585
708
  const seenGaps = new Set();
709
+ const maxN = MAX_ATTEMPTS - triesDone;
710
+ let lastTurns = null;
711
+ const stopWords = (tryNo, turns) => (turns > 0
712
+ ? `stopped after turn ${turns} of try ${tryNo} of step ${stepNo}`
713
+ : (tryNo > 0 ? `stopped after try ${tryNo} of step ${stepNo}` : (stepNo > 1 ? `stopped after step ${stepNo - 1}` : 'stopped before step 1')));
714
+ /** The ralph's return for a Stop: the cut try's own row fields (`book`) ride the one `stopped` row `settleStop` writes.
715
+ * @param {string} where @param {Record<string, any>} [book] @returns {{ok:false, outcome:string, red:string, stop:{where:string, book:Record<string, any>, step:string|null}}} */
716
+ const stopped = (where, book = {}) => ({
717
+ ok: false,
718
+ outcome: 'stopped',
719
+ red: `stopped by you — ${where}`,
720
+ // one value: the words name the step the row is filed under — "after step N-1" (before this step's first call) is N-1's, the rest this step's
721
+ stop: { where, book, step: where === stopWords(0, 0) ? prevStepId : (step?.emits ?? step?.goal ?? null) },
722
+ });
586
723
 
587
- for (let n = 1; n <= MAX_ATTEMPTS; n += 1) {
724
+ for (let n = 1; n <= maxN; n += 1) {
588
725
  const attempt = attemptOffset + n;
726
+ // Between tries: the previous try closed red, no new model call has started — a pending Stop ends the run here.
727
+ if (n > 1 && readStop && readStop()) return stopped(stopWords(attempt - 1, lastTurns ?? 0));
589
728
  // This attempt's known floor from a FIRST transport fault that then
590
729
  // retried — every audit row this attempt still writes must carry this
591
730
  // floor summed with its own cost (F41 books gap: the fault's cost was
@@ -615,9 +754,11 @@ async function runStepRalph({
615
754
  // construction test below proves the context itself stays clean).
616
755
  const stepMeta = Object.freeze({ class: step.close?.class ?? null });
617
756
 
757
+ const stopSeam = readStop ? Object.freeze({ stopRequested: readStop }) : undefined;
758
+
618
759
  const startedAt = Date.now();
619
760
  // eslint-disable-next-line no-await-in-loop
620
- let result = await modelStep(executorContext, grantedTools, stepMeta);
761
+ let result = await modelStep(executorContext, grantedTools, stepMeta, stopSeam);
621
762
  if (result && result.ok === false && result.transport === true) {
622
763
  // A known partial cost from the FIRST transport fault must survive as
623
764
  // the floor even though this attempt goes on to retry — never
@@ -633,7 +774,7 @@ async function runStepRalph({
633
774
  // `transport: true` shape, exactly once.
634
775
  const first = result;
635
776
  // eslint-disable-next-line no-await-in-loop
636
- result = await modelStep(executorContext, grantedTools, stepMeta);
777
+ result = await modelStep(executorContext, grantedTools, stepMeta, stopSeam);
637
778
  // The first call's gate refusals and tool tally belong to this attempt's
638
779
  // audit row too (the retry's collector starts empty). Only refused /
639
780
  // tools / ungranted are merged — cost is never touched here.
@@ -647,6 +788,19 @@ async function runStepRalph({
647
788
  }
648
789
  const wallMs = Date.now() - startedAt;
649
790
 
791
+ // A Stop landed during this try: the call in flight finished and is booked here (its cost into the run's spend and onto the one
792
+ // `stopped` row), no new call started. Unknown cost stays unknown (usd null, spend incomplete), never 0.
793
+ const turns = typeof result?.turns === 'number' ? result.turns : null;
794
+ lastTurns = turns;
795
+ if (result && result.ok === false && result.stopped === true) {
796
+ if (typeof result.costUsd === 'number') spent.value += result.costUsd;
797
+ const usd = sumKnownUsd(attemptFloorUsd, result.costUsd);
798
+ const ranCalls = (turns ?? 0) > 0 || attemptFloorUsd !== null;
799
+ return stopped(stopWords(ranCalls ? attempt : attempt - 1, turns ?? 0), makeAuditRow({
800
+ step, attempt: ranCalls ? attempt : null, verdict: 'stopped', gap: null, usd, spendComplete: usd !== null, 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,
801
+ }));
802
+ }
803
+
650
804
  if (result && result.ok === false && result.transport === true) {
651
805
  if (typeof result.costUsd === 'number') spent.value += result.costUsd;
652
806
  // Both faults' known costs, summed — the first fault's floor was
@@ -673,7 +827,7 @@ async function runStepRalph({
673
827
  recordAudit(makeAuditRow({
674
828
  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,
675
829
  }), red);
676
- if (n === MAX_ATTEMPTS) return { ok: false, outcome: 'attempt-fallback', red: `attempt-fallback: step "${step.goal}" — ${red}` };
830
+ if (n === maxN) return { ok: false, outcome: 'attempt-fallback', red: `attempt-fallback: step "${step.goal}" — ${red}` };
677
831
  if (strikes >= STRIKE_LIMIT) return { ok: false, outcome: 'struck-out', red: `struck-out: step "${step.goal}" — ${red}` };
678
832
  gap = red;
679
833
  // eslint-disable-next-line no-continue
@@ -712,7 +866,7 @@ async function runStepRalph({
712
866
  recordAudit(makeAuditRow({
713
867
  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,
714
868
  }), result.artifact ?? null);
715
- if (n === MAX_ATTEMPTS) return { ok: false, outcome: 'attempt-fallback', red: `attempt-fallback: ${happened.red}` };
869
+ if (n === maxN) return { ok: false, outcome: 'attempt-fallback', red: `attempt-fallback: ${happened.red}` };
716
870
  if (strikes >= STRIKE_LIMIT) return { ok: false, outcome: 'struck-out', red: `struck-out: ${happened.red}` };
717
871
  gap = happened.red ?? null;
718
872
  // eslint-disable-next-line no-continue
@@ -747,7 +901,7 @@ async function runStepRalph({
747
901
  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,
748
902
  }), result.artifact);
749
903
 
750
- if (n === MAX_ATTEMPTS) return { ok: false, outcome: 'attempt-fallback', red: `attempt-fallback: step "${step.goal}" — ${closed.red}` };
904
+ if (n === maxN) return { ok: false, outcome: 'attempt-fallback', red: `attempt-fallback: step "${step.goal}" — ${closed.red}` };
751
905
  if (strikes >= STRIKE_LIMIT) return { ok: false, outcome: 'struck-out', red: `struck-out: step "${step.goal}" — ${closed.red}` };
752
906
  gap = closed.red ?? null;
753
907
  }
@@ -824,15 +978,22 @@ export async function runFlow({
824
978
  return { outcome: 'refused', red: read.reds[0], reds: read.reds };
825
979
  }
826
980
 
827
- const { arbiter, declaration, signature } = read;
981
+ const { declaration, signature } = read;
982
+ const runDir = runIdCheck.runDir;
983
+ // M4e amendment 5 item 3: the values THIS run was signed with (cap, send folder, ask waits) lie over the flow's own — one decision (`pickRunValues`).
984
+ const applied = applyRunValues(read.arbiter, name, signature.flow, pickRunValues(runDir));
985
+ if (!applied.ok) {
986
+ return haltRun({
987
+ flowDir, runDir, runId, capUsd: null, startedAt, now, nowMs: getNowMs, signatureHash: signature.flow, outcome: 'preflight-red', red: applied.red, spent: { value: 0 },
988
+ });
989
+ }
990
+ const { arbiter } = applied;
828
991
  const capUsd = arbiter.capUsd;
829
992
  const redoCap = arbiter.redoCap ?? 3;
830
993
  const effectiveCeilingUsd = ceilingUsd ?? resolveCeilingUsd(null);
831
994
  const askLines = new Map((arbiter.asks ?? []).map((a) => [a.line, a]));
832
995
  const sendLines = new Map((arbiter.sends ?? []).map((s) => [s.line, s]));
833
996
 
834
- const runDir = runIdCheck.runDir;
835
-
836
997
  const unwiredVerb = findUnwiredVerbStep(declaration);
837
998
  if (unwiredVerb) {
838
999
  return haltRun({
@@ -845,7 +1006,7 @@ export async function runFlow({
845
1006
  nowMs: getNowMs,
846
1007
  signatureHash: signature.flow,
847
1008
  outcome: 'preflight-red',
848
- red: `preflight: step "${unwiredVerb.step.emits}" (line ${unwiredVerb.step.fromLine}) grants verb "${unwiredVerb.verb}", which has no wired implementation`,
1009
+ red: unwiredRed(unwiredVerb),
849
1010
  spent: { value: 0 },
850
1011
  });
851
1012
  }
@@ -1031,7 +1192,7 @@ function makeOneShotThenParkAskStep({ decision, reason, artifactSha256 }) {
1031
1192
  * @returns {Promise<any>}
1032
1193
  */
1033
1194
  async function runAskSlot({
1034
- step, stepIndex, askSlot, priorId, priorStep, priorArtifact, redoCap, effectiveCeilingUsd, capUsd,
1195
+ step, stepIndex, askSlot, priorId, priorStep, priorStepNo, priorPrevStepId = null, priorArtifact, redoCap, effectiveCeilingUsd, capUsd,
1035
1196
  primitives, businessDate, modelStep, askStep, spent, spendComplete, recordAudit,
1036
1197
  evidenceUnjudged, unjudgedCount, redone: initialRedone,
1037
1198
  runDir, flowDir, runId, flowRoot, flowName, signatureHash, inputsManifest, attemptsLog, artifacts, now, startedAt,
@@ -1052,6 +1213,17 @@ async function runAskSlot({
1052
1213
  // M4b amendment 3: a decision from any askStep is translated once, here.
1053
1214
  const answer = { ...rawAnswer, decision: normalizeDecision(rawAnswer.decision) };
1054
1215
 
1216
+ if (answer.decision === 'park' && stopPending(runDir)) {
1217
+ // M4e amendment 13: a Stop pending as the turn leads to an ask stops AT the ask — nothing is written for it, no wait begins.
1218
+ return {
1219
+ type: 'halted',
1220
+ outcome: 'stopped',
1221
+ red: `stopped by you at the ask of step ${stepIndex + 1} ("${step.goal}")`,
1222
+ stop: { where: `stopped at the ask of step ${stepIndex + 1}`, step: step.emits ?? step.goal ?? null },
1223
+ redone,
1224
+ };
1225
+ }
1226
+
1055
1227
  if (answer.decision === 'park') {
1056
1228
  // M3 scope item 1 (fixes F43): the wait is ALWAYS the signed ttlMs —
1057
1229
  // no code default ever overrides it, on the first park or any re-park.
@@ -1128,6 +1300,15 @@ async function runAskSlot({
1128
1300
  // at its final outcome (complete / a halt / ask-expired), written by
1129
1301
  // `foldFromStep`/`resumeRun`, never here.
1130
1302
  writeLog(runDir, { runId, outcome: 'paused', attempts: attemptsLog, artifacts });
1303
+ // M4e amendment 13: a park is not an end. A Stop that landed while the ask was being written stops the run at the ask
1304
+ // (the ask is set aside; one winner against the Stop door, by rename).
1305
+ if (stopPending(runDir)) {
1306
+ const stopped = stopAtAsk({
1307
+ flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, signatureHash, spent, spendComplete: spendComplete.value, attempts: attemptsLog, artifacts,
1308
+ stepIndex, stepEmits: step.emits ?? step.goal ?? null, flowRoot, flowName, inputsManifest, unjudged: evidenceUnjudged, redone, parkedAskId: askId,
1309
+ });
1310
+ if (stopped) return { type: 'stopped', result: stopped };
1311
+ }
1131
1312
  return {
1132
1313
  type: 'paused',
1133
1314
  result: {
@@ -1196,9 +1377,12 @@ async function runAskSlot({
1196
1377
  // eslint-disable-next-line no-await-in-loop
1197
1378
  const redoResult = await runStepRalph({
1198
1379
  step: priorStep, primitivesMap: primitives, readsMap: priorReadsResult.map, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, initialGap: reason, attemptOffset: redone, now,
1380
+ readStop: () => stopPending(runDir), stepNo: priorStepNo, prevStepId: priorPrevStepId,
1199
1381
  });
1200
1382
  if (!redoResult.ok) {
1201
- return { type: 'halted', outcome: redoResult.outcome, red: redoResult.red };
1383
+ return {
1384
+ type: 'halted', outcome: redoResult.outcome, red: redoResult.red, ...(redoResult.stop ? { stop: redoResult.stop } : {}),
1385
+ };
1202
1386
  }
1203
1387
  currentPrior = redoResult.artifact;
1204
1388
  // A redo deliberately REPLACES the prior step's own artifact — the one
@@ -1245,6 +1429,11 @@ async function foldFromStep({
1245
1429
  // `@param {object} opts` this function's block comment never declared)
1246
1430
  // is what keeps every OTHER destructured field's inferred type intact.
1247
1431
  firstStepGap = /** @type {string|null} */ (null),
1432
+ // Amendment 7 item 8: a run Resumed after a Stop that cut step `i0` mid-way re-enters it as a NEW try — `numbered` tries already
1433
+ // wear numbers (the new one is numbered after them), `done` of them closed and count against the step's limit.
1434
+ resumeTries = { numbered: 0, done: 0 },
1435
+ // Amendment 13: the redo count a stop-at-ask carried in its halt record, restored for the ask step it re-enters (`i0`).
1436
+ resumeRedone = 0,
1248
1437
  }) {
1249
1438
  let runAcceptedThisRun = acceptedThisRun;
1250
1439
  let runUnjudged = unjudgedSinceLastAsk;
@@ -1252,6 +1441,24 @@ async function foldFromStep({
1252
1441
  for (let i = i0; i < steps.length; i += 1) {
1253
1442
  const step = steps[i];
1254
1443
 
1444
+ // M4e amendment 4 item 4: the Stop seam. Step i-1 has closed (artifact written, rows booked); a pending request ends the run here.
1445
+ // Amendment 7 item 8 adds the same seam before every model call (turns and tries, inside `runStepRalph`/`modelStep`).
1446
+ if (stopPending(runDir)) {
1447
+ // Amendment 13: when the turn that just closed leads to an ask, the run stops AT the ask, in the ask's words.
1448
+ if (askLines.has(step.fromLine)) {
1449
+ return stopAtAsk({
1450
+ flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, spendComplete: spendComplete.value, attempts: attemptsLog, artifacts,
1451
+ stepIndex: i, stepEmits: step.emits ?? step.goal ?? null, flowRoot, flowName, inputsManifest, unjudged: runUnjudged, redone: i === i0 ? resumeRedone : 0,
1452
+ });
1453
+ }
1454
+ return haltRun({
1455
+ flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts,
1456
+ outcome: 'stopped', red: `stopped by you before step ${i + 1} ("${step.goal}")`,
1457
+ stop: { where: i === 0 ? 'stopped before step 1' : `stopped after step ${i}`, step: i === 0 ? null : (steps[i - 1].emits ?? steps[i - 1].goal ?? null) },
1458
+ resumeAt: { stepIndex: i, flowRoot, flowName, inputsManifest, unjudged: runUnjudged },
1459
+ });
1460
+ }
1461
+
1255
1462
  // --- the signed send slot: never through modelStep, only after an
1256
1463
  // accept THIS run, re-checked at write time. ---
1257
1464
  if (sendLines.has(step.fromLine)) {
@@ -1302,9 +1509,9 @@ async function foldFromStep({
1302
1509
  });
1303
1510
  }
1304
1511
  const content = contentResult.value;
1305
- const filename = `${runId}-${step.emits}.json`;
1512
+ const filename = `${flowName}-${runId}-${step.emits}.json`;
1306
1513
  // eslint-disable-next-line no-await-in-loop
1307
- const sendResult = await sendStep(target, filename, content, acceptedAskEmitsThisRun.get(askArtifactId));
1514
+ const sendResult = await sendStep(target, filename, content, acceptedAskEmitsThisRun.get(askArtifactId), { root: flowRoot, runDir });
1308
1515
  const sendRow = makeAuditRow({
1309
1516
  step, attempt: 1, verdict: sendResult.ok ? 'green' : 'red', gap: sendResult.ok ? null : sendResult.red, usd: 0, spendComplete: true, wallMs: 0, strike: false, at: now(),
1310
1517
  });
@@ -1357,6 +1564,8 @@ async function foldFromStep({
1357
1564
  askSlot,
1358
1565
  priorId,
1359
1566
  priorStep: steps[priorStepIndex],
1567
+ priorStepNo: priorStepIndex + 1,
1568
+ priorPrevStepId: priorStepIndex > 0 ? (steps[priorStepIndex - 1].emits ?? null) : null,
1360
1569
  priorArtifact,
1361
1570
  redoCap,
1362
1571
  effectiveCeilingUsd,
@@ -1370,7 +1579,7 @@ async function foldFromStep({
1370
1579
  recordAudit,
1371
1580
  evidenceUnjudged,
1372
1581
  unjudgedCount,
1373
- redone: 0,
1582
+ redone: i === i0 ? resumeRedone : 0,
1374
1583
  runDir,
1375
1584
  flowDir,
1376
1585
  runId,
@@ -1385,10 +1594,14 @@ async function foldFromStep({
1385
1594
  runStartedAt,
1386
1595
  });
1387
1596
 
1388
- if (askResult.type === 'paused') return askResult.result;
1597
+ if (askResult.type === 'paused' || askResult.type === 'stopped') return askResult.result;
1389
1598
  if (askResult.type === 'halted') {
1390
1599
  return haltRun({
1391
- flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts, outcome: askResult.outcome, red: askResult.red,
1600
+ flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value && askResult.stop?.book?.spendComplete !== false, attempts: attemptsLog, artifacts, outcome: askResult.outcome, red: askResult.red,
1601
+ ...(askResult.stop ? { stop: askResult.stop } : {}),
1602
+ resumeAt: {
1603
+ stepIndex: i, flowRoot, flowName, inputsManifest, unjudged: evidenceUnjudged, redone: askResult.redone,
1604
+ },
1392
1605
  });
1393
1606
  }
1394
1607
 
@@ -1419,10 +1632,13 @@ async function foldFromStep({
1419
1632
  // eslint-disable-next-line no-await-in-loop
1420
1633
  const stepResult = await runStepRalph({
1421
1634
  step, primitivesMap: primitives, readsMap, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, initialGap: i === i0 ? firstStepGap : null, now,
1635
+ readStop: () => stopPending(runDir), stepNo: i + 1, prevStepId: i > 0 ? (steps[i - 1].emits ?? steps[i - 1].goal ?? null) : null, attemptOffset: i === i0 ? resumeTries.numbered : 0, triesDone: i === i0 ? resumeTries.done : 0,
1422
1636
  });
1423
1637
  if (!stepResult.ok) {
1424
1638
  return haltRun({
1425
- flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts, outcome: stepResult.outcome, red: stepResult.red,
1639
+ flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value && stepResult.stop?.book?.spendComplete !== false, attempts: attemptsLog, artifacts, outcome: stepResult.outcome, red: stepResult.red,
1640
+ ...(stepResult.stop ? { stop: stepResult.stop } : {}),
1641
+ resumeAt: { stepIndex: i, flowRoot, flowName, inputsManifest, unjudged: runUnjudged },
1426
1642
  });
1427
1643
  }
1428
1644
  writeArtifact(runDir, step.emits, stepResult.artifact);
@@ -1449,6 +1665,7 @@ async function foldFromStep({
1449
1665
  writeLog(runDir, {
1450
1666
  runId, outcome: 'complete', attempts: attemptsLog, artifacts,
1451
1667
  });
1668
+ settleStop({ runDir, now, outcome: 'complete' });
1452
1669
  return {
1453
1670
  outcome: 'complete', runDir, artifacts, spentUsd: spent.value,
1454
1671
  };
@@ -1465,17 +1682,19 @@ async function foldFromStep({
1465
1682
  * resumable run's audit.jsonl). A row this function cannot price refuses
1466
1683
  * rather than guessing (never `?? 0`, never skipped).
1467
1684
  * @param {string} runDir
1468
- * @returns {{ ok: true, total: number } | { ok: false, red: string }}
1685
+ * @param {{skipVerdicts?: string[]}} [opts]
1686
+ * @returns {{ ok: true, total: number, complete: boolean } | { ok: false, red: string }}
1469
1687
  */
1470
- function sumAuditUsd(runDir) {
1688
+ function sumAuditUsd(runDir, { skipVerdicts = /** @type {string[]} */ ([]) } = {}) {
1471
1689
  // F48 round 3: goes through `readFileInside` (`src/flow.js`) rather than a
1472
1690
  // raw `readFileSync` — a symlinked `audit.jsonl` (or a symlinked ancestor
1473
1691
  // directory) reads as "missing" (total 0), never as some outside file's
1474
1692
  // content summed into a cap check.
1475
1693
  const result = readFileInside(runDir, 'audit.jsonl');
1476
- if (!result.ok) return { ok: true, total: 0 };
1694
+ if (!result.ok) return { ok: true, total: 0, complete: true };
1477
1695
  const lines = result.text.split('\n').filter((line) => line.trim().length > 0);
1478
1696
  let total = 0;
1697
+ let complete = true;
1479
1698
  for (const line of lines) {
1480
1699
  let row;
1481
1700
  try {
@@ -1483,12 +1702,15 @@ function sumAuditUsd(runDir) {
1483
1702
  } catch (err) {
1484
1703
  return { ok: false, red: `audit.jsonl line is not valid JSON — ${err.message}` };
1485
1704
  }
1705
+ // a row of a verdict the caller names cost nothing and carries `usd: null` on purpose (a cap-halt: the round was never bought)
1706
+ if (skipVerdicts.includes(row.verdict)) continue;
1707
+ if (row.spendComplete === false) complete = false;
1486
1708
  if (typeof row.usd !== 'number' || !Number.isFinite(row.usd)) {
1487
1709
  return { ok: false, red: `audit.jsonl carries a row whose "usd" is not a finite number (got ${JSON.stringify(row.usd)}) — refusing to sum past an unpriced round` };
1488
1710
  }
1489
1711
  total += row.usd;
1490
1712
  }
1491
- return { ok: true, total };
1713
+ return { ok: true, total, complete };
1492
1714
  }
1493
1715
 
1494
1716
  /** Unlink `resume.lock` only when its recorded holder is still THIS process (`readResumeLock`'s holder pid + start
@@ -1616,7 +1838,7 @@ export async function resumeRun({
1616
1838
  if (unwiredVerb) {
1617
1839
  return {
1618
1840
  outcome: 'refused',
1619
- red: `preflight: step "${unwiredVerb.step.emits}" (line ${unwiredVerb.step.fromLine}) grants verb "${unwiredVerb.verb}", which has no wired implementation`,
1841
+ red: unwiredRed(unwiredVerb),
1620
1842
  };
1621
1843
  }
1622
1844
  }
@@ -1675,7 +1897,11 @@ export async function resumeRun({
1675
1897
  if (!read.ok) {
1676
1898
  return { outcome: 'refused', red: `resume: flow re-read failed for run "${runId}": ${read.reds.join('; ')}` };
1677
1899
  }
1678
- const { declaration, arbiter, signature } = read;
1900
+ const { declaration, signature } = read;
1901
+ // M4e amendment 5 item 3 / amendment 4 item 6: the run's own signed values (its highest version) lie over the flow's.
1902
+ const applied = applyRunValues(read.arbiter, name, signature.flow, pickRunValues(runDir));
1903
+ if (!applied.ok) return { outcome: 'refused', red: `resume: run "${runId}" — ${applied.red}` };
1904
+ const { arbiter } = applied;
1679
1905
 
1680
1906
  if (signature.flow !== state.signatureHash) {
1681
1907
  return { outcome: 'refused', red: `resume: signature mismatch for run "${runId}" — the flow changed while parked` };
@@ -1807,6 +2033,24 @@ export async function resumeRun({
1807
2033
  return { outcome: 'refused', red: `resume: answer.json for run "${runId}" has a missing or unreadable answeredAt ("${answer.answeredAt}") — refusing rather than treating it as on time` };
1808
2034
  }
1809
2035
 
2036
+ // M4e amendment 13: a Stop asked STRICTLY before this answer was saved was asked of a run that was waiting (it landed after the
2037
+ // park, before the Stop door could act). The run is stopped AT the ask and the answer to it is not used. A Stop asked at the same
2038
+ // instant as the answer, or after it, belongs to the apply that follows: the fold's own seam reads it and stops before the next
2039
+ // step. On a tie the ANSWER WINS (hamr's ruling, 2026-10-07: a fast CI gave both the same millisecond). A Stop with no readable
2040
+ // time is stopped at the ask: conservative, stated here so it never falls out of a NaN comparison.
2041
+ const stopReq = readStopRequest(runDir);
2042
+ const stopMs = stopReq ? Date.parse(stopReq.at ?? '') : NaN;
2043
+ const stopFirst = Number.isNaN(stopMs) || stopMs < Date.parse(answer.answeredAt);
2044
+ if (stopReq && stopFirst) {
2045
+ const prev = readLog(runDir);
2046
+ return stopAtAsk({
2047
+ flowDir, runDir, runId, capUsd: arbiter.capUsd ?? null, startedAt: runStartedAt, now, nowMs: getNowMs, signatureHash: state.signatureHash, spent, spendComplete: spendComplete.value,
2048
+ attempts: Array.isArray(prev?.attempts) ? prev.attempts : [], artifacts: prev?.artifacts && typeof prev.artifacts === 'object' ? prev.artifacts : {},
2049
+ stepIndex: state.stepIndex, stepEmits: steps[state.stepIndex]?.emits ?? null, flowRoot: root, flowName: name, inputsManifest: state.inputsManifest,
2050
+ unjudged: state.evidenceUnjudged ?? [], redone: typeof state.redone === 'number' ? state.redone : 0, parkedAskId: state.askId,
2051
+ });
2052
+ }
2053
+
1810
2054
  // M4b amendment 2: hashes recorded by earlier-process accepts, read back
1811
2055
  // from the archive + consumed markers. Refused BEFORE the consume below so
1812
2056
  // the answer stays replayable.
@@ -1967,6 +2211,8 @@ export async function resumeRun({
1967
2211
  askSlot,
1968
2212
  priorId,
1969
2213
  priorStep: steps[priorStepIndex],
2214
+ priorStepNo: priorStepIndex + 1,
2215
+ priorPrevStepId: priorStepIndex > 0 ? (steps[priorStepIndex - 1].emits ?? null) : null,
1970
2216
  priorArtifact,
1971
2217
  redoCap,
1972
2218
  effectiveCeilingUsd,
@@ -1995,10 +2241,14 @@ export async function resumeRun({
1995
2241
  runStartedAt,
1996
2242
  });
1997
2243
 
1998
- if (askResult.type === 'paused') return askResult.result;
2244
+ if (askResult.type === 'paused' || askResult.type === 'stopped') return askResult.result;
1999
2245
  if (askResult.type === 'halted') {
2000
2246
  return haltRun({
2001
- flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs: getNowMs, signatureHash: state.signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts, outcome: askResult.outcome, red: askResult.red,
2247
+ flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs: getNowMs, signatureHash: state.signatureHash, spent, priorSpendComplete: spendComplete.value && askResult.stop?.book?.spendComplete !== false, attempts: attemptsLog, artifacts, outcome: askResult.outcome, red: askResult.red,
2248
+ ...(askResult.stop ? { stop: askResult.stop } : {}),
2249
+ resumeAt: {
2250
+ stepIndex: state.stepIndex, flowRoot: root, flowName: name, inputsManifest: state.inputsManifest, unjudged: state.evidenceUnjudged ?? [], redone: askResult.redone,
2251
+ },
2002
2252
  });
2003
2253
  }
2004
2254
 
@@ -2054,6 +2304,296 @@ export async function resumeRun({
2054
2304
  }
2055
2305
  }
2056
2306
 
2307
+ /**
2308
+ * What a run has spent so far, from its own books (audit.jsonl is the source of truth): the sum of every priced row (a cap-halt
2309
+ * row cost nothing and carries no number), and whether any row left the total a floor. Used by `continueRun` and the CLI's hold.
2310
+ * @param {string} runDir
2311
+ * @returns {{ ok: true, total: number, complete: boolean } | { ok: false, red: string }}
2312
+ */
2313
+ export function auditSpend(runDir) {
2314
+ return sumAuditUsd(runDir, { skipVerdicts: ['cap-halt'] });
2315
+ }
2316
+
2317
+ /**
2318
+ * M4e amendment 4 items 4 and 6 (Resume of a stopped or cap-halted run): the SAME run id continues, never a new run. Takes the
2319
+ * same exclusive `resume.lock` as an answer-resume (one resume at a time per run), reads `halt.json` (the runner's own record of
2320
+ * where it stopped), re-verifies the flow's signature, the frozen inputs and every finished step's artifact, lays the run's
2321
+ * highest signed values version over the flow's (`pickRunValues`: the human's new cap lives there, write-once, never in the flow's
2322
+ * own files), refuses by name at $0 when that cap is not above what is already spent, consumes `halt.json` by rename (the
2323
+ * mutex, like an answer), then re-enters the ONE fold at the first step with no artifact. Done steps are not re-run, spend so
2324
+ * far (re-summed from the books) counts against the new cap, the plan is never redrawn.
2325
+ *
2326
+ * @param {object} opts same shape as `resumeRun`'s
2327
+ * @param {string} opts.root
2328
+ * @param {string} opts.name
2329
+ * @param {string} opts.runId
2330
+ * @param {unknown} opts.catalogue
2331
+ * @param {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class:string|null}) => Promise<any>} opts.modelStep
2332
+ * @param {(target:string, filename:string, content:unknown) => Promise<{ok:boolean, red?:string, bytes?:number}>} opts.sendStep
2333
+ * @param {Record<string, any>} [opts.primitives]
2334
+ * @param {string[]} [opts.primitiveReds]
2335
+ * @param {() => string} [opts.clock]
2336
+ * @param {string} opts.businessDate
2337
+ * @param {number} [opts.ceilingUsd]
2338
+ * @param {() => number} [opts.nowMs]
2339
+ */
2340
+ export async function continueRun({
2341
+ root, name, runId, catalogue, modelStep, sendStep, primitives, primitiveReds, clock, businessDate, ceilingUsd, nowMs,
2342
+ }) {
2343
+ const now = typeof clock === 'function' ? clock : () => new Date().toISOString();
2344
+ const getNowMs = typeof nowMs === 'function' ? nowMs : Date.now;
2345
+ const flowDir = join(root, name);
2346
+ const startedAt = getNowMs();
2347
+ const refused = (red) => ({ outcome: 'refused', red: `continue: ${red}` });
2348
+
2349
+ const runIdCheck = resolveRunDir(flowDir, runId);
2350
+ if (!runIdCheck.ok) return { outcome: 'refused', red: runIdCheck.red };
2351
+ const runDir = runIdCheck.runDir;
2352
+
2353
+ const preflightRead = readFlow({ root, name, catalogue });
2354
+ if (preflightRead.ok) {
2355
+ const unwiredVerb = findUnwiredVerbStep(preflightRead.declaration);
2356
+ if (unwiredVerb) return refused(unwiredRed(unwiredVerb));
2357
+ }
2358
+ if (primitiveReds?.length) return refused(primitiveReds[0]);
2359
+
2360
+ const lockPath = join(runDir, 'resume.lock');
2361
+ const took = await takeResumeLock(runDir, runId, lockPath);
2362
+ if (!took.ok) return { outcome: 'refused', red: took.red };
2363
+ const { lockFd } = took;
2364
+
2365
+ try {
2366
+ const haltRead = readHaltRecord(runDir);
2367
+ if (!haltRead.ok) {
2368
+ return refused(haltRead.missing
2369
+ ? `run "${runId}" was not stopped or cap-halted by this version (no halt record) — there is nothing to continue; start a new run`
2370
+ : `run "${runId}" ${haltRead.red}`);
2371
+ }
2372
+ const { halt } = haltRead;
2373
+ if (!sameRoot(halt.flow?.root, root) || halt.flow?.name !== name) {
2374
+ return refused(`run "${runId}" was halted against flow "${halt.flow?.root}/${halt.flow?.name}", not the requested "${root}/${name}" — refusing rather than reading a different flow than asked`);
2375
+ }
2376
+ if (!Number.isInteger(halt.stepIndex) || halt.stepIndex < 0) return refused(`run "${runId}" halt.json field "stepIndex" is not a step number`);
2377
+
2378
+ const read = readFlow({ root, name, catalogue });
2379
+ if (!read.ok) return refused(`flow re-read failed for run "${runId}": ${read.reds.join('; ')}`);
2380
+ const { declaration, signature } = read;
2381
+ if (signature.flow !== halt.signatureHash) return refused(`signature mismatch for run "${runId}" — the flow changed while it was halted`);
2382
+ // the human's signed values for this run (its highest version): the new cap is read from here, nowhere else
2383
+ const applied = applyRunValues(read.arbiter, name, signature.flow, pickRunValues(runDir));
2384
+ if (!applied.ok) return refused(`run "${runId}" — ${applied.red}`);
2385
+ const { arbiter } = applied;
2386
+
2387
+ for (const entry of halt.inputsManifest ?? []) {
2388
+ if (!existsSync(entry.frozen)) return refused(`frozen input "${entry.id}" missing for run "${runId}" (${entry.frozen})`);
2389
+ if (createHash('sha256').update(readFileSync(entry.frozen)).digest('hex') !== entry.sha256) {
2390
+ return refused(`frozen input "${entry.id}" changed while halted for run "${runId}"`);
2391
+ }
2392
+ }
2393
+
2394
+ const { steps } = declaration;
2395
+ if (halt.stepIndex > steps.length) return refused(`run "${runId}" halt.json names step ${halt.stepIndex}, past this flow's ${steps.length} steps`);
2396
+ /** @type {Record<string, any>} */
2397
+ const artifacts = {};
2398
+ for (let i = 0; i < halt.stepIndex; i += 1) {
2399
+ const a = readArtifactResult(runDir, steps[i].emits);
2400
+ if (!a.ok) {
2401
+ return refused(a.missing
2402
+ ? `artifact "${steps[i].emits}" missing for run "${runId}" — cannot continue`
2403
+ : `artifact "${steps[i].emits}" for run "${runId}" — ${a.red} — refusing rather than treating a refused read as "not done" and re-running it`);
2404
+ }
2405
+ artifacts[steps[i].emits] = a.value;
2406
+ }
2407
+
2408
+ const audit = auditSpend(runDir);
2409
+ if (!audit.ok) return refused(`run "${runId}" ${audit.red}`);
2410
+ const capUsd = arbiter.capUsd;
2411
+ if (!(capUsd - audit.total > SPEND_TOLERANCE_USD)) {
2412
+ return refused(`the cap $${capUsd} is not above what run "${runId}" has already spent ($${audit.total}) — raise it first; $0 spent now`);
2413
+ }
2414
+ const recordedHashes = readAcceptedHashesByEmits(runDir);
2415
+ if (!recordedHashes.ok) return { outcome: 'refused', red: recordedHashes.red };
2416
+
2417
+ // Consume-once BEFORE acting (the answer's own rule, F44): the rename is a one-winner gate on top of the lock.
2418
+ const taken = readdirInside(runDir, '.').filter((n) => /^halt\.\d+\.consumed\.json$/.test(n)).length;
2419
+ renameSync(join(runDir, HALT_FILE), join(runDir, `halt.${taken + 1}.consumed.json`));
2420
+ settleStop({ runDir, now, outcome: halt.outcome ?? 'halted' }); // a request left over from before the halt is not this continue's
2421
+ recordPid(runDir, 'continue', now());
2422
+
2423
+ const spent = { value: audit.total };
2424
+ const spendComplete = { value: audit.complete };
2425
+ const askLines = new Map((arbiter.asks ?? []).map((a) => [a.line, a]));
2426
+ const sendLines = new Map((arbiter.sends ?? []).map((s) => [s.line, s]));
2427
+ const askStepEmits = new Set(steps.filter((s) => askLines.has(s.fromLine)).map((s) => s.emits));
2428
+ const acceptedAskEmitsThisRun = new Map();
2429
+ for (const emits of askStepEmits) {
2430
+ const idx = steps.findIndex((s) => s.emits === emits);
2431
+ // a step before the halt point has its artifact (the gate above refused any that was missing or red)
2432
+ if (idx !== -1 && idx < halt.stepIndex) {
2433
+ acceptedAskEmitsThisRun.set(emits, recordedHashes.byEmits.get(emits) ?? null);
2434
+ }
2435
+ }
2436
+ const attemptsLog = [];
2437
+ const auditRows = [];
2438
+ const recordAudit = (row, modelOutput, unjudgedCount) => {
2439
+ const fullRow = unjudgedCount === undefined ? row : { ...row, unjudgedCount };
2440
+ auditRows.push(fullRow);
2441
+ appendAudit(runDir, fullRow);
2442
+ if (row.spendComplete === false) spendComplete.value = false;
2443
+ if (modelOutput !== undefined) {
2444
+ attemptsLog.push({
2445
+ step: row.step, attempt: row.attempt, class: row.class, verdict: row.verdict, gap: row.gap, ...(row.refused ? { refused: row.refused } : {}), modelOutput,
2446
+ });
2447
+ }
2448
+ };
2449
+ const runStartedAt = typeof halt.startedAt === 'number' ? halt.startedAt : startedAt;
2450
+
2451
+ // Amendment 7 item 8: a Stop that cut the step short leaves its tries in the books; Resume re-enters it as a NEW try, numbered after them.
2452
+ // A try the Stop cut mid-way (its `stopped` row) wears a number but is replaced, not counted against the step's limit. Read from the
2453
+ // books (the source of truth), never a second record. A cap-halt re-entry keeps its own, earlier behaviour.
2454
+ const resumeTries = { numbered: 0, done: 0 };
2455
+ if (halt.outcome === 'stopped' && steps[halt.stepIndex]) {
2456
+ const tries = readAudit(runDir).filter((r) => r.step === steps[halt.stepIndex].emits && Number.isInteger(r.attempt) && r.verdict !== 'cap-halt');
2457
+ resumeTries.numbered = tries.length;
2458
+ resumeTries.done = Math.min(tries.filter((r) => r.verdict !== 'stopped').length, MAX_ATTEMPTS - 1);
2459
+ }
2460
+
2461
+ const result = await foldFromStep({
2462
+ i0: halt.stepIndex,
2463
+ resumeTries,
2464
+ steps,
2465
+ askLines,
2466
+ sendLines,
2467
+ askStepEmits,
2468
+ runDir,
2469
+ flowDir,
2470
+ runId,
2471
+ flowRoot: root,
2472
+ flowName: name,
2473
+ signatureHash: halt.signatureHash,
2474
+ inputsManifest: halt.inputsManifest,
2475
+ capUsd,
2476
+ redoCap: arbiter.redoCap ?? 3,
2477
+ effectiveCeilingUsd: ceilingUsd ?? resolveCeilingUsd(null),
2478
+ primitives,
2479
+ businessDate,
2480
+ modelStep,
2481
+ // a continued run never waits in-process: a signed ask it reaches parks, under the wait in force
2482
+ askStep: makeParkingAskStep(),
2483
+ sendStep,
2484
+ now,
2485
+ startedAt,
2486
+ runStartedAt,
2487
+ nowMs: getNowMs,
2488
+ spent,
2489
+ spendComplete,
2490
+ artifacts,
2491
+ acceptedThisRun: acceptedAskEmitsThisRun.size > 0,
2492
+ acceptedAskEmitsThisRun,
2493
+ unjudgedSinceLastAsk: Array.isArray(halt.unjudged) ? halt.unjudged : [],
2494
+ resumeRedone: Number.isInteger(halt.redone) && halt.redone > 0 ? halt.redone : 0,
2495
+ recordAudit,
2496
+ attemptsLog,
2497
+ });
2498
+ if (result.outcome === 'complete') return { ...result, auditRows };
2499
+ return result;
2500
+ } finally {
2501
+ releaseResumeLock(runDir, lockPath);
2502
+ try { closeSync(lockFd); } catch { /* already closed */ }
2503
+ }
2504
+ }
2505
+
2506
+ /**
2507
+ * M4e amendment 13 (SIGNED 2026-10-07): a Stop at an ask. The ONE place a run is stopped at its ask, whether the turn led to it
2508
+ * (`parkedAskId` null: nothing was written for the ask) or the ask was already parked (`parkedAskId` set: the open ask and its
2509
+ * state are set aside as `ask.<id>.stopped.json` / `state.<id>.stopped.json` so no wait can expire and no answer can reach them;
2510
+ * the rename of `ask.json` is the one-winner gate, like an answer's). A saved answer to that ask is set aside, never used. The
2511
+ * rows are `settleStop`'s ("stop asked (you) at <time>", then "stopped at the ask of step N"); `halt.json` points at the ask
2512
+ * step, with the redo count carried, so Resume asks again, fresh, with no model call.
2513
+ * @param {Record<string, any>} o
2514
+ * @returns {any}
2515
+ */
2516
+ function stopAtAsk(o) {
2517
+ const {
2518
+ flowDir, runDir, runId, capUsd, startedAt, now, nowMs, signatureHash, spent, spendComplete = true, attempts = [], artifacts = {},
2519
+ stepIndex, stepEmits, flowRoot, flowName, inputsManifest, unjudged, redone, parkedAskId = null,
2520
+ } = o;
2521
+ const red = `stopped by you at the ask of step ${stepIndex + 1}`;
2522
+ if (parkedAskId !== null) {
2523
+ try { renameSync(join(runDir, 'ask.json'), join(runDir, `ask.${parkedAskId}.stopped.json`)); } catch {
2524
+ return { outcome: 'stopped', red, spentUsd: spent.value }; // another stopper won the rename: it writes the rows
2525
+ }
2526
+ try { renameSync(join(runDir, 'state.json'), join(runDir, `state.${parkedAskId}.stopped.json`)); } catch { /* no state: nothing to set aside */ }
2527
+ if (existsSync(join(runDir, 'answer.json'))) setAsideAnswer(runDir, parkedAskId, 'late');
2528
+ }
2529
+ return haltRun({
2530
+ flowDir, runDir, runId, capUsd, startedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete, attempts, artifacts,
2531
+ outcome: 'stopped', red,
2532
+ stop: { where: `stopped at the ask of step ${stepIndex + 1}`, step: stepEmits },
2533
+ resumeAt: {
2534
+ stepIndex, flowRoot, flowName, inputsManifest, unjudged, redone,
2535
+ },
2536
+ });
2537
+ }
2538
+
2539
+ /**
2540
+ * M4e amendment 13: the Stop on a run that already waits at its ask (the panel's Stop door; also the fallback for a request that
2541
+ * landed right after the park). Writes the request if none is pending (`requestStop`, its one writer), takes the same exclusive
2542
+ * `resume.lock` as a resume, checks the run really is parked on its open, unanswered ask, and stops it at the ask (`stopAtAsk`).
2543
+ * Refused by name, writing nothing, for a run that is not waiting at an ask. $0: no model call, no spend.
2544
+ * @param {object} opts
2545
+ * @param {string} opts.root
2546
+ * @param {string} opts.name
2547
+ * @param {string} opts.runId
2548
+ * @param {unknown} opts.catalogue
2549
+ * @param {() => string} [opts.clock]
2550
+ * @param {() => number} [opts.nowMs]
2551
+ */
2552
+ export async function stopParkedRun({
2553
+ root, name, runId, catalogue, clock, nowMs,
2554
+ }) {
2555
+ const now = typeof clock === 'function' ? clock : () => new Date().toISOString();
2556
+ const flowDir = join(root, name);
2557
+ const refused = (red) => ({ outcome: 'refused', red: `stop: ${red}` });
2558
+ const runIdCheck = resolveRunDir(flowDir, runId);
2559
+ if (!runIdCheck.ok) return { outcome: 'refused', red: runIdCheck.red };
2560
+ const runDir = runIdCheck.runDir;
2561
+
2562
+ const lockPath = join(runDir, 'resume.lock');
2563
+ const took = await takeResumeLock(runDir, runId, lockPath);
2564
+ if (!took.ok) return { outcome: 'refused', red: took.red };
2565
+ const { lockFd } = took;
2566
+ try {
2567
+ const ask = readAsk(runDir);
2568
+ const state = readRunState(runDir);
2569
+ if (!ask || typeof ask.askId !== 'string' || !state || state.askId !== ask.askId) return refused(`run "${runId}" is not waiting at an ask`);
2570
+ if (existsSync(join(runDir, `answer.${ask.askId}.consumed.json`))) return refused(`run "${runId}" already took its answer`);
2571
+ if (endRow(readHistory(flowDir), runDir, runId) !== null) return refused(`run "${runId}" has ended`);
2572
+ if (!Number.isInteger(state.stepIndex) || state.stepIndex < 0) return refused(`run "${runId}" state.json field "stepIndex" is not a step number`);
2573
+ const audit = auditSpend(runDir);
2574
+ if (!audit.ok) return refused(`run "${runId}" ${audit.red}`);
2575
+ requestStop(runDir); // 'exists' when the door (or a race) wrote it already
2576
+ const read = readFlow({ root, name, catalogue });
2577
+ let capUsd = null;
2578
+ if (read.ok) {
2579
+ const applied = applyRunValues(read.arbiter, name, read.signature.flow, pickRunValues(runDir));
2580
+ if (applied.ok) capUsd = applied.arbiter.capUsd ?? null;
2581
+ }
2582
+ const prev = readLog(runDir);
2583
+ const stepEmits = readAudit(runDir).filter((r) => r.verdict === 'paused').map((r) => r.step).pop() ?? null;
2584
+ return stopAtAsk({
2585
+ flowDir, runDir, runId, capUsd, startedAt: typeof state.startedAt === 'number' ? state.startedAt : Date.now(), now, nowMs: typeof nowMs === 'function' ? nowMs : Date.now,
2586
+ signatureHash: state.signatureHash ?? null, spent: { value: audit.total }, spendComplete: audit.complete,
2587
+ attempts: Array.isArray(prev?.attempts) ? prev.attempts : [], artifacts: prev?.artifacts && typeof prev.artifacts === 'object' ? prev.artifacts : {},
2588
+ stepIndex: state.stepIndex, stepEmits, flowRoot: root, flowName: name, inputsManifest: state.inputsManifest, unjudged: state.evidenceUnjudged ?? [],
2589
+ redone: typeof state.redone === 'number' ? state.redone : 0, parkedAskId: ask.askId,
2590
+ });
2591
+ } finally {
2592
+ releaseResumeLock(runDir, lockPath);
2593
+ try { closeSync(lockFd); } catch { /* already closed */ }
2594
+ }
2595
+ }
2596
+
2057
2597
  /** log.json's one writer, called from every exit path (complete + every
2058
2598
  * halt) — M2 scope item 9 / the M0 ruling: what the model wrote, every
2059
2599
  * attempt, red runs included, never just the final artifacts. */
@@ -2127,10 +2667,14 @@ export function readAsk(runDir) {
2127
2667
  * earlier attempt this run, that already left `spendComplete: false`).
2128
2668
  * ANDed with this halt's own outcome-based verdict — once false, always
2129
2669
  * false. Defaults to `true` (every pre-existing call site is unaffected).
2670
+ * @param {{stepIndex: number, flowRoot: string, flowName: string, inputsManifest: any, unjudged?: any[], redone?: number}|null} [opts.resumeAt] - M4e
2671
+ * amendment 4 item 4: where a `cap-halt`/`stopped` run is re-entered; `haltRun` writes `halt.json` from it (and only for those outcomes).
2672
+ * @param {{where:string, step?:string|null, book?:Record<string, any>}|null} [opts.stop] - amendment 7 item 8: this halt honours a Stop (its words, and the
2673
+ * cut try's row fields so the call in flight is booked); a request still pending on any other halt is recorded `not honoured`.
2130
2674
  */
2131
2675
  function haltRun({
2132
2676
  flowDir, runDir, runId, capUsd, startedAt, now, nowMs = Date.now, outcome, red, spent, attempts = [], artifacts = {}, signatureHash = null,
2133
- priorSpendComplete = true,
2677
+ priorSpendComplete = true, resumeAt = null, stop = null,
2134
2678
  }) {
2135
2679
  // F45 finding 3: `startedAt` here is always the RUN's start (every caller
2136
2680
  // now passes `runStartedAt` under this key — see call sites), so `wallMs`
@@ -2139,14 +2683,24 @@ function haltRun({
2139
2683
  const spendComplete = priorSpendComplete
2140
2684
  && outcome !== 'provider-red' && outcome !== 'pricing-red' && outcome !== 'cap-halt';
2141
2685
  mkdirSync(flowDir, { recursive: true });
2142
- appendHistory(flowDir, {
2143
- runId, at: now(), outcome, spentUsd: spent.value, spendComplete, capUsd: capUsd ?? null, wallMs, signatureHash,
2144
- });
2145
2686
  if (existsSync(runDir)) {
2146
2687
  recordLateAnswerIfAny(runDir, now);
2147
2688
  writeLog(runDir, {
2148
2689
  runId, outcome, red, attempts, artifacts,
2149
2690
  });
2691
+ // M4e amendment 4 item 4: a cap-halted or stopped run leaves the one record Resume continues from (its only writer).
2692
+ if (resumeAt && HALT_OUTCOMES.includes(outcome)) {
2693
+ writeFileSync(join(runDir, HALT_FILE), `${JSON.stringify({
2694
+ runId, outcome, at: now(), flow: { root: resumeAt.flowRoot, name: resumeAt.flowName }, signatureHash, inputsManifest: resumeAt.inputsManifest,
2695
+ stepIndex: resumeAt.stepIndex, startedAt, unjudged: resumeAt.unjudged ?? [],
2696
+ ...(Number.isInteger(resumeAt.redone) ? { redone: resumeAt.redone } : {}),
2697
+ }, null, 2)}\n`, { flag: 'wx' });
2698
+ }
2699
+ settleStop({ runDir, now, outcome, stop }); // amendment 7 item 8: every Stop leaves its rows
2150
2700
  }
2701
+ // The history end row is the LAST write: a reader that sees it finds the run fully settled (halt.json, log.json, stop rows).
2702
+ appendHistory(flowDir, {
2703
+ runId, at: now(), outcome, spentUsd: spent.value, spendComplete, capUsd: capUsd ?? null, wallMs, signatureHash,
2704
+ });
2151
2705
  return { outcome, red, spentUsd: spent.value };
2152
2706
  }