fwdloop 0.12.0 → 0.14.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 +155 -27
  2. package/package.json +2 -2
  3. package/src/ask.js +3 -0
  4. package/src/authoring.js +135 -16
  5. package/src/books.js +23 -2
  6. package/src/canrun.js +106 -0
  7. package/src/catalogue.json +2 -2
  8. package/src/checked.js +50 -0
  9. package/src/closers.js +112 -91
  10. package/src/config.js +2 -1
  11. package/src/declaration.js +175 -3
  12. package/src/drafter.js +148 -10
  13. package/src/draftspend.js +70 -0
  14. package/src/flow.js +43 -0
  15. package/src/keysfile.js +4 -2
  16. package/src/liveness.js +1 -1
  17. package/src/model-step.js +31 -5
  18. package/src/monthly.js +195 -28
  19. package/src/panel/author.js +638 -0
  20. package/src/panel/authorcard.js +340 -0
  21. package/src/panel/authorflows.js +317 -0
  22. package/src/panel/authorresume.js +149 -0
  23. package/src/panel/authorstart.js +257 -0
  24. package/src/panel/authorvalues.js +110 -0
  25. package/src/panel/data.js +318 -99
  26. package/src/panel/index.html +2000 -330
  27. package/src/panel/resume.js +6 -8
  28. package/src/panel/server.js +122 -119
  29. package/src/panel/settings.js +8 -6
  30. package/src/panel/spawn.js +77 -0
  31. package/src/provider.js +12 -17
  32. package/src/runner.js +707 -104
  33. package/src/runvalues.js +178 -0
  34. package/src/send.js +10 -3
  35. package/src/setup.js +127 -0
  36. package/types/authoring.d.ts +56 -2
  37. package/types/books.d.ts +14 -2
  38. package/types/canrun.d.ts +64 -0
  39. package/types/checked.d.ts +23 -0
  40. package/types/closers.d.ts +47 -28
  41. package/types/config.d.ts +1 -0
  42. package/types/declaration.d.ts +23 -1
  43. package/types/drafter.d.ts +151 -2
  44. package/types/draftspend.d.ts +21 -0
  45. package/types/flow.d.ts +23 -0
  46. package/types/liveness.d.ts +2 -2
  47. package/types/model-step.d.ts +4 -7
  48. package/types/monthly.d.ts +46 -1
  49. package/types/panel/author.d.ts +316 -0
  50. package/types/panel/authorcard.d.ts +142 -0
  51. package/types/panel/authorflows.d.ts +175 -0
  52. package/types/panel/authorresume.d.ts +32 -0
  53. package/types/panel/authorstart.d.ts +115 -0
  54. package/types/panel/authorvalues.d.ts +62 -0
  55. package/types/panel/data.d.ts +105 -63
  56. package/types/panel/server.d.ts +11 -33
  57. package/types/panel/spawn.d.ts +30 -0
  58. package/types/provider.d.ts +6 -9
  59. package/types/runner.d.ts +129 -6
  60. package/types/runvalues.d.ts +97 -0
  61. package/types/send.d.ts +5 -1
  62. package/types/setup.d.ts +77 -0
package/src/runner.js CHANGED
@@ -41,19 +41,25 @@ 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 {
55
+ findUnwiredVerbStep, unwiredRed, findUnbuildableCheckStep, unbuildableRed,
56
+ } from './canrun.js'; // M4e am7 item 7: the ONE decider (F46 refusal lives there)
57
+ import { configHome, configDoorHome } from './config.js';
55
58
  import { closeByClass } from './closers.js';
56
- import { appendAudit, appendHistory } from './books.js';
59
+ import {
60
+ appendAudit, appendHistory, readAudit, readHistory, endRow, HALT_OUTCOMES,
61
+ } from './books.js';
62
+ import { applyRunValues, pickRunValues } from './runvalues.js';
57
63
  import {
58
64
  readResumeLock, recordPid, writeLockHolder, procStartOf, LOCK_NO_HOLDER,
59
65
  } from './liveness.js';
@@ -80,6 +86,107 @@ export const MAX_ATTEMPTS = 4;
80
86
  * $0.0006+), so nothing a real tamper produces can hide inside it. */
81
87
  export const SPEND_TOLERANCE_USD = 1e-9;
82
88
 
89
+ // ---------------------------------------------------------------------------
90
+ // M4e amendment 4 item 4 (Stop) and the halt record Resume continues from.
91
+ //
92
+ // `stop.request` is written by the panel's Stop door (`requestStop`, its one writer) and read ONLY at the seam at the top of
93
+ // `foldFromStep`'s loop, i.e. after the previous step closed (its artifact written, its audit rows booked): every kind of
94
+ // step (model, a non-ask hitl pass-through, the signed send, an accepted ask) therefore reads it the same way. The reader
95
+ // 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
96
+ // stops AT the ask (`stopAtAsk`, the one place; `stopParkedRun` for a waiting run), because a park is not an end; a stop that
97
+ // arrives after the last step closed finds nothing left to stop and the run completes.
98
+ //
99
+ // `halt.json` is the one record a `cap-halt` or `stopped` run leaves for Resume (`continueRun`): where to re-enter (`stepIndex`,
100
+ // the first step whose artifact is not written), what was frozen/signed, and the hitl evidence not yet shown to an ask. Money and
101
+ // the spend-complete floor are NOT in it: the books (audit.jsonl) are the source of truth and `continueRun` re-sums them.
102
+ // Write-once (`wx`); `continueRun` consumes it by rename to `halt.<n>.consumed.json`, so "resumable" = halt.json exists.
103
+ // ---------------------------------------------------------------------------
104
+
105
+ export const STOP_FILE = 'stop.request';
106
+ export const HALT_FILE = 'halt.json';
107
+
108
+ /** The panel's one write of a stop request. `'exists'` = already asked, nothing more to do. @param {string} runDir */
109
+ export function requestStop(runDir) {
110
+ try {
111
+ writeFileSync(join(runDir, STOP_FILE), `${JSON.stringify({ at: new Date().toISOString() })}\n`, { mode: 0o600, flag: 'wx' });
112
+ return 'written';
113
+ } catch (err) {
114
+ if (err.code === 'EEXIST') return 'exists';
115
+ throw err;
116
+ }
117
+ }
118
+
119
+ /**
120
+ * The ONE reader of the stop request: `{at}` (when it was asked) or `null` when none is pending. Amendment 16 C11 / amendment 17 2A: a
121
+ * time that is not a real date (a non-date string, a number, a missing or empty time, a torn file) is treated as made "now" (`now`,
122
+ * when given), one rule for all, so the stop completes with every record and the ask is never lost. Without `now` (a pending check)
123
+ * such a request reads `{at:null}`.
124
+ * @param {string} runDir @param {() => string} [now]
125
+ */
126
+ export function readStopRequest(runDir, now) {
127
+ const r = readFileInside(runDir, STOP_FILE);
128
+ if (!r.ok) return null;
129
+ let at = null;
130
+ try {
131
+ const t = JSON.parse(r.text)?.at;
132
+ if (typeof t === 'string' && !Number.isNaN(Date.parse(t))) at = t;
133
+ } catch { /* a torn file: no time */ }
134
+ return { at: at ?? (typeof now === 'function' ? now() : null) };
135
+ }
136
+
137
+ /** Is a stop pending for this run? (read-only) @param {string} runDir */
138
+ export function stopPending(runDir) {
139
+ return readStopRequest(runDir) !== null;
140
+ }
141
+
142
+ /**
143
+ * 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
144
+ * silently. A pending request leaves "stop asked (you) at <time>" and then its outcome: `stop` given = honoured (`verdict:'stopped'`,
145
+ * `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
146
+ * ended (<outcome>) first`. No pending request and no `stop` = no rows. The notes cost 0; a booked call's cost rides the `stopped` row.
147
+ *
148
+ * @param {object} o
149
+ * @param {string} o.runDir
150
+ * @param {() => string} o.now
151
+ * @param {string} o.outcome how the run ended (the words of the not-honoured row)
152
+ * 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.
153
+ * "stopped before step 1"), else its book's step; with no stop, the step the run ended on (the last row that names one).
154
+ * @param {{where:string, step?:string|null, book?:Record<string, any>}|null} [o.stop]
155
+ */
156
+ function settleStop({
157
+ runDir, now, outcome, stop = null,
158
+ }) {
159
+ const req = readStopRequest(runDir, now);
160
+ if (!req && !stop) return;
161
+ const lastStep = () => readAudit(runDir).map((r) => r.step).filter((s) => typeof s === 'string' && s.length > 0).pop() ?? null;
162
+ const step = stop ? (stop.step ?? stop.book?.step ?? null) : lastStep();
163
+ const note = {
164
+ step, attempt: null, class: null, usd: 0, spendComplete: true, wallMs: 0, model: null, modelMatch: null, strike: false, tokens: null, tools: null, refused: [],
165
+ };
166
+ appendAudit(runDir, {
167
+ ...note, verdict: 'stop-asked', gap: `stop asked (you) at ${req?.at ?? 'an unrecorded time'}`, at: req?.at ?? now(),
168
+ });
169
+ appendAudit(runDir, stop
170
+ ? {
171
+ ...note, ...stop.book, step, verdict: 'stopped', gap: stop.where, at: now(),
172
+ }
173
+ : {
174
+ ...note, verdict: 'stop-not-honoured', gap: `not honoured: the run ended (${outcome}) first`, at: now(),
175
+ });
176
+ clearStop(runDir);
177
+ }
178
+
179
+ function clearStop(runDir) {
180
+ try { unlinkSync(join(runDir, STOP_FILE)); } catch { /* none pending */ }
181
+ }
182
+
183
+ /** The one reader of halt.json: `{ok:true, halt}`, `{ok:false, missing:true}` (not resumable), or `{ok:false, red}`. @param {string} runDir */
184
+ export function readHaltRecord(runDir) {
185
+ const r = readFileInside(runDir, HALT_FILE);
186
+ if (!r.ok) return r.missing ? { ok: false, missing: true } : { ok: false, red: `halt.json — ${r.red}` };
187
+ try { return { ok: true, halt: JSON.parse(r.text) }; } catch (err) { return { ok: false, red: `halt.json is not valid JSON — ${err.message}` }; }
188
+ }
189
+
83
190
  // ---------------------------------------------------------------------------
84
191
  // Money — piece 2 wires live provider rates; this piece takes a per-attempt
85
192
  // ceiling as injected data, defaulting to a frozen table's highest entry for
@@ -270,34 +377,6 @@ function hashFile(path) {
270
377
  return createHash('sha256').update(readFileSync(path)).digest('hex');
271
378
  }
272
379
 
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
380
  /** A run dir that already holds `ask.json`/`answer.json` from an earlier run
302
381
  * is a stale-answer hazard — refuse, never silently proceed or delete. */
303
382
  export function checkFreshRunDir(runDir) {
@@ -332,39 +411,85 @@ export function freezeInputs(runDir, sources) {
332
411
  return { ok: true, manifest };
333
412
  }
334
413
 
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).
414
+ /** realpath of a path that may not exist (falls back to the lexical resolve). */
415
+ function realOrResolved(p) {
416
+ try { return realpathSync(p); } catch { return resolve(p); }
417
+ }
418
+
419
+ const isInside = (child, base) => child === base || child.startsWith(base + sep);
420
+
421
+ /** The send target's folder (M4e amendment 1, "Destination is any folder").
422
+ * An absolute `file:/abs/path` is that folder, anywhere on the machine. A
423
+ * relative path keeps its M0/M2 meaning: joined onto the install folder and
424
+ * fenced inside it (lexically AND after realpath — a symlink inside the repo
425
+ * pointing outside must not pass). Either way, with `realpathSync` (symlinks
426
+ * followed), the folder must exist, be a folder, be writable, and must NOT be
427
+ * the run's own folder (its records and `inputs/`), the panel/CLI flow root, any flow
428
+ * folder under it (one holding a FLOW_FILES file) or `<root>/.drafts` or `<root>/.starts`, or the fwdloop config folder (holds the keys).
429
+ * Called at sign time and re-called at write time (time-of-check vs
430
+ * time-of-use, M0's own fix) — the one rule for both.
339
431
  * @param {string} target
432
+ * @param {{root?: string, runDir?: string}} [ctx] `root` = the flow root, `runDir` = this run's folder
340
433
  * @returns {{ok:true, dir:string} | {ok:false, red:string}} */
341
- export function checkSendDestination(target) {
434
+ export function checkSendDestination(target, ctx = {}) {
342
435
  const match = /^file:(.+)$/.exec(target ?? '');
343
436
  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})` };
437
+ const absolute = isAbsolute(match[1]);
438
+ const dir = absolute ? match[1] : join(REPO_ROOT, match[1]);
439
+ if (!absolute) {
440
+ const resolvedDir = resolve(dir);
441
+ const resolvedRoot = resolve(REPO_ROOT);
442
+ if (!isInside(resolvedDir, resolvedRoot)) {
443
+ return { ok: false, red: `destination: send target "${target}" resolves outside the repo (${dir})` };
444
+ }
445
+ try {
446
+ const realDir = realpathSync(dir);
447
+ const realRoot = realpathSync(REPO_ROOT);
448
+ if (!isInside(realDir, realRoot)) {
449
+ return {
450
+ ok: false,
451
+ red: `destination: send target "${target}" is a symlink that resolves outside the repo (${realDir})`,
452
+ };
453
+ }
454
+ } catch {
455
+ // dir doesn't exist — handled by the not-a-folder red below.
456
+ }
349
457
  }
458
+ let realDir;
350
459
  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
- }
460
+ realDir = realpathSync(dir);
461
+ if (!statSync(realDir).isDirectory()) throw new Error('not a directory');
359
462
  } catch {
360
- // dir doesn't exist yet — handled by the accessSync red below.
463
+ return { ok: false, red: `destination: send target "${target}" is not an existing folder (${dir})` };
464
+ }
465
+ const refused = [];
466
+ if (ctx.runDir) refused.push([realOrResolved(ctx.runDir), "the run's own folder (its records and inputs)"]);
467
+ refused.push([realOrResolved(configHome(configDoorHome().home)), 'the fwdloop config folder']);
468
+ if (ctx.root) {
469
+ const realRoot = realOrResolved(ctx.root);
470
+ if (realDir === realRoot) {
471
+ return { ok: false, red: `destination: send target "${target}" is the flow root (${realDir}) — refused` };
472
+ }
473
+ if (isInside(realDir, realRoot)) {
474
+ const child = realDir.slice(realRoot.length + 1).split(sep)[0];
475
+ const childDir = join(realRoot, child);
476
+ // a flow folder = holds any of the flow's own files (the same FLOW_FILES `src/flow.js` writes)
477
+ if (FLOW_FILES.some((f) => existsSync(join(childDir, f)))) refused.push([childDir, 'a flow folder']);
478
+ else if (child === '.drafts') refused.push([childDir, 'the panel drafts folder']);
479
+ else if (child === PANEL_STARTS_DIR) refused.push([childDir, 'the panel starts folder']);
480
+ }
481
+ }
482
+ for (const [base, what] of refused) {
483
+ if (isInside(realDir, base)) {
484
+ return { ok: false, red: `destination: send target "${target}" is ${what} (${realDir}) — refused` };
485
+ }
361
486
  }
362
487
  try {
363
488
  accessSync(dir, fsConstants.W_OK);
364
489
  } catch (err) {
365
490
  return { ok: false, red: `destination: send target directory "${dir}" is not writable (${err.code})` };
366
491
  }
367
- return { ok: true, dir };
492
+ return { ok: true, dir: absolute ? realDir : dir };
368
493
  }
369
494
 
370
495
  // ---------------------------------------------------------------------------
@@ -559,7 +684,7 @@ function makeAuditRow({
559
684
  * @param {Record<string, any>} [opts.primitivesMap]
560
685
  * @param {Record<string, any>} opts.readsMap
561
686
  * @param {string} opts.businessDate
562
- * @param {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class:string|null}) => Promise<any>} opts.modelStep
687
+ * @param {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class:string|null}, seam?:{stopRequested?:() => boolean}) => Promise<any>} opts.modelStep
563
688
  * @param {{ value: number }} opts.spent
564
689
  * @param {number} opts.capUsd
565
690
  * @param {number} opts.ceilingUsd
@@ -568,7 +693,11 @@ function makeAuditRow({
568
693
  * @param {number} [opts.attemptOffset]
569
694
  * @param {() => string} [opts.now] - M4a-2: stamps each audit row's `at`;
570
695
  * defaults to the real wall clock.
571
- * @returns {Promise<{ok:true, artifact:any, attempts:number, hitl?:boolean} | {ok:false, outcome:string, red:string}>}
696
+ * @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
697
+ * @param {number} [opts.stepNo] - this step's 1-based number, for the words of a stop row
698
+ * @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
699
+ * @param {number} [opts.triesDone] - tries a Stop already closed on this step (they count against its limit)
700
+ * @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
701
  */
573
702
  async function runStepRalph({
574
703
  step, primitivesMap, readsMap, businessDate, modelStep, spent, capUsd, ceilingUsd, recordAudit, initialGap = null, attemptOffset = 0,
@@ -578,14 +707,37 @@ async function runStepRalph({
578
707
  // none left in production; a defensive default only) still writes a valid
579
708
  // ISO string.
580
709
  now = () => new Date().toISOString(),
710
+ // 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
711
+ // `readStopRequest`); `stepNo` is this step's 1-based number for the words of the stop row; `triesDone` is the tries a Stop already
712
+ // 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
713
+ // against the limit, so Resume always gets at least one new try).
714
+ readStop = null, stepNo = 0, triesDone = 0,
715
+ // 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
716
+ prevStepId = null,
581
717
  }) {
582
718
  /** @type {string|null} */
583
719
  let gap = initialGap ?? null;
584
720
  let strikes = 0;
585
721
  const seenGaps = new Set();
722
+ const maxN = MAX_ATTEMPTS - triesDone;
723
+ let lastTurns = null;
724
+ const stopWords = (tryNo, turns) => (turns > 0
725
+ ? `stopped after turn ${turns} of try ${tryNo} of step ${stepNo}`
726
+ : (tryNo > 0 ? `stopped after try ${tryNo} of step ${stepNo}` : (stepNo > 1 ? `stopped after step ${stepNo - 1}` : 'stopped before step 1')));
727
+ /** The ralph's return for a Stop: the cut try's own row fields (`book`) ride the one `stopped` row `settleStop` writes.
728
+ * @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}}} */
729
+ const stopped = (where, book = {}) => ({
730
+ ok: false,
731
+ outcome: 'stopped',
732
+ red: `stopped by you — ${where}`,
733
+ // 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
734
+ stop: { where, book, step: where === stopWords(0, 0) ? prevStepId : (step?.emits ?? step?.goal ?? null) },
735
+ });
586
736
 
587
- for (let n = 1; n <= MAX_ATTEMPTS; n += 1) {
737
+ for (let n = 1; n <= maxN; n += 1) {
588
738
  const attempt = attemptOffset + n;
739
+ // Between tries: the previous try closed red, no new model call has started — a pending Stop ends the run here.
740
+ if (n > 1 && readStop && readStop()) return stopped(stopWords(attempt - 1, lastTurns ?? 0));
589
741
  // This attempt's known floor from a FIRST transport fault that then
590
742
  // retried — every audit row this attempt still writes must carry this
591
743
  // floor summed with its own cost (F41 books gap: the fault's cost was
@@ -615,9 +767,11 @@ async function runStepRalph({
615
767
  // construction test below proves the context itself stays clean).
616
768
  const stepMeta = Object.freeze({ class: step.close?.class ?? null });
617
769
 
770
+ const stopSeam = readStop ? Object.freeze({ stopRequested: readStop }) : undefined;
771
+
618
772
  const startedAt = Date.now();
619
773
  // eslint-disable-next-line no-await-in-loop
620
- let result = await modelStep(executorContext, grantedTools, stepMeta);
774
+ let result = await modelStep(executorContext, grantedTools, stepMeta, stopSeam);
621
775
  if (result && result.ok === false && result.transport === true) {
622
776
  // A known partial cost from the FIRST transport fault must survive as
623
777
  // the floor even though this attempt goes on to retry — never
@@ -633,7 +787,7 @@ async function runStepRalph({
633
787
  // `transport: true` shape, exactly once.
634
788
  const first = result;
635
789
  // eslint-disable-next-line no-await-in-loop
636
- result = await modelStep(executorContext, grantedTools, stepMeta);
790
+ result = await modelStep(executorContext, grantedTools, stepMeta, stopSeam);
637
791
  // The first call's gate refusals and tool tally belong to this attempt's
638
792
  // audit row too (the retry's collector starts empty). Only refused /
639
793
  // tools / ungranted are merged — cost is never touched here.
@@ -647,6 +801,19 @@ async function runStepRalph({
647
801
  }
648
802
  const wallMs = Date.now() - startedAt;
649
803
 
804
+ // 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
805
+ // `stopped` row), no new call started. Unknown cost stays unknown (usd null, spend incomplete), never 0.
806
+ const turns = typeof result?.turns === 'number' ? result.turns : null;
807
+ lastTurns = turns;
808
+ if (result && result.ok === false && result.stopped === true) {
809
+ if (typeof result.costUsd === 'number') spent.value += result.costUsd;
810
+ const usd = sumKnownUsd(attemptFloorUsd, result.costUsd);
811
+ const ranCalls = (turns ?? 0) > 0 || attemptFloorUsd !== null;
812
+ return stopped(stopWords(ranCalls ? attempt : attempt - 1, turns ?? 0), makeAuditRow({
813
+ 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,
814
+ }));
815
+ }
816
+
650
817
  if (result && result.ok === false && result.transport === true) {
651
818
  if (typeof result.costUsd === 'number') spent.value += result.costUsd;
652
819
  // Both faults' known costs, summed — the first fault's floor was
@@ -673,7 +840,7 @@ async function runStepRalph({
673
840
  recordAudit(makeAuditRow({
674
841
  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
842
  }), red);
676
- if (n === MAX_ATTEMPTS) return { ok: false, outcome: 'attempt-fallback', red: `attempt-fallback: step "${step.goal}" — ${red}` };
843
+ if (n === maxN) return { ok: false, outcome: 'attempt-fallback', red: `attempt-fallback: step "${step.goal}" — ${red}` };
677
844
  if (strikes >= STRIKE_LIMIT) return { ok: false, outcome: 'struck-out', red: `struck-out: step "${step.goal}" — ${red}` };
678
845
  gap = red;
679
846
  // eslint-disable-next-line no-continue
@@ -712,14 +879,14 @@ async function runStepRalph({
712
879
  recordAudit(makeAuditRow({
713
880
  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
881
  }), result.artifact ?? null);
715
- if (n === MAX_ATTEMPTS) return { ok: false, outcome: 'attempt-fallback', red: `attempt-fallback: ${happened.red}` };
882
+ if (n === maxN) return { ok: false, outcome: 'attempt-fallback', red: `attempt-fallback: ${happened.red}` };
716
883
  if (strikes >= STRIKE_LIMIT) return { ok: false, outcome: 'struck-out', red: `struck-out: ${happened.red}` };
717
884
  gap = happened.red ?? null;
718
885
  // eslint-disable-next-line no-continue
719
886
  continue;
720
887
  }
721
888
 
722
- const closed = closeByClass(step, artifact, { reads: readsMap, businessDate });
889
+ const closed = await closeByClass(step, artifact, { reads: readsMap, businessDate });
723
890
 
724
891
  if (closed.verdict === 'green' || closed.verdict === 'hitl') {
725
892
  recordAudit(makeAuditRow({
@@ -747,7 +914,7 @@ async function runStepRalph({
747
914
  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
915
  }), result.artifact);
749
916
 
750
- if (n === MAX_ATTEMPTS) return { ok: false, outcome: 'attempt-fallback', red: `attempt-fallback: step "${step.goal}" — ${closed.red}` };
917
+ if (n === maxN) return { ok: false, outcome: 'attempt-fallback', red: `attempt-fallback: step "${step.goal}" — ${closed.red}` };
751
918
  if (strikes >= STRIKE_LIMIT) return { ok: false, outcome: 'struck-out', red: `struck-out: step "${step.goal}" — ${closed.red}` };
752
919
  gap = closed.red ?? null;
753
920
  }
@@ -824,15 +991,22 @@ export async function runFlow({
824
991
  return { outcome: 'refused', red: read.reds[0], reds: read.reds };
825
992
  }
826
993
 
827
- const { arbiter, declaration, signature } = read;
994
+ const { declaration, signature } = read;
995
+ const runDir = runIdCheck.runDir;
996
+ // 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`).
997
+ const applied = applyRunValues(read.arbiter, name, signature.flow, pickRunValues(runDir));
998
+ if (!applied.ok) {
999
+ return haltRun({
1000
+ flowDir, runDir, runId, capUsd: null, startedAt, now, nowMs: getNowMs, signatureHash: signature.flow, outcome: 'preflight-red', red: applied.red, spent: { value: 0 },
1001
+ });
1002
+ }
1003
+ const { arbiter } = applied;
828
1004
  const capUsd = arbiter.capUsd;
829
1005
  const redoCap = arbiter.redoCap ?? 3;
830
1006
  const effectiveCeilingUsd = ceilingUsd ?? resolveCeilingUsd(null);
831
1007
  const askLines = new Map((arbiter.asks ?? []).map((a) => [a.line, a]));
832
1008
  const sendLines = new Map((arbiter.sends ?? []).map((s) => [s.line, s]));
833
1009
 
834
- const runDir = runIdCheck.runDir;
835
-
836
1010
  const unwiredVerb = findUnwiredVerbStep(declaration);
837
1011
  if (unwiredVerb) {
838
1012
  return haltRun({
@@ -845,11 +1019,19 @@ export async function runFlow({
845
1019
  nowMs: getNowMs,
846
1020
  signatureHash: signature.flow,
847
1021
  outcome: 'preflight-red',
848
- red: `preflight: step "${unwiredVerb.step.emits}" (line ${unwiredVerb.step.fromLine}) grants verb "${unwiredVerb.verb}", which has no wired implementation`,
1022
+ red: unwiredRed(unwiredVerb),
849
1023
  spent: { value: 0 },
850
1024
  });
851
1025
  }
852
1026
 
1027
+ // M4e amendment 19 4: every softgreen check is built before the first model call; one that cannot be built is refused at $0, by step name
1028
+ const unbuildable = findUnbuildableCheckStep(declaration);
1029
+ if (unbuildable) {
1030
+ return haltRun({
1031
+ flowDir, runDir, runId, capUsd, startedAt, now, nowMs: getNowMs, signatureHash: signature.flow, outcome: 'preflight-red', red: unbuildableRed(unbuildable), detail: unbuildable.why, spent: { value: 0 },
1032
+ });
1033
+ }
1034
+
853
1035
  if (primitiveReds?.length) {
854
1036
  return haltRun({
855
1037
  flowDir, runDir, runId, capUsd, startedAt, now, nowMs: getNowMs, signatureHash: signature.flow, outcome: 'preflight-red', red: primitiveReds[0], spent: { value: 0 },
@@ -1031,7 +1213,7 @@ function makeOneShotThenParkAskStep({ decision, reason, artifactSha256 }) {
1031
1213
  * @returns {Promise<any>}
1032
1214
  */
1033
1215
  async function runAskSlot({
1034
- step, stepIndex, askSlot, priorId, priorStep, priorArtifact, redoCap, effectiveCeilingUsd, capUsd,
1216
+ step, stepIndex, askSlot, priorId, priorStep, priorStepNo, priorPrevStepId = null, priorArtifact, redoCap, effectiveCeilingUsd, capUsd,
1035
1217
  primitives, businessDate, modelStep, askStep, spent, spendComplete, recordAudit,
1036
1218
  evidenceUnjudged, unjudgedCount, redone: initialRedone,
1037
1219
  runDir, flowDir, runId, flowRoot, flowName, signatureHash, inputsManifest, attemptsLog, artifacts, now, startedAt,
@@ -1052,6 +1234,17 @@ async function runAskSlot({
1052
1234
  // M4b amendment 3: a decision from any askStep is translated once, here.
1053
1235
  const answer = { ...rawAnswer, decision: normalizeDecision(rawAnswer.decision) };
1054
1236
 
1237
+ if (answer.decision === 'park' && stopPending(runDir)) {
1238
+ // 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.
1239
+ return {
1240
+ type: 'halted',
1241
+ outcome: 'stopped',
1242
+ red: `stopped by you at the ask of step ${stepIndex + 1} ("${step.goal}")`,
1243
+ stop: { where: `stopped at the ask of step ${stepIndex + 1}`, step: step.emits ?? step.goal ?? null },
1244
+ redone,
1245
+ };
1246
+ }
1247
+
1055
1248
  if (answer.decision === 'park') {
1056
1249
  // M3 scope item 1 (fixes F43): the wait is ALWAYS the signed ttlMs —
1057
1250
  // no code default ever overrides it, on the first park or any re-park.
@@ -1128,6 +1321,15 @@ async function runAskSlot({
1128
1321
  // at its final outcome (complete / a halt / ask-expired), written by
1129
1322
  // `foldFromStep`/`resumeRun`, never here.
1130
1323
  writeLog(runDir, { runId, outcome: 'paused', attempts: attemptsLog, artifacts });
1324
+ // 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
1325
+ // (the ask is set aside; one winner against the Stop door, by rename).
1326
+ if (stopPending(runDir)) {
1327
+ const stopped = stopAtAsk({
1328
+ flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, signatureHash, spent, spendComplete: spendComplete.value, attempts: attemptsLog, artifacts,
1329
+ stepIndex, stepEmits: step.emits ?? step.goal ?? null, flowRoot, flowName, inputsManifest, unjudged: evidenceUnjudged, redone, parkedAskId: askId,
1330
+ });
1331
+ if (stopped && stopped.outcome !== 'stop-failed') return { type: 'stopped', result: stopped };
1332
+ }
1131
1333
  return {
1132
1334
  type: 'paused',
1133
1335
  result: {
@@ -1196,9 +1398,12 @@ async function runAskSlot({
1196
1398
  // eslint-disable-next-line no-await-in-loop
1197
1399
  const redoResult = await runStepRalph({
1198
1400
  step: priorStep, primitivesMap: primitives, readsMap: priorReadsResult.map, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, initialGap: reason, attemptOffset: redone, now,
1401
+ readStop: () => stopPending(runDir), stepNo: priorStepNo, prevStepId: priorPrevStepId,
1199
1402
  });
1200
1403
  if (!redoResult.ok) {
1201
- return { type: 'halted', outcome: redoResult.outcome, red: redoResult.red };
1404
+ return {
1405
+ type: 'halted', outcome: redoResult.outcome, red: redoResult.red, ...(redoResult.stop ? { stop: redoResult.stop } : {}),
1406
+ };
1202
1407
  }
1203
1408
  currentPrior = redoResult.artifact;
1204
1409
  // A redo deliberately REPLACES the prior step's own artifact — the one
@@ -1245,6 +1450,11 @@ async function foldFromStep({
1245
1450
  // `@param {object} opts` this function's block comment never declared)
1246
1451
  // is what keeps every OTHER destructured field's inferred type intact.
1247
1452
  firstStepGap = /** @type {string|null} */ (null),
1453
+ // 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
1454
+ // wear numbers (the new one is numbered after them), `done` of them closed and count against the step's limit.
1455
+ resumeTries = { numbered: 0, done: 0 },
1456
+ // Amendment 13: the redo count a stop-at-ask carried in its halt record, restored for the ask step it re-enters (`i0`).
1457
+ resumeRedone = 0,
1248
1458
  }) {
1249
1459
  let runAcceptedThisRun = acceptedThisRun;
1250
1460
  let runUnjudged = unjudgedSinceLastAsk;
@@ -1252,6 +1462,24 @@ async function foldFromStep({
1252
1462
  for (let i = i0; i < steps.length; i += 1) {
1253
1463
  const step = steps[i];
1254
1464
 
1465
+ // M4e amendment 4 item 4: the Stop seam. Step i-1 has closed (artifact written, rows booked); a pending request ends the run here.
1466
+ // Amendment 7 item 8 adds the same seam before every model call (turns and tries, inside `runStepRalph`/`modelStep`).
1467
+ if (stopPending(runDir)) {
1468
+ // Amendment 13: when the turn that just closed leads to an ask, the run stops AT the ask, in the ask's words.
1469
+ if (askLines.has(step.fromLine)) {
1470
+ return stopAtAsk({
1471
+ flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, spendComplete: spendComplete.value, attempts: attemptsLog, artifacts,
1472
+ stepIndex: i, stepEmits: step.emits ?? step.goal ?? null, flowRoot, flowName, inputsManifest, unjudged: runUnjudged, redone: i === i0 ? resumeRedone : 0,
1473
+ });
1474
+ }
1475
+ return haltRun({
1476
+ flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts,
1477
+ outcome: 'stopped', red: `stopped by you before step ${i + 1} ("${step.goal}")`,
1478
+ 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) },
1479
+ resumeAt: { stepIndex: i, flowRoot, flowName, inputsManifest, unjudged: runUnjudged },
1480
+ });
1481
+ }
1482
+
1255
1483
  // --- the signed send slot: never through modelStep, only after an
1256
1484
  // accept THIS run, re-checked at write time. ---
1257
1485
  if (sendLines.has(step.fromLine)) {
@@ -1302,9 +1530,9 @@ async function foldFromStep({
1302
1530
  });
1303
1531
  }
1304
1532
  const content = contentResult.value;
1305
- const filename = `${runId}-${step.emits}.json`;
1533
+ const filename = `${flowName}-${runId}-${step.emits}.json`;
1306
1534
  // eslint-disable-next-line no-await-in-loop
1307
- const sendResult = await sendStep(target, filename, content, acceptedAskEmitsThisRun.get(askArtifactId));
1535
+ const sendResult = await sendStep(target, filename, content, acceptedAskEmitsThisRun.get(askArtifactId), { root: flowRoot, runDir });
1308
1536
  const sendRow = makeAuditRow({
1309
1537
  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
1538
  });
@@ -1357,6 +1585,8 @@ async function foldFromStep({
1357
1585
  askSlot,
1358
1586
  priorId,
1359
1587
  priorStep: steps[priorStepIndex],
1588
+ priorStepNo: priorStepIndex + 1,
1589
+ priorPrevStepId: priorStepIndex > 0 ? (steps[priorStepIndex - 1].emits ?? null) : null,
1360
1590
  priorArtifact,
1361
1591
  redoCap,
1362
1592
  effectiveCeilingUsd,
@@ -1370,7 +1600,7 @@ async function foldFromStep({
1370
1600
  recordAudit,
1371
1601
  evidenceUnjudged,
1372
1602
  unjudgedCount,
1373
- redone: 0,
1603
+ redone: i === i0 ? resumeRedone : 0,
1374
1604
  runDir,
1375
1605
  flowDir,
1376
1606
  runId,
@@ -1385,10 +1615,14 @@ async function foldFromStep({
1385
1615
  runStartedAt,
1386
1616
  });
1387
1617
 
1388
- if (askResult.type === 'paused') return askResult.result;
1618
+ if (askResult.type === 'paused' || askResult.type === 'stopped') return askResult.result;
1389
1619
  if (askResult.type === 'halted') {
1390
1620
  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,
1621
+ 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,
1622
+ ...(askResult.stop ? { stop: askResult.stop } : {}),
1623
+ resumeAt: {
1624
+ stepIndex: i, flowRoot, flowName, inputsManifest, unjudged: evidenceUnjudged, redone: askResult.redone,
1625
+ },
1392
1626
  });
1393
1627
  }
1394
1628
 
@@ -1419,10 +1653,13 @@ async function foldFromStep({
1419
1653
  // eslint-disable-next-line no-await-in-loop
1420
1654
  const stepResult = await runStepRalph({
1421
1655
  step, primitivesMap: primitives, readsMap, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, initialGap: i === i0 ? firstStepGap : null, now,
1656
+ 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
1657
  });
1423
1658
  if (!stepResult.ok) {
1424
1659
  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,
1660
+ 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,
1661
+ ...(stepResult.stop ? { stop: stepResult.stop } : {}),
1662
+ resumeAt: { stepIndex: i, flowRoot, flowName, inputsManifest, unjudged: runUnjudged },
1426
1663
  });
1427
1664
  }
1428
1665
  writeArtifact(runDir, step.emits, stepResult.artifact);
@@ -1442,13 +1679,18 @@ async function foldFromStep({
1442
1679
  // run really was sitting there waiting on a human, so it belongs in
1443
1680
  // "how long did this run take", not carved out of it.
1444
1681
  const wallMs = nowMs() - runStartedAt;
1445
- appendHistory(flowDir, {
1446
- runId, at: now(), outcome: 'complete', spentUsd: spent.value, spendComplete: spendComplete.value, capUsd, wallMs, signatureHash,
1447
- });
1448
- recordLateAnswerIfAny(runDir, now);
1449
- writeLog(runDir, {
1450
- runId, outcome: 'complete', attempts: attemptsLog, artifacts,
1451
- });
1682
+ try {
1683
+ recordLateAnswerIfAny(runDir, now);
1684
+ writeLog(runDir, {
1685
+ runId, outcome: 'complete', attempts: attemptsLog, artifacts,
1686
+ });
1687
+ settleStop({ runDir, now, outcome: 'complete' });
1688
+ } finally {
1689
+ // Amendment 16 C6/C7: the history end row is written last, and always.
1690
+ appendHistory(flowDir, {
1691
+ runId, at: now(), outcome: 'complete', spentUsd: spent.value, spendComplete: spendComplete.value, capUsd, wallMs, signatureHash,
1692
+ });
1693
+ }
1452
1694
  return {
1453
1695
  outcome: 'complete', runDir, artifacts, spentUsd: spent.value,
1454
1696
  };
@@ -1465,17 +1707,19 @@ async function foldFromStep({
1465
1707
  * resumable run's audit.jsonl). A row this function cannot price refuses
1466
1708
  * rather than guessing (never `?? 0`, never skipped).
1467
1709
  * @param {string} runDir
1468
- * @returns {{ ok: true, total: number } | { ok: false, red: string }}
1710
+ * @param {{skipVerdicts?: string[]}} [opts]
1711
+ * @returns {{ ok: true, total: number, complete: boolean } | { ok: false, red: string }}
1469
1712
  */
1470
- function sumAuditUsd(runDir) {
1713
+ function sumAuditUsd(runDir, { skipVerdicts = /** @type {string[]} */ ([]) } = {}) {
1471
1714
  // F48 round 3: goes through `readFileInside` (`src/flow.js`) rather than a
1472
1715
  // raw `readFileSync` — a symlinked `audit.jsonl` (or a symlinked ancestor
1473
1716
  // directory) reads as "missing" (total 0), never as some outside file's
1474
1717
  // content summed into a cap check.
1475
1718
  const result = readFileInside(runDir, 'audit.jsonl');
1476
- if (!result.ok) return { ok: true, total: 0 };
1719
+ if (!result.ok) return { ok: true, total: 0, complete: true };
1477
1720
  const lines = result.text.split('\n').filter((line) => line.trim().length > 0);
1478
1721
  let total = 0;
1722
+ let complete = true;
1479
1723
  for (const line of lines) {
1480
1724
  let row;
1481
1725
  try {
@@ -1483,12 +1727,15 @@ function sumAuditUsd(runDir) {
1483
1727
  } catch (err) {
1484
1728
  return { ok: false, red: `audit.jsonl line is not valid JSON — ${err.message}` };
1485
1729
  }
1730
+ // a row of a verdict the caller names cost nothing and carries `usd: null` on purpose (a cap-halt: the round was never bought)
1731
+ if (skipVerdicts.includes(row.verdict)) continue;
1732
+ if (row.spendComplete === false) complete = false;
1486
1733
  if (typeof row.usd !== 'number' || !Number.isFinite(row.usd)) {
1487
1734
  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
1735
  }
1489
1736
  total += row.usd;
1490
1737
  }
1491
- return { ok: true, total };
1738
+ return { ok: true, total, complete };
1492
1739
  }
1493
1740
 
1494
1741
  /** Unlink `resume.lock` only when its recorded holder is still THIS process (`readResumeLock`'s holder pid + start
@@ -1582,12 +1829,15 @@ function sameRoot(recorded, requested) {
1582
1829
  * @param {string} opts.businessDate
1583
1830
  * @param {number} [opts.ceilingUsd]
1584
1831
  * @param {() => number} [opts.nowMs] - F45 finding 3; see `runFlow`'s own.
1832
+ * @param {(newRunDir:string) => void} [opts.onRerunStart] - amendment 16 C2: called with the new run's folder just before a `rerun` starts it.
1585
1833
  */
1586
1834
  export async function resumeRun({
1587
1835
  root, name, runId, catalogue, modelStep, sendStep, primitives, primitiveReds, clock, businessDate, ceilingUsd,
1588
1836
  // F45 finding 3 (see `runFlow`'s own `nowMs`): additive, defaults to the
1589
1837
  // real `Date.now` for every existing caller.
1590
1838
  nowMs,
1839
+ // Amendment 16 C2: called with the new run's folder just before a `rerun` starts it, so the caller can name it in the money records.
1840
+ onRerunStart,
1591
1841
  }) {
1592
1842
  const now = typeof clock === 'function' ? clock : () => new Date().toISOString();
1593
1843
  const getNowMs = typeof nowMs === 'function' ? nowMs : Date.now;
@@ -1616,9 +1866,11 @@ export async function resumeRun({
1616
1866
  if (unwiredVerb) {
1617
1867
  return {
1618
1868
  outcome: 'refused',
1619
- red: `preflight: step "${unwiredVerb.step.emits}" (line ${unwiredVerb.step.fromLine}) grants verb "${unwiredVerb.verb}", which has no wired implementation`,
1869
+ red: unwiredRed(unwiredVerb),
1620
1870
  };
1621
1871
  }
1872
+ const unbuildable = findUnbuildableCheckStep(preflightRead.declaration);
1873
+ if (unbuildable) return { outcome: 'refused', red: unbuildableRed(unbuildable), detail: unbuildable.why };
1622
1874
  }
1623
1875
 
1624
1876
  if (primitiveReds?.length) return { outcome: 'refused', red: primitiveReds[0] };
@@ -1675,7 +1927,11 @@ export async function resumeRun({
1675
1927
  if (!read.ok) {
1676
1928
  return { outcome: 'refused', red: `resume: flow re-read failed for run "${runId}": ${read.reds.join('; ')}` };
1677
1929
  }
1678
- const { declaration, arbiter, signature } = read;
1930
+ const { declaration, signature } = read;
1931
+ // M4e amendment 5 item 3 / amendment 4 item 6: the run's own signed values (its highest version) lie over the flow's.
1932
+ const applied = applyRunValues(read.arbiter, name, signature.flow, pickRunValues(runDir));
1933
+ if (!applied.ok) return { outcome: 'refused', red: `resume: run "${runId}" — ${applied.red}` };
1934
+ const { arbiter } = applied;
1679
1935
 
1680
1936
  if (signature.flow !== state.signatureHash) {
1681
1937
  return { outcome: 'refused', red: `resume: signature mismatch for run "${runId}" — the flow changed while parked` };
@@ -1807,6 +2063,23 @@ export async function resumeRun({
1807
2063
  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
2064
  }
1809
2065
 
2066
+ // M4e amendment 13: a Stop asked STRICTLY before this answer was saved was asked of a run that was waiting (it landed after the
2067
+ // 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
2068
+ // 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
2069
+ // 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
2070
+ // time is read as made "now" by `readStopRequest` (amendment 17 2A, one rule), which is after the answer: the answer wins.
2071
+ const stopReq = readStopRequest(runDir, now);
2072
+ const stopFirst = stopReq !== null && Date.parse(/** @type {string} */ (stopReq.at)) < Date.parse(answer.answeredAt);
2073
+ if (stopReq && stopFirst) {
2074
+ const prev = readLog(runDir);
2075
+ return stopAtAsk({
2076
+ flowDir, runDir, runId, capUsd: arbiter.capUsd ?? null, startedAt: runStartedAt, now, nowMs: getNowMs, signatureHash: state.signatureHash, spent, spendComplete: spendComplete.value,
2077
+ attempts: Array.isArray(prev?.attempts) ? prev.attempts : [], artifacts: prev?.artifacts && typeof prev.artifacts === 'object' ? prev.artifacts : {},
2078
+ stepIndex: state.stepIndex, stepEmits: steps[state.stepIndex]?.emits ?? null, flowRoot: root, flowName: name, inputsManifest: state.inputsManifest,
2079
+ unjudged: state.evidenceUnjudged ?? [], redone: typeof state.redone === 'number' ? state.redone : 0, parkedAskId: state.askId,
2080
+ });
2081
+ }
2082
+
1810
2083
  // M4b amendment 2: hashes recorded by earlier-process accepts, read back
1811
2084
  // from the archive + consumed markers. Refused BEFORE the consume below so
1812
2085
  // the answer stays replayable.
@@ -1858,11 +2131,15 @@ export async function resumeRun({
1858
2131
  for (let i = 0; i < state.stepIndex; i += 1) {
1859
2132
  priorArtifactsForLog[steps[i].emits] = readArtifact(runDir, steps[i].emits);
1860
2133
  }
1861
- appendHistory(flowDir, {
1862
- runId, at: now(), outcome: 'rerun', spentUsd: spent.value, spendComplete: spendComplete.value, capUsd: arbiter.capUsd ?? null, wallMs: getNowMs() - runStartedAt, signatureHash: state.signatureHash,
1863
- });
1864
- recordLateAnswerIfAny(runDir, now);
1865
- writeLog(runDir, { runId, outcome: 'rerun', attempts: [], artifacts: priorArtifactsForLog });
2134
+ try {
2135
+ recordLateAnswerIfAny(runDir, now);
2136
+ writeLog(runDir, { runId, outcome: 'rerun', attempts: [], artifacts: priorArtifactsForLog });
2137
+ } finally {
2138
+ // Amendment 16 C6/C7: the history end row is written last, and always.
2139
+ appendHistory(flowDir, {
2140
+ runId, at: now(), outcome: 'rerun', spentUsd: spent.value, spendComplete: spendComplete.value, capUsd: arbiter.capUsd ?? null, wallMs: getNowMs() - runStartedAt, signatureHash: state.signatureHash,
2141
+ });
2142
+ }
1866
2143
 
1867
2144
  // Deterministic derived id (M3 scope item 7) — refused by name, never
1868
2145
  // silently renumbered, if it already exists.
@@ -1881,6 +2158,7 @@ export async function resumeRun({
1881
2158
  // they aren't already" — they already are, via this field).
1882
2159
  const rerunSources = (state.inputsManifest ?? []).map((entry) => ({ id: entry.id, path: entry.source }));
1883
2160
 
2161
+ if (typeof onRerunStart === 'function') onRerunStart(newRunDir);
1884
2162
  const newRun = await runFlow({
1885
2163
  root,
1886
2164
  name,
@@ -1967,6 +2245,8 @@ export async function resumeRun({
1967
2245
  askSlot,
1968
2246
  priorId,
1969
2247
  priorStep: steps[priorStepIndex],
2248
+ priorStepNo: priorStepIndex + 1,
2249
+ priorPrevStepId: priorStepIndex > 0 ? (steps[priorStepIndex - 1].emits ?? null) : null,
1970
2250
  priorArtifact,
1971
2251
  redoCap,
1972
2252
  effectiveCeilingUsd,
@@ -1995,10 +2275,14 @@ export async function resumeRun({
1995
2275
  runStartedAt,
1996
2276
  });
1997
2277
 
1998
- if (askResult.type === 'paused') return askResult.result;
2278
+ if (askResult.type === 'paused' || askResult.type === 'stopped') return askResult.result;
1999
2279
  if (askResult.type === 'halted') {
2000
2280
  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,
2281
+ 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,
2282
+ ...(askResult.stop ? { stop: askResult.stop } : {}),
2283
+ resumeAt: {
2284
+ stepIndex: state.stepIndex, flowRoot: root, flowName: name, inputsManifest: state.inputsManifest, unjudged: state.evidenceUnjudged ?? [], redone: askResult.redone,
2285
+ },
2002
2286
  });
2003
2287
  }
2004
2288
 
@@ -2054,6 +2338,301 @@ export async function resumeRun({
2054
2338
  }
2055
2339
  }
2056
2340
 
2341
+ /**
2342
+ * 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
2343
+ * row cost nothing and carries no number), and whether any row left the total a floor. Used by `continueRun` and the CLI's hold.
2344
+ * @param {string} runDir
2345
+ * @returns {{ ok: true, total: number, complete: boolean } | { ok: false, red: string }}
2346
+ */
2347
+ export function auditSpend(runDir) {
2348
+ return sumAuditUsd(runDir, { skipVerdicts: ['cap-halt'] });
2349
+ }
2350
+
2351
+ /**
2352
+ * 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
2353
+ * same exclusive `resume.lock` as an answer-resume (one resume at a time per run), reads `halt.json` (the runner's own record of
2354
+ * where it stopped), re-verifies the flow's signature, the frozen inputs and every finished step's artifact, lays the run's
2355
+ * highest signed values version over the flow's (`pickRunValues`: the human's new cap lives there, write-once, never in the flow's
2356
+ * own files), refuses by name at $0 when that cap is not above what is already spent, consumes `halt.json` by rename (the
2357
+ * 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
2358
+ * far (re-summed from the books) counts against the new cap, the plan is never redrawn.
2359
+ *
2360
+ * @param {object} opts same shape as `resumeRun`'s
2361
+ * @param {string} opts.root
2362
+ * @param {string} opts.name
2363
+ * @param {string} opts.runId
2364
+ * @param {unknown} opts.catalogue
2365
+ * @param {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class:string|null}) => Promise<any>} opts.modelStep
2366
+ * @param {(target:string, filename:string, content:unknown) => Promise<{ok:boolean, red?:string, bytes?:number}>} opts.sendStep
2367
+ * @param {Record<string, any>} [opts.primitives]
2368
+ * @param {string[]} [opts.primitiveReds]
2369
+ * @param {() => string} [opts.clock]
2370
+ * @param {string} opts.businessDate
2371
+ * @param {number} [opts.ceilingUsd]
2372
+ * @param {() => number} [opts.nowMs]
2373
+ */
2374
+ export async function continueRun({
2375
+ root, name, runId, catalogue, modelStep, sendStep, primitives, primitiveReds, clock, businessDate, ceilingUsd, nowMs,
2376
+ }) {
2377
+ const now = typeof clock === 'function' ? clock : () => new Date().toISOString();
2378
+ const getNowMs = typeof nowMs === 'function' ? nowMs : Date.now;
2379
+ const flowDir = join(root, name);
2380
+ const startedAt = getNowMs();
2381
+ const refused = (red, detail) => ({ outcome: 'refused', red: `continue: ${red}`, ...(detail ? { detail } : {}) });
2382
+
2383
+ const runIdCheck = resolveRunDir(flowDir, runId);
2384
+ if (!runIdCheck.ok) return { outcome: 'refused', red: runIdCheck.red };
2385
+ const runDir = runIdCheck.runDir;
2386
+
2387
+ const preflightRead = readFlow({ root, name, catalogue });
2388
+ if (preflightRead.ok) {
2389
+ const unwiredVerb = findUnwiredVerbStep(preflightRead.declaration);
2390
+ if (unwiredVerb) return refused(unwiredRed(unwiredVerb));
2391
+ const unbuildable = findUnbuildableCheckStep(preflightRead.declaration);
2392
+ if (unbuildable) return refused(unbuildableRed(unbuildable), unbuildable.why);
2393
+ }
2394
+ if (primitiveReds?.length) return refused(primitiveReds[0]);
2395
+
2396
+ const lockPath = join(runDir, 'resume.lock');
2397
+ const took = await takeResumeLock(runDir, runId, lockPath);
2398
+ if (!took.ok) return { outcome: 'refused', red: took.red };
2399
+ const { lockFd } = took;
2400
+
2401
+ try {
2402
+ const haltRead = readHaltRecord(runDir);
2403
+ if (!haltRead.ok) {
2404
+ return refused(haltRead.missing
2405
+ ? `run "${runId}" was not stopped or cap-halted by this version (no halt record) — there is nothing to continue; start a new run`
2406
+ : `run "${runId}" ${haltRead.red}`);
2407
+ }
2408
+ const { halt } = haltRead;
2409
+ if (!sameRoot(halt.flow?.root, root) || halt.flow?.name !== name) {
2410
+ 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`);
2411
+ }
2412
+ if (!Number.isInteger(halt.stepIndex) || halt.stepIndex < 0) return refused(`run "${runId}" halt.json field "stepIndex" is not a step number`);
2413
+
2414
+ const read = readFlow({ root, name, catalogue });
2415
+ if (!read.ok) return refused(`flow re-read failed for run "${runId}": ${read.reds.join('; ')}`);
2416
+ const { declaration, signature } = read;
2417
+ if (signature.flow !== halt.signatureHash) return refused(`signature mismatch for run "${runId}" — the flow changed while it was halted`);
2418
+ // the human's signed values for this run (its highest version): the new cap is read from here, nowhere else
2419
+ const applied = applyRunValues(read.arbiter, name, signature.flow, pickRunValues(runDir));
2420
+ if (!applied.ok) return refused(`run "${runId}" — ${applied.red}`);
2421
+ const { arbiter } = applied;
2422
+
2423
+ for (const entry of halt.inputsManifest ?? []) {
2424
+ if (!existsSync(entry.frozen)) return refused(`frozen input "${entry.id}" missing for run "${runId}" (${entry.frozen})`);
2425
+ if (createHash('sha256').update(readFileSync(entry.frozen)).digest('hex') !== entry.sha256) {
2426
+ return refused(`frozen input "${entry.id}" changed while halted for run "${runId}"`);
2427
+ }
2428
+ }
2429
+
2430
+ const { steps } = declaration;
2431
+ if (halt.stepIndex > steps.length) return refused(`run "${runId}" halt.json names step ${halt.stepIndex}, past this flow's ${steps.length} steps`);
2432
+ /** @type {Record<string, any>} */
2433
+ const artifacts = {};
2434
+ for (let i = 0; i < halt.stepIndex; i += 1) {
2435
+ const a = readArtifactResult(runDir, steps[i].emits);
2436
+ if (!a.ok) {
2437
+ return refused(a.missing
2438
+ ? `artifact "${steps[i].emits}" missing for run "${runId}" — cannot continue`
2439
+ : `artifact "${steps[i].emits}" for run "${runId}" — ${a.red} — refusing rather than treating a refused read as "not done" and re-running it`);
2440
+ }
2441
+ artifacts[steps[i].emits] = a.value;
2442
+ }
2443
+
2444
+ const audit = auditSpend(runDir);
2445
+ if (!audit.ok) return refused(`run "${runId}" ${audit.red}`);
2446
+ const capUsd = arbiter.capUsd;
2447
+ if (!(capUsd - audit.total > SPEND_TOLERANCE_USD)) {
2448
+ return refused(`the cap $${capUsd} is not above what run "${runId}" has already spent ($${audit.total}) — raise it first; $0 spent now`);
2449
+ }
2450
+ const recordedHashes = readAcceptedHashesByEmits(runDir);
2451
+ if (!recordedHashes.ok) return { outcome: 'refused', red: recordedHashes.red };
2452
+
2453
+ // Consume-once BEFORE acting (the answer's own rule, F44): the rename is a one-winner gate on top of the lock.
2454
+ const taken = readdirInside(runDir, '.').filter((n) => /^halt\.\d+\.consumed\.json$/.test(n)).length;
2455
+ renameSync(join(runDir, HALT_FILE), join(runDir, `halt.${taken + 1}.consumed.json`));
2456
+ settleStop({ runDir, now, outcome: halt.outcome ?? 'halted' }); // a request left over from before the halt is not this continue's
2457
+ recordPid(runDir, 'continue', now());
2458
+
2459
+ const spent = { value: audit.total };
2460
+ const spendComplete = { value: audit.complete };
2461
+ const askLines = new Map((arbiter.asks ?? []).map((a) => [a.line, a]));
2462
+ const sendLines = new Map((arbiter.sends ?? []).map((s) => [s.line, s]));
2463
+ const askStepEmits = new Set(steps.filter((s) => askLines.has(s.fromLine)).map((s) => s.emits));
2464
+ const acceptedAskEmitsThisRun = new Map();
2465
+ for (const emits of askStepEmits) {
2466
+ const idx = steps.findIndex((s) => s.emits === emits);
2467
+ // a step before the halt point has its artifact (the gate above refused any that was missing or red)
2468
+ if (idx !== -1 && idx < halt.stepIndex) {
2469
+ acceptedAskEmitsThisRun.set(emits, recordedHashes.byEmits.get(emits) ?? null);
2470
+ }
2471
+ }
2472
+ const attemptsLog = [];
2473
+ const auditRows = [];
2474
+ const recordAudit = (row, modelOutput, unjudgedCount) => {
2475
+ const fullRow = unjudgedCount === undefined ? row : { ...row, unjudgedCount };
2476
+ auditRows.push(fullRow);
2477
+ appendAudit(runDir, fullRow);
2478
+ if (row.spendComplete === false) spendComplete.value = false;
2479
+ if (modelOutput !== undefined) {
2480
+ attemptsLog.push({
2481
+ step: row.step, attempt: row.attempt, class: row.class, verdict: row.verdict, gap: row.gap, ...(row.refused ? { refused: row.refused } : {}), modelOutput,
2482
+ });
2483
+ }
2484
+ };
2485
+ const runStartedAt = typeof halt.startedAt === 'number' ? halt.startedAt : startedAt;
2486
+
2487
+ // 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.
2488
+ // 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
2489
+ // books (the source of truth), never a second record. A cap-halt re-entry keeps its own, earlier behaviour.
2490
+ const resumeTries = { numbered: 0, done: 0 };
2491
+ if (halt.outcome === 'stopped' && steps[halt.stepIndex]) {
2492
+ const tries = readAudit(runDir).filter((r) => r.step === steps[halt.stepIndex].emits && Number.isInteger(r.attempt) && r.verdict !== 'cap-halt');
2493
+ resumeTries.numbered = tries.length;
2494
+ resumeTries.done = Math.min(tries.filter((r) => r.verdict !== 'stopped').length, MAX_ATTEMPTS - 1);
2495
+ }
2496
+
2497
+ const result = await foldFromStep({
2498
+ i0: halt.stepIndex,
2499
+ resumeTries,
2500
+ steps,
2501
+ askLines,
2502
+ sendLines,
2503
+ askStepEmits,
2504
+ runDir,
2505
+ flowDir,
2506
+ runId,
2507
+ flowRoot: root,
2508
+ flowName: name,
2509
+ signatureHash: halt.signatureHash,
2510
+ inputsManifest: halt.inputsManifest,
2511
+ capUsd,
2512
+ redoCap: arbiter.redoCap ?? 3,
2513
+ effectiveCeilingUsd: ceilingUsd ?? resolveCeilingUsd(null),
2514
+ primitives,
2515
+ businessDate,
2516
+ modelStep,
2517
+ // a continued run never waits in-process: a signed ask it reaches parks, under the wait in force
2518
+ askStep: makeParkingAskStep(),
2519
+ sendStep,
2520
+ now,
2521
+ startedAt,
2522
+ runStartedAt,
2523
+ nowMs: getNowMs,
2524
+ spent,
2525
+ spendComplete,
2526
+ artifacts,
2527
+ acceptedThisRun: acceptedAskEmitsThisRun.size > 0,
2528
+ acceptedAskEmitsThisRun,
2529
+ unjudgedSinceLastAsk: Array.isArray(halt.unjudged) ? halt.unjudged : [],
2530
+ resumeRedone: Number.isInteger(halt.redone) && halt.redone > 0 ? halt.redone : 0,
2531
+ recordAudit,
2532
+ attemptsLog,
2533
+ });
2534
+ if (result.outcome === 'complete') return { ...result, auditRows };
2535
+ return result;
2536
+ } finally {
2537
+ releaseResumeLock(runDir, lockPath);
2538
+ try { closeSync(lockFd); } catch { /* already closed */ }
2539
+ }
2540
+ }
2541
+
2542
+ /**
2543
+ * 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
2544
+ * (`parkedAskId` null: nothing was written for the ask) or the ask was already parked (`parkedAskId` set: the open ask and its
2545
+ * state are set aside as `ask.<id>.stopped.json` / `state.<id>.stopped.json` so no wait can expire and no answer can reach them;
2546
+ * 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
2547
+ * rows are `settleStop`'s ("stop asked (you) at <time>", then "stopped at the ask of step N"); `halt.json` points at the ask
2548
+ * step, with the redo count carried, so Resume asks again, fresh, with no model call.
2549
+ * @param {Record<string, any>} o
2550
+ * @returns {any}
2551
+ */
2552
+ function stopAtAsk(o) {
2553
+ const {
2554
+ flowDir, runDir, runId, capUsd, startedAt, now, nowMs, signatureHash, spent, spendComplete = true, attempts = [], artifacts = {},
2555
+ stepIndex, stepEmits, flowRoot, flowName, inputsManifest, unjudged, redone, parkedAskId = null,
2556
+ } = o;
2557
+ const red = `stopped by you at the ask of step ${stepIndex + 1}`;
2558
+ if (parkedAskId !== null) {
2559
+ try { renameSync(join(runDir, 'ask.json'), join(runDir, `ask.${parkedAskId}.stopped.json`)); } catch (err) {
2560
+ // Amendment 16 C8: only "file not found" means another stopper won the rename (it writes the rows). Any other error is a failed
2561
+ // stop: said plainly with the error named, nothing written, the run left as it was.
2562
+ if (err?.code === 'ENOENT') return { outcome: 'stopped', red, spentUsd: spent.value };
2563
+ return { outcome: 'stop-failed', red: `the stop failed: could not set the ask aside (${err?.code ?? 'error'}: ${err?.message ?? err})`, spentUsd: spent.value };
2564
+ }
2565
+ try { renameSync(join(runDir, 'state.json'), join(runDir, `state.${parkedAskId}.stopped.json`)); } catch { /* no state: nothing to set aside */ }
2566
+ if (existsSync(join(runDir, 'answer.json'))) setAsideAnswer(runDir, parkedAskId, 'late');
2567
+ }
2568
+ return haltRun({
2569
+ flowDir, runDir, runId, capUsd, startedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete, attempts, artifacts,
2570
+ outcome: 'stopped', red,
2571
+ stop: { where: `stopped at the ask of step ${stepIndex + 1}`, step: stepEmits },
2572
+ resumeAt: {
2573
+ stepIndex, flowRoot, flowName, inputsManifest, unjudged, redone,
2574
+ },
2575
+ });
2576
+ }
2577
+
2578
+ /**
2579
+ * 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
2580
+ * landed right after the park). Writes the request if none is pending (`requestStop`, its one writer), takes the same exclusive
2581
+ * `resume.lock` as a resume, checks the run really is parked on its open, unanswered ask, and stops it at the ask (`stopAtAsk`).
2582
+ * Refused by name, writing nothing, for a run that is not waiting at an ask. $0: no model call, no spend.
2583
+ * @param {object} opts
2584
+ * @param {string} opts.root
2585
+ * @param {string} opts.name
2586
+ * @param {string} opts.runId
2587
+ * @param {unknown} opts.catalogue
2588
+ * @param {() => string} [opts.clock]
2589
+ * @param {() => number} [opts.nowMs]
2590
+ */
2591
+ export async function stopParkedRun({
2592
+ root, name, runId, catalogue, clock, nowMs,
2593
+ }) {
2594
+ const now = typeof clock === 'function' ? clock : () => new Date().toISOString();
2595
+ const flowDir = join(root, name);
2596
+ const refused = (red) => ({ outcome: 'refused', red: `stop: ${red}` });
2597
+ const runIdCheck = resolveRunDir(flowDir, runId);
2598
+ if (!runIdCheck.ok) return { outcome: 'refused', red: runIdCheck.red };
2599
+ const runDir = runIdCheck.runDir;
2600
+
2601
+ const lockPath = join(runDir, 'resume.lock');
2602
+ const took = await takeResumeLock(runDir, runId, lockPath);
2603
+ if (!took.ok) return { outcome: 'refused', red: took.red };
2604
+ const { lockFd } = took;
2605
+ try {
2606
+ const ask = readAsk(runDir);
2607
+ const state = readRunState(runDir);
2608
+ if (!ask || typeof ask.askId !== 'string' || !state || state.askId !== ask.askId) return refused(`run "${runId}" is not waiting at an ask`);
2609
+ if (existsSync(join(runDir, `answer.${ask.askId}.consumed.json`))) return refused(`run "${runId}" already took its answer`);
2610
+ if (endRow(readHistory(flowDir), runDir, runId) !== null) return refused(`run "${runId}" has ended`);
2611
+ if (!Number.isInteger(state.stepIndex) || state.stepIndex < 0) return refused(`run "${runId}" state.json field "stepIndex" is not a step number`);
2612
+ const audit = auditSpend(runDir);
2613
+ if (!audit.ok) return refused(`run "${runId}" ${audit.red}`);
2614
+ requestStop(runDir); // 'exists' when the door (or a race) wrote it already
2615
+ const read = readFlow({ root, name, catalogue });
2616
+ let capUsd = null;
2617
+ if (read.ok) {
2618
+ const applied = applyRunValues(read.arbiter, name, read.signature.flow, pickRunValues(runDir));
2619
+ if (applied.ok) capUsd = applied.arbiter.capUsd ?? null;
2620
+ }
2621
+ const prev = readLog(runDir);
2622
+ const stepEmits = readAudit(runDir).filter((r) => r.verdict === 'paused').map((r) => r.step).pop() ?? null;
2623
+ return stopAtAsk({
2624
+ flowDir, runDir, runId, capUsd, startedAt: typeof state.startedAt === 'number' ? state.startedAt : Date.now(), now, nowMs: typeof nowMs === 'function' ? nowMs : Date.now,
2625
+ signatureHash: state.signatureHash ?? null, spent: { value: audit.total }, spendComplete: audit.complete,
2626
+ attempts: Array.isArray(prev?.attempts) ? prev.attempts : [], artifacts: prev?.artifacts && typeof prev.artifacts === 'object' ? prev.artifacts : {},
2627
+ stepIndex: state.stepIndex, stepEmits, flowRoot: root, flowName: name, inputsManifest: state.inputsManifest, unjudged: state.evidenceUnjudged ?? [],
2628
+ redone: typeof state.redone === 'number' ? state.redone : 0, parkedAskId: ask.askId,
2629
+ });
2630
+ } finally {
2631
+ releaseResumeLock(runDir, lockPath);
2632
+ try { closeSync(lockFd); } catch { /* already closed */ }
2633
+ }
2634
+ }
2635
+
2057
2636
  /** log.json's one writer, called from every exit path (complete + every
2058
2637
  * halt) — M2 scope item 9 / the M0 ruling: what the model wrote, every
2059
2638
  * attempt, red runs included, never just the final artifacts. */
@@ -2114,6 +2693,7 @@ export function readAsk(runDir) {
2114
2693
  * @param {() => number} [opts.nowMs] - F45 finding 3; defaults to `Date.now`.
2115
2694
  * @param {string} opts.outcome
2116
2695
  * @param {string} [opts.red]
2696
+ * @param {string|null} [opts.detail] - amendment 23: bareguard's raw reason, recorded beside `red` (never the sentence).
2117
2697
  * @param {{ value: number }} opts.spent
2118
2698
  * @param {any[]} [opts.attempts]
2119
2699
  * @param {Record<string, any>} [opts.artifacts]
@@ -2127,10 +2707,14 @@ export function readAsk(runDir) {
2127
2707
  * earlier attempt this run, that already left `spendComplete: false`).
2128
2708
  * ANDed with this halt's own outcome-based verdict — once false, always
2129
2709
  * false. Defaults to `true` (every pre-existing call site is unaffected).
2710
+ * @param {{stepIndex: number, flowRoot: string, flowName: string, inputsManifest: any, unjudged?: any[], redone?: number}|null} [opts.resumeAt] - M4e
2711
+ * amendment 4 item 4: where a `cap-halt`/`stopped` run is re-entered; `haltRun` writes `halt.json` from it (and only for those outcomes).
2712
+ * @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
2713
+ * 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
2714
  */
2131
2715
  function haltRun({
2132
2716
  flowDir, runDir, runId, capUsd, startedAt, now, nowMs = Date.now, outcome, red, spent, attempts = [], artifacts = {}, signatureHash = null,
2133
- priorSpendComplete = true,
2717
+ priorSpendComplete = true, resumeAt = null, stop = null, detail = null,
2134
2718
  }) {
2135
2719
  // F45 finding 3: `startedAt` here is always the RUN's start (every caller
2136
2720
  // now passes `runStartedAt` under this key — see call sites), so `wallMs`
@@ -2139,14 +2723,33 @@ function haltRun({
2139
2723
  const spendComplete = priorSpendComplete
2140
2724
  && outcome !== 'provider-red' && outcome !== 'pricing-red' && outcome !== 'cap-halt';
2141
2725
  mkdirSync(flowDir, { recursive: true });
2142
- appendHistory(flowDir, {
2143
- runId, at: now(), outcome, spentUsd: spent.value, spendComplete, capUsd: capUsd ?? null, wallMs, signatureHash,
2144
- });
2145
- if (existsSync(runDir)) {
2146
- recordLateAnswerIfAny(runDir, now);
2147
- writeLog(runDir, {
2148
- runId, outcome, red, attempts, artifacts,
2149
- });
2726
+ try {
2727
+ if (existsSync(runDir)) {
2728
+ recordLateAnswerIfAny(runDir, now);
2729
+ writeLog(runDir, {
2730
+ runId, outcome, red, ...(detail ? { detail } : {}), attempts, artifacts,
2731
+ });
2732
+ // M4e amendment 4 item 4: a cap-halted or stopped run leaves the one record Resume continues from (its only writer).
2733
+ if (resumeAt && HALT_OUTCOMES.includes(outcome)) {
2734
+ writeFileSync(join(runDir, HALT_FILE), `${JSON.stringify({
2735
+ runId, outcome, at: now(), flow: { root: resumeAt.flowRoot, name: resumeAt.flowName }, signatureHash, inputsManifest: resumeAt.inputsManifest,
2736
+ stepIndex: resumeAt.stepIndex, startedAt, unjudged: resumeAt.unjudged ?? [],
2737
+ ...(Number.isInteger(resumeAt.redone) ? { redone: resumeAt.redone } : {}),
2738
+ }, null, 2)}\n`, { flag: 'wx' });
2739
+ }
2740
+ settleStop({ runDir, now, outcome, stop }); // amendment 7 item 8: every Stop leaves its rows
2741
+ }
2742
+ } finally {
2743
+ // The history end row is the LAST write and is always written (amendment 16 C7): a reader that sees it finds the run settled, and a
2744
+ // failed log, halt.json or settle row above never costs the row its real signature hash or the run's spend.
2745
+ // The one exception is the earlier rule (test/m4e-halt-write-order.test.js): a `stopped` row with no halt.json would read "stopped" with
2746
+ // no Resume offered, so a Stop whose halt record failed leaves no end row. C7 names the cap-halt, which always gets its row.
2747
+ const stoppedWithoutHaltRecord = outcome === 'stopped' && resumeAt && !readHaltRecord(runDir).ok;
2748
+ if (!stoppedWithoutHaltRecord) {
2749
+ appendHistory(flowDir, {
2750
+ runId, at: now(), outcome, spentUsd: spent.value, spendComplete, capUsd: capUsd ?? null, wallMs, signatureHash, ...(detail ? { detail } : {}), // amendment 23: bareguard's raw reason, never the sentence
2751
+ });
2752
+ }
2150
2753
  }
2151
- return { outcome, red, spentUsd: spent.value };
2754
+ return { outcome, red, ...(detail ? { detail } : {}), spentUsd: spent.value };
2152
2755
  }