@juicesharp/rpiv-workflow 1.19.1 → 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 (136) hide show
  1. package/README.md +81 -8
  2. package/api.ts +18 -703
  3. package/audit-ctx.ts +103 -0
  4. package/audit-rows.ts +154 -0
  5. package/audit.ts +158 -190
  6. package/built-ins.ts +40 -45
  7. package/chain-state.ts +220 -0
  8. package/command-run.ts +64 -31
  9. package/command.ts +123 -21
  10. package/docs/workflow-authoring.md +356 -63
  11. package/{lifecycle.ts → events.ts} +161 -37
  12. package/execution-host.ts +75 -0
  13. package/host.ts +149 -64
  14. package/index.ts +25 -81
  15. package/internal-utils.ts +171 -71
  16. package/internal.ts +22 -1
  17. package/judge.ts +241 -0
  18. package/layers.ts +10 -15
  19. package/load/alias.ts +6 -12
  20. package/load/cache.ts +9 -6
  21. package/load/index.ts +27 -106
  22. package/load/issues.ts +31 -0
  23. package/load/legacy.ts +102 -0
  24. package/load/merge.ts +2 -2
  25. package/load/resolve-default.ts +3 -4
  26. package/load/shape-guards.ts +3 -6
  27. package/load/skill-contract-phase.ts +94 -0
  28. package/loop-constructors.ts +24 -0
  29. package/loop-def.ts +285 -0
  30. package/loop-kinds.ts +750 -0
  31. package/loop-parallel.ts +250 -0
  32. package/loop-waves.ts +99 -0
  33. package/loop.ts +330 -0
  34. package/loops/constructors.ts +334 -0
  35. package/loops/derivations.ts +65 -0
  36. package/loops/introspection.ts +184 -0
  37. package/loops/panel.ts +196 -0
  38. package/loops/verify.ts +99 -0
  39. package/messages.ts +249 -156
  40. package/outcomes/collectors/directory-path.ts +7 -3
  41. package/outcomes/collectors/index.ts +1 -0
  42. package/outcomes/collectors/require-opt.ts +11 -0
  43. package/outcomes/collectors/text-scan.ts +47 -0
  44. package/outcomes/collectors/tool-call.ts +8 -3
  45. package/outcomes/collectors/transcript-path.ts +4 -18
  46. package/outcomes/collectors/union.ts +30 -10
  47. package/outcomes/collectors/url.ts +9 -14
  48. package/outcomes/collectors/workspace-diff.ts +21 -14
  49. package/outcomes/exec.ts +17 -0
  50. package/outcomes/git-commit.ts +190 -100
  51. package/outcomes/index.ts +1 -0
  52. package/outcomes/parsers/json-body.ts +2 -2
  53. package/outcomes/side-effect.ts +3 -3
  54. package/output-spec.ts +36 -10
  55. package/output.ts +98 -20
  56. package/package.json +27 -11
  57. package/predicates.ts +11 -8
  58. package/preview.ts +81 -21
  59. package/registration.ts +117 -36
  60. package/routing-dsl.ts +322 -0
  61. package/routing.ts +48 -2
  62. package/runner/by-name.ts +2 -1
  63. package/runner/by-run-id.ts +2 -1
  64. package/runner/chain-advance.ts +84 -56
  65. package/runner/errors.ts +10 -0
  66. package/runner/failure.ts +163 -0
  67. package/runner/index.ts +7 -13
  68. package/runner/input-validation.ts +16 -23
  69. package/runner/preflight.ts +169 -0
  70. package/runner/resolve-stage.ts +68 -0
  71. package/runner/resume-entry.ts +121 -0
  72. package/runner/resume-loop.ts +131 -0
  73. package/runner/resume.ts +368 -262
  74. package/runner/run-context.ts +165 -0
  75. package/runner/run-stage.ts +490 -0
  76. package/runner/runner.ts +202 -449
  77. package/runner/script-stage.ts +104 -112
  78. package/schema-compat.ts +12 -1
  79. package/semaphore.ts +55 -0
  80. package/sessions/extraction.ts +146 -81
  81. package/sessions/halt-routing.ts +195 -0
  82. package/sessions/index.ts +3 -1
  83. package/sessions/locate.ts +141 -0
  84. package/sessions/reattach.ts +71 -0
  85. package/sessions/sessions.ts +114 -199
  86. package/sessions/spawn.ts +132 -119
  87. package/sessions/success-persist.ts +89 -0
  88. package/skill-contract.ts +22 -25
  89. package/skill-contracts/composition.ts +86 -37
  90. package/skill-contracts/{registries.ts → extension-points.ts} +45 -12
  91. package/skill-contracts/harvest.ts +4 -4
  92. package/skill-contracts/index.ts +15 -8
  93. package/skill-contracts/registry.ts +33 -50
  94. package/stage-def.ts +595 -0
  95. package/stage-errors.ts +84 -0
  96. package/stage-identity.ts +56 -0
  97. package/startup.ts +4 -1
  98. package/state/index.ts +8 -1
  99. package/state/names.ts +91 -65
  100. package/state/paths.ts +20 -0
  101. package/state/raw.ts +77 -0
  102. package/state/reads.ts +103 -85
  103. package/state/resolve.ts +73 -0
  104. package/state/state.ts +135 -15
  105. package/state/writes.ts +29 -12
  106. package/transcript.ts +24 -0
  107. package/triggers.ts +11 -3
  108. package/types.ts +290 -78
  109. package/validate/contract-compat.ts +198 -0
  110. package/validate/graph.ts +134 -0
  111. package/validate/issue.ts +328 -0
  112. package/validate/stage-rules.ts +499 -0
  113. package/validate-output.ts +82 -7
  114. package/validate-workflow.ts +57 -759
  115. package/validation-bounds.ts +35 -0
  116. package/control-flow.ts +0 -135
  117. package/fanout.ts +0 -102
  118. package/iterate.ts +0 -155
  119. package/load/cache.test.ts +0 -82
  120. package/load/shape-guards.test.ts +0 -74
  121. package/outcomes/collectors/directory-path.test.ts +0 -64
  122. package/outcomes/collectors/tool-call.test.ts +0 -110
  123. package/outcomes/collectors/transcript-path.test.ts +0 -70
  124. package/outcomes/collectors/union.test.ts +0 -59
  125. package/outcomes/collectors/url.test.ts +0 -67
  126. package/outcomes/collectors/workspace-diff.test.ts +0 -107
  127. package/outcomes/git-commit.test.ts +0 -194
  128. package/outcomes/parsers/json-body.test.ts +0 -80
  129. package/runner/by-name.test.ts +0 -95
  130. package/runner/by-run-id.test.ts +0 -115
  131. package/runner/resume-fanout.test.ts +0 -331
  132. package/runner/resume-fanout.ts +0 -136
  133. package/runner/resume-iterate.test.ts +0 -444
  134. package/runner/resume-iterate.ts +0 -111
  135. package/runner/resume.test.ts +0 -1130
  136. package/runner/stage-lifecycle.ts +0 -500
package/index.ts CHANGED
@@ -10,87 +10,31 @@
10
10
  * like `@juicesharp/rpiv-pi` opt in by calling `registerBuiltIns(...)`
11
11
  * from their own extension entry.
12
12
  *
13
- * ─── Public surface, grouped by audience ────────────────────────────────
14
- *
15
- * 1. Authoring DSL — `./api.js`, `./predicates.js`, `./typebox-adapter.js`
16
- * What a `workflows.config.ts` author imports to declare a workflow:
17
- * `defineWorkflow`, `produces`, `acts`, `terminal`, `defineRoute`, `gate`,
18
- * `STOP` (terminal-edge sentinel; `"stop"` literal also valid),
19
- * `Workflow`, `StageDef`, `EdgeFn`, `EdgeTarget`, `EdgeContext`,
20
- * `StageSchema`, `StageKind`, `SessionPolicy`, `OutputSpec`,
21
- * `READS_DATA`, the runtime-mirror `*_VALUES` arrays, the
22
- * `gt`/`gte`/`lt`/`lte`/`eq` predicate helpers, and `typeboxSchema`
23
- * (the TypeBox adapter).
24
- *
25
- * 2. Runner (programmatic embedders) — `./runner/index.js`, `./host.js`
26
- * Drive a workflow from outside `/wf`: `runWorkflow` (+ the by-name
27
- * sugar `runWorkflowByName`) and `resumeWorkflow` (+ the by-run-id
28
- * sugar `resumeWorkflowByRunId`), with `RunWorkflowOptions`,
29
- * `RunWorkflowByNameOptions`, `ResumeWorkflowOptions`,
30
- * `ResumeWorkflowByRunIdOptions`, and the shared `RunWorkflowResult`.
31
- * Every options bag accepts an optional `signal: AbortSignal` for
32
- * between-stage cooperative cancellation. Embedders type their host
33
- * handles against `WorkflowHost` / `WorkflowHostContext` (the host
34
- * ports) — Pi's `ExtensionAPI` / `ExtensionCommandContext` /
35
- * `ReplacedSessionContext` structurally satisfy them, so the
36
- * values pass through without casting.
37
- *
38
- * 3. Loader (programmatic embedders) — `./load/index.js`
39
- * Materialise the merged workflow registry: `loadWorkflows`,
40
- * `LoadedWorkflows`, `Issue`, `LoadIssue`, `ConfigLayer`,
41
- * `OverlayPaths`, `projectOverlayPaths`, `userOverlayPaths`,
42
- * `aliasSkills`. Siblings can apply the same remap to a built-in
43
- * workflow before handing it to `runWorkflow`.
44
- *
45
- * 4. Built-in registry (sibling packages) — `./built-ins.js`
46
- * Contribute workflows to the lowest config layer:
47
- * `registerBuiltIns`. (`getBuiltIns` is test-only and lives on
48
- * `@juicesharp/rpiv-workflow/internal`.)
49
- *
50
- * 5. Output envelope + bundled outcomes — `./output.js`,
51
- * `./outcomes/index.js`, `./handle.js`
52
- * Inter-stage data channel (`Output<K, D>`, `OutputMeta`,
53
- * `Artifact`, `ArtifactHandle` + constructors `fs`/`url`/
54
- * `opaque`/`inline`/`handleToString`) + bundled outcomes
55
- * (`sideEffectOutcome`, `gitCommitOutcome`, `GitCommitData`,
56
- * `gitHeadSnapshot`, `GitHeadSnapshot`) + the bundled
57
- * collector/parser catalog wireable into any custom `OutputSpec`:
58
- * - collectors: `transcriptPathCollector` (regex over assistant
59
- * text), `toolCallCollector` (universal tool_use observer),
60
- * `workspaceDiffCollector` (git status diff pre/post),
61
- * `gitCommitCollector` (commit detection), the wrappers
62
- * `directoryPathCollector` / `urlCollector`, plus composition
63
- * `unionCollectors` and the empty-list primitive `noopCollector`.
64
- * - parsers: `jsonBodyParser` (parses primary fs body),
65
- * `gitCommitParser`.
66
- * The `.rpiv/artifacts/<bucket>/<file>.md` outcome + the
67
- * markdown-frontmatter parser live in `@juicesharp/rpiv-pi`
68
- * (`rpivArtifactMdOutcome` / `frontmatterParser`) — those are
69
- * rpiv conventions, not framework defaults.
70
- *
71
- * 6. Custom-outcome authoring surface — `./output.js`
72
- * `OutputSpec<Snapshot, Kind, Data>` (collector + optional parser),
73
- * `ArtifactCollector`, `ArtifactParser`, `CollectCtx`,
74
- * `CollectResult`, `ParseCtx`, `ParseResult`, `SnapshotCtx`,
75
- * `SnapshotFn`. Sugar: `defineCollector` / `defineParser`.
76
- *
77
- * 7. Validation surfaces — `./validate-workflow.js`,
78
- * `./validate-output.js`
79
- * `validateWorkflow`, `WorkflowValidationIssue`,
80
- * `validateOutputData`, `SchemaValidationFailure`.
81
- *
82
- * 8. Persistence (low-level — JSONL inspect) — `./state/index.js`
83
- * Read past runs at `<cwd>/.rpiv/workflows/runs/<run-id>.jsonl`:
84
- * `listRuns`, `readHeader`, `resolveRun` (run-id → header; today an
85
- * alias of `readHeader`), `readLastStage`, `listArtifacts`,
86
- * `stateFilePath`, `runsDir`, `RunSummary`,
87
- * `WorkflowHeader`, `WorkflowStage`. `recordStage` lives on
88
- * `@juicesharp/rpiv-workflow/internal` (test-only — rpiv-pi's
89
- * `[I3]` regression test pokes it directly; runner owns row
90
- * writes, embedders never need it).
91
- *
92
- * 9. Runtime types — `./types.js`
93
- * `RunState`.
13
+ * ─── Audience map ────────────────────────────────────────────────────────
14
+ *
15
+ * `registration.ts` is the SINGLE enumeration of the runner-free public
16
+ * surface — this header only routes you to the right module. (A previous
17
+ * symbol-by-symbol catalog here drifted from reality twice; it is gone on
18
+ * purpose.)
19
+ *
20
+ * - Authoring a workflow (config/pack files) → `./api.js` (DSL barrel:
21
+ * `defineWorkflow` + the stage/loop/routing factories),
22
+ * `./predicates.js`, `./typebox-adapter.js`.
23
+ * - Driving runs programmatically → `./runner/index.js` (`runWorkflow`,
24
+ * `resumeWorkflow` + by-name/by-run-id sugar); host ports in `./host.js`.
25
+ * - Loading the merged registry → `./load/index.js` (`loadWorkflows`).
26
+ * - Contributing built-in workflows (sibling packages) → `./built-ins.js`
27
+ * (`registerBuiltIns`).
28
+ * - Output envelope + bundled collectors/parsers → `./output.js`,
29
+ * `./outcomes/index.js`, `./handle.js`; custom-outcome authoring →
30
+ * `./output-spec.js` (`Outcome`, `defineCollector` / `defineParser`).
31
+ * - Validation → `./validate-workflow.js`, `./validate-output.js`.
32
+ * - Observing runs → `./events.js` (`registerLifecycle`, per-call
33
+ * `RunWorkflowOptions.lifecycle`).
34
+ * - Inspecting past runs (JSONL) → `./state/index.js` (`listRuns`,
35
+ * `readHeader`, `runFileFor`, …). Row WRITES are runner-owned;
36
+ * `recordStage` lives on `@juicesharp/rpiv-workflow/internal`
37
+ * (test-only).
94
38
  *
95
39
  * Per-module deep imports (`from "@juicesharp/rpiv-workflow/api.js"`)
96
40
  * are NOT supported across the package boundary.
package/internal-utils.ts CHANGED
@@ -1,5 +1,10 @@
1
1
  /**
2
- * Internal utilities shared across the rpiv-workflow package.
2
+ * Internal utilities shared across the rpiv-workflow package — GENERIC
3
+ * helpers only (error rendering, timeouts, global slots, structural
4
+ * equality, construction-time throw helpers). Workflow-domain helpers
5
+ * live in their domain modules:
6
+ * chain/artifact authorities in `chain-state.ts`, audit-row plumbing in
7
+ * `audit-rows.ts`, schema-timeout signalling in `validate-output.ts`.
3
8
  *
4
9
  * Not part of the public surface — not re-exported from `index.ts`. If a
5
10
  * helper graduates into the documented authoring or embedding contract,
@@ -7,10 +12,6 @@
7
12
  */
8
13
 
9
14
  import { isAbsolute, join } from "node:path";
10
- import type { StageDef } from "./api.js";
11
- import type { Artifact } from "./handle.js";
12
- import type { Output } from "./output.js";
13
- import type { RunState } from "./types.js";
14
15
 
15
16
  /** Exhaustiveness guard for discriminated-union switches. */
16
17
  export function assertNever(value: never): never {
@@ -18,38 +19,79 @@ export function assertNever(value: never): never {
18
19
  }
19
20
 
20
21
  /**
21
- * Canonical accessor for "the primary artifact the chain is currently
22
- * carrying." Reads the rolling slot maintained by the runner —
23
- * produces stages update it on success; side-effect stages leave it
24
- * alone. Replaces the load-bearing single-string artifact_path mirror
25
- * from the pre-collector shape.
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.
26
27
  */
27
- export function currentPrimaryArtifact(state: RunState): Artifact | undefined {
28
- return state.primaryArtifact;
28
+ export function throwInvalid(origin: string, message: string): never {
29
+ throw new Error(`${origin}: ${message}`);
29
30
  }
30
31
 
31
32
  /**
32
- * Resolve the `state.named` key a produces stage appends its `Output`
33
- * envelope onto. Two layers of fallback, in priority order:
34
- * 1. `stage.outcome?.name` — categorical name carried by the outcome.
35
- * 2. The stage's record key — always defined.
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
+
51
+ /**
52
+ * Render a caught `unknown` as a human-readable message. The ONE spelling of
53
+ * the `instanceof Error` dance — every catch block that needs the reason as a
54
+ * string calls this instead of inlining the ternary.
55
+ */
56
+ export function formatError(e: unknown): string {
57
+ return e instanceof Error ? e.message : String(e);
58
+ }
59
+
60
+ /** Single source of ISO-8601 timestamps for audit rows + output meta. */
61
+ export const nowIso = (): string => new Date().toISOString();
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.
36
70
  *
37
- * Single source of truth for the key derivation so the skill-stage path
38
- * and the script-stage path stay in lockstep, and so `validateWorkflow`
39
- * can compute the same key set at load time.
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.
40
74
  */
41
- export function resolvePublishName(def: StageDef, stageName: string): string {
42
- return def.outcome?.name ?? stageName;
75
+ export class WorkflowAbortError extends Error {
76
+ constructor(message = "aborted") {
77
+ super(message);
78
+ this.name = "WorkflowAbortError";
79
+ }
43
80
  }
44
81
 
82
+ export const isAbortError = (e: unknown): e is WorkflowAbortError => e instanceof WorkflowAbortError;
83
+
45
84
  /**
46
- * Resolve a stage's effective skill — the contract-registry key. Twin of
47
- * `resolvePublishName`. Single source of truth so the runtime resolution
48
- * (`resolveStage`) and the load-time lookups (`validate-workflow.ts`) key the
49
- * registry identically and can't drift.
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`.
50
89
  */
51
- export function resolveSkill(def: StageDef, stageName: string): string {
52
- return def.skill ?? stageName;
90
+ export class WorkflowConfigError extends Error {
91
+ constructor(message: string) {
92
+ super(message);
93
+ this.name = "WorkflowConfigError";
94
+ }
53
95
  }
54
96
 
55
97
  /**
@@ -75,20 +117,112 @@ export function globalSlot<T>(key: symbol, init: () => T): () => T {
75
117
  };
76
118
  }
77
119
 
78
- /** Thrown by `withTimeout` when the caller passes a `SchemaTimeoutError`
79
- * instance as the message. Lets consumers distinguish timeout errors from
80
- * inner-promise rejections via `instanceof` instead of string-identity
81
- * comparison. */
82
- export class SchemaTimeoutError extends Error {}
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
+
141
+ /**
142
+ * Register-providers / flush-on-demand lifecycle over global slots —
143
+ * the shared structure behind `registerBuiltInsProvider`/`flushBuiltInProviders`
144
+ * and their skill-contract twins, which were implemented twice near
145
+ * line-for-line. The one real divergence — error posture — is the
146
+ * `onError` parameter: when given, each provider throw is RECORDED via the
147
+ * callback (the registry stays usable, the caller drains and surfaces);
148
+ * when omitted, a throw rejects the flush promise (trusted in-process
149
+ * providers).
150
+ *
151
+ * Flush semantics: each provider runs AT MOST ONCE, but the flush is not a
152
+ * one-shot process latch — providers registered after a flush run on the
153
+ * NEXT flush, chained after everything that already ran. This is what makes
154
+ * `/reload` work: Pi re-runs extension entries (which re-register their
155
+ * providers) while these slots survive on `globalThis`; the next consumer
156
+ * read then flushes the re-registered providers, so owner-scoped
157
+ * registrations refresh (the contract registry's prune-on-reload semantics
158
+ * depend on this).
159
+ *
160
+ * State (provider list + flush chain) is anchored on `Symbol.for` slots
161
+ * derived from `key`, so a duplicate module load shares one process-wide
162
+ * lifecycle — same rationale as `globalSlot` itself. The chain is a mutable
163
+ * box because the slot value must never be reset to `undefined` (globalSlot
164
+ * would re-init), only its contents.
165
+ */
166
+ export interface LazyProviderRegistry {
167
+ /** Register a lazy thunk — runs once, on the next `flush()`. */
168
+ register(provider: () => void | Promise<void>): void;
169
+ /**
170
+ * Run every not-yet-run provider, chained after prior flushes; memoized
171
+ * when nothing new is pending. Concurrency-safe (callers await the same
172
+ * promise; a provider registered mid-flight runs on the next call). A
173
+ * provider throw (no-onError variant) rejects only that flush — later
174
+ * registrations run on subsequent flushes.
175
+ */
176
+ flush(): Promise<void>;
177
+ /** Test reset: clears pending providers and the flush chain. */
178
+ reset(): void;
179
+ }
180
+
181
+ export function lazyProviderRegistry(key: string, opts?: { onError: (err: unknown) => void }): LazyProviderRegistry {
182
+ type Provider = () => void | Promise<void>;
183
+ const getProviders = globalSlot(Symbol.for(`${key}:providers`), () => [] as Provider[]);
184
+ const getFlushBox = globalSlot(Symbol.for(`${key}:flush`), () => ({
185
+ flushed: undefined as Promise<void> | undefined,
186
+ }));
187
+ const onError = opts?.onError;
188
+ return {
189
+ register(provider) {
190
+ getProviders().push(provider);
191
+ },
192
+ flush() {
193
+ const box = getFlushBox();
194
+ const pending = getProviders().splice(0);
195
+ if (pending.length === 0) return box.flushed ?? Promise.resolve();
196
+ const run = () =>
197
+ Promise.all(
198
+ pending.map((p) => {
199
+ const r = Promise.resolve().then(p);
200
+ return onError ? r.catch(onError) : r;
201
+ }),
202
+ ).then(() => undefined);
203
+ // Chain after the prior flush — settled either way — so registration
204
+ // order is preserved across reload generations and a rejection (no-
205
+ // onError variant) only fails the callers awaiting THAT flush; later
206
+ // registrations still run, so `/reload` can recover from a bad provider.
207
+ box.flushed = box.flushed ? box.flushed.then(run, run) : run();
208
+ return box.flushed;
209
+ },
210
+ reset() {
211
+ getProviders().length = 0;
212
+ getFlushBox().flushed = undefined;
213
+ },
214
+ };
215
+ }
83
216
 
84
217
  /**
85
218
  * Race a promise against `ms`. The inner promise is NOT cancelled — Pi's
86
219
  * `ctx.waitForIdle()` has no abort signal today; the dangling promise becomes
87
- * inert when the next stage's `newSession` replaces the ctx.
220
+ * inert once the child session it was waiting on is disposed.
88
221
  *
89
222
  * When `message` is a string, a plain `Error` is thrown on timeout
90
- * (backward-compatible). When `message` is an `Error` (e.g.
91
- * `SchemaTimeoutError`), it is thrown directly so `instanceof` checks work.
223
+ * (backward-compatible). When `message` is an `Error` instance (e.g.
224
+ * `SchemaTimeoutError` from validate-output.ts), it is thrown directly so
225
+ * `instanceof` checks work.
92
226
  */
93
227
  export async function withTimeout<T>(promise: Promise<T>, ms: number, message: string | Error): Promise<T> {
94
228
  let timer: ReturnType<typeof setTimeout> | undefined;
@@ -102,40 +236,6 @@ export async function withTimeout<T>(promise: Promise<T>, ms: number, message: s
102
236
  }
103
237
  }
104
238
 
105
- /**
106
- * The single authority for "a completed produces stage mutates the rolling
107
- * artifact state." Called by the live skill path (sessions/sessions.ts), the
108
- * live script path (runner/script-stage.ts), and state reconstruction
109
- * (runner/resume.ts) — keeping all three in lockstep (parity-tested).
110
- *
111
- * Scope: primary slot + named-publish registry ONLY. `state.output` and
112
- * `state.stagesCompleted` stay at call sites — `state.output` lives in the
113
- * shared, gated `tryRecordStage` (also serving fanout, which never advances
114
- * the primary), so folding it here would couple fanout to the produces rule.
115
- *
116
- * - kind "produces" → first artifact wins the rolling slot; the
117
- * full Output appends onto state.named[key].
118
- * - inheritsArtifacts === false → clear the slot (terminal()).
119
- * - other side-effect → leave the slot untouched.
120
- */
121
- export function applyCompletedStage(state: RunState, def: StageDef, stageName: string, output: Output): void {
122
- if (def.kind === "produces") {
123
- const next = output.artifacts[0];
124
- if (next) state.primaryArtifact = next;
125
- const key = resolvePublishName(def, stageName);
126
- let slot = state.named[key];
127
- if (!slot) {
128
- slot = [];
129
- state.named[key] = slot;
130
- }
131
- slot.push(output);
132
- return;
133
- }
134
- if (def.inheritsArtifacts === false) {
135
- state.primaryArtifact = undefined;
136
- }
137
- }
138
-
139
239
  /**
140
240
  * Resolve `p` against `cwd`. Returns `p` unchanged if it is already absolute;
141
241
  * otherwise joins `cwd + p` with the platform path separator. Uses
@@ -148,8 +248,8 @@ export function resolveUnderCwd(cwd: string, p: string): string {
148
248
 
149
249
  /**
150
250
  * Structural (key-order-independent) deep equality. Used by the
151
- * cross-owner collision check in `skill-contracts.ts` (later
152
- * `skill-contracts/registry.ts`) so two semantically-identical contracts
251
+ * cross-owner collision check in `skill-contracts/registry.ts`
252
+ * so two semantically-identical contracts
153
253
  * built by different code paths (or with different YAML key order) don't
154
254
  * read as divergent — `JSON.stringify` is insertion-order dependent and
155
255
  * would raise a spurious collision warning. Contracts are plain JSON data
package/internal.ts CHANGED
@@ -19,16 +19,37 @@
19
19
  * Adding a new export here is a signal you have test-coupling to
20
20
  * production state. Reach for it sparingly; prefer making the
21
21
  * production module itself idempotent across `beforeEach` resets.
22
+ *
23
+ * KNOWN DEBT (deliberately deferred): most of these exist because the
24
+ * built-in/contract registries are process-global singletons (a deliberate
25
+ * choice — siblings register across package-instance boundaries via
26
+ * `Symbol.for` slots). Making them instantiable and threading an instance
27
+ * through `loadWorkflows` would let tests construct fresh registries and
28
+ * shrink this file toward zero; it's an API-design change that must be
29
+ * coordinated with rpiv-pi's internal-subpath regression test, so it ships
30
+ * in a follow-up minor, not the pre-release window.
22
31
  */
23
32
 
24
33
  export { recordStage } from "./audit.js";
25
34
  export { __resetBuiltIns, flushBuiltInProviders, getBuiltIns } from "./built-ins.js";
26
- export { __resetLifecycleRegistry } from "./lifecycle.js";
35
+ export { __resetLifecycleRegistry } from "./events.js";
36
+ export { __resetWorkflowExecutionHost } from "./execution-host.js";
27
37
  export { __resetLoadCache } from "./load/cache.js";
28
38
  export {
29
39
  __resetSkillContracts,
40
+ buildEffectiveContracts,
41
+ drainSkillContractCollisions,
42
+ drainSkillContractProviderErrors,
30
43
  flushSkillContractProviders,
44
+ getBucketKindMappings,
31
45
  getCompositionComparators,
32
46
  getSkillContracts,
33
47
  harvestStageContracts,
48
+ registerBucketKindMapping,
34
49
  } from "./skill-contracts/index.js";
50
+ // Layout-coupled path helpers — test fixtures that WRITE synthetic run files
51
+ // need them; production consumers use the opaque `runFileFor` instead.
52
+ export { runsDir, stateFilePath } from "./state/index.js";
53
+ // Type-only: lets external test fixtures construct the full mutable run state
54
+ // for direct `recordStage` calls. Production consumers read `RunView` instead.
55
+ export type { RunState } from "./types.js";