@juicesharp/rpiv-workflow 1.19.0 → 1.20.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-rows.ts +136 -0
- package/audit.ts +139 -126
- package/built-ins.ts +20 -45
- package/chain-state.ts +169 -0
- package/command-run.ts +31 -3
- package/command.ts +116 -20
- package/docs/workflow-authoring.md +322 -61
- package/{lifecycle.ts → events.ts} +119 -35
- package/host.ts +30 -0
- package/index.ts +25 -81
- package/internal-utils.ts +92 -78
- package/internal.ts +21 -1
- package/judge.ts +229 -0
- package/layers.ts +10 -15
- package/load/alias.ts +6 -12
- package/load/cache.ts +9 -6
- package/load/index.ts +16 -109
- package/load/issues.ts +31 -0
- package/load/legacy.ts +102 -0
- package/load/merge.ts +2 -2
- package/load/shape-guards.test.ts +4 -1
- package/load/shape-guards.ts +3 -6
- package/load/skill-contract-phase.ts +94 -0
- package/loop-constructors.ts +623 -0
- package/loop-def.ts +240 -0
- package/loop-kinds.ts +493 -0
- package/loop.ts +304 -0
- package/messages.ts +225 -157
- package/outcomes/collectors/directory-path.ts +7 -3
- package/outcomes/collectors/require-opt.ts +11 -0
- package/outcomes/collectors/tool-call.test.ts +3 -1
- package/outcomes/collectors/tool-call.ts +8 -3
- package/outcomes/collectors/transcript-path.ts +2 -3
- package/outcomes/collectors/union.test.ts +54 -0
- package/outcomes/collectors/union.ts +28 -9
- package/outcomes/collectors/url.ts +7 -0
- package/outcomes/collectors/workspace-diff.test.ts +13 -0
- package/outcomes/collectors/workspace-diff.ts +21 -14
- package/outcomes/exec.ts +17 -0
- package/outcomes/git-commit.test.ts +76 -30
- package/outcomes/git-commit.ts +139 -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 +40 -20
- package/package.json +13 -7
- package/predicates.ts +11 -8
- package/preview.ts +77 -17
- package/registration.ts +109 -35
- package/routing-dsl.ts +310 -0
- package/routing.ts +2 -2
- package/runner/by-name.ts +2 -1
- package/runner/by-run-id.ts +2 -1
- package/runner/chain-advance.ts +59 -44
- package/runner/errors.ts +33 -0
- package/runner/failure.ts +109 -0
- package/runner/header-write-failure.test.ts +64 -0
- package/runner/index.ts +7 -13
- package/runner/input-validation.ts +11 -21
- package/runner/preflight.ts +173 -0
- package/runner/resolve-stage.ts +68 -0
- package/runner/resume-entry.ts +101 -0
- package/runner/resume-loop.test.ts +1410 -0
- package/runner/resume-loop.ts +110 -0
- package/runner/resume-session.test.ts +400 -0
- package/runner/resume.test.ts +881 -206
- package/runner/resume.ts +281 -261
- package/runner/run-context.ts +161 -0
- package/runner/run-stage.ts +456 -0
- package/runner/runner.ts +59 -400
- package/runner/script-stage.ts +103 -105
- package/schema-compat.ts +13 -1
- package/sessions/extraction.ts +53 -31
- package/sessions/index.ts +3 -1
- package/sessions/locate.test.ts +77 -0
- package/sessions/locate.ts +90 -0
- package/sessions/reattach.ts +63 -0
- package/sessions/sessions.ts +130 -127
- package/skill-contract.ts +22 -25
- package/skill-contracts/composition.ts +88 -37
- package/skill-contracts/{registries.ts → extension-points.ts} +45 -12
- package/skill-contracts/harvest.ts +2 -3
- package/skill-contracts/index.ts +15 -8
- package/skill-contracts/registry.ts +33 -50
- package/stage-def.ts +527 -0
- package/startup.ts +3 -1
- package/state/index.ts +8 -1
- package/state/names.ts +91 -65
- package/state/paths.ts +12 -0
- package/state/raw.ts +78 -0
- package/state/reads.ts +103 -85
- package/state/resolve.ts +73 -0
- package/state/state.ts +112 -15
- package/state/writes.ts +29 -12
- package/transcript.ts +24 -0
- package/triggers.ts +11 -3
- package/types.ts +202 -44
- package/validate/contract-compat.ts +193 -0
- package/validate/graph.ts +125 -0
- package/validate/issue.ts +314 -0
- package/validate/stage-rules.ts +420 -0
- package/validate-output.ts +69 -1
- package/validate-workflow.ts +55 -759
- package/control-flow.ts +0 -135
- package/fanout.ts +0 -102
- package/iterate.ts +0 -155
- 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/stage-lifecycle.ts +0 -500
package/runner/script-stage.ts
CHANGED
|
@@ -9,63 +9,67 @@
|
|
|
9
9
|
* returns `{ kind, artifacts, data }` (`produces.script`) or `void`
|
|
10
10
|
* (`acts.script` / `terminal.script`), and the runner stamps `meta`,
|
|
11
11
|
* persists the JSONL row, advances the rolling primary slot, fires
|
|
12
|
-
* lifecycle events, and recurses through `
|
|
12
|
+
* lifecycle events, and recurses through the injected `advance`.
|
|
13
13
|
*
|
|
14
|
-
* The
|
|
15
|
-
*
|
|
16
|
-
*
|
|
14
|
+
* The retry policy is the SHARED `runValidationRetryLoop`
|
|
15
|
+
* (validate-output.ts) — same structure the skill path's extraction runs;
|
|
16
|
+
* success persistence is the SHARED `persistStageSuccess` (audit-rows.ts) —
|
|
17
|
+
* so the audit row shape, the lifecycle fire order (`onStageStart` →
|
|
17
18
|
* `onStageRetry`* → `onStageEnd` | `onStageError`), and the
|
|
18
19
|
* primary-artifact advance behaviour stay aligned across the two
|
|
19
|
-
* stage kinds.
|
|
20
|
+
* stage kinds by construction.
|
|
20
21
|
*
|
|
21
22
|
* Invariants this file relies on (enforced at load time by
|
|
22
23
|
* `validateWorkflow:checkScriptStageInvariants`):
|
|
23
24
|
* - `stage.skill` is unset.
|
|
24
25
|
* - `stage.outcome` is unset (no collector to run).
|
|
25
|
-
* - `stage.
|
|
26
|
+
* - `stage.loop` is unset (the runner's per-unit machinery doesn't
|
|
26
27
|
* apply; authors write their own loop inside `run()`).
|
|
27
28
|
* - `stage.sessionPolicy !== "continue"` (no session to continue).
|
|
28
29
|
*/
|
|
29
30
|
|
|
30
31
|
import type { ScriptContext } from "../api.js";
|
|
31
|
-
import { auditCtxFor,
|
|
32
|
-
import
|
|
33
|
-
import {
|
|
34
|
-
import {
|
|
32
|
+
import { auditCtxFor, failedArgs, recordTerminalFailure, terminate } from "../audit.js";
|
|
33
|
+
import { allocateStageNumber, persistStageSuccess } from "../audit-rows.js";
|
|
34
|
+
import { lifecycleCtxFor, scriptStageRef } from "../events.js";
|
|
35
|
+
import type { Artifact } from "../handle.js";
|
|
36
|
+
import { formatError, nowIso } from "../internal-utils.js";
|
|
35
37
|
import {
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
MSG_AUDIT_WRITE_FAILED,
|
|
40
|
-
MSG_SCRIPT_THREW,
|
|
38
|
+
FAIL_AUDIT_WRITE,
|
|
39
|
+
FAIL_SCRIPT_THREW,
|
|
40
|
+
FAIL_VALIDATION_EXHAUSTED,
|
|
41
41
|
MSG_STAGE_COMPLETE,
|
|
42
|
-
MSG_VALIDATION_EXHAUSTED,
|
|
43
42
|
STATUS_KEY,
|
|
44
43
|
STATUS_STAGE,
|
|
45
44
|
} from "../messages.js";
|
|
46
45
|
import { finalizeOutput, type Output } from "../output.js";
|
|
47
|
-
import type { RunContext,
|
|
48
|
-
import {
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
46
|
+
import type { RunContext, WorkflowHostContext } from "../types.js";
|
|
47
|
+
import {
|
|
48
|
+
DEFAULT_VALIDATION_RETRIES,
|
|
49
|
+
describeFailure,
|
|
50
|
+
runValidationRetryLoop,
|
|
51
|
+
validateOutputData,
|
|
52
|
+
} from "../validate-output.js";
|
|
53
|
+
import type { AdvanceFn, ChainOutcome } from "./failure.js";
|
|
54
|
+
import type { ResolvedStage } from "./resolve-stage.js";
|
|
52
55
|
|
|
53
56
|
/**
|
|
54
57
|
* Drive a script stage: lifecycle-fire `onStageStart`, retry-loop the
|
|
55
58
|
* `run` body against `outputSchema`, then either persist + advance or
|
|
56
59
|
* record a terminal failure. Sole entry point — `runStage` branches
|
|
57
|
-
* here
|
|
60
|
+
* here on `mode === "script"`, passing the composed `advance`.
|
|
58
61
|
*
|
|
59
62
|
* Caller pre-conditions (held by `runStage`):
|
|
60
|
-
* - `ensureInputValid` already passed
|
|
61
|
-
* - `
|
|
63
|
+
* - `ensureInputValid` already passed.
|
|
64
|
+
* - `mode === "script"` (a script stage cannot carry a `loop`).
|
|
62
65
|
*/
|
|
63
66
|
export async function runScript(
|
|
64
67
|
curCtx: WorkflowHostContext,
|
|
65
68
|
stage: ResolvedStage,
|
|
66
69
|
idx: number,
|
|
67
70
|
run: RunContext,
|
|
68
|
-
|
|
71
|
+
advance: AdvanceFn,
|
|
72
|
+
): Promise<ChainOutcome> {
|
|
69
73
|
curCtx.ui.setStatus(STATUS_KEY, STATUS_STAGE(stage.stageNumber, run.totalStages, stage.name));
|
|
70
74
|
|
|
71
75
|
const ref = scriptStageRef(stage.name, stage.stageNumber);
|
|
@@ -77,44 +81,74 @@ export async function runScript(
|
|
|
77
81
|
state: run.state,
|
|
78
82
|
};
|
|
79
83
|
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
const invocation = await invokeRun(curCtx, stage, scriptCtx, ref, run);
|
|
85
|
-
if (!invocation.ok) return;
|
|
86
|
-
|
|
87
|
-
const output = finalizeOutput(invocation.raw, {
|
|
88
|
-
stage: stage.name,
|
|
89
|
-
stageNumber: run.state.lastAllocatedStageNumber + 1,
|
|
90
|
-
ts: nowIso(),
|
|
91
|
-
runId: run.runId,
|
|
92
|
-
});
|
|
84
|
+
// One allocation per activation, BEFORE any output is built — the
|
|
85
|
+
// envelope, the success/failure row, and lifecycle bookkeeping share it
|
|
86
|
+
// (mirrors `produceAndValidateOutput` on the skill path).
|
|
87
|
+
const stageNumber = allocateStageNumber(run.state);
|
|
93
88
|
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
89
|
+
// `halt: "recorded"` = invokeRun already recorded the terminal failure.
|
|
90
|
+
const result = await runValidationRetryLoop<Output, "recorded">(
|
|
91
|
+
{
|
|
92
|
+
maxRetries: stage.def.maxRetries ?? DEFAULT_VALIDATION_RETRIES,
|
|
93
|
+
haltOnInvalid: (stage.def.onInvalid ?? "retry") === "halt",
|
|
94
|
+
},
|
|
95
|
+
{
|
|
96
|
+
produce: async () => {
|
|
97
|
+
const invocation = await invokeRun(curCtx, stage, scriptCtx, run, stageNumber);
|
|
98
|
+
if (!invocation.ok) return { ok: false, halt: "recorded" };
|
|
99
|
+
const output = finalizeOutput(invocation.raw, {
|
|
100
|
+
stage: stage.name,
|
|
101
|
+
stageNumber,
|
|
102
|
+
ts: nowIso(),
|
|
103
|
+
runId: run.runId,
|
|
104
|
+
});
|
|
105
|
+
return { ok: true, value: output };
|
|
106
|
+
},
|
|
107
|
+
validate: async (output) => {
|
|
108
|
+
if (!(stage.def.kind === "produces" && stage.def.outputSchema)) {
|
|
109
|
+
return { ok: true, result: { valid: true, failures: [] } };
|
|
106
110
|
}
|
|
111
|
+
// No catch: a throwing author schema propagates to the runner's
|
|
112
|
+
// single catch site (today's contract).
|
|
113
|
+
return { ok: true, result: await Promise.resolve(validateOutputData(stage.def.outputSchema, output.data)) };
|
|
114
|
+
},
|
|
115
|
+
onRetry: async (attempt) => {
|
|
107
116
|
await run.lifecycle.fire(curCtx, "onStageRetry", ref, attempt, lifecycleCtxFor(run));
|
|
108
|
-
|
|
109
|
-
}
|
|
110
|
-
}
|
|
117
|
+
return { ok: true };
|
|
118
|
+
},
|
|
119
|
+
},
|
|
120
|
+
);
|
|
111
121
|
|
|
112
|
-
|
|
122
|
+
if (result.kind === "halt") return "halted";
|
|
123
|
+
if (result.kind === "exhausted") {
|
|
124
|
+
const failureSummary = result.failures.map(describeFailure).join("; ");
|
|
125
|
+
await recordTerminalFailure(
|
|
126
|
+
curCtx,
|
|
127
|
+
scriptAuditCtx(run, stage, stageNumber),
|
|
128
|
+
failedArgs(FAIL_VALIDATION_EXHAUSTED(stage.name, failureSummary)),
|
|
129
|
+
);
|
|
130
|
+
return "halted";
|
|
131
|
+
}
|
|
113
132
|
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
133
|
+
const output = result.value;
|
|
134
|
+
// `skill` is intentionally absent on script-stage rows — JSON.stringify
|
|
135
|
+
// drops `undefined` so the JSONL row carries no skill field at all.
|
|
136
|
+
// `session: null` is explicit: script stages never open a Pi session.
|
|
137
|
+
const persisted = persistStageSuccess(
|
|
138
|
+
run.state,
|
|
139
|
+
{ cwd: run.cwd, runId: run.runId, stage: stage.name, output, session: null, preAllocated: stageNumber },
|
|
140
|
+
stage.def,
|
|
141
|
+
);
|
|
142
|
+
if (!persisted) {
|
|
143
|
+
const auditFailure = FAIL_AUDIT_WRITE(stage.name);
|
|
144
|
+
curCtx.ui.notify(auditFailure.toast, "error");
|
|
145
|
+
terminate(run.state, { status: "failed", error: auditFailure.error });
|
|
146
|
+
return "halted";
|
|
117
147
|
}
|
|
148
|
+
curCtx.ui.notify(MSG_STAGE_COMPLETE(stage.name), "info");
|
|
149
|
+
|
|
150
|
+
await run.lifecycle.fire(curCtx, "onStageEnd", ref, output, lifecycleCtxFor(run));
|
|
151
|
+
return advance(curCtx, stage.name, idx, run);
|
|
118
152
|
}
|
|
119
153
|
|
|
120
154
|
type ScriptInvocationResult =
|
|
@@ -132,8 +166,8 @@ async function invokeRun(
|
|
|
132
166
|
curCtx: WorkflowHostContext,
|
|
133
167
|
stage: ResolvedStage,
|
|
134
168
|
scriptCtx: ScriptContext,
|
|
135
|
-
ref: ReturnType<typeof scriptStageRef>,
|
|
136
169
|
run: RunContext,
|
|
170
|
+
stageNumber: number,
|
|
137
171
|
): Promise<ScriptInvocationResult> {
|
|
138
172
|
try {
|
|
139
173
|
const result = await Promise.resolve(stage.def.run!(scriptCtx));
|
|
@@ -143,65 +177,29 @@ async function invokeRun(
|
|
|
143
177
|
: { kind: "side-effect", artifacts: [] as readonly Artifact[], data: {} as unknown };
|
|
144
178
|
return { ok: true, raw };
|
|
145
179
|
} catch (e) {
|
|
146
|
-
const reason =
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
// `_ref` arg here so the caller doesn't fire a second time.
|
|
155
|
-
void ref;
|
|
180
|
+
const reason = formatError(e);
|
|
181
|
+
// `recordTerminalFailure` fires `onStageError` itself — the caller must
|
|
182
|
+
// not fire a second time on the `ok: false` return.
|
|
183
|
+
await recordTerminalFailure(
|
|
184
|
+
curCtx,
|
|
185
|
+
scriptAuditCtx(run, stage, stageNumber),
|
|
186
|
+
failedArgs(FAIL_SCRIPT_THREW(stage.name, reason)),
|
|
187
|
+
);
|
|
156
188
|
return { ok: false };
|
|
157
189
|
}
|
|
158
190
|
}
|
|
159
191
|
|
|
160
|
-
/**
|
|
161
|
-
* Persist the success row + advance the rolling primary-artifact slot.
|
|
162
|
-
* Returns `true` iff the JSONL row landed. Mirrors
|
|
163
|
-
* `tryRecordStage` + `recordStageSuccess` in `sessions/sessions.ts`,
|
|
164
|
-
* specialised for the script path (no SessionContext, no skill field,
|
|
165
|
-
* no `onStageEnd` fire — caller owns lifecycle ordering here).
|
|
166
|
-
*/
|
|
167
|
-
function recordScriptSuccess(
|
|
168
|
-
curCtx: WorkflowHostContext,
|
|
169
|
-
stage: ResolvedStage,
|
|
170
|
-
output: Output,
|
|
171
|
-
state: RunState,
|
|
172
|
-
cwd: string,
|
|
173
|
-
runId: string,
|
|
174
|
-
): boolean {
|
|
175
|
-
const assigned = recordStage(
|
|
176
|
-
cwd,
|
|
177
|
-
runId,
|
|
178
|
-
// `skill` is intentionally absent on script-stage rows — JSON.stringify
|
|
179
|
-
// drops `undefined` so the JSONL row carries no skill field at all.
|
|
180
|
-
{ stage: stage.name, status: "completed", ts: nowIso(), output },
|
|
181
|
-
state,
|
|
182
|
-
);
|
|
183
|
-
if (assigned === undefined) {
|
|
184
|
-
curCtx.ui.notify(MSG_AUDIT_WRITE_FAILED(stage.name), "error");
|
|
185
|
-
state.termination.error = ERR_AUDIT_WRITE_FAILED(stage.name);
|
|
186
|
-
return false;
|
|
187
|
-
}
|
|
188
|
-
applyCompletedStage(state, stage.def, stage.name, output);
|
|
189
|
-
state.output = output;
|
|
190
|
-
state.stagesCompleted++;
|
|
191
|
-
curCtx.ui.notify(MSG_STAGE_COMPLETE(stage.name), "info");
|
|
192
|
-
return true;
|
|
193
|
-
}
|
|
194
|
-
|
|
195
192
|
/**
|
|
196
193
|
* Build the `AuditCtx`-shaped object `recordTerminalFailure` needs for
|
|
197
194
|
* a script-stage halt. The `skill` field doubles as the lifecycle
|
|
198
195
|
* `onStageError` ref payload — using `stage.name` keeps the failure
|
|
199
196
|
* attribution aligned with the success row's `stage` identity.
|
|
200
197
|
*/
|
|
201
|
-
function scriptAuditCtx(run: RunContext, stage: ResolvedStage) {
|
|
198
|
+
function scriptAuditCtx(run: RunContext, stage: ResolvedStage, stageNumber: number) {
|
|
202
199
|
// `skill` doubles as the notify-message subject (`MSG_VALIDATION_EXHAUSTED`,
|
|
203
200
|
// `MSG_STAGE_FAILED`); set to the stage name so the user sees the stage
|
|
204
201
|
// identity. `isScript: true` ensures the JSONL row drops the field and
|
|
205
202
|
// `onStageError` fires with `scriptStageRef` (no `skill` payload).
|
|
206
|
-
|
|
203
|
+
// `allocatedStageNumber` lets a failure row reuse the activation's number.
|
|
204
|
+
return auditCtxFor(run, stage.name, stage.name, { isScript: true, allocatedStageNumber: stageNumber });
|
|
207
205
|
}
|
package/schema-compat.ts
CHANGED
|
@@ -14,7 +14,19 @@
|
|
|
14
14
|
|
|
15
15
|
import { deepEqual } from "./internal-utils.js";
|
|
16
16
|
import type { JsonSchemaObject } from "./json-schema.js";
|
|
17
|
-
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Result of a conservative structural compatibility check between a
|
|
20
|
+
* producer's output schema and a consumer's input schema. Owned by the
|
|
21
|
+
* engine that defines its semantics (this module); the contract domain
|
|
22
|
+
* (`skill-contract.ts`) re-exports it so `CompositionComparator` consumers
|
|
23
|
+
* stay self-contained (G7 — the old direction was a utility→domain
|
|
24
|
+
* inversion).
|
|
25
|
+
*/
|
|
26
|
+
export interface SchemaCompatResult {
|
|
27
|
+
ok: boolean;
|
|
28
|
+
reason?: string;
|
|
29
|
+
}
|
|
18
30
|
|
|
19
31
|
/** The set of JSON-Schema `type`s a schema allows (string or string[]), or undefined if untyped. */
|
|
20
32
|
function typeSet(schema: JsonSchemaObject): Set<string> | undefined {
|
package/sessions/extraction.ts
CHANGED
|
@@ -16,15 +16,15 @@
|
|
|
16
16
|
*/
|
|
17
17
|
|
|
18
18
|
import type { StageDef, StageSchema } from "../api.js";
|
|
19
|
-
import {
|
|
19
|
+
import { allocateStageNumber, currentStageRef } from "../audit.js";
|
|
20
|
+
import { lifecycleCtxFromSession } from "../events.js";
|
|
20
21
|
import type { Artifact } from "../handle.js";
|
|
21
|
-
import { assertNever, withTimeout } from "../internal-utils.js";
|
|
22
|
+
import { assertNever, formatError, nowIso, withTimeout } from "../internal-utils.js";
|
|
22
23
|
import { isJsonSchemaObject, jsonSchemaToStandard } from "../json-schema.js";
|
|
23
|
-
import {
|
|
24
|
-
import { ERR_SCHEMA_TIMEOUT, MSG_VALIDATION_RETRY, MSG_VALIDATION_RETRY_PROMPT } from "../messages.js";
|
|
24
|
+
import { ERR_COLLECTOR_THREW, ERR_PARSER_THREW, ERR_SCHEMA_TIMEOUT, MSG_VALIDATION_RETRY } from "../messages.js";
|
|
25
25
|
import { sideEffectOutcome } from "../outcomes/index.js";
|
|
26
26
|
import { finalizeOutput, type Output } from "../output.js";
|
|
27
|
-
import type { CollectCtx,
|
|
27
|
+
import type { CollectCtx, Outcome } from "../output-spec.js";
|
|
28
28
|
import { type BranchEntry, readBranch } from "../transcript.js";
|
|
29
29
|
import type { StageSession, WorkflowHostContext } from "../types.js";
|
|
30
30
|
import {
|
|
@@ -53,6 +53,10 @@ export async function produceAndValidateOutput(
|
|
|
53
53
|
branch: BranchEntry[],
|
|
54
54
|
branchOffset: number | undefined,
|
|
55
55
|
): Promise<OutputProduction> {
|
|
56
|
+
// Allocate the activation's stage number ONCE, before any output envelope
|
|
57
|
+
// is built — the envelope's `meta.stageNumber`, the eventual audit row
|
|
58
|
+
// (success or failure), and every lifecycle ref share this value.
|
|
59
|
+
s.allocatedStageNumber ??= allocateStageNumber(s.state);
|
|
56
60
|
const outcome = resolveOutcome(s.stage, s.skill);
|
|
57
61
|
const collectCtx = buildCollectCtx(s, branch, branchOffset);
|
|
58
62
|
const finalize = (parts: { kind: string; artifacts: readonly Artifact[]; data: unknown }) => wrapOutput(s, parts);
|
|
@@ -76,7 +80,7 @@ export async function produceAndValidateOutput(
|
|
|
76
80
|
* load time; the runtime throw is defense-in-depth for programmatic
|
|
77
81
|
* embedders that bypassed validation.
|
|
78
82
|
*/
|
|
79
|
-
function resolveOutcome(stage: StageDef, skill: string):
|
|
83
|
+
function resolveOutcome(stage: StageDef, skill: string): Outcome {
|
|
80
84
|
if (stage.outcome) return stage.outcome;
|
|
81
85
|
switch (stage.kind) {
|
|
82
86
|
case "side-effect":
|
|
@@ -117,7 +121,10 @@ function wrapOutput(s: StageSession, parts: { kind: string; artifacts: readonly
|
|
|
117
121
|
return finalizeOutput(parts, {
|
|
118
122
|
stage: s.stageName,
|
|
119
123
|
skill: s.skill,
|
|
120
|
-
|
|
124
|
+
// Pre-allocated by `produceAndValidateOutput` before any finalize runs —
|
|
125
|
+
// no `lastAllocatedStageNumber + 1` peek, no temporal coupling with
|
|
126
|
+
// recordStage.
|
|
127
|
+
stageNumber: s.allocatedStageNumber!,
|
|
121
128
|
ts: nowIso(),
|
|
122
129
|
runId: s.runId,
|
|
123
130
|
});
|
|
@@ -129,13 +136,23 @@ type RunOutcomeResult = { kind: "ok"; output: Output } | { kind: "fatal"; messag
|
|
|
129
136
|
* The collector → parser pipeline. When `parser` is omitted, the
|
|
130
137
|
* output emits `kind: "artifacts"` with `data = artifacts` — a stage
|
|
131
138
|
* that only needs to enumerate doesn't have to write a parser.
|
|
139
|
+
*
|
|
140
|
+
* `collect`/`parse` are the PRIMARY user extension points, so a throw from
|
|
141
|
+
* either is guarded here and attributed ("collector threw…"), folding into
|
|
142
|
+
* the same fatal arm a tagged `{ kind: "fatal" }` return takes — instead of
|
|
143
|
+
* escaping to the runner's generic catch and reading as a machinery failure.
|
|
132
144
|
*/
|
|
133
145
|
async function runOutcome(
|
|
134
|
-
outcome:
|
|
146
|
+
outcome: Outcome,
|
|
135
147
|
ctx: CollectCtx,
|
|
136
148
|
finalize: (parts: { kind: string; artifacts: readonly Artifact[]; data: unknown }) => Output,
|
|
137
149
|
): Promise<RunOutcomeResult> {
|
|
138
|
-
|
|
150
|
+
let collected: Awaited<ReturnType<typeof outcome.collector.collect>>;
|
|
151
|
+
try {
|
|
152
|
+
collected = await outcome.collector.collect(ctx);
|
|
153
|
+
} catch (e) {
|
|
154
|
+
return { kind: "fatal", message: ERR_COLLECTOR_THREW(ctx.skill, formatError(e)) };
|
|
155
|
+
}
|
|
139
156
|
if (collected.kind === "fatal") return collected;
|
|
140
157
|
|
|
141
158
|
if (!outcome.parser) {
|
|
@@ -145,7 +162,12 @@ async function runOutcome(
|
|
|
145
162
|
};
|
|
146
163
|
}
|
|
147
164
|
|
|
148
|
-
|
|
165
|
+
let parsed: Awaited<ReturnType<typeof outcome.parser.parse>>;
|
|
166
|
+
try {
|
|
167
|
+
parsed = await outcome.parser.parse({ ...ctx, artifacts: collected.artifacts });
|
|
168
|
+
} catch (e) {
|
|
169
|
+
return { kind: "fatal", message: ERR_PARSER_THREW(ctx.skill, formatError(e)) };
|
|
170
|
+
}
|
|
149
171
|
if (parsed.kind === "fatal") return parsed;
|
|
150
172
|
return {
|
|
151
173
|
kind: "ok",
|
|
@@ -181,7 +203,7 @@ function enforceCompletionContract(
|
|
|
181
203
|
/**
|
|
182
204
|
* The schema output is validated against: the stage's own `outputSchema` if it
|
|
183
205
|
* declares one, otherwise the dispatched skill's contract `produces.data`
|
|
184
|
-
* (sourced from the
|
|
206
|
+
* (sourced from the registered-contract registry threaded onto the session).
|
|
185
207
|
*
|
|
186
208
|
* Degrades exactly like the input-side runtime mirror (`ensureContractInputValid`):
|
|
187
209
|
* a non-object / unparseable `produces.data` is treated as absent (no schema),
|
|
@@ -190,7 +212,7 @@ function enforceCompletionContract(
|
|
|
190
212
|
function effectiveOutputSchema(s: StageSession): StageSchema | undefined {
|
|
191
213
|
if (s.stage.outputSchema) return s.stage.outputSchema;
|
|
192
214
|
// `s.skill` is resolved via `resolveSkill(def, stageName)` in `resolveStage`
|
|
193
|
-
// (stage
|
|
215
|
+
// (run-stage.ts), matching the contract map key used by
|
|
194
216
|
// `validate-workflow.ts` and `harvestStageContracts`. The single helper
|
|
195
217
|
// ensures load-time lint and runtime agree on which contract covers the stage.
|
|
196
218
|
const producesData = s.skillContracts?.get(s.skill)?.produces?.data;
|
|
@@ -203,7 +225,7 @@ function shouldValidateOutput(s: StageSession, output: Output): boolean {
|
|
|
203
225
|
}
|
|
204
226
|
|
|
205
227
|
interface RetryDeps {
|
|
206
|
-
outcome:
|
|
228
|
+
outcome: Outcome;
|
|
207
229
|
collectCtx: CollectCtx;
|
|
208
230
|
finalize: (parts: { kind: string; artifacts: readonly Artifact[]; data: unknown }) => Output;
|
|
209
231
|
}
|
|
@@ -233,25 +255,14 @@ async function retryUntilValid(
|
|
|
233
255
|
while (!result.valid && attempts < maxRetries && s.stage.onInvalid !== "halt") {
|
|
234
256
|
attempts++;
|
|
235
257
|
// onStageRetry fires before the agent is re-prompted; `attempt` is 1-based.
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
attempts,
|
|
241
|
-
buildLifecycleContext({
|
|
242
|
-
cwd: s.cwd,
|
|
243
|
-
runId: s.runId,
|
|
244
|
-
workflow: s.runIdentity.workflow,
|
|
245
|
-
totalStages: s.runIdentity.totalStages,
|
|
246
|
-
trigger: s.runIdentity.trigger,
|
|
247
|
-
state: s.state,
|
|
248
|
-
}),
|
|
249
|
-
);
|
|
258
|
+
// Ref shares the activation's ALLOCATOR number (currentStageRef) so
|
|
259
|
+
// listeners can correlate this retry with the end/error event it
|
|
260
|
+
// belongs to — graph position (`stageIndex + 1`) diverges past any loop.
|
|
261
|
+
await s.lifecycle.fire(ctx, "onStageRetry", currentStageRef(s), attempts, lifecycleCtxFromSession(s));
|
|
250
262
|
try {
|
|
251
263
|
await askAgentToFix(ctx, s, attempts, result.failures, timeoutMs);
|
|
252
264
|
} catch (e) {
|
|
253
|
-
|
|
254
|
-
return { kind: "fatal", message: msg };
|
|
265
|
+
return { kind: "fatal", message: formatError(e) };
|
|
255
266
|
}
|
|
256
267
|
|
|
257
268
|
const retryBranch = readBranch(ctx);
|
|
@@ -271,6 +282,18 @@ async function retryUntilValid(
|
|
|
271
282
|
return { kind: "ok", output };
|
|
272
283
|
}
|
|
273
284
|
|
|
285
|
+
/**
|
|
286
|
+
* Sent to the AGENT as a follow-up message when an output-schema validation
|
|
287
|
+
* fails — instructs it to re-write the artifact at the same path with a
|
|
288
|
+
* corrected frontmatter. Lives beside its only consumer (this is
|
|
289
|
+
* model-facing prompt text, not a UI constant). `errorLines` is a pre-joined
|
|
290
|
+
* bullet list (one line per failure) so the factory stays single-arg-typed.
|
|
291
|
+
*/
|
|
292
|
+
const MSG_VALIDATION_RETRY_PROMPT = (skill: string, errorLines: string) =>
|
|
293
|
+
`The ${skill} artifact's frontmatter doesn't satisfy the expected output schema. ` +
|
|
294
|
+
"Fix only the fields listed below, then re-write the artifact at the same path (don't move it):\n\n" +
|
|
295
|
+
`${errorLines}`;
|
|
296
|
+
|
|
274
297
|
/**
|
|
275
298
|
* Translate a thrown `validateOutputData` (user-authored schemas may throw
|
|
276
299
|
* synchronously or reject their Promise) into the canonical fatal-extraction
|
|
@@ -292,8 +315,7 @@ async function validateOrFatal(
|
|
|
292
315
|
);
|
|
293
316
|
return { kind: "ok", result };
|
|
294
317
|
} catch (e) {
|
|
295
|
-
|
|
296
|
-
return { kind: "fatal", message: `${skill}: ${reason}` };
|
|
318
|
+
return { kind: "fatal", message: `${skill}: ${formatError(e)}` };
|
|
297
319
|
}
|
|
298
320
|
}
|
|
299
321
|
|
package/sessions/index.ts
CHANGED
|
@@ -4,4 +4,6 @@
|
|
|
4
4
|
* barrel re-exports only the symbols the rest of the package consumes.
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
-
export {
|
|
7
|
+
export { locateSessionFile } from "./locate.js";
|
|
8
|
+
export { reattachStageSession } from "./reattach.js";
|
|
9
|
+
export { runStageSession } from "./sessions.js";
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tests for locate.ts — id → on-disk session file with the three-rung
|
|
3
|
+
* fallback (exact hint → filename search → header scan → null). Pure
|
|
4
|
+
* node:fs over temp dirs; no Pi involvement.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
8
|
+
import { tmpdir } from "node:os";
|
|
9
|
+
import { join } from "node:path";
|
|
10
|
+
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
|
11
|
+
import { locateSessionFile } from "./locate.js";
|
|
12
|
+
|
|
13
|
+
describe("locateSessionFile", () => {
|
|
14
|
+
let dir: string;
|
|
15
|
+
|
|
16
|
+
beforeEach(() => {
|
|
17
|
+
dir = mkdtempSync(join(tmpdir(), "rpiv-locate-"));
|
|
18
|
+
});
|
|
19
|
+
afterEach(() => {
|
|
20
|
+
rmSync(dir, { recursive: true, force: true });
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
const sessionHeader = (id: string) =>
|
|
24
|
+
`${JSON.stringify({ type: "session", version: 3, id, timestamp: "2026-06-11T00:00:00Z", cwd: "/x" })}\n`;
|
|
25
|
+
|
|
26
|
+
it("fast path: the recorded file still exists → returned verbatim", () => {
|
|
27
|
+
const file = join(dir, "2026-06-11_sess-1.jsonl");
|
|
28
|
+
writeFileSync(file, sessionHeader("sess-1"));
|
|
29
|
+
expect(locateSessionFile({ id: "sess-1", file })).toBe(file);
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it("stale hint: falls back to `*_<id>.jsonl` search in the hint's dirname", () => {
|
|
33
|
+
const actual = join(dir, "renamed-label_sess-1.jsonl");
|
|
34
|
+
writeFileSync(actual, sessionHeader("sess-1"));
|
|
35
|
+
// The hint points at a file that no longer exists; same directory.
|
|
36
|
+
const stale = join(dir, "old-name_sess-1-gone.jsonl");
|
|
37
|
+
expect(locateSessionFile({ id: "sess-1", file: stale })).toBe(actual);
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
it("filename-convention drift: falls back to the header scan", () => {
|
|
41
|
+
// Filename does NOT embed the id — only the header line carries it.
|
|
42
|
+
const actual = join(dir, "totally-different-name.jsonl");
|
|
43
|
+
writeFileSync(actual, sessionHeader("sess-1"));
|
|
44
|
+
writeFileSync(join(dir, "other.jsonl"), sessionHeader("sess-2"));
|
|
45
|
+
const stale = join(dir, "gone.jsonl");
|
|
46
|
+
expect(locateSessionFile({ id: "sess-1", file: stale })).toBe(actual);
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
it("header scan tolerates corrupt + non-jsonl neighbours", () => {
|
|
50
|
+
writeFileSync(join(dir, "corrupt.jsonl"), "{not json\n");
|
|
51
|
+
writeFileSync(join(dir, "notes.txt"), "irrelevant");
|
|
52
|
+
const actual = join(dir, "real.jsonl");
|
|
53
|
+
writeFileSync(actual, sessionHeader("sess-1"));
|
|
54
|
+
expect(locateSessionFile({ id: "sess-1", file: join(dir, "gone.jsonl") })).toBe(actual);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it("returns null when the id is nowhere to be found (deleted / different machine)", () => {
|
|
58
|
+
writeFileSync(join(dir, "other.jsonl"), sessionHeader("sess-2"));
|
|
59
|
+
expect(locateSessionFile({ id: "sess-1", file: join(dir, "gone.jsonl") })).toBeNull();
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
it("returns null when the hint's directory is gone entirely", () => {
|
|
63
|
+
expect(locateSessionFile({ id: "sess-1", file: join(dir, "nope", "gone.jsonl") })).toBeNull();
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it("returns null without a file hint (in-memory session — nowhere to search)", () => {
|
|
67
|
+
expect(locateSessionFile({ id: "sess-1" })).toBeNull();
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
it("never returns a directory — only regular files survive every rung", () => {
|
|
71
|
+
const asDir = join(dir, "weird_sess-1.jsonl");
|
|
72
|
+
mkdirSync(asDir);
|
|
73
|
+
const actual = join(dir, "real_sess-1.jsonl");
|
|
74
|
+
writeFileSync(actual, sessionHeader("sess-1"));
|
|
75
|
+
expect(locateSessionFile({ id: "sess-1", file: asDir })).toBe(actual);
|
|
76
|
+
});
|
|
77
|
+
});
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session-file location for session-backed resume. `SessionRef.file` is a
|
|
3
|
+
* HINT captured at activation time — sessions move (Pi renames on label
|
|
4
|
+
* change), get cleaned up, or live on another machine. `locateSessionFile`
|
|
5
|
+
* resolves id → on-disk path with a three-rung fallback; `null` means
|
|
6
|
+
* "fall back to cold re-run" (the caller's ladder notifies).
|
|
7
|
+
*
|
|
8
|
+
* `node:fs` only — no Pi import; unit-testable with temp dirs. Fail-soft
|
|
9
|
+
* throughout: any fs error degrades to the next rung, never throws.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { closeSync, existsSync, openSync, readdirSync, readSync, statSync } from "node:fs";
|
|
13
|
+
import { dirname, join } from "node:path";
|
|
14
|
+
import type { SessionRef } from "../state/index.js";
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* id → on-disk session file. Fail-soft: `null` means "fall back to cold
|
|
18
|
+
* re-run".
|
|
19
|
+
*
|
|
20
|
+
* 1. `ref.file` exists on disk → use it (fast path).
|
|
21
|
+
* 2. Else search `dirname(ref.file)` for `*_<id>.jsonl` (Pi's filename
|
|
22
|
+
* convention embeds the session id).
|
|
23
|
+
* 3. Else scan each `.jsonl` header line in that dir for `id === ref.id`
|
|
24
|
+
* (robust against filename-convention drift).
|
|
25
|
+
* 4. Else `null`.
|
|
26
|
+
*
|
|
27
|
+
* No `file` hint at all (in-memory session) → `null` immediately: without
|
|
28
|
+
* the hint there is no directory to search.
|
|
29
|
+
*/
|
|
30
|
+
export function locateSessionFile(ref: SessionRef): string | null {
|
|
31
|
+
if (!ref.file) return null;
|
|
32
|
+
try {
|
|
33
|
+
if (existsSync(ref.file) && statSync(ref.file).isFile()) return ref.file;
|
|
34
|
+
} catch {
|
|
35
|
+
// fall through to the directory rungs
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const dir = dirname(ref.file);
|
|
39
|
+
let entries: string[];
|
|
40
|
+
try {
|
|
41
|
+
entries = readdirSync(dir);
|
|
42
|
+
} catch {
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// Rung 2: Pi's filename embeds the id (`<timestamp>_<id>.jsonl`).
|
|
47
|
+
for (const entry of entries) {
|
|
48
|
+
if (!entry.endsWith(`_${ref.id}.jsonl`)) continue;
|
|
49
|
+
const path = join(dir, entry);
|
|
50
|
+
if (isFile(path)) return path;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Rung 3: header scan — first JSONL line carries the session `id`.
|
|
54
|
+
for (const entry of entries) {
|
|
55
|
+
if (!entry.endsWith(".jsonl")) continue;
|
|
56
|
+
const path = join(dir, entry);
|
|
57
|
+
if (isFile(path) && headerIdOf(path) === ref.id) return path;
|
|
58
|
+
}
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function isFile(path: string): boolean {
|
|
63
|
+
try {
|
|
64
|
+
return statSync(path).isFile();
|
|
65
|
+
} catch {
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Bounded prefix read — session files run to tens of MB; the header is line one. */
|
|
71
|
+
const HEADER_PREFIX_BYTES = 8192;
|
|
72
|
+
|
|
73
|
+
/** First-line `id` of a Pi session file, or undefined on any read/parse miss. */
|
|
74
|
+
function headerIdOf(path: string): string | undefined {
|
|
75
|
+
let fd: number | undefined;
|
|
76
|
+
try {
|
|
77
|
+
fd = openSync(path, "r");
|
|
78
|
+
const buf = Buffer.alloc(HEADER_PREFIX_BYTES);
|
|
79
|
+
const bytes = readSync(fd, buf, 0, HEADER_PREFIX_BYTES, 0);
|
|
80
|
+
const firstLine = buf.toString("utf-8", 0, bytes).split("\n", 1)[0];
|
|
81
|
+
if (!firstLine) return undefined;
|
|
82
|
+
const parsed: unknown = JSON.parse(firstLine);
|
|
83
|
+
const id = (parsed as { id?: unknown } | null)?.id;
|
|
84
|
+
return typeof id === "string" ? id : undefined;
|
|
85
|
+
} catch {
|
|
86
|
+
return undefined;
|
|
87
|
+
} finally {
|
|
88
|
+
if (fd !== undefined) closeSync(fd);
|
|
89
|
+
}
|
|
90
|
+
}
|