fwdloop 0.5.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/fwdloop +480 -0
- package/package.json +5 -1
- package/src/ask.js +104 -5
- package/src/declaration.js +12 -1
- package/src/index.js +2 -1
- package/src/model-step.js +2 -2
- package/src/runner.js +865 -110
- package/types/ask.d.ts +18 -1
- package/types/index.d.ts +2 -1
- package/types/runner.d.ts +71 -23
package/src/runner.js
CHANGED
|
@@ -36,10 +36,10 @@
|
|
|
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';
|
|
@@ -60,6 +60,16 @@ export const STRIKE_LIMIT = 2;
|
|
|
60
60
|
* fallback, never the governor" — it never raises the strike bound, it only
|
|
61
61
|
* bounds the case the strike governor doesn't catch). */
|
|
62
62
|
export const MAX_ATTEMPTS = 4;
|
|
63
|
+
/** Debrief round 2: `state.spent` (accumulated by repeated `spent.value +=`
|
|
64
|
+
* during the run) and `sumAuditUsd`'s re-summed total are two independent
|
|
65
|
+
* float summations of the same rows in a different order — IEEE 754
|
|
66
|
+
* addition is not associative, so they can differ by a single ULP (e.g.
|
|
67
|
+
* 0.006874 vs 0.006874000000000001) with no real discrepancy. The books
|
|
68
|
+
* (audit.jsonl) stay the source of truth; this tolerance only absorbs
|
|
69
|
+
* summation-order noise, not a real gap. A billionth of a dollar is ~6
|
|
70
|
+
* orders of magnitude below the cheapest real round (audit rows here run
|
|
71
|
+
* $0.0006+), so nothing a real tamper produces can hide inside it. */
|
|
72
|
+
export const SPEND_TOLERANCE_USD = 1e-9;
|
|
63
73
|
|
|
64
74
|
// ---------------------------------------------------------------------------
|
|
65
75
|
// Money — piece 2 wires live provider rates; this piece takes a per-attempt
|
|
@@ -625,19 +635,33 @@ async function runStepRalph({
|
|
|
625
635
|
* @param {Array<{id:string, path:string}>} opts.sources - the real files to freeze for this run.
|
|
626
636
|
* @param {unknown} opts.catalogue - passed straight through to `readFlow`.
|
|
627
637
|
* @param {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class:string|null}) => Promise<{ok:boolean, artifact?:unknown, costUsd:number|null, red?:string, transport?:boolean, model?:string, modelMatch?:boolean}>} opts.modelStep
|
|
628
|
-
* @param {(opts:{question:string, evidence:unknown, runDir:string}) => Promise<{decision:'accept'|'reject'|'rerun'|'timeout', reason?:string}>} opts.askStep
|
|
638
|
+
* @param {(opts:{question:string, evidence:unknown, runDir:string}) => Promise<{decision:'accept'|'reject'|'rerun'|'timeout'|'park', reason?:string}>} opts.askStep
|
|
629
639
|
* @param {(target:string, filename:string, content:unknown) => Promise<{ok:boolean, red?:string, bytes?:number}>} opts.sendStep
|
|
630
640
|
* @param {Record<string, any>} [opts.primitives] - injected primitive implementations, keyed by catalogue verb.
|
|
631
641
|
* @param {() => string} [opts.clock] - returns the current ISO timestamp; defaults to the wall clock.
|
|
632
642
|
* @param {string} opts.businessDate - the run's explicit "as of today", never the wall clock.
|
|
633
643
|
* @param {number} [opts.ceilingUsd] - per-attempt ceiling override; defaults to `resolveCeilingUsd(null)`.
|
|
644
|
+
* @param {string|null} [opts.initialGap] - M3 scope item 7 (rerun as a fresh
|
|
645
|
+
* run): a human's rerun reason, carried as the FIRST ordinary step's
|
|
646
|
+
* starting gap. Never used by a plain `runFlow` call outside `resumeRun`'s
|
|
647
|
+
* own rerun path.
|
|
648
|
+
* @param {() => number} [opts.nowMs] - F45 finding 3: returns the current
|
|
649
|
+
* epoch ms; defaults to the wall clock. Mirrors `clock` (ISO) so a test
|
|
650
|
+
* can advance wall time across a park/resume boundary without a real wait.
|
|
634
651
|
*/
|
|
635
652
|
export async function runFlow({
|
|
636
|
-
root, name, runId, sources, catalogue, modelStep, askStep, sendStep, primitives, clock, businessDate, ceilingUsd,
|
|
653
|
+
root, name, runId, sources, catalogue, modelStep, askStep, sendStep, primitives, clock, businessDate, ceilingUsd, initialGap,
|
|
654
|
+
// F45 finding 3's test needs to advance wall time across a park/resume
|
|
655
|
+
// boundary without a real wait, exactly like `clock` already does for ISO
|
|
656
|
+
// timestamps — `nowMs` is the same idea for epoch-ms wall-clock reads.
|
|
657
|
+
// Minimal and additive: every existing caller (no `nowMs`) gets the real
|
|
658
|
+
// `Date.now`, unchanged.
|
|
659
|
+
nowMs,
|
|
637
660
|
}) {
|
|
638
661
|
const now = typeof clock === 'function' ? clock : () => new Date().toISOString();
|
|
662
|
+
const getNowMs = typeof nowMs === 'function' ? nowMs : Date.now;
|
|
639
663
|
const flowDir = join(root, name);
|
|
640
|
-
const startedAt =
|
|
664
|
+
const startedAt = getNowMs();
|
|
641
665
|
|
|
642
666
|
const read = readFlow({ root, name, catalogue });
|
|
643
667
|
if (!read.ok) {
|
|
@@ -666,7 +690,7 @@ export async function runFlow({
|
|
|
666
690
|
const fresh = checkFreshRunDir(runDir);
|
|
667
691
|
if (!fresh.ok) {
|
|
668
692
|
return haltRun({
|
|
669
|
-
flowDir, runDir, runId, capUsd, startedAt, now, signatureHash: signature.flow, outcome: 'preflight-red', red: fresh.red, spent: { value: 0 },
|
|
693
|
+
flowDir, runDir, runId, capUsd, startedAt, now, nowMs: getNowMs, signatureHash: signature.flow, outcome: 'preflight-red', red: fresh.red, spent: { value: 0 },
|
|
670
694
|
});
|
|
671
695
|
}
|
|
672
696
|
mkdirSync(runDir, { recursive: true });
|
|
@@ -674,7 +698,7 @@ export async function runFlow({
|
|
|
674
698
|
const frozen = freezeInputs(runDir, sources ?? []);
|
|
675
699
|
if (!frozen.ok) {
|
|
676
700
|
return haltRun({
|
|
677
|
-
flowDir, runDir, runId, capUsd, startedAt, now, signatureHash: signature.flow, outcome: 'preflight-red', red: frozen.red, spent: { value: 0 },
|
|
701
|
+
flowDir, runDir, runId, capUsd, startedAt, now, nowMs: getNowMs, signatureHash: signature.flow, outcome: 'preflight-red', red: frozen.red, spent: { value: 0 },
|
|
678
702
|
});
|
|
679
703
|
}
|
|
680
704
|
|
|
@@ -685,6 +709,14 @@ export async function runFlow({
|
|
|
685
709
|
// shape) and folded into log.json only, on every exit path.
|
|
686
710
|
/** @type {any[]} */
|
|
687
711
|
const attemptsLog = [];
|
|
712
|
+
// Orchestrator review fix (4): a floor stays a floor — once ANY row this
|
|
713
|
+
// run carries `spendComplete: false` (a cost that never resolved to a
|
|
714
|
+
// known number, e.g. a retried transport fault that still failed), the
|
|
715
|
+
// run's OWN aggregate never flips back to true, park or no park. Threaded
|
|
716
|
+
// into every book row `foldFromStep`/`runAskSlot` writes and persisted in
|
|
717
|
+
// `state.json` so a resumed run inherits the floor instead of quietly
|
|
718
|
+
// reporting complete.
|
|
719
|
+
const spendComplete = { value: true };
|
|
688
720
|
const recordAudit = (row, modelOutput, unjudgedCount) => {
|
|
689
721
|
// M2 amendment 1 item 2: "audit row for the ask gains unjudgedCount" —
|
|
690
722
|
// only the ask's own rows pass a third argument; every other row is
|
|
@@ -692,6 +724,7 @@ export async function runFlow({
|
|
|
692
724
|
const fullRow = unjudgedCount === undefined ? row : { ...row, unjudgedCount };
|
|
693
725
|
auditRows.push(fullRow);
|
|
694
726
|
appendAudit(runDir, fullRow);
|
|
727
|
+
if (row.spendComplete === false) spendComplete.value = false;
|
|
695
728
|
if (modelOutput !== undefined) {
|
|
696
729
|
attemptsLog.push({
|
|
697
730
|
step: row.step, attempt: row.attempt, class: row.class, verdict: row.verdict, gap: row.gap, modelOutput,
|
|
@@ -711,42 +744,337 @@ export async function runFlow({
|
|
|
711
744
|
// emitted by a signed ask step), never by position in `reads` — every id
|
|
712
745
|
// in a send step's `reads` names an earlier step, so picking `reads[0]`
|
|
713
746
|
// silently ships whatever was read first instead of what was accepted.
|
|
714
|
-
// Derived the same way the
|
|
747
|
+
// Derived the same way the fold below knows a step is an ask — bound to
|
|
715
748
|
// an `arbiter.asks[]` line.
|
|
716
749
|
const askStepEmits = new Set(steps.filter((s) => askLines.has(s.fromLine)).map((s) => s.emits));
|
|
717
750
|
// Tracks which specific ask emits were accepted THIS run (acceptedThisRun
|
|
718
751
|
// above stays run-wide, for the "reached with no accept this run" gate).
|
|
719
752
|
const acceptedAskEmitsThisRun = new Set();
|
|
720
|
-
|
|
753
|
+
|
|
754
|
+
const result = await foldFromStep({
|
|
755
|
+
i0: 0,
|
|
756
|
+
steps,
|
|
757
|
+
askLines,
|
|
758
|
+
sendLines,
|
|
759
|
+
askStepEmits,
|
|
760
|
+
runDir,
|
|
761
|
+
flowDir,
|
|
762
|
+
runId,
|
|
763
|
+
flowRoot: root,
|
|
764
|
+
flowName: name,
|
|
765
|
+
signatureHash: signature.flow,
|
|
766
|
+
inputsManifest: frozen.manifest,
|
|
767
|
+
capUsd,
|
|
768
|
+
redoCap,
|
|
769
|
+
effectiveCeilingUsd,
|
|
770
|
+
primitives,
|
|
771
|
+
businessDate,
|
|
772
|
+
modelStep,
|
|
773
|
+
askStep,
|
|
774
|
+
sendStep,
|
|
775
|
+
now,
|
|
776
|
+
startedAt,
|
|
777
|
+
nowMs: getNowMs,
|
|
778
|
+
// F45 finding 3: `runStartedAt` is the run's TRUE wall-clock start — for
|
|
779
|
+
// a fresh `runFlow` call it's this same `startedAt` (there is no earlier
|
|
780
|
+
// process). It is what park persists into state.json and every resume
|
|
781
|
+
// restores, so a run's final `wallMs` times the whole run, not just the
|
|
782
|
+
// last process (a pause counts as elapsed wall time — see the comment
|
|
783
|
+
// at its use in `foldFromStep`).
|
|
784
|
+
runStartedAt: startedAt,
|
|
785
|
+
spent,
|
|
786
|
+
spendComplete,
|
|
787
|
+
artifacts,
|
|
788
|
+
acceptedThisRun,
|
|
789
|
+
acceptedAskEmitsThisRun,
|
|
790
|
+
unjudgedSinceLastAsk,
|
|
791
|
+
recordAudit,
|
|
792
|
+
attemptsLog,
|
|
793
|
+
firstStepGap: initialGap ?? null,
|
|
794
|
+
});
|
|
795
|
+
|
|
796
|
+
if (result.outcome === 'complete') return { ...result, auditRows };
|
|
797
|
+
return result;
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
// ---------------------------------------------------------------------------
|
|
801
|
+
// M3 piece 1 (docs/wiki/the-module-ladder.md, "M3 — scope, exit, negative —
|
|
802
|
+
// SIGNED", scope items 1-2, 4-6, 8): park-and-exit at a signed ask, and
|
|
803
|
+
// resuming into the SAME fold from a separate process later. ONE fold —
|
|
804
|
+
// `foldFromStep` below is the loop `runFlow` always ran (M2), now starting
|
|
805
|
+
// at an arbitrary step index with restored accumulators so `resumeRun` can
|
|
806
|
+
// re-enter it exactly where a parked run left off, instead of a second
|
|
807
|
+
// runner.
|
|
808
|
+
//
|
|
809
|
+
// borrowed-from: fwdloop poc/m3/park.mjs@afb85d7 (the park/answer/resume
|
|
810
|
+
// protocol proved at F44 — ask.json+state.json's fields, the exclusive
|
|
811
|
+
// `resume.lock`, consuming `answer.json` by rename BEFORE acting). Rewritten
|
|
812
|
+
// against the real `runFlow` fold (the POC ran fake, hand-rolled steps
|
|
813
|
+
// against a single hard-coded ask, never `runStepRalph`/`runAskSlot`) — src/
|
|
814
|
+
// never imports from poc/.
|
|
815
|
+
// ---------------------------------------------------------------------------
|
|
816
|
+
|
|
817
|
+
/** An ask step that never waits — it immediately tells the fold to park.
|
|
818
|
+
* The counterpart to `makeFileAskStep`'s in-process poll (M2 scope item 6);
|
|
819
|
+
* a caller wanting park-and-exit behaviour from a FRESH `runFlow` call
|
|
820
|
+
* passes this (or an equivalent) as `askStep`.
|
|
821
|
+
* @returns {(opts?: any) => Promise<{decision: 'park'}>} */
|
|
822
|
+
export function makeParkingAskStep() {
|
|
823
|
+
return async function parkingAskStep() {
|
|
824
|
+
return /** @type {{decision: 'park'}} */ ({ decision: 'park' });
|
|
825
|
+
};
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
/** `resumeRun`'s own askStep: yields the human's already-consumed decision
|
|
829
|
+
* exactly once (for the ask it was built for), then — if that decision was
|
|
830
|
+
* a reject and the ask loops back around to ask again — parks under a NEW
|
|
831
|
+
* askId, exactly like a fresh ask would. This is what turns "redo, then
|
|
832
|
+
* ask again" into "redo, then re-park" for a resumed run, with no second
|
|
833
|
+
* code path. */
|
|
834
|
+
function makeOneShotThenParkAskStep({ decision, reason }) {
|
|
835
|
+
let used = false;
|
|
836
|
+
return async function resumeAskStep() {
|
|
837
|
+
if (!used) {
|
|
838
|
+
used = true;
|
|
839
|
+
return { decision, reason };
|
|
840
|
+
}
|
|
841
|
+
return { decision: 'park' };
|
|
842
|
+
};
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
/**
|
|
846
|
+
* One signed ask slot's own loop (M2's ask branch, unchanged in spirit,
|
|
847
|
+
* extracted so `resumeRun` can re-enter the SAME logic mid-ask instead of
|
|
848
|
+
* duplicating it). Returns exactly one of:
|
|
849
|
+
* - `{ type: 'paused', result }` — `askStep` chose to park; ask.json +
|
|
850
|
+
* state.json are written and `result` is `runFlow`/`resumeRun`'s own
|
|
851
|
+
* return value.
|
|
852
|
+
* - `{ type: 'halted', outcome, red }` — the caller wraps this in
|
|
853
|
+
* `haltRun` (it knows the right `signatureHash`/`artifacts` to attach).
|
|
854
|
+
* - `{ type: 'accepted', artifact }` — the human accepted; the caller
|
|
855
|
+
* writes the ask step's own artifact and continues the fold.
|
|
856
|
+
*
|
|
857
|
+
* @param {object} opts
|
|
858
|
+
* @returns {Promise<any>}
|
|
859
|
+
*/
|
|
860
|
+
async function runAskSlot({
|
|
861
|
+
step, stepIndex, askSlot, priorId, priorStep, priorArtifact, redoCap, effectiveCeilingUsd, capUsd,
|
|
862
|
+
primitives, businessDate, modelStep, askStep, spent, spendComplete, recordAudit,
|
|
863
|
+
evidenceUnjudged, unjudgedCount, redone: initialRedone,
|
|
864
|
+
runDir, flowDir, runId, flowRoot, flowName, signatureHash, inputsManifest, attemptsLog, artifacts, now, startedAt,
|
|
865
|
+
// F45 finding 3: the run's TRUE wall-clock start, persisted into
|
|
866
|
+
// state.json on every park/re-park so a later resume can restore it
|
|
867
|
+
// instead of substituting its own process's start.
|
|
868
|
+
runStartedAt,
|
|
869
|
+
}) {
|
|
870
|
+
let redone = initialRedone;
|
|
871
|
+
let currentPrior = priorArtifact;
|
|
872
|
+
|
|
873
|
+
for (;;) {
|
|
874
|
+
const evidence = { artifact: currentPrior, unjudged: evidenceUnjudged };
|
|
875
|
+
// eslint-disable-next-line no-await-in-loop
|
|
876
|
+
const answer = await askStep({
|
|
877
|
+
question: askSlot?.question ?? step.goal, evidence, runDir, ttlMs: askSlot?.ttlMs, stepIndex,
|
|
878
|
+
});
|
|
879
|
+
|
|
880
|
+
if (answer.decision === 'park') {
|
|
881
|
+
// M3 scope item 1 (fixes F43): the wait is ALWAYS the signed ttlMs —
|
|
882
|
+
// no code default ever overrides it, on the first park or any re-park.
|
|
883
|
+
const askId = randomUUID();
|
|
884
|
+
const askedAt = now();
|
|
885
|
+
const expiresAt = new Date(Date.parse(askedAt) + askSlot.ttlMs).toISOString();
|
|
886
|
+
// F45 finding 2: a parked ask.json must carry the SAME evidence a
|
|
887
|
+
// human sees in-process (`makeFileAskStep`'s `{ artifact, unjudged }`)
|
|
888
|
+
// — the draft under review and the unjudged evidence, never just the
|
|
889
|
+
// question. `evidence` above is already recomputed at the top of every
|
|
890
|
+
// loop iteration (including a re-park after a reject, where
|
|
891
|
+
// `currentPrior` is the just-redrafted artifact), so this write always
|
|
892
|
+
// carries the CURRENT evidence, not a stale first-park copy.
|
|
893
|
+
writeFileSync(join(runDir, 'ask.json'), JSON.stringify({
|
|
894
|
+
askId, question: askSlot?.question ?? step.goal, askedAt, expiresAt, evidence,
|
|
895
|
+
}, null, 2));
|
|
896
|
+
// M3 scope item 2: the minimum the fold needs to resume identically —
|
|
897
|
+
// WHERE (stepIndex), WHAT was frozen/signed (signatureHash,
|
|
898
|
+
// inputsManifest, to be re-verified before anything runs), WHAT this
|
|
899
|
+
// ask is (askId/expiresAt), and the two accumulators a mid-ask resume
|
|
900
|
+
// cannot recompute from disk alone: `redone` (the redo cap is spent
|
|
901
|
+
// across pauses, not per process) and the evidence bundle this
|
|
902
|
+
// specific ask already showed the human (`evidenceUnjudged`/
|
|
903
|
+
// `unjudgedCount` — recomputing them from `unjudgedSinceLastAsk` on
|
|
904
|
+
// resume would double-count anything a later, still-unparked ask
|
|
905
|
+
// hasn't reset yet). `spent` carries the run's money across pauses too
|
|
906
|
+
// (the cap binds over the whole run, never per process).
|
|
907
|
+
const state = {
|
|
908
|
+
runId,
|
|
909
|
+
flow: { root: flowRoot, name: flowName },
|
|
910
|
+
signatureHash,
|
|
911
|
+
inputsManifest,
|
|
912
|
+
stepIndex,
|
|
913
|
+
askId,
|
|
914
|
+
expiresAt,
|
|
915
|
+
spent: spent.value,
|
|
916
|
+
// Orchestrator review fix (4): the floor persists across a pause —
|
|
917
|
+
// once any pre-park row left `spendComplete: false`, a resume must
|
|
918
|
+
// inherit that, never quietly start "complete" again.
|
|
919
|
+
spendComplete: spendComplete.value,
|
|
920
|
+
redone,
|
|
921
|
+
evidenceUnjudged,
|
|
922
|
+
unjudgedCount,
|
|
923
|
+
// F45 finding 3: persisted every park/re-park (unchanged value, just
|
|
924
|
+
// carried forward) so `resumeRun` restores the run's true start
|
|
925
|
+
// instead of timing only the process that happens to resume it.
|
|
926
|
+
startedAt: runStartedAt,
|
|
927
|
+
};
|
|
928
|
+
writeFileSync(join(runDir, 'state.json'), JSON.stringify(state, null, 2));
|
|
929
|
+
recordAudit(makeAuditRow({
|
|
930
|
+
step, attempt: redone + 1, verdict: 'paused', gap: null, usd: 0, spendComplete: true, wallMs: 0, strike: false,
|
|
931
|
+
}), undefined, unjudgedCount);
|
|
932
|
+
// Orchestrator review fix (3): M2 item 9 says history is ONE row per
|
|
933
|
+
// run; M3's signed scope item 2 only asks for an AUDIT row "paused"
|
|
934
|
+
// (already recorded above). A "paused" HISTORY row was the earlier
|
|
935
|
+
// draft's own error — removed here. The run's one history row lands
|
|
936
|
+
// at its final outcome (complete / a halt / ask-expired), written by
|
|
937
|
+
// `foldFromStep`/`resumeRun`, never here.
|
|
938
|
+
writeLog(runDir, { runId, outcome: 'paused', attempts: attemptsLog, artifacts });
|
|
939
|
+
return {
|
|
940
|
+
type: 'paused',
|
|
941
|
+
result: {
|
|
942
|
+
outcome: 'paused', runDir, askId, expiresAt, spentUsd: spent.value,
|
|
943
|
+
},
|
|
944
|
+
};
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
if (answer.decision === 'timeout') {
|
|
948
|
+
// A pause spends nothing (M2 scope item 6) — a halt, never a red
|
|
949
|
+
// with a fabricated cost, and never re-asked (the run is over).
|
|
950
|
+
recordAudit(makeAuditRow({
|
|
951
|
+
step, attempt: redone + 1, verdict: 'ask-timeout', gap: null, usd: 0, spendComplete: true, wallMs: 0, strike: false,
|
|
952
|
+
}), undefined, unjudgedCount);
|
|
953
|
+
return {
|
|
954
|
+
type: 'halted',
|
|
955
|
+
outcome: 'ask-timeout',
|
|
956
|
+
red: `ask-timeout: step "${step.goal}" expired waiting for a human answer`,
|
|
957
|
+
};
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
const isRedo = answer.decision === 'reject' || answer.decision === 'rerun';
|
|
961
|
+
const reason = typeof answer.reason === 'string' ? answer.reason.trim() : '';
|
|
962
|
+
|
|
963
|
+
if (isRedo && reason.length === 0) {
|
|
964
|
+
recordAudit(makeAuditRow({
|
|
965
|
+
step, attempt: redone + 1, verdict: 'refused', gap: 'a rejection/rerun needs a reason', usd: 0, spendComplete: true, wallMs: 0, strike: false,
|
|
966
|
+
}), undefined, unjudgedCount);
|
|
967
|
+
// Refused, re-asked for the SAME attempt — never re-runs the step.
|
|
968
|
+
// eslint-disable-next-line no-continue
|
|
969
|
+
continue;
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
if (answer.decision === 'accept') {
|
|
973
|
+
recordAudit(makeAuditRow({
|
|
974
|
+
step, attempt: redone + 1, verdict: 'green', gap: null, usd: 0, spendComplete: true, wallMs: 0, strike: false,
|
|
975
|
+
}), undefined, unjudgedCount);
|
|
976
|
+
return { type: 'accepted', artifact: currentPrior };
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
if (isRedo) {
|
|
980
|
+
redone += 1;
|
|
981
|
+
recordAudit(makeAuditRow({
|
|
982
|
+
step, attempt: redone, verdict: 'red', gap: reason, usd: 0, spendComplete: true, wallMs: 0, strike: false,
|
|
983
|
+
}), undefined, unjudgedCount);
|
|
984
|
+
if (redone > redoCap) {
|
|
985
|
+
return {
|
|
986
|
+
type: 'halted',
|
|
987
|
+
outcome: 'redo-halt',
|
|
988
|
+
red: `redo cap ${redoCap} reached at step "${step.goal}" after ${redone} rejections`,
|
|
989
|
+
};
|
|
990
|
+
}
|
|
991
|
+
const priorReads = readArtifactsMap(runDir, priorStep.reads);
|
|
992
|
+
// eslint-disable-next-line no-await-in-loop
|
|
993
|
+
const redoResult = await runStepRalph({
|
|
994
|
+
step: priorStep, primitivesMap: primitives, readsMap: priorReads, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, initialGap: reason, attemptOffset: redone,
|
|
995
|
+
});
|
|
996
|
+
if (!redoResult.ok) {
|
|
997
|
+
return { type: 'halted', outcome: redoResult.outcome, red: redoResult.red };
|
|
998
|
+
}
|
|
999
|
+
currentPrior = redoResult.artifact;
|
|
1000
|
+
// A redo deliberately REPLACES the prior step's own artifact — the one
|
|
1001
|
+
// case `writeArtifact` allows to overwrite on purpose.
|
|
1002
|
+
writeArtifact(runDir, priorId, currentPrior, { overwrite: true });
|
|
1003
|
+
artifacts[priorId] = currentPrior;
|
|
1004
|
+
// eslint-disable-next-line no-continue
|
|
1005
|
+
continue;
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
return {
|
|
1009
|
+
type: 'halted',
|
|
1010
|
+
outcome: 'red',
|
|
1011
|
+
red: `ask: step "${step.goal}" got an unrecognised decision "${answer.decision}"`,
|
|
1012
|
+
};
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
/**
|
|
1017
|
+
* The fold itself (M2 scope item 1's "one fold", now start-anywhere): walks
|
|
1018
|
+
* `steps` from `i0`, handling the signed send slot, the signed ask slot (via
|
|
1019
|
+
* `runAskSlot`), and ordinary steps exactly as `runFlow` always did. Used by
|
|
1020
|
+
* `runFlow` (i0 = 0, fresh accumulators) and by `resumeRun` (i0 = the step
|
|
1021
|
+
* AFTER the ask it just resolved, accumulators restored from `state.json`
|
|
1022
|
+
* plus disk).
|
|
1023
|
+
* @returns {Promise<any>}
|
|
1024
|
+
*/
|
|
1025
|
+
async function foldFromStep({
|
|
1026
|
+
i0, steps, askLines, sendLines, askStepEmits, runDir, flowDir, runId, flowRoot, flowName, signatureHash,
|
|
1027
|
+
inputsManifest, capUsd, redoCap, effectiveCeilingUsd, primitives, businessDate, modelStep, askStep, sendStep,
|
|
1028
|
+
// F45 finding 3: `startedAt` times only THIS process (used for the pre-fold
|
|
1029
|
+
// halts in `runFlow` and as this call's own fallback below); `runStartedAt`
|
|
1030
|
+
// is the run's true wall-clock start, persisted at park and restored on
|
|
1031
|
+
// every resume — every halt/complete a fold reaches must time itself
|
|
1032
|
+
// against `runStartedAt`, never the current process's own start, or a
|
|
1033
|
+
// resumed run's wallMs collapses to "how long did this resume take" (F45's
|
|
1034
|
+
// observed 19ms). Defaults to `startedAt` for a fresh run, where they are
|
|
1035
|
+
// the same instant.
|
|
1036
|
+
now, startedAt, runStartedAt = startedAt, nowMs = Date.now, spent, spendComplete, artifacts, acceptedThisRun, acceptedAskEmitsThisRun, unjudgedSinceLastAsk,
|
|
1037
|
+
recordAudit, attemptsLog,
|
|
1038
|
+
// M3 scope item 7: a fresh rerun's own reason, carried as step `i0`'s
|
|
1039
|
+
// starting gap (never any later step's). `/** @type */` here (rather than
|
|
1040
|
+
// a JSDoc `@param opts.firstStepGap`, which would need a preceding typed
|
|
1041
|
+
// `@param {object} opts` this function's block comment never declared)
|
|
1042
|
+
// is what keeps every OTHER destructured field's inferred type intact.
|
|
1043
|
+
firstStepGap = /** @type {string|null} */ (null),
|
|
1044
|
+
}) {
|
|
1045
|
+
let runAcceptedThisRun = acceptedThisRun;
|
|
1046
|
+
let runUnjudged = unjudgedSinceLastAsk;
|
|
1047
|
+
|
|
1048
|
+
for (let i = i0; i < steps.length; i += 1) {
|
|
721
1049
|
const step = steps[i];
|
|
722
1050
|
|
|
723
1051
|
// --- the signed send slot: never through modelStep, only after an
|
|
724
1052
|
// accept THIS run, re-checked at write time. ---
|
|
725
1053
|
if (sendLines.has(step.fromLine)) {
|
|
726
|
-
if (!
|
|
1054
|
+
if (!runAcceptedThisRun) {
|
|
727
1055
|
return haltRun({
|
|
728
|
-
flowDir, runDir, runId, capUsd, startedAt, now, signatureHash:
|
|
1056
|
+
flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts,
|
|
729
1057
|
outcome: 'red', red: `send: step "${step.goal}" reached with no accept this run`,
|
|
730
1058
|
});
|
|
731
1059
|
}
|
|
732
1060
|
const sendSlot = sendLines.get(step.fromLine);
|
|
733
1061
|
if (!sendSlot) {
|
|
734
1062
|
return haltRun({
|
|
735
|
-
flowDir, runDir, runId, capUsd, startedAt, now, signatureHash:
|
|
1063
|
+
flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts, outcome: 'red', red: `send: no arbiter slot bound to line ${step.fromLine}`,
|
|
736
1064
|
});
|
|
737
1065
|
}
|
|
738
1066
|
const target = `${sendSlot.target.kind}:${sendSlot.target.path}`;
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
const [askArtifactId] =
|
|
1067
|
+
// The send's content is identified by IDENTITY (the artifact emitted
|
|
1068
|
+
// by the ONE earlier signed ask step this send reads) — never by
|
|
1069
|
+
// position in `reads`. `readFlow`/`validateDeclaration` already
|
|
1070
|
+
// refuse, at signing time, any declaration whose send step doesn't
|
|
1071
|
+
// read the emits of exactly one earlier signed ask (M3 item 8); every
|
|
1072
|
+
// path into this fold goes through `readFlow` first, so `askIdsInReads`
|
|
1073
|
+
// is always exactly 1 here.
|
|
1074
|
+
const [askArtifactId] = (step.reads ?? []).filter((id) => askStepEmits.has(id));
|
|
747
1075
|
if (!acceptedAskEmitsThisRun.has(askArtifactId)) {
|
|
748
1076
|
return haltRun({
|
|
749
|
-
flowDir, runDir, runId, capUsd, startedAt, now, signatureHash:
|
|
1077
|
+
flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts,
|
|
750
1078
|
outcome: 'red', red: `send: step "${step.goal}" reads ask artifact "${askArtifactId}" that was not accepted this run`,
|
|
751
1079
|
});
|
|
752
1080
|
}
|
|
@@ -760,7 +1088,7 @@ export async function runFlow({
|
|
|
760
1088
|
recordAudit(sendRow);
|
|
761
1089
|
if (!sendResult.ok) {
|
|
762
1090
|
return haltRun({
|
|
763
|
-
flowDir, runDir, runId, capUsd, startedAt, now, signatureHash:
|
|
1091
|
+
flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts, outcome: 'red', red: `send: ${sendResult.red}`,
|
|
764
1092
|
});
|
|
765
1093
|
}
|
|
766
1094
|
writeArtifact(runDir, step.emits, content);
|
|
@@ -769,111 +1097,85 @@ export async function runFlow({
|
|
|
769
1097
|
continue;
|
|
770
1098
|
}
|
|
771
1099
|
|
|
772
|
-
// --- the signed ask slot: interactive, consume-once, reason-gated redo
|
|
1100
|
+
// --- the signed ask slot: interactive, consume-once, reason-gated redo,
|
|
1101
|
+
// OR park-and-exit (M3 scope item 2). ---
|
|
773
1102
|
if (askLines.has(step.fromLine)) {
|
|
774
1103
|
const askSlot = askLines.get(step.fromLine);
|
|
775
1104
|
const priorId = (step.reads ?? [])[0];
|
|
776
1105
|
const priorStepIndex = steps.findIndex((s) => s.emits === priorId);
|
|
777
|
-
|
|
778
|
-
let redone = 0;
|
|
1106
|
+
const priorArtifact = readArtifact(runDir, priorId);
|
|
779
1107
|
|
|
780
1108
|
// M2 amendment 1 item 2: every hitl artifact carried since the
|
|
781
1109
|
// previous ask goes to THIS ask as evidence, alongside the ask step's
|
|
782
1110
|
// own artifact — then the list resets (a fresh accumulator for the
|
|
783
1111
|
// NEXT ask), so a later ask never re-shows what an earlier one covered.
|
|
784
|
-
const evidenceUnjudged =
|
|
1112
|
+
const evidenceUnjudged = runUnjudged;
|
|
785
1113
|
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
|
-
}
|
|
1114
|
+
runUnjudged = [];
|
|
1115
|
+
|
|
1116
|
+
// eslint-disable-next-line no-await-in-loop
|
|
1117
|
+
const askResult = await runAskSlot({
|
|
1118
|
+
step,
|
|
1119
|
+
stepIndex: i,
|
|
1120
|
+
askSlot,
|
|
1121
|
+
priorId,
|
|
1122
|
+
priorStep: steps[priorStepIndex],
|
|
1123
|
+
priorArtifact,
|
|
1124
|
+
redoCap,
|
|
1125
|
+
effectiveCeilingUsd,
|
|
1126
|
+
capUsd,
|
|
1127
|
+
primitives,
|
|
1128
|
+
businessDate,
|
|
1129
|
+
modelStep,
|
|
1130
|
+
askStep,
|
|
1131
|
+
spent,
|
|
1132
|
+
spendComplete,
|
|
1133
|
+
recordAudit,
|
|
1134
|
+
evidenceUnjudged,
|
|
1135
|
+
unjudgedCount,
|
|
1136
|
+
redone: 0,
|
|
1137
|
+
runDir,
|
|
1138
|
+
flowDir,
|
|
1139
|
+
runId,
|
|
1140
|
+
flowRoot,
|
|
1141
|
+
flowName,
|
|
1142
|
+
signatureHash,
|
|
1143
|
+
inputsManifest,
|
|
1144
|
+
attemptsLog,
|
|
1145
|
+
artifacts,
|
|
1146
|
+
now,
|
|
1147
|
+
startedAt,
|
|
1148
|
+
runStartedAt,
|
|
1149
|
+
});
|
|
858
1150
|
|
|
1151
|
+
if (askResult.type === 'paused') return askResult.result;
|
|
1152
|
+
if (askResult.type === 'halted') {
|
|
859
1153
|
return haltRun({
|
|
860
|
-
flowDir, runDir, runId, capUsd, startedAt, now, signatureHash:
|
|
861
|
-
outcome: 'red', red: `ask: step "${step.goal}" got an unrecognised decision "${answer.decision}"`,
|
|
1154
|
+
flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts, outcome: askResult.outcome, red: askResult.red,
|
|
862
1155
|
});
|
|
863
1156
|
}
|
|
1157
|
+
|
|
1158
|
+
writeArtifact(runDir, step.emits, askResult.artifact);
|
|
1159
|
+
artifacts[step.emits] = askResult.artifact;
|
|
1160
|
+
runAcceptedThisRun = true;
|
|
1161
|
+
acceptedAskEmitsThisRun.add(step.emits);
|
|
864
1162
|
// eslint-disable-next-line no-continue
|
|
865
1163
|
continue;
|
|
866
1164
|
}
|
|
867
1165
|
|
|
868
1166
|
// --- an ordinary step: green / softgreen / a non-ask hitl pass-through. ---
|
|
869
1167
|
const readsMap = readArtifactsMap(runDir, step.reads);
|
|
1168
|
+
// M3 scope item 7: a fresh rerun's own first step (and only that one —
|
|
1169
|
+
// `i === i0` is this fold's own starting point, never any later step)
|
|
1170
|
+
// starts with the human's rerun reason as its gap, exactly like a
|
|
1171
|
+
// redo's `initialGap` above.
|
|
870
1172
|
// eslint-disable-next-line no-await-in-loop
|
|
871
1173
|
const stepResult = await runStepRalph({
|
|
872
|
-
step, primitivesMap: primitives, readsMap, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit,
|
|
1174
|
+
step, primitivesMap: primitives, readsMap, businessDate, modelStep, spent, capUsd, ceilingUsd: effectiveCeilingUsd, recordAudit, initialGap: i === i0 ? firstStepGap : null,
|
|
873
1175
|
});
|
|
874
1176
|
if (!stepResult.ok) {
|
|
875
1177
|
return haltRun({
|
|
876
|
-
flowDir, runDir, runId, capUsd, startedAt, now, signatureHash:
|
|
1178
|
+
flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs, signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts, outcome: stepResult.outcome, red: stepResult.red,
|
|
877
1179
|
});
|
|
878
1180
|
}
|
|
879
1181
|
writeArtifact(runDir, step.emits, stepResult.artifact);
|
|
@@ -883,23 +1185,465 @@ export async function runFlow({
|
|
|
883
1185
|
// reached when neither askLines nor sendLines claimed the step) passes
|
|
884
1186
|
// through silently here; carry it as evidence for the NEXT signed ask.
|
|
885
1187
|
if (stepResult.hitl) {
|
|
886
|
-
|
|
1188
|
+
runUnjudged.push({ step: step.goal ?? null, emits: step.emits, artifact: stepResult.artifact });
|
|
887
1189
|
}
|
|
888
1190
|
}
|
|
889
1191
|
|
|
890
|
-
|
|
1192
|
+
// F45 finding 3: the run's history row times the whole run, from its
|
|
1193
|
+
// FIRST process's start (`runStartedAt`, never this process's own
|
|
1194
|
+
// `startedAt`) to right now. A pause counts as elapsed wall time — the
|
|
1195
|
+
// run really was sitting there waiting on a human, so it belongs in
|
|
1196
|
+
// "how long did this run take", not carved out of it.
|
|
1197
|
+
const wallMs = nowMs() - runStartedAt;
|
|
891
1198
|
appendHistory(flowDir, {
|
|
892
|
-
runId, at: now(), outcome: 'complete', spentUsd: spent.value, spendComplete:
|
|
1199
|
+
runId, at: now(), outcome: 'complete', spentUsd: spent.value, spendComplete: spendComplete.value, capUsd, wallMs, signatureHash,
|
|
893
1200
|
});
|
|
894
1201
|
recordLateAnswerIfAny(runDir);
|
|
895
1202
|
writeLog(runDir, {
|
|
896
1203
|
runId, outcome: 'complete', attempts: attemptsLog, artifacts,
|
|
897
1204
|
});
|
|
898
1205
|
return {
|
|
899
|
-
outcome: 'complete', runDir, artifacts, spentUsd: spent.value,
|
|
1206
|
+
outcome: 'complete', runDir, artifacts, spentUsd: spent.value,
|
|
900
1207
|
};
|
|
901
1208
|
}
|
|
902
1209
|
|
|
1210
|
+
/**
|
|
1211
|
+
* Debrief fix: sums a run's own `audit.jsonl` — the books are the source of
|
|
1212
|
+
* truth for money already spent, so `state.spent` (a value carried in a
|
|
1213
|
+
* separately-writable state.json) is cross-checked against it before a
|
|
1214
|
+
* resume trusts it under the cap. Every row's `usd` here is expected to be
|
|
1215
|
+
* a finite number (the audit rows a park can precede — attempts, the pause
|
|
1216
|
+
* itself — never carry `usd: null`; only a `cap-halt` row does, and a
|
|
1217
|
+
* cap-halt ends the run without parking, so it can never appear in a
|
|
1218
|
+
* resumable run's audit.jsonl). A row this function cannot price refuses
|
|
1219
|
+
* rather than guessing (never `?? 0`, never skipped).
|
|
1220
|
+
* @param {string} runDir
|
|
1221
|
+
* @returns {{ ok: true, total: number } | { ok: false, red: string }}
|
|
1222
|
+
*/
|
|
1223
|
+
function sumAuditUsd(runDir) {
|
|
1224
|
+
const auditPath = join(runDir, 'audit.jsonl');
|
|
1225
|
+
if (!existsSync(auditPath)) return { ok: true, total: 0 };
|
|
1226
|
+
const lines = readFileSync(auditPath, 'utf8').split('\n').filter((line) => line.trim().length > 0);
|
|
1227
|
+
let total = 0;
|
|
1228
|
+
for (const line of lines) {
|
|
1229
|
+
let row;
|
|
1230
|
+
try {
|
|
1231
|
+
row = JSON.parse(line);
|
|
1232
|
+
} catch (err) {
|
|
1233
|
+
return { ok: false, red: `audit.jsonl line is not valid JSON — ${err.message}` };
|
|
1234
|
+
}
|
|
1235
|
+
if (typeof row.usd !== 'number' || !Number.isFinite(row.usd)) {
|
|
1236
|
+
return { ok: false, red: `audit.jsonl carries a row whose "usd" is not a finite number (got ${JSON.stringify(row.usd)}) — refusing to sum past an unpriced round` };
|
|
1237
|
+
}
|
|
1238
|
+
total += row.usd;
|
|
1239
|
+
}
|
|
1240
|
+
return { ok: true, total };
|
|
1241
|
+
}
|
|
1242
|
+
|
|
1243
|
+
/**
|
|
1244
|
+
* M3 scope items 4-6: re-enter a parked run's SAME fold from a separate
|
|
1245
|
+
* process. Takes an exclusive `resume.lock` (refuses by name if already
|
|
1246
|
+
* held; a lock left behind by a killed resumer is a red naming it, never
|
|
1247
|
+
* stolen), re-reads the flow, refuses by name at $0 on any signature/input/
|
|
1248
|
+
* missing-artifact mismatch, consumes `answer.json` by atomic rename BEFORE
|
|
1249
|
+
* acting (F44), then either cancels an expired ask ($0, nothing sent) or
|
|
1250
|
+
* resolves it and folds on to `complete`/the next pause/a halt.
|
|
1251
|
+
*
|
|
1252
|
+
* @param {object} opts
|
|
1253
|
+
* @param {string} opts.root
|
|
1254
|
+
* @param {string} opts.name
|
|
1255
|
+
* @param {string} opts.runId
|
|
1256
|
+
* @param {unknown} opts.catalogue
|
|
1257
|
+
* @param {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class:string|null}) => Promise<any>} opts.modelStep
|
|
1258
|
+
* @param {(target:string, filename:string, content:unknown) => Promise<{ok:boolean, red?:string, bytes?:number}>} opts.sendStep
|
|
1259
|
+
* @param {Record<string, any>} [opts.primitives]
|
|
1260
|
+
* @param {() => string} [opts.clock]
|
|
1261
|
+
* @param {string} opts.businessDate
|
|
1262
|
+
* @param {number} [opts.ceilingUsd]
|
|
1263
|
+
* @param {() => number} [opts.nowMs] - F45 finding 3; see `runFlow`'s own.
|
|
1264
|
+
*/
|
|
1265
|
+
export async function resumeRun({
|
|
1266
|
+
root, name, runId, catalogue, modelStep, sendStep, primitives, clock, businessDate, ceilingUsd,
|
|
1267
|
+
// F45 finding 3 (see `runFlow`'s own `nowMs`): additive, defaults to the
|
|
1268
|
+
// real `Date.now` for every existing caller.
|
|
1269
|
+
nowMs,
|
|
1270
|
+
}) {
|
|
1271
|
+
const now = typeof clock === 'function' ? clock : () => new Date().toISOString();
|
|
1272
|
+
const getNowMs = typeof nowMs === 'function' ? nowMs : Date.now;
|
|
1273
|
+
const flowDir = join(root, name);
|
|
1274
|
+
const runDir = join(flowDir, 'runs', runId);
|
|
1275
|
+
const startedAt = getNowMs();
|
|
1276
|
+
const lockPath = join(runDir, 'resume.lock');
|
|
1277
|
+
|
|
1278
|
+
let lockFd;
|
|
1279
|
+
try {
|
|
1280
|
+
lockFd = openSync(lockPath, 'wx');
|
|
1281
|
+
} catch (err) {
|
|
1282
|
+
if (err.code === 'EEXIST') {
|
|
1283
|
+
return { outcome: 'refused', red: `resume: run "${runId}" is locked by another resumer (${lockPath})` };
|
|
1284
|
+
}
|
|
1285
|
+
return { outcome: 'refused', red: `resume: could not create lock ${lockPath} — ${err.message}` };
|
|
1286
|
+
}
|
|
1287
|
+
|
|
1288
|
+
try {
|
|
1289
|
+
const statePath = join(runDir, 'state.json');
|
|
1290
|
+
if (!existsSync(statePath)) {
|
|
1291
|
+
return { outcome: 'refused', red: `resume: no parked state for run "${runId}" (${statePath})` };
|
|
1292
|
+
}
|
|
1293
|
+
let state;
|
|
1294
|
+
try {
|
|
1295
|
+
state = JSON.parse(readFileSync(statePath, 'utf8'));
|
|
1296
|
+
} catch (err) {
|
|
1297
|
+
return { outcome: 'refused', red: `resume: state.json for run "${runId}" is not valid JSON — ${err.message}` };
|
|
1298
|
+
}
|
|
1299
|
+
|
|
1300
|
+
// F45 finding 3: the run's TRUE wall-clock start, restored from the
|
|
1301
|
+
// parked state rather than this process's own `startedAt` — otherwise
|
|
1302
|
+
// every resume's history/audit `wallMs` times just that resume (F45's
|
|
1303
|
+
// observed 19ms), not the run. Falls back to this process's own start
|
|
1304
|
+
// for a run parked BEFORE this fix (no `state.startedAt` on disk) —
|
|
1305
|
+
// not a money field, so a best-known fallback rather than a refusal.
|
|
1306
|
+
const runStartedAt = typeof state.startedAt === 'number' ? state.startedAt : startedAt;
|
|
1307
|
+
|
|
1308
|
+
// Orchestrator review fix (6): the CALLER's `root`/`name` are the source
|
|
1309
|
+
// of truth — never `state.flow.root`/`state.flow.name` silently. A
|
|
1310
|
+
// parked run whose recorded flow location disagrees with what THIS call
|
|
1311
|
+
// was asked to resume is refused by name, never re-read from wherever
|
|
1312
|
+
// the state file happens to point.
|
|
1313
|
+
if (state.flow?.root !== root || state.flow?.name !== name) {
|
|
1314
|
+
return {
|
|
1315
|
+
outcome: 'refused',
|
|
1316
|
+
red: `resume: run "${runId}" was parked against flow "${state.flow?.root}/${state.flow?.name}", `
|
|
1317
|
+
+ `not the requested "${root}/${name}" — refusing rather than reading a different flow than asked`,
|
|
1318
|
+
};
|
|
1319
|
+
}
|
|
1320
|
+
|
|
1321
|
+
const read = readFlow({ root, name, catalogue });
|
|
1322
|
+
if (!read.ok) {
|
|
1323
|
+
return { outcome: 'refused', red: `resume: flow re-read failed for run "${runId}": ${read.reds.join('; ')}` };
|
|
1324
|
+
}
|
|
1325
|
+
const { declaration, arbiter, signature } = read;
|
|
1326
|
+
|
|
1327
|
+
if (signature.flow !== state.signatureHash) {
|
|
1328
|
+
return { outcome: 'refused', red: `resume: signature mismatch for run "${runId}" — the flow changed while parked` };
|
|
1329
|
+
}
|
|
1330
|
+
|
|
1331
|
+
for (const entry of state.inputsManifest ?? []) {
|
|
1332
|
+
if (!existsSync(entry.frozen)) {
|
|
1333
|
+
return { outcome: 'refused', red: `resume: frozen input "${entry.id}" missing for run "${runId}" (${entry.frozen})` };
|
|
1334
|
+
}
|
|
1335
|
+
const sha256 = createHash('sha256').update(readFileSync(entry.frozen)).digest('hex');
|
|
1336
|
+
if (sha256 !== entry.sha256) {
|
|
1337
|
+
return { outcome: 'refused', red: `resume: frozen input "${entry.id}" changed while parked for run "${runId}"` };
|
|
1338
|
+
}
|
|
1339
|
+
}
|
|
1340
|
+
|
|
1341
|
+
const { steps } = declaration;
|
|
1342
|
+
for (let i = 0; i < state.stepIndex; i += 1) {
|
|
1343
|
+
if (readArtifact(runDir, steps[i].emits) === undefined) {
|
|
1344
|
+
return { outcome: 'refused', red: `resume: artifact "${steps[i].emits}" missing for run "${runId}" — cannot resume` };
|
|
1345
|
+
}
|
|
1346
|
+
}
|
|
1347
|
+
|
|
1348
|
+
// Orchestrator review fix (1): unknown cost is never rendered as 0 — a
|
|
1349
|
+
// missing/non-number/non-finite `state.spent` refuses the resume by
|
|
1350
|
+
// name (naming the run AND the field), $0 further spend, rather than
|
|
1351
|
+
// silently treating an unreadable ledger as "nothing spent yet". Checked
|
|
1352
|
+
// BEFORE the answer is consumed — a refusal here must be replayable.
|
|
1353
|
+
if (typeof state.spent !== 'number' || !Number.isFinite(state.spent)) {
|
|
1354
|
+
return {
|
|
1355
|
+
outcome: 'refused',
|
|
1356
|
+
red: `resume: run "${runId}" state.json field "spent" is not a finite number (got ${JSON.stringify(state.spent)}) — `
|
|
1357
|
+
+ 'unknown cost is never rendered as 0; refusing further spend',
|
|
1358
|
+
};
|
|
1359
|
+
}
|
|
1360
|
+
// Debrief fix: a negative spend is an impossible cost, never a number
|
|
1361
|
+
// the cap can trust — refused the same way as a non-finite one.
|
|
1362
|
+
if (state.spent < 0) {
|
|
1363
|
+
return {
|
|
1364
|
+
outcome: 'refused',
|
|
1365
|
+
red: `resume: run "${runId}" state.json field "spent" is negative (${state.spent}) — `
|
|
1366
|
+
+ 'an impossible cost is never trusted by the cap; refusing further spend',
|
|
1367
|
+
};
|
|
1368
|
+
}
|
|
1369
|
+
// Debrief fix: the run's own audit.jsonl is the books' source of truth
|
|
1370
|
+
// for money already spent — if state.spent claims LESS than what the
|
|
1371
|
+
// audit already recorded, state.spent is wrong (or tampered) and must
|
|
1372
|
+
// never be trusted to gate further spend under the cap.
|
|
1373
|
+
const auditSum = sumAuditUsd(runDir);
|
|
1374
|
+
if (!auditSum.ok) {
|
|
1375
|
+
return { outcome: 'refused', red: `resume: run "${runId}" ${auditSum.red}` };
|
|
1376
|
+
}
|
|
1377
|
+
if (auditSum.total - state.spent > SPEND_TOLERANCE_USD) {
|
|
1378
|
+
return {
|
|
1379
|
+
outcome: 'refused',
|
|
1380
|
+
red: `resume: run "${runId}" state.json field "spent" ($${state.spent}) is less than its own audit.jsonl sum ($${auditSum.total}) — `
|
|
1381
|
+
+ "the books are the source of truth for money already spent; refusing rather than trusting state.json's lower figure",
|
|
1382
|
+
};
|
|
1383
|
+
}
|
|
1384
|
+
const spent = { value: state.spent };
|
|
1385
|
+
// Orchestrator review fix (4): a floor persisted across the pause
|
|
1386
|
+
// (`state.spendComplete`) is restored here, never quietly reset to
|
|
1387
|
+
// `true` — an absent/non-boolean value defaults to `false` (unknown
|
|
1388
|
+
// never renders as "complete"), never `true`.
|
|
1389
|
+
const spendComplete = { value: state.spendComplete === true };
|
|
1390
|
+
|
|
1391
|
+
// A present-but-unparseable `state.expiresAt` (Date.parse -> NaN) must
|
|
1392
|
+
// never read as "not expired" — `NaN > x`/`x > NaN` are both false, so
|
|
1393
|
+
// the real expiry compare below would silently treat garbage as open
|
|
1394
|
+
// forever. Refused here, naming the run, BEFORE the answer is consumed
|
|
1395
|
+
// (same "checked before consuming" rule as the spent check above — a
|
|
1396
|
+
// refusal here must be replayable).
|
|
1397
|
+
if (Number.isNaN(Date.parse(state.expiresAt))) {
|
|
1398
|
+
return {
|
|
1399
|
+
outcome: 'refused',
|
|
1400
|
+
red: `resume: run "${runId}" state.json field "expiresAt" ("${state.expiresAt}") is not a parseable date — `
|
|
1401
|
+
+ 'refusing rather than treating it as not-expired',
|
|
1402
|
+
};
|
|
1403
|
+
}
|
|
1404
|
+
|
|
1405
|
+
const answerPath = join(runDir, 'answer.json');
|
|
1406
|
+
if (!existsSync(answerPath)) {
|
|
1407
|
+
return { outcome: 'refused', red: `resume: no answer yet for run "${runId}"` };
|
|
1408
|
+
}
|
|
1409
|
+
let answer;
|
|
1410
|
+
try {
|
|
1411
|
+
answer = JSON.parse(readFileSync(answerPath, 'utf8'));
|
|
1412
|
+
} catch (err) {
|
|
1413
|
+
return { outcome: 'refused', red: `resume: answer.json for run "${runId}" is not valid JSON — ${err.message}` };
|
|
1414
|
+
}
|
|
1415
|
+
if (answer.askId !== state.askId) {
|
|
1416
|
+
return { outcome: 'refused', red: `resume: answer askId "${answer.askId}" does not match open askId "${state.askId}" for run "${runId}"` };
|
|
1417
|
+
}
|
|
1418
|
+
|
|
1419
|
+
// Consume-once, BEFORE acting on the decision (F44) — the rename is
|
|
1420
|
+
// itself a one-winner gate, on top of the lock above.
|
|
1421
|
+
const consumedPath = join(runDir, `answer.${answer.askId}.consumed.json`);
|
|
1422
|
+
renameSync(answerPath, consumedPath);
|
|
1423
|
+
|
|
1424
|
+
// The run's own injected clock governs expiry, exactly like every other
|
|
1425
|
+
// "now" in this module (never the bare wall clock) — the same fixed
|
|
1426
|
+
// clock a test controls for `runFlow` also controls what "expired" means
|
|
1427
|
+
// for `resumeRun`, with no real wait required to prove it.
|
|
1428
|
+
if (Date.parse(now()) > Date.parse(state.expiresAt)) {
|
|
1429
|
+
// Negative (i): an answer arriving after expiry cancels the run —
|
|
1430
|
+
// adds NOTHING further, but the run's own already-spent total is
|
|
1431
|
+
// real money and must be reported, never coerced to 0 (orchestrator
|
|
1432
|
+
// review fix 2: "a pause spends nothing" means the pause adds
|
|
1433
|
+
// nothing, not that the run's total resets).
|
|
1434
|
+
appendAudit(runDir, {
|
|
1435
|
+
step: null, attempt: null, class: null, verdict: 'ask-expired', gap: null, usd: 0, spendComplete: true, wallMs: 0, model: null, modelMatch: null, strike: false,
|
|
1436
|
+
});
|
|
1437
|
+
appendHistory(flowDir, {
|
|
1438
|
+
runId, at: now(), outcome: 'ask-expired', spentUsd: spent.value, spendComplete: spendComplete.value, capUsd: arbiter.capUsd ?? null, wallMs: getNowMs() - runStartedAt, signatureHash: state.signatureHash,
|
|
1439
|
+
});
|
|
1440
|
+
return { outcome: 'ask-expired', runDir, spentUsd: spent.value };
|
|
1441
|
+
}
|
|
1442
|
+
|
|
1443
|
+
if (answer.decision === 'rerun') {
|
|
1444
|
+
// M3 scope item 7 (hamr "2A"): `rerun` ends THIS run (one history row,
|
|
1445
|
+
// `rerun`, its real spend, $0 added) and starts a brand-new run on the
|
|
1446
|
+
// same signed flow — never a redo of the step before the ask.
|
|
1447
|
+
const reason = typeof answer.reason === 'string' ? answer.reason.trim() : '';
|
|
1448
|
+
if (reason.length === 0) {
|
|
1449
|
+
// `answerAsk` already refuses a blank reason at write time — this
|
|
1450
|
+
// re-check exists because `resumeRun` never trusts a file it did
|
|
1451
|
+
// not itself just validate, same as every other field read above.
|
|
1452
|
+
return { outcome: 'refused', red: `resume: rerun answer for run "${runId}" carries a blank reason` };
|
|
1453
|
+
}
|
|
1454
|
+
|
|
1455
|
+
const priorArtifactsForLog = {};
|
|
1456
|
+
for (let i = 0; i < state.stepIndex; i += 1) {
|
|
1457
|
+
priorArtifactsForLog[steps[i].emits] = readArtifact(runDir, steps[i].emits);
|
|
1458
|
+
}
|
|
1459
|
+
appendHistory(flowDir, {
|
|
1460
|
+
runId, at: now(), outcome: 'rerun', spentUsd: spent.value, spendComplete: spendComplete.value, capUsd: arbiter.capUsd ?? null, wallMs: getNowMs() - runStartedAt, signatureHash: state.signatureHash,
|
|
1461
|
+
});
|
|
1462
|
+
recordLateAnswerIfAny(runDir);
|
|
1463
|
+
writeLog(runDir, { runId, outcome: 'rerun', attempts: [], artifacts: priorArtifactsForLog });
|
|
1464
|
+
|
|
1465
|
+
// Deterministic derived id (M3 scope item 7) — refused by name, never
|
|
1466
|
+
// silently renumbered, if it already exists.
|
|
1467
|
+
const newRunId = `${runId}-rerun-1`;
|
|
1468
|
+
const newRunDir = join(flowDir, 'runs', newRunId);
|
|
1469
|
+
if (existsSync(newRunDir)) {
|
|
1470
|
+
return {
|
|
1471
|
+
outcome: 'refused',
|
|
1472
|
+
red: `resume: rerun target run "${newRunId}" already exists for run "${runId}" — refused`,
|
|
1473
|
+
};
|
|
1474
|
+
}
|
|
1475
|
+
|
|
1476
|
+
// Fresh inputs, re-frozen from the ORIGINAL source paths — carried in
|
|
1477
|
+
// `inputsManifest[].source` since `freezeInputs` first wrote it (M3
|
|
1478
|
+
// scope item 7's own note: "persist those in state.json at park if
|
|
1479
|
+
// they aren't already" — they already are, via this field).
|
|
1480
|
+
const rerunSources = (state.inputsManifest ?? []).map((entry) => ({ id: entry.id, path: entry.source }));
|
|
1481
|
+
|
|
1482
|
+
const newRun = await runFlow({
|
|
1483
|
+
root,
|
|
1484
|
+
name,
|
|
1485
|
+
runId: newRunId,
|
|
1486
|
+
sources: rerunSources,
|
|
1487
|
+
catalogue,
|
|
1488
|
+
modelStep,
|
|
1489
|
+
// A fresh run never waits in-process — any signed ask it reaches
|
|
1490
|
+
// parks immediately, exactly like any other `runFlow` call this
|
|
1491
|
+
// piece drives.
|
|
1492
|
+
askStep: makeParkingAskStep(),
|
|
1493
|
+
sendStep,
|
|
1494
|
+
primitives,
|
|
1495
|
+
clock,
|
|
1496
|
+
businessDate,
|
|
1497
|
+
ceilingUsd,
|
|
1498
|
+
// Item 7: the reason becomes the new run's FIRST step's starting gap.
|
|
1499
|
+
initialGap: reason,
|
|
1500
|
+
});
|
|
1501
|
+
|
|
1502
|
+
return {
|
|
1503
|
+
outcome: 'rerun', runDir, runId, newRunId, spentUsd: spent.value, newRun,
|
|
1504
|
+
};
|
|
1505
|
+
}
|
|
1506
|
+
|
|
1507
|
+
if (answer.decision !== 'accept' && answer.decision !== 'reject') {
|
|
1508
|
+
return { outcome: 'refused', red: `resume: unrecognised decision "${answer.decision}" for run "${runId}"` };
|
|
1509
|
+
}
|
|
1510
|
+
|
|
1511
|
+
// Reconstruct the fold's accumulators from disk + state.json — never
|
|
1512
|
+
// re-running a step that already went green (M3 scope item 4).
|
|
1513
|
+
const artifacts = {};
|
|
1514
|
+
for (let i = 0; i < state.stepIndex; i += 1) {
|
|
1515
|
+
artifacts[steps[i].emits] = readArtifact(runDir, steps[i].emits);
|
|
1516
|
+
}
|
|
1517
|
+
const askLines = new Map((arbiter.asks ?? []).map((a) => [a.line, a]));
|
|
1518
|
+
const sendLines = new Map((arbiter.sends ?? []).map((s) => [s.line, s]));
|
|
1519
|
+
const askStepEmits = new Set(steps.filter((s) => askLines.has(s.fromLine)).map((s) => s.emits));
|
|
1520
|
+
const acceptedAskEmitsThisRun = new Set();
|
|
1521
|
+
for (const emits of askStepEmits) {
|
|
1522
|
+
const idx = steps.findIndex((s) => s.emits === emits);
|
|
1523
|
+
if (idx !== -1 && idx < state.stepIndex && readArtifact(runDir, emits) !== undefined) {
|
|
1524
|
+
acceptedAskEmitsThisRun.add(emits);
|
|
1525
|
+
}
|
|
1526
|
+
}
|
|
1527
|
+
|
|
1528
|
+
const attemptsLog = [];
|
|
1529
|
+
const auditRows = [];
|
|
1530
|
+
const recordAudit = (row, modelOutput, unjudgedCount) => {
|
|
1531
|
+
const fullRow = unjudgedCount === undefined ? row : { ...row, unjudgedCount };
|
|
1532
|
+
auditRows.push(fullRow);
|
|
1533
|
+
appendAudit(runDir, fullRow);
|
|
1534
|
+
if (row.spendComplete === false) spendComplete.value = false;
|
|
1535
|
+
if (modelOutput !== undefined) {
|
|
1536
|
+
attemptsLog.push({
|
|
1537
|
+
step: row.step, attempt: row.attempt, class: row.class, verdict: row.verdict, gap: row.gap, modelOutput,
|
|
1538
|
+
});
|
|
1539
|
+
}
|
|
1540
|
+
};
|
|
1541
|
+
|
|
1542
|
+
const capUsd = arbiter.capUsd;
|
|
1543
|
+
const redoCap = arbiter.redoCap ?? 3;
|
|
1544
|
+
const effectiveCeilingUsd = ceilingUsd ?? resolveCeilingUsd(null);
|
|
1545
|
+
|
|
1546
|
+
const step = steps[state.stepIndex];
|
|
1547
|
+
const askSlot = askLines.get(step.fromLine);
|
|
1548
|
+
const priorId = (step.reads ?? [])[0];
|
|
1549
|
+
const priorStepIndex = steps.findIndex((s) => s.emits === priorId);
|
|
1550
|
+
const priorArtifact = readArtifact(runDir, priorId);
|
|
1551
|
+
|
|
1552
|
+
const oneShotAskStep = makeOneShotThenParkAskStep({ decision: answer.decision, reason: answer.reason });
|
|
1553
|
+
|
|
1554
|
+
const askResult = await runAskSlot({
|
|
1555
|
+
step,
|
|
1556
|
+
stepIndex: state.stepIndex,
|
|
1557
|
+
askSlot,
|
|
1558
|
+
priorId,
|
|
1559
|
+
priorStep: steps[priorStepIndex],
|
|
1560
|
+
priorArtifact,
|
|
1561
|
+
redoCap,
|
|
1562
|
+
effectiveCeilingUsd,
|
|
1563
|
+
capUsd,
|
|
1564
|
+
primitives,
|
|
1565
|
+
businessDate,
|
|
1566
|
+
modelStep,
|
|
1567
|
+
askStep: oneShotAskStep,
|
|
1568
|
+
spent,
|
|
1569
|
+
spendComplete,
|
|
1570
|
+
recordAudit,
|
|
1571
|
+
evidenceUnjudged: state.evidenceUnjudged ?? [],
|
|
1572
|
+
unjudgedCount: state.unjudgedCount ?? 0,
|
|
1573
|
+
redone: typeof state.redone === 'number' ? state.redone : 0,
|
|
1574
|
+
runDir,
|
|
1575
|
+
flowDir,
|
|
1576
|
+
runId,
|
|
1577
|
+
flowRoot: root,
|
|
1578
|
+
flowName: name,
|
|
1579
|
+
signatureHash: state.signatureHash,
|
|
1580
|
+
inputsManifest: state.inputsManifest,
|
|
1581
|
+
attemptsLog,
|
|
1582
|
+
artifacts,
|
|
1583
|
+
now,
|
|
1584
|
+
startedAt,
|
|
1585
|
+
runStartedAt,
|
|
1586
|
+
});
|
|
1587
|
+
|
|
1588
|
+
if (askResult.type === 'paused') return askResult.result;
|
|
1589
|
+
if (askResult.type === 'halted') {
|
|
1590
|
+
return haltRun({
|
|
1591
|
+
flowDir, runDir, runId, capUsd, startedAt: runStartedAt, now, nowMs: getNowMs, signatureHash: state.signatureHash, spent, priorSpendComplete: spendComplete.value, attempts: attemptsLog, artifacts, outcome: askResult.outcome, red: askResult.red,
|
|
1592
|
+
});
|
|
1593
|
+
}
|
|
1594
|
+
|
|
1595
|
+
// accepted — write the ask step's own artifact, then fold on to
|
|
1596
|
+
// whatever comes next (another signed ask parks again; the ordinary
|
|
1597
|
+
// send/step path completes exactly as `runFlow` would have, in-process).
|
|
1598
|
+
writeArtifact(runDir, step.emits, askResult.artifact);
|
|
1599
|
+
artifacts[step.emits] = askResult.artifact;
|
|
1600
|
+
acceptedAskEmitsThisRun.add(step.emits);
|
|
1601
|
+
|
|
1602
|
+
const result = await foldFromStep({
|
|
1603
|
+
i0: state.stepIndex + 1,
|
|
1604
|
+
steps,
|
|
1605
|
+
askLines,
|
|
1606
|
+
sendLines,
|
|
1607
|
+
askStepEmits,
|
|
1608
|
+
runDir,
|
|
1609
|
+
flowDir,
|
|
1610
|
+
runId,
|
|
1611
|
+
flowRoot: root,
|
|
1612
|
+
flowName: name,
|
|
1613
|
+
signatureHash: state.signatureHash,
|
|
1614
|
+
inputsManifest: state.inputsManifest,
|
|
1615
|
+
capUsd,
|
|
1616
|
+
redoCap,
|
|
1617
|
+
effectiveCeilingUsd,
|
|
1618
|
+
primitives,
|
|
1619
|
+
businessDate,
|
|
1620
|
+
modelStep,
|
|
1621
|
+
// A resumed run never waits in-process — any FURTHER signed ask it
|
|
1622
|
+
// reaches parks immediately too, under its own signed ttl.
|
|
1623
|
+
askStep: makeParkingAskStep(),
|
|
1624
|
+
sendStep,
|
|
1625
|
+
now,
|
|
1626
|
+
startedAt,
|
|
1627
|
+
runStartedAt,
|
|
1628
|
+
nowMs: getNowMs,
|
|
1629
|
+
spent,
|
|
1630
|
+
spendComplete,
|
|
1631
|
+
artifacts,
|
|
1632
|
+
acceptedThisRun: true,
|
|
1633
|
+
acceptedAskEmitsThisRun,
|
|
1634
|
+
unjudgedSinceLastAsk: [],
|
|
1635
|
+
recordAudit,
|
|
1636
|
+
attemptsLog,
|
|
1637
|
+
});
|
|
1638
|
+
|
|
1639
|
+
if (result.outcome === 'complete') return { ...result, auditRows };
|
|
1640
|
+
return result;
|
|
1641
|
+
} finally {
|
|
1642
|
+
try { closeSync(lockFd); } catch { /* already closed */ }
|
|
1643
|
+
try { unlinkSync(lockPath); } catch { /* already gone */ }
|
|
1644
|
+
}
|
|
1645
|
+
}
|
|
1646
|
+
|
|
903
1647
|
/** log.json's one writer, called from every exit path (complete + every
|
|
904
1648
|
* halt) — M2 scope item 9 / the M0 ruling: what the model wrote, every
|
|
905
1649
|
* attempt, red runs included, never just the final artifacts. */
|
|
@@ -915,6 +1659,7 @@ function writeLog(runDir, payload) {
|
|
|
915
1659
|
* @param {number|null} opts.capUsd
|
|
916
1660
|
* @param {number} opts.startedAt
|
|
917
1661
|
* @param {() => string} opts.now
|
|
1662
|
+
* @param {() => number} [opts.nowMs] - F45 finding 3; defaults to `Date.now`.
|
|
918
1663
|
* @param {string} opts.outcome
|
|
919
1664
|
* @param {string} [opts.red]
|
|
920
1665
|
* @param {{ value: number }} opts.spent
|
|
@@ -925,12 +1670,22 @@ function writeLog(runDir, payload) {
|
|
|
925
1670
|
* history row carries it, halts included). A halt before the signature was
|
|
926
1671
|
* read/verified (the pre-`readFlow`-success refused path, and any halt
|
|
927
1672
|
* before `signature` comes into scope) keeps the default `null`.
|
|
1673
|
+
* @param {boolean} [opts.priorSpendComplete] - orchestrator review fix (4):
|
|
1674
|
+
* a floor carried in from BEFORE this halt (e.g. a pre-park row, or an
|
|
1675
|
+
* earlier attempt this run, that already left `spendComplete: false`).
|
|
1676
|
+
* ANDed with this halt's own outcome-based verdict — once false, always
|
|
1677
|
+
* false. Defaults to `true` (every pre-existing call site is unaffected).
|
|
928
1678
|
*/
|
|
929
1679
|
function haltRun({
|
|
930
|
-
flowDir, runDir, runId, capUsd, startedAt, now, outcome, red, spent, attempts = [], artifacts = {}, signatureHash = null,
|
|
1680
|
+
flowDir, runDir, runId, capUsd, startedAt, now, nowMs = Date.now, outcome, red, spent, attempts = [], artifacts = {}, signatureHash = null,
|
|
1681
|
+
priorSpendComplete = true,
|
|
931
1682
|
}) {
|
|
932
|
-
|
|
933
|
-
|
|
1683
|
+
// F45 finding 3: `startedAt` here is always the RUN's start (every caller
|
|
1684
|
+
// now passes `runStartedAt` under this key — see call sites), so `wallMs`
|
|
1685
|
+
// times the whole run, pauses included, never just the halting process.
|
|
1686
|
+
const wallMs = nowMs() - startedAt;
|
|
1687
|
+
const spendComplete = priorSpendComplete
|
|
1688
|
+
&& outcome !== 'provider-red' && outcome !== 'pricing-red' && outcome !== 'cap-halt';
|
|
934
1689
|
mkdirSync(flowDir, { recursive: true });
|
|
935
1690
|
appendHistory(flowDir, {
|
|
936
1691
|
runId, at: now(), outcome, spentUsd: spent.value, spendComplete, capUsd: capUsd ?? null, wallMs, signatureHash,
|