@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/sessions/spawn.ts CHANGED
@@ -1,139 +1,152 @@
1
1
  /**
2
- * Session policy dispatch. Owns the three policy-specific decisions the
3
- * stage / phase machinery has to make per session: which branch offset
4
- * the outcome sees, how the session is opened, and how an
5
- * already-established session is sent to.
2
+ * Session opening — the child-spawn primitives every stage and loop unit runs
3
+ * through. With every stage isolated in its own child session, "send into an
4
+ * existing session" doesn't exist, so there's no stale-ctx fallback ladder,
5
+ * no registry-host fallback param, and no defensive `sendUserMessage` guards.
6
6
  *
7
- * Two handlers — `FRESH_HANDLER` and `CONTINUE_HANDLER` — implement the
8
- * interface; `handlerFor(policy)` picks. Everything else in the
9
- * `sessions/` directory is policy-agnostic.
7
+ * Three open modes, all routed through `ctx.spawnChild`:
8
+ * - FRESH (`spawnChildAndRun`) — a brand-new child; the host sends the prompt.
9
+ * - REATTACH (`reattachChildSession`) — open a persisted file IN PLACE
10
+ * (session-backed resume); the host skips the prompt, the body promotes/nudges.
11
+ * - FORK (`forkChildSession`) — copy a PREDECESSOR's persisted session into a
12
+ * NEW file carrying its full transcript (`sessionPolicy: "continue"`); the host
13
+ * skips the prompt, the body re-derives the inherited-prefix offset and sends
14
+ * the continuation turn. This is the detached continuation mechanism — prior-
15
+ * session lineage survives detachment via `SessionManager.forkFrom`, resolving
16
+ * the original OQ1 (which assumed it could not). The source file is never
17
+ * mutated, so DAG forks are safe and the continue child has its own resumable
18
+ * identity.
10
19
  */
11
20
 
12
21
  import type { SessionPolicy } from "../api.js";
13
- import type { WorkflowHost } from "../host.js";
14
- import type { WorkflowHostContext } from "../types.js";
22
+ import type { StageSession, WorkflowHostContext, WorkflowSessionContext } from "../types.js";
15
23
 
16
24
  /**
17
- * Three policy-specific decisions that used to live as five ternaries
18
- * scattered across sessions.ts:
25
+ * The per-policy branch offset — fresh ignores the stage-captured value;
26
+ * continue flows it through so a continue stage's outcome still skips the prior
27
+ * transcript its forked child inherited (trail / replay symmetry). The sole
28
+ * surviving policy divergence.
19
29
  *
20
- * - `branchOffset(captured)` — the offset outcomes apply to skip
21
- * the prior-stage prefix in continue sessions. Fresh ignores the
22
- * stage-side captured value (it's `undefined` from
23
- * `computeBranchOffset` for fresh stages anyway); continue returns
24
- * it as-is.
25
- * - `spawn(ctx, prompt, body, host?)` — open the session and run `body`
26
- * on whichever ctx is valid for that policy (fresh → freshCtx
27
- * inside `withSession`; continue → the supplied ctx, after a
28
- * send+waitForIdle settles the existing session). `cancelled: true`
29
- * means a fresh session was cancelled before `withSession` ran.
30
- * - `send(ctx, msg, host?)` — send into an already-established session
31
- * and wait for it to settle (used by the validation-retry path).
32
- *
33
- * `host` is the registry-level fallback for continue stages — used only
34
- * when `ctx.sendUserMessage` is absent (the outer command ctx at the
35
- * very start of a workflow whose first stage is continue-policy).
36
- * Everywhere else (continue stages following any other stage),
37
- * `ctx.sendUserMessage` is present and preferred because Pi marks the
38
- * captured host stale after `ctx.newSession()`. `enforceSessionInvariants`
39
- * still requires a host whenever any stage is continue-policy so the
40
- * start-stage path has a working fallback. Fresh ignores `host` entirely.
30
+ * The `captured` value is sourced from the continuation's ACTUAL branch:
31
+ * - live (`continueStageSession`) re-derives it from the forked child's branch
32
+ * length before the continuation turn is sent, and threads it through `postStage`;
33
+ * - resume takes it from the persisted row (`SessionRef.branchOffset`) of the
34
+ * continue stage's own forked session.
35
+ * Never the launcher's branch (the bug the fork redesign removed).
41
36
  */
42
- export interface SessionPolicyHandler {
43
- branchOffset(capturedOffset: number | undefined): number | undefined;
44
- spawn(
45
- ctx: WorkflowHostContext,
46
- prompt: string,
47
- body: (sessionCtx: WorkflowHostContext) => Promise<void>,
48
- host?: WorkflowHost,
49
- ): Promise<{ cancelled: boolean }>;
50
- send(ctx: WorkflowHostContext, msg: string, host?: WorkflowHost): Promise<void>;
37
+ export function branchOffsetFor(policy: SessionPolicy | undefined, captured: number | undefined): number | undefined {
38
+ return policy === "continue" ? captured : undefined;
51
39
  }
52
40
 
53
- export const FRESH_HANDLER: SessionPolicyHandler = {
54
- branchOffset: () => undefined,
55
- async spawn(ctx, prompt, body) {
56
- const { cancelled } = await ctx.newSession({
57
- // `freshCtx` is a `WorkflowSessionContext` — the port guarantees
58
- // `sendUserMessage` on the replacement ctx, so no runtime guard.
59
- withSession: async (freshCtx) => {
60
- await freshCtx.sendUserMessage(prompt);
61
- await body(freshCtx);
62
- },
63
- });
64
- return { cancelled };
65
- },
66
- async send(ctx, msg) {
67
- // At runtime ctx is the in-session replacement (a
68
- // `WorkflowSessionContext`), but the shared `SessionPolicyHandler`
69
- // types it as the base `WorkflowHostContext` (continue's send may run
70
- // on the senderless start ctx), so this seam keeps a defensive guard.
71
- if (!ctx.sendUserMessage) {
72
- throw new Error("FRESH_HANDLER.send: replacement ctx missing sendUserMessage");
73
- }
74
- await ctx.sendUserMessage(msg);
75
- },
76
- };
41
+ /** Optional open mode — absent ⇒ FRESH; `reattach` opens a persisted file in
42
+ * place; `fork` copies a predecessor's session into a new file. The two carry
43
+ * the same `{ sessionFile }` shape; only the host's open semantics differ. */
44
+ type OpenMode = { reattach: { sessionFile: string } } | { fork: { sessionFile: string } };
77
45
 
78
- export const CONTINUE_HANDLER: SessionPolicyHandler = {
79
- branchOffset: (captured) => captured,
80
- async spawn(ctx, prompt, body, host) {
81
- // Prefer the live `ctx.sendUserMessage` over the captured `host`.
82
- // Pi marks the registry-level host handle stale after the first
83
- // `ctx.newSession()`, so a continue stage that follows a fresh
84
- // stage would throw "extension ctx is stale" if we called
85
- // `host.sendUserMessage` here. The inner replacement ctx delivered
86
- // to `withSession` always exposes `sendUserMessage` (the port
87
- // marks it optional because only the outer command ctx lacks it).
88
- // `host` remains the fallback for the workflow-start-with-continue
89
- // case where there is no inner ctx yet — `enforceSessionInvariants`
90
- // requires a host whenever any stage is continue-policy, so the
91
- // fallback can be taken safely.
92
- //
93
- // Awaiting the send (vs fire-and-forget) lands transport errors on
94
- // this stage's halt path; pre-I5b we discarded the promise and the
95
- // runner walked the chain blind on rejection.
96
- await sendIntoExistingSession(ctx, host, prompt);
97
- await ctx.waitForIdle();
98
- await body(ctx);
99
- return { cancelled: false };
100
- },
101
- async send(ctx, msg, host) {
102
- // Same precedence as spawn: live ctx first, captured host as
103
- // fallback. Validation-retry sends always run inside a stage's
104
- // session, so `ctx.sendUserMessage` is present in practice; the
105
- // host branch is there for symmetry with spawn.
106
- await sendIntoExistingSession(ctx, host, msg);
107
- await ctx.waitForIdle();
108
- },
109
- };
46
+ /**
47
+ * THE child-spawn primitive every mode below reduces to. Open an isolated child
48
+ * (parent stays valid) in the requested `mode`, let the host apply the
49
+ * prompt/model/signal (+ reattach/fork), wait for the agent to settle, then run
50
+ * `body` on the guaranteed-in-session child ctx. The await-idle-then-body
51
+ * sequence — load-bearing for the IDLE-BEFORE-REPROMPT invariant — lives here
52
+ * once, so the three named entries can't drift on it. Up to `ctx.maxConcurrency`
53
+ * may be in flight (the loop's semaphore bounds fanout; single stages run one).
54
+ */
55
+ function openChild(
56
+ ctx: WorkflowHostContext,
57
+ s: Pick<StageSession, "prompt" | "model" | "signal" | "laneUnitIndex">,
58
+ body: (child: WorkflowSessionContext) => Promise<void>,
59
+ mode?: OpenMode,
60
+ ): Promise<void> {
61
+ return ctx.spawnChild({
62
+ prompt: s.prompt, // FRESH: host sends it. REATTACH/FORK: carried for parity; host skips auto-replay.
63
+ model: s.model,
64
+ signal: s.signal,
65
+ // The lane key for a lane-aware host's per-unit slot — set only for fan-out units.
66
+ // Undefined for sequential loop units / single stages / reattach / fork, all
67
+ // of which map to the host's reserved single-unit slot so the lane row keeps
68
+ // showing the one live session. Inert on a non-lane host.
69
+ unitIndex: s.laneUnitIndex,
70
+ ...mode,
71
+ withSession: async (child) => {
72
+ await child.waitForIdle();
73
+ await body(child);
74
+ },
75
+ });
76
+ }
110
77
 
111
78
  /**
112
- * Send a message into the already-active session. Prefers the live
113
- * `ctx.sendUserMessage`; falls back to the captured registry-level
114
- * `host.sendUserMessage` only when ctx doesn't expose one (workflow start
115
- * with a continue-first-stage). Throws if neither path is available —
116
- * `enforceSessionInvariants` should have rejected the workflow before
117
- * we land here.
79
+ * FRESH open. Open a brand-new isolated child session; the host sends the prompt
80
+ * and applies the model. The default stage/loop-unit entry.
118
81
  */
119
- async function sendIntoExistingSession(
82
+ export function spawnChildAndRun(
120
83
  ctx: WorkflowHostContext,
121
- host: WorkflowHost | undefined,
122
- msg: string,
84
+ s: Pick<StageSession, "prompt" | "model" | "signal" | "laneUnitIndex">,
85
+ body: (child: WorkflowSessionContext) => Promise<void>,
123
86
  ): Promise<void> {
124
- if (ctx.sendUserMessage) {
125
- await ctx.sendUserMessage(msg);
126
- return;
127
- }
128
- if (host) {
129
- await host.sendUserMessage(msg);
130
- return;
131
- }
132
- throw new Error(
133
- "CONTINUE_HANDLER: neither ctx.sendUserMessage nor a workflow host available — continue policy requires one of them",
134
- );
87
+ return openChild(ctx, s, body);
135
88
  }
136
89
 
137
- export function handlerFor(policy: SessionPolicy | undefined): SessionPolicyHandler {
138
- return policy === "continue" ? CONTINUE_HANDLER : FRESH_HANDLER;
90
+ /**
91
+ * THE reattach primitive — the detached replacement for the deleted
92
+ * live-session swap (`ctx.switchSession`). Spawn a child bound to the PERSISTED
93
+ * session at `sessionFile` (the host opens it, no fresh creation, no initial `prompt`),
94
+ * then run `body` on the in-session child ctx whose `getBranch` reflects the
95
+ * prior transcript. `body` is `reattachStageSession` (sessions/reattach.ts),
96
+ * which promotes from the loaded branch or nudges via `resendIntoChild`.
97
+ *
98
+ * `sessionFile` is supplied by the resume entry (a `locateSessionFile` hit), so
99
+ * the host always has a real file; a missing/in-memory case is gated upstream.
100
+ * There is NO `{ cancelled }` arm — a detached reattach has no live-session swap
101
+ * for the user to dismiss.
102
+ */
103
+ export function reattachChildSession(
104
+ ctx: WorkflowHostContext,
105
+ s: Pick<StageSession, "prompt" | "model" | "signal" | "laneUnitIndex">,
106
+ sessionFile: string,
107
+ body: (child: WorkflowSessionContext) => Promise<void>,
108
+ ): Promise<void> {
109
+ return openChild(ctx, s, body, { reattach: { sessionFile } });
110
+ }
111
+
112
+ /**
113
+ * THE fork primitive — the detached continuation mechanism for
114
+ * `sessionPolicy: "continue"`. Spawn a child by FORKING the PREDECESSOR's
115
+ * persisted session at `sessionFile` (`SessionManager.forkFrom`: a new file +
116
+ * new id carrying the predecessor's full transcript, source left intact), then
117
+ * run `body` on the in-session child ctx whose `getBranch` reflects that prior
118
+ * transcript. The host opens the fork and does NOT send the carried `prompt` —
119
+ * `body` (`continueStageSession`, sessions.ts) measures the inherited prefix and
120
+ * sends the continuation turn via `resendIntoChild`.
121
+ *
122
+ * `sessionFile` is the predecessor stage's persisted session (a
123
+ * `locateSessionFile` hit gated by the caller, from `run.state.lastSession`), so
124
+ * the host always has a real file. Distinct from `reattachChildSession` (which
125
+ * opens the SAME file IN PLACE for resume): a fork must not mutate the
126
+ * predecessor's file and gives the continue stage its own resumable identity.
127
+ */
128
+ export function forkChildSession(
129
+ ctx: WorkflowHostContext,
130
+ s: Pick<StageSession, "prompt" | "model" | "signal" | "laneUnitIndex">,
131
+ sessionFile: string,
132
+ body: (child: WorkflowSessionContext) => Promise<void>,
133
+ ): Promise<void> {
134
+ return openChild(ctx, s, body, { fork: { sessionFile } });
135
+ }
136
+
137
+ /**
138
+ * Re-prompt an already-open child and wait for it to settle — the
139
+ * validation-retry path (`askAgentToFix`) and the resume reattach nudge.
140
+ * The child ctx always exposes `sendUserMessage`, so no guard.
141
+ *
142
+ * IDLE-BEFORE-REPROMPT INVARIANT: uses `sendUserMessage` (which QUEUES, safe
143
+ * mid-stream), NOT `prompt()` — the SDK THROWS "Agent is already processing" if
144
+ * `prompt()` is called while streaming. Every entry point honors this:
145
+ * `spawnChildAndRun` calls `waitForIdle()` before `body`, and the host's
146
+ * `prompt()` is only the single initial send. Callers must never call a child's
147
+ * `prompt()` again after the first; re-prompts go through `sendUserMessage` here.
148
+ */
149
+ export async function resendIntoChild(child: WorkflowSessionContext, msg: string): Promise<void> {
150
+ await child.sendUserMessage(msg);
151
+ await child.waitForIdle();
139
152
  }
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Success-persistence facet — extracted from `sessions.ts`'s
3
+ * SUCCESS-PERSISTENCE HELPERS. `recordStageSuccess` persists a successful
4
+ * stage/unit row and fires the lifecycle signal; `unitEventOf` builds the
5
+ * `UnitEvent` payload used by BOTH the success path and the halt path's
6
+ * soft-halt lifecycle signal (halt-routing.ts value-imports it).
7
+ *
8
+ * Companion modules (see `sessions.ts`'s header for the full map):
9
+ * - halt-routing.ts — the halt pipeline; consumes `unitEventOf`.
10
+ */
11
+
12
+ import { currentStageRef, failAuditWrite } from "../audit.js";
13
+ import { persistStageSuccess, rollLastSession } from "../audit-rows.js";
14
+ import { lifecycleCtxFromSession, skillStageRef, type UnitEvent } from "../events.js";
15
+ import type { Output } from "../output.js";
16
+ import type { SessionRef } from "../state/index.js";
17
+ import type { StageSession, WorkflowHostContext } from "../types.js";
18
+
19
+ /**
20
+ * Returns true on successful write — caller gates `onSuccess` on this so the
21
+ * chain advances only when the audit row landed. On failure, leaves
22
+ * `state.output` / `state.primaryArtifact` at their prior values ("output is
23
+ * set iff the row that carried it landed") and sets `state.termination.error`
24
+ * to halt the run. Persistence + state apply run through
25
+ * `persistStageSuccess` (audit-rows.ts) — the ONE success pipeline shared
26
+ * with the script path: the row reuses the activation's pre-allocated number
27
+ * so `output.meta.stageNumber` and the row agree, and unit rows carry the
28
+ * structured identity fields alongside the decorated display `stage`.
29
+ *
30
+ * Single stages keep the `onStageEnd` contract verbatim. Loop units fire
31
+ * `onUnitEnd` (NEVER `onStageEnd` — that's reserved for single-stage and
32
+ * loop-level semantics), the ref carrying the PARENT stage name so listeners
33
+ * key on graph identity, not the display decoration. Neither path emits a
34
+ * completion toast — the status line is the live progress channel.
35
+ *
36
+ * Exported to the `reattach.ts` companion — promotion persists through this
37
+ * exact pipeline (one success path, live and adopted alike).
38
+ */
39
+ export async function recordStageSuccess(
40
+ ctx: WorkflowHostContext,
41
+ s: StageSession,
42
+ output: Output,
43
+ session: SessionRef | null,
44
+ ): Promise<boolean> {
45
+ const persisted = persistStageSuccess(
46
+ s.state,
47
+ {
48
+ cwd: s.cwd,
49
+ runId: s.runId,
50
+ stage: s.stageName,
51
+ skill: s.skill,
52
+ output,
53
+ session,
54
+ unit: s.unit,
55
+ preAllocated: s.allocatedStageNumber,
56
+ },
57
+ s.stage,
58
+ );
59
+ if (persisted) {
60
+ if (s.unit) {
61
+ await s.lifecycle.fire(
62
+ ctx,
63
+ "onUnitEnd",
64
+ // Same allocator base as every other ref of this activation; the
65
+ // ref's NAME stays the parent stage key (graph identity).
66
+ skillStageRef(s.unit.parent, s.allocatedStageNumber ?? s.state.lastAllocatedStageNumber, s.skill),
67
+ unitEventOf(s),
68
+ output,
69
+ lifecycleCtxFromSession(s),
70
+ );
71
+ } else {
72
+ // Roll the predecessor session forward: a downstream `continue` stage
73
+ // forks THIS session. Single stages only — loop units take the `if (s.unit)`
74
+ // branch above and never seed a continuation. Shared with the resume fold
75
+ // (`rollLastSession`) so the null-handling can't drift between the paths.
76
+ rollLastSession(s.state, session);
77
+ await s.lifecycle.fire(ctx, "onStageEnd", currentStageRef(s), output, lifecycleCtxFromSession(s));
78
+ }
79
+ return true;
80
+ }
81
+ failAuditWrite(ctx, s.state, s.skill);
82
+ return false;
83
+ }
84
+
85
+ /** Public `UnitEvent` payload from the session's `UnitRef` + dispatched skill. */
86
+ export function unitEventOf(s: StageSession): UnitEvent {
87
+ const u = s.unit!;
88
+ return { role: u.role, index: u.index, unitId: u.id, label: u.label, skill: s.skill };
89
+ }
package/skill-contract.ts CHANGED
@@ -4,8 +4,8 @@
4
4
  * A contract declares what a skill consumes and produces, as data — the
5
5
  * keystone that lets an agent reason about composition without scanning prose.
6
6
  * The contract is the SKILL's property (declared once in its frontmatter),
7
- * injected into this framework via `registerSkillContracts` / a provider
8
- * (see `skill-contracts.ts`). This package never reads skill files or parses
7
+ * registered into this framework via `registerSkillContracts` / a provider
8
+ * (see `skill-contracts/`). This package never reads skill files or parses
9
9
  * YAML — the primary consumer (rpiv-pi) supplies already-parsed contracts.
10
10
  *
11
11
  * Three field tiers, by who understands them:
@@ -22,27 +22,22 @@
22
22
  */
23
23
 
24
24
  import type { JsonSchemaObject } from "./json-schema.js";
25
+ import type { SchemaCompatResult } from "./schema-compat.js";
25
26
 
26
- /**
27
- * Result of a conservative structural compatibility check between a producer's
28
- * output schema and a consumer's input schema. Co-located with
29
- * `CompositionComparator` (which returns this type) so the contract vocabulary
30
- * is self-contained — consumers don't need to reach into `json-schema.ts` or
31
- * `schema-compat.ts` for the result type.
32
- */
33
- export interface SchemaCompatResult {
34
- ok: boolean;
35
- reason?: string;
36
- }
27
+ // `SchemaCompatResult` lives with the compat engine (schema-compat.ts) that
28
+ // defines its semantics — re-exported here so the contract vocabulary stays
29
+ // self-contained for consumers (`CompositionComparator` returns it).
30
+ export type { SchemaCompatResult } from "./schema-compat.js";
37
31
 
38
32
  /**
39
33
  * Where a contract came from, in descending authority. `declared` = the skill's
40
- * own frontmatter (truth); `harvested` = derived from how workflow stages use
41
- * the skill (a cross-check / lint); `inferred` = future JSONL/LLM sources
42
- * (deferred). Absence (no contract at all) is modelled by the skill simply not
43
- * being present in the registry — there is no `missing` source.
34
+ * own frontmatter (truth) — every externally REGISTERED contract
35
+ * (`registerSkillContracts` / a provider) carries this source; `harvested` =
36
+ * derived from how workflow stages use the skill (a cross-check / lint).
37
+ * Absence (no contract at all) is modelled by the skill simply not being
38
+ * present in the registry — there is no `missing` source.
44
39
  */
45
- export type ContractSource = "declared" | "harvested" | "inferred";
40
+ export type ContractSource = "declared" | "harvested";
46
41
 
47
42
  /**
48
43
  * A named-channel reference a skill reads (`reads:` / `state.named`). v1 records
@@ -97,13 +92,15 @@ export type SkillContractMap = ReadonlyMap<string, SkillContract>;
97
92
  /**
98
93
  * A consumer-supplied adjudicator for one named channel's `meta` compatibility.
99
94
  * The framework INVOKES it but never reads inside `meta` — the channel's
100
- * ontology lives entirely with the consumer. Registered per channel
101
- * via `registerCompositionComparator(channelName, comparator)` and consulted by
102
- * the three adjudication points (`canCompose`/`legalNextSkills`,
103
- * `checkEdgeSchemaCompat`, `ensureContractInputValid`) for any consumer
104
- * declaring `consumes.reads[channelName]`. Conservative by contract: return
105
- * `{ ok: true }` whenever there is nothing to compare (absent meta on either
106
- * side) so a missing tag degrades, never HALTs.
95
+ * ontology lives entirely with the consumer. Registered per channel via
96
+ * `registerCompositionComparator(channelName, comparator)` and invoked through
97
+ * ONE shared rule, `adjudicateChannel` (skill-contracts/composition.ts), at
98
+ * its two consumption points: `canCompose`/`legalNextSkills` (advisory query)
99
+ * and `checkReadsChannelCompat` (the load gate). The shared gate fires only
100
+ * for consumers declaring `consumes.reads[channelName]` with a `meta`
101
+ * requirement. Conservative by contract: return `{ ok: true }` whenever there
102
+ * is nothing to compare (absent meta on either side) so a missing tag
103
+ * degrades, never HALTs.
107
104
  */
108
105
  export type CompositionComparator = (
109
106
  produces: ProducesSpec,
@@ -7,56 +7,105 @@
7
7
  * (not provably incompatible).
8
8
  */
9
9
 
10
+ import { formatError } from "../internal-utils.js";
11
+ import type { JsonSchemaObject } from "../json-schema.js";
10
12
  import { isSchemaCompatible } from "../schema-compat.js";
11
- import type { SchemaCompatResult, SkillContractMap } from "../skill-contract.js";
12
- import { getCompositionComparators } from "./registries.js";
13
- import { getSkillContracts } from "./registry.js";
13
+ import type {
14
+ CompositionComparator,
15
+ ConsumesSpec,
16
+ ProducesSpec,
17
+ SchemaCompatResult,
18
+ SkillContractMap,
19
+ } from "../skill-contract.js";
20
+ import { getCompositionComparators } from "./extension-points.js";
21
+
22
+ /**
23
+ * THE single data-channel comparison core — shared by `canCompose` and the
24
+ * validator's `checkEdgeSchemaCompat`, so the adviser and the load gate
25
+ * answer the producer→consumer data question through one engine. Conservative:
26
+ * either side absent/opaque → `{ ok: true }` (not provably incompatible);
27
+ * both present → `isSchemaCompatible`.
28
+ */
29
+ export function compareDataChannel(
30
+ producer: JsonSchemaObject | undefined,
31
+ consumer: JsonSchemaObject | undefined,
32
+ ): SchemaCompatResult {
33
+ if (!producer || !consumer) return { ok: true };
34
+ return isSchemaCompatible(producer, consumer);
35
+ }
36
+
37
+ /** Outcome of adjudicating one named channel — see `adjudicateChannel`. */
38
+ export type ChannelAdjudication =
39
+ | { kind: "ok" }
40
+ | { kind: "mismatch"; reason?: string }
41
+ /** No comparator registered, or the consumer declares no `meta` requirement for the channel. */
42
+ | { kind: "skipped" }
43
+ /** The consumer-supplied comparator threw — an author defect, reported, never propagated. */
44
+ | { kind: "comparator-threw"; error: string };
45
+
46
+ /**
47
+ * THE single adjudication rule for one named channel — shared by `canCompose`
48
+ * (the advisory composition query) and `checkReadsChannelCompat` (the load
49
+ * gate) so the two can never disagree about a producer/consumer pair.
50
+ *
51
+ * Gating: a channel is adjudicated iff a comparator is registered for it AND
52
+ * the consumer's `consumes.reads[channel]` declares a `meta` requirement —
53
+ * without a declared requirement there is no kind to compare, and invoking
54
+ * the comparator anyway is a false-reject risk for multi-channel consumers.
55
+ * Degrade posture: gating misses return `"skipped"`; a comparator throw
56
+ * returns `"comparator-threw"` (callers decide whether to surface it) —
57
+ * adjudication itself never throws.
58
+ */
59
+ export function adjudicateChannel(
60
+ produces: ProducesSpec,
61
+ consumes: ConsumesSpec,
62
+ channel: string,
63
+ comparators: ReadonlyMap<string, CompositionComparator> = getCompositionComparators(),
64
+ ): ChannelAdjudication {
65
+ const comparator = comparators.get(channel);
66
+ if (!comparator || !consumes.reads?.[channel]?.meta) return { kind: "skipped" };
67
+ try {
68
+ const compat = comparator(produces, consumes, channel);
69
+ return compat.ok ? { kind: "ok" } : { kind: "mismatch", reason: compat.reason };
70
+ } catch (e) {
71
+ return { kind: "comparator-threw", error: formatError(e) };
72
+ }
73
+ }
14
74
 
15
75
  /**
16
76
  * Can a producer skill's `produces.data` feed a consumer skill's `consumes.data`?
17
77
  * Conservative (via `isSchemaCompatible`): returns `{ ok: true }` when either
18
78
  * schema is absent/opaque (not provably incompatible).
19
79
  *
20
- * IMPORTANT: the default `contracts` is the GLOBAL registry
21
- * (`getSkillContracts()`), which holds only `declared` + `injected` contracts —
22
- * NOT the `harvested` ones, which exist solely on `LoadedWorkflows.skillContracts`
23
- * (built per load, never written back to the global). So the zero-arg call sees a
24
- * weaker map than the loader's own edge-compat pass and will degrade to
25
- * `{ ok: true }` for any harvest-only skill. For the effective (declared ⊕
26
- * harvested) view an agent should pass `loaded.skillContracts` explicitly.
80
+ * `contracts` is REQUIRED: the GLOBAL registry holds only registered
81
+ * (`declared`-source) contracts — NOT the `harvested` ones, which exist solely
82
+ * on `LoadedWorkflows.skillContracts` (built per load, never written back to the
83
+ * global) — so a default would be the wrong call for any harvest-only skill.
84
+ * Pass `loaded.skillContracts` for the effective (declared ⊕ harvested) view,
85
+ * or `getSkillContracts()` when the registered slice is genuinely what you mean.
27
86
  */
28
87
  export function canCompose(
29
88
  producerSkill: string,
30
89
  consumerSkill: string,
31
- contracts: SkillContractMap = getSkillContracts(),
90
+ contracts: SkillContractMap,
32
91
  ): SchemaCompatResult {
33
92
  const producerContract = contracts.get(producerSkill);
34
93
  const consumerContract = contracts.get(consumerSkill);
35
- // Data channel: a provable data mismatch is decisive.
36
- const producerData = producerContract?.produces?.data;
37
- const consumerData = consumerContract?.consumes?.data;
38
- if (producerData && consumerData) {
39
- const dataCompat = isSchemaCompatible(producerData, consumerData);
40
- if (!dataCompat.ok) return dataCompat;
41
- }
42
- // Named-channel (reads) compat: consult per-channel comparators for the
43
- // consumer's declared reads channels. Degrades to `{ ok: true }` when no comparator
44
- // is registered or the producer has no `produces` spec. Only adjudicates channels
45
- // where the consumer has explicitly declared a meta requirement (readSpec.meta
46
- // present) — without it there is no kind to compare, and invoking the comparator
47
- // for a channel the producer may not publish would be a false-reject risk for
48
- // multi-channel consumers like `revise` (reads ["plans","reviews"]).
94
+ // Data channel: a provable data mismatch is decisive (shared core).
95
+ const dataCompat = compareDataChannel(producerContract?.produces?.data, consumerContract?.consumes?.data);
96
+ if (!dataCompat.ok) return dataCompat;
97
+ // Named-channel (reads) compat — THE shared `adjudicateChannel` rule (same
98
+ // gating + degrade posture as the validator's load gate). Only a clean
99
+ // mismatch is decisive; skipped channels and comparator throws degrade to
100
+ // `{ ok: true }` — this advisory query never propagates a comparator defect.
49
101
  const produces = producerContract?.produces;
50
102
  const consumes = consumerContract?.consumes;
51
103
  if (produces && consumes?.reads) {
52
- const comparators = getCompositionComparators();
53
104
  for (const channel of Object.keys(consumes.reads)) {
54
- const comparator = comparators.get(channel);
55
- if (!comparator) continue;
56
- const readSpec = consumes.reads[channel];
57
- if (!readSpec?.meta) continue; // no declared kind requirement — degrade
58
- const compat = comparator(produces, consumes, channel);
59
- if (!compat.ok) return compat;
105
+ const verdict = adjudicateChannel(produces, consumes, channel);
106
+ if (verdict.kind === "mismatch") {
107
+ return { ok: false, reason: verdict.reason ?? `named-channel "${channel}" meta incompatibility` };
108
+ }
60
109
  }
61
110
  }
62
111
  return { ok: true };
@@ -65,12 +114,12 @@ export function canCompose(
65
114
  /**
66
115
  * Every known skill whose `consumes` is not provably incompatible with `skill`'s
67
116
  * `produces` — the generator's search-space narrowing. Sorted for determinism.
68
- * Same default-map caveat as `canCompose`: pass `loaded.skillContracts` for
69
- * the effective (declared ⊕ harvested) view, else only declared/injected skills
70
- * are considered. Conservative by design — absent/opaque schemas count as
71
- * compatible, so this excludes only PROVABLE data-channel mismatches.
117
+ * `contracts` is REQUIRED — same rationale as `canCompose`: pass
118
+ * `loaded.skillContracts` for the effective (declared ⊕ harvested) view.
119
+ * Conservative by design — absent/opaque schemas count as compatible, so this
120
+ * excludes only PROVABLE data-channel mismatches.
72
121
  */
73
- export function legalNextSkills(skill: string, contracts: SkillContractMap = getSkillContracts()): string[] {
122
+ export function legalNextSkills(skill: string, contracts: SkillContractMap): string[] {
74
123
  const next: string[] = [];
75
124
  for (const candidate of contracts.keys()) {
76
125
  if (canCompose(skill, candidate, contracts).ok) next.push(candidate);