@juicesharp/rpiv-workflow 1.17.0 → 1.18.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 +56 -15
- package/api.ts +1 -1
- package/audit.ts +42 -7
- package/built-ins.ts +46 -2
- package/command-run.ts +132 -0
- package/command.ts +29 -100
- package/docs/workflow-authoring.md +23 -23
- package/extension.ts +18 -0
- package/fanout.ts +11 -5
- package/host.ts +26 -13
- package/index.ts +40 -134
- package/internal-utils.ts +35 -0
- package/internal.ts +1 -1
- package/iterate.ts +20 -8
- package/lifecycle.ts +1 -1
- package/load/index.ts +5 -1
- package/messages.ts +34 -0
- package/package.json +9 -3
- package/registration.ts +113 -0
- package/runner/by-name.test.ts +95 -0
- package/runner/by-name.ts +76 -0
- package/runner/by-run-id.test.ts +115 -0
- package/runner/by-run-id.ts +92 -0
- package/runner/chain-advance.ts +22 -42
- package/runner/index.ts +10 -1
- package/runner/resume-fanout.test.ts +331 -0
- package/runner/resume-fanout.ts +136 -0
- package/runner/resume-iterate.test.ts +444 -0
- package/runner/resume-iterate.ts +110 -0
- package/runner/resume.test.ts +1130 -0
- package/runner/resume.ts +333 -0
- package/runner/runner.ts +281 -91
- package/runner/script-stage.ts +18 -51
- package/runner/stage-lifecycle.ts +35 -27
- package/sessions/extraction.ts +4 -4
- package/sessions/sessions.ts +22 -40
- package/sessions/spawn.ts +15 -11
- package/startup.ts +9 -0
- package/state/index.ts +1 -0
- package/state/reads.ts +20 -0
- package/state/state.ts +1 -0
- package/types.ts +18 -13
package/runner/runner.ts
CHANGED
|
@@ -5,12 +5,15 @@
|
|
|
5
5
|
* directory owns graph traversal, per-stage prerequisites, and routing.
|
|
6
6
|
*
|
|
7
7
|
* Modules:
|
|
8
|
-
* - runner.ts — runWorkflow +
|
|
8
|
+
* - runner.ts — runWorkflow + resumeWorkflow + executeRun (shared
|
|
9
|
+
* tail) + countReachableStages +
|
|
9
10
|
* runStageOrRecordFailure + finalizeWorkflow.
|
|
10
11
|
* - stage-lifecycle.ts — runStage + StagePreflightError + preflight
|
|
11
12
|
* pipeline + outcome.collector.snapshot hook.
|
|
12
13
|
* - chain-advance.ts — advanceChain + routing audit + backward-jump
|
|
13
14
|
* guard + halt-on-error.
|
|
15
|
+
* - resume.ts — reconstructState: pure RunState rebuild from a
|
|
16
|
+
* past run's JSONL trail (consumed by resumeWorkflow).
|
|
14
17
|
*
|
|
15
18
|
* Ctx lifecycle: every level only touches the ctx it was handed.
|
|
16
19
|
* - `newSession({cancelled: false})` invalidates the outer ctx; all
|
|
@@ -25,16 +28,38 @@
|
|
|
25
28
|
*/
|
|
26
29
|
|
|
27
30
|
import type { Workflow } from "../api.js";
|
|
28
|
-
import { notifyPartialArtifacts, nowIso, recordTerminalFailure } from "../audit.js";
|
|
31
|
+
import { auditCtxFor, notifyPartialArtifacts, nowIso, recordTerminalFailure } from "../audit.js";
|
|
32
|
+
import type { FanoutDeps } from "../fanout.js";
|
|
29
33
|
import { handleToString } from "../handle.js";
|
|
30
|
-
import type {
|
|
34
|
+
import type { WorkflowHost, WorkflowHostContext } from "../host.js";
|
|
31
35
|
import { currentPrimaryArtifact } from "../internal-utils.js";
|
|
36
|
+
import type { IterateDeps } from "../iterate.js";
|
|
32
37
|
import { buildLifecycleContext, LifecycleDispatcher, type LifecycleListeners } from "../lifecycle.js";
|
|
33
|
-
import {
|
|
38
|
+
import {
|
|
39
|
+
ERR_RESUME_NO_ROWS,
|
|
40
|
+
ERR_RESUME_STAGE_GONE,
|
|
41
|
+
ERR_WORKFLOW_ABORTED,
|
|
42
|
+
MSG_STAGE_THREW,
|
|
43
|
+
MSG_WORKFLOW_ABORTED,
|
|
44
|
+
MSG_WORKFLOW_COMPLETE,
|
|
45
|
+
STATUS_KEY,
|
|
46
|
+
} from "../messages.js";
|
|
47
|
+
import { runFanoutSession, runStageSession } from "../sessions/index.js";
|
|
34
48
|
import { generateRunId, writeHeader } from "../state/index.js";
|
|
49
|
+
import type { WorkflowHeader } from "../state/state.js";
|
|
35
50
|
import { DEFAULT_TRIGGER, type RunTrigger } from "../triggers.js";
|
|
36
|
-
import type { RunContext,
|
|
37
|
-
import {
|
|
51
|
+
import type { RunContext, RunState } from "../types.js";
|
|
52
|
+
import { advanceChain } from "./chain-advance.js";
|
|
53
|
+
import {
|
|
54
|
+
fanoutStageNames,
|
|
55
|
+
iterateStageNames,
|
|
56
|
+
matchFanoutParent,
|
|
57
|
+
type ReconstructResult,
|
|
58
|
+
reconstructState,
|
|
59
|
+
} from "./resume.js";
|
|
60
|
+
import { resumeFanoutStage } from "./resume-fanout.js";
|
|
61
|
+
import { resumeIterateStage } from "./resume-iterate.js";
|
|
62
|
+
import { captureStageSnapshot, haltIterations, runStage, StagePreflightError } from "./stage-lifecycle.js";
|
|
38
63
|
|
|
39
64
|
// ---------------------------------------------------------------------------
|
|
40
65
|
// Policy constants
|
|
@@ -88,6 +113,15 @@ export interface RunWorkflowOptions {
|
|
|
88
113
|
* run.
|
|
89
114
|
*/
|
|
90
115
|
lifecycle?: LifecycleListeners;
|
|
116
|
+
/**
|
|
117
|
+
* Cooperative cancellation. When the signal is aborted, the runner stops at
|
|
118
|
+
* the next between-stage seam — it records an `"aborted"` terminal row for
|
|
119
|
+
* the stage about to run and returns `{ success: false }` with an aborted
|
|
120
|
+
* error. It does NOT interrupt a stage already streaming (Pi owns the live
|
|
121
|
+
* session), so cancellation takes effect at the next stage boundary, not
|
|
122
|
+
* mid-stage.
|
|
123
|
+
*/
|
|
124
|
+
signal?: AbortSignal;
|
|
91
125
|
}
|
|
92
126
|
|
|
93
127
|
export interface RunWorkflowResult {
|
|
@@ -123,6 +157,44 @@ export interface RunWorkflowResult {
|
|
|
123
157
|
droppedRoutingRows?: Array<{ fromStageIndex: number; fromStage: string; decision: string }>;
|
|
124
158
|
}
|
|
125
159
|
|
|
160
|
+
// ---------------------------------------------------------------------------
|
|
161
|
+
// Shared tail — executeRun
|
|
162
|
+
// ---------------------------------------------------------------------------
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Shared tail: fire `onWorkflowStart`, kick the chain via `entry`,
|
|
166
|
+
* assemble the result envelope, fire `onWorkflowEnd`. Used by both
|
|
167
|
+
* `runWorkflow` (new runs) and `resumeWorkflow` (resumed runs) so
|
|
168
|
+
* lifecycle events, result assembly, and error propagation stay in lockstep.
|
|
169
|
+
*/
|
|
170
|
+
async function executeRun(
|
|
171
|
+
ctx: WorkflowHostContext,
|
|
172
|
+
run: RunContext,
|
|
173
|
+
entry: () => Promise<void>,
|
|
174
|
+
): Promise<RunWorkflowResult> {
|
|
175
|
+
await run.lifecycle.fire(ctx, "onWorkflowStart", lifecycleCtxFor(run));
|
|
176
|
+
|
|
177
|
+
await entry();
|
|
178
|
+
|
|
179
|
+
const { state } = run;
|
|
180
|
+
const result: RunWorkflowResult = {
|
|
181
|
+
runId: run.runId,
|
|
182
|
+
stagesCompleted: state.stagesCompleted,
|
|
183
|
+
success: state.termination.success,
|
|
184
|
+
lastArtifact: (() => {
|
|
185
|
+
const a = currentPrimaryArtifact(state);
|
|
186
|
+
return a ? handleToString(a.handle) : undefined;
|
|
187
|
+
})(),
|
|
188
|
+
error: state.termination.error,
|
|
189
|
+
...(state.telemetry.droppedRoutingRows.length > 0
|
|
190
|
+
? { droppedRoutingRows: state.telemetry.droppedRoutingRows }
|
|
191
|
+
: {}),
|
|
192
|
+
};
|
|
193
|
+
|
|
194
|
+
await run.lifecycle.fire(ctx, "onWorkflowEnd", result, lifecycleCtxFor(run));
|
|
195
|
+
return result;
|
|
196
|
+
}
|
|
197
|
+
|
|
126
198
|
// ---------------------------------------------------------------------------
|
|
127
199
|
// runWorkflow — workflow entry point
|
|
128
200
|
// ---------------------------------------------------------------------------
|
|
@@ -132,7 +204,7 @@ export interface RunWorkflowResult {
|
|
|
132
204
|
* previous withSession — never on a captured outer ctx (which Pi invalidates
|
|
133
205
|
* as soon as the session is replaced).
|
|
134
206
|
*/
|
|
135
|
-
export async function runWorkflow(ctx:
|
|
207
|
+
export async function runWorkflow(ctx: WorkflowHostContext, options: RunWorkflowOptions): Promise<RunWorkflowResult> {
|
|
136
208
|
const { workflow } = options;
|
|
137
209
|
if (!workflow.stages[workflow.start]) {
|
|
138
210
|
return {
|
|
@@ -142,99 +214,217 @@ export async function runWorkflow(ctx: WorkflowContext, options: RunWorkflowOpti
|
|
|
142
214
|
};
|
|
143
215
|
}
|
|
144
216
|
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
// throw at the first such stage.
|
|
148
|
-
// Reject at workflow entry so embedders get a clean envelope instead of a throw.
|
|
149
|
-
if (options.host === undefined && Object.values(workflow.stages).some((s) => s.sessionPolicy === "continue")) {
|
|
150
|
-
return {
|
|
151
|
-
stagesCompleted: 0,
|
|
152
|
-
success: false,
|
|
153
|
-
error: "workflow contains continue-policy stages which require a workflow host",
|
|
154
|
-
};
|
|
155
|
-
}
|
|
217
|
+
const continueGuard = hostMissingForContinueStages(workflow, options.host);
|
|
218
|
+
if (continueGuard) return { stagesCompleted: 0, success: false, error: continueGuard };
|
|
156
219
|
|
|
157
220
|
const cwd = ctx.cwd;
|
|
158
221
|
const runId = generateRunId();
|
|
159
|
-
const totalStages = countReachableStages(workflow);
|
|
160
222
|
const trigger = options.trigger ?? DEFAULT_TRIGGER;
|
|
161
223
|
|
|
162
|
-
writeHeader(cwd, {
|
|
224
|
+
writeHeader(cwd, { runId, workflow: workflow.name, input: options.input, ts: nowIso(), trigger });
|
|
225
|
+
|
|
226
|
+
const run = buildRunContext(cwd, workflow, options, {
|
|
163
227
|
runId,
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
ts: nowIso(),
|
|
228
|
+
state: freshRunState(options.input),
|
|
229
|
+
visited: new Set(),
|
|
167
230
|
trigger,
|
|
168
231
|
});
|
|
169
232
|
|
|
170
|
-
|
|
171
|
-
|
|
233
|
+
return executeRun(ctx, run, () => runStageOrRecordFailure(ctx, workflow.start, 0, run));
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
export interface ResumeWorkflowOptions {
|
|
237
|
+
/** Workflow whose run is being resumed — caller resolves by name from `LoadedWorkflows`. */
|
|
238
|
+
workflow: Workflow;
|
|
239
|
+
/** Header of the run to resume — caller resolves via `resolveRun`. */
|
|
240
|
+
header: WorkflowHeader;
|
|
241
|
+
/** Required for "continue"-policy stages (host.sendUserMessage). */
|
|
242
|
+
host?: WorkflowHost;
|
|
243
|
+
/** Defaults to MAX_BACKWARD_JUMPS. */
|
|
244
|
+
maxBackwardJumps?: number;
|
|
245
|
+
/** Run-wide safety cap on iterate-stage units. Defaults to MAX_ITERATIONS. */
|
|
246
|
+
maxIterations?: number;
|
|
247
|
+
/** The user's `@<ref>` — surfaced in trigger.meta + refusal messages. */
|
|
248
|
+
ref: string;
|
|
249
|
+
/** Per-call lifecycle listener bundle. */
|
|
250
|
+
lifecycle?: LifecycleListeners;
|
|
251
|
+
/** Cooperative cancellation — see `RunWorkflowOptions.signal`. */
|
|
252
|
+
signal?: AbortSignal;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* Resume a failed (or cut-off) workflow run by rebuilding `RunState` from
|
|
257
|
+
* the run's JSONL audit trail and re-entering the chain machinery at the
|
|
258
|
+
* right seam — re-running the failed stage, or routing onward from the
|
|
259
|
+
* last completed one.
|
|
260
|
+
*
|
|
261
|
+
* New rows **append to the same JSONL file** so the trail reads as one
|
|
262
|
+
* story: *ran → failed → resumed → continued*.
|
|
263
|
+
*/
|
|
264
|
+
export async function resumeWorkflow(
|
|
265
|
+
ctx: WorkflowHostContext,
|
|
266
|
+
options: ResumeWorkflowOptions,
|
|
267
|
+
): Promise<RunWorkflowResult> {
|
|
268
|
+
const { workflow, header } = options;
|
|
269
|
+
const cwd = ctx.cwd;
|
|
270
|
+
|
|
271
|
+
const recon = reconstructState(cwd, workflow, header);
|
|
272
|
+
if (!recon.ok) {
|
|
273
|
+
// Pure envelope — no self-notify, mirroring `runWorkflow`'s pre-flight
|
|
274
|
+
// rejections. A reconstruct refusal writes no JSONL, so the caller surfaces
|
|
275
|
+
// it: `command.ts` via the `!result.runId` discriminator, programmatic
|
|
276
|
+
// embedders via `if (!result.success)`. Keeps the run and resume families
|
|
277
|
+
// on one notify contract.
|
|
278
|
+
return { stagesCompleted: 0, success: false, error: resumeRefusalError(recon, header.workflow) };
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
const continueGuard = hostMissingForContinueStages(workflow, options.host);
|
|
282
|
+
if (continueGuard) return { stagesCompleted: 0, success: false, error: continueGuard };
|
|
283
|
+
|
|
284
|
+
const run = buildRunContext(cwd, workflow, options, {
|
|
285
|
+
runId: header.runId, // SAME run — new rows append to the same file
|
|
286
|
+
state: recon.state,
|
|
287
|
+
visited: recon.visited,
|
|
288
|
+
trigger: { kind: "command", name: "wf", meta: { resumedFrom: options.ref } },
|
|
289
|
+
});
|
|
290
|
+
|
|
291
|
+
return executeRun(ctx, run, selectResumeEntry(ctx, workflow, recon, run));
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
// ---------------------------------------------------------------------------
|
|
295
|
+
// Run-construction helpers (shared by runWorkflow + resumeWorkflow)
|
|
296
|
+
// ---------------------------------------------------------------------------
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* Continue-policy stages thread the prior session via the host's
|
|
300
|
+
* `sendUserMessage`; with no host, `enforceSessionInvariants` would throw at
|
|
301
|
+
* the first such stage. Reject at workflow entry so embedders get a clean
|
|
302
|
+
* envelope instead of a throw. Returns the error message, or undefined if the
|
|
303
|
+
* workflow is safe to run.
|
|
304
|
+
*/
|
|
305
|
+
function hostMissingForContinueStages(workflow: Workflow, host: WorkflowHost | undefined): string | undefined {
|
|
306
|
+
if (host !== undefined) return undefined;
|
|
307
|
+
if (!Object.values(workflow.stages).some((s) => s.sessionPolicy === "continue")) return undefined;
|
|
308
|
+
return "workflow contains continue-policy stages which require a workflow host";
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** A pristine `RunState` for a brand-new run (resumes rebuild theirs via `reconstructState`). */
|
|
312
|
+
function freshRunState(originalInput: string): RunState {
|
|
313
|
+
return {
|
|
314
|
+
originalInput,
|
|
172
315
|
primaryArtifact: undefined,
|
|
173
316
|
output: undefined,
|
|
174
317
|
named: {},
|
|
175
318
|
stagesCompleted: 0,
|
|
176
319
|
lastAllocatedStageNumber: 0,
|
|
177
|
-
telemetry: {
|
|
178
|
-
|
|
179
|
-
droppedRoutingRows: [],
|
|
180
|
-
},
|
|
181
|
-
termination: {
|
|
182
|
-
success: false,
|
|
183
|
-
error: undefined,
|
|
184
|
-
},
|
|
320
|
+
telemetry: { backwardJumps: 0, droppedRoutingRows: [] },
|
|
321
|
+
termination: { success: false, error: undefined },
|
|
185
322
|
};
|
|
323
|
+
}
|
|
186
324
|
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
325
|
+
/**
|
|
326
|
+
* Assemble the `RunContext` shared by both entry points. `identity` carries the
|
|
327
|
+
* four fields that differ between a new run (fresh id/state/visited, caller
|
|
328
|
+
* trigger) and a resume (same run id, reconstructed state/visited, resume
|
|
329
|
+
* trigger); everything else derives identically from `options`.
|
|
330
|
+
*
|
|
331
|
+
* The skill-registry snapshot happens here, BEFORE any stage opens a fresh
|
|
332
|
+
* session — Pi invalidates the `WorkflowHost` handle on the first
|
|
333
|
+
* `ctx.newSession()`, so this is the only safe moment to enumerate. After this
|
|
334
|
+
* the runner reads `run.registeredSkills`; `options.host` survives only on
|
|
335
|
+
* `run.continueHost` for the continue-policy session handler.
|
|
336
|
+
*/
|
|
337
|
+
function buildRunContext(
|
|
338
|
+
cwd: string,
|
|
339
|
+
workflow: Workflow,
|
|
340
|
+
options: {
|
|
341
|
+
host?: WorkflowHost;
|
|
342
|
+
maxBackwardJumps?: number;
|
|
343
|
+
maxIterations?: number;
|
|
344
|
+
lifecycle?: LifecycleListeners;
|
|
345
|
+
signal?: AbortSignal;
|
|
346
|
+
},
|
|
347
|
+
identity: { runId: string; state: RunState; visited: Set<string>; trigger: RunTrigger },
|
|
348
|
+
): RunContext {
|
|
349
|
+
return {
|
|
199
350
|
cwd,
|
|
200
|
-
runId,
|
|
351
|
+
runId: identity.runId,
|
|
201
352
|
workflow,
|
|
202
|
-
totalStages,
|
|
203
|
-
state,
|
|
204
|
-
visited:
|
|
205
|
-
registeredSkills,
|
|
353
|
+
totalStages: countReachableStages(workflow),
|
|
354
|
+
state: identity.state,
|
|
355
|
+
visited: identity.visited,
|
|
356
|
+
registeredSkills: options.host ? snapshotRegisteredSkills(options.host) : undefined,
|
|
206
357
|
continueHost: options.host,
|
|
207
|
-
maxBackwardJumps,
|
|
208
|
-
maxIterations,
|
|
209
|
-
trigger,
|
|
210
|
-
lifecycle,
|
|
358
|
+
maxBackwardJumps: options.maxBackwardJumps ?? MAX_BACKWARD_JUMPS,
|
|
359
|
+
maxIterations: options.maxIterations ?? MAX_ITERATIONS,
|
|
360
|
+
trigger: identity.trigger,
|
|
361
|
+
lifecycle: new LifecycleDispatcher(options.lifecycle),
|
|
362
|
+
signal: options.signal,
|
|
211
363
|
};
|
|
364
|
+
}
|
|
212
365
|
|
|
213
|
-
|
|
366
|
+
/**
|
|
367
|
+
* Pick the chain re-entry thunk for a resumed run from its trail trailer:
|
|
368
|
+
* - decorated fanout-unit trailer → resume the fanout from the next unit
|
|
369
|
+
* (`resumeFanoutStage`);
|
|
370
|
+
* - decorated iterate-unit trailer → re-enter the pull loop at the next unit
|
|
371
|
+
* (`resumeIterateStage`) — catches BOTH a completed and a failed iterate-unit
|
|
372
|
+
* trailer, since a completed unit may still have remaining units to pull;
|
|
373
|
+
* - completed normal trailer → route onward (a finished run hits stop ⇒ no-op);
|
|
374
|
+
* - failed/aborted trailer → re-run that stage.
|
|
375
|
+
*
|
|
376
|
+
* A decorated unit row has a `stage` key absent from `workflow.stages` matching a
|
|
377
|
+
* fanout/iterate parent — meaning the run died inside that stage. The
|
|
378
|
+
* `workflow.stages[last.stage] === undefined` outer guard keeps normal trailers on
|
|
379
|
+
* the binary arms; a normal trailer after a fully-completed fanout/iterate falls
|
|
380
|
+
* through to them.
|
|
381
|
+
*/
|
|
382
|
+
function selectResumeEntry(
|
|
383
|
+
ctx: WorkflowHostContext,
|
|
384
|
+
workflow: Workflow,
|
|
385
|
+
recon: Extract<ReconstructResult, { ok: true }>,
|
|
386
|
+
run: RunContext,
|
|
387
|
+
): () => Promise<void> {
|
|
388
|
+
const last = recon.rows[recon.rows.length - 1]!;
|
|
389
|
+
const idx = last.stageNumber - 1; // status-line / routing index; JSONL number comes from the allocator
|
|
214
390
|
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
391
|
+
if (workflow.stages[last.stage] === undefined) {
|
|
392
|
+
const fanoutParent = matchFanoutParent(last.stage, fanoutStageNames(workflow));
|
|
393
|
+
if (fanoutParent) {
|
|
394
|
+
const fanoutDeps: FanoutDeps = {
|
|
395
|
+
runFanoutSession,
|
|
396
|
+
advanceAfter: (freshCtx, name, completedIdx, r) => advanceChain(freshCtx, name, completedIdx, r),
|
|
397
|
+
};
|
|
398
|
+
const completed = recon.fanoutProgress.get(fanoutParent) ?? [];
|
|
399
|
+
return () => resumeFanoutStage(ctx, fanoutParent, idx, completed, run, fanoutDeps);
|
|
400
|
+
}
|
|
401
|
+
const iterateParent = matchFanoutParent(last.stage, iterateStageNames(workflow));
|
|
402
|
+
if (iterateParent) {
|
|
403
|
+
const iterateDeps: IterateDeps = {
|
|
404
|
+
runStageSession,
|
|
405
|
+
advanceAfter: (freshCtx, name, completedIdx, r) => advanceChain(freshCtx, name, completedIdx, r),
|
|
406
|
+
captureSnapshot: (d, i, r) => captureStageSnapshot(d, i, r),
|
|
407
|
+
haltIterations,
|
|
408
|
+
};
|
|
409
|
+
const point = recon.iterateProgress.get(iterateParent) ?? { entryArtifact: undefined, accumulated: [] };
|
|
410
|
+
const pendingDecorated = last.status !== "completed" ? last.stage : undefined;
|
|
411
|
+
return () => resumeIterateStage(ctx, iterateParent, idx, point, pendingDecorated, run, iterateDeps);
|
|
412
|
+
}
|
|
413
|
+
}
|
|
221
414
|
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
const a = currentPrimaryArtifact(state);
|
|
228
|
-
return a ? handleToString(a.handle) : undefined;
|
|
229
|
-
})(),
|
|
230
|
-
error: state.termination.error,
|
|
231
|
-
...(state.telemetry.droppedRoutingRows.length > 0
|
|
232
|
-
? { droppedRoutingRows: state.telemetry.droppedRoutingRows }
|
|
233
|
-
: {}),
|
|
234
|
-
};
|
|
415
|
+
if (last.status === "completed") {
|
|
416
|
+
return () => advanceChain(ctx, last.stage, idx, run); // route onward; finished run ⇒ hits stop ⇒ no-op
|
|
417
|
+
}
|
|
418
|
+
return () => runStageOrRecordFailure(ctx, last.stage, idx, run); // re-run the failed/aborted stage
|
|
419
|
+
}
|
|
235
420
|
|
|
236
|
-
|
|
237
|
-
|
|
421
|
+
function resumeRefusalError(recon: Extract<ReconstructResult, { ok: false }>, workflow: string): string {
|
|
422
|
+
switch (recon.reason) {
|
|
423
|
+
case "no-rows":
|
|
424
|
+
return ERR_RESUME_NO_ROWS(recon.detail);
|
|
425
|
+
case "stage-gone":
|
|
426
|
+
return ERR_RESUME_STAGE_GONE(recon.detail, workflow);
|
|
427
|
+
}
|
|
238
428
|
}
|
|
239
429
|
|
|
240
430
|
/** Build a `LifecycleContext` from the current `RunContext`. Captured per fire so listeners always see the latest `state` snapshot. */
|
|
@@ -300,11 +490,24 @@ function countReachableStages(workflow: Workflow): number {
|
|
|
300
490
|
* generic `MSG_STAGE_THREW` shape attributed to the stage id.
|
|
301
491
|
*/
|
|
302
492
|
export async function runStageOrRecordFailure(
|
|
303
|
-
curCtx:
|
|
493
|
+
curCtx: WorkflowHostContext,
|
|
304
494
|
name: string,
|
|
305
495
|
idx: number,
|
|
306
496
|
run: RunContext,
|
|
307
497
|
): Promise<void> {
|
|
498
|
+
// Cooperative cancellation seam. Checked before the start stage and before
|
|
499
|
+
// every routed next stage (advanceChain funnels through here), so an aborted
|
|
500
|
+
// signal stops the chain at the next stage boundary without interrupting a
|
|
501
|
+
// stage already streaming. Records an "aborted" terminal row + halts.
|
|
502
|
+
if (run.signal?.aborted) {
|
|
503
|
+
await recordTerminalFailure(curCtx, auditCtxFor(run, name, name), {
|
|
504
|
+
status: "aborted",
|
|
505
|
+
notifyMsg: MSG_WORKFLOW_ABORTED,
|
|
506
|
+
notifyLevel: "warning",
|
|
507
|
+
errMsg: ERR_WORKFLOW_ABORTED(name),
|
|
508
|
+
});
|
|
509
|
+
return;
|
|
510
|
+
}
|
|
308
511
|
try {
|
|
309
512
|
await runStage(curCtx, name, idx, run);
|
|
310
513
|
} catch (e) {
|
|
@@ -327,20 +530,7 @@ export async function runStageOrRecordFailure(
|
|
|
327
530
|
}
|
|
328
531
|
}
|
|
329
532
|
|
|
330
|
-
|
|
331
|
-
function auditCtxFor(run: RunContext, stageName: string, skill: string) {
|
|
332
|
-
return {
|
|
333
|
-
cwd: run.cwd,
|
|
334
|
-
runId: run.runId,
|
|
335
|
-
state: run.state,
|
|
336
|
-
stageName,
|
|
337
|
-
skill,
|
|
338
|
-
lifecycle: run.lifecycle,
|
|
339
|
-
runIdentity: { workflow: run.workflow.name, totalStages: run.totalStages, trigger: run.trigger },
|
|
340
|
-
};
|
|
341
|
-
}
|
|
342
|
-
|
|
343
|
-
export function finalizeWorkflow(curCtx: RunnerCtx, run: RunContext): void {
|
|
533
|
+
export function finalizeWorkflow(curCtx: WorkflowHostContext, run: RunContext): void {
|
|
344
534
|
curCtx.ui.setStatus(STATUS_KEY, undefined);
|
|
345
535
|
curCtx.ui.notify(MSG_WORKFLOW_COMPLETE(run.state.stagesCompleted), "info");
|
|
346
536
|
run.state.termination.success = true;
|
package/runner/script-stage.ts
CHANGED
|
@@ -27,10 +27,10 @@
|
|
|
27
27
|
* - `stage.sessionPolicy !== "continue"` (no session to continue).
|
|
28
28
|
*/
|
|
29
29
|
|
|
30
|
-
import type { ScriptContext
|
|
31
|
-
import { nowIso, recordStage, recordTerminalFailure } from "../audit.js";
|
|
30
|
+
import type { ScriptContext } from "../api.js";
|
|
31
|
+
import { auditCtxFor, nowIso, recordStage, recordTerminalFailure } from "../audit.js";
|
|
32
32
|
import type { Artifact } from "./../handle.js";
|
|
33
|
-
import {
|
|
33
|
+
import { applyCompletedStage } from "../internal-utils.js";
|
|
34
34
|
import { scriptStageRef } from "../lifecycle.js";
|
|
35
35
|
import {
|
|
36
36
|
ERR_AUDIT_WRITE_FAILED,
|
|
@@ -44,7 +44,7 @@ import {
|
|
|
44
44
|
STATUS_STAGE,
|
|
45
45
|
} from "../messages.js";
|
|
46
46
|
import { finalizeOutput, type Output } from "../output.js";
|
|
47
|
-
import type { RunContext,
|
|
47
|
+
import type { RunContext, RunState, WorkflowHostContext } from "../types.js";
|
|
48
48
|
import { DEFAULT_VALIDATION_RETRIES, validateOutputData } from "../validate-output.js";
|
|
49
49
|
import { advanceChain } from "./chain-advance.js";
|
|
50
50
|
import { lifecycleCtxFor } from "./runner.js";
|
|
@@ -60,7 +60,12 @@ import type { ResolvedStage } from "./stage-lifecycle.js";
|
|
|
60
60
|
* - `ensureInputValid` already passed (post-prompt-checks pipeline).
|
|
61
61
|
* - `tryFanout` returned `false` (fanout incompatible by validation).
|
|
62
62
|
*/
|
|
63
|
-
export async function runScript(
|
|
63
|
+
export async function runScript(
|
|
64
|
+
curCtx: WorkflowHostContext,
|
|
65
|
+
stage: ResolvedStage,
|
|
66
|
+
idx: number,
|
|
67
|
+
run: RunContext,
|
|
68
|
+
): Promise<void> {
|
|
64
69
|
curCtx.ui.setStatus(STATUS_KEY, STATUS_STAGE(stage.stageNumber, run.totalStages, stage.name));
|
|
65
70
|
|
|
66
71
|
const ref = scriptStageRef(stage.name, stage.stageNumber);
|
|
@@ -124,7 +129,7 @@ type ScriptInvocationResult =
|
|
|
124
129
|
* failure attributed via `MSG_SCRIPT_THREW` + `ERR_SCRIPT_THREW`.
|
|
125
130
|
*/
|
|
126
131
|
async function invokeRun(
|
|
127
|
-
curCtx:
|
|
132
|
+
curCtx: WorkflowHostContext,
|
|
128
133
|
stage: ResolvedStage,
|
|
129
134
|
scriptCtx: ScriptContext,
|
|
130
135
|
ref: ReturnType<typeof scriptStageRef>,
|
|
@@ -160,7 +165,7 @@ async function invokeRun(
|
|
|
160
165
|
* no `onStageEnd` fire — caller owns lifecycle ordering here).
|
|
161
166
|
*/
|
|
162
167
|
function recordScriptSuccess(
|
|
163
|
-
curCtx:
|
|
168
|
+
curCtx: WorkflowHostContext,
|
|
164
169
|
stage: ResolvedStage,
|
|
165
170
|
output: Output,
|
|
166
171
|
state: RunState,
|
|
@@ -180,42 +185,13 @@ function recordScriptSuccess(
|
|
|
180
185
|
state.termination.error = ERR_AUDIT_WRITE_FAILED(stage.name);
|
|
181
186
|
return false;
|
|
182
187
|
}
|
|
183
|
-
|
|
188
|
+
applyCompletedStage(state, stage.def, stage.name, output);
|
|
184
189
|
state.output = output;
|
|
185
190
|
state.stagesCompleted++;
|
|
186
191
|
curCtx.ui.notify(MSG_STAGE_COMPLETE(stage.name), "info");
|
|
187
192
|
return true;
|
|
188
193
|
}
|
|
189
194
|
|
|
190
|
-
/**
|
|
191
|
-
* Mirror of `sessions/sessions.ts:maybeAdvancePrimary` for the script
|
|
192
|
-
* path. Kept local instead of extracted to a shared helper: the rule
|
|
193
|
-
* is small (eight lines), and the two call sites live in different
|
|
194
|
-
* folders (`runner/` vs `sessions/`) — extracting would force a
|
|
195
|
-
* runner-imports-sessions or sessions-imports-runner crossing for one
|
|
196
|
-
* predicate.
|
|
197
|
-
*
|
|
198
|
-
* - `kind: "produces"` → first artifact wins the rolling slot.
|
|
199
|
-
* - `inheritsArtifacts: false` (`terminal.script`) → clear the slot
|
|
200
|
-
* so downstream stages start without an inherited handle.
|
|
201
|
-
* - other `side-effect` → leave the slot untouched (a downstream
|
|
202
|
-
* stage still inherits whatever the upstream produces stage set).
|
|
203
|
-
*/
|
|
204
|
-
function advancePrimaryForScript(state: RunState, def: StageDef, stageName: string, output: Output): void {
|
|
205
|
-
if (def.kind === "produces") {
|
|
206
|
-
const next = output.artifacts[0];
|
|
207
|
-
if (next) state.primaryArtifact = next;
|
|
208
|
-
const key = resolvePublishName(def, stageName);
|
|
209
|
-
const slot = state.named[key];
|
|
210
|
-
if (slot) slot.push(output);
|
|
211
|
-
else state.named[key] = [output];
|
|
212
|
-
return;
|
|
213
|
-
}
|
|
214
|
-
if (def.inheritsArtifacts === false) {
|
|
215
|
-
state.primaryArtifact = undefined;
|
|
216
|
-
}
|
|
217
|
-
}
|
|
218
|
-
|
|
219
195
|
/**
|
|
220
196
|
* Build the `AuditCtx`-shaped object `recordTerminalFailure` needs for
|
|
221
197
|
* a script-stage halt. The `skill` field doubles as the lifecycle
|
|
@@ -223,18 +199,9 @@ function advancePrimaryForScript(state: RunState, def: StageDef, stageName: stri
|
|
|
223
199
|
* attribution aligned with the success row's `stage` identity.
|
|
224
200
|
*/
|
|
225
201
|
function scriptAuditCtx(run: RunContext, stage: ResolvedStage) {
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
// `skill` doubles as the notify-message subject (`MSG_VALIDATION_EXHAUSTED`,
|
|
232
|
-
// `MSG_STAGE_FAILED`); set to the stage name so the user sees the stage
|
|
233
|
-
// identity. `isScript: true` ensures the JSONL row drops the field and
|
|
234
|
-
// `onStageError` fires with `scriptStageRef` (no `skill` payload).
|
|
235
|
-
skill: stage.name,
|
|
236
|
-
lifecycle: run.lifecycle,
|
|
237
|
-
runIdentity: { workflow: run.workflow.name, totalStages: run.totalStages, trigger: run.trigger },
|
|
238
|
-
isScript: true,
|
|
239
|
-
};
|
|
202
|
+
// `skill` doubles as the notify-message subject (`MSG_VALIDATION_EXHAUSTED`,
|
|
203
|
+
// `MSG_STAGE_FAILED`); set to the stage name so the user sees the stage
|
|
204
|
+
// identity. `isScript: true` ensures the JSONL row drops the field and
|
|
205
|
+
// `onStageError` fires with `scriptStageRef` (no `skill` payload).
|
|
206
|
+
return auditCtxFor(run, stage.name, stage.name, { isScript: true });
|
|
240
207
|
}
|