@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.
Files changed (114) hide show
  1. package/README.md +81 -8
  2. package/api.ts +18 -703
  3. package/audit-rows.ts +136 -0
  4. package/audit.ts +139 -126
  5. package/built-ins.ts +20 -45
  6. package/chain-state.ts +169 -0
  7. package/command-run.ts +31 -3
  8. package/command.ts +116 -20
  9. package/docs/workflow-authoring.md +322 -61
  10. package/{lifecycle.ts → events.ts} +119 -35
  11. package/host.ts +30 -0
  12. package/index.ts +25 -81
  13. package/internal-utils.ts +92 -78
  14. package/internal.ts +21 -1
  15. package/judge.ts +229 -0
  16. package/layers.ts +10 -15
  17. package/load/alias.ts +6 -12
  18. package/load/cache.ts +9 -6
  19. package/load/index.ts +16 -109
  20. package/load/issues.ts +31 -0
  21. package/load/legacy.ts +102 -0
  22. package/load/merge.ts +2 -2
  23. package/load/shape-guards.test.ts +4 -1
  24. package/load/shape-guards.ts +3 -6
  25. package/load/skill-contract-phase.ts +94 -0
  26. package/loop-constructors.ts +623 -0
  27. package/loop-def.ts +240 -0
  28. package/loop-kinds.ts +493 -0
  29. package/loop.ts +304 -0
  30. package/messages.ts +225 -157
  31. package/outcomes/collectors/directory-path.ts +7 -3
  32. package/outcomes/collectors/require-opt.ts +11 -0
  33. package/outcomes/collectors/tool-call.test.ts +3 -1
  34. package/outcomes/collectors/tool-call.ts +8 -3
  35. package/outcomes/collectors/transcript-path.ts +2 -3
  36. package/outcomes/collectors/union.test.ts +54 -0
  37. package/outcomes/collectors/union.ts +28 -9
  38. package/outcomes/collectors/url.ts +7 -0
  39. package/outcomes/collectors/workspace-diff.test.ts +13 -0
  40. package/outcomes/collectors/workspace-diff.ts +21 -14
  41. package/outcomes/exec.ts +17 -0
  42. package/outcomes/git-commit.test.ts +76 -30
  43. package/outcomes/git-commit.ts +139 -100
  44. package/outcomes/index.ts +1 -0
  45. package/outcomes/parsers/json-body.ts +2 -2
  46. package/outcomes/side-effect.ts +3 -3
  47. package/output-spec.ts +36 -10
  48. package/output.ts +40 -20
  49. package/package.json +13 -7
  50. package/predicates.ts +11 -8
  51. package/preview.ts +77 -17
  52. package/registration.ts +109 -35
  53. package/routing-dsl.ts +310 -0
  54. package/routing.ts +2 -2
  55. package/runner/by-name.ts +2 -1
  56. package/runner/by-run-id.ts +2 -1
  57. package/runner/chain-advance.ts +59 -44
  58. package/runner/errors.ts +33 -0
  59. package/runner/failure.ts +109 -0
  60. package/runner/header-write-failure.test.ts +64 -0
  61. package/runner/index.ts +7 -13
  62. package/runner/input-validation.ts +11 -21
  63. package/runner/preflight.ts +173 -0
  64. package/runner/resolve-stage.ts +68 -0
  65. package/runner/resume-entry.ts +101 -0
  66. package/runner/resume-loop.test.ts +1410 -0
  67. package/runner/resume-loop.ts +110 -0
  68. package/runner/resume-session.test.ts +400 -0
  69. package/runner/resume.test.ts +881 -206
  70. package/runner/resume.ts +281 -261
  71. package/runner/run-context.ts +161 -0
  72. package/runner/run-stage.ts +456 -0
  73. package/runner/runner.ts +59 -400
  74. package/runner/script-stage.ts +103 -105
  75. package/schema-compat.ts +13 -1
  76. package/sessions/extraction.ts +53 -31
  77. package/sessions/index.ts +3 -1
  78. package/sessions/locate.test.ts +77 -0
  79. package/sessions/locate.ts +90 -0
  80. package/sessions/reattach.ts +63 -0
  81. package/sessions/sessions.ts +130 -127
  82. package/skill-contract.ts +22 -25
  83. package/skill-contracts/composition.ts +88 -37
  84. package/skill-contracts/{registries.ts → extension-points.ts} +45 -12
  85. package/skill-contracts/harvest.ts +2 -3
  86. package/skill-contracts/index.ts +15 -8
  87. package/skill-contracts/registry.ts +33 -50
  88. package/stage-def.ts +527 -0
  89. package/startup.ts +3 -1
  90. package/state/index.ts +8 -1
  91. package/state/names.ts +91 -65
  92. package/state/paths.ts +12 -0
  93. package/state/raw.ts +78 -0
  94. package/state/reads.ts +103 -85
  95. package/state/resolve.ts +73 -0
  96. package/state/state.ts +112 -15
  97. package/state/writes.ts +29 -12
  98. package/transcript.ts +24 -0
  99. package/triggers.ts +11 -3
  100. package/types.ts +202 -44
  101. package/validate/contract-compat.ts +193 -0
  102. package/validate/graph.ts +125 -0
  103. package/validate/issue.ts +314 -0
  104. package/validate/stage-rules.ts +420 -0
  105. package/validate-output.ts +69 -1
  106. package/validate-workflow.ts +55 -759
  107. package/control-flow.ts +0 -135
  108. package/fanout.ts +0 -102
  109. package/iterate.ts +0 -155
  110. package/runner/resume-fanout.test.ts +0 -331
  111. package/runner/resume-fanout.ts +0 -136
  112. package/runner/resume-iterate.test.ts +0 -444
  113. package/runner/resume-iterate.ts +0 -111
  114. package/runner/stage-lifecycle.ts +0 -500
package/loop.ts ADDED
@@ -0,0 +1,304 @@
1
+ /**
2
+ * loop.ts — THE unit-loop driver. One continuation loop runs every loop
3
+ * stage: `fanout` (push: units precomputed), `iterate` (pull: one unit per
4
+ * generator call, accumulating), `assess` (producer→judge rounds until the
5
+ * judge's verdict satisfies `done`). The only per-kind code is the strategy
6
+ * table in loop-kinds.ts (`pull` / `guardExpectation` / `hasPending`) —
7
+ * dispatch, persistence, cap policy, result projection, and completion are
8
+ * shared and kind-agnostic here.
9
+ *
10
+ * A `verify`-bearing stage runs here too — `effectiveLoopOf` desugars it into
11
+ * a degenerate assess loop; verify-aware code is presentation only
12
+ * (role/label flavoring keyed on `e.def.verify` inside the assess strategy).
13
+ *
14
+ * Every unit runs `runStageSession` with a pre-decorated session: `stageName`
15
+ * carries the DISPLAY decoration (`decorateStage`), `unit` carries the
16
+ * machine identity that lands in the row's `parent`/`role`/`unitId`/`unitIndex`
17
+ * fields and the `onUnitStart`/`onUnitEnd` payloads.
18
+ *
19
+ * Continuation-style: each unit's `onSuccess` advances the cursor and
20
+ * re-enters `step`. Everything is awaited up the stack, so a throw from a
21
+ * user fn (`units`/`next`/`feedForward`/`done`/judge prompt) propagates to
22
+ * `runStageOrRecordFailure`'s single catch — a thrown `StagePreflightError`
23
+ * (the `haltPreflight` consumer contract) keeps its own attribution.
24
+ *
25
+ * Capture semantics (the post-refactor bug class — pinned):
26
+ * - `entryArtifact` + `entryPair` frozen by the CALLER before unit 1;
27
+ * - snapshot captured per unit, immediately before its session;
28
+ * - the skill registry was snapshotted once at run start (RunContext).
29
+ *
30
+ * `runner/run-stage.ts` injects primitives through `LoopDeps` so this
31
+ * module never imports the engine back (cycle-free).
32
+ *
33
+ * Resume re-enters `runLoop` with a fold-reconstructed cursor (see
34
+ * `runner/resume-loop.ts`); the silence rule — banner only when this
35
+ * invocation dispatched ≥1 unit — keeps a finished-loop resume a silent
36
+ * no-op (pinned behavior).
37
+ */
38
+
39
+ import type { AssessLoop, LoopDef, StageDef } from "./api.js";
40
+ import { decorateStage, runIdentityOf } from "./audit.js";
41
+ import { applyCompletedStage } from "./chain-state.js";
42
+ import { lifecycleCtxFor, skillStageRef, type UnitEvent } from "./events.js";
43
+ import { nowIso } from "./internal-utils.js";
44
+ import { isPanel } from "./judge.js";
45
+ import { panelVerdictChannel, panelVerdictDef } from "./loop-constructors.js";
46
+ import {
47
+ advanceCursor,
48
+ type LoopCursor,
49
+ type LoopEntry,
50
+ loopStrategyOf,
51
+ type NextStep,
52
+ presentedKindOf,
53
+ } from "./loop-kinds.js";
54
+ import {
55
+ MSG_LOOP_CAP_ADVANCE,
56
+ MSG_LOOP_ZERO_UNITS,
57
+ MSG_STAGE_COMPLETE,
58
+ STATUS_KEY,
59
+ STATUS_LOOP_UNIT,
60
+ } from "./messages.js";
61
+ import { appendLoopCap } from "./state/index.js";
62
+ import type { RunContext, StageSession, UnitRef, WorkflowHostContext } from "./types.js";
63
+
64
+ export interface LoopDeps {
65
+ /** Dispatch one unit through the standard stage-session path. */
66
+ runStageSession: (ctx: WorkflowHostContext, s: StageSession) => Promise<void>;
67
+ /**
68
+ * Resume the chain after the loop finishes — receives the loop node's REAL
69
+ * name. `Promise<unknown>` so the walk's `ChainOutcome`-returning composed
70
+ * advance plugs in directly (the driver only awaits settlement).
71
+ */
72
+ advanceAfter: (
73
+ curCtx: WorkflowHostContext,
74
+ completedName: string,
75
+ completedIdx: number,
76
+ run: RunContext,
77
+ ) => Promise<unknown>;
78
+ /** Re-capture the outcome's pre-stage snapshot per unit (ctx + stage name for the fail-soft warning). */
79
+ captureSnapshot: (
80
+ curCtx: WorkflowHostContext,
81
+ stageName: string,
82
+ def: StageDef,
83
+ idx: number,
84
+ run: RunContext,
85
+ ) => Promise<unknown>;
86
+ /** Record the terminal failure when `onCap: "halt"` trips — verify-worded for verify stages. */
87
+ haltLoop: (
88
+ curCtx: WorkflowHostContext,
89
+ run: RunContext,
90
+ e: Pick<LoopEntry, "name" | "def">,
91
+ count: number,
92
+ cap: number,
93
+ ) => Promise<void>;
94
+ }
95
+
96
+ /**
97
+ * The loop-entry announcement — `onStageStart` then `onLoopStart` with the
98
+ * presented kind (+ the precomputed unit list when the loop has one). ONE
99
+ * helper for the live entry (`runLoopStage`) and the resume re-entry
100
+ * (`resumeLoopStage`), which used to re-spell the pair and keep the
101
+ * presented-kind expression aligned by convention.
102
+ */
103
+ export async function announceLoopStart(
104
+ curCtx: WorkflowHostContext,
105
+ run: RunContext,
106
+ e: Pick<LoopEntry, "stageIdx" | "name" | "skill" | "def" | "loop" | "units">,
107
+ ): Promise<void> {
108
+ const ref = skillStageRef(e.name, e.stageIdx + 1, e.skill);
109
+ await run.lifecycle.fire(curCtx, "onStageStart", ref, lifecycleCtxFor(run));
110
+ await run.lifecycle.fire(
111
+ curCtx,
112
+ "onLoopStart",
113
+ ref,
114
+ { kind: presentedKindOf(e.def, e.loop), ...(e.units ? { units: e.units } : {}) },
115
+ lifecycleCtxFor(run),
116
+ );
117
+ }
118
+
119
+ /** Run (or resume) one loop generation. The caller fired onStageStart/onLoopStart. */
120
+ export async function runLoop(
121
+ curCtx: WorkflowHostContext,
122
+ e: LoopEntry,
123
+ cursor: LoopCursor,
124
+ run: RunContext,
125
+ deps: LoopDeps,
126
+ ): Promise<void> {
127
+ const cap = Math.min(e.loop.max ?? Number.POSITIVE_INFINITY, run.maxIterations);
128
+ await step(curCtx, e, cursor, cap, run, deps);
129
+ }
130
+
131
+ // ---------------------------------------------------------------------------
132
+ // The step cycle
133
+ // ---------------------------------------------------------------------------
134
+
135
+ async function step(
136
+ curCtx: WorkflowHostContext,
137
+ e: LoopEntry,
138
+ cursor: LoopCursor,
139
+ cap: number,
140
+ run: RunContext,
141
+ deps: LoopDeps,
142
+ ): Promise<void> {
143
+ const next = await loopStrategyOf(e.loop.kind).pull(e, cursor, cap, run);
144
+ if (next.kind === "complete") return finishLoop(curCtx, e, cursor, run, deps);
145
+ if (next.kind === "cap") return hitCap(curCtx, e, cursor, next.count, cap, run, deps);
146
+ return dispatchUnit(curCtx, e, cursor, next, cap, run, deps);
147
+ }
148
+
149
+ /** Dispatch one unit session; the onSuccess continuation advances the cursor and re-enters step. */
150
+ async function dispatchUnit(
151
+ curCtx: WorkflowHostContext,
152
+ e: LoopEntry,
153
+ cursor: LoopCursor,
154
+ u: Extract<NextStep, { kind: "unit" }>,
155
+ cap: number,
156
+ run: RunContext,
157
+ deps: LoopDeps,
158
+ ): Promise<void> {
159
+ curCtx.ui.setStatus(STATUS_KEY, STATUS_LOOP_UNIT(e.stageIdx + 1, run.totalStages, u.skill, u.label));
160
+
161
+ const unitRef: UnitRef = { parent: e.name, role: u.role, index: cursor.index, id: u.id, label: u.label };
162
+ const event: UnitEvent = { role: u.role, index: cursor.index, unitId: u.id, label: u.label, skill: u.skill };
163
+ await run.lifecycle.fire(
164
+ curCtx,
165
+ "onUnitStart",
166
+ skillStageRef(e.name, e.stageIdx + 1, u.skill),
167
+ event,
168
+ lifecycleCtxFor(run),
169
+ );
170
+
171
+ const snapshot = await deps.captureSnapshot(curCtx, e.name, u.def, e.stageIdx, run);
172
+
173
+ await deps.runStageSession(curCtx, {
174
+ cwd: run.cwd,
175
+ runId: run.runId,
176
+ state: run.state,
177
+ prompt: u.prompt,
178
+ stageName: decorateStage(e.name, u.tag), // DISPLAY only — machine identity is `unit`
179
+ skill: u.skill,
180
+ lifecycle: run.lifecycle,
181
+ runIdentity: runIdentityOf(run),
182
+ stage: u.def,
183
+ skillContracts: run.skillContracts,
184
+ stageIndex: e.stageIdx,
185
+ snapshot,
186
+ branchOffset: undefined,
187
+ unit: unitRef,
188
+ onFailure: undefined,
189
+ onSuccess: (freshCtx, output) => {
190
+ cursor.ranThisInvocation++;
191
+ advanceCursor(cursor, u.role, output, e.loop);
192
+ publishPanelVerdict(e.loop, e.name, cursor, run.state);
193
+ return step(freshCtx, e, cursor, cap, run, deps);
194
+ },
195
+ });
196
+ }
197
+
198
+ /**
199
+ * Panel-close publish — lands a panel's FOLDED verdict on its named channel,
200
+ * run by BOTH the live driver (`dispatchUnit.onSuccess`) and the resume fold
201
+ * (`runner/resume.ts` `foldUnitRow`) immediately after the SAME `advanceCursor`,
202
+ * so the two paths publish byte-identically (THE REPLAY CONTRACT). Fires exactly
203
+ * once per round — only on the transition that closes a panel: the LAST member's
204
+ * judge advance is the one that clears `cursor.panel` AND flips back to `produce`
205
+ * with the folded verdict already on `lastVerdict`. A single judge (non-panel),
206
+ * a mid-panel member advance (`cursor.panel` still set), and every produce
207
+ * advance (`phase` left at `judge`) all fall through untouched. `advanceCursor`
208
+ * already manufactured the verdict (pure); this only appends it — the fold
209
+ * carries no artifact, so `applyCompletedStage` leaves the rolling primary alone
210
+ * and writes only the named channel. It lives BESIDE `advanceCursor`, not inside
211
+ * it: publishing mutates `RunState`, and `advanceCursor` must stay pure for the
212
+ * live + resume folds to agree.
213
+ */
214
+ export function publishPanelVerdict(
215
+ loop: LoopDef,
216
+ stageName: string,
217
+ cursor: LoopCursor,
218
+ state: RunContext["state"],
219
+ ): void {
220
+ if (loop.kind !== "assess") return;
221
+ const judge = (loop as AssessLoop).judge;
222
+ if (!isPanel(judge) || cursor.panel !== undefined || cursor.phase !== "produce") return;
223
+ if (cursor.lastVerdict === undefined) return; // defensive — the fold always set it
224
+ applyCompletedStage(
225
+ state,
226
+ panelVerdictDef(judge, stageName),
227
+ panelVerdictChannel(judge, stageName),
228
+ cursor.lastVerdict,
229
+ );
230
+ }
231
+
232
+ // ---------------------------------------------------------------------------
233
+ // Loop end — projection, notification, cap policy
234
+ // ---------------------------------------------------------------------------
235
+
236
+ /**
237
+ * The declared `result` projection — the ONE place the loop's outcome lands
238
+ * in `{state.output, state.primaryArtifact}` (the pair is governed as one;
239
+ * mid-loop transient rolls are accepted by design). The resume fold applies
240
+ * this same function at generation close.
241
+ */
242
+ export function projectResult(
243
+ loop: LoopDef,
244
+ entryPair: LoopEntry["entryPair"],
245
+ cursor: LoopCursor,
246
+ state: RunContext["state"],
247
+ ): void {
248
+ if (loop.result === "last" && cursor.lastProduce) {
249
+ state.output = cursor.lastProduce.output;
250
+ // `artifact` is undefined only for acts-stage units (produces units are
251
+ // guaranteed ≥1 artifact by enforceCompletionContract) — the entry
252
+ // primary carries through, mirroring how a single acts stage behaves.
253
+ state.primaryArtifact = cursor.lastProduce.artifact ?? entryPair.primaryArtifact;
254
+ return;
255
+ }
256
+ // "entry" — or "last" with zero produce units (degrades to entry: the
257
+ // zero-unit pull loop leaves the chain exactly as it found it).
258
+ state.output = entryPair.output;
259
+ state.primaryArtifact = entryPair.primaryArtifact;
260
+ }
261
+
262
+ /**
263
+ * Notification rules: banner iff THIS invocation ran units; the zero-unit
264
+ * warning only for a live empty pull loop; a resumed finished loop stays
265
+ * SILENT (pinned — no re-announce, no double completion toast).
266
+ */
267
+ async function finishLoop(
268
+ curCtx: WorkflowHostContext,
269
+ e: LoopEntry,
270
+ cursor: LoopCursor,
271
+ run: RunContext,
272
+ deps: LoopDeps,
273
+ ): Promise<void> {
274
+ projectResult(e.loop, e.entryPair, cursor, run.state);
275
+ if (cursor.ranThisInvocation > 0) {
276
+ curCtx.ui.notify(MSG_STAGE_COMPLETE(e.skill), "info");
277
+ } else if (cursor.accumulated.length === 0 && e.loop.kind === "iterate") {
278
+ curCtx.ui.notify(MSG_LOOP_ZERO_UNITS(e.skill), "warning");
279
+ }
280
+ await deps.advanceAfter(curCtx, e.name, e.stageIdx, run);
281
+ }
282
+
283
+ /** Cap trip: "halt" → terminal failure; "advance" → durable telemetry + event + projected advance. */
284
+ async function hitCap(
285
+ curCtx: WorkflowHostContext,
286
+ e: LoopEntry,
287
+ cursor: LoopCursor,
288
+ count: number,
289
+ cap: number,
290
+ run: RunContext,
291
+ deps: LoopDeps,
292
+ ): Promise<void> {
293
+ if (e.loop.onCap === "halt") return deps.haltLoop(curCtx, run, e, count, cap);
294
+ appendLoopCap(run.cwd, run.runId, { type: "loop-cap", stage: e.name, count, max: cap, ts: nowIso() });
295
+ curCtx.ui.notify(MSG_LOOP_CAP_ADVANCE(e.skill, cap), "warning");
296
+ await run.lifecycle.fire(
297
+ curCtx,
298
+ "onLoopCap",
299
+ skillStageRef(e.name, e.stageIdx + 1, e.skill),
300
+ { kind: e.loop.kind, count, max: cap, policy: "advance" as const },
301
+ lifecycleCtxFor(run),
302
+ );
303
+ return finishLoop(curCtx, e, cursor, run, deps);
304
+ }