fwdloop 0.4.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/runner.js ADDED
@@ -0,0 +1,1700 @@
1
+ // M2 piece 1 (docs/wiki/the-module-ladder.md, "M2 — scope, exit, negative —
2
+ // SIGNED"): `runFlow` — one fold over a signed flow's `declaration.steps`,
3
+ // no job-specific code path. Reads the flow through M1's `readFlow`
4
+ // (refusing by file name on any red), freezes the run's inputs, then folds:
5
+ // a fresh executor per step (goal in, gap back — no close/cap/strike ever
6
+ // reachable from it), the ralph loop with strikes, close by declared class,
7
+ // money honesty, the provider-red ladder, two append-only books.
8
+ //
9
+ // borrowed-from: fwdloop poc/m0/runner.mjs@29caa83 (`freezeInputs`,
10
+ // `checkFreshRunDir`, `checkSendDestination` with its write-time symlink
11
+ // re-check) and fwdloop poc/m2/executor.mjs@29caa83 /
12
+ // poc/m2/gapback.mjs@29caa83 (`buildExecutor`'s "no field but goal/
13
+ // primitives/reads/gap" shape, `normaliseGap`, the strike-governed ralph
14
+ // loop) and fwdloop poc/m0/askWithRedo@29caa83 (the ask-with-redo: consume-once,
15
+ // a reason-less rerun refused and re-asked, a rejection redoes the step that
16
+ // emitted the artifact under review). Rewritten against M1's real
17
+ // `readFlow`/`arbiter` shape (the POCs above ran on hand-rolled declarations
18
+ // and a single hard-coded ask/send slot) — src/ never imports from poc/.
19
+ //
20
+ // ---------------------------------------------------------------------------
21
+ // A reading call this piece makes where the signed scope was silent
22
+ // (flagged here, not invented quietly): a `hitl`-class step is only ever
23
+ // asked of a human when its `fromLine` is one of the arbiter's SIGNED ask
24
+ // lines. M1's own class derivation makes a step `hitl` by silent default too
25
+ // (no guardrail proposed for its line, or none at all) — job #1's own
26
+ // fixture has two such steps (lines 1 and 2, both carrying real primitives,
27
+ // neither an ask slot). A step in that position has no shape/citation to
28
+ // mechanically judge (that is exactly why the schema left it `hitl`) and is
29
+ // not bound to the interactive ask either, so `closeByClass` returning
30
+ // `{ verdict: 'hitl' }` for it is read here as "no judgment to render — the
31
+ // happened check already ran, let it through" (one attempt, no ralph loop,
32
+ // no strike accounting), not as a second, undeclared human checkpoint. Only
33
+ // the step actually bound to an `arbiter.asks[]` line pauses for a real
34
+ // human. This is an interpretation, not a rule the signed text states in so
35
+ // many words — worth hamr's ruling if it reads differently.
36
+ // ---------------------------------------------------------------------------
37
+
38
+ import {
39
+ accessSync, closeSync, constants as fsConstants, copyFileSync, existsSync, mkdirSync, openSync, readFileSync,
40
+ realpathSync, renameSync, statSync, unlinkSync, writeFileSync,
41
+ } from 'node:fs';
42
+ import { createHash, randomUUID } from 'node:crypto';
43
+ import {
44
+ dirname, extname, join, resolve, sep,
45
+ } from 'node:path';
46
+ import { fileURLToPath } from 'node:url';
47
+
48
+ import { readFlow } from './flow.js';
49
+ import { closeByClass } from './closers.js';
50
+ import { appendAudit, appendHistory } from './books.js';
51
+
52
+ const __dirname = dirname(fileURLToPath(import.meta.url));
53
+ const REPO_ROOT = resolve(__dirname, '..');
54
+
55
+ /** The strike governor — a run-owned constant, never raised by a caller,
56
+ * never carried in the arbiter block or the declaration (M2 scope item 5,
57
+ * signed 2026-09-24 "2A"). */
58
+ export const STRIKE_LIMIT = 2;
59
+ /** The hard attempt fallback per step (bareloop's rule: "the count is a
60
+ * fallback, never the governor" — it never raises the strike bound, it only
61
+ * bounds the case the strike governor doesn't catch). */
62
+ export const MAX_ATTEMPTS = 4;
63
+ /** Debrief round 2: `state.spent` (accumulated by repeated `spent.value +=`
64
+ * during the run) and `sumAuditUsd`'s re-summed total are two independent
65
+ * float summations of the same rows in a different order — IEEE 754
66
+ * addition is not associative, so they can differ by a single ULP (e.g.
67
+ * 0.006874 vs 0.006874000000000001) with no real discrepancy. The books
68
+ * (audit.jsonl) stay the source of truth; this tolerance only absorbs
69
+ * summation-order noise, not a real gap. A billionth of a dollar is ~6
70
+ * orders of magnitude below the cheapest real round (audit rows here run
71
+ * $0.0006+), so nothing a real tamper produces can hide inside it. */
72
+ export const SPEND_TOLERANCE_USD = 1e-9;
73
+
74
+ // ---------------------------------------------------------------------------
75
+ // Money — piece 2 wires live provider rates; this piece takes a per-attempt
76
+ // ceiling as injected data, defaulting to a frozen table's highest entry for
77
+ // an unknown model id (never a silent $0/unbounded assumption).
78
+ // ---------------------------------------------------------------------------
79
+
80
+ const CEILING_TABLE_USD = Object.freeze({
81
+ 'deepseek-flash': 0.02,
82
+ 'synthetic-default': 0.05,
83
+ });
84
+
85
+ /** @param {string|null|undefined} modelId */
86
+ export function resolveCeilingUsd(modelId) {
87
+ if (typeof modelId === 'string' && Object.prototype.hasOwnProperty.call(CEILING_TABLE_USD, modelId)) {
88
+ return CEILING_TABLE_USD[modelId];
89
+ }
90
+ return Math.max(...Object.values(CEILING_TABLE_USD));
91
+ }
92
+
93
+ // ---------------------------------------------------------------------------
94
+ // The executor — "goal in, gap back", constructed WITHOUT its close and
95
+ // WITHOUT the cap (M2 scope item 3, the load-bearing invariant).
96
+ // ---------------------------------------------------------------------------
97
+
98
+ const EXECUTOR_FIELDS = Object.freeze(['goal', 'primitives', 'reads', 'gap']);
99
+
100
+ /** @param {{goal:string, primitives?:string[], reads?:Record<string,any>, gap?:string|null}} opts */
101
+ export function buildExecutorContext(opts) {
102
+ for (const key of Object.keys(opts ?? {})) {
103
+ if (!EXECUTOR_FIELDS.includes(key)) {
104
+ throw new Error(`executor: unknown field "${key}" — only ${EXECUTOR_FIELDS.join(', ')} may cross a step boundary`);
105
+ }
106
+ }
107
+ const {
108
+ goal, primitives = [], reads = {}, gap = null,
109
+ } = opts ?? {};
110
+ return Object.freeze({
111
+ goal,
112
+ primitives: Object.freeze([...primitives]),
113
+ reads: Object.freeze({ ...reads }),
114
+ gap: gap ?? null,
115
+ });
116
+ }
117
+
118
+ /** The identifiers a leaky executor must never carry (M2 scope item 3's own
119
+ * construction test, negative vi). Walks any depth, any key, any array
120
+ * entry; also catches a bare function value anywhere in the tree. */
121
+ const FORBIDDEN_CONTEXT_KEYS = Object.freeze([
122
+ 'close', 'shape', 'cap', 'strike', 'maxWords', 'sections', 'linesPerInvoice', 'mustCarry',
123
+ ]);
124
+
125
+ /**
126
+ * @param {unknown} value
127
+ * @param {string} [path]
128
+ * @returns {string|null} a description of the first violation found, or null when clean.
129
+ */
130
+ export function findForbiddenInContext(value, path = 'executorContext') {
131
+ if (typeof value === 'function') return `${path} is a function`;
132
+ if (Array.isArray(value)) {
133
+ for (let i = 0; i < value.length; i += 1) {
134
+ const found = findForbiddenInContext(value[i], `${path}[${i}]`);
135
+ if (found) return found;
136
+ }
137
+ return null;
138
+ }
139
+ if (value && typeof value === 'object') {
140
+ for (const key of Object.keys(value)) {
141
+ if (FORBIDDEN_CONTEXT_KEYS.includes(key)) return `${path}.${key} is a forbidden identifier`;
142
+ const found = findForbiddenInContext(value[key], `${path}.${key}`);
143
+ if (found) return found;
144
+ }
145
+ return null;
146
+ }
147
+ return null;
148
+ }
149
+
150
+ /** Also checks the executor's serialised (JSON round-tripped) form for the
151
+ * declared shape's own heading strings — a leak that survived key-name
152
+ * scanning (e.g. a heading baked into `goal` text) still needs to be
153
+ * physically absent, per M2 scope item 3. */
154
+ export function findForbiddenHeadingText(context, headingStrings) {
155
+ if (!Array.isArray(headingStrings) || headingStrings.length === 0) return null;
156
+ let serialised;
157
+ try {
158
+ serialised = JSON.stringify(context).toLowerCase();
159
+ } catch {
160
+ return null;
161
+ }
162
+ for (const heading of headingStrings) {
163
+ if (typeof heading === 'string' && heading.length > 0 && serialised.includes(heading.toLowerCase())) {
164
+ return `executorContext contains the shape heading text "${heading}"`;
165
+ }
166
+ }
167
+ return null;
168
+ }
169
+
170
+ // ---------------------------------------------------------------------------
171
+ // normaliseGap — borrowed verbatim in spirit from poc/m2/gapback.mjs: every
172
+ // digit run collapses to one '#' so "689 words, limit 600" and "661 words,
173
+ // limit 600" are the SAME gap shape for strike purposes; a different check's
174
+ // gap normalises differently.
175
+ // ---------------------------------------------------------------------------
176
+
177
+ export function normaliseGap(red) {
178
+ if (typeof red !== 'string') return '';
179
+ return red.toLowerCase().replace(/\d+/g, '#').replace(/\s+/g, ' ').trim();
180
+ }
181
+
182
+ // ---------------------------------------------------------------------------
183
+ // The mechanical "happened" check — every step's artifact, before its close,
184
+ // no exception (M2 scope item 10). This piece's artifacts are typed JS
185
+ // objects (not raw bytes), so "0-byte" reads as "the shape that class's
186
+ // artifact contract defines carries nothing" — empty text, no fields, or
187
+ // (for the generic hitl case with no declared contract) no own keys at all.
188
+ // ---------------------------------------------------------------------------
189
+
190
+ // ---------------------------------------------------------------------------
191
+ // M2 amendment 1 item 1 (docs/wiki/the-module-ladder.md, "M2 amendment 1 —
192
+ // SIGNED"): the model's own typed word, taken at face value, BEFORE the
193
+ // happened check or the close ever run. `done: false` — or a missing/non-
194
+ // boolean `done` (a schema the provider ignored is not a pass) — is a HALT,
195
+ // never a strike, never a retry. `done`/`blocker` are stripped from the
196
+ // artifact before it reaches the happened check, the closer, or disk — a
197
+ // self-report is not something a closer judges; it is kept verbatim only in
198
+ // log.json's modelOutput (the raw `result.artifact`, untouched by this).
199
+ // ---------------------------------------------------------------------------
200
+
201
+ /**
202
+ * @param {any} step
203
+ * @param {unknown} artifact
204
+ * @returns {{verdict:'not-done', red:string} | {verdict:'done'}}
205
+ */
206
+ function checkDoneBlocker(step, artifact) {
207
+ const label = step?.emits ?? 'step';
208
+ const obj = /** @type {Record<string, unknown>} */ (artifact);
209
+ if (!artifact || typeof artifact !== 'object' || typeof obj.done !== 'boolean') {
210
+ return { verdict: 'not-done', red: `step "${label}" artifact has no boolean "done"` };
211
+ }
212
+ if (obj.done === false) {
213
+ const blocker = typeof obj.blocker === 'string' && obj.blocker.length > 0 ? obj.blocker : 'no blocker given';
214
+ return { verdict: 'not-done', red: `step "${label}" reports done: false — ${blocker}` };
215
+ }
216
+ return { verdict: 'done' };
217
+ }
218
+
219
+ /** @param {unknown} artifact */
220
+ function stripDoneBlocker(artifact) {
221
+ if (!artifact || typeof artifact !== 'object') return artifact;
222
+ const obj = /** @type {Record<string, unknown>} */ (artifact);
223
+ const { done, blocker, ...rest } = obj;
224
+ return rest;
225
+ }
226
+
227
+ function checkArtifactHappened(step, artifact) {
228
+ const label = step?.goal ? `"${step.goal}"` : (step?.emits ?? 'step');
229
+ if (artifact === null || artifact === undefined) {
230
+ return { verdict: 'red', red: `happened: ${label} produced nothing` };
231
+ }
232
+ if (typeof artifact === 'string') {
233
+ return artifact.length === 0
234
+ ? { verdict: 'red', red: `happened: ${label} produced an empty string` }
235
+ : { verdict: 'green' };
236
+ }
237
+ if (typeof artifact === 'object') {
238
+ if (Object.prototype.hasOwnProperty.call(artifact, 'text')) {
239
+ return typeof artifact.text === 'string' && artifact.text.length > 0
240
+ ? { verdict: 'green' }
241
+ : { verdict: 'red', red: `happened: ${label} produced empty text` };
242
+ }
243
+ if (Object.prototype.hasOwnProperty.call(artifact, 'fields')) {
244
+ return artifact.fields && typeof artifact.fields === 'object' && Object.keys(artifact.fields).length > 0
245
+ ? { verdict: 'green' }
246
+ : { verdict: 'red', red: `happened: ${label} produced no fields` };
247
+ }
248
+ return Object.keys(artifact).length > 0
249
+ ? { verdict: 'green' }
250
+ : { verdict: 'red', red: `happened: ${label} produced an empty object` };
251
+ }
252
+ return { verdict: 'green' };
253
+ }
254
+
255
+ // ---------------------------------------------------------------------------
256
+ // Preflight — borrowed from poc/m0/runner.mjs, adapted to M1's real
257
+ // `readFlow`/`arbiter` shape.
258
+ // ---------------------------------------------------------------------------
259
+
260
+ function hashFile(path) {
261
+ return createHash('sha256').update(readFileSync(path)).digest('hex');
262
+ }
263
+
264
+ /** A run dir that already holds `ask.json`/`answer.json` from an earlier run
265
+ * is a stale-answer hazard — refuse, never silently proceed or delete. */
266
+ export function checkFreshRunDir(runDir) {
267
+ for (const file of ['ask.json', 'answer.json']) {
268
+ if (existsSync(join(runDir, file))) {
269
+ return { ok: false, red: `preflight: run dir ${runDir} already holds ${file} from an earlier run — use a new runId` };
270
+ }
271
+ }
272
+ return { ok: true };
273
+ }
274
+
275
+ /** Copy each named source into `<runDir>/inputs/`, hash the FROZEN copy
276
+ * (never the original again after this), write `inputs.json`. An
277
+ * unreadable source refuses by name. */
278
+ export function freezeInputs(runDir, sources) {
279
+ const inputsDir = join(runDir, 'inputs');
280
+ mkdirSync(inputsDir, { recursive: true });
281
+ const manifest = [];
282
+ for (const { id, path: sourcePath } of sources ?? []) {
283
+ if (!existsSync(sourcePath)) {
284
+ return { ok: false, red: `freeze: input "${id}" is unreadable at ${sourcePath}` };
285
+ }
286
+ const frozenPath = join(inputsDir, `${id}${extname(sourcePath)}`);
287
+ copyFileSync(sourcePath, frozenPath);
288
+ const sha256 = hashFile(frozenPath);
289
+ const { size: bytes } = statSync(frozenPath);
290
+ manifest.push({
291
+ id, source: sourcePath, frozen: frozenPath, sha256, bytes,
292
+ });
293
+ }
294
+ writeFileSync(join(runDir, 'inputs.json'), JSON.stringify(manifest, null, 2));
295
+ return { ok: true, manifest };
296
+ }
297
+
298
+ /** The send target's directory must resolve (lexically AND after
299
+ * realpath — a symlink inside the repo pointing outside it must not pass)
300
+ * inside the repo, and be writable. Re-checked at write time, not just at
301
+ * preflight (time-of-check vs time-of-use, M0's own fix).
302
+ * @param {string} target
303
+ * @returns {{ok:true, dir:string} | {ok:false, red:string}} */
304
+ export function checkSendDestination(target) {
305
+ const match = /^file:(.+)$/.exec(target ?? '');
306
+ if (!match) return { ok: false, red: `destination: send target "${target}" is not a "file:<path>" target` };
307
+ const dir = join(REPO_ROOT, match[1]);
308
+ const resolvedDir = resolve(dir);
309
+ const resolvedRoot = resolve(REPO_ROOT);
310
+ if (resolvedDir !== resolvedRoot && !resolvedDir.startsWith(resolvedRoot + sep)) {
311
+ return { ok: false, red: `destination: send target "${target}" resolves outside the repo (${dir})` };
312
+ }
313
+ try {
314
+ const realDir = realpathSync(dir);
315
+ const realRoot = realpathSync(REPO_ROOT);
316
+ if (realDir !== realRoot && !realDir.startsWith(realRoot + sep)) {
317
+ return {
318
+ ok: false,
319
+ red: `destination: send target "${target}" is a symlink that resolves outside the repo (${realDir})`,
320
+ };
321
+ }
322
+ } catch {
323
+ // dir doesn't exist yet — handled by the accessSync red below.
324
+ }
325
+ try {
326
+ accessSync(dir, fsConstants.W_OK);
327
+ } catch (err) {
328
+ return { ok: false, red: `destination: send target directory "${dir}" is not writable (${err.code})` };
329
+ }
330
+ return { ok: true, dir };
331
+ }
332
+
333
+ // ---------------------------------------------------------------------------
334
+ // Artifacts on disk (M2 scope item 2): every emitted artifact is written to
335
+ // `runs/<runId>/artifacts/<emits>.json` the moment its step closes
336
+ // (green/hitl pass-through/accepted) — ONE writer function, and later steps'
337
+ // `reads` are loaded back from these files, never from the in-memory
338
+ // `artifacts` object alone.
339
+ // ---------------------------------------------------------------------------
340
+
341
+ function artifactPath(runDir, id) {
342
+ return join(runDir, 'artifacts', `${id}.json`);
343
+ }
344
+
345
+ /** The one writer for a run's artifact files. Refuses (throws) to overwrite
346
+ * an existing artifact id within a run UNLESS the caller explicitly asks
347
+ * for it (`overwrite: true` — the ask-redo path's own deliberate
348
+ * replacement of a step it is re-running; every other call site accepts
349
+ * the default and gets the safety refusal). */
350
+ export function writeArtifact(runDir, id, artifact, { overwrite = false } = {}) {
351
+ const dir = join(runDir, 'artifacts');
352
+ mkdirSync(dir, { recursive: true });
353
+ const target = artifactPath(runDir, id);
354
+ if (existsSync(target) && !overwrite) {
355
+ throw new Error(`writeArtifact: artifact "${id}" already exists in this run (${target}) — refused`);
356
+ }
357
+ writeFileSync(target, JSON.stringify(artifact, null, 2));
358
+ }
359
+
360
+ /** Reads one artifact back off disk; `undefined` when it was never written
361
+ * (mirrors the in-memory map's own "absent" shape for a not-yet-produced
362
+ * read). */
363
+ export function readArtifact(runDir, id) {
364
+ const target = artifactPath(runDir, id);
365
+ if (!existsSync(target)) return undefined;
366
+ return JSON.parse(readFileSync(target, 'utf8'));
367
+ }
368
+
369
+ function readArtifactsMap(runDir, ids) {
370
+ return Object.fromEntries((ids ?? []).map((id) => [id, readArtifact(runDir, id)]));
371
+ }
372
+
373
+ // ---------------------------------------------------------------------------
374
+ // Item 4 (small): an `answer.json` still on disk, unconsumed, at run end —
375
+ // a late human answer that arrived after the run already moved on. One
376
+ // audit row, never applied, so the human can see their late answer changed
377
+ // nothing.
378
+ // ---------------------------------------------------------------------------
379
+
380
+ function recordLateAnswerIfAny(runDir) {
381
+ const file = join(runDir, 'answer.json');
382
+ if (!existsSync(file)) return;
383
+ appendAudit(runDir, {
384
+ step: null,
385
+ attempt: null,
386
+ class: null,
387
+ verdict: 'answer-after-run',
388
+ gap: null,
389
+ usd: 0,
390
+ spendComplete: true,
391
+ wallMs: 0,
392
+ model: null,
393
+ modelMatch: null,
394
+ strike: false,
395
+ kind: 'answer-after-run',
396
+ file,
397
+ });
398
+ }
399
+
400
+ // ---------------------------------------------------------------------------
401
+ // The ralph loop with strikes (M2 scope item 5) for ONE step.
402
+ // ---------------------------------------------------------------------------
403
+
404
+ /**
405
+ * Sums only the KNOWN (typeof === 'number') values, e.g. a transport fault's
406
+ * priced floor plus this attempt's own cost. Never `?? 0` — a value that is
407
+ * null/undefined is dropped from the sum rather than zeroing it out, so a
408
+ * lone known partial survives as itself and "no known cost at all" stays
409
+ * `null` (never coerced to 0).
410
+ * @param {...(number|null|undefined)} values
411
+ * @returns {number|null}
412
+ */
413
+ function sumKnownUsd(...values) {
414
+ const known = values.filter((v) => typeof v === 'number');
415
+ if (known.length === 0) return null;
416
+ return known.reduce((a, b) => a + b, 0);
417
+ }
418
+
419
+ function makeAuditRow({
420
+ step, attempt, verdict, gap, usd, spendComplete, wallMs, model = null, modelMatch = null, strike,
421
+ }) {
422
+ return {
423
+ step: step?.emits ?? step?.goal ?? null,
424
+ attempt,
425
+ class: step?.close?.class ?? null,
426
+ verdict,
427
+ gap: gap ?? null,
428
+ usd,
429
+ spendComplete,
430
+ wallMs,
431
+ model: model ?? null,
432
+ modelMatch: modelMatch ?? null,
433
+ strike: !!strike,
434
+ };
435
+ }
436
+
437
+ /**
438
+ * Run one step to green (or hitl pass-through), looping under strikes and
439
+ * the attempt fallback. Returns `{ ok:true, artifact, attempts }` on success
440
+ * or `{ ok:false, outcome, red }` on any halt. Appends one audit row per
441
+ * attempt via `deps.recordAudit`. Never throws for a model/close failure —
442
+ * only a programmer error (a malformed step, an unreachable branch) escapes.
443
+ *
444
+ * @param {object} opts
445
+ * @param {any} opts.step
446
+ * @param {Record<string, any>} [opts.primitivesMap]
447
+ * @param {Record<string, any>} opts.readsMap
448
+ * @param {string} opts.businessDate
449
+ * @param {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class:string|null}) => Promise<any>} opts.modelStep
450
+ * @param {{ value: number }} opts.spent
451
+ * @param {number} opts.capUsd
452
+ * @param {number} opts.ceilingUsd
453
+ * @param {(row: any, modelOutput?: any) => void} opts.recordAudit
454
+ * @param {string|null} [opts.initialGap]
455
+ * @param {number} [opts.attemptOffset]
456
+ * @returns {Promise<{ok:true, artifact:any, attempts:number, hitl?:boolean} | {ok:false, outcome:string, red:string}>}
457
+ */
458
+ async function runStepRalph({
459
+ step, primitivesMap, readsMap, businessDate, modelStep, spent, capUsd, ceilingUsd, recordAudit, initialGap = null, attemptOffset = 0,
460
+ }) {
461
+ /** @type {string|null} */
462
+ let gap = initialGap ?? null;
463
+ let strikes = 0;
464
+ const seenGaps = new Set();
465
+
466
+ for (let n = 1; n <= MAX_ATTEMPTS; n += 1) {
467
+ const attempt = attemptOffset + n;
468
+ // This attempt's known floor from a FIRST transport fault that then
469
+ // retried — every audit row this attempt still writes must carry this
470
+ // floor summed with its own cost (F41 books gap: the fault's cost was
471
+ // only ever in `spent.value`'s total, never on the attempt's own row).
472
+ let attemptFloorUsd = null;
473
+ if (spent.value + ceilingUsd > capUsd) {
474
+ recordAudit(makeAuditRow({
475
+ step, attempt, verdict: 'cap-halt', gap, usd: null, spendComplete: false, wallMs: 0, strike: false,
476
+ }));
477
+ return {
478
+ ok: false,
479
+ outcome: 'cap-halt',
480
+ red: `cap-halt: step "${step.goal}" attempt ${attempt} cannot be funded under cap $${capUsd} (spent so far $${spent.value})`,
481
+ };
482
+ }
483
+
484
+ const grantedTools = Object.fromEntries((step.primitives ?? []).map((verb) => [verb, primitivesMap?.[verb]]));
485
+ const executorContext = buildExecutorContext({
486
+ goal: step.goal, primitives: step.primitives ?? [], reads: readsMap, gap,
487
+ });
488
+
489
+ // `stepMeta` is a SEPARATE argument from `executorContext` — never a
490
+ // field on it. It carries the step's declared close CLASS only (never
491
+ // its shape), so a live `modelStep` can build its `emit_artifact` tool
492
+ // schema without the executor context ever needing to carry one (M2
493
+ // scope item 3's own invariant: the schema is class-only, and the
494
+ // construction test below proves the context itself stays clean).
495
+ const stepMeta = Object.freeze({ class: step.close?.class ?? null });
496
+
497
+ const startedAt = Date.now();
498
+ // eslint-disable-next-line no-await-in-loop
499
+ let result = await modelStep(executorContext, grantedTools, stepMeta);
500
+ if (result && result.ok === false && result.transport === true) {
501
+ // A known partial cost from the FIRST transport fault must survive as
502
+ // the floor even though this attempt goes on to retry — never
503
+ // dropped on the retry path (the brief's own gap, closed here).
504
+ if (typeof result.costUsd === 'number') {
505
+ spent.value += result.costUsd;
506
+ attemptFloorUsd = result.costUsd;
507
+ }
508
+ // Exactly one immediate retry on the SAME attempt for a transport
509
+ // fault; an HTTP status is not transport, a wall-clock timeout is
510
+ // never retried (M2 scope item 8) — both are the caller's own
511
+ // `modelStep`'s job to distinguish; this loop only ever retries the
512
+ // `transport: true` shape, exactly once.
513
+ // eslint-disable-next-line no-await-in-loop
514
+ result = await modelStep(executorContext, grantedTools, stepMeta);
515
+ }
516
+ const wallMs = Date.now() - startedAt;
517
+
518
+ if (result && result.ok === false && result.transport === true) {
519
+ if (typeof result.costUsd === 'number') spent.value += result.costUsd;
520
+ // Both faults' known costs, summed — the first fault's floor was
521
+ // already added to `spent.value` above (never double-added here); a
522
+ // null second cost never zeroes out a known first floor.
523
+ const usd = sumKnownUsd(attemptFloorUsd, result.costUsd);
524
+ recordAudit(makeAuditRow({
525
+ step, attempt, verdict: 'provider-red', gap, usd, spendComplete: false, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false,
526
+ }), result.red ?? 'transport fault twice');
527
+ return { ok: false, outcome: 'provider-red', red: `provider-red: step "${step.goal}" attempt ${attempt}: ${result.red ?? 'transport fault twice'}` };
528
+ }
529
+
530
+ if (!result || result.ok !== true) {
531
+ // A non-transport model failure — never thrown, never coerced into a
532
+ // fabricated artifact. Treated as this attempt's red (it is the
533
+ // step's own failure to produce, not a system halt), strike-eligible
534
+ // like any other close red.
535
+ const red = result?.red ?? 'model step failed with no artifact';
536
+ const normalised = normaliseGap(red);
537
+ const strike = seenGaps.has(normalised);
538
+ seenGaps.add(normalised);
539
+ if (strike) strikes += 1;
540
+ const usd = sumKnownUsd(attemptFloorUsd, result?.costUsd);
541
+ recordAudit(makeAuditRow({
542
+ step, attempt, verdict: 'red', gap: red, usd, spendComplete: usd !== null, wallMs, model: result?.model, modelMatch: result?.modelMatch, strike,
543
+ }), red);
544
+ if (n === MAX_ATTEMPTS) return { ok: false, outcome: 'attempt-fallback', red: `attempt-fallback: step "${step.goal}" — ${red}` };
545
+ if (strikes >= STRIKE_LIMIT) return { ok: false, outcome: 'struck-out', red: `struck-out: step "${step.goal}" — ${red}` };
546
+ gap = red;
547
+ // eslint-disable-next-line no-continue
548
+ continue;
549
+ }
550
+
551
+ if (result.costUsd === null || result.costUsd === undefined) {
552
+ recordAudit(makeAuditRow({
553
+ step, attempt, verdict: 'pricing-red', gap, usd: attemptFloorUsd, spendComplete: false, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false,
554
+ }), result.artifact ?? null);
555
+ return { ok: false, outcome: 'pricing-red', red: `pricing-red: step "${step.goal}" attempt ${attempt} returned no cost (never "?? 0")` };
556
+ }
557
+ spent.value += result.costUsd;
558
+ const attemptUsd = sumKnownUsd(attemptFloorUsd, result.costUsd);
559
+
560
+ // The model's own word, taken at face value — before the happened check,
561
+ // before any close, no exception (M2 amendment 1 item 1). A halt, not a
562
+ // strike, not a retry: `recordAudit`'s modelOutput arg keeps the RAW
563
+ // `result.artifact` (done/blocker included) for log.json; everything
564
+ // downstream of a `done: true` gets the STRIPPED artifact.
565
+ const doneCheck = checkDoneBlocker(step, result.artifact);
566
+ if (doneCheck.verdict === 'not-done') {
567
+ recordAudit(makeAuditRow({
568
+ step, attempt, verdict: 'not-done', gap: doneCheck.red, usd: attemptUsd, spendComplete: true, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false,
569
+ }), result.artifact ?? null);
570
+ return { ok: false, outcome: 'not-done', red: doneCheck.red };
571
+ }
572
+ const artifact = stripDoneBlocker(result.artifact);
573
+
574
+ const happened = checkArtifactHappened(step, artifact);
575
+ if (happened.verdict === 'red') {
576
+ // Item 5: "or wrote no artifact" strikes unconditionally, every time
577
+ // (never gated by novelty — an empty artifact is always the same
578
+ // failure) — matches poc/m2/gapback.mjs's own rule exactly.
579
+ strikes += 1;
580
+ recordAudit(makeAuditRow({
581
+ step, attempt, verdict: 'red', gap: happened.red, usd: attemptUsd, spendComplete: true, wallMs, model: result.model, modelMatch: result.modelMatch, strike: true,
582
+ }), result.artifact ?? null);
583
+ if (n === MAX_ATTEMPTS) return { ok: false, outcome: 'attempt-fallback', red: `attempt-fallback: ${happened.red}` };
584
+ if (strikes >= STRIKE_LIMIT) return { ok: false, outcome: 'struck-out', red: `struck-out: ${happened.red}` };
585
+ gap = happened.red ?? null;
586
+ // eslint-disable-next-line no-continue
587
+ continue;
588
+ }
589
+
590
+ const closed = closeByClass(step, artifact, { reads: readsMap, businessDate });
591
+
592
+ if (closed.verdict === 'green' || closed.verdict === 'hitl') {
593
+ recordAudit(makeAuditRow({
594
+ step, attempt, verdict: closed.verdict, gap: null, usd: attemptUsd, spendComplete: true, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false,
595
+ }), result.artifact);
596
+ return {
597
+ ok: true, artifact, attempts: attempt, hitl: closed.verdict === 'hitl',
598
+ };
599
+ }
600
+
601
+ if (closed.verdict !== 'red') {
602
+ // A closer that renders no judgment ('unparseable'/'crash') is a
603
+ // CASUALTY, never a red and never a strike (bareloop F17).
604
+ recordAudit(makeAuditRow({
605
+ step, attempt, verdict: 'close-casualty', gap: closed.red, usd: attemptUsd, spendComplete: true, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false,
606
+ }), result.artifact);
607
+ return { ok: false, outcome: 'close-casualty', red: `close-casualty: step "${step.goal}" — ${closed.red} (${closed.verdict})` };
608
+ }
609
+
610
+ const normalised = normaliseGap(closed.red);
611
+ const strike = seenGaps.has(normalised);
612
+ seenGaps.add(normalised);
613
+ if (strike) strikes += 1;
614
+ recordAudit(makeAuditRow({
615
+ step, attempt, verdict: 'red', gap: closed.red, usd: attemptUsd, spendComplete: true, wallMs, model: result.model, modelMatch: result.modelMatch, strike,
616
+ }), result.artifact);
617
+
618
+ if (n === MAX_ATTEMPTS) return { ok: false, outcome: 'attempt-fallback', red: `attempt-fallback: step "${step.goal}" — ${closed.red}` };
619
+ if (strikes >= STRIKE_LIMIT) return { ok: false, outcome: 'struck-out', red: `struck-out: step "${step.goal}" — ${closed.red}` };
620
+ gap = closed.red ?? null;
621
+ }
622
+ // Unreachable — the loop above always returns by n === MAX_ATTEMPTS.
623
+ return { ok: false, outcome: 'attempt-fallback', red: `attempt-fallback: step "${step.goal}" — exhausted attempts` };
624
+ }
625
+
626
+ // ---------------------------------------------------------------------------
627
+ // runFlow — the entry point.
628
+ // ---------------------------------------------------------------------------
629
+
630
+ /**
631
+ * @param {object} opts
632
+ * @param {string} opts.root - the flows root directory (M1's `readFlow` root).
633
+ * @param {string} opts.name - the flow name.
634
+ * @param {string} opts.runId
635
+ * @param {Array<{id:string, path:string}>} opts.sources - the real files to freeze for this run.
636
+ * @param {unknown} opts.catalogue - passed straight through to `readFlow`.
637
+ * @param {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class:string|null}) => Promise<{ok:boolean, artifact?:unknown, costUsd:number|null, red?:string, transport?:boolean, model?:string, modelMatch?:boolean}>} opts.modelStep
638
+ * @param {(opts:{question:string, evidence:unknown, runDir:string}) => Promise<{decision:'accept'|'reject'|'rerun'|'timeout'|'park', reason?:string}>} opts.askStep
639
+ * @param {(target:string, filename:string, content:unknown) => Promise<{ok:boolean, red?:string, bytes?:number}>} opts.sendStep
640
+ * @param {Record<string, any>} [opts.primitives] - injected primitive implementations, keyed by catalogue verb.
641
+ * @param {() => string} [opts.clock] - returns the current ISO timestamp; defaults to the wall clock.
642
+ * @param {string} opts.businessDate - the run's explicit "as of today", never the wall clock.
643
+ * @param {number} [opts.ceilingUsd] - per-attempt ceiling override; defaults to `resolveCeilingUsd(null)`.
644
+ * @param {string|null} [opts.initialGap] - M3 scope item 7 (rerun as a fresh
645
+ * run): a human's rerun reason, carried as the FIRST ordinary step's
646
+ * starting gap. Never used by a plain `runFlow` call outside `resumeRun`'s
647
+ * own rerun path.
648
+ * @param {() => number} [opts.nowMs] - F45 finding 3: returns the current
649
+ * epoch ms; defaults to the wall clock. Mirrors `clock` (ISO) so a test
650
+ * can advance wall time across a park/resume boundary without a real wait.
651
+ */
652
+ export async function runFlow({
653
+ root, name, runId, sources, catalogue, modelStep, askStep, sendStep, primitives, clock, businessDate, ceilingUsd, initialGap,
654
+ // F45 finding 3's test needs to advance wall time across a park/resume
655
+ // boundary without a real wait, exactly like `clock` already does for ISO
656
+ // timestamps — `nowMs` is the same idea for epoch-ms wall-clock reads.
657
+ // Minimal and additive: every existing caller (no `nowMs`) gets the real
658
+ // `Date.now`, unchanged.
659
+ nowMs,
660
+ }) {
661
+ const now = typeof clock === 'function' ? clock : () => new Date().toISOString();
662
+ const getNowMs = typeof nowMs === 'function' ? nowMs : Date.now;
663
+ const flowDir = join(root, name);
664
+ const startedAt = getNowMs();
665
+
666
+ const read = readFlow({ root, name, catalogue });
667
+ if (!read.ok) {
668
+ // Negative iv: a flow whose files don't hash to the signature (or is
669
+ // otherwise unreadable) is refused by name, at $0. No run dir exists to
670
+ // hold an audit.jsonl, so the ONLY book row is one history row: a
671
+ // refusal spent nothing, and `usd: 0`/`spendComplete: true` is honestly
672
+ // true here (never the "unknown coerced to 0" case money honesty
673
+ // otherwise forbids) — stated explicitly per the brief's own note.
674
+ mkdirSync(flowDir, { recursive: true });
675
+ appendHistory(flowDir, {
676
+ runId, at: now(), outcome: 'refused', spentUsd: 0, spendComplete: true, capUsd: null, wallMs: Date.now() - startedAt, signatureHash: null,
677
+ });
678
+ return { outcome: 'refused', red: read.reds[0], reds: read.reds };
679
+ }
680
+
681
+ const { arbiter, declaration, signature } = read;
682
+ const capUsd = arbiter.capUsd;
683
+ const redoCap = arbiter.redoCap ?? 3;
684
+ const effectiveCeilingUsd = ceilingUsd ?? resolveCeilingUsd(null);
685
+ const askLines = new Map((arbiter.asks ?? []).map((a) => [a.line, a]));
686
+ const sendLines = new Map((arbiter.sends ?? []).map((s) => [s.line, s]));
687
+
688
+ const runDir = join(flowDir, 'runs', runId);
689
+
690
+ const fresh = checkFreshRunDir(runDir);
691
+ if (!fresh.ok) {
692
+ return haltRun({
693
+ flowDir, runDir, runId, capUsd, startedAt, now, nowMs: getNowMs, signatureHash: signature.flow, outcome: 'preflight-red', red: fresh.red, spent: { value: 0 },
694
+ });
695
+ }
696
+ mkdirSync(runDir, { recursive: true });
697
+
698
+ const frozen = freezeInputs(runDir, sources ?? []);
699
+ if (!frozen.ok) {
700
+ return haltRun({
701
+ flowDir, runDir, runId, capUsd, startedAt, now, nowMs: getNowMs, signatureHash: signature.flow, outcome: 'preflight-red', red: frozen.red, spent: { value: 0 },
702
+ });
703
+ }
704
+
705
+ const artifacts = {};
706
+ const auditRows = [];
707
+ // Item 3: what the model actually wrote, every attempt, red runs included
708
+ // — kept SEPARATELY from auditRows (which stay the signed book's own
709
+ // shape) and folded into log.json only, on every exit path.
710
+ /** @type {any[]} */
711
+ const attemptsLog = [];
712
+ // Orchestrator review fix (4): a floor stays a floor — once ANY row this
713
+ // run carries `spendComplete: false` (a cost that never resolved to a
714
+ // known number, e.g. a retried transport fault that still failed), the
715
+ // run's OWN aggregate never flips back to true, park or no park. Threaded
716
+ // into every book row `foldFromStep`/`runAskSlot` writes and persisted in
717
+ // `state.json` so a resumed run inherits the floor instead of quietly
718
+ // reporting complete.
719
+ const spendComplete = { value: true };
720
+ const recordAudit = (row, modelOutput, unjudgedCount) => {
721
+ // M2 amendment 1 item 2: "audit row for the ask gains unjudgedCount" —
722
+ // only the ask's own rows pass a third argument; every other row is
723
+ // unaffected (the key is simply absent, never a stray 0/null).
724
+ const fullRow = unjudgedCount === undefined ? row : { ...row, unjudgedCount };
725
+ auditRows.push(fullRow);
726
+ appendAudit(runDir, fullRow);
727
+ if (row.spendComplete === false) spendComplete.value = false;
728
+ if (modelOutput !== undefined) {
729
+ attemptsLog.push({
730
+ step: row.step, attempt: row.attempt, class: row.class, verdict: row.verdict, gap: row.gap, modelOutput,
731
+ });
732
+ }
733
+ };
734
+ const spent = { value: 0 };
735
+ let acceptedThisRun = false;
736
+ // M2 amendment 1 item 2: every hitl-class step NOT bound to a signed ask
737
+ // line is carried as evidence into the NEXT signed ask, in order, then
738
+ // reset — never silently passed through unseen.
739
+ /** @type {Array<{step:string|null, emits:string, artifact:unknown}>} */
740
+ let unjudgedSinceLastAsk = [];
741
+
742
+ const steps = declaration.steps;
743
+ // M2 fix: the send's content is identified by IDENTITY (the artifact
744
+ // emitted by a signed ask step), never by position in `reads` — every id
745
+ // in a send step's `reads` names an earlier step, so picking `reads[0]`
746
+ // silently ships whatever was read first instead of what was accepted.
747
+ // Derived the same way the fold below knows a step is an ask — bound to
748
+ // an `arbiter.asks[]` line.
749
+ const askStepEmits = new Set(steps.filter((s) => askLines.has(s.fromLine)).map((s) => s.emits));
750
+ // Tracks which specific ask emits were accepted THIS run (acceptedThisRun
751
+ // above stays run-wide, for the "reached with no accept this run" gate).
752
+ const acceptedAskEmitsThisRun = new Set();
753
+
754
+ const result = await foldFromStep({
755
+ i0: 0,
756
+ steps,
757
+ askLines,
758
+ sendLines,
759
+ askStepEmits,
760
+ runDir,
761
+ flowDir,
762
+ runId,
763
+ flowRoot: root,
764
+ flowName: name,
765
+ signatureHash: signature.flow,
766
+ inputsManifest: frozen.manifest,
767
+ capUsd,
768
+ redoCap,
769
+ effectiveCeilingUsd,
770
+ primitives,
771
+ businessDate,
772
+ modelStep,
773
+ askStep,
774
+ sendStep,
775
+ now,
776
+ startedAt,
777
+ nowMs: getNowMs,
778
+ // F45 finding 3: `runStartedAt` is the run's TRUE wall-clock start — for
779
+ // a fresh `runFlow` call it's this same `startedAt` (there is no earlier
780
+ // process). It is what park persists into state.json and every resume
781
+ // restores, so a run's final `wallMs` times the whole run, not just the
782
+ // last process (a pause counts as elapsed wall time — see the comment
783
+ // at its use in `foldFromStep`).
784
+ runStartedAt: startedAt,
785
+ spent,
786
+ spendComplete,
787
+ artifacts,
788
+ acceptedThisRun,
789
+ acceptedAskEmitsThisRun,
790
+ unjudgedSinceLastAsk,
791
+ recordAudit,
792
+ attemptsLog,
793
+ firstStepGap: initialGap ?? null,
794
+ });
795
+
796
+ if (result.outcome === 'complete') return { ...result, auditRows };
797
+ return result;
798
+ }
799
+
800
+ // ---------------------------------------------------------------------------
801
+ // M3 piece 1 (docs/wiki/the-module-ladder.md, "M3 — scope, exit, negative —
802
+ // SIGNED", scope items 1-2, 4-6, 8): park-and-exit at a signed ask, and
803
+ // resuming into the SAME fold from a separate process later. ONE fold —
804
+ // `foldFromStep` below is the loop `runFlow` always ran (M2), now starting
805
+ // at an arbitrary step index with restored accumulators so `resumeRun` can
806
+ // re-enter it exactly where a parked run left off, instead of a second
807
+ // runner.
808
+ //
809
+ // borrowed-from: fwdloop poc/m3/park.mjs@afb85d7 (the park/answer/resume
810
+ // protocol proved at F44 — ask.json+state.json's fields, the exclusive
811
+ // `resume.lock`, consuming `answer.json` by rename BEFORE acting). Rewritten
812
+ // against the real `runFlow` fold (the POC ran fake, hand-rolled steps
813
+ // against a single hard-coded ask, never `runStepRalph`/`runAskSlot`) — src/
814
+ // never imports from poc/.
815
+ // ---------------------------------------------------------------------------
816
+
817
+ /** An ask step that never waits — it immediately tells the fold to park.
818
+ * The counterpart to `makeFileAskStep`'s in-process poll (M2 scope item 6);
819
+ * a caller wanting park-and-exit behaviour from a FRESH `runFlow` call
820
+ * passes this (or an equivalent) as `askStep`.
821
+ * @returns {(opts?: any) => Promise<{decision: 'park'}>} */
822
+ export function makeParkingAskStep() {
823
+ return async function parkingAskStep() {
824
+ return /** @type {{decision: 'park'}} */ ({ decision: 'park' });
825
+ };
826
+ }
827
+
828
+ /** `resumeRun`'s own askStep: yields the human's already-consumed decision
829
+ * exactly once (for the ask it was built for), then — if that decision was
830
+ * a reject and the ask loops back around to ask again — parks under a NEW
831
+ * askId, exactly like a fresh ask would. This is what turns "redo, then
832
+ * ask again" into "redo, then re-park" for a resumed run, with no second
833
+ * code path. */
834
+ function makeOneShotThenParkAskStep({ decision, reason }) {
835
+ let used = false;
836
+ return async function resumeAskStep() {
837
+ if (!used) {
838
+ used = true;
839
+ return { decision, reason };
840
+ }
841
+ return { decision: 'park' };
842
+ };
843
+ }
844
+
845
+ /**
846
+ * One signed ask slot's own loop (M2's ask branch, unchanged in spirit,
847
+ * extracted so `resumeRun` can re-enter the SAME logic mid-ask instead of
848
+ * duplicating it). Returns exactly one of:
849
+ * - `{ type: 'paused', result }` — `askStep` chose to park; ask.json +
850
+ * state.json are written and `result` is `runFlow`/`resumeRun`'s own
851
+ * return value.
852
+ * - `{ type: 'halted', outcome, red }` — the caller wraps this in
853
+ * `haltRun` (it knows the right `signatureHash`/`artifacts` to attach).
854
+ * - `{ type: 'accepted', artifact }` — the human accepted; the caller
855
+ * writes the ask step's own artifact and continues the fold.
856
+ *
857
+ * @param {object} opts
858
+ * @returns {Promise<any>}
859
+ */
860
+ async function runAskSlot({
861
+ step, stepIndex, askSlot, priorId, priorStep, priorArtifact, redoCap, effectiveCeilingUsd, capUsd,
862
+ primitives, businessDate, modelStep, askStep, spent, spendComplete, recordAudit,
863
+ evidenceUnjudged, unjudgedCount, redone: initialRedone,
864
+ runDir, flowDir, runId, flowRoot, flowName, signatureHash, inputsManifest, attemptsLog, artifacts, now, startedAt,
865
+ // F45 finding 3: the run's TRUE wall-clock start, persisted into
866
+ // state.json on every park/re-park so a later resume can restore it
867
+ // instead of substituting its own process's start.
868
+ runStartedAt,
869
+ }) {
870
+ let redone = initialRedone;
871
+ let currentPrior = priorArtifact;
872
+
873
+ for (;;) {
874
+ const evidence = { artifact: currentPrior, unjudged: evidenceUnjudged };
875
+ // eslint-disable-next-line no-await-in-loop
876
+ const answer = await askStep({
877
+ question: askSlot?.question ?? step.goal, evidence, runDir, ttlMs: askSlot?.ttlMs, stepIndex,
878
+ });
879
+
880
+ if (answer.decision === 'park') {
881
+ // M3 scope item 1 (fixes F43): the wait is ALWAYS the signed ttlMs —
882
+ // no code default ever overrides it, on the first park or any re-park.
883
+ const askId = randomUUID();
884
+ const askedAt = now();
885
+ const expiresAt = new Date(Date.parse(askedAt) + askSlot.ttlMs).toISOString();
886
+ // F45 finding 2: a parked ask.json must carry the SAME evidence a
887
+ // human sees in-process (`makeFileAskStep`'s `{ artifact, unjudged }`)
888
+ // — the draft under review and the unjudged evidence, never just the
889
+ // question. `evidence` above is already recomputed at the top of every
890
+ // loop iteration (including a re-park after a reject, where
891
+ // `currentPrior` is the just-redrafted artifact), so this write always
892
+ // carries the CURRENT evidence, not a stale first-park copy.
893
+ writeFileSync(join(runDir, 'ask.json'), JSON.stringify({
894
+ askId, question: askSlot?.question ?? step.goal, askedAt, expiresAt, evidence,
895
+ }, null, 2));
896
+ // M3 scope item 2: the minimum the fold needs to resume identically —
897
+ // WHERE (stepIndex), WHAT was frozen/signed (signatureHash,
898
+ // inputsManifest, to be re-verified before anything runs), WHAT this
899
+ // ask is (askId/expiresAt), and the two accumulators a mid-ask resume
900
+ // cannot recompute from disk alone: `redone` (the redo cap is spent
901
+ // across pauses, not per process) and the evidence bundle this
902
+ // specific ask already showed the human (`evidenceUnjudged`/
903
+ // `unjudgedCount` — recomputing them from `unjudgedSinceLastAsk` on
904
+ // resume would double-count anything a later, still-unparked ask
905
+ // hasn't reset yet). `spent` carries the run's money across pauses too
906
+ // (the cap binds over the whole run, never per process).
907
+ const state = {
908
+ runId,
909
+ flow: { root: flowRoot, name: flowName },
910
+ signatureHash,
911
+ inputsManifest,
912
+ stepIndex,
913
+ askId,
914
+ expiresAt,
915
+ spent: spent.value,
916
+ // Orchestrator review fix (4): the floor persists across a pause —
917
+ // once any pre-park row left `spendComplete: false`, a resume must
918
+ // inherit that, never quietly start "complete" again.
919
+ spendComplete: spendComplete.value,
920
+ redone,
921
+ evidenceUnjudged,
922
+ unjudgedCount,
923
+ // F45 finding 3: persisted every park/re-park (unchanged value, just
924
+ // carried forward) so `resumeRun` restores the run's true start
925
+ // instead of timing only the process that happens to resume it.
926
+ startedAt: runStartedAt,
927
+ };
928
+ writeFileSync(join(runDir, 'state.json'), JSON.stringify(state, null, 2));
929
+ recordAudit(makeAuditRow({
930
+ step, attempt: redone + 1, verdict: 'paused', gap: null, usd: 0, spendComplete: true, wallMs: 0, strike: false,
931
+ }), undefined, unjudgedCount);
932
+ // Orchestrator review fix (3): M2 item 9 says history is ONE row per
933
+ // run; M3's signed scope item 2 only asks for an AUDIT row "paused"
934
+ // (already recorded above). A "paused" HISTORY row was the earlier
935
+ // draft's own error — removed here. The run's one history row lands
936
+ // at its final outcome (complete / a halt / ask-expired), written by
937
+ // `foldFromStep`/`resumeRun`, never here.
938
+ writeLog(runDir, { runId, outcome: 'paused', attempts: attemptsLog, artifacts });
939
+ return {
940
+ type: 'paused',
941
+ result: {
942
+ outcome: 'paused', runDir, askId, expiresAt, spentUsd: spent.value,
943
+ },
944
+ };
945
+ }
946
+
947
+ if (answer.decision === 'timeout') {
948
+ // A pause spends nothing (M2 scope item 6) — a halt, never a red
949
+ // with a fabricated cost, and never re-asked (the run is over).
950
+ recordAudit(makeAuditRow({
951
+ step, attempt: redone + 1, verdict: 'ask-timeout', gap: null, usd: 0, spendComplete: true, wallMs: 0, strike: false,
952
+ }), undefined, unjudgedCount);
953
+ return {
954
+ type: 'halted',
955
+ outcome: 'ask-timeout',
956
+ red: `ask-timeout: step "${step.goal}" expired waiting for a human answer`,
957
+ };
958
+ }
959
+
960
+ const isRedo = answer.decision === 'reject' || answer.decision === 'rerun';
961
+ const reason = typeof answer.reason === 'string' ? answer.reason.trim() : '';
962
+
963
+ if (isRedo && reason.length === 0) {
964
+ recordAudit(makeAuditRow({
965
+ step, attempt: redone + 1, verdict: 'refused', gap: 'a rejection/rerun needs a reason', usd: 0, spendComplete: true, wallMs: 0, strike: false,
966
+ }), undefined, unjudgedCount);
967
+ // Refused, re-asked for the SAME attempt — never re-runs the step.
968
+ // eslint-disable-next-line no-continue
969
+ continue;
970
+ }
971
+
972
+ if (answer.decision === 'accept') {
973
+ recordAudit(makeAuditRow({
974
+ step, attempt: redone + 1, verdict: 'green', gap: null, usd: 0, spendComplete: true, wallMs: 0, strike: false,
975
+ }), undefined, unjudgedCount);
976
+ return { type: 'accepted', artifact: currentPrior };
977
+ }
978
+
979
+ if (isRedo) {
980
+ redone += 1;
981
+ recordAudit(makeAuditRow({
982
+ step, attempt: redone, verdict: 'red', gap: reason, usd: 0, spendComplete: true, wallMs: 0, strike: false,
983
+ }), undefined, unjudgedCount);
984
+ if (redone > redoCap) {
985
+ return {
986
+ type: 'halted',
987
+ outcome: 'redo-halt',
988
+ red: `redo cap ${redoCap} reached at step "${step.goal}" after ${redone} rejections`,
989
+ };
990
+ }
991
+ const priorReads = readArtifactsMap(runDir, priorStep.reads);
992
+ // eslint-disable-next-line no-await-in-loop
993
+ const redoResult = await runStepRalph({
994
+ step: priorStep, primitivesMap: primitives, readsMap: priorReads, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, initialGap: reason, attemptOffset: redone,
995
+ });
996
+ if (!redoResult.ok) {
997
+ return { type: 'halted', outcome: redoResult.outcome, red: redoResult.red };
998
+ }
999
+ currentPrior = redoResult.artifact;
1000
+ // A redo deliberately REPLACES the prior step's own artifact — the one
1001
+ // case `writeArtifact` allows to overwrite on purpose.
1002
+ writeArtifact(runDir, priorId, currentPrior, { overwrite: true });
1003
+ artifacts[priorId] = currentPrior;
1004
+ // eslint-disable-next-line no-continue
1005
+ continue;
1006
+ }
1007
+
1008
+ return {
1009
+ type: 'halted',
1010
+ outcome: 'red',
1011
+ red: `ask: step "${step.goal}" got an unrecognised decision "${answer.decision}"`,
1012
+ };
1013
+ }
1014
+ }
1015
+
1016
+ /**
1017
+ * The fold itself (M2 scope item 1's "one fold", now start-anywhere): walks
1018
+ * `steps` from `i0`, handling the signed send slot, the signed ask slot (via
1019
+ * `runAskSlot`), and ordinary steps exactly as `runFlow` always did. Used by
1020
+ * `runFlow` (i0 = 0, fresh accumulators) and by `resumeRun` (i0 = the step
1021
+ * AFTER the ask it just resolved, accumulators restored from `state.json`
1022
+ * plus disk).
1023
+ * @returns {Promise<any>}
1024
+ */
1025
+ async function foldFromStep({
1026
+ i0, steps, askLines, sendLines, askStepEmits, runDir, flowDir, runId, flowRoot, flowName, signatureHash,
1027
+ inputsManifest, capUsd, redoCap, effectiveCeilingUsd, primitives, businessDate, modelStep, askStep, sendStep,
1028
+ // F45 finding 3: `startedAt` times only THIS process (used for the pre-fold
1029
+ // halts in `runFlow` and as this call's own fallback below); `runStartedAt`
1030
+ // is the run's true wall-clock start, persisted at park and restored on
1031
+ // every resume — every halt/complete a fold reaches must time itself
1032
+ // against `runStartedAt`, never the current process's own start, or a
1033
+ // resumed run's wallMs collapses to "how long did this resume take" (F45's
1034
+ // observed 19ms). Defaults to `startedAt` for a fresh run, where they are
1035
+ // the same instant.
1036
+ now, startedAt, runStartedAt = startedAt, nowMs = Date.now, spent, spendComplete, artifacts, acceptedThisRun, acceptedAskEmitsThisRun, unjudgedSinceLastAsk,
1037
+ recordAudit, attemptsLog,
1038
+ // M3 scope item 7: a fresh rerun's own reason, carried as step `i0`'s
1039
+ // starting gap (never any later step's). `/** @type */` here (rather than
1040
+ // a JSDoc `@param opts.firstStepGap`, which would need a preceding typed
1041
+ // `@param {object} opts` this function's block comment never declared)
1042
+ // is what keeps every OTHER destructured field's inferred type intact.
1043
+ firstStepGap = /** @type {string|null} */ (null),
1044
+ }) {
1045
+ let runAcceptedThisRun = acceptedThisRun;
1046
+ let runUnjudged = unjudgedSinceLastAsk;
1047
+
1048
+ for (let i = i0; i < steps.length; i += 1) {
1049
+ const step = steps[i];
1050
+
1051
+ // --- the signed send slot: never through modelStep, only after an
1052
+ // accept THIS run, re-checked at write time. ---
1053
+ if (sendLines.has(step.fromLine)) {
1054
+ if (!runAcceptedThisRun) {
1055
+ return haltRun({
1056
+ flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts,
1057
+ outcome: 'red', red: `send: step "${step.goal}" reached with no accept this run`,
1058
+ });
1059
+ }
1060
+ const sendSlot = sendLines.get(step.fromLine);
1061
+ if (!sendSlot) {
1062
+ return haltRun({
1063
+ flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts, outcome: 'red', red: `send: no arbiter slot bound to line ${step.fromLine}`,
1064
+ });
1065
+ }
1066
+ const target = `${sendSlot.target.kind}:${sendSlot.target.path}`;
1067
+ // The send's content is identified by IDENTITY (the artifact emitted
1068
+ // by the ONE earlier signed ask step this send reads) — never by
1069
+ // position in `reads`. `readFlow`/`validateDeclaration` already
1070
+ // refuse, at signing time, any declaration whose send step doesn't
1071
+ // read the emits of exactly one earlier signed ask (M3 item 8); every
1072
+ // path into this fold goes through `readFlow` first, so `askIdsInReads`
1073
+ // is always exactly 1 here.
1074
+ const [askArtifactId] = (step.reads ?? []).filter((id) => askStepEmits.has(id));
1075
+ if (!acceptedAskEmitsThisRun.has(askArtifactId)) {
1076
+ return haltRun({
1077
+ flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts,
1078
+ outcome: 'red', red: `send: step "${step.goal}" reads ask artifact "${askArtifactId}" that was not accepted this run`,
1079
+ });
1080
+ }
1081
+ const content = readArtifact(runDir, askArtifactId);
1082
+ const filename = `${runId}-${step.emits}.json`;
1083
+ // eslint-disable-next-line no-await-in-loop
1084
+ const sendResult = await sendStep(target, filename, content);
1085
+ const sendRow = makeAuditRow({
1086
+ step, attempt: 1, verdict: sendResult.ok ? 'green' : 'red', gap: sendResult.ok ? null : sendResult.red, usd: 0, spendComplete: true, wallMs: 0, strike: false,
1087
+ });
1088
+ recordAudit(sendRow);
1089
+ if (!sendResult.ok) {
1090
+ return haltRun({
1091
+ flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts, outcome: 'red', red: `send: ${sendResult.red}`,
1092
+ });
1093
+ }
1094
+ writeArtifact(runDir, step.emits, content);
1095
+ artifacts[step.emits] = content;
1096
+ // eslint-disable-next-line no-continue
1097
+ continue;
1098
+ }
1099
+
1100
+ // --- the signed ask slot: interactive, consume-once, reason-gated redo,
1101
+ // OR park-and-exit (M3 scope item 2). ---
1102
+ if (askLines.has(step.fromLine)) {
1103
+ const askSlot = askLines.get(step.fromLine);
1104
+ const priorId = (step.reads ?? [])[0];
1105
+ const priorStepIndex = steps.findIndex((s) => s.emits === priorId);
1106
+ const priorArtifact = readArtifact(runDir, priorId);
1107
+
1108
+ // M2 amendment 1 item 2: every hitl artifact carried since the
1109
+ // previous ask goes to THIS ask as evidence, alongside the ask step's
1110
+ // own artifact — then the list resets (a fresh accumulator for the
1111
+ // NEXT ask), so a later ask never re-shows what an earlier one covered.
1112
+ const evidenceUnjudged = runUnjudged;
1113
+ const unjudgedCount = evidenceUnjudged.length;
1114
+ runUnjudged = [];
1115
+
1116
+ // eslint-disable-next-line no-await-in-loop
1117
+ const askResult = await runAskSlot({
1118
+ step,
1119
+ stepIndex: i,
1120
+ askSlot,
1121
+ priorId,
1122
+ priorStep: steps[priorStepIndex],
1123
+ priorArtifact,
1124
+ redoCap,
1125
+ effectiveCeilingUsd,
1126
+ capUsd,
1127
+ primitives,
1128
+ businessDate,
1129
+ modelStep,
1130
+ askStep,
1131
+ spent,
1132
+ spendComplete,
1133
+ recordAudit,
1134
+ evidenceUnjudged,
1135
+ unjudgedCount,
1136
+ redone: 0,
1137
+ runDir,
1138
+ flowDir,
1139
+ runId,
1140
+ flowRoot,
1141
+ flowName,
1142
+ signatureHash,
1143
+ inputsManifest,
1144
+ attemptsLog,
1145
+ artifacts,
1146
+ now,
1147
+ startedAt,
1148
+ runStartedAt,
1149
+ });
1150
+
1151
+ if (askResult.type === 'paused') return askResult.result;
1152
+ if (askResult.type === 'halted') {
1153
+ return haltRun({
1154
+ flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts, outcome: askResult.outcome, red: askResult.red,
1155
+ });
1156
+ }
1157
+
1158
+ writeArtifact(runDir, step.emits, askResult.artifact);
1159
+ artifacts[step.emits] = askResult.artifact;
1160
+ runAcceptedThisRun = true;
1161
+ acceptedAskEmitsThisRun.add(step.emits);
1162
+ // eslint-disable-next-line no-continue
1163
+ continue;
1164
+ }
1165
+
1166
+ // --- an ordinary step: green / softgreen / a non-ask hitl pass-through. ---
1167
+ const readsMap = readArtifactsMap(runDir, step.reads);
1168
+ // M3 scope item 7: a fresh rerun's own first step (and only that one —
1169
+ // `i === i0` is this fold's own starting point, never any later step)
1170
+ // starts with the human's rerun reason as its gap, exactly like a
1171
+ // redo's `initialGap` above.
1172
+ // eslint-disable-next-line no-await-in-loop
1173
+ const stepResult = await runStepRalph({
1174
+ step, primitivesMap: primitives, readsMap, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, initialGap: i === i0 ? firstStepGap : null,
1175
+ });
1176
+ if (!stepResult.ok) {
1177
+ return haltRun({
1178
+ flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts, outcome: stepResult.outcome, red: stepResult.red,
1179
+ });
1180
+ }
1181
+ writeArtifact(runDir, step.emits, stepResult.artifact);
1182
+ artifacts[step.emits] = stepResult.artifact;
1183
+ // M2 amendment 1 item 2: a hitl-class step not bound to a signed ask
1184
+ // line (the routing above already guarantees that — this branch is only
1185
+ // reached when neither askLines nor sendLines claimed the step) passes
1186
+ // through silently here; carry it as evidence for the NEXT signed ask.
1187
+ if (stepResult.hitl) {
1188
+ runUnjudged.push({ step: step.goal ?? null, emits: step.emits, artifact: stepResult.artifact });
1189
+ }
1190
+ }
1191
+
1192
+ // F45 finding 3: the run's history row times the whole run, from its
1193
+ // FIRST process's start (`runStartedAt`, never this process's own
1194
+ // `startedAt`) to right now. A pause counts as elapsed wall time — the
1195
+ // run really was sitting there waiting on a human, so it belongs in
1196
+ // "how long did this run take", not carved out of it.
1197
+ const wallMs = nowMs() - runStartedAt;
1198
+ appendHistory(flowDir, {
1199
+ runId, at: now(), outcome: 'complete', spentUsd: spent.value, spendComplete: spendComplete.value, capUsd, wallMs, signatureHash,
1200
+ });
1201
+ recordLateAnswerIfAny(runDir);
1202
+ writeLog(runDir, {
1203
+ runId, outcome: 'complete', attempts: attemptsLog, artifacts,
1204
+ });
1205
+ return {
1206
+ outcome: 'complete', runDir, artifacts, spentUsd: spent.value,
1207
+ };
1208
+ }
1209
+
1210
+ /**
1211
+ * Debrief fix: sums a run's own `audit.jsonl` — the books are the source of
1212
+ * truth for money already spent, so `state.spent` (a value carried in a
1213
+ * separately-writable state.json) is cross-checked against it before a
1214
+ * resume trusts it under the cap. Every row's `usd` here is expected to be
1215
+ * a finite number (the audit rows a park can precede — attempts, the pause
1216
+ * itself — never carry `usd: null`; only a `cap-halt` row does, and a
1217
+ * cap-halt ends the run without parking, so it can never appear in a
1218
+ * resumable run's audit.jsonl). A row this function cannot price refuses
1219
+ * rather than guessing (never `?? 0`, never skipped).
1220
+ * @param {string} runDir
1221
+ * @returns {{ ok: true, total: number } | { ok: false, red: string }}
1222
+ */
1223
+ function sumAuditUsd(runDir) {
1224
+ const auditPath = join(runDir, 'audit.jsonl');
1225
+ if (!existsSync(auditPath)) return { ok: true, total: 0 };
1226
+ const lines = readFileSync(auditPath, 'utf8').split('\n').filter((line) => line.trim().length > 0);
1227
+ let total = 0;
1228
+ for (const line of lines) {
1229
+ let row;
1230
+ try {
1231
+ row = JSON.parse(line);
1232
+ } catch (err) {
1233
+ return { ok: false, red: `audit.jsonl line is not valid JSON — ${err.message}` };
1234
+ }
1235
+ if (typeof row.usd !== 'number' || !Number.isFinite(row.usd)) {
1236
+ 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` };
1237
+ }
1238
+ total += row.usd;
1239
+ }
1240
+ return { ok: true, total };
1241
+ }
1242
+
1243
+ /**
1244
+ * M3 scope items 4-6: re-enter a parked run's SAME fold from a separate
1245
+ * process. Takes an exclusive `resume.lock` (refuses by name if already
1246
+ * held; a lock left behind by a killed resumer is a red naming it, never
1247
+ * stolen), re-reads the flow, refuses by name at $0 on any signature/input/
1248
+ * missing-artifact mismatch, consumes `answer.json` by atomic rename BEFORE
1249
+ * acting (F44), then either cancels an expired ask ($0, nothing sent) or
1250
+ * resolves it and folds on to `complete`/the next pause/a halt.
1251
+ *
1252
+ * @param {object} opts
1253
+ * @param {string} opts.root
1254
+ * @param {string} opts.name
1255
+ * @param {string} opts.runId
1256
+ * @param {unknown} opts.catalogue
1257
+ * @param {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class:string|null}) => Promise<any>} opts.modelStep
1258
+ * @param {(target:string, filename:string, content:unknown) => Promise<{ok:boolean, red?:string, bytes?:number}>} opts.sendStep
1259
+ * @param {Record<string, any>} [opts.primitives]
1260
+ * @param {() => string} [opts.clock]
1261
+ * @param {string} opts.businessDate
1262
+ * @param {number} [opts.ceilingUsd]
1263
+ * @param {() => number} [opts.nowMs] - F45 finding 3; see `runFlow`'s own.
1264
+ */
1265
+ export async function resumeRun({
1266
+ root, name, runId, catalogue, modelStep, sendStep, primitives, clock, businessDate, ceilingUsd,
1267
+ // F45 finding 3 (see `runFlow`'s own `nowMs`): additive, defaults to the
1268
+ // real `Date.now` for every existing caller.
1269
+ nowMs,
1270
+ }) {
1271
+ const now = typeof clock === 'function' ? clock : () => new Date().toISOString();
1272
+ const getNowMs = typeof nowMs === 'function' ? nowMs : Date.now;
1273
+ const flowDir = join(root, name);
1274
+ const runDir = join(flowDir, 'runs', runId);
1275
+ const startedAt = getNowMs();
1276
+ const lockPath = join(runDir, 'resume.lock');
1277
+
1278
+ let lockFd;
1279
+ try {
1280
+ lockFd = openSync(lockPath, 'wx');
1281
+ } catch (err) {
1282
+ if (err.code === 'EEXIST') {
1283
+ return { outcome: 'refused', red: `resume: run "${runId}" is locked by another resumer (${lockPath})` };
1284
+ }
1285
+ return { outcome: 'refused', red: `resume: could not create lock ${lockPath} — ${err.message}` };
1286
+ }
1287
+
1288
+ try {
1289
+ const statePath = join(runDir, 'state.json');
1290
+ if (!existsSync(statePath)) {
1291
+ return { outcome: 'refused', red: `resume: no parked state for run "${runId}" (${statePath})` };
1292
+ }
1293
+ let state;
1294
+ try {
1295
+ state = JSON.parse(readFileSync(statePath, 'utf8'));
1296
+ } catch (err) {
1297
+ return { outcome: 'refused', red: `resume: state.json for run "${runId}" is not valid JSON — ${err.message}` };
1298
+ }
1299
+
1300
+ // F45 finding 3: the run's TRUE wall-clock start, restored from the
1301
+ // parked state rather than this process's own `startedAt` — otherwise
1302
+ // every resume's history/audit `wallMs` times just that resume (F45's
1303
+ // observed 19ms), not the run. Falls back to this process's own start
1304
+ // for a run parked BEFORE this fix (no `state.startedAt` on disk) —
1305
+ // not a money field, so a best-known fallback rather than a refusal.
1306
+ const runStartedAt = typeof state.startedAt === 'number' ? state.startedAt : startedAt;
1307
+
1308
+ // Orchestrator review fix (6): the CALLER's `root`/`name` are the source
1309
+ // of truth — never `state.flow.root`/`state.flow.name` silently. A
1310
+ // parked run whose recorded flow location disagrees with what THIS call
1311
+ // was asked to resume is refused by name, never re-read from wherever
1312
+ // the state file happens to point.
1313
+ if (state.flow?.root !== root || state.flow?.name !== name) {
1314
+ return {
1315
+ outcome: 'refused',
1316
+ red: `resume: run "${runId}" was parked against flow "${state.flow?.root}/${state.flow?.name}", `
1317
+ + `not the requested "${root}/${name}" — refusing rather than reading a different flow than asked`,
1318
+ };
1319
+ }
1320
+
1321
+ const read = readFlow({ root, name, catalogue });
1322
+ if (!read.ok) {
1323
+ return { outcome: 'refused', red: `resume: flow re-read failed for run "${runId}": ${read.reds.join('; ')}` };
1324
+ }
1325
+ const { declaration, arbiter, signature } = read;
1326
+
1327
+ if (signature.flow !== state.signatureHash) {
1328
+ return { outcome: 'refused', red: `resume: signature mismatch for run "${runId}" — the flow changed while parked` };
1329
+ }
1330
+
1331
+ for (const entry of state.inputsManifest ?? []) {
1332
+ if (!existsSync(entry.frozen)) {
1333
+ return { outcome: 'refused', red: `resume: frozen input "${entry.id}" missing for run "${runId}" (${entry.frozen})` };
1334
+ }
1335
+ const sha256 = createHash('sha256').update(readFileSync(entry.frozen)).digest('hex');
1336
+ if (sha256 !== entry.sha256) {
1337
+ return { outcome: 'refused', red: `resume: frozen input "${entry.id}" changed while parked for run "${runId}"` };
1338
+ }
1339
+ }
1340
+
1341
+ const { steps } = declaration;
1342
+ for (let i = 0; i < state.stepIndex; i += 1) {
1343
+ if (readArtifact(runDir, steps[i].emits) === undefined) {
1344
+ return { outcome: 'refused', red: `resume: artifact "${steps[i].emits}" missing for run "${runId}" — cannot resume` };
1345
+ }
1346
+ }
1347
+
1348
+ // Orchestrator review fix (1): unknown cost is never rendered as 0 — a
1349
+ // missing/non-number/non-finite `state.spent` refuses the resume by
1350
+ // name (naming the run AND the field), $0 further spend, rather than
1351
+ // silently treating an unreadable ledger as "nothing spent yet". Checked
1352
+ // BEFORE the answer is consumed — a refusal here must be replayable.
1353
+ if (typeof state.spent !== 'number' || !Number.isFinite(state.spent)) {
1354
+ return {
1355
+ outcome: 'refused',
1356
+ red: `resume: run "${runId}" state.json field "spent" is not a finite number (got ${JSON.stringify(state.spent)}) — `
1357
+ + 'unknown cost is never rendered as 0; refusing further spend',
1358
+ };
1359
+ }
1360
+ // Debrief fix: a negative spend is an impossible cost, never a number
1361
+ // the cap can trust — refused the same way as a non-finite one.
1362
+ if (state.spent < 0) {
1363
+ return {
1364
+ outcome: 'refused',
1365
+ red: `resume: run "${runId}" state.json field "spent" is negative (${state.spent}) — `
1366
+ + 'an impossible cost is never trusted by the cap; refusing further spend',
1367
+ };
1368
+ }
1369
+ // Debrief fix: the run's own audit.jsonl is the books' source of truth
1370
+ // for money already spent — if state.spent claims LESS than what the
1371
+ // audit already recorded, state.spent is wrong (or tampered) and must
1372
+ // never be trusted to gate further spend under the cap.
1373
+ const auditSum = sumAuditUsd(runDir);
1374
+ if (!auditSum.ok) {
1375
+ return { outcome: 'refused', red: `resume: run "${runId}" ${auditSum.red}` };
1376
+ }
1377
+ if (auditSum.total - state.spent > SPEND_TOLERANCE_USD) {
1378
+ return {
1379
+ outcome: 'refused',
1380
+ red: `resume: run "${runId}" state.json field "spent" ($${state.spent}) is less than its own audit.jsonl sum ($${auditSum.total}) — `
1381
+ + "the books are the source of truth for money already spent; refusing rather than trusting state.json's lower figure",
1382
+ };
1383
+ }
1384
+ const spent = { value: state.spent };
1385
+ // Orchestrator review fix (4): a floor persisted across the pause
1386
+ // (`state.spendComplete`) is restored here, never quietly reset to
1387
+ // `true` — an absent/non-boolean value defaults to `false` (unknown
1388
+ // never renders as "complete"), never `true`.
1389
+ const spendComplete = { value: state.spendComplete === true };
1390
+
1391
+ // A present-but-unparseable `state.expiresAt` (Date.parse -> NaN) must
1392
+ // never read as "not expired" — `NaN > x`/`x > NaN` are both false, so
1393
+ // the real expiry compare below would silently treat garbage as open
1394
+ // forever. Refused here, naming the run, BEFORE the answer is consumed
1395
+ // (same "checked before consuming" rule as the spent check above — a
1396
+ // refusal here must be replayable).
1397
+ if (Number.isNaN(Date.parse(state.expiresAt))) {
1398
+ return {
1399
+ outcome: 'refused',
1400
+ red: `resume: run "${runId}" state.json field "expiresAt" ("${state.expiresAt}") is not a parseable date — `
1401
+ + 'refusing rather than treating it as not-expired',
1402
+ };
1403
+ }
1404
+
1405
+ const answerPath = join(runDir, 'answer.json');
1406
+ if (!existsSync(answerPath)) {
1407
+ return { outcome: 'refused', red: `resume: no answer yet for run "${runId}"` };
1408
+ }
1409
+ let answer;
1410
+ try {
1411
+ answer = JSON.parse(readFileSync(answerPath, 'utf8'));
1412
+ } catch (err) {
1413
+ return { outcome: 'refused', red: `resume: answer.json for run "${runId}" is not valid JSON — ${err.message}` };
1414
+ }
1415
+ if (answer.askId !== state.askId) {
1416
+ return { outcome: 'refused', red: `resume: answer askId "${answer.askId}" does not match open askId "${state.askId}" for run "${runId}"` };
1417
+ }
1418
+
1419
+ // Consume-once, BEFORE acting on the decision (F44) — the rename is
1420
+ // itself a one-winner gate, on top of the lock above.
1421
+ const consumedPath = join(runDir, `answer.${answer.askId}.consumed.json`);
1422
+ renameSync(answerPath, consumedPath);
1423
+
1424
+ // The run's own injected clock governs expiry, exactly like every other
1425
+ // "now" in this module (never the bare wall clock) — the same fixed
1426
+ // clock a test controls for `runFlow` also controls what "expired" means
1427
+ // for `resumeRun`, with no real wait required to prove it.
1428
+ if (Date.parse(now()) > Date.parse(state.expiresAt)) {
1429
+ // Negative (i): an answer arriving after expiry cancels the run —
1430
+ // adds NOTHING further, but the run's own already-spent total is
1431
+ // real money and must be reported, never coerced to 0 (orchestrator
1432
+ // review fix 2: "a pause spends nothing" means the pause adds
1433
+ // nothing, not that the run's total resets).
1434
+ appendAudit(runDir, {
1435
+ step: null, attempt: null, class: null, verdict: 'ask-expired', gap: null, usd: 0, spendComplete: true, wallMs: 0, model: null, modelMatch: null, strike: false,
1436
+ });
1437
+ appendHistory(flowDir, {
1438
+ runId, at: now(), outcome: 'ask-expired', spentUsd: spent.value, spendComplete: spendComplete.value, capUsd: arbiter.capUsd ?? null, wallMs: getNowMs() - runStartedAt, signatureHash: state.signatureHash,
1439
+ });
1440
+ return { outcome: 'ask-expired', runDir, spentUsd: spent.value };
1441
+ }
1442
+
1443
+ if (answer.decision === 'rerun') {
1444
+ // M3 scope item 7 (hamr "2A"): `rerun` ends THIS run (one history row,
1445
+ // `rerun`, its real spend, $0 added) and starts a brand-new run on the
1446
+ // same signed flow — never a redo of the step before the ask.
1447
+ const reason = typeof answer.reason === 'string' ? answer.reason.trim() : '';
1448
+ if (reason.length === 0) {
1449
+ // `answerAsk` already refuses a blank reason at write time — this
1450
+ // re-check exists because `resumeRun` never trusts a file it did
1451
+ // not itself just validate, same as every other field read above.
1452
+ return { outcome: 'refused', red: `resume: rerun answer for run "${runId}" carries a blank reason` };
1453
+ }
1454
+
1455
+ const priorArtifactsForLog = {};
1456
+ for (let i = 0; i < state.stepIndex; i += 1) {
1457
+ priorArtifactsForLog[steps[i].emits] = readArtifact(runDir, steps[i].emits);
1458
+ }
1459
+ appendHistory(flowDir, {
1460
+ runId, at: now(), outcome: 'rerun', spentUsd: spent.value, spendComplete: spendComplete.value, capUsd: arbiter.capUsd ?? null, wallMs: getNowMs() - runStartedAt, signatureHash: state.signatureHash,
1461
+ });
1462
+ recordLateAnswerIfAny(runDir);
1463
+ writeLog(runDir, { runId, outcome: 'rerun', attempts: [], artifacts: priorArtifactsForLog });
1464
+
1465
+ // Deterministic derived id (M3 scope item 7) — refused by name, never
1466
+ // silently renumbered, if it already exists.
1467
+ const newRunId = `${runId}-rerun-1`;
1468
+ const newRunDir = join(flowDir, 'runs', newRunId);
1469
+ if (existsSync(newRunDir)) {
1470
+ return {
1471
+ outcome: 'refused',
1472
+ red: `resume: rerun target run "${newRunId}" already exists for run "${runId}" — refused`,
1473
+ };
1474
+ }
1475
+
1476
+ // Fresh inputs, re-frozen from the ORIGINAL source paths — carried in
1477
+ // `inputsManifest[].source` since `freezeInputs` first wrote it (M3
1478
+ // scope item 7's own note: "persist those in state.json at park if
1479
+ // they aren't already" — they already are, via this field).
1480
+ const rerunSources = (state.inputsManifest ?? []).map((entry) => ({ id: entry.id, path: entry.source }));
1481
+
1482
+ const newRun = await runFlow({
1483
+ root,
1484
+ name,
1485
+ runId: newRunId,
1486
+ sources: rerunSources,
1487
+ catalogue,
1488
+ modelStep,
1489
+ // A fresh run never waits in-process — any signed ask it reaches
1490
+ // parks immediately, exactly like any other `runFlow` call this
1491
+ // piece drives.
1492
+ askStep: makeParkingAskStep(),
1493
+ sendStep,
1494
+ primitives,
1495
+ clock,
1496
+ businessDate,
1497
+ ceilingUsd,
1498
+ // Item 7: the reason becomes the new run's FIRST step's starting gap.
1499
+ initialGap: reason,
1500
+ });
1501
+
1502
+ return {
1503
+ outcome: 'rerun', runDir, runId, newRunId, spentUsd: spent.value, newRun,
1504
+ };
1505
+ }
1506
+
1507
+ if (answer.decision !== 'accept' && answer.decision !== 'reject') {
1508
+ return { outcome: 'refused', red: `resume: unrecognised decision "${answer.decision}" for run "${runId}"` };
1509
+ }
1510
+
1511
+ // Reconstruct the fold's accumulators from disk + state.json — never
1512
+ // re-running a step that already went green (M3 scope item 4).
1513
+ const artifacts = {};
1514
+ for (let i = 0; i < state.stepIndex; i += 1) {
1515
+ artifacts[steps[i].emits] = readArtifact(runDir, steps[i].emits);
1516
+ }
1517
+ const askLines = new Map((arbiter.asks ?? []).map((a) => [a.line, a]));
1518
+ const sendLines = new Map((arbiter.sends ?? []).map((s) => [s.line, s]));
1519
+ const askStepEmits = new Set(steps.filter((s) => askLines.has(s.fromLine)).map((s) => s.emits));
1520
+ const acceptedAskEmitsThisRun = new Set();
1521
+ for (const emits of askStepEmits) {
1522
+ const idx = steps.findIndex((s) => s.emits === emits);
1523
+ if (idx !== -1 && idx < state.stepIndex && readArtifact(runDir, emits) !== undefined) {
1524
+ acceptedAskEmitsThisRun.add(emits);
1525
+ }
1526
+ }
1527
+
1528
+ const attemptsLog = [];
1529
+ const auditRows = [];
1530
+ const recordAudit = (row, modelOutput, unjudgedCount) => {
1531
+ const fullRow = unjudgedCount === undefined ? row : { ...row, unjudgedCount };
1532
+ auditRows.push(fullRow);
1533
+ appendAudit(runDir, fullRow);
1534
+ if (row.spendComplete === false) spendComplete.value = false;
1535
+ if (modelOutput !== undefined) {
1536
+ attemptsLog.push({
1537
+ step: row.step, attempt: row.attempt, class: row.class, verdict: row.verdict, gap: row.gap, modelOutput,
1538
+ });
1539
+ }
1540
+ };
1541
+
1542
+ const capUsd = arbiter.capUsd;
1543
+ const redoCap = arbiter.redoCap ?? 3;
1544
+ const effectiveCeilingUsd = ceilingUsd ?? resolveCeilingUsd(null);
1545
+
1546
+ const step = steps[state.stepIndex];
1547
+ const askSlot = askLines.get(step.fromLine);
1548
+ const priorId = (step.reads ?? [])[0];
1549
+ const priorStepIndex = steps.findIndex((s) => s.emits === priorId);
1550
+ const priorArtifact = readArtifact(runDir, priorId);
1551
+
1552
+ const oneShotAskStep = makeOneShotThenParkAskStep({ decision: answer.decision, reason: answer.reason });
1553
+
1554
+ const askResult = await runAskSlot({
1555
+ step,
1556
+ stepIndex: state.stepIndex,
1557
+ askSlot,
1558
+ priorId,
1559
+ priorStep: steps[priorStepIndex],
1560
+ priorArtifact,
1561
+ redoCap,
1562
+ effectiveCeilingUsd,
1563
+ capUsd,
1564
+ primitives,
1565
+ businessDate,
1566
+ modelStep,
1567
+ askStep: oneShotAskStep,
1568
+ spent,
1569
+ spendComplete,
1570
+ recordAudit,
1571
+ evidenceUnjudged: state.evidenceUnjudged ?? [],
1572
+ unjudgedCount: state.unjudgedCount ?? 0,
1573
+ redone: typeof state.redone === 'number' ? state.redone : 0,
1574
+ runDir,
1575
+ flowDir,
1576
+ runId,
1577
+ flowRoot: root,
1578
+ flowName: name,
1579
+ signatureHash: state.signatureHash,
1580
+ inputsManifest: state.inputsManifest,
1581
+ attemptsLog,
1582
+ artifacts,
1583
+ now,
1584
+ startedAt,
1585
+ runStartedAt,
1586
+ });
1587
+
1588
+ if (askResult.type === 'paused') return askResult.result;
1589
+ if (askResult.type === 'halted') {
1590
+ return haltRun({
1591
+ 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,
1592
+ });
1593
+ }
1594
+
1595
+ // accepted — write the ask step's own artifact, then fold on to
1596
+ // whatever comes next (another signed ask parks again; the ordinary
1597
+ // send/step path completes exactly as `runFlow` would have, in-process).
1598
+ writeArtifact(runDir, step.emits, askResult.artifact);
1599
+ artifacts[step.emits] = askResult.artifact;
1600
+ acceptedAskEmitsThisRun.add(step.emits);
1601
+
1602
+ const result = await foldFromStep({
1603
+ i0: state.stepIndex + 1,
1604
+ steps,
1605
+ askLines,
1606
+ sendLines,
1607
+ askStepEmits,
1608
+ runDir,
1609
+ flowDir,
1610
+ runId,
1611
+ flowRoot: root,
1612
+ flowName: name,
1613
+ signatureHash: state.signatureHash,
1614
+ inputsManifest: state.inputsManifest,
1615
+ capUsd,
1616
+ redoCap,
1617
+ effectiveCeilingUsd,
1618
+ primitives,
1619
+ businessDate,
1620
+ modelStep,
1621
+ // A resumed run never waits in-process — any FURTHER signed ask it
1622
+ // reaches parks immediately too, under its own signed ttl.
1623
+ askStep: makeParkingAskStep(),
1624
+ sendStep,
1625
+ now,
1626
+ startedAt,
1627
+ runStartedAt,
1628
+ nowMs: getNowMs,
1629
+ spent,
1630
+ spendComplete,
1631
+ artifacts,
1632
+ acceptedThisRun: true,
1633
+ acceptedAskEmitsThisRun,
1634
+ unjudgedSinceLastAsk: [],
1635
+ recordAudit,
1636
+ attemptsLog,
1637
+ });
1638
+
1639
+ if (result.outcome === 'complete') return { ...result, auditRows };
1640
+ return result;
1641
+ } finally {
1642
+ try { closeSync(lockFd); } catch { /* already closed */ }
1643
+ try { unlinkSync(lockPath); } catch { /* already gone */ }
1644
+ }
1645
+ }
1646
+
1647
+ /** log.json's one writer, called from every exit path (complete + every
1648
+ * halt) — M2 scope item 9 / the M0 ruling: what the model wrote, every
1649
+ * attempt, red runs included, never just the final artifacts. */
1650
+ function writeLog(runDir, payload) {
1651
+ writeFileSync(join(runDir, 'log.json'), JSON.stringify(payload, null, 2));
1652
+ }
1653
+
1654
+ /**
1655
+ * @param {object} opts
1656
+ * @param {string} opts.flowDir
1657
+ * @param {string} opts.runDir
1658
+ * @param {string} opts.runId
1659
+ * @param {number|null} opts.capUsd
1660
+ * @param {number} opts.startedAt
1661
+ * @param {() => string} opts.now
1662
+ * @param {() => number} [opts.nowMs] - F45 finding 3; defaults to `Date.now`.
1663
+ * @param {string} opts.outcome
1664
+ * @param {string} [opts.red]
1665
+ * @param {{ value: number }} opts.spent
1666
+ * @param {any[]} [opts.attempts]
1667
+ * @param {Record<string, any>} [opts.artifacts]
1668
+ * @param {string|null} [opts.signatureHash] - the flow's `signature.json` `flow`
1669
+ * hash, when this halt happened AFTER `readFlow` succeeded (item 9: every
1670
+ * history row carries it, halts included). A halt before the signature was
1671
+ * read/verified (the pre-`readFlow`-success refused path, and any halt
1672
+ * before `signature` comes into scope) keeps the default `null`.
1673
+ * @param {boolean} [opts.priorSpendComplete] - orchestrator review fix (4):
1674
+ * a floor carried in from BEFORE this halt (e.g. a pre-park row, or an
1675
+ * earlier attempt this run, that already left `spendComplete: false`).
1676
+ * ANDed with this halt's own outcome-based verdict — once false, always
1677
+ * false. Defaults to `true` (every pre-existing call site is unaffected).
1678
+ */
1679
+ function haltRun({
1680
+ flowDir, runDir, runId, capUsd, startedAt, now, nowMs = Date.now, outcome, red, spent, attempts = [], artifacts = {}, signatureHash = null,
1681
+ priorSpendComplete = true,
1682
+ }) {
1683
+ // F45 finding 3: `startedAt` here is always the RUN's start (every caller
1684
+ // now passes `runStartedAt` under this key — see call sites), so `wallMs`
1685
+ // times the whole run, pauses included, never just the halting process.
1686
+ const wallMs = nowMs() - startedAt;
1687
+ const spendComplete = priorSpendComplete
1688
+ && outcome !== 'provider-red' && outcome !== 'pricing-red' && outcome !== 'cap-halt';
1689
+ mkdirSync(flowDir, { recursive: true });
1690
+ appendHistory(flowDir, {
1691
+ runId, at: now(), outcome, spentUsd: spent.value, spendComplete, capUsd: capUsd ?? null, wallMs, signatureHash,
1692
+ });
1693
+ if (existsSync(runDir)) {
1694
+ recordLateAnswerIfAny(runDir);
1695
+ writeLog(runDir, {
1696
+ runId, outcome, red, attempts, artifacts,
1697
+ });
1698
+ }
1699
+ return { outcome, red, spentUsd: spent.value };
1700
+ }