fwdloop 0.5.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/fwdloop +559 -0
- package/package.json +7 -3
- package/src/ask.js +360 -7
- package/src/books.js +209 -2
- package/src/declaration.js +12 -1
- package/src/flow.js +247 -2
- package/src/index.js +9 -2
- package/src/model-step.js +153 -14
- package/src/panel/data.js +1589 -0
- package/src/panel/index.html +2377 -0
- package/src/panel/server.js +268 -0
- package/src/primitives.js +136 -41
- package/src/provider.js +57 -41
- package/src/runner.js +1231 -137
- package/src/send.js +20 -1
- package/src/types.js +18 -0
- package/types/ask.d.ts +95 -1
- package/types/books.d.ts +70 -2
- package/types/flow.d.ts +135 -0
- package/types/index.d.ts +5 -2
- package/types/panel/data.d.ts +433 -0
- package/types/panel/server.d.ts +45 -0
- package/types/primitives.d.ts +29 -0
- package/types/provider.d.ts +11 -0
- package/types/runner.d.ts +135 -26
- package/types/types.d.ts +41 -0
package/src/runner.js
CHANGED
|
@@ -36,16 +36,20 @@
|
|
|
36
36
|
// ---------------------------------------------------------------------------
|
|
37
37
|
|
|
38
38
|
import {
|
|
39
|
-
accessSync, constants as fsConstants, copyFileSync, existsSync, mkdirSync,
|
|
40
|
-
statSync, writeFileSync,
|
|
39
|
+
accessSync, closeSync, constants as fsConstants, copyFileSync, existsSync, mkdirSync, openSync, readFileSync,
|
|
40
|
+
realpathSync, renameSync, statSync, unlinkSync, writeFileSync,
|
|
41
41
|
} from 'node:fs';
|
|
42
|
-
import { createHash } from 'node:crypto';
|
|
42
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
43
43
|
import {
|
|
44
44
|
dirname, extname, join, resolve, sep,
|
|
45
45
|
} from 'node:path';
|
|
46
46
|
import { fileURLToPath } from 'node:url';
|
|
47
47
|
|
|
48
|
-
import {
|
|
48
|
+
import {
|
|
49
|
+
readFlow, resolveRunDir, readFileInside, resolveInside,
|
|
50
|
+
} from './flow.js';
|
|
51
|
+
import { writeAskArchive } from './ask.js';
|
|
52
|
+
import { WIRED_VERBS } from './primitives.js';
|
|
49
53
|
import { closeByClass } from './closers.js';
|
|
50
54
|
import { appendAudit, appendHistory } from './books.js';
|
|
51
55
|
|
|
@@ -60,6 +64,16 @@ export const STRIKE_LIMIT = 2;
|
|
|
60
64
|
* fallback, never the governor" — it never raises the strike bound, it only
|
|
61
65
|
* bounds the case the strike governor doesn't catch). */
|
|
62
66
|
export const MAX_ATTEMPTS = 4;
|
|
67
|
+
/** Debrief round 2: `state.spent` (accumulated by repeated `spent.value +=`
|
|
68
|
+
* during the run) and `sumAuditUsd`'s re-summed total are two independent
|
|
69
|
+
* float summations of the same rows in a different order — IEEE 754
|
|
70
|
+
* addition is not associative, so they can differ by a single ULP (e.g.
|
|
71
|
+
* 0.006874 vs 0.006874000000000001) with no real discrepancy. The books
|
|
72
|
+
* (audit.jsonl) stay the source of truth; this tolerance only absorbs
|
|
73
|
+
* summation-order noise, not a real gap. A billionth of a dollar is ~6
|
|
74
|
+
* orders of magnitude below the cheapest real round (audit rows here run
|
|
75
|
+
* $0.0006+), so nothing a real tamper produces can hide inside it. */
|
|
76
|
+
export const SPEND_TOLERANCE_USD = 1e-9;
|
|
63
77
|
|
|
64
78
|
// ---------------------------------------------------------------------------
|
|
65
79
|
// Money — piece 2 wires live provider rates; this piece takes a per-attempt
|
|
@@ -251,6 +265,34 @@ function hashFile(path) {
|
|
|
251
265
|
return createHash('sha256').update(readFileSync(path)).digest('hex');
|
|
252
266
|
}
|
|
253
267
|
|
|
268
|
+
/**
|
|
269
|
+
* F46 (docs/logs/FINDINGS.md): a step whose declaration grants a verb the
|
|
270
|
+
* catalogue lists but `resolvePrimitives` has no case for (e.g. litectx's
|
|
271
|
+
* `compress`) must refuse the whole run at preflight, naming the step and
|
|
272
|
+
* the verb — never a warning the run continues (and spends) past. Lives
|
|
273
|
+
* here, not in `bin/fwdloop`, so any caller of `runFlow`/`resumeRun`
|
|
274
|
+
* (the CLI, M4's web panel) gets the same refusal for free — one writer,
|
|
275
|
+
* `src/primitives.js`'s own `WIRED_VERBS`, never a second copy of the list.
|
|
276
|
+
* A verb absent from the catalogue entirely is caught earlier, at
|
|
277
|
+
* declaration-validation time (`readFlow`) — by the time a declaration
|
|
278
|
+
* reaches here every granted verb is already catalogue-present, so
|
|
279
|
+
* `WIRED_VERBS` alone is enough to tell "wired" from "not yet".
|
|
280
|
+
*
|
|
281
|
+
* @param {Record<string, any>} declaration - `readFlow`'s own loosely-typed
|
|
282
|
+
* `ReadFlowOk.declaration` shape (src/types.js) — same idiom as every
|
|
283
|
+
* other reader of it in this file (e.g. `declaration.steps` below); only
|
|
284
|
+
* `steps[].{emits,fromLine,primitives}` are actually read here.
|
|
285
|
+
* @returns {{step: {emits: string, fromLine: number}, verb: string}|null}
|
|
286
|
+
*/
|
|
287
|
+
function findUnwiredVerbStep(declaration) {
|
|
288
|
+
for (const step of declaration.steps) {
|
|
289
|
+
for (const verb of step.primitives ?? []) {
|
|
290
|
+
if (!WIRED_VERBS.has(verb)) return { step, verb };
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
return null;
|
|
294
|
+
}
|
|
295
|
+
|
|
254
296
|
/** A run dir that already holds `ask.json`/`answer.json` from an earlier run
|
|
255
297
|
* is a stale-answer hazard — refuse, never silently proceed or delete. */
|
|
256
298
|
export function checkFreshRunDir(runDir) {
|
|
@@ -347,17 +389,64 @@ export function writeArtifact(runDir, id, artifact, { overwrite = false } = {})
|
|
|
347
389
|
writeFileSync(target, JSON.stringify(artifact, null, 2));
|
|
348
390
|
}
|
|
349
391
|
|
|
350
|
-
/**
|
|
351
|
-
*
|
|
352
|
-
*
|
|
392
|
+
/**
|
|
393
|
+
* F48 round 4 (redesign, docs/logs/FINDINGS.md): the ONE tri-state reader
|
|
394
|
+
* every artifact-reading call site routes through. Round 3's `readArtifact`
|
|
395
|
+
* collapsed THREE outcomes into one `undefined` — "never written" and
|
|
396
|
+
* "read refused" (symlink escape / outside the run dir / unparseable JSON)
|
|
397
|
+
* were indistinguishable to every caller. That single value with two
|
|
398
|
+
* meanings is exactly what let a swapped/deleted accepted artifact reach
|
|
399
|
+
* the send slot as `undefined`, get `?? null`-ed by `src/send.js`, and ship
|
|
400
|
+
* a 4-byte `null` to the signed destination as a recorded "green" send —
|
|
401
|
+
* the refusal `readFileInside` already computes was thrown away one layer
|
|
402
|
+
* up. Every caller below now sees the real shape and decides, explicitly,
|
|
403
|
+
* whether "missing" is fine (a genuinely not-yet-written read) or whether
|
|
404
|
+
* ANY refusal — missing or red — must halt the run.
|
|
405
|
+
* @returns {{ok:true, value:any} | {ok:false, missing:true} | {ok:false, missing:false, red:string}}
|
|
406
|
+
*/
|
|
407
|
+
export function readArtifactResult(runDir, id) {
|
|
408
|
+
const result = readFileInside(runDir, `artifacts/${id}.json`);
|
|
409
|
+
if (!result.ok) return result;
|
|
410
|
+
let value;
|
|
411
|
+
try {
|
|
412
|
+
value = JSON.parse(result.text);
|
|
413
|
+
} catch (err) {
|
|
414
|
+
return { ok: false, missing: false, red: `artifact "${id}" is not valid JSON — ${err.message}` };
|
|
415
|
+
}
|
|
416
|
+
return { ok: true, value };
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/** Back-compat convenience collapse of `readArtifactResult`: `undefined` for
|
|
420
|
+
* BOTH "never written" and "read refused" — the exact collapse the F48
|
|
421
|
+
* round 4 redesign says a caller must never reach for on its own. Safe to
|
|
422
|
+
* use ONLY where an explicit tri-state check has already refused any `red`
|
|
423
|
+
* for this same id earlier in the same call (documented at each remaining
|
|
424
|
+
* call site) — never add a NEW call site with this function instead of
|
|
425
|
+
* `readArtifactResult`.
|
|
426
|
+
*/
|
|
353
427
|
export function readArtifact(runDir, id) {
|
|
354
|
-
const
|
|
355
|
-
|
|
356
|
-
return JSON.parse(readFileSync(target, 'utf8'));
|
|
428
|
+
const result = readArtifactResult(runDir, id);
|
|
429
|
+
return result.ok ? result.value : undefined;
|
|
357
430
|
}
|
|
358
431
|
|
|
359
|
-
|
|
360
|
-
|
|
432
|
+
/** `readArtifactResult` for a whole `reads` array. A genuinely-missing read
|
|
433
|
+
* (never written) still renders as `undefined` in the map, unchanged from
|
|
434
|
+
* before — but a REFUSED read (red) is never silently folded in as
|
|
435
|
+
* `undefined` alongside it; the caller gets `{ok:false, red}` instead and
|
|
436
|
+
* must halt rather than feed tampered/unreadable content (or a `undefined`
|
|
437
|
+
* indistinguishable from "not written yet") into a step.
|
|
438
|
+
* @returns {{ok:true, map:Record<string,any>} | {ok:false, red:string}}
|
|
439
|
+
*/
|
|
440
|
+
function readArtifactsMapChecked(runDir, ids) {
|
|
441
|
+
const map = {};
|
|
442
|
+
for (const id of ids ?? []) {
|
|
443
|
+
const result = readArtifactResult(runDir, id);
|
|
444
|
+
if (!result.ok && !result.missing) {
|
|
445
|
+
return { ok: false, red: `artifact "${id}" — ${result.red}` };
|
|
446
|
+
}
|
|
447
|
+
map[id] = result.ok ? result.value : undefined;
|
|
448
|
+
}
|
|
449
|
+
return { ok: true, map };
|
|
361
450
|
}
|
|
362
451
|
|
|
363
452
|
// ---------------------------------------------------------------------------
|
|
@@ -367,7 +456,7 @@ function readArtifactsMap(runDir, ids) {
|
|
|
367
456
|
// nothing.
|
|
368
457
|
// ---------------------------------------------------------------------------
|
|
369
458
|
|
|
370
|
-
function recordLateAnswerIfAny(runDir) {
|
|
459
|
+
function recordLateAnswerIfAny(runDir, now = () => new Date().toISOString()) {
|
|
371
460
|
const file = join(runDir, 'answer.json');
|
|
372
461
|
if (!existsSync(file)) return;
|
|
373
462
|
appendAudit(runDir, {
|
|
@@ -382,6 +471,9 @@ function recordLateAnswerIfAny(runDir) {
|
|
|
382
471
|
model: null,
|
|
383
472
|
modelMatch: null,
|
|
384
473
|
strike: false,
|
|
474
|
+
at: now(),
|
|
475
|
+
tokens: null,
|
|
476
|
+
tools: null,
|
|
385
477
|
kind: 'answer-after-run',
|
|
386
478
|
file,
|
|
387
479
|
});
|
|
@@ -406,10 +498,29 @@ function sumKnownUsd(...values) {
|
|
|
406
498
|
return known.reduce((a, b) => a + b, 0);
|
|
407
499
|
}
|
|
408
500
|
|
|
501
|
+
// Amendment M4a-2 — SIGNED by hamr 2026-09-27 ("sign mfa2", = M4a-2):
|
|
502
|
+
// `at` (this attempt's own finish time, off the run's injected clock — never
|
|
503
|
+
// the bare wall clock, exactly like every other timestamp this module
|
|
504
|
+
// writes) and `tokens` (threaded straight from `modelStep`'s own result,
|
|
505
|
+
// which sums it at the SAME place it sums `costUsd` across a step's rounds
|
|
506
|
+
// — never re-derived here or anywhere else by position from spend.jsonl).
|
|
507
|
+
// `tokens` defaults to `null`: every call site with no model call (cap-halt,
|
|
508
|
+
// paused, ask-timeout, refused, accept, redo-rejected) leaves it at that
|
|
509
|
+
// default; every call site with a `modelStep` result passes its own
|
|
510
|
+
// `result.tokens` through unchanged.
|
|
511
|
+
// M4a-3 (docs/wiki/the-module-ladder.md, "M4a" section, "Amendment M4a-3 —
|
|
512
|
+
// SIGNED by hamr 2026-09-27"): `tools` (a {toolName: count} tally, threaded
|
|
513
|
+
// straight from `modelStep`'s own result — never re-derived here) and
|
|
514
|
+
// `ungranted` (an array of tool names the model called that this step never
|
|
515
|
+
// granted; omitted entirely when empty, per `src/books.js`'s own contract).
|
|
516
|
+
// Both default the same way `tokens` does: every call site with no model
|
|
517
|
+
// call leaves `tools` at its `null` default; every call site with a
|
|
518
|
+
// `modelStep` result passes `result.tools`/`result.ungranted` through
|
|
519
|
+
// unchanged.
|
|
409
520
|
function makeAuditRow({
|
|
410
|
-
step, attempt, verdict, gap, usd, spendComplete, wallMs, model = null, modelMatch = null, strike,
|
|
521
|
+
step, attempt, verdict, gap, usd, spendComplete, wallMs, model = null, modelMatch = null, strike, at, tokens = null, tools = null, ungranted = /** @type {string[]|undefined} */ (undefined), refused = /** @type {Array<{verb:string,path:string,rule:string}>} */ ([]),
|
|
411
522
|
}) {
|
|
412
|
-
|
|
523
|
+
const row = {
|
|
413
524
|
step: step?.emits ?? step?.goal ?? null,
|
|
414
525
|
attempt,
|
|
415
526
|
class: step?.close?.class ?? null,
|
|
@@ -421,7 +532,13 @@ function makeAuditRow({
|
|
|
421
532
|
model: model ?? null,
|
|
422
533
|
modelMatch: modelMatch ?? null,
|
|
423
534
|
strike: !!strike,
|
|
535
|
+
at,
|
|
536
|
+
tokens,
|
|
537
|
+
tools,
|
|
538
|
+
refused,
|
|
424
539
|
};
|
|
540
|
+
if (ungranted !== undefined && ungranted.length > 0) row.ungranted = ungranted;
|
|
541
|
+
return row;
|
|
425
542
|
}
|
|
426
543
|
|
|
427
544
|
/**
|
|
@@ -443,10 +560,18 @@ function makeAuditRow({
|
|
|
443
560
|
* @param {(row: any, modelOutput?: any) => void} opts.recordAudit
|
|
444
561
|
* @param {string|null} [opts.initialGap]
|
|
445
562
|
* @param {number} [opts.attemptOffset]
|
|
563
|
+
* @param {() => string} [opts.now] - M4a-2: stamps each audit row's `at`;
|
|
564
|
+
* defaults to the real wall clock.
|
|
446
565
|
* @returns {Promise<{ok:true, artifact:any, attempts:number, hitl?:boolean} | {ok:false, outcome:string, red:string}>}
|
|
447
566
|
*/
|
|
448
567
|
async function runStepRalph({
|
|
449
568
|
step, primitivesMap, readsMap, businessDate, modelStep, spent, capUsd, ceilingUsd, recordAudit, initialGap = null, attemptOffset = 0,
|
|
569
|
+
// M4a-2: the run's own injected clock (never the bare wall clock) —
|
|
570
|
+
// stamps every audit row's `at` with this attempt's finish time. Defaults
|
|
571
|
+
// to the real wall clock so a caller that doesn't inject one (there are
|
|
572
|
+
// none left in production; a defensive default only) still writes a valid
|
|
573
|
+
// ISO string.
|
|
574
|
+
now = () => new Date().toISOString(),
|
|
450
575
|
}) {
|
|
451
576
|
/** @type {string|null} */
|
|
452
577
|
let gap = initialGap ?? null;
|
|
@@ -462,7 +587,7 @@ async function runStepRalph({
|
|
|
462
587
|
let attemptFloorUsd = null;
|
|
463
588
|
if (spent.value + ceilingUsd > capUsd) {
|
|
464
589
|
recordAudit(makeAuditRow({
|
|
465
|
-
step, attempt, verdict: 'cap-halt', gap, usd: null, spendComplete: false, wallMs: 0, strike: false,
|
|
590
|
+
step, attempt, verdict: 'cap-halt', gap, usd: null, spendComplete: false, wallMs: 0, strike: false, at: now(),
|
|
466
591
|
}));
|
|
467
592
|
return {
|
|
468
593
|
ok: false,
|
|
@@ -512,7 +637,7 @@ async function runStepRalph({
|
|
|
512
637
|
// null second cost never zeroes out a known first floor.
|
|
513
638
|
const usd = sumKnownUsd(attemptFloorUsd, result.costUsd);
|
|
514
639
|
recordAudit(makeAuditRow({
|
|
515
|
-
step, attempt, verdict: 'provider-red', gap, usd, spendComplete: false, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false,
|
|
640
|
+
step, attempt, verdict: 'provider-red', gap, usd, spendComplete: false, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false, at: now(), tokens: result.tokens ?? null, tools: result.tools ?? null, ungranted: result.ungranted, refused: result.refused,
|
|
516
641
|
}), result.red ?? 'transport fault twice');
|
|
517
642
|
return { ok: false, outcome: 'provider-red', red: `provider-red: step "${step.goal}" attempt ${attempt}: ${result.red ?? 'transport fault twice'}` };
|
|
518
643
|
}
|
|
@@ -529,7 +654,7 @@ async function runStepRalph({
|
|
|
529
654
|
if (strike) strikes += 1;
|
|
530
655
|
const usd = sumKnownUsd(attemptFloorUsd, result?.costUsd);
|
|
531
656
|
recordAudit(makeAuditRow({
|
|
532
|
-
step, attempt, verdict: 'red', gap: red, usd, spendComplete: usd !== null, wallMs, model: result?.model, modelMatch: result?.modelMatch, strike,
|
|
657
|
+
step, attempt, verdict: 'red', gap: red, usd, spendComplete: usd !== null, wallMs, model: result?.model, modelMatch: result?.modelMatch, strike, at: now(), tokens: result?.tokens ?? null, tools: result?.tools ?? null, ungranted: result?.ungranted, refused: result?.refused,
|
|
533
658
|
}), red);
|
|
534
659
|
if (n === MAX_ATTEMPTS) return { ok: false, outcome: 'attempt-fallback', red: `attempt-fallback: step "${step.goal}" — ${red}` };
|
|
535
660
|
if (strikes >= STRIKE_LIMIT) return { ok: false, outcome: 'struck-out', red: `struck-out: step "${step.goal}" — ${red}` };
|
|
@@ -540,7 +665,7 @@ async function runStepRalph({
|
|
|
540
665
|
|
|
541
666
|
if (result.costUsd === null || result.costUsd === undefined) {
|
|
542
667
|
recordAudit(makeAuditRow({
|
|
543
|
-
step, attempt, verdict: 'pricing-red', gap, usd: attemptFloorUsd, spendComplete: false, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false,
|
|
668
|
+
step, attempt, verdict: 'pricing-red', gap, usd: attemptFloorUsd, spendComplete: false, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false, at: now(), tokens: result.tokens ?? null, tools: result.tools ?? null, ungranted: result.ungranted, refused: result.refused,
|
|
544
669
|
}), result.artifact ?? null);
|
|
545
670
|
return { ok: false, outcome: 'pricing-red', red: `pricing-red: step "${step.goal}" attempt ${attempt} returned no cost (never "?? 0")` };
|
|
546
671
|
}
|
|
@@ -555,7 +680,7 @@ async function runStepRalph({
|
|
|
555
680
|
const doneCheck = checkDoneBlocker(step, result.artifact);
|
|
556
681
|
if (doneCheck.verdict === 'not-done') {
|
|
557
682
|
recordAudit(makeAuditRow({
|
|
558
|
-
step, attempt, verdict: 'not-done', gap: doneCheck.red, usd: attemptUsd, spendComplete: true, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false,
|
|
683
|
+
step, attempt, verdict: 'not-done', gap: doneCheck.red, usd: attemptUsd, spendComplete: true, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false, at: now(), tokens: result.tokens ?? null, tools: result.tools ?? null, ungranted: result.ungranted, refused: result.refused,
|
|
559
684
|
}), result.artifact ?? null);
|
|
560
685
|
return { ok: false, outcome: 'not-done', red: doneCheck.red };
|
|
561
686
|
}
|
|
@@ -568,7 +693,7 @@ async function runStepRalph({
|
|
|
568
693
|
// failure) — matches poc/m2/gapback.mjs's own rule exactly.
|
|
569
694
|
strikes += 1;
|
|
570
695
|
recordAudit(makeAuditRow({
|
|
571
|
-
step, attempt, verdict: 'red', gap: happened.red, usd: attemptUsd, spendComplete: true, wallMs, model: result.model, modelMatch: result.modelMatch, strike: true,
|
|
696
|
+
step, attempt, verdict: 'red', gap: happened.red, usd: attemptUsd, spendComplete: true, wallMs, model: result.model, modelMatch: result.modelMatch, strike: true, at: now(), tokens: result.tokens ?? null, tools: result.tools ?? null, ungranted: result.ungranted, refused: result.refused,
|
|
572
697
|
}), result.artifact ?? null);
|
|
573
698
|
if (n === MAX_ATTEMPTS) return { ok: false, outcome: 'attempt-fallback', red: `attempt-fallback: ${happened.red}` };
|
|
574
699
|
if (strikes >= STRIKE_LIMIT) return { ok: false, outcome: 'struck-out', red: `struck-out: ${happened.red}` };
|
|
@@ -581,7 +706,7 @@ async function runStepRalph({
|
|
|
581
706
|
|
|
582
707
|
if (closed.verdict === 'green' || closed.verdict === 'hitl') {
|
|
583
708
|
recordAudit(makeAuditRow({
|
|
584
|
-
step, attempt, verdict: closed.verdict, gap: null, usd: attemptUsd, spendComplete: true, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false,
|
|
709
|
+
step, attempt, verdict: closed.verdict, gap: null, usd: attemptUsd, spendComplete: true, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false, at: now(), tokens: result.tokens ?? null, tools: result.tools ?? null, ungranted: result.ungranted, refused: result.refused,
|
|
585
710
|
}), result.artifact);
|
|
586
711
|
return {
|
|
587
712
|
ok: true, artifact, attempts: attempt, hitl: closed.verdict === 'hitl',
|
|
@@ -592,7 +717,7 @@ async function runStepRalph({
|
|
|
592
717
|
// A closer that renders no judgment ('unparseable'/'crash') is a
|
|
593
718
|
// CASUALTY, never a red and never a strike (bareloop F17).
|
|
594
719
|
recordAudit(makeAuditRow({
|
|
595
|
-
step, attempt, verdict: 'close-casualty', gap: closed.red, usd: attemptUsd, spendComplete: true, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false,
|
|
720
|
+
step, attempt, verdict: 'close-casualty', gap: closed.red, usd: attemptUsd, spendComplete: true, wallMs, model: result.model, modelMatch: result.modelMatch, strike: false, at: now(), tokens: result.tokens ?? null, tools: result.tools ?? null, ungranted: result.ungranted, refused: result.refused,
|
|
596
721
|
}), result.artifact);
|
|
597
722
|
return { ok: false, outcome: 'close-casualty', red: `close-casualty: step "${step.goal}" — ${closed.red} (${closed.verdict})` };
|
|
598
723
|
}
|
|
@@ -602,7 +727,7 @@ async function runStepRalph({
|
|
|
602
727
|
seenGaps.add(normalised);
|
|
603
728
|
if (strike) strikes += 1;
|
|
604
729
|
recordAudit(makeAuditRow({
|
|
605
|
-
step, attempt, verdict: 'red', gap: closed.red, usd: attemptUsd, spendComplete: true, wallMs, model: result.model, modelMatch: result.modelMatch, strike,
|
|
730
|
+
step, attempt, verdict: 'red', gap: closed.red, usd: attemptUsd, spendComplete: true, wallMs, model: result.model, modelMatch: result.modelMatch, strike, at: now(), tokens: result.tokens ?? null, tools: result.tools ?? null, ungranted: result.ungranted, refused: result.refused,
|
|
606
731
|
}), result.artifact);
|
|
607
732
|
|
|
608
733
|
if (n === MAX_ATTEMPTS) return { ok: false, outcome: 'attempt-fallback', red: `attempt-fallback: step "${step.goal}" — ${closed.red}` };
|
|
@@ -625,19 +750,47 @@ async function runStepRalph({
|
|
|
625
750
|
* @param {Array<{id:string, path:string}>} opts.sources - the real files to freeze for this run.
|
|
626
751
|
* @param {unknown} opts.catalogue - passed straight through to `readFlow`.
|
|
627
752
|
* @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
|
|
753
|
+
* @param {(opts:{question:string, evidence:unknown, runDir:string}) => Promise<{decision:'accept'|'reject'|'rerun'|'timeout'|'park', reason?:string}>} opts.askStep
|
|
629
754
|
* @param {(target:string, filename:string, content:unknown) => Promise<{ok:boolean, red?:string, bytes?:number}>} opts.sendStep
|
|
630
755
|
* @param {Record<string, any>} [opts.primitives] - injected primitive implementations, keyed by catalogue verb.
|
|
756
|
+
* @param {string[]} [opts.primitiveReds] - `resolvePrimitives`'s own `reds` (e.g. bareguard refusing a symlinked file scope); any entry refuses the run at $0 like an unwired verb, before the run dir exists.
|
|
631
757
|
* @param {() => string} [opts.clock] - returns the current ISO timestamp; defaults to the wall clock.
|
|
632
758
|
* @param {string} opts.businessDate - the run's explicit "as of today", never the wall clock.
|
|
633
759
|
* @param {number} [opts.ceilingUsd] - per-attempt ceiling override; defaults to `resolveCeilingUsd(null)`.
|
|
760
|
+
* @param {string|null} [opts.initialGap] - M3 scope item 7 (rerun as a fresh
|
|
761
|
+
* run): a human's rerun reason, carried as the FIRST ordinary step's
|
|
762
|
+
* starting gap. Never used by a plain `runFlow` call outside `resumeRun`'s
|
|
763
|
+
* own rerun path.
|
|
764
|
+
* @param {() => number} [opts.nowMs] - F45 finding 3: returns the current
|
|
765
|
+
* epoch ms; defaults to the wall clock. Mirrors `clock` (ISO) so a test
|
|
766
|
+
* can advance wall time across a park/resume boundary without a real wait.
|
|
634
767
|
*/
|
|
635
768
|
export async function runFlow({
|
|
636
|
-
root, name, runId, sources, catalogue, modelStep, askStep, sendStep, primitives, clock, businessDate, ceilingUsd,
|
|
769
|
+
root, name, runId, sources, catalogue, modelStep, askStep, sendStep, primitives, primitiveReds, clock, businessDate, ceilingUsd, initialGap,
|
|
770
|
+
// F45 finding 3's test needs to advance wall time across a park/resume
|
|
771
|
+
// boundary without a real wait, exactly like `clock` already does for ISO
|
|
772
|
+
// timestamps — `nowMs` is the same idea for epoch-ms wall-clock reads.
|
|
773
|
+
// Minimal and additive: every existing caller (no `nowMs`) gets the real
|
|
774
|
+
// `Date.now`, unchanged.
|
|
775
|
+
nowMs,
|
|
637
776
|
}) {
|
|
638
777
|
const now = typeof clock === 'function' ? clock : () => new Date().toISOString();
|
|
778
|
+
const getNowMs = typeof nowMs === 'function' ? nowMs : Date.now;
|
|
639
779
|
const flowDir = join(root, name);
|
|
640
|
-
const startedAt =
|
|
780
|
+
const startedAt = getNowMs();
|
|
781
|
+
|
|
782
|
+
// Defense in depth alongside `bin/fwdloop`'s own `resolveRunDir` check on
|
|
783
|
+
// `--run-id`: a caller-supplied runId that would escape `flowDir/runs/`
|
|
784
|
+
// (`..`, a `/`/`\` segment, ...) is refused by name, at $0, before any
|
|
785
|
+
// directory for this run is even looked at, let alone created.
|
|
786
|
+
const runIdCheck = resolveRunDir(flowDir, runId);
|
|
787
|
+
if (!runIdCheck.ok) {
|
|
788
|
+
mkdirSync(flowDir, { recursive: true });
|
|
789
|
+
appendHistory(flowDir, {
|
|
790
|
+
runId, at: now(), outcome: 'refused', spentUsd: 0, spendComplete: true, capUsd: null, wallMs: Date.now() - startedAt, signatureHash: null,
|
|
791
|
+
});
|
|
792
|
+
return { outcome: 'refused', red: runIdCheck.red };
|
|
793
|
+
}
|
|
641
794
|
|
|
642
795
|
const read = readFlow({ root, name, catalogue });
|
|
643
796
|
if (!read.ok) {
|
|
@@ -661,12 +814,35 @@ export async function runFlow({
|
|
|
661
814
|
const askLines = new Map((arbiter.asks ?? []).map((a) => [a.line, a]));
|
|
662
815
|
const sendLines = new Map((arbiter.sends ?? []).map((s) => [s.line, s]));
|
|
663
816
|
|
|
664
|
-
const runDir =
|
|
817
|
+
const runDir = runIdCheck.runDir;
|
|
818
|
+
|
|
819
|
+
const unwiredVerb = findUnwiredVerbStep(declaration);
|
|
820
|
+
if (unwiredVerb) {
|
|
821
|
+
return haltRun({
|
|
822
|
+
flowDir,
|
|
823
|
+
runDir,
|
|
824
|
+
runId,
|
|
825
|
+
capUsd,
|
|
826
|
+
startedAt,
|
|
827
|
+
now,
|
|
828
|
+
nowMs: getNowMs,
|
|
829
|
+
signatureHash: signature.flow,
|
|
830
|
+
outcome: 'preflight-red',
|
|
831
|
+
red: `preflight: step "${unwiredVerb.step.emits}" (line ${unwiredVerb.step.fromLine}) grants verb "${unwiredVerb.verb}", which has no wired implementation`,
|
|
832
|
+
spent: { value: 0 },
|
|
833
|
+
});
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
if (primitiveReds?.length) {
|
|
837
|
+
return haltRun({
|
|
838
|
+
flowDir, runDir, runId, capUsd, startedAt, now, nowMs: getNowMs, signatureHash: signature.flow, outcome: 'preflight-red', red: primitiveReds[0], spent: { value: 0 },
|
|
839
|
+
});
|
|
840
|
+
}
|
|
665
841
|
|
|
666
842
|
const fresh = checkFreshRunDir(runDir);
|
|
667
843
|
if (!fresh.ok) {
|
|
668
844
|
return haltRun({
|
|
669
|
-
flowDir, runDir, runId, capUsd, startedAt, now, signatureHash: signature.flow, outcome: 'preflight-red', red: fresh.red, spent: { value: 0 },
|
|
845
|
+
flowDir, runDir, runId, capUsd, startedAt, now, nowMs: getNowMs, signatureHash: signature.flow, outcome: 'preflight-red', red: fresh.red, spent: { value: 0 },
|
|
670
846
|
});
|
|
671
847
|
}
|
|
672
848
|
mkdirSync(runDir, { recursive: true });
|
|
@@ -674,7 +850,7 @@ export async function runFlow({
|
|
|
674
850
|
const frozen = freezeInputs(runDir, sources ?? []);
|
|
675
851
|
if (!frozen.ok) {
|
|
676
852
|
return haltRun({
|
|
677
|
-
flowDir, runDir, runId, capUsd, startedAt, now, signatureHash: signature.flow, outcome: 'preflight-red', red: frozen.red, spent: { value: 0 },
|
|
853
|
+
flowDir, runDir, runId, capUsd, startedAt, now, nowMs: getNowMs, signatureHash: signature.flow, outcome: 'preflight-red', red: frozen.red, spent: { value: 0 },
|
|
678
854
|
});
|
|
679
855
|
}
|
|
680
856
|
|
|
@@ -685,6 +861,14 @@ export async function runFlow({
|
|
|
685
861
|
// shape) and folded into log.json only, on every exit path.
|
|
686
862
|
/** @type {any[]} */
|
|
687
863
|
const attemptsLog = [];
|
|
864
|
+
// Orchestrator review fix (4): a floor stays a floor — once ANY row this
|
|
865
|
+
// run carries `spendComplete: false` (a cost that never resolved to a
|
|
866
|
+
// known number, e.g. a retried transport fault that still failed), the
|
|
867
|
+
// run's OWN aggregate never flips back to true, park or no park. Threaded
|
|
868
|
+
// into every book row `foldFromStep`/`runAskSlot` writes and persisted in
|
|
869
|
+
// `state.json` so a resumed run inherits the floor instead of quietly
|
|
870
|
+
// reporting complete.
|
|
871
|
+
const spendComplete = { value: true };
|
|
688
872
|
const recordAudit = (row, modelOutput, unjudgedCount) => {
|
|
689
873
|
// M2 amendment 1 item 2: "audit row for the ask gains unjudgedCount" —
|
|
690
874
|
// only the ask's own rows pass a third argument; every other row is
|
|
@@ -692,9 +876,10 @@ export async function runFlow({
|
|
|
692
876
|
const fullRow = unjudgedCount === undefined ? row : { ...row, unjudgedCount };
|
|
693
877
|
auditRows.push(fullRow);
|
|
694
878
|
appendAudit(runDir, fullRow);
|
|
879
|
+
if (row.spendComplete === false) spendComplete.value = false;
|
|
695
880
|
if (modelOutput !== undefined) {
|
|
696
881
|
attemptsLog.push({
|
|
697
|
-
step: row.step, attempt: row.attempt, class: row.class, verdict: row.verdict, gap: row.gap, modelOutput,
|
|
882
|
+
step: row.step, attempt: row.attempt, class: row.class, verdict: row.verdict, gap: row.gap, ...(row.refused ? { refused: row.refused } : {}), modelOutput,
|
|
698
883
|
});
|
|
699
884
|
}
|
|
700
885
|
};
|
|
@@ -711,56 +896,395 @@ export async function runFlow({
|
|
|
711
896
|
// emitted by a signed ask step), never by position in `reads` — every id
|
|
712
897
|
// in a send step's `reads` names an earlier step, so picking `reads[0]`
|
|
713
898
|
// silently ships whatever was read first instead of what was accepted.
|
|
714
|
-
// Derived the same way the
|
|
899
|
+
// Derived the same way the fold below knows a step is an ask — bound to
|
|
715
900
|
// an `arbiter.asks[]` line.
|
|
716
901
|
const askStepEmits = new Set(steps.filter((s) => askLines.has(s.fromLine)).map((s) => s.emits));
|
|
717
902
|
// Tracks which specific ask emits were accepted THIS run (acceptedThisRun
|
|
718
903
|
// above stays run-wide, for the "reached with no accept this run" gate).
|
|
719
904
|
const acceptedAskEmitsThisRun = new Set();
|
|
720
|
-
|
|
905
|
+
|
|
906
|
+
const result = await foldFromStep({
|
|
907
|
+
i0: 0,
|
|
908
|
+
steps,
|
|
909
|
+
askLines,
|
|
910
|
+
sendLines,
|
|
911
|
+
askStepEmits,
|
|
912
|
+
runDir,
|
|
913
|
+
flowDir,
|
|
914
|
+
runId,
|
|
915
|
+
flowRoot: root,
|
|
916
|
+
flowName: name,
|
|
917
|
+
signatureHash: signature.flow,
|
|
918
|
+
inputsManifest: frozen.manifest,
|
|
919
|
+
capUsd,
|
|
920
|
+
redoCap,
|
|
921
|
+
effectiveCeilingUsd,
|
|
922
|
+
primitives,
|
|
923
|
+
businessDate,
|
|
924
|
+
modelStep,
|
|
925
|
+
askStep,
|
|
926
|
+
sendStep,
|
|
927
|
+
now,
|
|
928
|
+
startedAt,
|
|
929
|
+
nowMs: getNowMs,
|
|
930
|
+
// F45 finding 3: `runStartedAt` is the run's TRUE wall-clock start — for
|
|
931
|
+
// a fresh `runFlow` call it's this same `startedAt` (there is no earlier
|
|
932
|
+
// process). It is what park persists into state.json and every resume
|
|
933
|
+
// restores, so a run's final `wallMs` times the whole run, not just the
|
|
934
|
+
// last process (a pause counts as elapsed wall time — see the comment
|
|
935
|
+
// at its use in `foldFromStep`).
|
|
936
|
+
runStartedAt: startedAt,
|
|
937
|
+
spent,
|
|
938
|
+
spendComplete,
|
|
939
|
+
artifacts,
|
|
940
|
+
acceptedThisRun,
|
|
941
|
+
acceptedAskEmitsThisRun,
|
|
942
|
+
unjudgedSinceLastAsk,
|
|
943
|
+
recordAudit,
|
|
944
|
+
attemptsLog,
|
|
945
|
+
firstStepGap: initialGap ?? null,
|
|
946
|
+
});
|
|
947
|
+
|
|
948
|
+
if (result.outcome === 'complete') return { ...result, auditRows };
|
|
949
|
+
return result;
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
// ---------------------------------------------------------------------------
|
|
953
|
+
// M3 piece 1 (docs/wiki/the-module-ladder.md, "M3 — scope, exit, negative —
|
|
954
|
+
// SIGNED", scope items 1-2, 4-6, 8): park-and-exit at a signed ask, and
|
|
955
|
+
// resuming into the SAME fold from a separate process later. ONE fold —
|
|
956
|
+
// `foldFromStep` below is the loop `runFlow` always ran (M2), now starting
|
|
957
|
+
// at an arbitrary step index with restored accumulators so `resumeRun` can
|
|
958
|
+
// re-enter it exactly where a parked run left off, instead of a second
|
|
959
|
+
// runner.
|
|
960
|
+
//
|
|
961
|
+
// borrowed-from: fwdloop poc/m3/park.mjs@afb85d7 (the park/answer/resume
|
|
962
|
+
// protocol proved at F44 — ask.json+state.json's fields, the exclusive
|
|
963
|
+
// `resume.lock`, consuming `answer.json` by rename BEFORE acting). Rewritten
|
|
964
|
+
// against the real `runFlow` fold (the POC ran fake, hand-rolled steps
|
|
965
|
+
// against a single hard-coded ask, never `runStepRalph`/`runAskSlot`) — src/
|
|
966
|
+
// never imports from poc/.
|
|
967
|
+
// ---------------------------------------------------------------------------
|
|
968
|
+
|
|
969
|
+
/** An ask step that never waits — it immediately tells the fold to park.
|
|
970
|
+
* The counterpart to `makeFileAskStep`'s in-process poll (M2 scope item 6);
|
|
971
|
+
* a caller wanting park-and-exit behaviour from a FRESH `runFlow` call
|
|
972
|
+
* passes this (or an equivalent) as `askStep`.
|
|
973
|
+
* @returns {(opts?: any) => Promise<{decision: 'park'}>} */
|
|
974
|
+
export function makeParkingAskStep() {
|
|
975
|
+
return async function parkingAskStep() {
|
|
976
|
+
return /** @type {{decision: 'park'}} */ ({ decision: 'park' });
|
|
977
|
+
};
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
/** `resumeRun`'s own askStep: yields the human's already-consumed decision
|
|
981
|
+
* exactly once (for the ask it was built for), then — if that decision was
|
|
982
|
+
* a reject and the ask loops back around to ask again — parks under a NEW
|
|
983
|
+
* askId, exactly like a fresh ask would. This is what turns "redo, then
|
|
984
|
+
* ask again" into "redo, then re-park" for a resumed run, with no second
|
|
985
|
+
* code path. */
|
|
986
|
+
function makeOneShotThenParkAskStep({ decision, reason }) {
|
|
987
|
+
let used = false;
|
|
988
|
+
return async function resumeAskStep() {
|
|
989
|
+
if (!used) {
|
|
990
|
+
used = true;
|
|
991
|
+
return { decision, reason };
|
|
992
|
+
}
|
|
993
|
+
return { decision: 'park' };
|
|
994
|
+
};
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
/**
|
|
998
|
+
* One signed ask slot's own loop (M2's ask branch, unchanged in spirit,
|
|
999
|
+
* extracted so `resumeRun` can re-enter the SAME logic mid-ask instead of
|
|
1000
|
+
* duplicating it). Returns exactly one of:
|
|
1001
|
+
* - `{ type: 'paused', result }` — `askStep` chose to park; ask.json +
|
|
1002
|
+
* state.json are written and `result` is `runFlow`/`resumeRun`'s own
|
|
1003
|
+
* return value.
|
|
1004
|
+
* - `{ type: 'halted', outcome, red }` — the caller wraps this in
|
|
1005
|
+
* `haltRun` (it knows the right `signatureHash`/`artifacts` to attach).
|
|
1006
|
+
* - `{ type: 'accepted', artifact }` — the human accepted; the caller
|
|
1007
|
+
* writes the ask step's own artifact and continues the fold.
|
|
1008
|
+
*
|
|
1009
|
+
* @param {object} opts
|
|
1010
|
+
* @returns {Promise<any>}
|
|
1011
|
+
*/
|
|
1012
|
+
async function runAskSlot({
|
|
1013
|
+
step, stepIndex, askSlot, priorId, priorStep, priorArtifact, redoCap, effectiveCeilingUsd, capUsd,
|
|
1014
|
+
primitives, businessDate, modelStep, askStep, spent, spendComplete, recordAudit,
|
|
1015
|
+
evidenceUnjudged, unjudgedCount, redone: initialRedone,
|
|
1016
|
+
runDir, flowDir, runId, flowRoot, flowName, signatureHash, inputsManifest, attemptsLog, artifacts, now, startedAt,
|
|
1017
|
+
// F45 finding 3: the run's TRUE wall-clock start, persisted into
|
|
1018
|
+
// state.json on every park/re-park so a later resume can restore it
|
|
1019
|
+
// instead of substituting its own process's start.
|
|
1020
|
+
runStartedAt,
|
|
1021
|
+
}) {
|
|
1022
|
+
let redone = initialRedone;
|
|
1023
|
+
let currentPrior = priorArtifact;
|
|
1024
|
+
|
|
1025
|
+
for (;;) {
|
|
1026
|
+
const evidence = { artifact: currentPrior, unjudged: evidenceUnjudged };
|
|
1027
|
+
// eslint-disable-next-line no-await-in-loop
|
|
1028
|
+
const answer = await askStep({
|
|
1029
|
+
question: askSlot?.question ?? step.goal, evidence, runDir, ttlMs: askSlot?.ttlMs, stepIndex,
|
|
1030
|
+
});
|
|
1031
|
+
|
|
1032
|
+
if (answer.decision === 'park') {
|
|
1033
|
+
// M3 scope item 1 (fixes F43): the wait is ALWAYS the signed ttlMs —
|
|
1034
|
+
// no code default ever overrides it, on the first park or any re-park.
|
|
1035
|
+
const askId = randomUUID();
|
|
1036
|
+
const askedAt = now();
|
|
1037
|
+
const expiresAt = new Date(Date.parse(askedAt) + askSlot.ttlMs).toISOString();
|
|
1038
|
+
// F45 finding 2: a parked ask.json must carry the SAME evidence a
|
|
1039
|
+
// human sees in-process (`makeFileAskStep`'s `{ artifact, unjudged }`)
|
|
1040
|
+
// — the draft under review and the unjudged evidence, never just the
|
|
1041
|
+
// question. `evidence` above is already recomputed at the top of every
|
|
1042
|
+
// loop iteration (including a re-park after a reject, where
|
|
1043
|
+
// `currentPrior` is the just-redrafted artifact), so this write always
|
|
1044
|
+
// carries the CURRENT evidence, not a stale first-park copy.
|
|
1045
|
+
writeFileSync(join(runDir, 'ask.json'), JSON.stringify({
|
|
1046
|
+
askId, question: askSlot?.question ?? step.goal, askedAt, expiresAt, evidence,
|
|
1047
|
+
}, null, 2));
|
|
1048
|
+
// Amendment M4a-1 — SIGNED by hamr 2026-09-27 ("sign m4a1"): a
|
|
1049
|
+
// PERMANENT copy of this same park, `asks/<askId>.json`, written right
|
|
1050
|
+
// after `ask.json` (never before) — `ask.json`/`state.json` below are
|
|
1051
|
+
// what governs resume, unchanged; the archive is a second, append-only
|
|
1052
|
+
// record of the SAME content. Crash between the two writes leaves
|
|
1053
|
+
// `ask.json` present and no archive entry for this one askId — the run
|
|
1054
|
+
// is still correctly parked and resumable; `listArchivedAsks` only
|
|
1055
|
+
// ever reports what's actually on disk, never invents an entry. A
|
|
1056
|
+
// fresh `askId` per park means a red here (an already-archived askId)
|
|
1057
|
+
// is a genuine invariant violation, not a race to recover from — it
|
|
1058
|
+
// halts the run rather than silently dropping the archive duty.
|
|
1059
|
+
const archived = writeAskArchive({
|
|
1060
|
+
runDir, askId, question: askSlot?.question ?? step.goal, askedAt, expiresAt, evidence,
|
|
1061
|
+
});
|
|
1062
|
+
if (!archived.ok) {
|
|
1063
|
+
throw new Error(archived.red);
|
|
1064
|
+
}
|
|
1065
|
+
// M3 scope item 2: the minimum the fold needs to resume identically —
|
|
1066
|
+
// WHERE (stepIndex), WHAT was frozen/signed (signatureHash,
|
|
1067
|
+
// inputsManifest, to be re-verified before anything runs), WHAT this
|
|
1068
|
+
// ask is (askId/expiresAt), and the two accumulators a mid-ask resume
|
|
1069
|
+
// cannot recompute from disk alone: `redone` (the redo cap is spent
|
|
1070
|
+
// across pauses, not per process) and the evidence bundle this
|
|
1071
|
+
// specific ask already showed the human (`evidenceUnjudged`/
|
|
1072
|
+
// `unjudgedCount` — recomputing them from `unjudgedSinceLastAsk` on
|
|
1073
|
+
// resume would double-count anything a later, still-unparked ask
|
|
1074
|
+
// hasn't reset yet). `spent` carries the run's money across pauses too
|
|
1075
|
+
// (the cap binds over the whole run, never per process).
|
|
1076
|
+
const state = {
|
|
1077
|
+
runId,
|
|
1078
|
+
flow: { root: flowRoot, name: flowName },
|
|
1079
|
+
signatureHash,
|
|
1080
|
+
inputsManifest,
|
|
1081
|
+
stepIndex,
|
|
1082
|
+
askId,
|
|
1083
|
+
expiresAt,
|
|
1084
|
+
spent: spent.value,
|
|
1085
|
+
// Orchestrator review fix (4): the floor persists across a pause —
|
|
1086
|
+
// once any pre-park row left `spendComplete: false`, a resume must
|
|
1087
|
+
// inherit that, never quietly start "complete" again.
|
|
1088
|
+
spendComplete: spendComplete.value,
|
|
1089
|
+
redone,
|
|
1090
|
+
evidenceUnjudged,
|
|
1091
|
+
unjudgedCount,
|
|
1092
|
+
// F45 finding 3: persisted every park/re-park (unchanged value, just
|
|
1093
|
+
// carried forward) so `resumeRun` restores the run's true start
|
|
1094
|
+
// instead of timing only the process that happens to resume it.
|
|
1095
|
+
startedAt: runStartedAt,
|
|
1096
|
+
};
|
|
1097
|
+
writeFileSync(join(runDir, 'state.json'), JSON.stringify(state, null, 2));
|
|
1098
|
+
recordAudit(makeAuditRow({
|
|
1099
|
+
step, attempt: redone + 1, verdict: 'paused', gap: null, usd: 0, spendComplete: true, wallMs: 0, strike: false, at: now(),
|
|
1100
|
+
}), undefined, unjudgedCount);
|
|
1101
|
+
// Orchestrator review fix (3): M2 item 9 says history is ONE row per
|
|
1102
|
+
// run; M3's signed scope item 2 only asks for an AUDIT row "paused"
|
|
1103
|
+
// (already recorded above). A "paused" HISTORY row was the earlier
|
|
1104
|
+
// draft's own error — removed here. The run's one history row lands
|
|
1105
|
+
// at its final outcome (complete / a halt / ask-expired), written by
|
|
1106
|
+
// `foldFromStep`/`resumeRun`, never here.
|
|
1107
|
+
writeLog(runDir, { runId, outcome: 'paused', attempts: attemptsLog, artifacts });
|
|
1108
|
+
return {
|
|
1109
|
+
type: 'paused',
|
|
1110
|
+
result: {
|
|
1111
|
+
outcome: 'paused', runDir, askId, expiresAt, spentUsd: spent.value,
|
|
1112
|
+
},
|
|
1113
|
+
};
|
|
1114
|
+
}
|
|
1115
|
+
|
|
1116
|
+
if (answer.decision === 'timeout') {
|
|
1117
|
+
// A pause spends nothing (M2 scope item 6) — a halt, never a red
|
|
1118
|
+
// with a fabricated cost, and never re-asked (the run is over).
|
|
1119
|
+
recordAudit(makeAuditRow({
|
|
1120
|
+
step, attempt: redone + 1, verdict: 'ask-timeout', gap: null, usd: 0, spendComplete: true, wallMs: 0, strike: false, at: now(),
|
|
1121
|
+
}), undefined, unjudgedCount);
|
|
1122
|
+
return {
|
|
1123
|
+
type: 'halted',
|
|
1124
|
+
outcome: 'ask-timeout',
|
|
1125
|
+
red: `ask-timeout: step "${step.goal}" expired waiting for a human answer`,
|
|
1126
|
+
};
|
|
1127
|
+
}
|
|
1128
|
+
|
|
1129
|
+
const isRedo = answer.decision === 'reject' || answer.decision === 'rerun';
|
|
1130
|
+
const reason = typeof answer.reason === 'string' ? answer.reason.trim() : '';
|
|
1131
|
+
|
|
1132
|
+
if (isRedo && reason.length === 0) {
|
|
1133
|
+
recordAudit(makeAuditRow({
|
|
1134
|
+
step, attempt: redone + 1, verdict: 'refused', gap: 'a rejection/rerun needs a reason', usd: 0, spendComplete: true, wallMs: 0, strike: false, at: now(),
|
|
1135
|
+
}), undefined, unjudgedCount);
|
|
1136
|
+
// Refused, re-asked for the SAME attempt — never re-runs the step.
|
|
1137
|
+
// eslint-disable-next-line no-continue
|
|
1138
|
+
continue;
|
|
1139
|
+
}
|
|
1140
|
+
|
|
1141
|
+
if (answer.decision === 'accept') {
|
|
1142
|
+
recordAudit(makeAuditRow({
|
|
1143
|
+
step, attempt: redone + 1, verdict: 'green', gap: null, usd: 0, spendComplete: true, wallMs: 0, strike: false, at: now(),
|
|
1144
|
+
}), undefined, unjudgedCount);
|
|
1145
|
+
return { type: 'accepted', artifact: currentPrior };
|
|
1146
|
+
}
|
|
1147
|
+
|
|
1148
|
+
if (isRedo) {
|
|
1149
|
+
redone += 1;
|
|
1150
|
+
recordAudit(makeAuditRow({
|
|
1151
|
+
step, attempt: redone, verdict: 'red', gap: reason, usd: 0, spendComplete: true, wallMs: 0, strike: false, at: now(),
|
|
1152
|
+
}), undefined, unjudgedCount);
|
|
1153
|
+
if (redone > redoCap) {
|
|
1154
|
+
return {
|
|
1155
|
+
type: 'halted',
|
|
1156
|
+
outcome: 'redo-halt',
|
|
1157
|
+
red: `redo cap ${redoCap} reached at step "${step.goal}" after ${redone} rejections`,
|
|
1158
|
+
};
|
|
1159
|
+
}
|
|
1160
|
+
// F48 round 4: every id in `priorStep.reads` names a STILL EARLIER step
|
|
1161
|
+
// that already ran and wrote its artifact — a `red` here (symlink
|
|
1162
|
+
// swap / unparseable JSON) is tampering, never "not written yet", and
|
|
1163
|
+
// must halt the redo rather than silently feed forged/garbage content
|
|
1164
|
+
// into the model step that is about to re-run.
|
|
1165
|
+
const priorReadsResult = readArtifactsMapChecked(runDir, priorStep.reads);
|
|
1166
|
+
if (!priorReadsResult.ok) {
|
|
1167
|
+
return { type: 'halted', outcome: 'red', red: `redo: step "${priorStep.goal}" ${priorReadsResult.red}` };
|
|
1168
|
+
}
|
|
1169
|
+
// eslint-disable-next-line no-await-in-loop
|
|
1170
|
+
const redoResult = await runStepRalph({
|
|
1171
|
+
step: priorStep, primitivesMap: primitives, readsMap: priorReadsResult.map, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, initialGap: reason, attemptOffset: redone, now,
|
|
1172
|
+
});
|
|
1173
|
+
if (!redoResult.ok) {
|
|
1174
|
+
return { type: 'halted', outcome: redoResult.outcome, red: redoResult.red };
|
|
1175
|
+
}
|
|
1176
|
+
currentPrior = redoResult.artifact;
|
|
1177
|
+
// A redo deliberately REPLACES the prior step's own artifact — the one
|
|
1178
|
+
// case `writeArtifact` allows to overwrite on purpose.
|
|
1179
|
+
writeArtifact(runDir, priorId, currentPrior, { overwrite: true });
|
|
1180
|
+
artifacts[priorId] = currentPrior;
|
|
1181
|
+
// eslint-disable-next-line no-continue
|
|
1182
|
+
continue;
|
|
1183
|
+
}
|
|
1184
|
+
|
|
1185
|
+
return {
|
|
1186
|
+
type: 'halted',
|
|
1187
|
+
outcome: 'red',
|
|
1188
|
+
red: `ask: step "${step.goal}" got an unrecognised decision "${answer.decision}"`,
|
|
1189
|
+
};
|
|
1190
|
+
}
|
|
1191
|
+
}
|
|
1192
|
+
|
|
1193
|
+
/**
|
|
1194
|
+
* The fold itself (M2 scope item 1's "one fold", now start-anywhere): walks
|
|
1195
|
+
* `steps` from `i0`, handling the signed send slot, the signed ask slot (via
|
|
1196
|
+
* `runAskSlot`), and ordinary steps exactly as `runFlow` always did. Used by
|
|
1197
|
+
* `runFlow` (i0 = 0, fresh accumulators) and by `resumeRun` (i0 = the step
|
|
1198
|
+
* AFTER the ask it just resolved, accumulators restored from `state.json`
|
|
1199
|
+
* plus disk).
|
|
1200
|
+
* @returns {Promise<any>}
|
|
1201
|
+
*/
|
|
1202
|
+
async function foldFromStep({
|
|
1203
|
+
i0, steps, askLines, sendLines, askStepEmits, runDir, flowDir, runId, flowRoot, flowName, signatureHash,
|
|
1204
|
+
inputsManifest, capUsd, redoCap, effectiveCeilingUsd, primitives, businessDate, modelStep, askStep, sendStep,
|
|
1205
|
+
// F45 finding 3: `startedAt` times only THIS process (used for the pre-fold
|
|
1206
|
+
// halts in `runFlow` and as this call's own fallback below); `runStartedAt`
|
|
1207
|
+
// is the run's true wall-clock start, persisted at park and restored on
|
|
1208
|
+
// every resume — every halt/complete a fold reaches must time itself
|
|
1209
|
+
// against `runStartedAt`, never the current process's own start, or a
|
|
1210
|
+
// resumed run's wallMs collapses to "how long did this resume take" (F45's
|
|
1211
|
+
// observed 19ms). Defaults to `startedAt` for a fresh run, where they are
|
|
1212
|
+
// the same instant.
|
|
1213
|
+
now, startedAt, runStartedAt = startedAt, nowMs = Date.now, spent, spendComplete, artifacts, acceptedThisRun, acceptedAskEmitsThisRun, unjudgedSinceLastAsk,
|
|
1214
|
+
recordAudit, attemptsLog,
|
|
1215
|
+
// M3 scope item 7: a fresh rerun's own reason, carried as step `i0`'s
|
|
1216
|
+
// starting gap (never any later step's). `/** @type */` here (rather than
|
|
1217
|
+
// a JSDoc `@param opts.firstStepGap`, which would need a preceding typed
|
|
1218
|
+
// `@param {object} opts` this function's block comment never declared)
|
|
1219
|
+
// is what keeps every OTHER destructured field's inferred type intact.
|
|
1220
|
+
firstStepGap = /** @type {string|null} */ (null),
|
|
1221
|
+
}) {
|
|
1222
|
+
let runAcceptedThisRun = acceptedThisRun;
|
|
1223
|
+
let runUnjudged = unjudgedSinceLastAsk;
|
|
1224
|
+
|
|
1225
|
+
for (let i = i0; i < steps.length; i += 1) {
|
|
721
1226
|
const step = steps[i];
|
|
722
1227
|
|
|
723
1228
|
// --- the signed send slot: never through modelStep, only after an
|
|
724
1229
|
// accept THIS run, re-checked at write time. ---
|
|
725
1230
|
if (sendLines.has(step.fromLine)) {
|
|
726
|
-
if (!
|
|
1231
|
+
if (!runAcceptedThisRun) {
|
|
727
1232
|
return haltRun({
|
|
728
|
-
flowDir, runDir, runId, capUsd, startedAt, now, signatureHash:
|
|
1233
|
+
flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts,
|
|
729
1234
|
outcome: 'red', red: `send: step "${step.goal}" reached with no accept this run`,
|
|
730
1235
|
});
|
|
731
1236
|
}
|
|
732
1237
|
const sendSlot = sendLines.get(step.fromLine);
|
|
733
1238
|
if (!sendSlot) {
|
|
734
1239
|
return haltRun({
|
|
735
|
-
flowDir, runDir, runId, capUsd, startedAt, now, signatureHash:
|
|
1240
|
+
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}`,
|
|
736
1241
|
});
|
|
737
1242
|
}
|
|
738
1243
|
const target = `${sendSlot.target.kind}:${sendSlot.target.path}`;
|
|
739
|
-
|
|
740
|
-
|
|
1244
|
+
// The send's content is identified by IDENTITY (the artifact emitted
|
|
1245
|
+
// by the ONE earlier signed ask step this send reads) — never by
|
|
1246
|
+
// position in `reads`. `readFlow`/`validateDeclaration` already
|
|
1247
|
+
// refuse, at signing time, any declaration whose send step doesn't
|
|
1248
|
+
// read the emits of exactly one earlier signed ask (M3 item 8); every
|
|
1249
|
+
// path into this fold goes through `readFlow` first, so `askIdsInReads`
|
|
1250
|
+
// is always exactly 1 here.
|
|
1251
|
+
const [askArtifactId] = (step.reads ?? []).filter((id) => askStepEmits.has(id));
|
|
1252
|
+
if (!acceptedAskEmitsThisRun.has(askArtifactId)) {
|
|
741
1253
|
return haltRun({
|
|
742
|
-
flowDir, runDir, runId, capUsd, startedAt, now, signatureHash:
|
|
743
|
-
outcome: 'red', red: `send: step "${step.goal}"
|
|
1254
|
+
flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts,
|
|
1255
|
+
outcome: 'red', red: `send: step "${step.goal}" reads ask artifact "${askArtifactId}" that was not accepted this run`,
|
|
744
1256
|
});
|
|
745
1257
|
}
|
|
746
|
-
|
|
747
|
-
|
|
1258
|
+
// F48 round 4 (redesign): ONLY an `ok:true` read ships — a missing OR
|
|
1259
|
+
// refused (symlink swap / outside the run dir / unparseable JSON)
|
|
1260
|
+
// accepted artifact halts the run BY NAME, before `sendStep` is ever
|
|
1261
|
+
// called, so nothing reaches the signed destination. This is the exact
|
|
1262
|
+
// gap the round 3 fix left open: `readArtifact` returning `undefined`
|
|
1263
|
+
// for both shapes let a swapped/deleted artifact reach `sendStep` as
|
|
1264
|
+
// `undefined`, get `?? null`-ed by src/send.js, and ship as a
|
|
1265
|
+
// recorded-green `null` — a silent "success" for content that was
|
|
1266
|
+
// never verified.
|
|
1267
|
+
const contentResult = readArtifactResult(runDir, askArtifactId);
|
|
1268
|
+
if (!contentResult.ok) {
|
|
748
1269
|
return haltRun({
|
|
749
|
-
flowDir, runDir, runId, capUsd, startedAt, now, signatureHash:
|
|
750
|
-
outcome: 'red',
|
|
1270
|
+
flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts,
|
|
1271
|
+
outcome: 'red',
|
|
1272
|
+
red: contentResult.missing
|
|
1273
|
+
? `send: accepted artifact "${askArtifactId}" is missing for step "${step.goal}" — refusing to send`
|
|
1274
|
+
: `send: accepted artifact "${askArtifactId}" for step "${step.goal}" — ${contentResult.red}`,
|
|
751
1275
|
});
|
|
752
1276
|
}
|
|
753
|
-
const content =
|
|
1277
|
+
const content = contentResult.value;
|
|
754
1278
|
const filename = `${runId}-${step.emits}.json`;
|
|
755
1279
|
// eslint-disable-next-line no-await-in-loop
|
|
756
1280
|
const sendResult = await sendStep(target, filename, content);
|
|
757
1281
|
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,
|
|
1282
|
+
step, attempt: 1, verdict: sendResult.ok ? 'green' : 'red', gap: sendResult.ok ? null : sendResult.red, usd: 0, spendComplete: true, wallMs: 0, strike: false, at: now(),
|
|
759
1283
|
});
|
|
760
1284
|
recordAudit(sendRow);
|
|
761
1285
|
if (!sendResult.ok) {
|
|
762
1286
|
return haltRun({
|
|
763
|
-
flowDir, runDir, runId, capUsd, startedAt, now, signatureHash:
|
|
1287
|
+
flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts, outcome: 'red', red: `send: ${sendResult.red}`,
|
|
764
1288
|
});
|
|
765
1289
|
}
|
|
766
1290
|
writeArtifact(runDir, step.emits, content);
|
|
@@ -769,111 +1293,109 @@ export async function runFlow({
|
|
|
769
1293
|
continue;
|
|
770
1294
|
}
|
|
771
1295
|
|
|
772
|
-
// --- the signed ask slot: interactive, consume-once, reason-gated redo
|
|
1296
|
+
// --- the signed ask slot: interactive, consume-once, reason-gated redo,
|
|
1297
|
+
// OR park-and-exit (M3 scope item 2). ---
|
|
773
1298
|
if (askLines.has(step.fromLine)) {
|
|
774
1299
|
const askSlot = askLines.get(step.fromLine);
|
|
775
1300
|
const priorId = (step.reads ?? [])[0];
|
|
776
1301
|
const priorStepIndex = steps.findIndex((s) => s.emits === priorId);
|
|
777
|
-
|
|
778
|
-
|
|
1302
|
+
// F48 round 4: `priorId` names a STILL EARLIER step in this same fold
|
|
1303
|
+
// pass, already run and already written to disk — a `red` here is
|
|
1304
|
+
// tampering (or an outside symlink), never "not written yet", and
|
|
1305
|
+
// must halt before the human is ever shown evidence built from it.
|
|
1306
|
+
const priorArtifactResult = readArtifactResult(runDir, priorId);
|
|
1307
|
+
if (!priorArtifactResult.ok) {
|
|
1308
|
+
return haltRun({
|
|
1309
|
+
flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts,
|
|
1310
|
+
outcome: 'red',
|
|
1311
|
+
red: priorArtifactResult.missing
|
|
1312
|
+
? `ask: prior artifact "${priorId}" is missing for step "${step.goal}" — refusing`
|
|
1313
|
+
: `ask: prior artifact "${priorId}" for step "${step.goal}" — ${priorArtifactResult.red}`,
|
|
1314
|
+
});
|
|
1315
|
+
}
|
|
1316
|
+
const priorArtifact = priorArtifactResult.value;
|
|
779
1317
|
|
|
780
1318
|
// M2 amendment 1 item 2: every hitl artifact carried since the
|
|
781
1319
|
// previous ask goes to THIS ask as evidence, alongside the ask step's
|
|
782
1320
|
// own artifact — then the list resets (a fresh accumulator for the
|
|
783
1321
|
// NEXT ask), so a later ask never re-shows what an earlier one covered.
|
|
784
|
-
const evidenceUnjudged =
|
|
1322
|
+
const evidenceUnjudged = runUnjudged;
|
|
785
1323
|
const unjudgedCount = evidenceUnjudged.length;
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
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
|
-
}
|
|
1324
|
+
runUnjudged = [];
|
|
1325
|
+
|
|
1326
|
+
// eslint-disable-next-line no-await-in-loop
|
|
1327
|
+
const askResult = await runAskSlot({
|
|
1328
|
+
step,
|
|
1329
|
+
stepIndex: i,
|
|
1330
|
+
askSlot,
|
|
1331
|
+
priorId,
|
|
1332
|
+
priorStep: steps[priorStepIndex],
|
|
1333
|
+
priorArtifact,
|
|
1334
|
+
redoCap,
|
|
1335
|
+
effectiveCeilingUsd,
|
|
1336
|
+
capUsd,
|
|
1337
|
+
primitives,
|
|
1338
|
+
businessDate,
|
|
1339
|
+
modelStep,
|
|
1340
|
+
askStep,
|
|
1341
|
+
spent,
|
|
1342
|
+
spendComplete,
|
|
1343
|
+
recordAudit,
|
|
1344
|
+
evidenceUnjudged,
|
|
1345
|
+
unjudgedCount,
|
|
1346
|
+
redone: 0,
|
|
1347
|
+
runDir,
|
|
1348
|
+
flowDir,
|
|
1349
|
+
runId,
|
|
1350
|
+
flowRoot,
|
|
1351
|
+
flowName,
|
|
1352
|
+
signatureHash,
|
|
1353
|
+
inputsManifest,
|
|
1354
|
+
attemptsLog,
|
|
1355
|
+
artifacts,
|
|
1356
|
+
now,
|
|
1357
|
+
startedAt,
|
|
1358
|
+
runStartedAt,
|
|
1359
|
+
});
|
|
858
1360
|
|
|
1361
|
+
if (askResult.type === 'paused') return askResult.result;
|
|
1362
|
+
if (askResult.type === 'halted') {
|
|
859
1363
|
return haltRun({
|
|
860
|
-
flowDir, runDir, runId, capUsd, startedAt, now, signatureHash:
|
|
861
|
-
outcome: 'red', red: `ask: step "${step.goal}" got an unrecognised decision "${answer.decision}"`,
|
|
1364
|
+
flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts, outcome: askResult.outcome, red: askResult.red,
|
|
862
1365
|
});
|
|
863
1366
|
}
|
|
1367
|
+
|
|
1368
|
+
writeArtifact(runDir, step.emits, askResult.artifact);
|
|
1369
|
+
artifacts[step.emits] = askResult.artifact;
|
|
1370
|
+
runAcceptedThisRun = true;
|
|
1371
|
+
acceptedAskEmitsThisRun.add(step.emits);
|
|
864
1372
|
// eslint-disable-next-line no-continue
|
|
865
1373
|
continue;
|
|
866
1374
|
}
|
|
867
1375
|
|
|
868
1376
|
// --- an ordinary step: green / softgreen / a non-ask hitl pass-through. ---
|
|
869
|
-
|
|
1377
|
+
// F48 round 4: every id in `step.reads` names an earlier step in THIS
|
|
1378
|
+
// same fold pass, already run and already written — a `red` read here
|
|
1379
|
+
// halts rather than silently feeding tampered/unreadable content in.
|
|
1380
|
+
const readsMapResult = readArtifactsMapChecked(runDir, step.reads);
|
|
1381
|
+
if (!readsMapResult.ok) {
|
|
1382
|
+
return haltRun({
|
|
1383
|
+
flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts,
|
|
1384
|
+
outcome: 'red', red: `step "${step.goal}" ${readsMapResult.red}`,
|
|
1385
|
+
});
|
|
1386
|
+
}
|
|
1387
|
+
const readsMap = readsMapResult.map;
|
|
1388
|
+
// M3 scope item 7: a fresh rerun's own first step (and only that one —
|
|
1389
|
+
// `i === i0` is this fold's own starting point, never any later step)
|
|
1390
|
+
// starts with the human's rerun reason as its gap, exactly like a
|
|
1391
|
+
// redo's `initialGap` above.
|
|
870
1392
|
// eslint-disable-next-line no-await-in-loop
|
|
871
1393
|
const stepResult = await runStepRalph({
|
|
872
|
-
step, primitivesMap: primitives, readsMap, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit,
|
|
1394
|
+
step, primitivesMap: primitives, readsMap, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, initialGap: i === i0 ? firstStepGap : null, now,
|
|
873
1395
|
});
|
|
874
1396
|
if (!stepResult.ok) {
|
|
875
1397
|
return haltRun({
|
|
876
|
-
flowDir, runDir, runId, capUsd, startedAt, now, signatureHash:
|
|
1398
|
+
flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts, outcome: stepResult.outcome, red: stepResult.red,
|
|
877
1399
|
});
|
|
878
1400
|
}
|
|
879
1401
|
writeArtifact(runDir, step.emits, stepResult.artifact);
|
|
@@ -883,23 +1405,543 @@ export async function runFlow({
|
|
|
883
1405
|
// reached when neither askLines nor sendLines claimed the step) passes
|
|
884
1406
|
// through silently here; carry it as evidence for the NEXT signed ask.
|
|
885
1407
|
if (stepResult.hitl) {
|
|
886
|
-
|
|
1408
|
+
runUnjudged.push({ step: step.goal ?? null, emits: step.emits, artifact: stepResult.artifact });
|
|
887
1409
|
}
|
|
888
1410
|
}
|
|
889
1411
|
|
|
890
|
-
|
|
1412
|
+
// F45 finding 3: the run's history row times the whole run, from its
|
|
1413
|
+
// FIRST process's start (`runStartedAt`, never this process's own
|
|
1414
|
+
// `startedAt`) to right now. A pause counts as elapsed wall time — the
|
|
1415
|
+
// run really was sitting there waiting on a human, so it belongs in
|
|
1416
|
+
// "how long did this run take", not carved out of it.
|
|
1417
|
+
const wallMs = nowMs() - runStartedAt;
|
|
891
1418
|
appendHistory(flowDir, {
|
|
892
|
-
runId, at: now(), outcome: 'complete', spentUsd: spent.value, spendComplete:
|
|
1419
|
+
runId, at: now(), outcome: 'complete', spentUsd: spent.value, spendComplete: spendComplete.value, capUsd, wallMs, signatureHash,
|
|
893
1420
|
});
|
|
894
|
-
recordLateAnswerIfAny(runDir);
|
|
1421
|
+
recordLateAnswerIfAny(runDir, now);
|
|
895
1422
|
writeLog(runDir, {
|
|
896
1423
|
runId, outcome: 'complete', attempts: attemptsLog, artifacts,
|
|
897
1424
|
});
|
|
898
1425
|
return {
|
|
899
|
-
outcome: 'complete', runDir, artifacts, spentUsd: spent.value,
|
|
1426
|
+
outcome: 'complete', runDir, artifacts, spentUsd: spent.value,
|
|
900
1427
|
};
|
|
901
1428
|
}
|
|
902
1429
|
|
|
1430
|
+
/**
|
|
1431
|
+
* Debrief fix: sums a run's own `audit.jsonl` — the books are the source of
|
|
1432
|
+
* truth for money already spent, so `state.spent` (a value carried in a
|
|
1433
|
+
* separately-writable state.json) is cross-checked against it before a
|
|
1434
|
+
* resume trusts it under the cap. Every row's `usd` here is expected to be
|
|
1435
|
+
* a finite number (the audit rows a park can precede — attempts, the pause
|
|
1436
|
+
* itself — never carry `usd: null`; only a `cap-halt` row does, and a
|
|
1437
|
+
* cap-halt ends the run without parking, so it can never appear in a
|
|
1438
|
+
* resumable run's audit.jsonl). A row this function cannot price refuses
|
|
1439
|
+
* rather than guessing (never `?? 0`, never skipped).
|
|
1440
|
+
* @param {string} runDir
|
|
1441
|
+
* @returns {{ ok: true, total: number } | { ok: false, red: string }}
|
|
1442
|
+
*/
|
|
1443
|
+
function sumAuditUsd(runDir) {
|
|
1444
|
+
// F48 round 3: goes through `readFileInside` (`src/flow.js`) rather than a
|
|
1445
|
+
// raw `readFileSync` — a symlinked `audit.jsonl` (or a symlinked ancestor
|
|
1446
|
+
// directory) reads as "missing" (total 0), never as some outside file's
|
|
1447
|
+
// content summed into a cap check.
|
|
1448
|
+
const result = readFileInside(runDir, 'audit.jsonl');
|
|
1449
|
+
if (!result.ok) return { ok: true, total: 0 };
|
|
1450
|
+
const lines = result.text.split('\n').filter((line) => line.trim().length > 0);
|
|
1451
|
+
let total = 0;
|
|
1452
|
+
for (const line of lines) {
|
|
1453
|
+
let row;
|
|
1454
|
+
try {
|
|
1455
|
+
row = JSON.parse(line);
|
|
1456
|
+
} catch (err) {
|
|
1457
|
+
return { ok: false, red: `audit.jsonl line is not valid JSON — ${err.message}` };
|
|
1458
|
+
}
|
|
1459
|
+
if (typeof row.usd !== 'number' || !Number.isFinite(row.usd)) {
|
|
1460
|
+
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` };
|
|
1461
|
+
}
|
|
1462
|
+
total += row.usd;
|
|
1463
|
+
}
|
|
1464
|
+
return { ok: true, total };
|
|
1465
|
+
}
|
|
1466
|
+
|
|
1467
|
+
/**
|
|
1468
|
+
* M3 scope items 4-6: re-enter a parked run's SAME fold from a separate
|
|
1469
|
+
* process. Takes an exclusive `resume.lock` (refuses by name if already
|
|
1470
|
+
* held; a lock left behind by a killed resumer is a red naming it, never
|
|
1471
|
+
* stolen), re-reads the flow, refuses by name at $0 on any signature/input/
|
|
1472
|
+
* missing-artifact mismatch, consumes `answer.json` by atomic rename BEFORE
|
|
1473
|
+
* acting (F44), then either cancels an expired ask ($0, nothing sent) or
|
|
1474
|
+
* resolves it and folds on to `complete`/the next pause/a halt.
|
|
1475
|
+
*
|
|
1476
|
+
* @param {object} opts
|
|
1477
|
+
* @param {string} opts.root
|
|
1478
|
+
* @param {string} opts.name
|
|
1479
|
+
* @param {string} opts.runId
|
|
1480
|
+
* @param {unknown} opts.catalogue
|
|
1481
|
+
* @param {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class:string|null}) => Promise<any>} opts.modelStep
|
|
1482
|
+
* @param {(target:string, filename:string, content:unknown) => Promise<{ok:boolean, red?:string, bytes?:number}>} opts.sendStep
|
|
1483
|
+
* @param {Record<string, any>} [opts.primitives]
|
|
1484
|
+
* @param {string[]} [opts.primitiveReds] - see `runFlow`'s own.
|
|
1485
|
+
* @param {() => string} [opts.clock]
|
|
1486
|
+
* @param {string} opts.businessDate
|
|
1487
|
+
* @param {number} [opts.ceilingUsd]
|
|
1488
|
+
* @param {() => number} [opts.nowMs] - F45 finding 3; see `runFlow`'s own.
|
|
1489
|
+
*/
|
|
1490
|
+
export async function resumeRun({
|
|
1491
|
+
root, name, runId, catalogue, modelStep, sendStep, primitives, primitiveReds, clock, businessDate, ceilingUsd,
|
|
1492
|
+
// F45 finding 3 (see `runFlow`'s own `nowMs`): additive, defaults to the
|
|
1493
|
+
// real `Date.now` for every existing caller.
|
|
1494
|
+
nowMs,
|
|
1495
|
+
}) {
|
|
1496
|
+
const now = typeof clock === 'function' ? clock : () => new Date().toISOString();
|
|
1497
|
+
const getNowMs = typeof nowMs === 'function' ? nowMs : Date.now;
|
|
1498
|
+
const flowDir = join(root, name);
|
|
1499
|
+
const startedAt = getNowMs();
|
|
1500
|
+
|
|
1501
|
+
// Defense in depth alongside `bin/fwdloop`'s own `resolveRunDir` check on
|
|
1502
|
+
// the resume verb's runId positional — refused by name, at $0, before the
|
|
1503
|
+
// resume lock file (or anything else) is even looked at.
|
|
1504
|
+
const runIdCheck = resolveRunDir(flowDir, runId);
|
|
1505
|
+
if (!runIdCheck.ok) {
|
|
1506
|
+
return { outcome: 'refused', red: runIdCheck.red };
|
|
1507
|
+
}
|
|
1508
|
+
const runDir = runIdCheck.runDir;
|
|
1509
|
+
|
|
1510
|
+
// F46: same refusal `runFlow` carries, moved here so a resume can't spend
|
|
1511
|
+
// against a step whose granted verb has no wired implementation either —
|
|
1512
|
+
// checked before the resume lock (or anything else under `runDir`) is
|
|
1513
|
+
// touched. A separate, lightweight `readFlow` from the definitive one
|
|
1514
|
+
// below (inside the lock): if this pre-read itself fails, that failure is
|
|
1515
|
+
// reported properly by the definitive read further down, under the lock,
|
|
1516
|
+
// exactly as before this check existed.
|
|
1517
|
+
const preflightRead = readFlow({ root, name, catalogue });
|
|
1518
|
+
if (preflightRead.ok) {
|
|
1519
|
+
const unwiredVerb = findUnwiredVerbStep(preflightRead.declaration);
|
|
1520
|
+
if (unwiredVerb) {
|
|
1521
|
+
return {
|
|
1522
|
+
outcome: 'refused',
|
|
1523
|
+
red: `preflight: step "${unwiredVerb.step.emits}" (line ${unwiredVerb.step.fromLine}) grants verb "${unwiredVerb.verb}", which has no wired implementation`,
|
|
1524
|
+
};
|
|
1525
|
+
}
|
|
1526
|
+
}
|
|
1527
|
+
|
|
1528
|
+
if (primitiveReds?.length) return { outcome: 'refused', red: primitiveReds[0] };
|
|
1529
|
+
|
|
1530
|
+
const lockPath = join(runDir, 'resume.lock');
|
|
1531
|
+
|
|
1532
|
+
let lockFd;
|
|
1533
|
+
try {
|
|
1534
|
+
lockFd = openSync(lockPath, 'wx');
|
|
1535
|
+
} catch (err) {
|
|
1536
|
+
if (err.code === 'EEXIST') {
|
|
1537
|
+
return { outcome: 'refused', red: `resume: run "${runId}" is locked by another resumer (${lockPath})` };
|
|
1538
|
+
}
|
|
1539
|
+
return { outcome: 'refused', red: `resume: could not create lock ${lockPath} — ${err.message}` };
|
|
1540
|
+
}
|
|
1541
|
+
|
|
1542
|
+
try {
|
|
1543
|
+
const statePath = join(runDir, 'state.json');
|
|
1544
|
+
// F48 round 3 follow-up: goes through `readFileInside` (`src/flow.js`)
|
|
1545
|
+
// rather than a raw `readFileSync` — a symlinked state.json (or a
|
|
1546
|
+
// symlinked run dir ancestor) is refused by name here, never read
|
|
1547
|
+
// through to an outside file's content (the same class `answer.json`
|
|
1548
|
+
// and `audit.jsonl` above already close).
|
|
1549
|
+
const stateResult = readFileInside(runDir, 'state.json');
|
|
1550
|
+
if (!stateResult.ok) {
|
|
1551
|
+
if (stateResult.missing) {
|
|
1552
|
+
return { outcome: 'refused', red: `resume: no parked state for run "${runId}" (${statePath})` };
|
|
1553
|
+
}
|
|
1554
|
+
return { outcome: 'refused', red: `resume: state.json for run "${runId}" — ${stateResult.red}` };
|
|
1555
|
+
}
|
|
1556
|
+
let state;
|
|
1557
|
+
try {
|
|
1558
|
+
state = JSON.parse(stateResult.text);
|
|
1559
|
+
} catch (err) {
|
|
1560
|
+
return { outcome: 'refused', red: `resume: state.json for run "${runId}" is not valid JSON — ${err.message}` };
|
|
1561
|
+
}
|
|
1562
|
+
|
|
1563
|
+
// F45 finding 3: the run's TRUE wall-clock start, restored from the
|
|
1564
|
+
// parked state rather than this process's own `startedAt` — otherwise
|
|
1565
|
+
// every resume's history/audit `wallMs` times just that resume (F45's
|
|
1566
|
+
// observed 19ms), not the run. Falls back to this process's own start
|
|
1567
|
+
// for a run parked BEFORE this fix (no `state.startedAt` on disk) —
|
|
1568
|
+
// not a money field, so a best-known fallback rather than a refusal.
|
|
1569
|
+
const runStartedAt = typeof state.startedAt === 'number' ? state.startedAt : startedAt;
|
|
1570
|
+
|
|
1571
|
+
// Orchestrator review fix (6): the CALLER's `root`/`name` are the source
|
|
1572
|
+
// of truth — never `state.flow.root`/`state.flow.name` silently. A
|
|
1573
|
+
// parked run whose recorded flow location disagrees with what THIS call
|
|
1574
|
+
// was asked to resume is refused by name, never re-read from wherever
|
|
1575
|
+
// the state file happens to point.
|
|
1576
|
+
if (state.flow?.root !== root || state.flow?.name !== name) {
|
|
1577
|
+
return {
|
|
1578
|
+
outcome: 'refused',
|
|
1579
|
+
red: `resume: run "${runId}" was parked against flow "${state.flow?.root}/${state.flow?.name}", `
|
|
1580
|
+
+ `not the requested "${root}/${name}" — refusing rather than reading a different flow than asked`,
|
|
1581
|
+
};
|
|
1582
|
+
}
|
|
1583
|
+
|
|
1584
|
+
const read = readFlow({ root, name, catalogue });
|
|
1585
|
+
if (!read.ok) {
|
|
1586
|
+
return { outcome: 'refused', red: `resume: flow re-read failed for run "${runId}": ${read.reds.join('; ')}` };
|
|
1587
|
+
}
|
|
1588
|
+
const { declaration, arbiter, signature } = read;
|
|
1589
|
+
|
|
1590
|
+
if (signature.flow !== state.signatureHash) {
|
|
1591
|
+
return { outcome: 'refused', red: `resume: signature mismatch for run "${runId}" — the flow changed while parked` };
|
|
1592
|
+
}
|
|
1593
|
+
|
|
1594
|
+
for (const entry of state.inputsManifest ?? []) {
|
|
1595
|
+
if (!existsSync(entry.frozen)) {
|
|
1596
|
+
return { outcome: 'refused', red: `resume: frozen input "${entry.id}" missing for run "${runId}" (${entry.frozen})` };
|
|
1597
|
+
}
|
|
1598
|
+
const sha256 = createHash('sha256').update(readFileSync(entry.frozen)).digest('hex');
|
|
1599
|
+
if (sha256 !== entry.sha256) {
|
|
1600
|
+
return { outcome: 'refused', red: `resume: frozen input "${entry.id}" changed while parked for run "${runId}"` };
|
|
1601
|
+
}
|
|
1602
|
+
}
|
|
1603
|
+
|
|
1604
|
+
// F48 round 4 (redesign): the "was this step already done" gate — the
|
|
1605
|
+
// one place a resume decides whether an earlier step's artifact is
|
|
1606
|
+
// trustworthy BEFORE the answer is consumed or anything downstream reads
|
|
1607
|
+
// it again (site 6/7/8 below all read the SAME ids, for i < stepIndex,
|
|
1608
|
+
// and rely on this gate having already refused any red for them). A
|
|
1609
|
+
// `red` (symlink swap / unparseable JSON) is refused BY NAME, exactly
|
|
1610
|
+
// like `missing` — never silently treated as "not done yet" and redone,
|
|
1611
|
+
// which could spend money or re-ask a human for a step that already
|
|
1612
|
+
// completed.
|
|
1613
|
+
const { steps } = declaration;
|
|
1614
|
+
for (let i = 0; i < state.stepIndex; i += 1) {
|
|
1615
|
+
const artifactResult = readArtifactResult(runDir, steps[i].emits);
|
|
1616
|
+
if (!artifactResult.ok) {
|
|
1617
|
+
return {
|
|
1618
|
+
outcome: 'refused',
|
|
1619
|
+
red: artifactResult.missing
|
|
1620
|
+
? `resume: artifact "${steps[i].emits}" missing for run "${runId}" — cannot resume`
|
|
1621
|
+
: `resume: artifact "${steps[i].emits}" for run "${runId}" — ${artifactResult.red} — `
|
|
1622
|
+
+ 'refusing rather than treating a refused read as "not done" and re-running it',
|
|
1623
|
+
};
|
|
1624
|
+
}
|
|
1625
|
+
}
|
|
1626
|
+
|
|
1627
|
+
// Orchestrator review fix (1): unknown cost is never rendered as 0 — a
|
|
1628
|
+
// missing/non-number/non-finite `state.spent` refuses the resume by
|
|
1629
|
+
// name (naming the run AND the field), $0 further spend, rather than
|
|
1630
|
+
// silently treating an unreadable ledger as "nothing spent yet". Checked
|
|
1631
|
+
// BEFORE the answer is consumed — a refusal here must be replayable.
|
|
1632
|
+
if (typeof state.spent !== 'number' || !Number.isFinite(state.spent)) {
|
|
1633
|
+
return {
|
|
1634
|
+
outcome: 'refused',
|
|
1635
|
+
red: `resume: run "${runId}" state.json field "spent" is not a finite number (got ${JSON.stringify(state.spent)}) — `
|
|
1636
|
+
+ 'unknown cost is never rendered as 0; refusing further spend',
|
|
1637
|
+
};
|
|
1638
|
+
}
|
|
1639
|
+
// Debrief fix: a negative spend is an impossible cost, never a number
|
|
1640
|
+
// the cap can trust — refused the same way as a non-finite one.
|
|
1641
|
+
if (state.spent < 0) {
|
|
1642
|
+
return {
|
|
1643
|
+
outcome: 'refused',
|
|
1644
|
+
red: `resume: run "${runId}" state.json field "spent" is negative (${state.spent}) — `
|
|
1645
|
+
+ 'an impossible cost is never trusted by the cap; refusing further spend',
|
|
1646
|
+
};
|
|
1647
|
+
}
|
|
1648
|
+
// Debrief fix: the run's own audit.jsonl is the books' source of truth
|
|
1649
|
+
// for money already spent — if state.spent claims LESS than what the
|
|
1650
|
+
// audit already recorded, state.spent is wrong (or tampered) and must
|
|
1651
|
+
// never be trusted to gate further spend under the cap.
|
|
1652
|
+
const auditSum = sumAuditUsd(runDir);
|
|
1653
|
+
if (!auditSum.ok) {
|
|
1654
|
+
return { outcome: 'refused', red: `resume: run "${runId}" ${auditSum.red}` };
|
|
1655
|
+
}
|
|
1656
|
+
if (auditSum.total - state.spent > SPEND_TOLERANCE_USD) {
|
|
1657
|
+
return {
|
|
1658
|
+
outcome: 'refused',
|
|
1659
|
+
red: `resume: run "${runId}" state.json field "spent" ($${state.spent}) is less than its own audit.jsonl sum ($${auditSum.total}) — `
|
|
1660
|
+
+ "the books are the source of truth for money already spent; refusing rather than trusting state.json's lower figure",
|
|
1661
|
+
};
|
|
1662
|
+
}
|
|
1663
|
+
const spent = { value: state.spent };
|
|
1664
|
+
// Orchestrator review fix (4): a floor persisted across the pause
|
|
1665
|
+
// (`state.spendComplete`) is restored here, never quietly reset to
|
|
1666
|
+
// `true` — an absent/non-boolean value defaults to `false` (unknown
|
|
1667
|
+
// never renders as "complete"), never `true`.
|
|
1668
|
+
const spendComplete = { value: state.spendComplete === true };
|
|
1669
|
+
|
|
1670
|
+
// A present-but-unparseable `state.expiresAt` (Date.parse -> NaN) must
|
|
1671
|
+
// never read as "not expired" — `NaN > x`/`x > NaN` are both false, so
|
|
1672
|
+
// the real expiry compare below would silently treat garbage as open
|
|
1673
|
+
// forever. Refused here, naming the run, BEFORE the answer is consumed
|
|
1674
|
+
// (same "checked before consuming" rule as the spent check above — a
|
|
1675
|
+
// refusal here must be replayable).
|
|
1676
|
+
if (Number.isNaN(Date.parse(state.expiresAt))) {
|
|
1677
|
+
return {
|
|
1678
|
+
outcome: 'refused',
|
|
1679
|
+
red: `resume: run "${runId}" state.json field "expiresAt" ("${state.expiresAt}") is not a parseable date — `
|
|
1680
|
+
+ 'refusing rather than treating it as not-expired',
|
|
1681
|
+
};
|
|
1682
|
+
}
|
|
1683
|
+
|
|
1684
|
+
const answerPath = join(runDir, 'answer.json');
|
|
1685
|
+
// F48 round 3: `answer.json` goes through `resolveInside` too — a
|
|
1686
|
+
// symlinked answer file (or a symlinked run dir ancestor) is refused by
|
|
1687
|
+
// name here, the same as "no answer yet", never read through to an
|
|
1688
|
+
// outside file's content.
|
|
1689
|
+
const answerResolved = resolveInside(runDir, 'answer.json');
|
|
1690
|
+
if (!answerResolved.ok) {
|
|
1691
|
+
if (answerResolved.missing) {
|
|
1692
|
+
return { outcome: 'refused', red: `resume: no answer yet for run "${runId}"` };
|
|
1693
|
+
}
|
|
1694
|
+
return { outcome: 'refused', red: `resume: answer.json for run "${runId}" — ${answerResolved.red}` };
|
|
1695
|
+
}
|
|
1696
|
+
let answer;
|
|
1697
|
+
try {
|
|
1698
|
+
answer = JSON.parse(readFileSync(answerPath, 'utf8'));
|
|
1699
|
+
} catch (err) {
|
|
1700
|
+
return { outcome: 'refused', red: `resume: answer.json for run "${runId}" is not valid JSON — ${err.message}` };
|
|
1701
|
+
}
|
|
1702
|
+
if (answer.askId !== state.askId) {
|
|
1703
|
+
return { outcome: 'refused', red: `resume: answer askId "${answer.askId}" does not match open askId "${state.askId}" for run "${runId}"` };
|
|
1704
|
+
}
|
|
1705
|
+
|
|
1706
|
+
// Consume-once, BEFORE acting on the decision (F44) — the rename is
|
|
1707
|
+
// itself a one-winner gate, on top of the lock above.
|
|
1708
|
+
const consumedPath = join(runDir, `answer.${answer.askId}.consumed.json`);
|
|
1709
|
+
renameSync(answerPath, consumedPath);
|
|
1710
|
+
|
|
1711
|
+
// The run's own injected clock governs expiry, exactly like every other
|
|
1712
|
+
// "now" in this module (never the bare wall clock) — the same fixed
|
|
1713
|
+
// clock a test controls for `runFlow` also controls what "expired" means
|
|
1714
|
+
// for `resumeRun`, with no real wait required to prove it.
|
|
1715
|
+
if (Date.parse(now()) > Date.parse(state.expiresAt)) {
|
|
1716
|
+
// Negative (i): an answer arriving after expiry cancels the run —
|
|
1717
|
+
// adds NOTHING further, but the run's own already-spent total is
|
|
1718
|
+
// real money and must be reported, never coerced to 0 (orchestrator
|
|
1719
|
+
// review fix 2: "a pause spends nothing" means the pause adds
|
|
1720
|
+
// nothing, not that the run's total resets).
|
|
1721
|
+
appendAudit(runDir, {
|
|
1722
|
+
step: null, attempt: null, class: null, verdict: 'ask-expired', gap: null, usd: 0, spendComplete: true, wallMs: 0, model: null, modelMatch: null, strike: false, at: now(), tokens: null, tools: null,
|
|
1723
|
+
});
|
|
1724
|
+
appendHistory(flowDir, {
|
|
1725
|
+
runId, at: now(), outcome: 'ask-expired', spentUsd: spent.value, spendComplete: spendComplete.value, capUsd: arbiter.capUsd ?? null, wallMs: getNowMs() - runStartedAt, signatureHash: state.signatureHash,
|
|
1726
|
+
});
|
|
1727
|
+
return { outcome: 'ask-expired', runDir, spentUsd: spent.value };
|
|
1728
|
+
}
|
|
1729
|
+
|
|
1730
|
+
if (answer.decision === 'rerun') {
|
|
1731
|
+
// M3 scope item 7 (hamr "2A"): `rerun` ends THIS run (one history row,
|
|
1732
|
+
// `rerun`, its real spend, $0 added) and starts a brand-new run on the
|
|
1733
|
+
// same signed flow — never a redo of the step before the ask.
|
|
1734
|
+
const reason = typeof answer.reason === 'string' ? answer.reason.trim() : '';
|
|
1735
|
+
if (reason.length === 0) {
|
|
1736
|
+
// `answerAsk` already refuses a blank reason at write time — this
|
|
1737
|
+
// re-check exists because `resumeRun` never trusts a file it did
|
|
1738
|
+
// not itself just validate, same as every other field read above.
|
|
1739
|
+
return { outcome: 'refused', red: `resume: rerun answer for run "${runId}" carries a blank reason` };
|
|
1740
|
+
}
|
|
1741
|
+
|
|
1742
|
+
// Safe to collapse missing/red to `readArtifact`'s `undefined` here:
|
|
1743
|
+
// the "was this step already done" gate above already refused the
|
|
1744
|
+
// whole resume (before the answer was even consumed) if any
|
|
1745
|
+
// `steps[i].emits` for i < state.stepIndex was red — this loop only
|
|
1746
|
+
// ever runs once every one of those same ids has already read `ok`.
|
|
1747
|
+
const priorArtifactsForLog = {};
|
|
1748
|
+
for (let i = 0; i < state.stepIndex; i += 1) {
|
|
1749
|
+
priorArtifactsForLog[steps[i].emits] = readArtifact(runDir, steps[i].emits);
|
|
1750
|
+
}
|
|
1751
|
+
appendHistory(flowDir, {
|
|
1752
|
+
runId, at: now(), outcome: 'rerun', spentUsd: spent.value, spendComplete: spendComplete.value, capUsd: arbiter.capUsd ?? null, wallMs: getNowMs() - runStartedAt, signatureHash: state.signatureHash,
|
|
1753
|
+
});
|
|
1754
|
+
recordLateAnswerIfAny(runDir, now);
|
|
1755
|
+
writeLog(runDir, { runId, outcome: 'rerun', attempts: [], artifacts: priorArtifactsForLog });
|
|
1756
|
+
|
|
1757
|
+
// Deterministic derived id (M3 scope item 7) — refused by name, never
|
|
1758
|
+
// silently renumbered, if it already exists.
|
|
1759
|
+
const newRunId = `${runId}-rerun-1`;
|
|
1760
|
+
const newRunDir = join(flowDir, 'runs', newRunId);
|
|
1761
|
+
if (existsSync(newRunDir)) {
|
|
1762
|
+
return {
|
|
1763
|
+
outcome: 'refused',
|
|
1764
|
+
red: `resume: rerun target run "${newRunId}" already exists for run "${runId}" — refused`,
|
|
1765
|
+
};
|
|
1766
|
+
}
|
|
1767
|
+
|
|
1768
|
+
// Fresh inputs, re-frozen from the ORIGINAL source paths — carried in
|
|
1769
|
+
// `inputsManifest[].source` since `freezeInputs` first wrote it (M3
|
|
1770
|
+
// scope item 7's own note: "persist those in state.json at park if
|
|
1771
|
+
// they aren't already" — they already are, via this field).
|
|
1772
|
+
const rerunSources = (state.inputsManifest ?? []).map((entry) => ({ id: entry.id, path: entry.source }));
|
|
1773
|
+
|
|
1774
|
+
const newRun = await runFlow({
|
|
1775
|
+
root,
|
|
1776
|
+
name,
|
|
1777
|
+
runId: newRunId,
|
|
1778
|
+
sources: rerunSources,
|
|
1779
|
+
catalogue,
|
|
1780
|
+
modelStep,
|
|
1781
|
+
// A fresh run never waits in-process — any signed ask it reaches
|
|
1782
|
+
// parks immediately, exactly like any other `runFlow` call this
|
|
1783
|
+
// piece drives.
|
|
1784
|
+
askStep: makeParkingAskStep(),
|
|
1785
|
+
sendStep,
|
|
1786
|
+
primitives,
|
|
1787
|
+
clock,
|
|
1788
|
+
businessDate,
|
|
1789
|
+
ceilingUsd,
|
|
1790
|
+
// Item 7: the reason becomes the new run's FIRST step's starting gap.
|
|
1791
|
+
initialGap: reason,
|
|
1792
|
+
});
|
|
1793
|
+
|
|
1794
|
+
return {
|
|
1795
|
+
outcome: 'rerun', runDir, runId, newRunId, spentUsd: spent.value, newRun,
|
|
1796
|
+
};
|
|
1797
|
+
}
|
|
1798
|
+
|
|
1799
|
+
if (answer.decision !== 'accept' && answer.decision !== 'reject') {
|
|
1800
|
+
return { outcome: 'refused', red: `resume: unrecognised decision "${answer.decision}" for run "${runId}"` };
|
|
1801
|
+
}
|
|
1802
|
+
|
|
1803
|
+
// Reconstruct the fold's accumulators from disk + state.json — never
|
|
1804
|
+
// re-running a step that already went green (M3 scope item 4). Every
|
|
1805
|
+
// `readArtifact` call below reads an id already proven `ok` by the "was
|
|
1806
|
+
// this step already done" gate above (i < state.stepIndex, same ids) —
|
|
1807
|
+
// safe to collapse missing/red to `undefined` here for that reason only.
|
|
1808
|
+
const artifacts = {};
|
|
1809
|
+
for (let i = 0; i < state.stepIndex; i += 1) {
|
|
1810
|
+
artifacts[steps[i].emits] = readArtifact(runDir, steps[i].emits);
|
|
1811
|
+
}
|
|
1812
|
+
const askLines = new Map((arbiter.asks ?? []).map((a) => [a.line, a]));
|
|
1813
|
+
const sendLines = new Map((arbiter.sends ?? []).map((s) => [s.line, s]));
|
|
1814
|
+
const askStepEmits = new Set(steps.filter((s) => askLines.has(s.fromLine)).map((s) => s.emits));
|
|
1815
|
+
const acceptedAskEmitsThisRun = new Set();
|
|
1816
|
+
for (const emits of askStepEmits) {
|
|
1817
|
+
const idx = steps.findIndex((s) => s.emits === emits);
|
|
1818
|
+
if (idx !== -1 && idx < state.stepIndex && readArtifact(runDir, emits) !== undefined) {
|
|
1819
|
+
acceptedAskEmitsThisRun.add(emits);
|
|
1820
|
+
}
|
|
1821
|
+
}
|
|
1822
|
+
|
|
1823
|
+
const attemptsLog = [];
|
|
1824
|
+
const auditRows = [];
|
|
1825
|
+
const recordAudit = (row, modelOutput, unjudgedCount) => {
|
|
1826
|
+
const fullRow = unjudgedCount === undefined ? row : { ...row, unjudgedCount };
|
|
1827
|
+
auditRows.push(fullRow);
|
|
1828
|
+
appendAudit(runDir, fullRow);
|
|
1829
|
+
if (row.spendComplete === false) spendComplete.value = false;
|
|
1830
|
+
if (modelOutput !== undefined) {
|
|
1831
|
+
attemptsLog.push({
|
|
1832
|
+
step: row.step, attempt: row.attempt, class: row.class, verdict: row.verdict, gap: row.gap, ...(row.refused ? { refused: row.refused } : {}), modelOutput,
|
|
1833
|
+
});
|
|
1834
|
+
}
|
|
1835
|
+
};
|
|
1836
|
+
|
|
1837
|
+
const capUsd = arbiter.capUsd;
|
|
1838
|
+
const redoCap = arbiter.redoCap ?? 3;
|
|
1839
|
+
const effectiveCeilingUsd = ceilingUsd ?? resolveCeilingUsd(null);
|
|
1840
|
+
|
|
1841
|
+
const step = steps[state.stepIndex];
|
|
1842
|
+
const askSlot = askLines.get(step.fromLine);
|
|
1843
|
+
const priorId = (step.reads ?? [])[0];
|
|
1844
|
+
const priorStepIndex = steps.findIndex((s) => s.emits === priorId);
|
|
1845
|
+
// `priorId` names a step strictly earlier than the parked ask
|
|
1846
|
+
// (state.stepIndex), so i < state.stepIndex — already proven `ok` by the
|
|
1847
|
+
// "was this step already done" gate above; safe to collapse here.
|
|
1848
|
+
const priorArtifact = readArtifact(runDir, priorId);
|
|
1849
|
+
|
|
1850
|
+
const oneShotAskStep = makeOneShotThenParkAskStep({ decision: answer.decision, reason: answer.reason });
|
|
1851
|
+
|
|
1852
|
+
const askResult = await runAskSlot({
|
|
1853
|
+
step,
|
|
1854
|
+
stepIndex: state.stepIndex,
|
|
1855
|
+
askSlot,
|
|
1856
|
+
priorId,
|
|
1857
|
+
priorStep: steps[priorStepIndex],
|
|
1858
|
+
priorArtifact,
|
|
1859
|
+
redoCap,
|
|
1860
|
+
effectiveCeilingUsd,
|
|
1861
|
+
capUsd,
|
|
1862
|
+
primitives,
|
|
1863
|
+
businessDate,
|
|
1864
|
+
modelStep,
|
|
1865
|
+
askStep: oneShotAskStep,
|
|
1866
|
+
spent,
|
|
1867
|
+
spendComplete,
|
|
1868
|
+
recordAudit,
|
|
1869
|
+
evidenceUnjudged: state.evidenceUnjudged ?? [],
|
|
1870
|
+
unjudgedCount: state.unjudgedCount ?? 0,
|
|
1871
|
+
redone: typeof state.redone === 'number' ? state.redone : 0,
|
|
1872
|
+
runDir,
|
|
1873
|
+
flowDir,
|
|
1874
|
+
runId,
|
|
1875
|
+
flowRoot: root,
|
|
1876
|
+
flowName: name,
|
|
1877
|
+
signatureHash: state.signatureHash,
|
|
1878
|
+
inputsManifest: state.inputsManifest,
|
|
1879
|
+
attemptsLog,
|
|
1880
|
+
artifacts,
|
|
1881
|
+
now,
|
|
1882
|
+
startedAt,
|
|
1883
|
+
runStartedAt,
|
|
1884
|
+
});
|
|
1885
|
+
|
|
1886
|
+
if (askResult.type === 'paused') return askResult.result;
|
|
1887
|
+
if (askResult.type === 'halted') {
|
|
1888
|
+
return haltRun({
|
|
1889
|
+
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,
|
|
1890
|
+
});
|
|
1891
|
+
}
|
|
1892
|
+
|
|
1893
|
+
// accepted — write the ask step's own artifact, then fold on to
|
|
1894
|
+
// whatever comes next (another signed ask parks again; the ordinary
|
|
1895
|
+
// send/step path completes exactly as `runFlow` would have, in-process).
|
|
1896
|
+
writeArtifact(runDir, step.emits, askResult.artifact);
|
|
1897
|
+
artifacts[step.emits] = askResult.artifact;
|
|
1898
|
+
acceptedAskEmitsThisRun.add(step.emits);
|
|
1899
|
+
|
|
1900
|
+
const result = await foldFromStep({
|
|
1901
|
+
i0: state.stepIndex + 1,
|
|
1902
|
+
steps,
|
|
1903
|
+
askLines,
|
|
1904
|
+
sendLines,
|
|
1905
|
+
askStepEmits,
|
|
1906
|
+
runDir,
|
|
1907
|
+
flowDir,
|
|
1908
|
+
runId,
|
|
1909
|
+
flowRoot: root,
|
|
1910
|
+
flowName: name,
|
|
1911
|
+
signatureHash: state.signatureHash,
|
|
1912
|
+
inputsManifest: state.inputsManifest,
|
|
1913
|
+
capUsd,
|
|
1914
|
+
redoCap,
|
|
1915
|
+
effectiveCeilingUsd,
|
|
1916
|
+
primitives,
|
|
1917
|
+
businessDate,
|
|
1918
|
+
modelStep,
|
|
1919
|
+
// A resumed run never waits in-process — any FURTHER signed ask it
|
|
1920
|
+
// reaches parks immediately too, under its own signed ttl.
|
|
1921
|
+
askStep: makeParkingAskStep(),
|
|
1922
|
+
sendStep,
|
|
1923
|
+
now,
|
|
1924
|
+
startedAt,
|
|
1925
|
+
runStartedAt,
|
|
1926
|
+
nowMs: getNowMs,
|
|
1927
|
+
spent,
|
|
1928
|
+
spendComplete,
|
|
1929
|
+
artifacts,
|
|
1930
|
+
acceptedThisRun: true,
|
|
1931
|
+
acceptedAskEmitsThisRun,
|
|
1932
|
+
unjudgedSinceLastAsk: [],
|
|
1933
|
+
recordAudit,
|
|
1934
|
+
attemptsLog,
|
|
1935
|
+
});
|
|
1936
|
+
|
|
1937
|
+
if (result.outcome === 'complete') return { ...result, auditRows };
|
|
1938
|
+
return result;
|
|
1939
|
+
} finally {
|
|
1940
|
+
try { closeSync(lockFd); } catch { /* already closed */ }
|
|
1941
|
+
try { unlinkSync(lockPath); } catch { /* already gone */ }
|
|
1942
|
+
}
|
|
1943
|
+
}
|
|
1944
|
+
|
|
903
1945
|
/** log.json's one writer, called from every exit path (complete + every
|
|
904
1946
|
* halt) — M2 scope item 9 / the M0 ruling: what the model wrote, every
|
|
905
1947
|
* attempt, red runs included, never just the final artifacts. */
|
|
@@ -907,6 +1949,47 @@ function writeLog(runDir, payload) {
|
|
|
907
1949
|
writeFileSync(join(runDir, 'log.json'), JSON.stringify(payload, null, 2));
|
|
908
1950
|
}
|
|
909
1951
|
|
|
1952
|
+
/**
|
|
1953
|
+
* `writeLog`'s own sibling reader (M4a piece 2, docs/wiki/the-module-
|
|
1954
|
+
* ladder.md M4a scope item 2: "one reader per book") — `null` when the run
|
|
1955
|
+
* hasn't reached an exit path yet (still running, or parked before any
|
|
1956
|
+
* halt/complete), or the file is present but not valid JSON (a torn write),
|
|
1957
|
+
* never a thrown error.
|
|
1958
|
+
* @param {string} runDir
|
|
1959
|
+
* @returns {any|null}
|
|
1960
|
+
*/
|
|
1961
|
+
export function readLog(runDir) {
|
|
1962
|
+
const result = readFileInside(runDir, 'log.json');
|
|
1963
|
+
if (!result.ok) return null;
|
|
1964
|
+
try { return JSON.parse(result.text); } catch { return null; }
|
|
1965
|
+
}
|
|
1966
|
+
|
|
1967
|
+
/**
|
|
1968
|
+
* `state.json`'s own sibling reader (same rule as {@link readLog}) — `null`
|
|
1969
|
+
* when the run has never parked, or the file is present but not valid JSON.
|
|
1970
|
+
* @param {string} runDir
|
|
1971
|
+
* @returns {any|null}
|
|
1972
|
+
*/
|
|
1973
|
+
export function readRunState(runDir) {
|
|
1974
|
+
const result = readFileInside(runDir, 'state.json');
|
|
1975
|
+
if (!result.ok) return null;
|
|
1976
|
+
try { return JSON.parse(result.text); } catch { return null; }
|
|
1977
|
+
}
|
|
1978
|
+
|
|
1979
|
+
/**
|
|
1980
|
+
* `ask.json`'s own sibling reader (same rule as {@link readLog}) — the
|
|
1981
|
+
* parking ask protocol's own writer lives in {@link runAskSlot} above.
|
|
1982
|
+
* `null` when there is no open ask for this run, or the file is present but
|
|
1983
|
+
* not valid JSON.
|
|
1984
|
+
* @param {string} runDir
|
|
1985
|
+
* @returns {any|null}
|
|
1986
|
+
*/
|
|
1987
|
+
export function readAsk(runDir) {
|
|
1988
|
+
const result = readFileInside(runDir, 'ask.json');
|
|
1989
|
+
if (!result.ok) return null;
|
|
1990
|
+
try { return JSON.parse(result.text); } catch { return null; }
|
|
1991
|
+
}
|
|
1992
|
+
|
|
910
1993
|
/**
|
|
911
1994
|
* @param {object} opts
|
|
912
1995
|
* @param {string} opts.flowDir
|
|
@@ -915,6 +1998,7 @@ function writeLog(runDir, payload) {
|
|
|
915
1998
|
* @param {number|null} opts.capUsd
|
|
916
1999
|
* @param {number} opts.startedAt
|
|
917
2000
|
* @param {() => string} opts.now
|
|
2001
|
+
* @param {() => number} [opts.nowMs] - F45 finding 3; defaults to `Date.now`.
|
|
918
2002
|
* @param {string} opts.outcome
|
|
919
2003
|
* @param {string} [opts.red]
|
|
920
2004
|
* @param {{ value: number }} opts.spent
|
|
@@ -925,18 +2009,28 @@ function writeLog(runDir, payload) {
|
|
|
925
2009
|
* history row carries it, halts included). A halt before the signature was
|
|
926
2010
|
* read/verified (the pre-`readFlow`-success refused path, and any halt
|
|
927
2011
|
* before `signature` comes into scope) keeps the default `null`.
|
|
2012
|
+
* @param {boolean} [opts.priorSpendComplete] - orchestrator review fix (4):
|
|
2013
|
+
* a floor carried in from BEFORE this halt (e.g. a pre-park row, or an
|
|
2014
|
+
* earlier attempt this run, that already left `spendComplete: false`).
|
|
2015
|
+
* ANDed with this halt's own outcome-based verdict — once false, always
|
|
2016
|
+
* false. Defaults to `true` (every pre-existing call site is unaffected).
|
|
928
2017
|
*/
|
|
929
2018
|
function haltRun({
|
|
930
|
-
flowDir, runDir, runId, capUsd, startedAt, now, outcome, red, spent, attempts = [], artifacts = {}, signatureHash = null,
|
|
2019
|
+
flowDir, runDir, runId, capUsd, startedAt, now, nowMs = Date.now, outcome, red, spent, attempts = [], artifacts = {}, signatureHash = null,
|
|
2020
|
+
priorSpendComplete = true,
|
|
931
2021
|
}) {
|
|
932
|
-
|
|
933
|
-
|
|
2022
|
+
// F45 finding 3: `startedAt` here is always the RUN's start (every caller
|
|
2023
|
+
// now passes `runStartedAt` under this key — see call sites), so `wallMs`
|
|
2024
|
+
// times the whole run, pauses included, never just the halting process.
|
|
2025
|
+
const wallMs = nowMs() - startedAt;
|
|
2026
|
+
const spendComplete = priorSpendComplete
|
|
2027
|
+
&& outcome !== 'provider-red' && outcome !== 'pricing-red' && outcome !== 'cap-halt';
|
|
934
2028
|
mkdirSync(flowDir, { recursive: true });
|
|
935
2029
|
appendHistory(flowDir, {
|
|
936
2030
|
runId, at: now(), outcome, spentUsd: spent.value, spendComplete, capUsd: capUsd ?? null, wallMs, signatureHash,
|
|
937
2031
|
});
|
|
938
2032
|
if (existsSync(runDir)) {
|
|
939
|
-
recordLateAnswerIfAny(runDir);
|
|
2033
|
+
recordLateAnswerIfAny(runDir, now);
|
|
940
2034
|
writeLog(runDir, {
|
|
941
2035
|
runId, outcome, red, attempts, artifacts,
|
|
942
2036
|
});
|