@juicesharp/rpiv-workflow 1.17.0 → 1.18.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 +56 -15
- package/api.ts +1 -1
- package/audit.ts +42 -7
- package/built-ins.ts +46 -2
- package/command-run.ts +132 -0
- package/command.ts +29 -100
- package/docs/workflow-authoring.md +23 -23
- package/extension.ts +18 -0
- package/fanout.ts +11 -5
- package/host.ts +26 -13
- package/index.ts +40 -134
- package/internal-utils.ts +35 -0
- package/internal.ts +1 -1
- package/iterate.ts +20 -8
- package/lifecycle.ts +1 -1
- package/load/index.ts +5 -1
- package/messages.ts +34 -0
- package/package.json +9 -3
- package/registration.ts +113 -0
- package/runner/by-name.test.ts +95 -0
- package/runner/by-name.ts +76 -0
- package/runner/by-run-id.test.ts +115 -0
- package/runner/by-run-id.ts +92 -0
- package/runner/chain-advance.ts +22 -42
- package/runner/index.ts +10 -1
- package/runner/resume-fanout.test.ts +331 -0
- package/runner/resume-fanout.ts +136 -0
- package/runner/resume-iterate.test.ts +444 -0
- package/runner/resume-iterate.ts +110 -0
- package/runner/resume.test.ts +1130 -0
- package/runner/resume.ts +333 -0
- package/runner/runner.ts +281 -91
- package/runner/script-stage.ts +18 -51
- package/runner/stage-lifecycle.ts +35 -27
- package/sessions/extraction.ts +4 -4
- package/sessions/sessions.ts +22 -40
- package/sessions/spawn.ts +15 -11
- package/startup.ts +9 -0
- package/state/index.ts +1 -0
- package/state/reads.ts +20 -0
- package/state/state.ts +1 -0
- package/types.ts +18 -13
|
@@ -0,0 +1,444 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* End-to-end iterate-resume tests — drive `resumeWorkflow` with a mock session chain
|
|
3
|
+
* over a real iterate workflow. Complements the pure-fold cases in resume.test.ts.
|
|
4
|
+
*
|
|
5
|
+
* The generator reads the FROZEN review artifact for its phase list, so these tests
|
|
6
|
+
* exercise entry-artifact reconstruction, accumulation reconstruction, pull resumption,
|
|
7
|
+
* the boundary determinism guard, and chain continuation together.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
11
|
+
import { tmpdir } from "node:os";
|
|
12
|
+
import { join } from "node:path";
|
|
13
|
+
import { createMockSessionChain, mockAssistantMessage } from "@juicesharp/rpiv-test-utils";
|
|
14
|
+
import { Type } from "typebox";
|
|
15
|
+
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
|
16
|
+
import { acts, type FanoutFn, gate, type IterateFn, produces, type Workflow } from "../api.js";
|
|
17
|
+
import { fs as fsHandle } from "../handle.js";
|
|
18
|
+
import type { OutputSpec } from "../output.js";
|
|
19
|
+
import { eq, gt } from "../predicates.js";
|
|
20
|
+
import { appendStage, readAllStages, type WorkflowHeader, type WorkflowStage, writeHeader } from "../state/index.js";
|
|
21
|
+
import { typeboxSchema } from "../typebox-adapter.js";
|
|
22
|
+
import { resumeWorkflow } from "./runner.js";
|
|
23
|
+
|
|
24
|
+
let tmpDir: string;
|
|
25
|
+
beforeEach(() => {
|
|
26
|
+
tmpDir = mkdtempSync(join(tmpdir(), "rpiv-iterate-resume-"));
|
|
27
|
+
});
|
|
28
|
+
afterEach(() => {
|
|
29
|
+
rmSync(tmpDir, { recursive: true, force: true });
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
const header: WorkflowHeader = {
|
|
33
|
+
runId: "2026-06-03_08-00-00-cd34",
|
|
34
|
+
workflow: "polish",
|
|
35
|
+
input: "Ship it",
|
|
36
|
+
ts: "2026-06-03T08:00:00Z",
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
const REVIEW_3_PHASES = "# Review\n\n### Phase 1 — Alpha\nx\n### Phase 2 — Beta\ny\n### Phase 3 — Gamma\nz\n";
|
|
40
|
+
|
|
41
|
+
const writeArtifact = (rel: string, body: string) => {
|
|
42
|
+
mkdirSync(join(tmpDir, ...rel.split("/").slice(0, -1)), { recursive: true });
|
|
43
|
+
writeFileSync(join(tmpDir, rel), body);
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
const PATTERN = /\.rpiv\/artifacts\/[\w.-]+\/[\w.-]+\.md/g;
|
|
47
|
+
|
|
48
|
+
/** Transcript-scan outcome (rpiv-pi convention, inlined). Emits matched paths as artifacts. */
|
|
49
|
+
const makeOutcome = (name: string): OutputSpec<unknown, "artifact-md", Record<string, unknown>> => ({
|
|
50
|
+
name,
|
|
51
|
+
collector: {
|
|
52
|
+
collect: (ctx) => {
|
|
53
|
+
const matches: string[] = [];
|
|
54
|
+
for (let i = Math.max(ctx.branchOffset ?? 0, 0); i < ctx.branch.length; i++) {
|
|
55
|
+
const entry = ctx.branch[i]!;
|
|
56
|
+
if (entry.type !== "message" || entry.message?.role !== "assistant") continue;
|
|
57
|
+
const content = entry.message.content;
|
|
58
|
+
if (!Array.isArray(content)) continue;
|
|
59
|
+
for (const part of content) {
|
|
60
|
+
if (part.type === "text" && typeof part.text === "string") {
|
|
61
|
+
const m = part.text.match(PATTERN);
|
|
62
|
+
if (m) matches.push(...m);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
if (matches.length === 0) return { kind: "fatal", message: `${ctx.skill} produced no artifact path` };
|
|
67
|
+
return { kind: "ok", artifacts: matches.map((p) => ({ handle: fsHandle(p), role: "primary" as const })) };
|
|
68
|
+
},
|
|
69
|
+
},
|
|
70
|
+
parser: { parse: () => ({ kind: "ok", payload: { kind: "artifact-md", data: {} } }) },
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
/** Deterministic per-phase generator keyed off the frozen review file (mirror iterate.test.ts). */
|
|
74
|
+
const reviewPhaseIterate: IterateFn = ({ artifact, index, cwd }) => {
|
|
75
|
+
if (artifact?.handle.kind !== "fs") return null;
|
|
76
|
+
const abs = artifact.handle.path.startsWith("/") ? artifact.handle.path : join(cwd, artifact.handle.path);
|
|
77
|
+
const phases = [...readFileSync(abs, "utf-8").matchAll(/^### Phase (\d+) — (.+)$/gm)];
|
|
78
|
+
if (index >= phases.length) return null;
|
|
79
|
+
const num = phases[index]![1];
|
|
80
|
+
return { prompt: `plan phase ${num}`, label: `phase ${index + 1}/${phases.length}`, id: `phase-${num}` };
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
// review (produces "reviews") -> blueprint (iterate, produces "plans") -> consume.
|
|
84
|
+
const polishWf = (iterate: IterateFn = reviewPhaseIterate): Workflow =>
|
|
85
|
+
({
|
|
86
|
+
name: "polish",
|
|
87
|
+
start: "review",
|
|
88
|
+
stages: {
|
|
89
|
+
review: produces({ outcome: makeOutcome("reviews") }),
|
|
90
|
+
blueprint: produces({ outcome: makeOutcome("plans"), iterate }),
|
|
91
|
+
consume: acts(),
|
|
92
|
+
},
|
|
93
|
+
edges: { review: "blueprint", blueprint: "consume", consume: "stop" },
|
|
94
|
+
}) as Workflow;
|
|
95
|
+
|
|
96
|
+
const artifactOutput = (stage: string, num: number, rel: string): WorkflowStage["output"] => ({
|
|
97
|
+
kind: "artifacts",
|
|
98
|
+
artifacts: [{ handle: fsHandle(rel), role: "primary" }],
|
|
99
|
+
data: {},
|
|
100
|
+
meta: { stage, stageNumber: num, ts: "", runId: "" },
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
/** A recorded blueprint iterate-unit row. `phase` is the unit's phase number (== its `id`). */
|
|
104
|
+
const planRow = (phase: number, num: number, status: "completed" | "failed"): WorkflowStage => ({
|
|
105
|
+
stageNumber: num,
|
|
106
|
+
stage: `blueprint (phase-${phase})`,
|
|
107
|
+
skill: "blueprint",
|
|
108
|
+
status,
|
|
109
|
+
ts: `t${num}`,
|
|
110
|
+
...(status === "completed"
|
|
111
|
+
? { output: artifactOutput("blueprint", num, `.rpiv/artifacts/plans/p${phase}.md`) }
|
|
112
|
+
: { errMsg: "boom" }),
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
const reviewRow: WorkflowStage = {
|
|
116
|
+
stageNumber: 1,
|
|
117
|
+
stage: "review",
|
|
118
|
+
skill: "review",
|
|
119
|
+
status: "completed",
|
|
120
|
+
ts: "t1",
|
|
121
|
+
output: artifactOutput("review", 1, ".rpiv/artifacts/reviews/rev.md"),
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
function writeRun(stages: WorkflowStage[]): void {
|
|
125
|
+
writeArtifact(".rpiv/artifacts/reviews/rev.md", REVIEW_3_PHASES);
|
|
126
|
+
writeHeader(tmpDir, header);
|
|
127
|
+
for (const s of stages) appendStage(tmpDir, header.runId, s);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
describe("iterate-resume", () => {
|
|
131
|
+
it("mid-iterate failure: re-pulls + re-runs the failed unit + remaining, then chains to consume/stop", async () => {
|
|
132
|
+
writeRun([reviewRow, planRow(1, 2, "completed"), planRow(2, 3, "failed")]);
|
|
133
|
+
const chain = createMockSessionChain({
|
|
134
|
+
cwd: tmpDir,
|
|
135
|
+
steps: [
|
|
136
|
+
{ branch: [mockAssistantMessage("wrote .rpiv/artifacts/plans/p2.md")] }, // phase-2 re-run
|
|
137
|
+
{ branch: [mockAssistantMessage("wrote .rpiv/artifacts/plans/p3.md")] }, // phase-3
|
|
138
|
+
{ branch: [mockAssistantMessage("consumed")] }, // consume
|
|
139
|
+
],
|
|
140
|
+
});
|
|
141
|
+
const result = await resumeWorkflow(chain.ctx, { workflow: polishWf(), header, ref: "@x" });
|
|
142
|
+
expect(result.success).toBe(true);
|
|
143
|
+
// phase-2 (re-run), phase-3, consume — phase-1 NOT re-run.
|
|
144
|
+
expect(chain.sentMessages).toEqual([
|
|
145
|
+
"/skill:blueprint plan phase 2",
|
|
146
|
+
"/skill:blueprint plan phase 3",
|
|
147
|
+
expect.stringContaining("consume"),
|
|
148
|
+
]);
|
|
149
|
+
const rows = readAllStages(tmpDir, header.runId);
|
|
150
|
+
expect(rows[rows.length - 1]).toMatchObject({ stage: "consume", status: "completed" });
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
it("process died mid-iterate (no failure row): resumes at the next pull", async () => {
|
|
154
|
+
writeRun([reviewRow, planRow(1, 2, "completed")]);
|
|
155
|
+
const chain = createMockSessionChain({
|
|
156
|
+
cwd: tmpDir,
|
|
157
|
+
steps: [
|
|
158
|
+
{ branch: [mockAssistantMessage("wrote .rpiv/artifacts/plans/p2.md")] },
|
|
159
|
+
{ branch: [mockAssistantMessage("wrote .rpiv/artifacts/plans/p3.md")] },
|
|
160
|
+
{ branch: [mockAssistantMessage("consumed")] },
|
|
161
|
+
],
|
|
162
|
+
});
|
|
163
|
+
const result = await resumeWorkflow(chain.ctx, { workflow: polishWf(), header, ref: "@x" });
|
|
164
|
+
expect(result.success).toBe(true);
|
|
165
|
+
expect(chain.sentMessages.slice(0, 2)).toEqual([
|
|
166
|
+
"/skill:blueprint plan phase 2",
|
|
167
|
+
"/skill:blueprint plan phase 3",
|
|
168
|
+
]);
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
it("fully-completed iterate trailer: no-op, routes onward, no new blueprint sessions", async () => {
|
|
172
|
+
// All 3 phases done; trailer is the last completed unit (process died before advanceChain).
|
|
173
|
+
writeRun([reviewRow, planRow(1, 2, "completed"), planRow(2, 3, "completed"), planRow(3, 4, "completed")]);
|
|
174
|
+
const chain = createMockSessionChain({
|
|
175
|
+
cwd: tmpDir,
|
|
176
|
+
steps: [{ branch: [mockAssistantMessage("consumed")] }],
|
|
177
|
+
});
|
|
178
|
+
const result = await resumeWorkflow(chain.ctx, { workflow: polishWf(), header, ref: "@x" });
|
|
179
|
+
expect(result.success).toBe(true);
|
|
180
|
+
// Only `consume` ran; no blueprint re-pull dispatched.
|
|
181
|
+
expect(chain.sentMessages).toEqual([expect.stringContaining("consume")]);
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
it("non-deterministic IterateFn: boundary mismatch records terminal failure, runs no unit", async () => {
|
|
185
|
+
// Recorded run had `phase-2` failing; the workflow now recomputes a differently-tagged unit.
|
|
186
|
+
const drifted: IterateFn = ({ index }) =>
|
|
187
|
+
index >= 3 ? null : { prompt: "x", label: `task ${index}`, id: `task-${index}` };
|
|
188
|
+
writeRun([reviewRow, planRow(1, 2, "completed"), planRow(2, 3, "failed")]);
|
|
189
|
+
const chain = createMockSessionChain({ cwd: tmpDir, steps: [] });
|
|
190
|
+
const result = await resumeWorkflow(chain.ctx, { workflow: polishWf(drifted), header, ref: "@x" });
|
|
191
|
+
expect(result.success).toBe(false);
|
|
192
|
+
expect(result.error).toMatch(/deterministic/);
|
|
193
|
+
expect(result.runId).toBe(header.runId); // in-run failure → row written
|
|
194
|
+
const rows = readAllStages(tmpDir, header.runId);
|
|
195
|
+
expect(rows[rows.length - 1]).toMatchObject({ stage: "blueprint", status: "failed" });
|
|
196
|
+
expect(chain.sentMessages).toEqual([]); // no unit dispatched
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
it("paren-tolerant boundary guard: a unit label with parens resumes (full-string decoration compare)", async () => {
|
|
200
|
+
// Units carry parens in their label, so the decorated row key is `blueprint (phase (N))`.
|
|
201
|
+
// The boundary guard compares full decorated strings, so the inner parens don't false-mismatch.
|
|
202
|
+
const parenIterate: IterateFn = ({ index }) =>
|
|
203
|
+
index >= 2 ? null : { prompt: `do ${index}`, label: `phase (${index})` };
|
|
204
|
+
const wf: Workflow = {
|
|
205
|
+
name: "paren",
|
|
206
|
+
start: "blueprint",
|
|
207
|
+
stages: {
|
|
208
|
+
blueprint: produces({ outcome: makeOutcome("plans"), iterate: parenIterate }),
|
|
209
|
+
consume: acts(),
|
|
210
|
+
},
|
|
211
|
+
edges: { blueprint: "consume", consume: "stop" },
|
|
212
|
+
} as Workflow;
|
|
213
|
+
// Recorded: unit 0 completed, unit 1 (the boundary) failed.
|
|
214
|
+
writeHeader(tmpDir, header);
|
|
215
|
+
appendStage(tmpDir, header.runId, {
|
|
216
|
+
stageNumber: 1,
|
|
217
|
+
stage: "blueprint (phase (0))",
|
|
218
|
+
skill: "blueprint",
|
|
219
|
+
status: "completed",
|
|
220
|
+
ts: "t1",
|
|
221
|
+
output: artifactOutput("blueprint", 1, ".rpiv/artifacts/plans/p0.md"),
|
|
222
|
+
});
|
|
223
|
+
appendStage(tmpDir, header.runId, {
|
|
224
|
+
stageNumber: 2,
|
|
225
|
+
stage: "blueprint (phase (1))",
|
|
226
|
+
skill: "blueprint",
|
|
227
|
+
status: "failed",
|
|
228
|
+
ts: "t2",
|
|
229
|
+
errMsg: "boom",
|
|
230
|
+
});
|
|
231
|
+
const chain = createMockSessionChain({
|
|
232
|
+
cwd: tmpDir,
|
|
233
|
+
steps: [
|
|
234
|
+
{ branch: [mockAssistantMessage("wrote .rpiv/artifacts/plans/p1.md")] }, // phase (1) re-run
|
|
235
|
+
{ branch: [mockAssistantMessage("consumed")] },
|
|
236
|
+
],
|
|
237
|
+
});
|
|
238
|
+
const result = await resumeWorkflow(chain.ctx, { workflow: wf, header, ref: "@x" });
|
|
239
|
+
expect(result.success).toBe(true); // no false mismatch despite the inner parens
|
|
240
|
+
expect(chain.sentMessages).toEqual(["/skill:blueprint do 1", expect.stringContaining("consume")]);
|
|
241
|
+
});
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
// ---------------------------------------------------------------------------
|
|
245
|
+
// Corrective back-edge resume — a gated loop (code-review → blueprint) ran a
|
|
246
|
+
// SECOND iterate generation that died mid-way. Resume must continue only the
|
|
247
|
+
// trailing generation while `state.named.plans` carries BOTH generations.
|
|
248
|
+
// ---------------------------------------------------------------------------
|
|
249
|
+
|
|
250
|
+
describe("iterate-resume — corrective back-edge", () => {
|
|
251
|
+
let loopDir: string;
|
|
252
|
+
beforeEach(() => {
|
|
253
|
+
loopDir = mkdtempSync(join(tmpdir(), "rpiv-iterate-resume-loop-"));
|
|
254
|
+
});
|
|
255
|
+
afterEach(() => {
|
|
256
|
+
rmSync(loopDir, { recursive: true, force: true });
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
const loopHeader: WorkflowHeader = {
|
|
260
|
+
runId: "2026-06-03_09-00-00-ef56",
|
|
261
|
+
workflow: "polish-loop",
|
|
262
|
+
input: "Ship it",
|
|
263
|
+
ts: "2026-06-03T09:00:00Z",
|
|
264
|
+
};
|
|
265
|
+
const REVIEW_2_PHASES = "# Review\n\n### Phase 1 — A\nx\n### Phase 2 — B\ny\n";
|
|
266
|
+
|
|
267
|
+
const writeLoopArtifact = (rel: string, body: string) => {
|
|
268
|
+
mkdirSync(join(loopDir, ...rel.split("/").slice(0, -1)), { recursive: true });
|
|
269
|
+
writeFileSync(join(loopDir, rel), body);
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
/** Sources the review from state.named (robust to the rolling primary being the code-review doc on re-entry). */
|
|
273
|
+
const reviewFromState: IterateFn = ({ state, index, cwd }) => {
|
|
274
|
+
const review = state.named.architecture_reviews?.at(-1)?.artifacts.find((a) => a.handle.kind === "fs");
|
|
275
|
+
if (review?.handle.kind !== "fs") return null;
|
|
276
|
+
const abs = review.handle.path.startsWith("/") ? review.handle.path : join(cwd, review.handle.path);
|
|
277
|
+
const phases = [...readFileSync(abs, "utf-8").matchAll(/^### Phase (\d+) — (.+)$/gm)];
|
|
278
|
+
if (index >= phases.length) return null;
|
|
279
|
+
const num = phases[index]![1];
|
|
280
|
+
return {
|
|
281
|
+
prompt: `${review.handle.path} Phase ${num}`,
|
|
282
|
+
label: `phase ${index + 1}/${phases.length}`,
|
|
283
|
+
id: `phase-${num}`,
|
|
284
|
+
};
|
|
285
|
+
};
|
|
286
|
+
|
|
287
|
+
const transcriptOutcome = (name: string): OutputSpec<unknown, "artifact-md", Record<string, unknown>> => ({
|
|
288
|
+
name,
|
|
289
|
+
collector: {
|
|
290
|
+
collect: (ctx) => {
|
|
291
|
+
const matches: string[] = [];
|
|
292
|
+
for (let i = Math.max(ctx.branchOffset ?? 0, 0); i < ctx.branch.length; i++) {
|
|
293
|
+
const entry = ctx.branch[i]!;
|
|
294
|
+
if (entry.type !== "message" || entry.message?.role !== "assistant") continue;
|
|
295
|
+
const content = entry.message.content;
|
|
296
|
+
if (!Array.isArray(content)) continue;
|
|
297
|
+
for (const part of content) {
|
|
298
|
+
if (part.type === "text" && typeof part.text === "string") {
|
|
299
|
+
const m = part.text.match(PATTERN);
|
|
300
|
+
if (m) matches.push(...m);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
if (matches.length === 0) return { kind: "fatal", message: `${ctx.skill} produced no artifact path` };
|
|
305
|
+
return { kind: "ok", artifacts: matches.map((p) => ({ handle: fsHandle(p), role: "primary" as const })) };
|
|
306
|
+
},
|
|
307
|
+
},
|
|
308
|
+
parser: { parse: () => ({ kind: "ok", payload: { kind: "artifact-md", data: {} } }) },
|
|
309
|
+
});
|
|
310
|
+
|
|
311
|
+
/** Like transcriptOutcome but parses blockers_count from the artifact's frontmatter (drives the gate). */
|
|
312
|
+
const blockersOutcome = (name: string): OutputSpec<unknown, "artifact-md", Record<string, unknown>> => ({
|
|
313
|
+
name,
|
|
314
|
+
collector: transcriptOutcome(name).collector,
|
|
315
|
+
parser: {
|
|
316
|
+
parse: (ctx) => {
|
|
317
|
+
const primary = ctx.artifacts[0];
|
|
318
|
+
if (primary?.handle.kind !== "fs") return { kind: "ok", payload: { kind: "artifact-md", data: {} } };
|
|
319
|
+
const abs = primary.handle.path.startsWith("/") ? primary.handle.path : join(ctx.cwd, primary.handle.path);
|
|
320
|
+
const m = readFileSync(abs, "utf-8").match(/blockers_count:\s*(\d+)/);
|
|
321
|
+
return { kind: "ok", payload: { kind: "artifact-md", data: { blockers_count: Number(m?.[1] ?? 0) } } };
|
|
322
|
+
},
|
|
323
|
+
},
|
|
324
|
+
});
|
|
325
|
+
|
|
326
|
+
const plansFanout: FanoutFn = ({ state }) =>
|
|
327
|
+
(state.named.plans ?? [])
|
|
328
|
+
.flatMap((o) => o.artifacts)
|
|
329
|
+
.filter((a) => a.handle.kind === "fs")
|
|
330
|
+
.map((a, i) => ({ prompt: a.handle.kind === "fs" ? a.handle.path : "", label: `plan ${i + 1}` }));
|
|
331
|
+
|
|
332
|
+
const loopOutput = (stage: string, num: number, rel: string): WorkflowStage["output"] => ({
|
|
333
|
+
kind: "artifacts",
|
|
334
|
+
artifacts: [{ handle: fsHandle(rel), role: "primary" }],
|
|
335
|
+
data: {},
|
|
336
|
+
meta: { stage, stageNumber: num, ts: "", runId: "" },
|
|
337
|
+
});
|
|
338
|
+
|
|
339
|
+
it("resumes the trailing generation only; state.named.plans keeps both generations", async () => {
|
|
340
|
+
writeLoopArtifact(".rpiv/artifacts/architecture_reviews/rev.md", REVIEW_2_PHASES);
|
|
341
|
+
writeLoopArtifact(".rpiv/artifacts/reviews/cr2.md", "---\nblockers_count: 0\n---\n");
|
|
342
|
+
|
|
343
|
+
// Recorded trail: gen 1 (2 plans) → code-review (blockers=1, looped) → gen 2 phase-1 done, phase-2 died.
|
|
344
|
+
writeHeader(loopDir, loopHeader);
|
|
345
|
+
const rows: WorkflowStage[] = [
|
|
346
|
+
{
|
|
347
|
+
stageNumber: 1,
|
|
348
|
+
stage: "review",
|
|
349
|
+
skill: "review",
|
|
350
|
+
status: "completed",
|
|
351
|
+
ts: "t1",
|
|
352
|
+
output: loopOutput("review", 1, ".rpiv/artifacts/architecture_reviews/rev.md"),
|
|
353
|
+
},
|
|
354
|
+
{
|
|
355
|
+
stageNumber: 2,
|
|
356
|
+
stage: "blueprint (phase-1)",
|
|
357
|
+
skill: "blueprint",
|
|
358
|
+
status: "completed",
|
|
359
|
+
ts: "t2",
|
|
360
|
+
output: loopOutput("blueprint", 2, ".rpiv/artifacts/plans/g1p1.md"),
|
|
361
|
+
},
|
|
362
|
+
{
|
|
363
|
+
stageNumber: 3,
|
|
364
|
+
stage: "blueprint (phase-2)",
|
|
365
|
+
skill: "blueprint",
|
|
366
|
+
status: "completed",
|
|
367
|
+
ts: "t3",
|
|
368
|
+
output: loopOutput("blueprint", 3, ".rpiv/artifacts/plans/g1p2.md"),
|
|
369
|
+
},
|
|
370
|
+
{
|
|
371
|
+
stageNumber: 4,
|
|
372
|
+
stage: "code-review",
|
|
373
|
+
skill: "code-review",
|
|
374
|
+
status: "completed",
|
|
375
|
+
ts: "t4",
|
|
376
|
+
output: loopOutput("code-review", 4, ".rpiv/artifacts/reviews/cr1.md"),
|
|
377
|
+
},
|
|
378
|
+
{
|
|
379
|
+
stageNumber: 5,
|
|
380
|
+
stage: "blueprint (phase-1)",
|
|
381
|
+
skill: "blueprint",
|
|
382
|
+
status: "completed",
|
|
383
|
+
ts: "t5",
|
|
384
|
+
output: loopOutput("blueprint", 5, ".rpiv/artifacts/plans/g2p1.md"),
|
|
385
|
+
},
|
|
386
|
+
{
|
|
387
|
+
stageNumber: 6,
|
|
388
|
+
stage: "blueprint (phase-2)",
|
|
389
|
+
skill: "blueprint",
|
|
390
|
+
status: "failed",
|
|
391
|
+
ts: "t6",
|
|
392
|
+
errMsg: "boom",
|
|
393
|
+
},
|
|
394
|
+
];
|
|
395
|
+
for (const s of rows) appendStage(loopDir, loopHeader.runId, s);
|
|
396
|
+
|
|
397
|
+
const chain = createMockSessionChain({
|
|
398
|
+
cwd: loopDir,
|
|
399
|
+
steps: [
|
|
400
|
+
{ branch: [mockAssistantMessage("wrote .rpiv/artifacts/plans/g2p2.md")] }, // gen-2 phase-2 re-run
|
|
401
|
+
{ branch: [mockAssistantMessage("wrote .rpiv/artifacts/reviews/cr2.md")] }, // code-review → blockers=0
|
|
402
|
+
// consume fanout: one unit per accumulated plan (4 total).
|
|
403
|
+
{ branch: [mockAssistantMessage("impl 1")] },
|
|
404
|
+
{ branch: [mockAssistantMessage("impl 2")] },
|
|
405
|
+
{ branch: [mockAssistantMessage("impl 3")] },
|
|
406
|
+
{ branch: [mockAssistantMessage("impl 4")] },
|
|
407
|
+
],
|
|
408
|
+
});
|
|
409
|
+
|
|
410
|
+
const wf: Workflow = {
|
|
411
|
+
name: "polish-loop",
|
|
412
|
+
start: "review",
|
|
413
|
+
stages: {
|
|
414
|
+
review: produces({ outcome: transcriptOutcome("architecture_reviews") }),
|
|
415
|
+
blueprint: produces({ outcome: transcriptOutcome("plans"), iterate: reviewFromState }),
|
|
416
|
+
"code-review": produces({
|
|
417
|
+
outcome: blockersOutcome("reviews"),
|
|
418
|
+
outputSchema: typeboxSchema(Type.Object({ blockers_count: Type.Number() })),
|
|
419
|
+
}),
|
|
420
|
+
consume: acts({ fanout: plansFanout }),
|
|
421
|
+
},
|
|
422
|
+
edges: {
|
|
423
|
+
review: "blueprint",
|
|
424
|
+
blueprint: "code-review",
|
|
425
|
+
"code-review": gate("blockers_count", { blueprint: gt(0), consume: eq(0) }),
|
|
426
|
+
consume: "stop",
|
|
427
|
+
},
|
|
428
|
+
} as Workflow;
|
|
429
|
+
|
|
430
|
+
const result = await resumeWorkflow(chain.ctx, { workflow: wf, header: loopHeader, ref: "@x" });
|
|
431
|
+
|
|
432
|
+
expect(result.success).toBe(true);
|
|
433
|
+
// Only the trailing generation's remaining unit (phase-2) re-ran — phase-1 of gen 2 did NOT.
|
|
434
|
+
const blueprintMsgs = chain.sentMessages.filter((m) => m.startsWith("/skill:blueprint"));
|
|
435
|
+
expect(blueprintMsgs).toEqual(["/skill:blueprint .rpiv/artifacts/architecture_reviews/rev.md Phase 2"]);
|
|
436
|
+
// The consume fanout saw ALL FOUR plans — state.named["plans"] carried both generations.
|
|
437
|
+
expect(chain.sentMessages.slice(-4)).toEqual([
|
|
438
|
+
"/skill:consume .rpiv/artifacts/plans/g1p1.md",
|
|
439
|
+
"/skill:consume .rpiv/artifacts/plans/g1p2.md",
|
|
440
|
+
"/skill:consume .rpiv/artifacts/plans/g2p1.md",
|
|
441
|
+
"/skill:consume .rpiv/artifacts/plans/g2p2.md",
|
|
442
|
+
]);
|
|
443
|
+
});
|
|
444
|
+
});
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Iterate-resume dispatch. When a resumed run's trail trailer is a `def.iterate`
|
|
3
|
+
* unit row, `resumeWorkflow` routes here instead of the single-stage arms.
|
|
4
|
+
*
|
|
5
|
+
* Re-enters `runIterate` at the next pull index using the reconstructed entry
|
|
6
|
+
* artifact + accumulated prefix (`reconstructState`'s `iterateProgress` — the
|
|
7
|
+
* TRAILING generation only). The pull model re-derives each remaining unit from
|
|
8
|
+
* `accumulated`, so resume only needs the prefix, not a stored unit list.
|
|
9
|
+
*
|
|
10
|
+
* REQUIRES the IterateFn to be deterministic w.r.t. its entry artifact +
|
|
11
|
+
* accumulated outputs. We guard the ONE checkable boundary: a failed trailer unit
|
|
12
|
+
* recorded the decoration of the unit that was about to run, so the re-pulled unit
|
|
13
|
+
* at `index = accumulated.length` must match it. Earlier completed units are NOT
|
|
14
|
+
* replayed (the generator sees a mutating `state` per unit; faithful intermediate
|
|
15
|
+
* replay is infeasible) — the contract covers them.
|
|
16
|
+
*
|
|
17
|
+
* `deps` are injected by `resumeWorkflow` (the same primitives `tryIterate` injects),
|
|
18
|
+
* so this module mirrors `runIterate`'s primitive-injection shape and imports no cycle
|
|
19
|
+
* back into the session layer.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import type { IterateUnit, StageDef } from "../api.js";
|
|
23
|
+
import { auditCtxFor, iterateRowStage, recordTerminalFailure } from "../audit.js";
|
|
24
|
+
import type { IterateDeps } from "../iterate.js";
|
|
25
|
+
import { runIterate } from "../iterate.js";
|
|
26
|
+
import { skillStageRef } from "../lifecycle.js";
|
|
27
|
+
import { ERR_RESUME_ITERATE_MISMATCH, MSG_RESUME_ITERATE_MISMATCH } from "../messages.js";
|
|
28
|
+
import type { RunContext, WorkflowHostContext } from "../types.js";
|
|
29
|
+
import type { IterateResumePoint } from "./resume.js";
|
|
30
|
+
import { lifecycleCtxFor } from "./runner.js";
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Resume an iterate stage whose trailing-generation units are a completed prefix
|
|
34
|
+
* `1..k` (with the failure/cutoff at `k+1`). `point` is `reconstructState`'s
|
|
35
|
+
* `iterateProgress` entry for this parent. `pendingDecorated` is the failed trailer
|
|
36
|
+
* unit's decorated `stage` string when the run died ON a unit (the boundary-guard
|
|
37
|
+
* input); undefined when the process died between units (no recorded next unit).
|
|
38
|
+
*
|
|
39
|
+
* `idx` is the display/audit index (the trailer unit row's `stageNumber - 1`),
|
|
40
|
+
* consistent with the single-stage arms. Routing keys on the parent NAME, not `idx`.
|
|
41
|
+
*/
|
|
42
|
+
export async function resumeIterateStage(
|
|
43
|
+
ctx: WorkflowHostContext,
|
|
44
|
+
parent: string,
|
|
45
|
+
idx: number,
|
|
46
|
+
point: IterateResumePoint,
|
|
47
|
+
pendingDecorated: string | undefined,
|
|
48
|
+
run: RunContext,
|
|
49
|
+
deps: IterateDeps,
|
|
50
|
+
): Promise<void> {
|
|
51
|
+
const def = run.workflow.stages[parent]!; // caller verified parent is an iterate stage
|
|
52
|
+
const skill = def.skill ?? parent; // mirror resolveStage; aliased nodes tag rows with the skill body
|
|
53
|
+
|
|
54
|
+
// Pre-pull the next unit ONCE to branch: drift-guard + already-complete no-op.
|
|
55
|
+
const next = await pullNextUnit(def, point, run);
|
|
56
|
+
|
|
57
|
+
// Boundary determinism guard: if the run died on a unit, the recomputed unit must
|
|
58
|
+
// match the recorded decoration. A different (or null) unit means the IterateFn drifted.
|
|
59
|
+
if (pendingDecorated !== undefined) {
|
|
60
|
+
const recomputed = next ? iterateRowStage(parent, next.id ?? next.label) : undefined;
|
|
61
|
+
if (recomputed !== pendingDecorated) {
|
|
62
|
+
await recordIterateDriftFailure(ctx, run, parent, skill);
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// Generation already complete (generator now terminates at index=accumulated.length)
|
|
68
|
+
// → route onward, no re-announce, no toast (mirror fanout's silent no-op path).
|
|
69
|
+
if (!next) {
|
|
70
|
+
await deps.advanceAfter(ctx, parent, idx, run);
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// Re-fire onStageStart for listener coherence (mirror tryIterate; onStageEnd fires
|
|
75
|
+
// per unit inside runStageSession). Then re-enter the pull loop — runIterate re-pulls
|
|
76
|
+
// the same unit (a second, harmless deterministic call) and runs the remaining units;
|
|
77
|
+
// advanceAfter → advanceChain carries the chain onward.
|
|
78
|
+
await run.lifecycle.fire(ctx, "onStageStart", skillStageRef(parent, idx + 1, skill), lifecycleCtxFor(run));
|
|
79
|
+
await runIterate(ctx, idx, parent, skill, def, point.entryArtifact, point.accumulated, run, deps);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Re-derive the unit at the resume index — the same call `runIterate` makes (idempotent, deterministic). */
|
|
83
|
+
function pullNextUnit(
|
|
84
|
+
def: StageDef,
|
|
85
|
+
point: IterateResumePoint,
|
|
86
|
+
run: RunContext,
|
|
87
|
+
): Promise<IterateUnit | null> | IterateUnit | null {
|
|
88
|
+
return def.iterate!({
|
|
89
|
+
cwd: run.cwd,
|
|
90
|
+
artifact: point.entryArtifact,
|
|
91
|
+
state: run.state,
|
|
92
|
+
accumulated: point.accumulated,
|
|
93
|
+
index: point.accumulated.length,
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Record the terminal failure for a non-deterministic IterateFn (boundary drift). */
|
|
98
|
+
function recordIterateDriftFailure(
|
|
99
|
+
ctx: WorkflowHostContext,
|
|
100
|
+
run: RunContext,
|
|
101
|
+
parent: string,
|
|
102
|
+
skill: string,
|
|
103
|
+
): Promise<void> {
|
|
104
|
+
return recordTerminalFailure(ctx, auditCtxFor(run, parent, skill), {
|
|
105
|
+
status: "failed",
|
|
106
|
+
notifyMsg: MSG_RESUME_ITERATE_MISMATCH(parent),
|
|
107
|
+
notifyLevel: "error",
|
|
108
|
+
errMsg: ERR_RESUME_ITERATE_MISMATCH(parent),
|
|
109
|
+
});
|
|
110
|
+
}
|