@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
package/chain-state.ts CHANGED
@@ -11,11 +11,19 @@
11
11
  * `internal-utils.ts`; anything in this file is workflow-chain domain logic.
12
12
  */
13
13
 
14
- import type { PromptFn, SkillStage, StageDef } from "./api.js";
14
+ import type { PromptFn, StageDef } from "./api.js";
15
15
  import { type Artifact, handleToString } from "./handle.js";
16
- import type { Output } from "./output.js";
16
+ import { isFailedOutput, type Output } from "./output.js";
17
+ import { readName, readsAll } from "./stage-def.js";
18
+ import { resolvePublishName } from "./stage-identity.js";
17
19
  import type { RunState } from "./types.js";
18
20
 
21
+ // Stage-identity projections live in the dependency-free `stage-identity.ts`
22
+ // leaf so the load-time validators can consume them without importing this
23
+ // runtime-state module. Re-exported here so this module's own runtime callers
24
+ // (runner/*, registration) keep a single chain-state import.
25
+ export { isDispatchingStage, resolvePublishName, resolveSkill } from "./stage-identity.js";
26
+
19
27
  /**
20
28
  * Canonical accessor for "the primary artifact the chain is currently
21
29
  * carrying." Reads the rolling slot maintained by the runner —
@@ -27,47 +35,6 @@ export function currentPrimaryArtifact(state: RunState): Artifact | undefined {
27
35
  return state.primaryArtifact;
28
36
  }
29
37
 
30
- /**
31
- * Resolve the `state.named` key a produces stage appends its `Output`
32
- * envelope onto. Two layers of fallback, in priority order:
33
- * 1. `stage.outcome?.name` — categorical name carried by the outcome.
34
- * 2. The stage's record key — always defined.
35
- *
36
- * Single source of truth for the key derivation so the skill-stage path
37
- * and the script-stage path stay in lockstep, and so `validateWorkflow`
38
- * can compute the same key set at load time.
39
- */
40
- export function resolvePublishName(def: StageDef, stageName: string): string {
41
- return def.outcome?.name ?? stageName;
42
- }
43
-
44
- /**
45
- * Resolve a stage's effective skill — the contract-registry key. Twin of
46
- * `resolvePublishName`. Single source of truth so the runtime resolution
47
- * (`resolveStage`) and the load-time lookups (`validate-workflow.ts`) key the
48
- * registry identically and can't drift.
49
- */
50
- export function resolveSkill(def: StageDef, stageName: string): string {
51
- return def.skill ?? stageName;
52
- }
53
-
54
- /**
55
- * A stage dispatches a `/skill:<name>` exactly when it carries neither a `run`
56
- * (script body) nor a `prompt` (raw-text body). `fanout`/`iterate` stages carry
57
- * neither, so they ARE dispatching stages. The shared predicate for every site
58
- * that treats `resolveSkill`'s result as a REAL skill identity — the alias
59
- * remap + its no-op warning, contract harvest, and the validator's contract
60
- * lookups must all agree, or a script/prompt stage whose record key matches a
61
- * registered skill inherits that skill's contract by accident.
62
- *
63
- * A TYPE GUARD since the StageDef union (T1): a positive narrows to
64
- * `SkillStage`, so callers that wire skill-derived data onto the stage
65
- * (the alias remap, outcome derivers) get the writable arm.
66
- */
67
- export function isDispatchingStage(stage: StageDef): stage is SkillStage {
68
- return stage.run == null && stage.prompt == null;
69
- }
70
-
71
38
  /**
72
39
  * Resolve a stage's `prompt` dispatch text — the COMPLETE user message a
73
40
  * prompt stage sends (no `/skill:` prefix, no implicit arg). The dynamic form
@@ -84,23 +51,18 @@ export async function resolveStagePrompt(prompt: string | PromptFn, cwd: string,
84
51
  return prompt({ cwd, input: state.output, state });
85
52
  }
86
53
 
54
+ const isPromptStage = (def: StageDef): boolean => def.prompt !== undefined;
55
+
56
+ const usesOriginalInput = (def: StageDef, stageName: string, startStage: string): boolean =>
57
+ stageName === startStage || def.inheritsArtifacts === false;
58
+
59
+ const hasReads = (def: StageDef): def is StageDef & { reads: NonNullable<StageDef["reads"]> } =>
60
+ def.reads !== undefined && def.reads.length > 0;
61
+
87
62
  /**
88
63
  * The single arg-projection authority: the string a stage's
89
64
  * `/skill:<name> <args>` prompt carries, derived purely from
90
- * (def, stageName, startStage, state). Five cases in priority order:
91
- * 0. A prompt-dispatch stage (`def.prompt` set) owns its WHOLE message —
92
- * no skill args exist; returns `""` (never `undefined`: the missing-input
93
- * refusal arms below must not fire for a stage that doesn't consume the
94
- * rolling primary or named reads). The round-0 producer message of a
95
- * prompt-dispatch loop is `resolveStagePrompt`, not this projection.
96
- * 1. The start stage receives `originalInput` (the user's brief).
97
- * 2. A stage opting out of inheritance (`inheritsArtifacts: false`,
98
- * i.e. authored via `terminal()`) also receives `originalInput`.
99
- * 3. A stage with `reads: [...]` receives the labelled multi-flag form
100
- * `--<name1> <handle1> --<name2> <handle2> …` — each name resolves
101
- * against `state.named[name].at(-1)`; a multi-artifact entry repeats
102
- * the flag.
103
- * 4. Otherwise: the rolling primary artifact's handle string.
65
+ * (def, stageName, startStage, state).
104
66
  *
105
67
  * Returns `undefined` (instead of non-null-asserting) when a required
106
68
  * projection input is missing — the rolling primary is unset, or a `reads`
@@ -117,16 +79,34 @@ export function stageEntryArgs(
117
79
  startStage: string,
118
80
  state: RunState,
119
81
  ): string | undefined {
120
- if (def.prompt !== undefined) return "";
121
- if (stageName === startStage) return state.originalInput;
122
- if (def.inheritsArtifacts === false) return state.originalInput;
123
- if (def.reads?.length) {
82
+ if (isPromptStage(def)) return "";
83
+ if (usesOriginalInput(def, stageName, startStage)) return state.originalInput;
84
+ if (hasReads(def)) {
124
85
  const parts: string[] = [];
125
- for (const name of def.reads) {
126
- const latest = state.named[name]?.at(-1);
127
- if (!latest) return undefined;
128
- for (const artifact of latest.artifacts) {
129
- parts.push(`--${name}`, handleToString(artifact.handle));
86
+ for (const read of def.reads) {
87
+ const name = readName(read);
88
+ const slot = state.named[name];
89
+ if (!slot?.length) return undefined;
90
+ // `all` → every accumulated entry (fan-in); bare string → latest-wins.
91
+ // A produces-fanout channel is PRE-SIZED (length === total) and
92
+ // positionally filled, so a slot can carry `undefined` (pending) or a
93
+ // failed sentinel. The latest-wins branch must NOT `slot[length-1]!`
94
+ // blindly: scan backward for the last REAL entry, and the per-entry loop
95
+ // skips unfilled/failed slots so a `fanin(...)` read contributes no args
96
+ // for them (the `.filter(Boolean)` convention needs no widening).
97
+ //
98
+ // ALL-FAILED FANIN CONTRACT: pre-sizing means the channel is
99
+ // always present once the fold ran, so the `!slot?.length` bail no longer
100
+ // fires for a fanout channel; when EVERY unit failed/unfilled this read
101
+ // contributes ZERO `--name` args and `stageEntryArgs` returns the
102
+ // assembled (possibly empty) string — NEVER `undefined`. Collect-all
103
+ // fanout runs synthesis even when all units failed.
104
+ const entries = readsAll(read) ? slot : [lastReal(slot)];
105
+ for (const entry of entries) {
106
+ if (!entry || isFailedOutput(entry)) continue; // unfilled (pending) or failed → no args
107
+ for (const artifact of entry.artifacts) {
108
+ parts.push(`--${name}`, handleToString(artifact.handle));
109
+ }
130
110
  }
131
111
  }
132
112
  return parts.join(" ");
@@ -135,6 +115,18 @@ export function stageEntryArgs(
135
115
  return primary === undefined ? undefined : handleToString(primary.handle);
136
116
  }
137
117
 
118
+ /** The last REAL (filled, non-failed) entry of a channel slot — the latest-wins
119
+ * source. A produces-fanout channel is pre-sized + positionally filled, so its
120
+ * tail can be `undefined` (pending) or a failed sentinel; scan backward instead
121
+ * of asserting `slot[length-1]`. Returns `undefined` for an all-failed/empty slot. */
122
+ function lastReal(slot: readonly (Output | undefined)[]): Output | undefined {
123
+ for (let i = slot.length - 1; i >= 0; i--) {
124
+ const o = slot[i];
125
+ if (o && !isFailedOutput(o)) return o;
126
+ }
127
+ return undefined;
128
+ }
129
+
138
130
  /**
139
131
  * The single authority for "a completed produces stage mutates the rolling
140
132
  * artifact state." Called by the live skill path (sessions/sessions.ts), the
@@ -151,6 +143,21 @@ export function stageEntryArgs(
151
143
  * - other side-effect → leave the slot untouched.
152
144
  */
153
145
  export function applyCompletedStage(state: RunState, def: StageDef, stageName: string, output: Output): void {
146
+ // Fanout owns its channel through the index-addressed `placeFanoutOutput`
147
+ // fold (foldFanoutCompletion), so the produces-channel push here would
148
+ // double-write. Early-return for fanout. But the acts/side-effect
149
+ // PRIMARY-CLEAR (`inheritsArtifacts === false`) is IDEMPOTENT (it only sets
150
+ // primary = undefined), so run it here for fanout TOO: the SEQUENTIAL path (a
151
+ // resumed/non-pristine acts-fanout that routes through `step` → `dispatchUnit`
152
+ // → `recordStageSuccess` → here, not through foldFanoutCompletion until parallel
153
+ // resume is wired) would otherwise lose the primary-clear the only
154
+ // shipped fanout kind (acts) relies on. Live acts-fanout calls BOTH this and
155
+ // placeFanoutOutput — both set primary = undefined, harmless. Produces-fanout's
156
+ // channel push stays fold-only (non-idempotent → must not double-write).
157
+ if (def.loop?.kind === "fanout") {
158
+ clearPrimaryForActs(state, def);
159
+ return;
160
+ }
154
161
  if (def.kind === "produces") {
155
162
  const next = output.artifacts[0];
156
163
  if (next) state.primaryArtifact = next;
@@ -163,7 +170,51 @@ export function applyCompletedStage(state: RunState, def: StageDef, stageName: s
163
170
  slot.push(output);
164
171
  return;
165
172
  }
166
- if (def.inheritsArtifacts === false) {
167
- state.primaryArtifact = undefined;
173
+ clearPrimaryForActs(state, def);
174
+ }
175
+
176
+ /**
177
+ * The acts/side-effect primary-clear rule, in ONE place: a `terminal()` stage
178
+ * (`inheritsArtifacts === false`) drops the rolling primary; every other
179
+ * side-effect leaves it. Idempotent and produces-safe (the `kind` guard makes it
180
+ * a no-op for produces stages, whose channel arm owns the primary). Shared by
181
+ * `applyCompletedStage` (the fanout early-return AND the sequential acts arm) and
182
+ * `placeFanoutOutput`, so the rule can't drift across the three sites.
183
+ */
184
+ function clearPrimaryForActs(state: RunState, def: StageDef): void {
185
+ if (def.kind !== "produces" && def.inheritsArtifacts === false) state.primaryArtifact = undefined;
186
+ }
187
+
188
+ // The fanout fold's SINGLE state-effect site. It subsumes BOTH
189
+ // arms of applyCompletedStage (which early-returns for fanout),
190
+ // index-addressed:
191
+ // • produces-fanout (collecting): pre-size the channel slot to `total`, assign
192
+ // the unit's output at its declared `index`; set primaryArtifact from
193
+ // artifacts[0] unless this is a failed sentinel (no artifacts).
194
+ // • acts-fanout (side-effect, def.kind !== "produces"): no channel; mirror the
195
+ // applyCompletedStage `inheritsArtifacts === false ⇒ clear primary` rule so
196
+ // today's acts-fanout semantics are preserved.
197
+ // Called ONLY by foldFanoutCompletion (live + resume).
198
+ export function placeFanoutOutput(
199
+ state: RunState,
200
+ def: StageDef,
201
+ stageName: string,
202
+ index: number,
203
+ total: number,
204
+ output: Output,
205
+ ): void {
206
+ if (def.kind === "produces") {
207
+ const key = resolvePublishName(def, stageName);
208
+ let slot = state.named[key];
209
+ if (!slot || slot.length !== total) {
210
+ slot = new Array<Output | undefined>(total) as Output[];
211
+ state.named[key] = slot;
212
+ }
213
+ slot[index] = output;
214
+ const next = output.artifacts[0];
215
+ if (next && !isFailedOutput(output)) state.primaryArtifact = next;
216
+ return;
168
217
  }
218
+ // acts/side-effect fanout — same primary-clear rule as the sequential path.
219
+ clearPrimaryForActs(state, def);
169
220
  }
package/command-run.ts CHANGED
@@ -111,24 +111,27 @@ export async function handleWorkflowCommand(host: WorkflowHost, args: string, ct
111
111
  return;
112
112
  }
113
113
 
114
- // runWorkflow returns a result envelope rather than throwing — but a
115
- // thrown predicate or invariant could still bubble. Catch so Pi's
116
- // dispatcher doesn't print a raw stack.
117
- try {
118
- const result = await runWorkflow(ctx, {
119
- workflow,
120
- input,
121
- host,
122
- trigger: { kind: "command", name: "wf" },
123
- name,
114
+ // Float the run off the prompt: /wf returns immediately; the run executes
115
+ // detached and appears as a lane. runWorkflow returns an envelope (never throws on
116
+ // run failure), but a thrown predicate/invariant could still bubble — .catch keeps
117
+ // Pi's dispatcher from printing a raw stack AND a floated promise from going
118
+ // unhandled (NFR).
119
+ void runWorkflow(ctx, {
120
+ workflow,
121
+ input,
122
+ host,
123
+ trigger: { kind: "command", name: "wf" },
124
+ name,
125
+ })
126
+ .then((result) => {
127
+ // Surface pre-flight rejections (collision, etc.) — no runId means no JSONL on disk.
128
+ if (!result.success && result.runId === undefined && result.error) {
129
+ ctx.ui.notify(result.error, "error");
130
+ }
131
+ })
132
+ .catch((e) => {
133
+ ctx.ui.notify(MSG_WORKFLOW_THREW(formatError(e)), "error");
124
134
  });
125
- // Surface pre-flight rejections (collision, etc.) — no runId means no JSONL on disk.
126
- if (!result.success && result.runId === undefined && result.error) {
127
- ctx.ui.notify(result.error, "error");
128
- }
129
- } catch (e) {
130
- ctx.ui.notify(MSG_WORKFLOW_THREW(formatError(e)), "error");
131
- }
132
135
  }
133
136
 
134
137
  // ---------------------------------------------------------------------------
@@ -140,19 +143,21 @@ async function handleResume(host: WorkflowHost, ctx: WorkflowHostContext, ref: s
140
143
  ctx.ui.notify(MSG_RESUME_USAGE, "error");
141
144
  return;
142
145
  }
143
- try {
144
- const result = await resumeWorkflowByRunId(ctx, ref, { host });
145
- // A failure with no runId is a no-JSONL refusal (run-id didn't resolve,
146
- // load error, workflow gone, or an unreconstructable trail) — nothing else
147
- // surfaces it, so notify here. An in-run failure carries a runId and was
148
- // already notified by the stage machinery via its JSONL failure row;
149
- // re-notifying would double up.
150
- if (!result.success && result.runId === undefined && result.error) {
151
- ctx.ui.notify(result.error, "error");
152
- }
153
- } catch (e) {
154
- ctx.ui.notify(MSG_WORKFLOW_THREW(formatError(e)), "error");
155
- }
146
+ // Float the resume off the prompt — identical shape to the run path.
147
+ void resumeWorkflowByRunId(ctx, ref, { host })
148
+ .then((result) => {
149
+ // A failure with no runId is a no-JSONL refusal (run-id didn't resolve,
150
+ // load error, workflow gone, or an unreconstructable trail) — nothing else
151
+ // surfaces it, so notify here. An in-run failure carries a runId and was
152
+ // already notified by the stage machinery via its JSONL failure row;
153
+ // re-notifying would double up.
154
+ if (!result.success && result.runId === undefined && result.error) {
155
+ ctx.ui.notify(result.error, "error");
156
+ }
157
+ })
158
+ .catch((e) => {
159
+ ctx.ui.notify(MSG_WORKFLOW_THREW(formatError(e)), "error");
160
+ });
156
161
  }
157
162
 
158
163
  // ---------------------------------------------------------------------------
package/command.ts CHANGED
@@ -14,7 +14,7 @@
14
14
  * `parseArgs` stays here (pure, exported for tests).
15
15
  */
16
16
 
17
- import type { WorkflowHost, WorkflowHostContext } from "./host.js";
17
+ import type { WorkflowHost, WorkflowHostContext, WorkflowLauncherContext } from "./host.js";
18
18
 
19
19
  /** Pi command registry — displayed by Pi's `/?` / command list. */
20
20
  export const CMD_DESCRIPTION = "Run a skill workflow: /wf [workflow] [description]";
@@ -39,7 +39,7 @@ export const PREWARM_DELAY_MS = 2000;
39
39
  type CommandRunModule = typeof import("./command-run.js");
40
40
 
41
41
  export interface WfCommandHandler {
42
- (args: string, ctx: WorkflowHostContext): Promise<void>;
42
+ (args: string, ctx: WorkflowLauncherContext): Promise<void>;
43
43
  /** Kick (or join) the memoized command-run import — the pre-warm entry. */
44
44
  prewarm(): Promise<void>;
45
45
  }
@@ -71,12 +71,18 @@ export function makeWfHandler(
71
71
  }
72
72
  };
73
73
 
74
- const handler = async (args: string, ctx: WorkflowHostContext): Promise<void> => {
74
+ const handler = async (args: string, ctx: WorkflowLauncherContext): Promise<void> => {
75
75
  // `ready`, not `memo`: an in-flight pre-warm still leaves the user
76
76
  // waiting, so the toast covers that window too.
77
77
  if (!ready && ctx.hasUI) ctx.ui.notify(MSG_RUNTIME_LOADING, "info");
78
78
  const mod = await load();
79
- return mod.handleWorkflowCommand(host, args, ctx);
79
+ // The launcher hands us an OBSERVER ctx (Pi's command ctx has no
80
+ // spawnChild/maxConcurrency). The run-path is typed against the executor
81
+ // ctx, but it never executes a stage on this ctx directly: with a provider
82
+ // registered, runWorkflow builds the detached executor; with
83
+ // none, the test/embedder contract guarantees an executor-capable ctx. So
84
+ // narrow here at the single Pi→runtime boundary.
85
+ return mod.handleWorkflowCommand(host, args, ctx as WorkflowHostContext);
80
86
  };
81
87
 
82
88
  return Object.assign(handler, {