@juicesharp/rpiv-workflow 1.20.0 → 2.1.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.
Files changed (111) hide show
  1. package/README.md +98 -545
  2. package/api.ts +1 -1
  3. package/audit-ctx.ts +103 -0
  4. package/audit-rows.ts +18 -0
  5. package/audit.ts +119 -164
  6. package/built-ins.ts +26 -6
  7. package/chain-state.ts +119 -68
  8. package/command-run.ts +35 -30
  9. package/command.ts +10 -4
  10. package/docs/embedding.md +341 -0
  11. package/docs/workflow-authoring.md +70 -16
  12. package/docs/workflow-basics.md +125 -10
  13. package/events.ts +44 -4
  14. package/execution-host.ts +75 -0
  15. package/host.ts +137 -82
  16. package/internal-utils.ts +89 -3
  17. package/internal.ts +1 -0
  18. package/judge.ts +23 -11
  19. package/load/alias.ts +3 -3
  20. package/load/index.ts +15 -1
  21. package/load/issues.ts +2 -2
  22. package/load/legacy.ts +2 -2
  23. package/load/resolve-default.ts +3 -4
  24. package/load/skill-contract-phase.ts +1 -1
  25. package/loop-constructors.ts +19 -618
  26. package/loop-def.ts +60 -15
  27. package/loop-kinds.ts +319 -62
  28. package/loop-parallel.ts +250 -0
  29. package/loop-waves.ts +99 -0
  30. package/loop.ts +106 -80
  31. package/loops/constructors.ts +334 -0
  32. package/loops/derivations.ts +65 -0
  33. package/loops/introspection.ts +184 -0
  34. package/loops/panel.ts +196 -0
  35. package/loops/verify.ts +99 -0
  36. package/messages.ts +58 -33
  37. package/outcomes/collectors/index.ts +1 -0
  38. package/outcomes/collectors/text-scan.ts +47 -0
  39. package/outcomes/collectors/transcript-path.ts +2 -15
  40. package/outcomes/collectors/union.ts +2 -1
  41. package/outcomes/collectors/url.ts +2 -14
  42. package/outcomes/collectors/workspace-diff.ts +1 -1
  43. package/outcomes/git-commit.ts +57 -6
  44. package/output-spec.ts +1 -1
  45. package/output.ts +59 -1
  46. package/package.json +19 -6
  47. package/preview.ts +18 -18
  48. package/registration.ts +11 -4
  49. package/routing-dsl.ts +53 -41
  50. package/routing.ts +46 -0
  51. package/runner/chain-advance.ts +30 -17
  52. package/runner/errors.ts +7 -30
  53. package/runner/failure.ts +67 -13
  54. package/runner/input-validation.ts +8 -5
  55. package/runner/preflight.ts +17 -21
  56. package/runner/resume-entry.ts +23 -3
  57. package/runner/resume-loop.ts +50 -29
  58. package/runner/resume.ts +96 -10
  59. package/runner/run-context.ts +20 -16
  60. package/runner/run-stage.ts +125 -91
  61. package/runner/runner.ts +163 -69
  62. package/runner/script-stage.ts +23 -29
  63. package/schema-compat.ts +1 -2
  64. package/semaphore.ts +55 -0
  65. package/sessions/extraction.ts +103 -60
  66. package/sessions/halt-routing.ts +195 -0
  67. package/sessions/index.ts +2 -2
  68. package/sessions/locate.ts +60 -9
  69. package/sessions/reattach.ts +28 -20
  70. package/sessions/sessions.ts +103 -191
  71. package/sessions/spawn.ts +132 -119
  72. package/sessions/success-persist.ts +89 -0
  73. package/skill-contracts/composition.ts +8 -10
  74. package/skill-contracts/harvest.ts +3 -2
  75. package/skill-contracts/registry.ts +1 -1
  76. package/stage-def.ts +115 -47
  77. package/stage-errors.ts +84 -0
  78. package/stage-identity.ts +56 -0
  79. package/startup.ts +1 -0
  80. package/state/paths.ts +11 -3
  81. package/state/raw.ts +2 -3
  82. package/state/resolve.ts +3 -3
  83. package/state/state.ts +26 -3
  84. package/state/writes.ts +1 -1
  85. package/types.ts +97 -43
  86. package/validate/contract-compat.ts +16 -11
  87. package/validate/graph.ts +10 -1
  88. package/validate/issue.ts +20 -6
  89. package/validate/stage-rules.ts +139 -60
  90. package/validate-output.ts +27 -20
  91. package/validate-workflow.ts +5 -3
  92. package/validation-bounds.ts +35 -0
  93. package/docs/cover.png +0 -0
  94. package/docs/cover.svg +0 -120
  95. package/load/cache.test.ts +0 -82
  96. package/load/shape-guards.test.ts +0 -77
  97. package/outcomes/collectors/directory-path.test.ts +0 -64
  98. package/outcomes/collectors/tool-call.test.ts +0 -112
  99. package/outcomes/collectors/transcript-path.test.ts +0 -70
  100. package/outcomes/collectors/union.test.ts +0 -113
  101. package/outcomes/collectors/url.test.ts +0 -67
  102. package/outcomes/collectors/workspace-diff.test.ts +0 -120
  103. package/outcomes/git-commit.test.ts +0 -240
  104. package/outcomes/parsers/json-body.test.ts +0 -80
  105. package/runner/by-name.test.ts +0 -95
  106. package/runner/by-run-id.test.ts +0 -115
  107. package/runner/header-write-failure.test.ts +0 -64
  108. package/runner/resume-loop.test.ts +0 -1410
  109. package/runner/resume-session.test.ts +0 -400
  110. package/runner/resume.test.ts +0 -1805
  111. package/sessions/locate.test.ts +0 -77
@@ -1,400 +0,0 @@
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
- });