@juicesharp/rpiv-workflow 1.19.1 → 1.20.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/README.md +81 -8
- package/api.ts +18 -703
- package/audit-rows.ts +136 -0
- package/audit.ts +139 -126
- package/built-ins.ts +20 -45
- package/chain-state.ts +169 -0
- package/command-run.ts +31 -3
- package/command.ts +116 -20
- package/docs/workflow-authoring.md +322 -61
- package/{lifecycle.ts → events.ts} +119 -35
- package/host.ts +30 -0
- package/index.ts +25 -81
- package/internal-utils.ts +92 -78
- package/internal.ts +21 -1
- package/judge.ts +229 -0
- package/layers.ts +10 -15
- package/load/alias.ts +6 -12
- package/load/cache.ts +9 -6
- package/load/index.ts +16 -109
- package/load/issues.ts +31 -0
- package/load/legacy.ts +102 -0
- package/load/merge.ts +2 -2
- package/load/shape-guards.test.ts +4 -1
- package/load/shape-guards.ts +3 -6
- package/load/skill-contract-phase.ts +94 -0
- package/loop-constructors.ts +623 -0
- package/loop-def.ts +240 -0
- package/loop-kinds.ts +493 -0
- package/loop.ts +304 -0
- package/messages.ts +225 -157
- package/outcomes/collectors/directory-path.ts +7 -3
- package/outcomes/collectors/require-opt.ts +11 -0
- package/outcomes/collectors/tool-call.test.ts +3 -1
- package/outcomes/collectors/tool-call.ts +8 -3
- package/outcomes/collectors/transcript-path.ts +2 -3
- package/outcomes/collectors/union.test.ts +54 -0
- package/outcomes/collectors/union.ts +28 -9
- package/outcomes/collectors/url.ts +7 -0
- package/outcomes/collectors/workspace-diff.test.ts +13 -0
- package/outcomes/collectors/workspace-diff.ts +21 -14
- package/outcomes/exec.ts +17 -0
- package/outcomes/git-commit.test.ts +76 -30
- package/outcomes/git-commit.ts +139 -100
- package/outcomes/index.ts +1 -0
- package/outcomes/parsers/json-body.ts +2 -2
- package/outcomes/side-effect.ts +3 -3
- package/output-spec.ts +36 -10
- package/output.ts +40 -20
- package/package.json +13 -7
- package/predicates.ts +11 -8
- package/preview.ts +77 -17
- package/registration.ts +109 -35
- package/routing-dsl.ts +310 -0
- package/routing.ts +2 -2
- package/runner/by-name.ts +2 -1
- package/runner/by-run-id.ts +2 -1
- package/runner/chain-advance.ts +59 -44
- package/runner/errors.ts +33 -0
- package/runner/failure.ts +109 -0
- package/runner/header-write-failure.test.ts +64 -0
- package/runner/index.ts +7 -13
- package/runner/input-validation.ts +11 -21
- package/runner/preflight.ts +173 -0
- package/runner/resolve-stage.ts +68 -0
- package/runner/resume-entry.ts +101 -0
- package/runner/resume-loop.test.ts +1410 -0
- package/runner/resume-loop.ts +110 -0
- package/runner/resume-session.test.ts +400 -0
- package/runner/resume.test.ts +881 -206
- package/runner/resume.ts +281 -261
- package/runner/run-context.ts +161 -0
- package/runner/run-stage.ts +456 -0
- package/runner/runner.ts +59 -400
- package/runner/script-stage.ts +103 -105
- package/schema-compat.ts +13 -1
- package/sessions/extraction.ts +53 -31
- package/sessions/index.ts +3 -1
- package/sessions/locate.test.ts +77 -0
- package/sessions/locate.ts +90 -0
- package/sessions/reattach.ts +63 -0
- package/sessions/sessions.ts +130 -127
- package/skill-contract.ts +22 -25
- package/skill-contracts/composition.ts +88 -37
- package/skill-contracts/{registries.ts → extension-points.ts} +45 -12
- package/skill-contracts/harvest.ts +2 -3
- package/skill-contracts/index.ts +15 -8
- package/skill-contracts/registry.ts +33 -50
- package/stage-def.ts +527 -0
- package/startup.ts +3 -1
- package/state/index.ts +8 -1
- package/state/names.ts +91 -65
- package/state/paths.ts +12 -0
- package/state/raw.ts +78 -0
- package/state/reads.ts +103 -85
- package/state/resolve.ts +73 -0
- package/state/state.ts +112 -15
- package/state/writes.ts +29 -12
- package/transcript.ts +24 -0
- package/triggers.ts +11 -3
- package/types.ts +202 -44
- package/validate/contract-compat.ts +193 -0
- package/validate/graph.ts +125 -0
- package/validate/issue.ts +314 -0
- package/validate/stage-rules.ts +420 -0
- package/validate-output.ts +69 -1
- package/validate-workflow.ts +55 -759
- package/control-flow.ts +0 -135
- package/fanout.ts +0 -102
- package/iterate.ts +0 -155
- package/runner/resume-fanout.test.ts +0 -331
- package/runner/resume-fanout.ts +0 -136
- package/runner/resume-iterate.test.ts +0 -444
- package/runner/resume-iterate.ts +0 -111
- package/runner/stage-lifecycle.ts +0 -500
package/runner/resume.ts
CHANGED
|
@@ -1,333 +1,353 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* State reconstruction for resuming a
|
|
3
|
-
*
|
|
2
|
+
* State reconstruction for resuming a run. ONE async fold over the JSONL
|
|
3
|
+
* trail: rows with `parent` set are loop-unit rows (the structured machine
|
|
4
|
+
* channel — the decorated `stage` string is never parsed); everything else
|
|
5
|
+
* folds as a normal stage.
|
|
4
6
|
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
7
|
+
* THE REPLAY CONTRACT: a loop's unit source must be deterministic w.r.t. the
|
|
8
|
+
* fold-replayed `RunState` at the unit boundary + this generation's
|
|
9
|
+
* accumulated outputs. Because the fold replays rows in trail order, at row
|
|
10
|
+
* *i* the state is byte-identical to what the live driver saw — so the fold
|
|
11
|
+
* verifies EVERY unit row against the recomputed expectation (strictly
|
|
12
|
+
* stronger than the old per-primitive half-guards). Drift (or a generator
|
|
13
|
+
* throw) does not refuse outright: the fold finishes applying so state is
|
|
14
|
+
* complete, and returns `drift` — `resumeWorkflow`'s entry thunk records the
|
|
15
|
+
* terminal failure with full lifecycle bracketing and zero dispatch.
|
|
9
16
|
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
* generation's `accumulated` prefix + frozen entry artifact for the resume
|
|
19
|
-
* dispatch. This REQUIRES the IterateFn to be deterministic w.r.t. its entry
|
|
20
|
-
* artifact + accumulated outputs — `resume-iterate.ts` guards only the ONE
|
|
21
|
-
* checkable boundary (the re-pulled next unit vs the failed trailer's recorded
|
|
22
|
-
* decoration); the already-completed prefix is covered by that contract, not
|
|
23
|
-
* replayed (the generator sees a mutating `state` per unit, so faithful
|
|
24
|
-
* intermediate replay is infeasible).
|
|
17
|
+
* Generations: contiguous unit rows sharing a `parent`. A generation opens by
|
|
18
|
+
* freezing the entry pair from the replayed state (and, for fanout,
|
|
19
|
+
* recomputing the unit list ONCE against it); it closes when a non-unit row
|
|
20
|
+
* (or a different parent) appears — `projectResult` (the driver's own
|
|
21
|
+
* function) lands the declared result, exactly like the live loop advance.
|
|
22
|
+
* The TRAILING open generation is returned un-projected as a
|
|
23
|
+
* `LoopResumePoint` whose `cursor` is the driver's own `LoopCursor` —
|
|
24
|
+
* re-entry hands it straight back to `runLoop`.
|
|
25
25
|
*/
|
|
26
26
|
|
|
27
|
-
import type { StageDef, Workflow } from "../api.js";
|
|
27
|
+
import type { LoopDef, StageDef, Unit, Workflow } from "../api.js";
|
|
28
|
+
import { applyStageSuccess } from "../audit-rows.js";
|
|
29
|
+
import { stageEntryArgs } from "../chain-state.js";
|
|
28
30
|
import type { Artifact } from "../handle.js";
|
|
29
|
-
import {
|
|
31
|
+
import { formatError } from "../internal-utils.js";
|
|
32
|
+
import { panelMembers } from "../judge.js";
|
|
33
|
+
import { projectResult, publishPanelVerdict } from "../loop.js";
|
|
34
|
+
import { effectiveLoopOf } from "../loop-constructors.js";
|
|
35
|
+
import { advanceCursor, freshCursor, judgeStageDef, type LoopCursor, loopStrategyOf } from "../loop-kinds.js";
|
|
36
|
+
import { ERR_RESUME_LOOP_MISMATCH } from "../messages.js";
|
|
30
37
|
import type { Output } from "../output.js";
|
|
31
|
-
import {
|
|
32
|
-
|
|
38
|
+
import {
|
|
39
|
+
readAllStagesForResume,
|
|
40
|
+
STATE_SCHEMA_VERSION,
|
|
41
|
+
type WorkflowHeader,
|
|
42
|
+
type WorkflowStage,
|
|
43
|
+
} from "../state/index.js";
|
|
33
44
|
import type { RunState } from "../types.js";
|
|
45
|
+
import { freshRunState } from "./run-context.js";
|
|
34
46
|
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
/**
|
|
40
|
-
* Per-fanout-parent record of the TRAILING generation's COMPLETED unit rows, in
|
|
41
|
-
* trail order, as their decorated `WorkflowStage.stage` strings (`"impl (phase 1/4)"`).
|
|
42
|
-
* Consumed by `resumeFanoutStage` to compute the resume point + guard FanoutFn
|
|
43
|
-
* determinism by full-string comparison. A failed unit row is NOT recorded here
|
|
44
|
-
* (it's the `k+1` that resume re-runs). On a looped fanout the array resets per
|
|
45
|
-
* generation, so a second-pass resume compares only the second pass's prefix.
|
|
46
|
-
*/
|
|
47
|
-
export type FanoutProgress = ReadonlyMap<string, readonly string[]>;
|
|
48
|
-
|
|
49
|
-
/**
|
|
50
|
-
* Per-iterate-parent resume point — the TRAILING contiguous generation's state.
|
|
51
|
-
* Consumed by `resumeIterateStage` to re-enter the pull loop.
|
|
52
|
-
*
|
|
53
|
-
* - `entryArtifact` — the primary FROZEN at the generation's first unit (units
|
|
54
|
-
* roll the primary forward, so the rebuilt `state.primaryArtifact` is the LAST
|
|
55
|
-
* unit's artifact, not this). `undefined` if the iterate stage was the entry.
|
|
56
|
-
* - `accumulated` — the completed `Output`s of the trailing generation, in order
|
|
57
|
-
* (the IterateFn pull prefix; `index` resumes at `accumulated.length`). A failed
|
|
58
|
-
* unit contributes nothing (it's the unit resume re-pulls + re-runs).
|
|
59
|
-
*
|
|
60
|
-
* Reset whenever a non-iterate row (or a different parent) breaks contiguity, so a
|
|
61
|
-
* corrective-loop second pass overwrites the first pass's point. `state.named` still
|
|
62
|
-
* accumulates across ALL generations — only this prefix resets.
|
|
63
|
-
*/
|
|
64
|
-
export interface IterateResumePoint {
|
|
47
|
+
/** Trailing open generation — everything `resume-loop.ts` needs to re-enter `runLoop`. */
|
|
48
|
+
export interface LoopResumePoint {
|
|
49
|
+
parent: string;
|
|
65
50
|
entryArtifact: Artifact | undefined;
|
|
66
|
-
|
|
51
|
+
entryPair: { output: Output | undefined; primaryArtifact: Artifact | undefined };
|
|
52
|
+
/**
|
|
53
|
+
* Round-0 producer arg, FROZEN at generation open (assess-kind loops only;
|
|
54
|
+
* `""` otherwise). `undefined` = the trail no longer carries the rows that
|
|
55
|
+
* published this stage's inputs (truncated/corrupted) — re-entry records a
|
|
56
|
+
* refusal instead of dispatching with a wrong arg.
|
|
57
|
+
*/
|
|
58
|
+
entryArgs: string | undefined;
|
|
59
|
+
/** The driver's own cursor, reconstructed: next (role, index), accumulated, lastProduce, lastVerdict. */
|
|
60
|
+
cursor: LoopCursor;
|
|
61
|
+
/** Fanout: the recomputed-and-verified unit list (re-entry reuses it — no second compute). */
|
|
62
|
+
units?: readonly Unit[];
|
|
67
63
|
}
|
|
68
|
-
export type IterateProgress = ReadonlyMap<string, IterateResumePoint>;
|
|
69
64
|
|
|
70
65
|
export type ReconstructResult =
|
|
71
66
|
| {
|
|
72
67
|
ok: true;
|
|
73
68
|
state: RunState;
|
|
74
69
|
lastStageNumber: number;
|
|
70
|
+
/**
|
|
71
|
+
* 0-based chain index of the trail's LAST activation — the fold's
|
|
72
|
+
* reconstruction of the `idx` the live chain was at (one activation per
|
|
73
|
+
* top-level stage row or loop generation; a resume re-run of a failed
|
|
74
|
+
* stage keeps its index). NOT `stageNumber - 1`: the allocator counts
|
|
75
|
+
* every row including loop units, so the two diverge past any loop.
|
|
76
|
+
*/
|
|
77
|
+
lastChainIndex: number;
|
|
75
78
|
visited: Set<string>;
|
|
76
79
|
rows: WorkflowStage[];
|
|
77
|
-
|
|
78
|
-
|
|
80
|
+
/** Open generation at trail end, un-projected (the driver projects at its advance). */
|
|
81
|
+
trailing?: LoopResumePoint;
|
|
82
|
+
/** Guard tripped mid-fold — the resume entry records this as a terminal failure. */
|
|
83
|
+
drift?: { parent: string; errMsg: string };
|
|
79
84
|
}
|
|
80
|
-
| { ok: false; reason: "no-rows" | "stage-gone"; detail: string };
|
|
81
|
-
|
|
82
|
-
// ---------------------------------------------------------------------------
|
|
83
|
-
// Fanout-decoration helpers (shared with resumeWorkflow dispatch)
|
|
84
|
-
// ---------------------------------------------------------------------------
|
|
85
|
+
| { ok: false; reason: "no-rows" | "stage-gone" | "malformed-row" | "version-mismatch"; detail: string };
|
|
85
86
|
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
for (const [name, def] of Object.entries(workflow.stages)) {
|
|
99
|
-
if (def.iterate) names.add(name);
|
|
100
|
-
}
|
|
101
|
-
return names;
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
/**
|
|
105
|
-
* Recover the parent stage name from a decorated unit-row key. Matches the
|
|
106
|
-
* `fanoutRowStage`/`iterateRowStage` projection (`${parent} (${id ?? label})`,
|
|
107
|
-
* audit.ts:57,69) with an exact `${parent} (` prefix + `)` suffix. The space
|
|
108
|
-
* before `(` disambiguates prefix-name collisions (`"build-extra (x)"` does NOT
|
|
109
|
-
* start with `"build ("`); identifier-style stage names never contain `" ("`,
|
|
110
|
-
* so at most one parent matches. Returns undefined for a non-decorated key.
|
|
111
|
-
*/
|
|
112
|
-
export function matchFanoutParent(stageKey: string, parents: ReadonlySet<string>): string | undefined {
|
|
113
|
-
if (!stageKey.endsWith(")")) return undefined;
|
|
114
|
-
for (const parent of parents) {
|
|
115
|
-
if (stageKey.startsWith(`${parent} (`)) return parent;
|
|
116
|
-
}
|
|
117
|
-
return undefined;
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
// ---------------------------------------------------------------------------
|
|
121
|
-
// Reconstruction fold
|
|
122
|
-
// ---------------------------------------------------------------------------
|
|
123
|
-
|
|
124
|
-
/**
|
|
125
|
-
* Rebuild `RunState` by folding over the completed stage rows in a run's
|
|
126
|
-
* JSONL audit trail. Returns a discriminated result so the entry point
|
|
127
|
-
* (`resumeWorkflow`) maps refusals to error envelopes.
|
|
128
|
-
*
|
|
129
|
-
* Rules:
|
|
130
|
-
* - A row whose `stage` is a real `workflow.stages` key → fold as a normal
|
|
131
|
-
* stage (completed rows seed via `applyCompletedStage`; non-completed rows
|
|
132
|
-
* bump counters only). A bare `def.iterate`-parent row is never written by
|
|
133
|
-
* the runner; should one exist it folds harmlessly here (iterate mandates
|
|
134
|
-
* `kind: "produces"`).
|
|
135
|
-
* - A row whose `stage` is NOT a key — a decorated unit row, a renamed
|
|
136
|
-
* stage, or a removed one:
|
|
137
|
-
* - matches a `def.fanout` parent → fold counters-only (mirror the
|
|
138
|
-
* live `recordFanoutSuccess`: bump `stagesCompleted` on a completed
|
|
139
|
-
* row, add parent to `visited`, advance `lastStageNumber`; NO
|
|
140
|
-
* `applyCompletedStage`, NO `state.output` write) + record the
|
|
141
|
-
* completed decorated string under the parent in `fanoutProgress`,
|
|
142
|
-
* resetting that prefix on a new generation (a looped fanout).
|
|
143
|
-
* - matches a `def.iterate` parent → fold as a full produces pass
|
|
144
|
-
* (`foldIterateUnit`): roll the primary, append to `state.named`, set
|
|
145
|
-
* `state.output`, bump counters, and track the trailing generation's
|
|
146
|
-
* `accumulated` + frozen entry artifact in `iterateProgress`.
|
|
147
|
-
* - no match → refuse `stage-gone`.
|
|
148
|
-
*/
|
|
149
|
-
export function reconstructState(cwd: string, workflow: Workflow, header: WorkflowHeader): ReconstructResult {
|
|
150
|
-
const rows = readAllStages(cwd, header.runId);
|
|
151
|
-
|
|
152
|
-
if (rows.length === 0) {
|
|
153
|
-
return { ok: false, reason: "no-rows", detail: header.runId };
|
|
87
|
+
export async function reconstructState(
|
|
88
|
+
cwd: string,
|
|
89
|
+
workflow: Workflow,
|
|
90
|
+
header: WorkflowHeader,
|
|
91
|
+
): Promise<ReconstructResult> {
|
|
92
|
+
// Version gate first: the fold replays rows under the CURRENT shapes, so a
|
|
93
|
+
// file written under a different schema version must refuse cleanly rather
|
|
94
|
+
// than mis-replay. Absent `v` = version 1 (pre-field files) — see
|
|
95
|
+
// STATE_SCHEMA_VERSION's back-compat rule.
|
|
96
|
+
const v = header.v ?? 1;
|
|
97
|
+
if (v !== STATE_SCHEMA_VERSION) {
|
|
98
|
+
return { ok: false, reason: "version-mismatch", detail: `run ${header.runId} was written under schema v${v}` };
|
|
154
99
|
}
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
100
|
+
// Strict reader: a stage-shaped row failing the deep guard REFUSES here —
|
|
101
|
+
// the fold replays the trail as its system of record, so a silently
|
|
102
|
+
// skipped row would replay a hole and route onward past it.
|
|
103
|
+
const read = readAllStagesForResume(cwd, header.runId);
|
|
104
|
+
if (!read.ok) return { ok: false, reason: "malformed-row", detail: read.detail };
|
|
105
|
+
const rows = read.rows;
|
|
106
|
+
if (rows.length === 0) return { ok: false, reason: "no-rows", detail: header.runId };
|
|
158
107
|
|
|
159
108
|
const acc: FoldAcc = {
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
primaryArtifact: undefined,
|
|
163
|
-
output: undefined,
|
|
164
|
-
named: {},
|
|
165
|
-
stagesCompleted: 0,
|
|
166
|
-
lastAllocatedStageNumber: 0,
|
|
167
|
-
telemetry: { backwardJumps: 0, droppedRoutingRows: [] },
|
|
168
|
-
termination: { success: false, error: undefined },
|
|
169
|
-
},
|
|
109
|
+
cwd,
|
|
110
|
+
state: freshRunState(header.input),
|
|
170
111
|
visited: new Set<string>(),
|
|
171
|
-
fanoutProgress: new Map<string, string[]>(),
|
|
172
|
-
iterateProgress: new Map<string, IterateResumePoint>(),
|
|
173
|
-
lastFoldedUnitParent: undefined,
|
|
174
112
|
lastStageNumber: 0,
|
|
113
|
+
chainIndex: -1,
|
|
114
|
+
prevNode: undefined,
|
|
115
|
+
gen: undefined,
|
|
116
|
+
drift: undefined,
|
|
175
117
|
};
|
|
176
118
|
|
|
177
119
|
for (const row of rows) {
|
|
120
|
+
if (row.parent !== undefined) {
|
|
121
|
+
const refusal = await foldUnitRow(acc, workflow, row);
|
|
122
|
+
if (refusal) return refusal;
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
closeGeneration(acc);
|
|
178
126
|
const def = workflow.stages[row.stage];
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
127
|
+
// Unknown key refuses — including LEGACY decorated rows (pre-redesign
|
|
128
|
+
// runs carry no `parent`, so their unit rows land here): stage-gone.
|
|
129
|
+
if (!def) return { ok: false, reason: "stage-gone", detail: row.stage };
|
|
130
|
+
noteChainNode(acc, row.stage, row.status !== "completed");
|
|
131
|
+
foldKnownStage(acc, def, row);
|
|
183
132
|
}
|
|
184
133
|
|
|
185
|
-
acc.state.lastAllocatedStageNumber = acc.lastStageNumber; // allocator continues monotonically
|
|
134
|
+
acc.state.lastAllocatedStageNumber = acc.lastStageNumber; // allocator continues monotonically
|
|
186
135
|
|
|
187
136
|
return {
|
|
188
137
|
ok: true,
|
|
189
138
|
state: acc.state,
|
|
190
139
|
lastStageNumber: acc.lastStageNumber,
|
|
140
|
+
lastChainIndex: acc.chainIndex,
|
|
191
141
|
visited: acc.visited,
|
|
192
142
|
rows,
|
|
193
|
-
|
|
194
|
-
|
|
143
|
+
trailing: acc.gen ? toPoint(acc.gen) : undefined,
|
|
144
|
+
drift: acc.drift,
|
|
195
145
|
};
|
|
196
146
|
}
|
|
197
147
|
|
|
198
148
|
// ---------------------------------------------------------------------------
|
|
199
|
-
//
|
|
149
|
+
// Fold internals
|
|
200
150
|
// ---------------------------------------------------------------------------
|
|
201
151
|
|
|
202
|
-
|
|
152
|
+
interface OpenGeneration {
|
|
153
|
+
parent: string;
|
|
154
|
+
loop: LoopDef;
|
|
155
|
+
/** Parent stage def — produce-row apply (judge rows apply via judgeStageDef). */
|
|
156
|
+
def: StageDef;
|
|
157
|
+
entryArtifact: Artifact | undefined;
|
|
158
|
+
entryPair: { output: Output | undefined; primaryArtifact: Artifact | undefined };
|
|
159
|
+
/** Frozen at generation open — see LoopResumePoint.entryArgs. */
|
|
160
|
+
entryArgs: string | undefined;
|
|
161
|
+
cursor: LoopCursor;
|
|
162
|
+
units?: readonly Unit[];
|
|
163
|
+
/**
|
|
164
|
+
* Cached expected unit for the cursor's CURRENT index (iterate pulls once
|
|
165
|
+
* per index — a failed row followed by its resumed re-run row re-checks
|
|
166
|
+
* the same expectation without double-pulling the generator).
|
|
167
|
+
*/
|
|
168
|
+
expected?: { index: number; tag: string | undefined };
|
|
169
|
+
}
|
|
170
|
+
|
|
203
171
|
interface FoldAcc {
|
|
172
|
+
cwd: string;
|
|
204
173
|
state: RunState;
|
|
205
174
|
visited: Set<string>;
|
|
206
|
-
fanoutProgress: Map<string, string[]>;
|
|
207
|
-
iterateProgress: Map<string, IterateResumePoint>;
|
|
208
|
-
/** Parent of the immediately-preceding folded row IF it was a fanout OR iterate unit; else undefined. Drives generation reset for both. */
|
|
209
|
-
lastFoldedUnitParent: string | undefined;
|
|
210
175
|
lastStageNumber: number;
|
|
176
|
+
/** 0-based index of the current activation — see `ReconstructResult.lastChainIndex`. */
|
|
177
|
+
chainIndex: number;
|
|
178
|
+
/**
|
|
179
|
+
* Last chain-node activation. `reentrant` = a following row of the SAME
|
|
180
|
+
* stage continues this activation instead of opening a new one: a
|
|
181
|
+
* failed/aborted/skipped row (resume re-runs it at the same index) or a
|
|
182
|
+
* loop generation (its halt row and any resume re-entry belong to it).
|
|
183
|
+
*/
|
|
184
|
+
prevNode: { stage: string; reentrant: boolean } | undefined;
|
|
185
|
+
gen: OpenGeneration | undefined;
|
|
186
|
+
drift: { parent: string; errMsg: string } | undefined;
|
|
211
187
|
}
|
|
212
188
|
|
|
213
|
-
/**
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
refuse: true,
|
|
219
|
-
reason,
|
|
220
|
-
detail,
|
|
221
|
-
});
|
|
189
|
+
/** Advance the chain index for one activation — unless the row continues the previous one. */
|
|
190
|
+
function noteChainNode(acc: FoldAcc, stage: string, reentrant: boolean): void {
|
|
191
|
+
if (!(acc.prevNode?.stage === stage && acc.prevNode.reentrant)) acc.chainIndex++;
|
|
192
|
+
acc.prevNode = { stage, reentrant };
|
|
193
|
+
}
|
|
222
194
|
|
|
223
195
|
/**
|
|
224
|
-
*
|
|
225
|
-
*
|
|
226
|
-
*
|
|
227
|
-
* iterate-parent or fanout-parent row is never written by the runner; should one
|
|
228
|
-
* exist it folds harmlessly here — iterate mandates `kind: "produces"` so
|
|
229
|
-
* `applyCompletedStage` runs, and fanout rows carry no output so the `!row.output`
|
|
230
|
-
* guard skips it. A real-key row always breaks iterate contiguity (it is not a
|
|
231
|
-
* decorated unit), so the generation cursor resets.
|
|
196
|
+
* Normal-stage fold. A completed row replays through `applyStageSuccess` —
|
|
197
|
+
* the same apply the live success persistence runs, minus the I/O (the row
|
|
198
|
+
* is already on disk).
|
|
232
199
|
*/
|
|
233
|
-
function foldKnownStage(acc: FoldAcc, def: StageDef, row: WorkflowStage):
|
|
234
|
-
acc.lastFoldedUnitParent = undefined;
|
|
200
|
+
function foldKnownStage(acc: FoldAcc, def: StageDef, row: WorkflowStage): void {
|
|
235
201
|
acc.visited.add(row.stage);
|
|
236
202
|
acc.lastStageNumber = Math.max(acc.lastStageNumber, row.stageNumber);
|
|
237
|
-
if (row.status !== "completed") return
|
|
238
|
-
acc.state.
|
|
239
|
-
if (!row.output) return FOLD_OK;
|
|
240
|
-
acc.state.output = row.output;
|
|
241
|
-
applyCompletedStage(acc.state, def, row.stage, row.output);
|
|
242
|
-
return FOLD_OK;
|
|
203
|
+
if (row.status !== "completed") return;
|
|
204
|
+
applyStageSuccess(acc.state, def, row.stage, row.output);
|
|
243
205
|
}
|
|
244
206
|
|
|
245
|
-
/**
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
207
|
+
/** Close the open generation: project the declared result — the live loop-advance, replayed. */
|
|
208
|
+
function closeGeneration(acc: FoldAcc): void {
|
|
209
|
+
if (!acc.gen) return;
|
|
210
|
+
projectResult(acc.gen.loop, acc.gen.entryPair, acc.gen.cursor, acc.state);
|
|
211
|
+
acc.gen = undefined;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
async function foldUnitRow(
|
|
252
215
|
acc: FoldAcc,
|
|
253
216
|
workflow: Workflow,
|
|
254
217
|
row: WorkflowStage,
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
)
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
218
|
+
): Promise<Extract<ReconstructResult, { ok: false }> | undefined> {
|
|
219
|
+
// New generation: different parent (or first unit row / after a non-unit row).
|
|
220
|
+
if (!acc.gen || acc.gen.parent !== row.parent) {
|
|
221
|
+
closeGeneration(acc);
|
|
222
|
+
const def = workflow.stages[row.parent!];
|
|
223
|
+
// `effectiveLoopOf` — a verify stage's unit rows recover their synthesized
|
|
224
|
+
// loop here; without it every verify-stage trailer would refuse stage-gone.
|
|
225
|
+
const loop = def ? effectiveLoopOf(def) : undefined;
|
|
226
|
+
if (!def || !loop) return { ok: false, reason: "stage-gone", detail: row.stage };
|
|
227
|
+
// One generation = one chain-node activation. Always reentrant: a halt
|
|
228
|
+
// row for the parent or a resumed re-entry continues this activation.
|
|
229
|
+
noteChainNode(acc, row.parent!, true);
|
|
230
|
+
acc.gen = {
|
|
231
|
+
parent: row.parent!,
|
|
232
|
+
loop,
|
|
233
|
+
def,
|
|
234
|
+
entryArtifact: acc.state.primaryArtifact,
|
|
235
|
+
entryPair: { output: acc.state.output, primaryArtifact: acc.state.primaryArtifact },
|
|
236
|
+
// Frozen HERE: replayed state at generation open is byte-identical to
|
|
237
|
+
// what the live driver saw at loop entry (THE REPLAY CONTRACT) — the
|
|
238
|
+
// only safe place to derive the round-0 arg. `reads` projections in
|
|
239
|
+
// particular must NOT be re-derived post-fold, where the generation's
|
|
240
|
+
// own appends have moved the `.at(-1)` cursors.
|
|
241
|
+
entryArgs: loop.kind === "assess" ? stageEntryArgs(def, row.parent!, workflow.start, acc.state) : "",
|
|
242
|
+
cursor: freshCursor(),
|
|
243
|
+
units: undefined,
|
|
244
|
+
};
|
|
245
|
+
if (loop.kind === "fanout") {
|
|
246
|
+
acc.gen.units = await guarded(acc, acc.gen.parent, () =>
|
|
247
|
+
(loop as Extract<LoopDef, { kind: "fanout" }>).units({
|
|
248
|
+
cwd: acc.cwd,
|
|
249
|
+
artifact: acc.state.primaryArtifact,
|
|
250
|
+
state: acc.state,
|
|
251
|
+
}),
|
|
252
|
+
);
|
|
253
|
+
}
|
|
262
254
|
}
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
255
|
+
|
|
256
|
+
const gen = acc.gen;
|
|
257
|
+
acc.visited.add(gen.parent);
|
|
258
|
+
acc.lastStageNumber = Math.max(acc.lastStageNumber, row.stageNumber);
|
|
259
|
+
|
|
260
|
+
if (!acc.drift) await guardRow(acc, gen, row);
|
|
261
|
+
|
|
262
|
+
if (row.status !== "completed") return undefined; // pending unit — cursor stays (resume re-runs it)
|
|
263
|
+
|
|
264
|
+
if (row.role === "judge" || row.role === "verify") {
|
|
265
|
+
// Apply-then-project: each member verdict rolls the pair TRANSIENTLY
|
|
266
|
+
// (exactly like the live judge unit); projection at generation close
|
|
267
|
+
// restores. The member this row graded is the one the rebuilt sub-state
|
|
268
|
+
// currently points at — `cursor.panel.memberIndex` BEFORE `advanceCursor`
|
|
269
|
+
// bumps it (0 for a single judge, the panel of one). Using that member's
|
|
270
|
+
// own def publishes the verdict to the member's OWN channel, matching the
|
|
271
|
+
// live session path (`judgeStageDef(member)`) per member — `[0]` for every
|
|
272
|
+
// member would have mis-filed members 1..N-1 onto member 0's channel.
|
|
273
|
+
const judgeSlot = (gen.loop as Extract<LoopDef, { kind: "assess" }>).judge;
|
|
274
|
+
const memberIndex = gen.cursor.panel?.memberIndex ?? 0;
|
|
275
|
+
applyStageSuccess(acc.state, judgeStageDef(panelMembers(judgeSlot)[memberIndex]!), row.stage, row.output);
|
|
276
|
+
const role = row.role; // narrowed to "judge" | "verify" — captured for the closure below
|
|
277
|
+
const verdict = row.output;
|
|
278
|
+
if (!verdict) return undefined; // defensive — completed unit rows always carry output
|
|
279
|
+
// `guardRow` already verified `row.unitIndex === cursor.index` (drift
|
|
280
|
+
// otherwise), so the shared transition lands the same cursor the live
|
|
281
|
+
// driver had — and, on the last member, the same folded verdict.
|
|
282
|
+
//
|
|
283
|
+
// `advanceCursor` runs the author fold on the LAST member (`panel.fold`,
|
|
284
|
+
// which a sugar fold's per-member `pred` reaches too), and
|
|
285
|
+
// `publishPanelVerdict` lands it — BOTH behind `guarded()`. A fold/pred
|
|
286
|
+
// throw must become drift (a recorded terminal failure), NOT an unguarded
|
|
287
|
+
// rejection: this fold runs in `reconstructState`, which `resumeWorkflow`
|
|
288
|
+
// awaits BEFORE `executeRun` brackets the lifecycle — an escape here yields
|
|
289
|
+
// no JSONL failure row and no `onWorkflowEnd`. The live driver's same
|
|
290
|
+
// `advanceCursor`+`publishPanelVerdict` pair runs under
|
|
291
|
+
// `runStageOrRecordFailure`'s catch (loop.ts `dispatchUnit`); this is its
|
|
292
|
+
// resume-side error boundary.
|
|
293
|
+
await guarded(acc, gen.parent, () => {
|
|
294
|
+
advanceCursor(gen.cursor, role, verdict, gen.loop);
|
|
295
|
+
// Panel-close publish — the SAME call the live driver makes after the
|
|
296
|
+
// last member's advance, so the folded verdict lands byte-identically.
|
|
297
|
+
publishPanelVerdict(gen.loop, gen.parent, gen.cursor, acc.state);
|
|
298
|
+
});
|
|
299
|
+
return undefined;
|
|
267
300
|
}
|
|
268
|
-
|
|
301
|
+
|
|
302
|
+
// produce row — fanout/iterate units and assess producers alike
|
|
303
|
+
applyStageSuccess(acc.state, gen.def, row.stage, row.output);
|
|
304
|
+
if (!row.output) return undefined; // defensive — completed unit rows always carry output
|
|
305
|
+
advanceCursor(gen.cursor, "produce", row.output, gen.loop);
|
|
306
|
+
gen.expected = undefined; // consumed
|
|
307
|
+
return undefined;
|
|
269
308
|
}
|
|
270
309
|
|
|
271
310
|
/**
|
|
272
|
-
*
|
|
273
|
-
*
|
|
274
|
-
*
|
|
275
|
-
*
|
|
276
|
-
*
|
|
277
|
-
*
|
|
278
|
-
* Generation tracking: a row whose parent differs from the immediately-preceding
|
|
279
|
-
* unit row STARTS a new fanout generation — reset `fanoutProgress[parent]` so a
|
|
280
|
-
* looped fanout's trailing pass overwrites the prior pass's prefix. `stagesCompleted`
|
|
281
|
-
* stays cumulative (it mirrors the live count); only the resume-point array resets.
|
|
282
|
-
* Fanout units never roll the primary, so the reconstructed `state.primaryArtifact`
|
|
283
|
-
* already sits on the trailing generation's entry — no entry-artifact capture (the
|
|
284
|
-
* iterate asymmetry; see resume-iterate.ts).
|
|
311
|
+
* The full-row determinism guard — every unit row is checked against the
|
|
312
|
+
* recomputed expectation at its boundary (the replayed state IS what the live
|
|
313
|
+
* driver saw). The kind-agnostic (role, unitIndex) arithmetic lives here; the
|
|
314
|
+
* per-kind re-check delegates to the strategy table (loop-kinds.ts). Drift
|
|
315
|
+
* marks `acc.drift` and stops guarding; applying continues so the failure can
|
|
316
|
+
* be recorded against complete state.
|
|
285
317
|
*/
|
|
286
|
-
function
|
|
287
|
-
const
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
acc.
|
|
295
|
-
|
|
318
|
+
async function guardRow(acc: FoldAcc, gen: OpenGeneration, row: WorkflowStage): Promise<void> {
|
|
319
|
+
const judgeRole = gen.def.verify ? "verify" : "judge";
|
|
320
|
+
const expectRole = gen.loop.kind === "assess" ? (gen.cursor.phase === "judge" ? judgeRole : "produce") : "produce";
|
|
321
|
+
if (row.role !== expectRole || row.unitIndex !== gen.cursor.index) return setDrift(acc, gen.parent);
|
|
322
|
+
|
|
323
|
+
const matches = await guarded(acc, gen.parent, () =>
|
|
324
|
+
loopStrategyOf(gen.loop.kind).guardExpectation(gen, row, acc.cwd, acc.state),
|
|
325
|
+
);
|
|
326
|
+
if (acc.drift) return;
|
|
327
|
+
if (!matches) setDrift(acc, gen.parent);
|
|
296
328
|
}
|
|
297
329
|
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
* while `state.named` accumulates every generation (matching the live run).
|
|
310
|
-
*
|
|
311
|
-
* `visited` records the PARENT (not the decorated key), mirroring the live
|
|
312
|
-
* `advanceChain` visit + `foldFanoutUnit`. The generation cursor is shared with
|
|
313
|
-
* fanout — a fanout parent and an iterate parent are always distinct keys, so a
|
|
314
|
-
* row of the other kind always reads as a new generation here.
|
|
315
|
-
*/
|
|
316
|
-
function foldIterateUnit(acc: FoldAcc, def: StageDef, parent: string, row: WorkflowStage): void {
|
|
317
|
-
const newGeneration = acc.lastFoldedUnitParent !== parent;
|
|
318
|
-
let point = acc.iterateProgress.get(parent);
|
|
319
|
-
if (newGeneration || !point) {
|
|
320
|
-
point = { entryArtifact: acc.state.primaryArtifact, accumulated: [] };
|
|
321
|
-
acc.iterateProgress.set(parent, point);
|
|
330
|
+
function setDrift(acc: FoldAcc, parent: string): void {
|
|
331
|
+
acc.drift = { parent, errMsg: ERR_RESUME_LOOP_MISMATCH(parent) };
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** Run a user fn during the fold; a throw becomes drift with the thrown reason. */
|
|
335
|
+
async function guarded<T>(acc: FoldAcc, parent: string, fn: () => T | Promise<T>): Promise<T | undefined> {
|
|
336
|
+
try {
|
|
337
|
+
return await fn();
|
|
338
|
+
} catch (e) {
|
|
339
|
+
acc.drift = { parent, errMsg: formatError(e) };
|
|
340
|
+
return undefined;
|
|
322
341
|
}
|
|
323
|
-
|
|
324
|
-
acc.lastStageNumber = Math.max(acc.lastStageNumber, row.stageNumber);
|
|
325
|
-
acc.lastFoldedUnitParent = parent;
|
|
342
|
+
}
|
|
326
343
|
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
344
|
+
function toPoint(gen: OpenGeneration): LoopResumePoint {
|
|
345
|
+
return {
|
|
346
|
+
parent: gen.parent,
|
|
347
|
+
entryArtifact: gen.entryArtifact,
|
|
348
|
+
entryPair: gen.entryPair,
|
|
349
|
+
entryArgs: gen.entryArgs,
|
|
350
|
+
cursor: gen.cursor,
|
|
351
|
+
units: gen.units,
|
|
352
|
+
};
|
|
333
353
|
}
|