@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.
- package/README.md +81 -8
- package/api.ts +18 -703
- package/audit-ctx.ts +103 -0
- package/audit-rows.ts +154 -0
- package/audit.ts +158 -190
- package/built-ins.ts +40 -45
- package/chain-state.ts +220 -0
- package/command-run.ts +64 -31
- package/command.ts +123 -21
- package/docs/workflow-authoring.md +356 -63
- package/{lifecycle.ts → events.ts} +161 -37
- package/execution-host.ts +75 -0
- package/host.ts +149 -64
- package/index.ts +25 -81
- package/internal-utils.ts +171 -71
- package/internal.ts +22 -1
- package/judge.ts +241 -0
- package/layers.ts +10 -15
- package/load/alias.ts +6 -12
- package/load/cache.ts +9 -6
- package/load/index.ts +27 -106
- package/load/issues.ts +31 -0
- package/load/legacy.ts +102 -0
- package/load/merge.ts +2 -2
- package/load/resolve-default.ts +3 -4
- package/load/shape-guards.ts +3 -6
- package/load/skill-contract-phase.ts +94 -0
- package/loop-constructors.ts +24 -0
- package/loop-def.ts +285 -0
- package/loop-kinds.ts +750 -0
- package/loop-parallel.ts +250 -0
- package/loop-waves.ts +99 -0
- package/loop.ts +330 -0
- package/loops/constructors.ts +334 -0
- package/loops/derivations.ts +65 -0
- package/loops/introspection.ts +184 -0
- package/loops/panel.ts +196 -0
- package/loops/verify.ts +99 -0
- package/messages.ts +249 -156
- package/outcomes/collectors/directory-path.ts +7 -3
- package/outcomes/collectors/index.ts +1 -0
- package/outcomes/collectors/require-opt.ts +11 -0
- package/outcomes/collectors/text-scan.ts +47 -0
- package/outcomes/collectors/tool-call.ts +8 -3
- package/outcomes/collectors/transcript-path.ts +4 -18
- package/outcomes/collectors/union.ts +30 -10
- package/outcomes/collectors/url.ts +9 -14
- package/outcomes/collectors/workspace-diff.ts +21 -14
- package/outcomes/exec.ts +17 -0
- package/outcomes/git-commit.ts +190 -100
- package/outcomes/index.ts +1 -0
- package/outcomes/parsers/json-body.ts +2 -2
- package/outcomes/side-effect.ts +3 -3
- package/output-spec.ts +36 -10
- package/output.ts +98 -20
- package/package.json +27 -11
- package/predicates.ts +11 -8
- package/preview.ts +81 -21
- package/registration.ts +117 -36
- package/routing-dsl.ts +322 -0
- package/routing.ts +48 -2
- package/runner/by-name.ts +2 -1
- package/runner/by-run-id.ts +2 -1
- package/runner/chain-advance.ts +84 -56
- package/runner/errors.ts +10 -0
- package/runner/failure.ts +163 -0
- package/runner/index.ts +7 -13
- package/runner/input-validation.ts +16 -23
- package/runner/preflight.ts +169 -0
- package/runner/resolve-stage.ts +68 -0
- package/runner/resume-entry.ts +121 -0
- package/runner/resume-loop.ts +131 -0
- package/runner/resume.ts +368 -262
- package/runner/run-context.ts +165 -0
- package/runner/run-stage.ts +490 -0
- package/runner/runner.ts +202 -449
- package/runner/script-stage.ts +104 -112
- package/schema-compat.ts +12 -1
- package/semaphore.ts +55 -0
- package/sessions/extraction.ts +146 -81
- package/sessions/halt-routing.ts +195 -0
- package/sessions/index.ts +3 -1
- package/sessions/locate.ts +141 -0
- package/sessions/reattach.ts +71 -0
- package/sessions/sessions.ts +114 -199
- package/sessions/spawn.ts +132 -119
- package/sessions/success-persist.ts +89 -0
- package/skill-contract.ts +22 -25
- package/skill-contracts/composition.ts +86 -37
- package/skill-contracts/{registries.ts → extension-points.ts} +45 -12
- package/skill-contracts/harvest.ts +4 -4
- package/skill-contracts/index.ts +15 -8
- package/skill-contracts/registry.ts +33 -50
- package/stage-def.ts +595 -0
- package/stage-errors.ts +84 -0
- package/stage-identity.ts +56 -0
- package/startup.ts +4 -1
- package/state/index.ts +8 -1
- package/state/names.ts +91 -65
- package/state/paths.ts +20 -0
- package/state/raw.ts +77 -0
- package/state/reads.ts +103 -85
- package/state/resolve.ts +73 -0
- package/state/state.ts +135 -15
- package/state/writes.ts +29 -12
- package/transcript.ts +24 -0
- package/triggers.ts +11 -3
- package/types.ts +290 -78
- package/validate/contract-compat.ts +198 -0
- package/validate/graph.ts +134 -0
- package/validate/issue.ts +328 -0
- package/validate/stage-rules.ts +499 -0
- package/validate-output.ts +82 -7
- package/validate-workflow.ts +57 -759
- package/validation-bounds.ts +35 -0
- package/control-flow.ts +0 -135
- package/fanout.ts +0 -102
- package/iterate.ts +0 -155
- package/load/cache.test.ts +0 -82
- package/load/shape-guards.test.ts +0 -74
- package/outcomes/collectors/directory-path.test.ts +0 -64
- package/outcomes/collectors/tool-call.test.ts +0 -110
- package/outcomes/collectors/transcript-path.test.ts +0 -70
- package/outcomes/collectors/union.test.ts +0 -59
- package/outcomes/collectors/url.test.ts +0 -67
- package/outcomes/collectors/workspace-diff.test.ts +0 -107
- package/outcomes/git-commit.test.ts +0 -194
- package/outcomes/parsers/json-body.test.ts +0 -80
- package/runner/by-name.test.ts +0 -95
- package/runner/by-run-id.test.ts +0 -115
- package/runner/resume-fanout.test.ts +0 -331
- package/runner/resume-fanout.ts +0 -136
- package/runner/resume-iterate.test.ts +0 -444
- package/runner/resume-iterate.ts +0 -111
- package/runner/resume.test.ts +0 -1130
- package/runner/stage-lifecycle.ts +0 -500
package/sessions/spawn.ts
CHANGED
|
@@ -1,139 +1,152 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Session
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
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
|
-
*
|
|
8
|
-
*
|
|
9
|
-
* `
|
|
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 {
|
|
14
|
-
import type { WorkflowHostContext } from "../types.js";
|
|
22
|
+
import type { StageSession, WorkflowHostContext, WorkflowSessionContext } from "../types.js";
|
|
15
23
|
|
|
16
24
|
/**
|
|
17
|
-
*
|
|
18
|
-
*
|
|
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
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
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
|
|
43
|
-
|
|
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
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
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
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
//
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
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
|
-
*
|
|
113
|
-
*
|
|
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
|
-
|
|
82
|
+
export function spawnChildAndRun(
|
|
120
83
|
ctx: WorkflowHostContext,
|
|
121
|
-
|
|
122
|
-
|
|
84
|
+
s: Pick<StageSession, "prompt" | "model" | "signal" | "laneUnitIndex">,
|
|
85
|
+
body: (child: WorkflowSessionContext) => Promise<void>,
|
|
123
86
|
): Promise<void> {
|
|
124
|
-
|
|
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
|
-
|
|
138
|
-
|
|
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
|
-
*
|
|
8
|
-
* (see `skill-contracts
|
|
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
|
-
|
|
28
|
-
|
|
29
|
-
|
|
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)
|
|
41
|
-
*
|
|
42
|
-
*
|
|
43
|
-
*
|
|
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"
|
|
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
|
-
*
|
|
102
|
-
*
|
|
103
|
-
*
|
|
104
|
-
*
|
|
105
|
-
*
|
|
106
|
-
*
|
|
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 {
|
|
12
|
-
|
|
13
|
-
|
|
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
|
-
*
|
|
21
|
-
* (`
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
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
|
|
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
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
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
|
|
55
|
-
if (
|
|
56
|
-
|
|
57
|
-
|
|
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
|
-
*
|
|
69
|
-
* the effective (declared ⊕ harvested) view
|
|
70
|
-
*
|
|
71
|
-
*
|
|
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
|
|
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);
|