@juicesharp/rpiv-workflow 1.19.0 → 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
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Loop-resume dispatch. When a resumed run's trail trailer is a loop-unit
|
|
3
|
+
* row (`row.parent` set), `resumeWorkflow` routes here. The fold already
|
|
4
|
+
* verified EVERY unit row (full-row drift guard) and reconstructed the
|
|
5
|
+
* driver's own `LoopCursor`, so re-entry is: derive the frozen entry arg,
|
|
6
|
+
* announce iff work is pending, hand the cursor back to `runLoop`.
|
|
7
|
+
*
|
|
8
|
+
* All four assess pending paths fall out of `pullNext` with the
|
|
9
|
+
* reconstructed cursor — pending judge (grade without re-running the
|
|
10
|
+
* producer), pending produce with a recovered verdict (feedForward, no
|
|
11
|
+
* re-grade), done-verdict fast advance, and round-0 re-run — zero special
|
|
12
|
+
* cases here.
|
|
13
|
+
*
|
|
14
|
+
* The finished-loop resume is a pinned SILENT no-op: no onStageStart /
|
|
15
|
+
* onLoopStart re-fire, no toast (the driver's `ranThisInvocation` rule keeps
|
|
16
|
+
* the banner off; `hasPendingUnit` keeps the announce off). The iterate
|
|
17
|
+
* probe pull is the documented harmless deterministic double-pull.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { auditCtxFor, failedArgs, recordTerminalFailure } from "../audit.js";
|
|
21
|
+
import { resolveSkill } from "../chain-state.js";
|
|
22
|
+
import { announceLoopStart, type LoopDeps, runLoop } from "../loop.js";
|
|
23
|
+
import { effectiveLoopOf } from "../loop-constructors.js";
|
|
24
|
+
import { type LoopEntry, loopStrategyOf } from "../loop-kinds.js";
|
|
25
|
+
import { FAIL_MISSING_ARTIFACT, MSG_RESUME_LOOP_MISMATCH } from "../messages.js";
|
|
26
|
+
import type { RunContext, WorkflowHostContext } from "../types.js";
|
|
27
|
+
import type { LoopResumePoint } from "./resume.js";
|
|
28
|
+
|
|
29
|
+
export async function resumeLoopStage(
|
|
30
|
+
ctx: WorkflowHostContext,
|
|
31
|
+
point: LoopResumePoint,
|
|
32
|
+
idx: number,
|
|
33
|
+
run: RunContext,
|
|
34
|
+
deps: LoopDeps,
|
|
35
|
+
): Promise<void> {
|
|
36
|
+
const def = run.workflow.stages[point.parent]!; // fold verified the parent carries a loop (or verify)
|
|
37
|
+
const loop = effectiveLoopOf(def)!;
|
|
38
|
+
const skill = resolveSkill(def, point.parent);
|
|
39
|
+
|
|
40
|
+
// Round-0 producer arg (assess-kind only), FROZEN by the fold at generation
|
|
41
|
+
// open — never re-derived from post-fold state, so neither a trailing judge
|
|
42
|
+
// row's transient roll nor the generation's own named appends can leak into
|
|
43
|
+
// it. `undefined` means the trail no longer carries the rows that published
|
|
44
|
+
// this stage's inputs — recorded refusal with the forward preflight's
|
|
45
|
+
// messages (today's posture, now covering `reads` projections too). A
|
|
46
|
+
// prompt-dispatch stage never refuses here: the authority freezes `""` (no
|
|
47
|
+
// skill args exist) and the driver re-resolves the stage's own `prompt` at
|
|
48
|
+
// round-0 dispatch.
|
|
49
|
+
let entryArgs = "";
|
|
50
|
+
if (loop.kind === "assess") {
|
|
51
|
+
if (point.entryArgs === undefined) {
|
|
52
|
+
await recordMissingArtifactFailure(ctx, run, point.parent, skill, idx);
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
entryArgs = point.entryArgs;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const entry: LoopEntry = {
|
|
59
|
+
stageIdx: idx,
|
|
60
|
+
name: point.parent,
|
|
61
|
+
skill,
|
|
62
|
+
def,
|
|
63
|
+
loop,
|
|
64
|
+
entryArtifact: point.entryArtifact,
|
|
65
|
+
entryArgs,
|
|
66
|
+
entryPair: point.entryPair,
|
|
67
|
+
units: point.units, // fanout: the fold's recomputed-and-verified list — no second compute
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
// Pending-work probe (strategy table) gates the announce only — a
|
|
71
|
+
// finished-loop resume stays a pinned SILENT no-op.
|
|
72
|
+
if (await loopStrategyOf(loop.kind).hasPending(loop, point, run)) await announceLoopStart(ctx, run, entry);
|
|
73
|
+
|
|
74
|
+
await runLoop(ctx, entry, point.cursor, run, deps);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Recorded refusal for a corrupted/truncated trail (reuses the forward preflight's messages). */
|
|
78
|
+
function recordMissingArtifactFailure(
|
|
79
|
+
ctx: WorkflowHostContext,
|
|
80
|
+
run: RunContext,
|
|
81
|
+
parent: string,
|
|
82
|
+
skill: string,
|
|
83
|
+
idx: number,
|
|
84
|
+
): Promise<void> {
|
|
85
|
+
return recordTerminalFailure(
|
|
86
|
+
ctx,
|
|
87
|
+
auditCtxFor(run, parent, skill),
|
|
88
|
+
failedArgs(FAIL_MISSING_ARTIFACT(skill, idx + 1)),
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Recorded terminal failure for a fold-detected drift (or a generator throw
|
|
94
|
+
* during the fold). Parent-attributed failed row, zero dispatch — used as
|
|
95
|
+
* the resume ENTRY thunk so lifecycle bracketing (onWorkflowStart/End)
|
|
96
|
+
* matches every other resume outcome.
|
|
97
|
+
*/
|
|
98
|
+
export function recordLoopDriftFailure(
|
|
99
|
+
ctx: WorkflowHostContext,
|
|
100
|
+
run: RunContext,
|
|
101
|
+
parent: string,
|
|
102
|
+
errMsg: string,
|
|
103
|
+
): Promise<void> {
|
|
104
|
+
const skill = resolveSkill(run.workflow.stages[parent]!, parent);
|
|
105
|
+
return recordTerminalFailure(
|
|
106
|
+
ctx,
|
|
107
|
+
auditCtxFor(run, parent, skill),
|
|
108
|
+
failedArgs(MSG_RESUME_LOOP_MISMATCH(parent), errMsg),
|
|
109
|
+
);
|
|
110
|
+
}
|
|
@@ -0,0 +1,400 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session-backed resume — end-to-end through `resumeWorkflow`:
|
|
3
|
+
*
|
|
4
|
+
* - structured dispatch: failed trailer with `session` → promotion path
|
|
5
|
+
* (switchSession); `session: null` → cold re-run (newSession);
|
|
6
|
+
* - PROMOTION: the adopted branch already announces the artifact →
|
|
7
|
+
* completed row, chain advances, nothing sent into the session
|
|
8
|
+
* (issue #70's scenario);
|
|
9
|
+
* - fallback ladder: missing `switchSession` / missing session file →
|
|
10
|
+
* notify + cold re-run;
|
|
11
|
+
* - switchSession cancellation → sessionless skipped row (mirrors the
|
|
12
|
+
* live pre-open cancellation);
|
|
13
|
+
* - REATTACH: promotion miss → REATTACH_PROMPT + waitForIdle + the
|
|
14
|
+
* standard postStage (success persists; a second failure writes a
|
|
15
|
+
* session-backed failure row, keeping the run resumable);
|
|
16
|
+
* - continue-policy stages scope promotion extraction with the PERSISTED
|
|
17
|
+
* `branchOffset`.
|
|
18
|
+
*
|
|
19
|
+
* The host ctx is hand-rolled (not `createMockSessionChain`) because these
|
|
20
|
+
* tests script `switchSession`, which the chain fixture doesn't model.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
24
|
+
import { tmpdir } from "node:os";
|
|
25
|
+
import { join } from "node:path";
|
|
26
|
+
import { mockAssistantMessage } from "@juicesharp/rpiv-test-utils";
|
|
27
|
+
import { Type } from "typebox";
|
|
28
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
29
|
+
import type { Workflow } from "../api.js";
|
|
30
|
+
import { fs as fsHandle } from "../handle.js";
|
|
31
|
+
import type { WorkflowSessionContext } from "../host.js";
|
|
32
|
+
import {
|
|
33
|
+
MSG_RESUME_PROMOTED,
|
|
34
|
+
MSG_RESUME_REATTACHED,
|
|
35
|
+
MSG_RESUME_SESSION_FALLBACK,
|
|
36
|
+
REATTACH_PROMPT,
|
|
37
|
+
} from "../messages.js";
|
|
38
|
+
import type { CollectCtx, Outcome } from "../output-spec.js";
|
|
39
|
+
import {
|
|
40
|
+
appendStage,
|
|
41
|
+
readAllStages,
|
|
42
|
+
type SessionRef,
|
|
43
|
+
type WorkflowHeader,
|
|
44
|
+
type WorkflowStage,
|
|
45
|
+
writeHeader,
|
|
46
|
+
} from "../state/index.js";
|
|
47
|
+
import { lastMatchInBranch } from "../transcript.js";
|
|
48
|
+
import { typeboxSchema } from "../typebox-adapter.js";
|
|
49
|
+
import type { WorkflowHostContext } from "../types.js";
|
|
50
|
+
import { resumeWorkflow } from "./runner.js";
|
|
51
|
+
|
|
52
|
+
// ---------------------------------------------------------------------------
|
|
53
|
+
// Fixtures
|
|
54
|
+
// ---------------------------------------------------------------------------
|
|
55
|
+
|
|
56
|
+
let tmpDir: string;
|
|
57
|
+
|
|
58
|
+
beforeEach(() => {
|
|
59
|
+
tmpDir = mkdtempSync(join(tmpdir(), "rpiv-resume-session-"));
|
|
60
|
+
});
|
|
61
|
+
afterEach(() => {
|
|
62
|
+
rmSync(tmpDir, { recursive: true, force: true });
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
const header: WorkflowHeader = {
|
|
66
|
+
runId: "2026-06-11_09-00-00-ab12",
|
|
67
|
+
workflow: "wf",
|
|
68
|
+
input: "ship it",
|
|
69
|
+
ts: "2026-06-11T09:00:00Z",
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
/** Collector that adopts whatever artifact path the branch announced. */
|
|
73
|
+
const announceOutcome = (collectSpy?: (ctx: CollectCtx) => void): Outcome => ({
|
|
74
|
+
collector: {
|
|
75
|
+
collect: (ctx: CollectCtx) => {
|
|
76
|
+
collectSpy?.(ctx);
|
|
77
|
+
const m = lastMatchInBranch(ctx.branch, /\.rpiv\/artifacts\/\S+\.md/g, ctx.branchOffset);
|
|
78
|
+
return m
|
|
79
|
+
? { kind: "ok" as const, artifacts: [{ handle: fsHandle(m), role: "primary" as const }] }
|
|
80
|
+
: { kind: "ok" as const, artifacts: [] }; // produces ⇒ contract-fatal ⇒ promotion miss
|
|
81
|
+
},
|
|
82
|
+
},
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
const singleStageWorkflow = (outcome: Outcome, sessionPolicy: "fresh" | "continue" = "fresh"): Workflow =>
|
|
86
|
+
({
|
|
87
|
+
name: "wf",
|
|
88
|
+
start: "build",
|
|
89
|
+
stages: { build: { kind: "produces", sessionPolicy, outcome } },
|
|
90
|
+
edges: { build: "stop" },
|
|
91
|
+
}) as Workflow;
|
|
92
|
+
|
|
93
|
+
/** Write a Pi-shaped session file whose header carries `id`. */
|
|
94
|
+
const writeSessionFile = (id: string): string => {
|
|
95
|
+
const dir = join(tmpDir, "pi-sessions");
|
|
96
|
+
mkdirSync(dir, { recursive: true });
|
|
97
|
+
const file = join(dir, `2026-06-11_${id}.jsonl`);
|
|
98
|
+
writeFileSync(file, `${JSON.stringify({ type: "session", version: 3, id, timestamp: "t", cwd: tmpDir })}\n`);
|
|
99
|
+
return file;
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
const failedRow = (session: SessionRef | null): WorkflowStage => ({
|
|
103
|
+
stageNumber: 1,
|
|
104
|
+
stage: "build",
|
|
105
|
+
skill: "build",
|
|
106
|
+
status: "failed",
|
|
107
|
+
ts: "t1",
|
|
108
|
+
errMsg: "interrupted",
|
|
109
|
+
session,
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
const writeRun = (rows: WorkflowStage[]): void => {
|
|
113
|
+
writeHeader(tmpDir, header);
|
|
114
|
+
for (const r of rows) appendStage(tmpDir, header.runId, r);
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
interface Harness {
|
|
118
|
+
ctx: WorkflowHostContext;
|
|
119
|
+
notifications: Array<{ msg: string; level: string }>;
|
|
120
|
+
/** Messages sent INTO the adopted session (reattach prompt, retry fixes). */
|
|
121
|
+
sentIntoSession: string[];
|
|
122
|
+
switchSessionSpy: ReturnType<typeof vi.fn>;
|
|
123
|
+
newSessionSpy: ReturnType<typeof vi.fn>;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Hand-rolled host ctx. `switchBranch` is the adopted session's LIVE branch
|
|
128
|
+
* array (mutated by `onSessionSend` to simulate the agent answering);
|
|
129
|
+
* `omitSwitchSession` exercises the "host cannot switch" rung. `newSession`
|
|
130
|
+
* (the cold-re-run path) delivers a fresh session whose branch announces
|
|
131
|
+
* `coldAnnounce` so the fallback completes the stage.
|
|
132
|
+
*/
|
|
133
|
+
function makeHarness(opts: {
|
|
134
|
+
switchBranch?: unknown[];
|
|
135
|
+
omitSwitchSession?: boolean;
|
|
136
|
+
switchCancelled?: boolean;
|
|
137
|
+
onSessionSend?: (msg: string, branch: unknown[]) => void;
|
|
138
|
+
coldAnnounce?: string;
|
|
139
|
+
}): Harness {
|
|
140
|
+
const notifications: Array<{ msg: string; level: string }> = [];
|
|
141
|
+
const sentIntoSession: string[] = [];
|
|
142
|
+
const ui = {
|
|
143
|
+
notify: (msg: string, level?: string) => notifications.push({ msg, level: level ?? "info" }),
|
|
144
|
+
setStatus: () => {},
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
const sessionCtxFor = (branch: unknown[], id: string, file: string | undefined): WorkflowSessionContext =>
|
|
148
|
+
({
|
|
149
|
+
cwd: tmpDir,
|
|
150
|
+
hasUI: false,
|
|
151
|
+
ui,
|
|
152
|
+
sessionManager: {
|
|
153
|
+
getBranch: () => branch,
|
|
154
|
+
getSessionId: () => id,
|
|
155
|
+
getSessionFile: () => file,
|
|
156
|
+
},
|
|
157
|
+
waitForIdle: async () => {},
|
|
158
|
+
newSession: newSessionSpy,
|
|
159
|
+
sendUserMessage: async (msg: string) => {
|
|
160
|
+
sentIntoSession.push(msg);
|
|
161
|
+
opts.onSessionSend?.(msg, branch);
|
|
162
|
+
},
|
|
163
|
+
}) as unknown as WorkflowSessionContext;
|
|
164
|
+
|
|
165
|
+
const newSessionSpy = vi.fn(async (options?: { withSession?: (c: WorkflowSessionContext) => Promise<void> }) => {
|
|
166
|
+
const branch = [mockAssistantMessage(opts.coldAnnounce ?? "no artifact here")];
|
|
167
|
+
await options?.withSession?.(sessionCtxFor(branch, "cold-session", undefined));
|
|
168
|
+
return { cancelled: false };
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
const switchSessionSpy = vi.fn(
|
|
172
|
+
async (path: string, options: { withSession: (c: WorkflowSessionContext) => Promise<void> }) => {
|
|
173
|
+
if (opts.switchCancelled) return { cancelled: true };
|
|
174
|
+
await options.withSession(sessionCtxFor(opts.switchBranch ?? [], "sess-1", path));
|
|
175
|
+
return { cancelled: false };
|
|
176
|
+
},
|
|
177
|
+
);
|
|
178
|
+
|
|
179
|
+
const ctx = {
|
|
180
|
+
cwd: tmpDir,
|
|
181
|
+
hasUI: false,
|
|
182
|
+
ui,
|
|
183
|
+
sessionManager: {
|
|
184
|
+
getBranch: () => [],
|
|
185
|
+
getSessionId: () => "outer-session",
|
|
186
|
+
getSessionFile: () => undefined,
|
|
187
|
+
},
|
|
188
|
+
waitForIdle: async () => {},
|
|
189
|
+
newSession: newSessionSpy,
|
|
190
|
+
...(opts.omitSwitchSession ? {} : { switchSession: switchSessionSpy }),
|
|
191
|
+
} as unknown as WorkflowHostContext;
|
|
192
|
+
|
|
193
|
+
return { ctx, notifications, sentIntoSession, switchSessionSpy, newSessionSpy };
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const resume = (ctx: WorkflowHostContext, workflow: Workflow) => resumeWorkflow(ctx, { workflow, header, ref: "@1" });
|
|
197
|
+
|
|
198
|
+
/** Minimal WorkflowHost for the continue-policy arm (registers the dispatched skill). */
|
|
199
|
+
const fakeHost = () => ({
|
|
200
|
+
registerCommand: () => {},
|
|
201
|
+
sendUserMessage: async () => {},
|
|
202
|
+
getCommands: () => [{ name: "skill:build", source: "skill" }],
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
// ---------------------------------------------------------------------------
|
|
206
|
+
// Promotion (issue #70)
|
|
207
|
+
// ---------------------------------------------------------------------------
|
|
208
|
+
|
|
209
|
+
describe("session-backed resume — promotion", () => {
|
|
210
|
+
it("adopts the interrupted session's announced artifact: completed row, nothing sent, chain advances", async () => {
|
|
211
|
+
const file = writeSessionFile("sess-1");
|
|
212
|
+
writeRun([failedRow({ id: "sess-1", file })]);
|
|
213
|
+
const h = makeHarness({
|
|
214
|
+
switchBranch: [mockAssistantMessage("done — wrote .rpiv/artifacts/impl/build.md")],
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
const result = await resume(h.ctx, singleStageWorkflow(announceOutcome()));
|
|
218
|
+
|
|
219
|
+
expect(result.success).toBe(true);
|
|
220
|
+
expect(h.switchSessionSpy).toHaveBeenCalledWith(file, expect.anything());
|
|
221
|
+
expect(h.newSessionSpy).not.toHaveBeenCalled();
|
|
222
|
+
// Promotion sends NOTHING — the old branch already carried the work.
|
|
223
|
+
expect(h.sentIntoSession).toEqual([]);
|
|
224
|
+
expect(h.notifications.some((n) => n.msg === MSG_RESUME_PROMOTED("build"))).toBe(true);
|
|
225
|
+
|
|
226
|
+
const rows = readAllStages(tmpDir, header.runId);
|
|
227
|
+
expect(rows.map((r) => r.status)).toEqual(["failed", "completed"]);
|
|
228
|
+
// The promoted row is session-backed by the ADOPTED session.
|
|
229
|
+
expect(rows[1]?.session).toEqual({ id: "sess-1", file });
|
|
230
|
+
expect(result.lastArtifact).toBe(".rpiv/artifacts/impl/build.md");
|
|
231
|
+
});
|
|
232
|
+
|
|
233
|
+
it("promotion validation-exhausted halts exactly as live — session-backed failure row", async () => {
|
|
234
|
+
const file = writeSessionFile("sess-1");
|
|
235
|
+
writeRun([failedRow({ id: "sess-1", file })]);
|
|
236
|
+
const h = makeHarness({
|
|
237
|
+
switchBranch: [mockAssistantMessage("done — wrote .rpiv/artifacts/impl/build.md")],
|
|
238
|
+
});
|
|
239
|
+
// The adopted artifact exists but its data fails the output schema;
|
|
240
|
+
// onInvalid: "halt" skips retries → validation-exhausted.
|
|
241
|
+
const workflow = {
|
|
242
|
+
name: "wf",
|
|
243
|
+
start: "build",
|
|
244
|
+
stages: {
|
|
245
|
+
build: {
|
|
246
|
+
kind: "produces",
|
|
247
|
+
sessionPolicy: "fresh",
|
|
248
|
+
outcome: announceOutcome(),
|
|
249
|
+
outputSchema: typeboxSchema(Type.Object({ impossible: Type.Literal(1) })),
|
|
250
|
+
onInvalid: "halt",
|
|
251
|
+
},
|
|
252
|
+
},
|
|
253
|
+
edges: { build: "stop" },
|
|
254
|
+
} as unknown as Workflow;
|
|
255
|
+
|
|
256
|
+
const result = await resume(h.ctx, workflow);
|
|
257
|
+
|
|
258
|
+
expect(result.success).toBe(false);
|
|
259
|
+
expect(result.error).toContain("output validation failed after retries");
|
|
260
|
+
const rows = readAllStages(tmpDir, header.runId);
|
|
261
|
+
expect(rows.map((r) => r.status)).toEqual(["failed", "failed"]);
|
|
262
|
+
expect(rows[1]?.session).toEqual({ id: "sess-1", file });
|
|
263
|
+
});
|
|
264
|
+
|
|
265
|
+
it("dispatches on the structured session field: a sessionless failed trailer re-runs cold", async () => {
|
|
266
|
+
writeRun([failedRow(null)]);
|
|
267
|
+
const h = makeHarness({ coldAnnounce: "wrote .rpiv/artifacts/impl/cold.md" });
|
|
268
|
+
|
|
269
|
+
const result = await resume(h.ctx, singleStageWorkflow(announceOutcome()));
|
|
270
|
+
|
|
271
|
+
expect(result.success).toBe(true);
|
|
272
|
+
expect(h.switchSessionSpy).not.toHaveBeenCalled();
|
|
273
|
+
expect(h.newSessionSpy).toHaveBeenCalledTimes(1);
|
|
274
|
+
// Silent arm — no fallback notice for rows that never had a session.
|
|
275
|
+
expect(h.notifications.some((n) => n.msg.includes("re-running the stage"))).toBe(false);
|
|
276
|
+
});
|
|
277
|
+
|
|
278
|
+
it("continue-policy stage scopes promotion extraction with the PERSISTED branchOffset", async () => {
|
|
279
|
+
const file = writeSessionFile("sess-1");
|
|
280
|
+
writeRun([failedRow({ id: "sess-1", file, branchOffset: 1 })]);
|
|
281
|
+
const collectSpy = vi.fn();
|
|
282
|
+
const h = makeHarness({
|
|
283
|
+
switchBranch: [
|
|
284
|
+
mockAssistantMessage("PRIOR STAGE noise .rpiv/artifacts/wrong/prior.md"),
|
|
285
|
+
mockAssistantMessage("done — wrote .rpiv/artifacts/impl/cont.md"),
|
|
286
|
+
],
|
|
287
|
+
});
|
|
288
|
+
|
|
289
|
+
const result = await resumeWorkflow(h.ctx, {
|
|
290
|
+
workflow: singleStageWorkflow(announceOutcome(collectSpy), "continue"),
|
|
291
|
+
header,
|
|
292
|
+
host: fakeHost(),
|
|
293
|
+
ref: "@1",
|
|
294
|
+
});
|
|
295
|
+
|
|
296
|
+
expect(result.success).toBe(true);
|
|
297
|
+
// The collector saw the persisted offset — not a freshly-derived one.
|
|
298
|
+
expect(collectSpy.mock.calls[0]?.[0]?.branchOffset).toBe(1);
|
|
299
|
+
// And the offset kept the prior stage's announcement out of the result.
|
|
300
|
+
expect(result.lastArtifact).toBe(".rpiv/artifacts/impl/cont.md");
|
|
301
|
+
});
|
|
302
|
+
});
|
|
303
|
+
|
|
304
|
+
// ---------------------------------------------------------------------------
|
|
305
|
+
// Fallback ladder
|
|
306
|
+
// ---------------------------------------------------------------------------
|
|
307
|
+
|
|
308
|
+
describe("session-backed resume — fallback ladder", () => {
|
|
309
|
+
it("host without switchSession → notify + cold re-run", async () => {
|
|
310
|
+
const file = writeSessionFile("sess-1");
|
|
311
|
+
writeRun([failedRow({ id: "sess-1", file })]);
|
|
312
|
+
const h = makeHarness({ omitSwitchSession: true, coldAnnounce: "wrote .rpiv/artifacts/impl/cold.md" });
|
|
313
|
+
|
|
314
|
+
const result = await resume(h.ctx, singleStageWorkflow(announceOutcome()));
|
|
315
|
+
|
|
316
|
+
expect(result.success).toBe(true);
|
|
317
|
+
expect(h.newSessionSpy).toHaveBeenCalledTimes(1);
|
|
318
|
+
expect(
|
|
319
|
+
h.notifications.some((n) => n.msg === MSG_RESUME_SESSION_FALLBACK("build", "host cannot switch sessions")),
|
|
320
|
+
).toBe(true);
|
|
321
|
+
});
|
|
322
|
+
|
|
323
|
+
it("session file gone (deleted / different machine) → notify + cold re-run", async () => {
|
|
324
|
+
writeRun([failedRow({ id: "sess-1", file: join(tmpDir, "gone", "x_sess-1.jsonl") })]);
|
|
325
|
+
const h = makeHarness({ coldAnnounce: "wrote .rpiv/artifacts/impl/cold.md" });
|
|
326
|
+
|
|
327
|
+
const result = await resume(h.ctx, singleStageWorkflow(announceOutcome()));
|
|
328
|
+
|
|
329
|
+
expect(result.success).toBe(true);
|
|
330
|
+
expect(h.switchSessionSpy).not.toHaveBeenCalled();
|
|
331
|
+
expect(h.newSessionSpy).toHaveBeenCalledTimes(1);
|
|
332
|
+
expect(
|
|
333
|
+
h.notifications.some((n) => n.msg === MSG_RESUME_SESSION_FALLBACK("build", "session file not found")),
|
|
334
|
+
).toBe(true);
|
|
335
|
+
});
|
|
336
|
+
|
|
337
|
+
it("switchSession cancelled by the user → sessionless skipped row (mirrors live pre-open cancellation)", async () => {
|
|
338
|
+
const file = writeSessionFile("sess-1");
|
|
339
|
+
writeRun([failedRow({ id: "sess-1", file })]);
|
|
340
|
+
const h = makeHarness({ switchCancelled: true });
|
|
341
|
+
|
|
342
|
+
const result = await resume(h.ctx, singleStageWorkflow(announceOutcome()));
|
|
343
|
+
|
|
344
|
+
expect(result.success).toBe(false);
|
|
345
|
+
expect(result.termination?.status).toBe("cancelled");
|
|
346
|
+
const rows = readAllStages(tmpDir, header.runId);
|
|
347
|
+
expect(rows[1]?.status).toBe("skipped");
|
|
348
|
+
expect(rows[1]?.session).toBeNull();
|
|
349
|
+
});
|
|
350
|
+
});
|
|
351
|
+
|
|
352
|
+
// ---------------------------------------------------------------------------
|
|
353
|
+
// Reattach (promotion miss → continue the session from its leaf)
|
|
354
|
+
// ---------------------------------------------------------------------------
|
|
355
|
+
|
|
356
|
+
describe("session-backed resume — reattach", () => {
|
|
357
|
+
it("promotion miss → REATTACH_PROMPT into the session; agent finishes; normal success path", async () => {
|
|
358
|
+
const file = writeSessionFile("sess-1");
|
|
359
|
+
writeRun([failedRow({ id: "sess-1", file })]);
|
|
360
|
+
const h = makeHarness({
|
|
361
|
+
switchBranch: [mockAssistantMessage("was mid-work, no artifact yet")],
|
|
362
|
+
onSessionSend: (msg, branch) => {
|
|
363
|
+
// The nudged agent finishes and announces.
|
|
364
|
+
if (msg === REATTACH_PROMPT("build")) {
|
|
365
|
+
branch.push(mockAssistantMessage("finished — wrote .rpiv/artifacts/impl/late.md"));
|
|
366
|
+
}
|
|
367
|
+
},
|
|
368
|
+
});
|
|
369
|
+
|
|
370
|
+
const result = await resume(h.ctx, singleStageWorkflow(announceOutcome()));
|
|
371
|
+
|
|
372
|
+
expect(result.success).toBe(true);
|
|
373
|
+
expect(h.sentIntoSession).toEqual([REATTACH_PROMPT("build")]);
|
|
374
|
+
expect(h.notifications.some((n) => n.msg === MSG_RESUME_REATTACHED("build"))).toBe(true);
|
|
375
|
+
const rows = readAllStages(tmpDir, header.runId);
|
|
376
|
+
expect(rows.map((r) => r.status)).toEqual(["failed", "completed"]);
|
|
377
|
+
expect(result.lastArtifact).toBe(".rpiv/artifacts/impl/late.md");
|
|
378
|
+
});
|
|
379
|
+
|
|
380
|
+
it("reattach second failure → session-backed failure row (the run stays resumable)", async () => {
|
|
381
|
+
const file = writeSessionFile("sess-1");
|
|
382
|
+
writeRun([failedRow({ id: "sess-1", file })]);
|
|
383
|
+
// Agent never announces — promotion misses AND the reattached turn
|
|
384
|
+
// still produces nothing (produces-contract fatal).
|
|
385
|
+
const h = makeHarness({
|
|
386
|
+
switchBranch: [mockAssistantMessage("was mid-work, no artifact yet")],
|
|
387
|
+
onSessionSend: (_msg, branch) => {
|
|
388
|
+
branch.push(mockAssistantMessage("sorry, still nothing"));
|
|
389
|
+
},
|
|
390
|
+
});
|
|
391
|
+
|
|
392
|
+
const result = await resume(h.ctx, singleStageWorkflow(announceOutcome()));
|
|
393
|
+
|
|
394
|
+
expect(result.success).toBe(false);
|
|
395
|
+
const rows = readAllStages(tmpDir, header.runId);
|
|
396
|
+
expect(rows.map((r) => r.status)).toEqual(["failed", "failed"]);
|
|
397
|
+
// The new failure row carries the adopted session — resumable again.
|
|
398
|
+
expect(rows[1]?.session).toEqual({ id: "sess-1", file });
|
|
399
|
+
});
|
|
400
|
+
});
|