@juicesharp/rpiv-workflow 1.20.0 → 2.0.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 (106) hide show
  1. package/api.ts +1 -1
  2. package/audit-ctx.ts +103 -0
  3. package/audit-rows.ts +18 -0
  4. package/audit.ts +119 -164
  5. package/built-ins.ts +26 -6
  6. package/chain-state.ts +119 -68
  7. package/command-run.ts +35 -30
  8. package/command.ts +10 -4
  9. package/docs/workflow-authoring.md +34 -2
  10. package/events.ts +44 -4
  11. package/execution-host.ts +75 -0
  12. package/host.ts +137 -82
  13. package/internal-utils.ts +89 -3
  14. package/internal.ts +1 -0
  15. package/judge.ts +23 -11
  16. package/load/alias.ts +3 -3
  17. package/load/index.ts +15 -1
  18. package/load/issues.ts +2 -2
  19. package/load/legacy.ts +2 -2
  20. package/load/resolve-default.ts +3 -4
  21. package/load/skill-contract-phase.ts +1 -1
  22. package/loop-constructors.ts +19 -618
  23. package/loop-def.ts +60 -15
  24. package/loop-kinds.ts +319 -62
  25. package/loop-parallel.ts +250 -0
  26. package/loop-waves.ts +99 -0
  27. package/loop.ts +106 -80
  28. package/loops/constructors.ts +334 -0
  29. package/loops/derivations.ts +65 -0
  30. package/loops/introspection.ts +184 -0
  31. package/loops/panel.ts +196 -0
  32. package/loops/verify.ts +99 -0
  33. package/messages.ts +58 -33
  34. package/outcomes/collectors/index.ts +1 -0
  35. package/outcomes/collectors/text-scan.ts +47 -0
  36. package/outcomes/collectors/transcript-path.ts +2 -15
  37. package/outcomes/collectors/union.ts +2 -1
  38. package/outcomes/collectors/url.ts +2 -14
  39. package/outcomes/collectors/workspace-diff.ts +1 -1
  40. package/outcomes/git-commit.ts +57 -6
  41. package/output-spec.ts +1 -1
  42. package/output.ts +59 -1
  43. package/package.json +16 -6
  44. package/preview.ts +18 -18
  45. package/registration.ts +11 -4
  46. package/routing-dsl.ts +53 -41
  47. package/routing.ts +46 -0
  48. package/runner/chain-advance.ts +30 -17
  49. package/runner/errors.ts +7 -30
  50. package/runner/failure.ts +67 -13
  51. package/runner/input-validation.ts +8 -5
  52. package/runner/preflight.ts +17 -21
  53. package/runner/resume-entry.ts +23 -3
  54. package/runner/resume-loop.ts +50 -29
  55. package/runner/resume.ts +96 -10
  56. package/runner/run-context.ts +20 -16
  57. package/runner/run-stage.ts +125 -91
  58. package/runner/runner.ts +163 -69
  59. package/runner/script-stage.ts +23 -29
  60. package/schema-compat.ts +1 -2
  61. package/semaphore.ts +55 -0
  62. package/sessions/extraction.ts +103 -60
  63. package/sessions/halt-routing.ts +195 -0
  64. package/sessions/index.ts +2 -2
  65. package/sessions/locate.ts +60 -9
  66. package/sessions/reattach.ts +28 -20
  67. package/sessions/sessions.ts +103 -191
  68. package/sessions/spawn.ts +132 -119
  69. package/sessions/success-persist.ts +89 -0
  70. package/skill-contracts/composition.ts +8 -10
  71. package/skill-contracts/harvest.ts +3 -2
  72. package/skill-contracts/registry.ts +1 -1
  73. package/stage-def.ts +115 -47
  74. package/stage-errors.ts +84 -0
  75. package/stage-identity.ts +56 -0
  76. package/startup.ts +1 -0
  77. package/state/paths.ts +11 -3
  78. package/state/raw.ts +2 -3
  79. package/state/resolve.ts +3 -3
  80. package/state/state.ts +26 -3
  81. package/state/writes.ts +1 -1
  82. package/types.ts +97 -43
  83. package/validate/contract-compat.ts +16 -11
  84. package/validate/graph.ts +10 -1
  85. package/validate/issue.ts +20 -6
  86. package/validate/stage-rules.ts +139 -60
  87. package/validate-output.ts +27 -20
  88. package/validate-workflow.ts +5 -3
  89. package/validation-bounds.ts +35 -0
  90. package/load/cache.test.ts +0 -82
  91. package/load/shape-guards.test.ts +0 -77
  92. package/outcomes/collectors/directory-path.test.ts +0 -64
  93. package/outcomes/collectors/tool-call.test.ts +0 -112
  94. package/outcomes/collectors/transcript-path.test.ts +0 -70
  95. package/outcomes/collectors/union.test.ts +0 -113
  96. package/outcomes/collectors/url.test.ts +0 -67
  97. package/outcomes/collectors/workspace-diff.test.ts +0 -120
  98. package/outcomes/git-commit.test.ts +0 -240
  99. package/outcomes/parsers/json-body.test.ts +0 -80
  100. package/runner/by-name.test.ts +0 -95
  101. package/runner/by-run-id.test.ts +0 -115
  102. package/runner/header-write-failure.test.ts +0 -64
  103. package/runner/resume-loop.test.ts +0 -1410
  104. package/runner/resume-session.test.ts +0 -400
  105. package/runner/resume.test.ts +0 -1805
  106. package/sessions/locate.test.ts +0 -77
package/host.ts CHANGED
@@ -3,77 +3,86 @@
3
3
  * environment, expressed in workflow-domain vocabulary.
4
4
  *
5
5
  * The package never re-exports `@earendil-works/pi-coding-agent` types
6
- * from its public surface. Pi's `ExtensionAPI` / `ExtensionCommandContext`
7
- * / `ReplacedSessionContext` structurally satisfy these ports, so
8
- * embedders pass their Pi handles directly without casting; consumers
9
- * wanting to drive the runtime from a non-Pi adapter implement these two
10
- * interfaces.
6
+ * from its public surface. Two host shapes implement these ports:
11
7
  *
12
- * - `WorkflowHost` — registry-level host (default-export ctor + continue-policy sender).
13
- * - `WorkflowHostContext` — per-command ctx passed into `runWorkflow`, also the
14
- * replacement ctx delivered to `newSession`'s `withSession`
15
- * callback. `sendUserMessage` is optional at the type
16
- * level (the outer command ctx may not carry one) but
17
- * the runtime guarantees it is present inside
18
- * `withSession`.
8
+ * - The interactive Pi launcher (`ExtensionCommandContext`) — satisfies the
9
+ * OBSERVER surface (`ui`/`sessionManager`/`hasUI`/`waitForIdle`) and is
10
+ * retained as a progress observer only; it no longer executes stages.
11
+ * - The detached executor host (`SdkWorkflowHost`, in rpiv-pi) — satisfies the
12
+ * FULL surface including `spawnChild`/`maxConcurrency`; it owns the child
13
+ * `AgentSession` pool every stage runs in.
19
14
  *
20
- * Compile-time tripwire: `host.test.ts` asserts Pi's concrete types
21
- * extend these ports. If Pi's API drifts (a method renames, a signature
22
- * tightens), `npm run check` fails immediately on that file.
15
+ * - `WorkflowHost` — registry-level host (default-export ctor +
16
+ * skill-registration preflight).
17
+ * - `WorkflowHostContext` — per-command ctx passed into `runWorkflow`; spawns
18
+ * child sessions and never swaps itself out.
19
+ *
20
+ * Compile-time tripwire: `host.test.ts` asserts Pi's concrete observer types
21
+ * extend the observer surface; `rpiv-pi`'s `sdk-workflow-host.test.ts` asserts
22
+ * `SdkWorkflowHost` satisfies the full executor port (the satisfaction
23
+ * assertion lives there because rpiv-workflow must not import rpiv-pi).
23
24
  */
24
25
 
25
26
  /**
26
- * Registry-level host. Default-exported function receives this; the
27
- * runner also uses it for continue-policy stages (sends into the
28
- * already-streaming agent) and for skill-registration preflight.
27
+ * Registry-level host. Default-exported function receives this; the runner
28
+ * uses it for skill-registration preflight (enumerating registered commands).
29
29
  *
30
- * The three methods we touch on Pi's `ExtensionAPI`. Anything beyond
31
- * these is invisible to the runtime.
30
+ * The two methods we touch on Pi's `ExtensionAPI`. Anything beyond these is
31
+ * invisible to the runtime. (`sendUserMessage` was removed with the
32
+ * continue-policy host-fallback ladder — every stage now holds a live child
33
+ * ctx, so the registry-level sender has no caller.)
32
34
  */
33
35
  export interface WorkflowHost {
34
- /** Register a slash command. Used by the `/wf` entry point. */
36
+ /** Register a slash command. Used by the `/wf` entry point. The handler
37
+ * receives the LAUNCHER ctx (observer surface) — the interactive Pi
38
+ * `ExtensionCommandContext` Pi delivers; it constructs the executor host
39
+ * that actually runs stages. Typing the ctx as the executor
40
+ * `WorkflowHostContext` here would demand `spawnChild`/`maxConcurrency` of
41
+ * Pi's ctx and break the `host.test.ts` tripwire (Pi's ctx is an OBSERVER). */
35
42
  registerCommand(
36
43
  name: string,
37
44
  options: {
38
45
  description?: string;
39
- handler: (args: string, ctx: WorkflowHostContext) => Promise<void>;
46
+ handler: (args: string, ctx: WorkflowLauncherContext) => Promise<void>;
40
47
  },
41
48
  ): void;
42
- /**
43
- * Send a user message into the active agent stream. Used by the
44
- * continue-policy session handler.
45
- *
46
- * Pi declares this `void` at the type level but returns a Promise at
47
- * runtime; we declare `void | Promise<void>` so `await` is safe in
48
- * either world.
49
- */
50
- sendUserMessage(content: string): void | Promise<void>;
51
49
  /** Enumerate currently registered slash commands. Used by skill-registration preflight. */
52
50
  getCommands(): ReadonlyArray<{ name: string; source: string }>;
53
51
  }
54
52
 
55
53
  /**
56
- * Per-command host ctx. Embedders hand this to `runWorkflow`; the
57
- * runner threads it (and any replacement ctx returned by `newSession`)
54
+ * The observer-only ctx the registry-level host hands the `/wf` handler. The
55
+ * launcher relays progress through it and constructs the executor host that
56
+ * runs stages; it excludes the executor additions (`spawnChild`/
57
+ * `maxConcurrency`) so Pi's `ExtensionCommandContext` structurally satisfies it
58
+ * (and `ExtensionAPI` therefore satisfies `WorkflowHost` — the tripwire).
59
+ */
60
+ export type WorkflowLauncherContext = Omit<WorkflowHostContext, "spawnChild" | "maxConcurrency">;
61
+
62
+ /**
63
+ * Resolved per-unit model override, applied by the host at child-session
64
+ * creation — NOT via global mutation. `model` is a host-opaque model key the
65
+ * host's adapter resolves through its own registry; `thinking` mirrors Pi's
66
+ * thinking levels. Both optional — absent means "host default".
67
+ */
68
+ export interface ModelSelection {
69
+ model?: string;
70
+ thinking?: "off" | "minimal" | "low" | "medium" | "high" | "xhigh";
71
+ }
72
+
73
+ /**
74
+ * Per-command host ctx. Embedders hand this to `runWorkflow`; the runner
75
+ * threads it (and the child ctx delivered to each `spawnChild`'s `withSession`)
58
76
  * through stages.
59
77
  *
60
- * Exhaustive list of members the runtime touches — adding any reach
61
- * outside this list is a port-widening decision, not an oversight.
62
- *
63
- * `sendUserMessage` is declared optional HERE because the outer command
64
- * ctx Pi delivers to a `/wf` handler does not carry one. The replacement
65
- * ctx delivered inside `newSession`'s `withSession` callback always does
66
- * — that stronger guarantee is modelled by the `WorkflowSessionContext`
67
- * subtype below, which `withSession` delivers. Code holding a bare
68
- * `WorkflowHostContext` (the workflow-start path before any session
69
- * opens) must still null-check before calling.
78
+ * Exhaustive list of members the runtime touches — adding any reach outside
79
+ * this list is a port-widening decision, not an oversight.
70
80
  */
71
81
  export interface WorkflowHostContext {
72
82
  cwd: string;
73
83
  hasUI: boolean;
74
84
  ui: {
75
85
  notify(message: string, level?: "info" | "warning" | "error"): void;
76
- setStatus(key: string, text: string | undefined): void;
77
86
  };
78
87
  sessionManager: {
79
88
  /**
@@ -82,59 +91,105 @@ export interface WorkflowHostContext {
82
91
  * type here would break the no-cast structural pass-through of Pi's
83
92
  * ctx. The runtime never calls this directly: `readBranch(ctx)`
84
93
  * (transcript.ts) is the single boundary that narrows the value to
85
- * `BranchEntry[]`, the workflow-domain transcript shape.
94
+ * `BranchEntry[]`.
86
95
  */
87
96
  getBranch(): unknown;
88
97
  /**
89
98
  * Session identity + on-disk location of the active session — read by
90
- * `readSessionRef` (transcript.ts) so every stage row records which Pi
91
- * session backed it (`WorkflowStage.session`). `getSessionFile` is
92
- * `undefined` for non-persisting (in-memory) sessions. Both already
93
- * exist on Pi's `ReadonlySessionManager` — type-only widening; the
94
- * tripwire proves it.
99
+ * `readSessionRef` (transcript.ts) so every stage row records which
100
+ * session backed it. `getSessionFile` is `undefined` for non-persisting
101
+ * (in-memory) sessions.
95
102
  */
96
103
  getSessionId(): string;
97
104
  getSessionFile(): string | undefined;
98
105
  };
99
106
  waitForIdle(): Promise<void>;
107
+
108
+ /** Cooperative cancellation handle the launcher forwards into `runWorkflow`.
109
+ * On Pi this is `ExtensionCommandContext.signal`; optional so non-Pi
110
+ * embedders / the observer-only surface need not provide it. */
111
+ signal?: AbortSignal;
112
+
113
+ /** Max child sessions runnable at once. 1 ⇒ sequential. The loop reads this;
114
+ * it never invents a number. */
115
+ readonly maxConcurrency: number;
116
+
100
117
  /**
101
- * Open a fresh session and run `withSession` on the replacement ctx.
102
- * Returns `{ cancelled: true }` if the host declined to spawn (user
103
- * dismissed the swap, etc.). `cancelled: false` implies the outer
104
- * ctx is now invalidated — all further work runs on the replacement
105
- * delivered to `withSession`.
106
- */
107
- newSession(options: {
108
- withSession: (replacement: WorkflowSessionContext) => Promise<void>;
109
- }): Promise<{ cancelled: boolean }>;
110
- /**
111
- * Optional on the base port — only the outer command ctx lacks it.
112
- * Inside a session use `WorkflowSessionContext`, where it is required.
113
- */
114
- sendUserMessage?(content: string): Promise<void>;
115
- /**
116
- * Reopen a persisted session file at its leaf and run `withSession` on
117
- * the replacement ctx — the resume promotion/reattach path
118
- * (`resumeStageWithSession`, run-stage.ts) adopts an interrupted stage's
119
- * session through this. Declared exactly like `newSession`; OPTIONAL like
120
- * `sendUserMessage` — only command-capable contexts carry it, and a host
121
- * without it degrades to cold re-run (the fallback ladder's rung 3).
118
+ * Spawn an isolated child session, send `prompt`, run `body` on its ctx,
119
+ * return body's result. The PARENT ctx STAYS VALID (no swap). The runner may
120
+ * have up to `maxConcurrency` spawnChild calls in flight at once.
121
+ *
122
+ * `model` is the resolved per-unit override, applied by the host at session
123
+ * creation — NOT via global mutation. `signal`, when provided, lets the host abort THIS
124
+ * child mid-flight (`session.abort()`/`dispose()`) the moment it fires —
125
+ * the dispatcher threads `run.signal` here so an aborted run interrupts
126
+ * in-flight children, not just between stages.
127
+ *
128
+ * `reattach`, when provided, makes the host OPEN the persisted session at
129
+ * `sessionFile` IN PLACE (appending to it) instead of creating a fresh one,
130
+ * and DELIVER it to `withSession` WITHOUT sending `prompt` — the prior turn
131
+ * already ran, so the body promotes from the existing branch or re-prompts via
132
+ * `sendUserMessage`. This is the detached replacement for the deleted
133
+ * adopt-a-file session-swap path: session-backed resume of a failed
134
+ * single stage (`resumeWithSessionLadder`) and per-unit reattach
135
+ * both spawn a reattaching child rather than swapping the live session.
136
+ * On a non-persisting (in-memory) host or a missing
137
+ * file the host falls back to a fresh child; the runner already gates
138
+ * `reattach` on a `locateSessionFile` hit, so the file is known to exist.
139
+ *
140
+ * `fork`, when provided, makes the host FORK the persisted session at
141
+ * `sessionFile` into a NEW child session (new id, new file) carrying the full
142
+ * prior transcript as context, WITHOUT mutating the source file and WITHOUT
143
+ * sending `prompt` (the body sends the continuation turn via `sendUserMessage`,
144
+ * then measures the inherited prefix). This is how `sessionPolicy: "continue"`
145
+ * continues its predecessor's conversation under detachment — the predecessor's
146
+ * file stays intact (DAG-fork-safe; the continue child has its own resumable
147
+ * identity). The runner gates `fork` on a `locateSessionFile` hit, so the file
148
+ * is known to exist. At most one of `reattach` / `fork` is set; both suppress
149
+ * the host's initial `prompt` send.
122
150
  */
123
- switchSession?(
124
- sessionPath: string,
125
- options: { withSession: (replacement: WorkflowSessionContext) => Promise<void> },
126
- ): Promise<{ cancelled: boolean }>;
151
+ spawnChild<T>(options: {
152
+ prompt: string;
153
+ model?: ModelSelection;
154
+ signal?: AbortSignal;
155
+ reattach?: { sessionFile: string };
156
+ fork?: { sessionFile: string };
157
+ /**
158
+ * The fan-out unit index for this spawn, surfaced so a lane-aware host can
159
+ * publish the child under a per-unit registry slot (rpiv-pi's lane dock/viewer).
160
+ * Set by `openChild` from `StageSession.unit?.index`; undefined for a non-fan-out
161
+ * single stage (and for reattach/fork), which the host maps to its reserved
162
+ * single-unit slot. Purely an observability hint — a non-lane host ignores it and
163
+ * it NEVER affects execution.
164
+ */
165
+ unitIndex?: number;
166
+ withSession: (child: WorkflowSessionContext) => Promise<T>;
167
+ }): Promise<T>;
127
168
  }
128
169
 
129
170
  /**
130
- * The replacement ctx delivered to `newSession`'s `withSession` callback.
131
- * Identical to `WorkflowHostContext` except `sendUserMessage` is
132
- * GUARANTEED present — Pi always wires a sender into a freshly-opened
133
- * session. Narrowing the optional to required here turns what used to be
134
- * a runtime `if (!ctx.sendUserMessage) throw` guard into a compile-time
135
- * fact for every caller operating inside a session. `host.test.ts`
136
- * asserts Pi's internal replacement ctx still satisfies this.
171
+ * The child ctx delivered to `spawnChild`'s `withSession` callback. The parent
172
+ * `WorkflowHostContext` declares NO sender; this session subtype ADDS
173
+ * `sendUserMessage` as the guaranteed in-session sender — the host always wires
174
+ * one into a freshly-spawned child session. So any caller operating inside a
175
+ * session can send without a presence check, a compile-time fact of the subtype.
137
176
  */
138
177
  export interface WorkflowSessionContext extends WorkflowHostContext {
139
178
  sendUserMessage(content: string): Promise<void>;
179
+
180
+ /**
181
+ * Set by a watchdog-equipped host (rpiv-pi) when it aborted THIS child because a
182
+ * single tool call (bash) overran the per-command wall-clock ceiling; returns the
183
+ * failure reason for the recorded row, or `undefined` when no watchdog fired.
184
+ *
185
+ * The watchdog aborts via `session.abort()`, so the timeout reaches `postStage` as
186
+ * a `stopReason:"aborted"` branch — indistinguishable from a run/user abort by the
187
+ * transcript alone. This getter is the out-of-band channel that tells the two apart:
188
+ * a watchdog timeout routes through the soft-halt gate (a collect-all unit records a
189
+ * non-terminal failed row so the fan-out gate still finalizes; a non-fan-out stage
190
+ * fails terminally) INSTEAD of throwing `WorkflowAbortError` — which would re-dispatch
191
+ * the SAME runaway command on resume and wedge again. Optional: a host without a
192
+ * watchdog omits it and every abort stays a plain abort.
193
+ */
194
+ toolTimeout?(): { reason: string } | undefined;
140
195
  }
package/internal-utils.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * Internal utilities shared across the rpiv-workflow package — GENERIC
3
3
  * helpers only (error rendering, timeouts, global slots, structural
4
- * equality). Workflow-domain helpers live in their domain modules:
4
+ * equality, construction-time throw helpers). Workflow-domain helpers
5
+ * live in their domain modules:
5
6
  * chain/artifact authorities in `chain-state.ts`, audit-row plumbing in
6
7
  * `audit-rows.ts`, schema-timeout signalling in `validate-output.ts`.
7
8
  *
@@ -17,6 +18,36 @@ export function assertNever(value: never): never {
17
18
  throw new Error(`assertNever: unreachable value ${String(value)}`);
18
19
  }
19
20
 
21
+ /**
22
+ * Throw an `Error` whose message follows the authoring-surface convention
23
+ * `${origin}: ${message}` — the ONE spelling of that prefix every
24
+ * construction-time throw uses (defineRoute / gate / match / fanin /
25
+ * unionCollectors / …). Same plain `Error` (no named subclass) as the inline
26
+ * throws it replaces, so error posture and propagation are unchanged.
27
+ */
28
+ export function throwInvalid(origin: string, message: string): never {
29
+ throw new Error(`${origin}: ${message}`);
30
+ }
31
+
32
+ /**
33
+ * Assert `value` is a non-empty string, else throw via
34
+ * `throwInvalid(origin, requirement)`. The non-empty-string validation
35
+ * cluster: construction-time throws that reject a blank/whitespace stage name,
36
+ * channel name, flag, or fallback. `opts.trim` (default `false`) switches the
37
+ * empty check from zero-length to trimmed-zero-length — the lone
38
+ * `{ trim: true }` site is `depArtifactFlag`, where a whitespace-only flag would
39
+ * inject a bare ` <path>` with no marker.
40
+ */
41
+ export function requireNonEmptyString(
42
+ value: unknown,
43
+ origin: string,
44
+ requirement: string,
45
+ opts?: { trim?: boolean },
46
+ ): asserts value is string {
47
+ const empty = typeof value !== "string" || (opts?.trim ? value.trim().length === 0 : value.length === 0);
48
+ if (empty) throwInvalid(origin, requirement);
49
+ }
50
+
20
51
  /**
21
52
  * Render a caught `unknown` as a human-readable message. The ONE spelling of
22
53
  * the `instanceof Error` dance — every catch block that needs the reason as a
@@ -29,6 +60,40 @@ export function formatError(e: unknown): string {
29
60
  /** Single source of ISO-8601 timestamps for audit rows + output meta. */
30
61
  export const nowIso = (): string => new Date().toISOString();
31
62
 
63
+ /**
64
+ * The abort marker the detached-execution runtime throws when a child session is
65
+ * aborted (run-level Ctrl-C or a fail-fast sibling halt). `session.abort()` makes
66
+ * the SDK `prompt()` RESOLVE with a `stopReason:"aborted"` message (it does NOT
67
+ * reject), so the runtime detects that stop and
68
+ * throws THIS before any audit row is written: the fold's `isAbortError` check
69
+ * then leaves the slot unfilled so resume re-dispatches the unit.
70
+ *
71
+ * `name` is "WorkflowAbortError" — deliberately NOT "AbortError" — so it never
72
+ * collides with the DOM/third-party `AbortError` thrown by unrelated aborts;
73
+ * `isAbortError` is `instanceof`-based (not name-based) for the same reason.
74
+ */
75
+ export class WorkflowAbortError extends Error {
76
+ constructor(message = "aborted") {
77
+ super(message);
78
+ this.name = "WorkflowAbortError";
79
+ }
80
+ }
81
+
82
+ export const isAbortError = (e: unknown): e is WorkflowAbortError => e instanceof WorkflowAbortError;
83
+
84
+ /**
85
+ * Thrown on a programmer-error misconfiguration of a runtime primitive (e.g. a
86
+ * `Semaphore` constructed with `limit < 1`). A named type — matching the
87
+ * package convention (`WorkflowAbortError`, `StagePreflightError`) — so a
88
+ * misconfiguration surfaces a typed error rather than a bare `Error`.
89
+ */
90
+ export class WorkflowConfigError extends Error {
91
+ constructor(message: string) {
92
+ super(message);
93
+ this.name = "WorkflowConfigError";
94
+ }
95
+ }
96
+
32
97
  /**
33
98
  * Create a lazily-initialised global-slot getter anchored on a `Symbol.for` key.
34
99
  * The returned function reads from `globalThis` on every call, initialising the
@@ -52,11 +117,32 @@ export function globalSlot<T>(key: symbol, init: () => T): () => T {
52
117
  };
53
118
  }
54
119
 
120
+ /**
121
+ * Read a symbol-keyed property off a function object — the centralised
122
+ * alternative to sprinkling `obj as unknown as Record<symbol, T>` at every
123
+ * read site. Returns `undefined` when the symbol is unset. `globalSlot` is the
124
+ * twin for `globalThis`-anchored slots; this pair is for properties stored on
125
+ * plain function objects (the `READS_DATA` / `ROUTE_NOTE` / `CANONICAL_FOLD`
126
+ * family). One cast lives here so the domain modules read intent, not mechanics.
127
+ */
128
+ export function readSymbol<T>(obj: object, sym: symbol): T | undefined {
129
+ return (obj as Record<symbol, T | undefined>)[sym];
130
+ }
131
+
132
+ /**
133
+ * Write a symbol-keyed property onto a function object — the centralised write
134
+ * twin of `readSymbol`. The domain modules' sugar constructors / factories call
135
+ * this instead of inlining the `as unknown as Record<symbol, T>` cast.
136
+ */
137
+ export function markSymbol<T>(obj: object, sym: symbol, value: T): void {
138
+ (obj as Record<symbol, T>)[sym] = value;
139
+ }
140
+
55
141
  /**
56
142
  * Register-providers / flush-on-demand lifecycle over global slots —
57
143
  * the shared structure behind `registerBuiltInsProvider`/`flushBuiltInProviders`
58
144
  * and their skill-contract twins, which were implemented twice near
59
- * line-for-line (D2). The one real divergence — error posture — is the
145
+ * line-for-line. The one real divergence — error posture — is the
60
146
  * `onError` parameter: when given, each provider throw is RECORDED via the
61
147
  * callback (the registry stays usable, the caller drains and surfaces);
62
148
  * when omitted, a throw rejects the flush promise (trusted in-process
@@ -131,7 +217,7 @@ export function lazyProviderRegistry(key: string, opts?: { onError: (err: unknow
131
217
  /**
132
218
  * Race a promise against `ms`. The inner promise is NOT cancelled — Pi's
133
219
  * `ctx.waitForIdle()` has no abort signal today; the dangling promise becomes
134
- * inert when the next stage's `newSession` replaces the ctx.
220
+ * inert once the child session it was waiting on is disposed.
135
221
  *
136
222
  * When `message` is a string, a plain `Error` is thrown on timeout
137
223
  * (backward-compatible). When `message` is an `Error` instance (e.g.
package/internal.ts CHANGED
@@ -33,6 +33,7 @@
33
33
  export { recordStage } from "./audit.js";
34
34
  export { __resetBuiltIns, flushBuiltInProviders, getBuiltIns } from "./built-ins.js";
35
35
  export { __resetLifecycleRegistry } from "./events.js";
36
+ export { __resetWorkflowExecutionHost } from "./execution-host.js";
36
37
  export { __resetLoadCache } from "./load/cache.js";
37
38
  export {
38
39
  __resetSkillContracts,
package/judge.ts CHANGED
@@ -15,15 +15,17 @@
15
15
  * N judges with a vote fold. Keeping the termination predicate off `Judge`
16
16
  * is what makes the concept reusable across all three.
17
17
  *
18
- * Leaf module — type-only imports; safe on the runner-free `registration`
18
+ * Leaf module — value imports are limited to `internal-utils.ts` (the
19
+ * `readSymbol`/`markSymbol` leaf, which is itself runner-free); otherwise
20
+ * type-only. Safe on the runner-free `registration`
19
21
  * surface (siblings register built-ins without dragging the runner in).
20
22
  */
21
23
 
22
24
  import type { Artifact } from "./handle.js";
25
+ import { markSymbol, readSymbol } from "./internal-utils.js";
23
26
  import type { Output, RunView } from "./output.js";
24
27
  import type { Outcome } from "./output-spec.js";
25
28
 
26
- /** Context handed to a dynamic `Judge.prompt`. */
27
29
  export interface JudgeContext {
28
30
  cwd: string;
29
31
  /** Latest producer output (also the session's input handle). */
@@ -31,7 +33,6 @@ export interface JudgeContext {
31
33
  /** Frozen stage-entry primary, referenceable; the author embeds it if wanted. */
32
34
  entryArtifact: Artifact | undefined;
33
35
  state: RunView;
34
- /** 0-based round index. */
35
36
  round: number;
36
37
  }
37
38
 
@@ -67,7 +68,6 @@ interface JudgeBase {
67
68
  /** Skill dispatch: `/skill:<skill> <producerHandle>` (handle auto-injected). */
68
69
  export interface SkillJudge extends JudgeBase {
69
70
  skill: string;
70
- /** Structurally absent — skill XOR prompt (both is ambiguous). */
71
71
  prompt?: never;
72
72
  }
73
73
 
@@ -78,7 +78,6 @@ export interface SkillJudge extends JudgeBase {
78
78
  */
79
79
  export interface PromptJudge extends JudgeBase {
80
80
  prompt: string | JudgePromptFn;
81
- /** Structurally absent — skill XOR prompt (both is ambiguous). */
82
81
  skill?: never;
83
82
  }
84
83
 
@@ -116,7 +115,7 @@ export type FoldFn = (verdicts: readonly Output[]) => unknown;
116
115
  * `outcome` is the canonical-vs-custom switch: ABSENT ⇒ the built-in
117
116
  * `PANEL_VERDICT` shape on the `<stage>-panel` channel (sugar fold); PRESENT ⇒
118
117
  * the author's schema + channel (raw fold). The two are kept disjoint by a hard
119
- * XOR enforced by the `panel()` factory (Phase 2) — never both.
118
+ * XOR enforced by the `panel()` factory — never both.
120
119
  */
121
120
  export interface PanelJudge {
122
121
  kind: "panel";
@@ -169,12 +168,12 @@ export function marksCanonicalFold(fold: FoldFn): boolean {
169
168
 
170
169
  /** The sugar constructor that produced `fold` (`majority`/`all`/`any`), or `undefined` for a raw author closure. */
171
170
  export function canonicalFoldName(fold: FoldFn): CanonicalFoldName | undefined {
172
- return (fold as unknown as Record<symbol, CanonicalFoldName | undefined>)[CANONICAL_FOLD];
171
+ return readSymbol<CanonicalFoldName>(fold, CANONICAL_FOLD);
173
172
  }
174
173
 
175
174
  /** Attach the `CANONICAL_FOLD` brand (the sugar name) and return the fold — the ONE write site (sugar constructors). */
176
175
  export function brandCanonicalFold(name: CanonicalFoldName, fold: FoldFn): FoldFn {
177
- (fold as unknown as Record<symbol, CanonicalFoldName>)[CANONICAL_FOLD] = name;
176
+ markSymbol(fold, CANONICAL_FOLD, name);
178
177
  return fold;
179
178
  }
180
179
 
@@ -204,15 +203,28 @@ export function judgeShapeIssues(candidate: unknown): string[] {
204
203
  return issues;
205
204
  }
206
205
 
206
+ /**
207
+ * THE collect-then-throw-first idiom — one named operation for the
208
+ * `*ShapeIssues(candidate)` → throw-on-first policy the judge/assess/verify/
209
+ * panel factories share. Throws `new Error(`${ctor}(): ${issues[0]}`)` iff the
210
+ * rule source found any violation; the remaining issues are deliberately
211
+ * discarded (one actionable error at the authoring site). The load gate
212
+ * (`validate/stage-rules.ts`) consumes the SAME rule sources via collect-and-
213
+ * report (it does NOT route through here — assertShape owns only the
214
+ * throw-first shape).
215
+ */
216
+ export function assertShape(ctor: string, issues: string[]): void {
217
+ if (issues.length > 0) throw new Error(`${ctor}(): ${issues[0]}`);
218
+ }
219
+
207
220
  /**
208
221
  * Promote a judge literal to a validated `Judge` — identity passthrough that
209
222
  * throws on an invalid shape, so a `judge(...)`-authored value is correct by
210
223
  * construction (cf. `defineRoute`). Composes into `assess({ judge: judge({...}) })`
211
- * today and `panel(judge({...}), judge({...}))` in the follow-up.
224
+ * and `panel(judge({...}), judge({...}))` today.
212
225
  */
213
226
  export function judge(spec: Judge): Judge {
214
- const issues = judgeShapeIssues(spec);
215
- if (issues.length > 0) throw new Error(`judge(): ${issues[0]}`);
227
+ assertShape("judge", judgeShapeIssues(spec));
216
228
  return spec;
217
229
  }
218
230
 
package/load/alias.ts CHANGED
@@ -21,13 +21,13 @@
21
21
  */
22
22
 
23
23
  import type { Workflow } from "../api.js";
24
- import { isDispatchingStage, resolveSkill } from "../chain-state.js";
24
+ import { isDispatchingStage, resolveSkill } from "../stage-identity.js";
25
25
  import type { LayerOutcome, LoadAccumulator } from "./merge.js";
26
26
 
27
27
  // `isDispatchingStage` lives beside `resolveSkill` in chain-state.ts (the
28
28
  // validator and harvest consume it without reaching into load/); re-exported
29
- // here for existing consumers of the old path.
30
- export { isDispatchingStage } from "../chain-state.js";
29
+ // here for existing consumers.
30
+ export { isDispatchingStage } from "../stage-identity.js";
31
31
 
32
32
  export function aliasSkills(w: Workflow, aliases: Record<string, string>): Workflow {
33
33
  if (!aliases || Object.keys(aliases).length === 0) return w;
package/load/index.ts CHANGED
@@ -54,7 +54,8 @@
54
54
  */
55
55
 
56
56
  import type { Workflow } from "../api.js";
57
- import { flushBuiltInProviders, getBuiltIns } from "../built-ins.js";
57
+ import { drainBuiltInProviderErrors, flushBuiltInProviders, getBuiltIns } from "../built-ins.js";
58
+ import { formatError } from "../internal-utils.js";
58
59
  import type { ConfigLayer } from "../layers.js";
59
60
  import type { SkillContractMap } from "../skill-contract.js";
60
61
  import { validateWorkflow } from "../validate-workflow.js";
@@ -139,6 +140,19 @@ export async function loadWorkflows(cwd: string): Promise<LoadedWorkflows> {
139
140
  sources: new Map(),
140
141
  sourcePaths: new Map(),
141
142
  };
143
+ // Built-in provider failures — each provider throw was RECORDED (not
144
+ // propagated) during `flushBuiltInProviders()`; drain and surface as issues
145
+ // so the loader keeps its never-throws contract without swallowing the
146
+ // failure. Runs before `getBuiltIns()` is read, so a provider that throws
147
+ // before registering contributes its error but (correctly) no workflows.
148
+ for (const err of drainBuiltInProviderErrors()) {
149
+ acc.issues.push({
150
+ kind: "load",
151
+ layer: "framework",
152
+ message: `built-in provider failed: ${formatError(err)}`,
153
+ severity: "warning",
154
+ });
155
+ }
142
156
  const layers: ConfigLayer[] = getBuiltIns().length > 0 ? ["built-in"] : [];
143
157
 
144
158
  for (const w of getBuiltIns()) {
package/load/issues.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * The loader's issue vocabulary — a LEAF module so `merge.ts` (and any other
3
3
  * pipeline stage) can name the `Issue` shape without importing the
4
- * orchestrator back (the one back-edge the load pipeline used to have, G4).
4
+ * orchestrator back.
5
5
  *
6
6
  * `layer`/`path` attribution lives ONLY here: `validateWorkflow` knows
7
7
  * nothing about config layers; the loader is the seam that has both
@@ -16,7 +16,7 @@ import type { WorkflowValidationIssue } from "../validate/issue.js";
16
16
  * Where a load issue originated: one of the config layers, or `"framework"`
17
17
  * — the loader's own machinery (skill-contract providers, outcome derivers,
18
18
  * collision tracking). The framework origin is honest attribution for
19
- * errors no config file caused; `"built-in"` used to be the dumping ground.
19
+ * errors no config file caused.
20
20
  */
21
21
  export type LoadIssueOrigin = ConfigLayer | "framework";
22
22
 
package/load/legacy.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Legacy-layout migration advisories — the notice strings AND the probes
3
- * that fire them (moved here from messages.ts + load/index.ts, M8: the
4
- * migration shell snippets are a loader concern, not UI constants).
3
+ * that fire them (the migration shell snippets are a loader concern, not
4
+ * UI constants).
5
5
  *
6
6
  * Each advisory is a `"warning"` (never blocks the run) probing a distinct
7
7
  * stale layout the unified `.rpiv/workflows/` move left behind. Sunset
@@ -11,10 +11,9 @@
11
11
  * `default` that doesn't name an existing workflow records an error and
12
12
  * falls through to the next layer.
13
13
  *
14
- * Historic note: this used to fall back to a hard-coded `"mid"` sentinel,
15
- * which encoded an rpiv-pi-specific bias inside a skill-agnostic package.
16
- * Siblings that want to ship a preferred default set it via the
17
- * config-file envelope at their own load time.
14
+ * This package is skill-agnostic: there is no hard-coded default, so a
15
+ * `"mid"`-sentinel bias never leaks into it. Siblings that want to ship a
16
+ * preferred default set it via the config-file envelope at their own load time.
18
17
  */
19
18
 
20
19
  import type { ConfigLayer } from "../layers.js";
@@ -8,7 +8,7 @@
8
8
  * Extracted from `loadWorkflows` so the orchestrator reads as a
9
9
  * sequence of phases. Every issue this phase emits is attributed to
10
10
  * `"framework"` — these are failures of provider/deriver machinery, not of
11
- * any config file (the old `layer: "built-in"` attribution was a lie).
11
+ * any config file.
12
12
  */
13
13
 
14
14
  import { formatError } from "../internal-utils.js";