fwdloop 0.4.0 → 0.5.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,945 @@
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, constants as fsConstants, copyFileSync, existsSync, mkdirSync, readFileSync, realpathSync,
40
+ statSync, writeFileSync,
41
+ } from 'node:fs';
42
+ import { createHash } 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
+
64
+ // ---------------------------------------------------------------------------
65
+ // Money — piece 2 wires live provider rates; this piece takes a per-attempt
66
+ // ceiling as injected data, defaulting to a frozen table's highest entry for
67
+ // an unknown model id (never a silent $0/unbounded assumption).
68
+ // ---------------------------------------------------------------------------
69
+
70
+ const CEILING_TABLE_USD = Object.freeze({
71
+ 'deepseek-flash': 0.02,
72
+ 'synthetic-default': 0.05,
73
+ });
74
+
75
+ /** @param {string|null|undefined} modelId */
76
+ export function resolveCeilingUsd(modelId) {
77
+ if (typeof modelId === 'string' && Object.prototype.hasOwnProperty.call(CEILING_TABLE_USD, modelId)) {
78
+ return CEILING_TABLE_USD[modelId];
79
+ }
80
+ return Math.max(...Object.values(CEILING_TABLE_USD));
81
+ }
82
+
83
+ // ---------------------------------------------------------------------------
84
+ // The executor — "goal in, gap back", constructed WITHOUT its close and
85
+ // WITHOUT the cap (M2 scope item 3, the load-bearing invariant).
86
+ // ---------------------------------------------------------------------------
87
+
88
+ const EXECUTOR_FIELDS = Object.freeze(['goal', 'primitives', 'reads', 'gap']);
89
+
90
+ /** @param {{goal:string, primitives?:string[], reads?:Record<string,any>, gap?:string|null}} opts */
91
+ export function buildExecutorContext(opts) {
92
+ for (const key of Object.keys(opts ?? {})) {
93
+ if (!EXECUTOR_FIELDS.includes(key)) {
94
+ throw new Error(`executor: unknown field "${key}" — only ${EXECUTOR_FIELDS.join(', ')} may cross a step boundary`);
95
+ }
96
+ }
97
+ const {
98
+ goal, primitives = [], reads = {}, gap = null,
99
+ } = opts ?? {};
100
+ return Object.freeze({
101
+ goal,
102
+ primitives: Object.freeze([...primitives]),
103
+ reads: Object.freeze({ ...reads }),
104
+ gap: gap ?? null,
105
+ });
106
+ }
107
+
108
+ /** The identifiers a leaky executor must never carry (M2 scope item 3's own
109
+ * construction test, negative vi). Walks any depth, any key, any array
110
+ * entry; also catches a bare function value anywhere in the tree. */
111
+ const FORBIDDEN_CONTEXT_KEYS = Object.freeze([
112
+ 'close', 'shape', 'cap', 'strike', 'maxWords', 'sections', 'linesPerInvoice', 'mustCarry',
113
+ ]);
114
+
115
+ /**
116
+ * @param {unknown} value
117
+ * @param {string} [path]
118
+ * @returns {string|null} a description of the first violation found, or null when clean.
119
+ */
120
+ export function findForbiddenInContext(value, path = 'executorContext') {
121
+ if (typeof value === 'function') return `${path} is a function`;
122
+ if (Array.isArray(value)) {
123
+ for (let i = 0; i < value.length; i += 1) {
124
+ const found = findForbiddenInContext(value[i], `${path}[${i}]`);
125
+ if (found) return found;
126
+ }
127
+ return null;
128
+ }
129
+ if (value && typeof value === 'object') {
130
+ for (const key of Object.keys(value)) {
131
+ if (FORBIDDEN_CONTEXT_KEYS.includes(key)) return `${path}.${key} is a forbidden identifier`;
132
+ const found = findForbiddenInContext(value[key], `${path}.${key}`);
133
+ if (found) return found;
134
+ }
135
+ return null;
136
+ }
137
+ return null;
138
+ }
139
+
140
+ /** Also checks the executor's serialised (JSON round-tripped) form for the
141
+ * declared shape's own heading strings — a leak that survived key-name
142
+ * scanning (e.g. a heading baked into `goal` text) still needs to be
143
+ * physically absent, per M2 scope item 3. */
144
+ export function findForbiddenHeadingText(context, headingStrings) {
145
+ if (!Array.isArray(headingStrings) || headingStrings.length === 0) return null;
146
+ let serialised;
147
+ try {
148
+ serialised = JSON.stringify(context).toLowerCase();
149
+ } catch {
150
+ return null;
151
+ }
152
+ for (const heading of headingStrings) {
153
+ if (typeof heading === 'string' && heading.length > 0 && serialised.includes(heading.toLowerCase())) {
154
+ return `executorContext contains the shape heading text "${heading}"`;
155
+ }
156
+ }
157
+ return null;
158
+ }
159
+
160
+ // ---------------------------------------------------------------------------
161
+ // normaliseGap — borrowed verbatim in spirit from poc/m2/gapback.mjs: every
162
+ // digit run collapses to one '#' so "689 words, limit 600" and "661 words,
163
+ // limit 600" are the SAME gap shape for strike purposes; a different check's
164
+ // gap normalises differently.
165
+ // ---------------------------------------------------------------------------
166
+
167
+ export function normaliseGap(red) {
168
+ if (typeof red !== 'string') return '';
169
+ return red.toLowerCase().replace(/\d+/g, '#').replace(/\s+/g, ' ').trim();
170
+ }
171
+
172
+ // ---------------------------------------------------------------------------
173
+ // The mechanical "happened" check — every step's artifact, before its close,
174
+ // no exception (M2 scope item 10). This piece's artifacts are typed JS
175
+ // objects (not raw bytes), so "0-byte" reads as "the shape that class's
176
+ // artifact contract defines carries nothing" — empty text, no fields, or
177
+ // (for the generic hitl case with no declared contract) no own keys at all.
178
+ // ---------------------------------------------------------------------------
179
+
180
+ // ---------------------------------------------------------------------------
181
+ // M2 amendment 1 item 1 (docs/wiki/the-module-ladder.md, "M2 amendment 1 —
182
+ // SIGNED"): the model's own typed word, taken at face value, BEFORE the
183
+ // happened check or the close ever run. `done: false` — or a missing/non-
184
+ // boolean `done` (a schema the provider ignored is not a pass) — is a HALT,
185
+ // never a strike, never a retry. `done`/`blocker` are stripped from the
186
+ // artifact before it reaches the happened check, the closer, or disk — a
187
+ // self-report is not something a closer judges; it is kept verbatim only in
188
+ // log.json's modelOutput (the raw `result.artifact`, untouched by this).
189
+ // ---------------------------------------------------------------------------
190
+
191
+ /**
192
+ * @param {any} step
193
+ * @param {unknown} artifact
194
+ * @returns {{verdict:'not-done', red:string} | {verdict:'done'}}
195
+ */
196
+ function checkDoneBlocker(step, artifact) {
197
+ const label = step?.emits ?? 'step';
198
+ const obj = /** @type {Record<string, unknown>} */ (artifact);
199
+ if (!artifact || typeof artifact !== 'object' || typeof obj.done !== 'boolean') {
200
+ return { verdict: 'not-done', red: `step "${label}" artifact has no boolean "done"` };
201
+ }
202
+ if (obj.done === false) {
203
+ const blocker = typeof obj.blocker === 'string' && obj.blocker.length > 0 ? obj.blocker : 'no blocker given';
204
+ return { verdict: 'not-done', red: `step "${label}" reports done: false — ${blocker}` };
205
+ }
206
+ return { verdict: 'done' };
207
+ }
208
+
209
+ /** @param {unknown} artifact */
210
+ function stripDoneBlocker(artifact) {
211
+ if (!artifact || typeof artifact !== 'object') return artifact;
212
+ const obj = /** @type {Record<string, unknown>} */ (artifact);
213
+ const { done, blocker, ...rest } = obj;
214
+ return rest;
215
+ }
216
+
217
+ function checkArtifactHappened(step, artifact) {
218
+ const label = step?.goal ? `"${step.goal}"` : (step?.emits ?? 'step');
219
+ if (artifact === null || artifact === undefined) {
220
+ return { verdict: 'red', red: `happened: ${label} produced nothing` };
221
+ }
222
+ if (typeof artifact === 'string') {
223
+ return artifact.length === 0
224
+ ? { verdict: 'red', red: `happened: ${label} produced an empty string` }
225
+ : { verdict: 'green' };
226
+ }
227
+ if (typeof artifact === 'object') {
228
+ if (Object.prototype.hasOwnProperty.call(artifact, 'text')) {
229
+ return typeof artifact.text === 'string' && artifact.text.length > 0
230
+ ? { verdict: 'green' }
231
+ : { verdict: 'red', red: `happened: ${label} produced empty text` };
232
+ }
233
+ if (Object.prototype.hasOwnProperty.call(artifact, 'fields')) {
234
+ return artifact.fields && typeof artifact.fields === 'object' && Object.keys(artifact.fields).length > 0
235
+ ? { verdict: 'green' }
236
+ : { verdict: 'red', red: `happened: ${label} produced no fields` };
237
+ }
238
+ return Object.keys(artifact).length > 0
239
+ ? { verdict: 'green' }
240
+ : { verdict: 'red', red: `happened: ${label} produced an empty object` };
241
+ }
242
+ return { verdict: 'green' };
243
+ }
244
+
245
+ // ---------------------------------------------------------------------------
246
+ // Preflight — borrowed from poc/m0/runner.mjs, adapted to M1's real
247
+ // `readFlow`/`arbiter` shape.
248
+ // ---------------------------------------------------------------------------
249
+
250
+ function hashFile(path) {
251
+ return createHash('sha256').update(readFileSync(path)).digest('hex');
252
+ }
253
+
254
+ /** A run dir that already holds `ask.json`/`answer.json` from an earlier run
255
+ * is a stale-answer hazard — refuse, never silently proceed or delete. */
256
+ export function checkFreshRunDir(runDir) {
257
+ for (const file of ['ask.json', 'answer.json']) {
258
+ if (existsSync(join(runDir, file))) {
259
+ return { ok: false, red: `preflight: run dir ${runDir} already holds ${file} from an earlier run — use a new runId` };
260
+ }
261
+ }
262
+ return { ok: true };
263
+ }
264
+
265
+ /** Copy each named source into `<runDir>/inputs/`, hash the FROZEN copy
266
+ * (never the original again after this), write `inputs.json`. An
267
+ * unreadable source refuses by name. */
268
+ export function freezeInputs(runDir, sources) {
269
+ const inputsDir = join(runDir, 'inputs');
270
+ mkdirSync(inputsDir, { recursive: true });
271
+ const manifest = [];
272
+ for (const { id, path: sourcePath } of sources ?? []) {
273
+ if (!existsSync(sourcePath)) {
274
+ return { ok: false, red: `freeze: input "${id}" is unreadable at ${sourcePath}` };
275
+ }
276
+ const frozenPath = join(inputsDir, `${id}${extname(sourcePath)}`);
277
+ copyFileSync(sourcePath, frozenPath);
278
+ const sha256 = hashFile(frozenPath);
279
+ const { size: bytes } = statSync(frozenPath);
280
+ manifest.push({
281
+ id, source: sourcePath, frozen: frozenPath, sha256, bytes,
282
+ });
283
+ }
284
+ writeFileSync(join(runDir, 'inputs.json'), JSON.stringify(manifest, null, 2));
285
+ return { ok: true, manifest };
286
+ }
287
+
288
+ /** The send target's directory must resolve (lexically AND after
289
+ * realpath — a symlink inside the repo pointing outside it must not pass)
290
+ * inside the repo, and be writable. Re-checked at write time, not just at
291
+ * preflight (time-of-check vs time-of-use, M0's own fix).
292
+ * @param {string} target
293
+ * @returns {{ok:true, dir:string} | {ok:false, red:string}} */
294
+ export function checkSendDestination(target) {
295
+ const match = /^file:(.+)$/.exec(target ?? '');
296
+ if (!match) return { ok: false, red: `destination: send target "${target}" is not a "file:<path>" target` };
297
+ const dir = join(REPO_ROOT, match[1]);
298
+ const resolvedDir = resolve(dir);
299
+ const resolvedRoot = resolve(REPO_ROOT);
300
+ if (resolvedDir !== resolvedRoot && !resolvedDir.startsWith(resolvedRoot + sep)) {
301
+ return { ok: false, red: `destination: send target "${target}" resolves outside the repo (${dir})` };
302
+ }
303
+ try {
304
+ const realDir = realpathSync(dir);
305
+ const realRoot = realpathSync(REPO_ROOT);
306
+ if (realDir !== realRoot && !realDir.startsWith(realRoot + sep)) {
307
+ return {
308
+ ok: false,
309
+ red: `destination: send target "${target}" is a symlink that resolves outside the repo (${realDir})`,
310
+ };
311
+ }
312
+ } catch {
313
+ // dir doesn't exist yet — handled by the accessSync red below.
314
+ }
315
+ try {
316
+ accessSync(dir, fsConstants.W_OK);
317
+ } catch (err) {
318
+ return { ok: false, red: `destination: send target directory "${dir}" is not writable (${err.code})` };
319
+ }
320
+ return { ok: true, dir };
321
+ }
322
+
323
+ // ---------------------------------------------------------------------------
324
+ // Artifacts on disk (M2 scope item 2): every emitted artifact is written to
325
+ // `runs/<runId>/artifacts/<emits>.json` the moment its step closes
326
+ // (green/hitl pass-through/accepted) — ONE writer function, and later steps'
327
+ // `reads` are loaded back from these files, never from the in-memory
328
+ // `artifacts` object alone.
329
+ // ---------------------------------------------------------------------------
330
+
331
+ function artifactPath(runDir, id) {
332
+ return join(runDir, 'artifacts', `${id}.json`);
333
+ }
334
+
335
+ /** The one writer for a run's artifact files. Refuses (throws) to overwrite
336
+ * an existing artifact id within a run UNLESS the caller explicitly asks
337
+ * for it (`overwrite: true` — the ask-redo path's own deliberate
338
+ * replacement of a step it is re-running; every other call site accepts
339
+ * the default and gets the safety refusal). */
340
+ export function writeArtifact(runDir, id, artifact, { overwrite = false } = {}) {
341
+ const dir = join(runDir, 'artifacts');
342
+ mkdirSync(dir, { recursive: true });
343
+ const target = artifactPath(runDir, id);
344
+ if (existsSync(target) && !overwrite) {
345
+ throw new Error(`writeArtifact: artifact "${id}" already exists in this run (${target}) — refused`);
346
+ }
347
+ writeFileSync(target, JSON.stringify(artifact, null, 2));
348
+ }
349
+
350
+ /** Reads one artifact back off disk; `undefined` when it was never written
351
+ * (mirrors the in-memory map's own "absent" shape for a not-yet-produced
352
+ * read). */
353
+ export function readArtifact(runDir, id) {
354
+ const target = artifactPath(runDir, id);
355
+ if (!existsSync(target)) return undefined;
356
+ return JSON.parse(readFileSync(target, 'utf8'));
357
+ }
358
+
359
+ function readArtifactsMap(runDir, ids) {
360
+ return Object.fromEntries((ids ?? []).map((id) => [id, readArtifact(runDir, id)]));
361
+ }
362
+
363
+ // ---------------------------------------------------------------------------
364
+ // Item 4 (small): an `answer.json` still on disk, unconsumed, at run end —
365
+ // a late human answer that arrived after the run already moved on. One
366
+ // audit row, never applied, so the human can see their late answer changed
367
+ // nothing.
368
+ // ---------------------------------------------------------------------------
369
+
370
+ function recordLateAnswerIfAny(runDir) {
371
+ const file = join(runDir, 'answer.json');
372
+ if (!existsSync(file)) return;
373
+ appendAudit(runDir, {
374
+ step: null,
375
+ attempt: null,
376
+ class: null,
377
+ verdict: 'answer-after-run',
378
+ gap: null,
379
+ usd: 0,
380
+ spendComplete: true,
381
+ wallMs: 0,
382
+ model: null,
383
+ modelMatch: null,
384
+ strike: false,
385
+ kind: 'answer-after-run',
386
+ file,
387
+ });
388
+ }
389
+
390
+ // ---------------------------------------------------------------------------
391
+ // The ralph loop with strikes (M2 scope item 5) for ONE step.
392
+ // ---------------------------------------------------------------------------
393
+
394
+ /**
395
+ * Sums only the KNOWN (typeof === 'number') values, e.g. a transport fault's
396
+ * priced floor plus this attempt's own cost. Never `?? 0` — a value that is
397
+ * null/undefined is dropped from the sum rather than zeroing it out, so a
398
+ * lone known partial survives as itself and "no known cost at all" stays
399
+ * `null` (never coerced to 0).
400
+ * @param {...(number|null|undefined)} values
401
+ * @returns {number|null}
402
+ */
403
+ function sumKnownUsd(...values) {
404
+ const known = values.filter((v) => typeof v === 'number');
405
+ if (known.length === 0) return null;
406
+ return known.reduce((a, b) => a + b, 0);
407
+ }
408
+
409
+ function makeAuditRow({
410
+ step, attempt, verdict, gap, usd, spendComplete, wallMs, model = null, modelMatch = null, strike,
411
+ }) {
412
+ return {
413
+ step: step?.emits ?? step?.goal ?? null,
414
+ attempt,
415
+ class: step?.close?.class ?? null,
416
+ verdict,
417
+ gap: gap ?? null,
418
+ usd,
419
+ spendComplete,
420
+ wallMs,
421
+ model: model ?? null,
422
+ modelMatch: modelMatch ?? null,
423
+ strike: !!strike,
424
+ };
425
+ }
426
+
427
+ /**
428
+ * Run one step to green (or hitl pass-through), looping under strikes and
429
+ * the attempt fallback. Returns `{ ok:true, artifact, attempts }` on success
430
+ * or `{ ok:false, outcome, red }` on any halt. Appends one audit row per
431
+ * attempt via `deps.recordAudit`. Never throws for a model/close failure —
432
+ * only a programmer error (a malformed step, an unreachable branch) escapes.
433
+ *
434
+ * @param {object} opts
435
+ * @param {any} opts.step
436
+ * @param {Record<string, any>} [opts.primitivesMap]
437
+ * @param {Record<string, any>} opts.readsMap
438
+ * @param {string} opts.businessDate
439
+ * @param {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class:string|null}) => Promise<any>} opts.modelStep
440
+ * @param {{ value: number }} opts.spent
441
+ * @param {number} opts.capUsd
442
+ * @param {number} opts.ceilingUsd
443
+ * @param {(row: any, modelOutput?: any) => void} opts.recordAudit
444
+ * @param {string|null} [opts.initialGap]
445
+ * @param {number} [opts.attemptOffset]
446
+ * @returns {Promise<{ok:true, artifact:any, attempts:number, hitl?:boolean} | {ok:false, outcome:string, red:string}>}
447
+ */
448
+ async function runStepRalph({
449
+ step, primitivesMap, readsMap, businessDate, modelStep, spent, capUsd, ceilingUsd, recordAudit, initialGap = null, attemptOffset = 0,
450
+ }) {
451
+ /** @type {string|null} */
452
+ let gap = initialGap ?? null;
453
+ let strikes = 0;
454
+ const seenGaps = new Set();
455
+
456
+ for (let n = 1; n <= MAX_ATTEMPTS; n += 1) {
457
+ const attempt = attemptOffset + n;
458
+ // This attempt's known floor from a FIRST transport fault that then
459
+ // retried — every audit row this attempt still writes must carry this
460
+ // floor summed with its own cost (F41 books gap: the fault's cost was
461
+ // only ever in `spent.value`'s total, never on the attempt's own row).
462
+ let attemptFloorUsd = null;
463
+ if (spent.value + ceilingUsd > capUsd) {
464
+ recordAudit(makeAuditRow({
465
+ step, attempt, verdict: 'cap-halt', gap, usd: null, spendComplete: false, wallMs: 0, strike: false,
466
+ }));
467
+ return {
468
+ ok: false,
469
+ outcome: 'cap-halt',
470
+ red: `cap-halt: step "${step.goal}" attempt ${attempt} cannot be funded under cap $${capUsd} (spent so far $${spent.value})`,
471
+ };
472
+ }
473
+
474
+ const grantedTools = Object.fromEntries((step.primitives ?? []).map((verb) => [verb, primitivesMap?.[verb]]));
475
+ const executorContext = buildExecutorContext({
476
+ goal: step.goal, primitives: step.primitives ?? [], reads: readsMap, gap,
477
+ });
478
+
479
+ // `stepMeta` is a SEPARATE argument from `executorContext` — never a
480
+ // field on it. It carries the step's declared close CLASS only (never
481
+ // its shape), so a live `modelStep` can build its `emit_artifact` tool
482
+ // schema without the executor context ever needing to carry one (M2
483
+ // scope item 3's own invariant: the schema is class-only, and the
484
+ // construction test below proves the context itself stays clean).
485
+ const stepMeta = Object.freeze({ class: step.close?.class ?? null });
486
+
487
+ const startedAt = Date.now();
488
+ // eslint-disable-next-line no-await-in-loop
489
+ let result = await modelStep(executorContext, grantedTools, stepMeta);
490
+ if (result && result.ok === false && result.transport === true) {
491
+ // A known partial cost from the FIRST transport fault must survive as
492
+ // the floor even though this attempt goes on to retry — never
493
+ // dropped on the retry path (the brief's own gap, closed here).
494
+ if (typeof result.costUsd === 'number') {
495
+ spent.value += result.costUsd;
496
+ attemptFloorUsd = result.costUsd;
497
+ }
498
+ // Exactly one immediate retry on the SAME attempt for a transport
499
+ // fault; an HTTP status is not transport, a wall-clock timeout is
500
+ // never retried (M2 scope item 8) — both are the caller's own
501
+ // `modelStep`'s job to distinguish; this loop only ever retries the
502
+ // `transport: true` shape, exactly once.
503
+ // eslint-disable-next-line no-await-in-loop
504
+ result = await modelStep(executorContext, grantedTools, stepMeta);
505
+ }
506
+ const wallMs = Date.now() - startedAt;
507
+
508
+ if (result && result.ok === false && result.transport === true) {
509
+ if (typeof result.costUsd === 'number') spent.value += result.costUsd;
510
+ // Both faults' known costs, summed — the first fault's floor was
511
+ // already added to `spent.value` above (never double-added here); a
512
+ // null second cost never zeroes out a known first floor.
513
+ const usd = sumKnownUsd(attemptFloorUsd, result.costUsd);
514
+ recordAudit(makeAuditRow({
515
+ step, attempt, verdict: 'provider-red', gap, usd, spendComplete: false, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false,
516
+ }), result.red ?? 'transport fault twice');
517
+ return { ok: false, outcome: 'provider-red', red: `provider-red: step "${step.goal}" attempt ${attempt}: ${result.red ?? 'transport fault twice'}` };
518
+ }
519
+
520
+ if (!result || result.ok !== true) {
521
+ // A non-transport model failure — never thrown, never coerced into a
522
+ // fabricated artifact. Treated as this attempt's red (it is the
523
+ // step's own failure to produce, not a system halt), strike-eligible
524
+ // like any other close red.
525
+ const red = result?.red ?? 'model step failed with no artifact';
526
+ const normalised = normaliseGap(red);
527
+ const strike = seenGaps.has(normalised);
528
+ seenGaps.add(normalised);
529
+ if (strike) strikes += 1;
530
+ const usd = sumKnownUsd(attemptFloorUsd, result?.costUsd);
531
+ recordAudit(makeAuditRow({
532
+ step, attempt, verdict: 'red', gap: red, usd, spendComplete: usd !== null, wallMs, model: result?.model, modelMatch: result?.modelMatch, strike,
533
+ }), red);
534
+ if (n === MAX_ATTEMPTS) return { ok: false, outcome: 'attempt-fallback', red: `attempt-fallback: step "${step.goal}" — ${red}` };
535
+ if (strikes >= STRIKE_LIMIT) return { ok: false, outcome: 'struck-out', red: `struck-out: step "${step.goal}" — ${red}` };
536
+ gap = red;
537
+ // eslint-disable-next-line no-continue
538
+ continue;
539
+ }
540
+
541
+ if (result.costUsd === null || result.costUsd === undefined) {
542
+ recordAudit(makeAuditRow({
543
+ step, attempt, verdict: 'pricing-red', gap, usd: attemptFloorUsd, spendComplete: false, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false,
544
+ }), result.artifact ?? null);
545
+ return { ok: false, outcome: 'pricing-red', red: `pricing-red: step "${step.goal}" attempt ${attempt} returned no cost (never "?? 0")` };
546
+ }
547
+ spent.value += result.costUsd;
548
+ const attemptUsd = sumKnownUsd(attemptFloorUsd, result.costUsd);
549
+
550
+ // The model's own word, taken at face value — before the happened check,
551
+ // before any close, no exception (M2 amendment 1 item 1). A halt, not a
552
+ // strike, not a retry: `recordAudit`'s modelOutput arg keeps the RAW
553
+ // `result.artifact` (done/blocker included) for log.json; everything
554
+ // downstream of a `done: true` gets the STRIPPED artifact.
555
+ const doneCheck = checkDoneBlocker(step, result.artifact);
556
+ if (doneCheck.verdict === 'not-done') {
557
+ recordAudit(makeAuditRow({
558
+ step, attempt, verdict: 'not-done', gap: doneCheck.red, usd: attemptUsd, spendComplete: true, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false,
559
+ }), result.artifact ?? null);
560
+ return { ok: false, outcome: 'not-done', red: doneCheck.red };
561
+ }
562
+ const artifact = stripDoneBlocker(result.artifact);
563
+
564
+ const happened = checkArtifactHappened(step, artifact);
565
+ if (happened.verdict === 'red') {
566
+ // Item 5: "or wrote no artifact" strikes unconditionally, every time
567
+ // (never gated by novelty — an empty artifact is always the same
568
+ // failure) — matches poc/m2/gapback.mjs's own rule exactly.
569
+ strikes += 1;
570
+ recordAudit(makeAuditRow({
571
+ step, attempt, verdict: 'red', gap: happened.red, usd: attemptUsd, spendComplete: true, wallMs, model: result.model, modelMatch: result.modelMatch, strike: true,
572
+ }), result.artifact ?? null);
573
+ if (n === MAX_ATTEMPTS) return { ok: false, outcome: 'attempt-fallback', red: `attempt-fallback: ${happened.red}` };
574
+ if (strikes >= STRIKE_LIMIT) return { ok: false, outcome: 'struck-out', red: `struck-out: ${happened.red}` };
575
+ gap = happened.red ?? null;
576
+ // eslint-disable-next-line no-continue
577
+ continue;
578
+ }
579
+
580
+ const closed = closeByClass(step, artifact, { reads: readsMap, businessDate });
581
+
582
+ if (closed.verdict === 'green' || closed.verdict === 'hitl') {
583
+ recordAudit(makeAuditRow({
584
+ step, attempt, verdict: closed.verdict, gap: null, usd: attemptUsd, spendComplete: true, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false,
585
+ }), result.artifact);
586
+ return {
587
+ ok: true, artifact, attempts: attempt, hitl: closed.verdict === 'hitl',
588
+ };
589
+ }
590
+
591
+ if (closed.verdict !== 'red') {
592
+ // A closer that renders no judgment ('unparseable'/'crash') is a
593
+ // CASUALTY, never a red and never a strike (bareloop F17).
594
+ recordAudit(makeAuditRow({
595
+ step, attempt, verdict: 'close-casualty', gap: closed.red, usd: attemptUsd, spendComplete: true, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false,
596
+ }), result.artifact);
597
+ return { ok: false, outcome: 'close-casualty', red: `close-casualty: step "${step.goal}" — ${closed.red} (${closed.verdict})` };
598
+ }
599
+
600
+ const normalised = normaliseGap(closed.red);
601
+ const strike = seenGaps.has(normalised);
602
+ seenGaps.add(normalised);
603
+ if (strike) strikes += 1;
604
+ recordAudit(makeAuditRow({
605
+ step, attempt, verdict: 'red', gap: closed.red, usd: attemptUsd, spendComplete: true, wallMs, model: result.model, modelMatch: result.modelMatch, strike,
606
+ }), result.artifact);
607
+
608
+ if (n === MAX_ATTEMPTS) return { ok: false, outcome: 'attempt-fallback', red: `attempt-fallback: step "${step.goal}" — ${closed.red}` };
609
+ if (strikes >= STRIKE_LIMIT) return { ok: false, outcome: 'struck-out', red: `struck-out: step "${step.goal}" — ${closed.red}` };
610
+ gap = closed.red ?? null;
611
+ }
612
+ // Unreachable — the loop above always returns by n === MAX_ATTEMPTS.
613
+ return { ok: false, outcome: 'attempt-fallback', red: `attempt-fallback: step "${step.goal}" — exhausted attempts` };
614
+ }
615
+
616
+ // ---------------------------------------------------------------------------
617
+ // runFlow — the entry point.
618
+ // ---------------------------------------------------------------------------
619
+
620
+ /**
621
+ * @param {object} opts
622
+ * @param {string} opts.root - the flows root directory (M1's `readFlow` root).
623
+ * @param {string} opts.name - the flow name.
624
+ * @param {string} opts.runId
625
+ * @param {Array<{id:string, path:string}>} opts.sources - the real files to freeze for this run.
626
+ * @param {unknown} opts.catalogue - passed straight through to `readFlow`.
627
+ * @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
628
+ * @param {(opts:{question:string, evidence:unknown, runDir:string}) => Promise<{decision:'accept'|'reject'|'rerun'|'timeout', reason?:string}>} opts.askStep
629
+ * @param {(target:string, filename:string, content:unknown) => Promise<{ok:boolean, red?:string, bytes?:number}>} opts.sendStep
630
+ * @param {Record<string, any>} [opts.primitives] - injected primitive implementations, keyed by catalogue verb.
631
+ * @param {() => string} [opts.clock] - returns the current ISO timestamp; defaults to the wall clock.
632
+ * @param {string} opts.businessDate - the run's explicit "as of today", never the wall clock.
633
+ * @param {number} [opts.ceilingUsd] - per-attempt ceiling override; defaults to `resolveCeilingUsd(null)`.
634
+ */
635
+ export async function runFlow({
636
+ root, name, runId, sources, catalogue, modelStep, askStep, sendStep, primitives, clock, businessDate, ceilingUsd,
637
+ }) {
638
+ const now = typeof clock === 'function' ? clock : () => new Date().toISOString();
639
+ const flowDir = join(root, name);
640
+ const startedAt = Date.now();
641
+
642
+ const read = readFlow({ root, name, catalogue });
643
+ if (!read.ok) {
644
+ // Negative iv: a flow whose files don't hash to the signature (or is
645
+ // otherwise unreadable) is refused by name, at $0. No run dir exists to
646
+ // hold an audit.jsonl, so the ONLY book row is one history row: a
647
+ // refusal spent nothing, and `usd: 0`/`spendComplete: true` is honestly
648
+ // true here (never the "unknown coerced to 0" case money honesty
649
+ // otherwise forbids) — stated explicitly per the brief's own note.
650
+ mkdirSync(flowDir, { recursive: true });
651
+ appendHistory(flowDir, {
652
+ runId, at: now(), outcome: 'refused', spentUsd: 0, spendComplete: true, capUsd: null, wallMs: Date.now() - startedAt, signatureHash: null,
653
+ });
654
+ return { outcome: 'refused', red: read.reds[0], reds: read.reds };
655
+ }
656
+
657
+ const { arbiter, declaration, signature } = read;
658
+ const capUsd = arbiter.capUsd;
659
+ const redoCap = arbiter.redoCap ?? 3;
660
+ const effectiveCeilingUsd = ceilingUsd ?? resolveCeilingUsd(null);
661
+ const askLines = new Map((arbiter.asks ?? []).map((a) => [a.line, a]));
662
+ const sendLines = new Map((arbiter.sends ?? []).map((s) => [s.line, s]));
663
+
664
+ const runDir = join(flowDir, 'runs', runId);
665
+
666
+ const fresh = checkFreshRunDir(runDir);
667
+ if (!fresh.ok) {
668
+ return haltRun({
669
+ flowDir, runDir, runId, capUsd, startedAt, now, signatureHash: signature.flow, outcome: 'preflight-red', red: fresh.red, spent: { value: 0 },
670
+ });
671
+ }
672
+ mkdirSync(runDir, { recursive: true });
673
+
674
+ const frozen = freezeInputs(runDir, sources ?? []);
675
+ if (!frozen.ok) {
676
+ return haltRun({
677
+ flowDir, runDir, runId, capUsd, startedAt, now, signatureHash: signature.flow, outcome: 'preflight-red', red: frozen.red, spent: { value: 0 },
678
+ });
679
+ }
680
+
681
+ const artifacts = {};
682
+ const auditRows = [];
683
+ // Item 3: what the model actually wrote, every attempt, red runs included
684
+ // — kept SEPARATELY from auditRows (which stay the signed book's own
685
+ // shape) and folded into log.json only, on every exit path.
686
+ /** @type {any[]} */
687
+ const attemptsLog = [];
688
+ const recordAudit = (row, modelOutput, unjudgedCount) => {
689
+ // M2 amendment 1 item 2: "audit row for the ask gains unjudgedCount" —
690
+ // only the ask's own rows pass a third argument; every other row is
691
+ // unaffected (the key is simply absent, never a stray 0/null).
692
+ const fullRow = unjudgedCount === undefined ? row : { ...row, unjudgedCount };
693
+ auditRows.push(fullRow);
694
+ appendAudit(runDir, fullRow);
695
+ if (modelOutput !== undefined) {
696
+ attemptsLog.push({
697
+ step: row.step, attempt: row.attempt, class: row.class, verdict: row.verdict, gap: row.gap, modelOutput,
698
+ });
699
+ }
700
+ };
701
+ const spent = { value: 0 };
702
+ let acceptedThisRun = false;
703
+ // M2 amendment 1 item 2: every hitl-class step NOT bound to a signed ask
704
+ // line is carried as evidence into the NEXT signed ask, in order, then
705
+ // reset — never silently passed through unseen.
706
+ /** @type {Array<{step:string|null, emits:string, artifact:unknown}>} */
707
+ let unjudgedSinceLastAsk = [];
708
+
709
+ const steps = declaration.steps;
710
+ // M2 fix: the send's content is identified by IDENTITY (the artifact
711
+ // emitted by a signed ask step), never by position in `reads` — every id
712
+ // in a send step's `reads` names an earlier step, so picking `reads[0]`
713
+ // silently ships whatever was read first instead of what was accepted.
714
+ // Derived the same way the loop below knows a step is an ask — bound to
715
+ // an `arbiter.asks[]` line.
716
+ const askStepEmits = new Set(steps.filter((s) => askLines.has(s.fromLine)).map((s) => s.emits));
717
+ // Tracks which specific ask emits were accepted THIS run (acceptedThisRun
718
+ // above stays run-wide, for the "reached with no accept this run" gate).
719
+ const acceptedAskEmitsThisRun = new Set();
720
+ for (let i = 0; i < steps.length; i += 1) {
721
+ const step = steps[i];
722
+
723
+ // --- the signed send slot: never through modelStep, only after an
724
+ // accept THIS run, re-checked at write time. ---
725
+ if (sendLines.has(step.fromLine)) {
726
+ if (!acceptedThisRun) {
727
+ return haltRun({
728
+ flowDir, runDir, runId, capUsd, startedAt, now, signatureHash: signature.flow, spent, attempts: attemptsLog, artifacts,
729
+ outcome: 'red', red: `send: step "${step.goal}" reached with no accept this run`,
730
+ });
731
+ }
732
+ const sendSlot = sendLines.get(step.fromLine);
733
+ if (!sendSlot) {
734
+ return haltRun({
735
+ flowDir, runDir, runId, capUsd, startedAt, now, signatureHash: signature.flow, spent, attempts: attemptsLog, artifacts, outcome: 'red', red: `send: no arbiter slot bound to line ${step.fromLine}`,
736
+ });
737
+ }
738
+ const target = `${sendSlot.target.kind}:${sendSlot.target.path}`;
739
+ const askIdsInReads = (step.reads ?? []).filter((id) => askStepEmits.has(id));
740
+ if (askIdsInReads.length !== 1) {
741
+ return haltRun({
742
+ flowDir, runDir, runId, capUsd, startedAt, now, signatureHash: signature.flow, spent, attempts: attemptsLog, artifacts,
743
+ outcome: 'red', red: `send: step "${step.goal}" must read exactly one signed ask's artifact, found [${askIdsInReads.join(', ')}]`,
744
+ });
745
+ }
746
+ const [askArtifactId] = askIdsInReads;
747
+ if (!acceptedAskEmitsThisRun.has(askArtifactId)) {
748
+ return haltRun({
749
+ flowDir, runDir, runId, capUsd, startedAt, now, signatureHash: signature.flow, spent, attempts: attemptsLog, artifacts,
750
+ outcome: 'red', red: `send: step "${step.goal}" reads ask artifact "${askArtifactId}" that was not accepted this run`,
751
+ });
752
+ }
753
+ const content = readArtifact(runDir, askArtifactId);
754
+ const filename = `${runId}-${step.emits}.json`;
755
+ // eslint-disable-next-line no-await-in-loop
756
+ const sendResult = await sendStep(target, filename, content);
757
+ const sendRow = makeAuditRow({
758
+ step, attempt: 1, verdict: sendResult.ok ? 'green' : 'red', gap: sendResult.ok ? null : sendResult.red, usd: 0, spendComplete: true, wallMs: 0, strike: false,
759
+ });
760
+ recordAudit(sendRow);
761
+ if (!sendResult.ok) {
762
+ return haltRun({
763
+ flowDir, runDir, runId, capUsd, startedAt, now, signatureHash: signature.flow, spent, attempts: attemptsLog, artifacts, outcome: 'red', red: `send: ${sendResult.red}`,
764
+ });
765
+ }
766
+ writeArtifact(runDir, step.emits, content);
767
+ artifacts[step.emits] = content;
768
+ // eslint-disable-next-line no-continue
769
+ continue;
770
+ }
771
+
772
+ // --- the signed ask slot: interactive, consume-once, reason-gated redo. ---
773
+ if (askLines.has(step.fromLine)) {
774
+ const askSlot = askLines.get(step.fromLine);
775
+ const priorId = (step.reads ?? [])[0];
776
+ const priorStepIndex = steps.findIndex((s) => s.emits === priorId);
777
+ let priorArtifact = readArtifact(runDir, priorId);
778
+ let redone = 0;
779
+
780
+ // M2 amendment 1 item 2: every hitl artifact carried since the
781
+ // previous ask goes to THIS ask as evidence, alongside the ask step's
782
+ // own artifact — then the list resets (a fresh accumulator for the
783
+ // NEXT ask), so a later ask never re-shows what an earlier one covered.
784
+ const evidenceUnjudged = unjudgedSinceLastAsk;
785
+ const unjudgedCount = evidenceUnjudged.length;
786
+ unjudgedSinceLastAsk = [];
787
+
788
+ for (;;) {
789
+ const evidence = { artifact: priorArtifact, unjudged: evidenceUnjudged };
790
+ // eslint-disable-next-line no-await-in-loop
791
+ const answer = await askStep({ question: askSlot?.question ?? step.goal, evidence, runDir });
792
+
793
+ if (answer.decision === 'timeout') {
794
+ // A pause spends nothing (M2 scope item 6) — a halt, never a red
795
+ // with a fabricated cost, and never re-asked (the run is over).
796
+ recordAudit(makeAuditRow({
797
+ step, attempt: redone + 1, verdict: 'ask-timeout', gap: null, usd: 0, spendComplete: true, wallMs: 0, strike: false,
798
+ }), undefined, unjudgedCount);
799
+ return haltRun({
800
+ flowDir, runDir, runId, capUsd, startedAt, now, signatureHash: signature.flow, spent, attempts: attemptsLog, artifacts,
801
+ outcome: 'ask-timeout', red: `ask-timeout: step "${step.goal}" expired waiting for a human answer`,
802
+ });
803
+ }
804
+
805
+ const isRedo = answer.decision === 'reject' || answer.decision === 'rerun';
806
+ const reason = typeof answer.reason === 'string' ? answer.reason.trim() : '';
807
+
808
+ if (isRedo && reason.length === 0) {
809
+ recordAudit(makeAuditRow({
810
+ step, attempt: redone + 1, verdict: 'refused', gap: 'a rejection/rerun needs a reason', usd: 0, spendComplete: true, wallMs: 0, strike: false,
811
+ }), undefined, unjudgedCount);
812
+ // Refused, re-asked for the SAME attempt — never re-runs the step.
813
+ // eslint-disable-next-line no-continue
814
+ continue;
815
+ }
816
+
817
+ if (answer.decision === 'accept') {
818
+ recordAudit(makeAuditRow({
819
+ step, attempt: redone + 1, verdict: 'green', gap: null, usd: 0, spendComplete: true, wallMs: 0, strike: false,
820
+ }), undefined, unjudgedCount);
821
+ writeArtifact(runDir, step.emits, priorArtifact);
822
+ artifacts[step.emits] = priorArtifact;
823
+ acceptedThisRun = true;
824
+ acceptedAskEmitsThisRun.add(step.emits);
825
+ break;
826
+ }
827
+
828
+ if (isRedo) {
829
+ redone += 1;
830
+ recordAudit(makeAuditRow({
831
+ step, attempt: redone, verdict: 'red', gap: reason, usd: 0, spendComplete: true, wallMs: 0, strike: false,
832
+ }), undefined, unjudgedCount);
833
+ if (redone > redoCap) {
834
+ return haltRun({
835
+ flowDir, runDir, runId, capUsd, startedAt, now, signatureHash: signature.flow, spent, attempts: attemptsLog, artifacts,
836
+ outcome: 'redo-halt', red: `redo cap ${redoCap} reached at step "${step.goal}" after ${redone} rejections`,
837
+ });
838
+ }
839
+ const priorStep = steps[priorStepIndex];
840
+ const priorReads = readArtifactsMap(runDir, priorStep.reads);
841
+ // eslint-disable-next-line no-await-in-loop
842
+ const redoResult = await runStepRalph({
843
+ step: priorStep, primitivesMap: primitives, readsMap: priorReads, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, initialGap: reason, attemptOffset: redone,
844
+ });
845
+ if (!redoResult.ok) {
846
+ return haltRun({
847
+ flowDir, runDir, runId, capUsd, startedAt, now, signatureHash: signature.flow, spent, attempts: attemptsLog, artifacts, outcome: redoResult.outcome, red: redoResult.red,
848
+ });
849
+ }
850
+ priorArtifact = redoResult.artifact;
851
+ // A redo deliberately REPLACES the prior step's own artifact —
852
+ // the one case `writeArtifact` allows to overwrite on purpose.
853
+ writeArtifact(runDir, priorId, priorArtifact, { overwrite: true });
854
+ artifacts[priorId] = priorArtifact;
855
+ // eslint-disable-next-line no-continue
856
+ continue;
857
+ }
858
+
859
+ return haltRun({
860
+ flowDir, runDir, runId, capUsd, startedAt, now, signatureHash: signature.flow, spent, attempts: attemptsLog, artifacts,
861
+ outcome: 'red', red: `ask: step "${step.goal}" got an unrecognised decision "${answer.decision}"`,
862
+ });
863
+ }
864
+ // eslint-disable-next-line no-continue
865
+ continue;
866
+ }
867
+
868
+ // --- an ordinary step: green / softgreen / a non-ask hitl pass-through. ---
869
+ const readsMap = readArtifactsMap(runDir, step.reads);
870
+ // eslint-disable-next-line no-await-in-loop
871
+ const stepResult = await runStepRalph({
872
+ step, primitivesMap: primitives, readsMap, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit,
873
+ });
874
+ if (!stepResult.ok) {
875
+ return haltRun({
876
+ flowDir, runDir, runId, capUsd, startedAt, now, signatureHash: signature.flow, spent, attempts: attemptsLog, artifacts, outcome: stepResult.outcome, red: stepResult.red,
877
+ });
878
+ }
879
+ writeArtifact(runDir, step.emits, stepResult.artifact);
880
+ artifacts[step.emits] = stepResult.artifact;
881
+ // M2 amendment 1 item 2: a hitl-class step not bound to a signed ask
882
+ // line (the routing above already guarantees that — this branch is only
883
+ // reached when neither askLines nor sendLines claimed the step) passes
884
+ // through silently here; carry it as evidence for the NEXT signed ask.
885
+ if (stepResult.hitl) {
886
+ unjudgedSinceLastAsk.push({ step: step.goal ?? null, emits: step.emits, artifact: stepResult.artifact });
887
+ }
888
+ }
889
+
890
+ const wallMs = Date.now() - startedAt;
891
+ appendHistory(flowDir, {
892
+ runId, at: now(), outcome: 'complete', spentUsd: spent.value, spendComplete: true, capUsd, wallMs, signatureHash: signature.flow,
893
+ });
894
+ recordLateAnswerIfAny(runDir);
895
+ writeLog(runDir, {
896
+ runId, outcome: 'complete', attempts: attemptsLog, artifacts,
897
+ });
898
+ return {
899
+ outcome: 'complete', runDir, artifacts, spentUsd: spent.value, auditRows,
900
+ };
901
+ }
902
+
903
+ /** log.json's one writer, called from every exit path (complete + every
904
+ * halt) — M2 scope item 9 / the M0 ruling: what the model wrote, every
905
+ * attempt, red runs included, never just the final artifacts. */
906
+ function writeLog(runDir, payload) {
907
+ writeFileSync(join(runDir, 'log.json'), JSON.stringify(payload, null, 2));
908
+ }
909
+
910
+ /**
911
+ * @param {object} opts
912
+ * @param {string} opts.flowDir
913
+ * @param {string} opts.runDir
914
+ * @param {string} opts.runId
915
+ * @param {number|null} opts.capUsd
916
+ * @param {number} opts.startedAt
917
+ * @param {() => string} opts.now
918
+ * @param {string} opts.outcome
919
+ * @param {string} [opts.red]
920
+ * @param {{ value: number }} opts.spent
921
+ * @param {any[]} [opts.attempts]
922
+ * @param {Record<string, any>} [opts.artifacts]
923
+ * @param {string|null} [opts.signatureHash] - the flow's `signature.json` `flow`
924
+ * hash, when this halt happened AFTER `readFlow` succeeded (item 9: every
925
+ * history row carries it, halts included). A halt before the signature was
926
+ * read/verified (the pre-`readFlow`-success refused path, and any halt
927
+ * before `signature` comes into scope) keeps the default `null`.
928
+ */
929
+ function haltRun({
930
+ flowDir, runDir, runId, capUsd, startedAt, now, outcome, red, spent, attempts = [], artifacts = {}, signatureHash = null,
931
+ }) {
932
+ const wallMs = Date.now() - startedAt;
933
+ const spendComplete = outcome !== 'provider-red' && outcome !== 'pricing-red' && outcome !== 'cap-halt';
934
+ mkdirSync(flowDir, { recursive: true });
935
+ appendHistory(flowDir, {
936
+ runId, at: now(), outcome, spentUsd: spent.value, spendComplete, capUsd: capUsd ?? null, wallMs, signatureHash,
937
+ });
938
+ if (existsSync(runDir)) {
939
+ recordLateAnswerIfAny(runDir);
940
+ writeLog(runDir, {
941
+ runId, outcome, red, attempts, artifacts,
942
+ });
943
+ }
944
+ return { outcome, red, spentUsd: spent.value };
945
+ }