@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
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Child-session file layout — the two operations keyed off `childSessionsDir`:
|
|
3
|
+
* LOCATE one session by id (session-backed resume) and PRUNE the orphans (the
|
|
4
|
+
* run-end sweep). `SessionRef.file` is a HINT captured at activation time —
|
|
5
|
+
* sessions move (Pi renames on label change), get cleaned up, or live on another
|
|
6
|
+
* machine. `locateSessionFile` resolves id → on-disk path with a three-rung
|
|
7
|
+
* fallback; `null` means "fall back to cold re-run" (the caller's ladder
|
|
8
|
+
* notifies). `pruneOrphanedChildSessions` removes files no persisted row points
|
|
9
|
+
* at.
|
|
10
|
+
*
|
|
11
|
+
* `node:fs` only — no Pi import; unit-testable with temp dirs. Fail-soft
|
|
12
|
+
* throughout: any fs error degrades to the next rung, never throws.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { closeSync, existsSync, openSync, readdirSync, readSync, rmSync, statSync } from "node:fs";
|
|
16
|
+
import { dirname, join } from "node:path";
|
|
17
|
+
import type { SessionRef } from "../state/index.js";
|
|
18
|
+
import { childSessionsDir } from "../state/paths.js";
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* id → on-disk session file. Fail-soft: `null` means "fall back to cold
|
|
22
|
+
* re-run".
|
|
23
|
+
*
|
|
24
|
+
* 0. When a `runId`+`cwd` are known, try the run-scoped child dir by id
|
|
25
|
+
* FIRST (`childSessionsDir(cwd, runId)/<id>.jsonl`, O(1)) — detached
|
|
26
|
+
* children persist there keyed by `SessionRef.id`.
|
|
27
|
+
* 1. `ref.file` exists on disk → use it (fast path).
|
|
28
|
+
* 2. Else search `dirname(ref.file)` for `*_<id>.jsonl` (Pi's filename
|
|
29
|
+
* convention embeds the session id).
|
|
30
|
+
* 3. Else scan each `.jsonl` header line in that dir for `id === ref.id`
|
|
31
|
+
* (robust against filename-convention drift).
|
|
32
|
+
* 4. Else `null`.
|
|
33
|
+
*
|
|
34
|
+
* No `file` hint at all (in-memory session) → `null` immediately AFTER the
|
|
35
|
+
* id-first rung: without the hint there is no directory to search.
|
|
36
|
+
*/
|
|
37
|
+
export function locateSessionFile(ref: SessionRef, runId?: string, cwd?: string): string | null {
|
|
38
|
+
if (runId && cwd) {
|
|
39
|
+
const candidate = join(childSessionsDir(cwd, runId), `${ref.id}.jsonl`);
|
|
40
|
+
if (isFile(candidate)) return candidate;
|
|
41
|
+
}
|
|
42
|
+
if (!ref.file) return null;
|
|
43
|
+
try {
|
|
44
|
+
if (existsSync(ref.file) && statSync(ref.file).isFile()) return ref.file;
|
|
45
|
+
} catch {
|
|
46
|
+
// fall through to the directory rungs
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const dir = dirname(ref.file);
|
|
50
|
+
let entries: string[];
|
|
51
|
+
try {
|
|
52
|
+
entries = readdirSync(dir);
|
|
53
|
+
} catch {
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// Rung 2: Pi's filename embeds the id (`<timestamp>_<id>.jsonl`).
|
|
58
|
+
for (const entry of entries) {
|
|
59
|
+
if (!entry.endsWith(`_${ref.id}.jsonl`)) continue;
|
|
60
|
+
const path = join(dir, entry);
|
|
61
|
+
if (isFile(path)) return path;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// Rung 3: header scan — first JSONL line carries the session `id`.
|
|
65
|
+
for (const entry of entries) {
|
|
66
|
+
if (!entry.endsWith(".jsonl")) continue;
|
|
67
|
+
const path = join(dir, entry);
|
|
68
|
+
if (isFile(path) && headerIdOf(path) === ref.id) return path;
|
|
69
|
+
}
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Orphan sweep — delete every persisted child-session file under the run's
|
|
75
|
+
* `childSessionsDir` whose session id NO entry in `referenced` carries. Run ONCE
|
|
76
|
+
* at run end (`executeRun`), after every child is torn down and every row is
|
|
77
|
+
* written, so the keep-set is complete.
|
|
78
|
+
*
|
|
79
|
+
* The orphan source today is a `continue` fork whose stage threw between
|
|
80
|
+
* `SessionManager.forkFrom` (which wrote the fork file) and its first audit-row
|
|
81
|
+
* write: `recordEntryThrow` pins `session: null` on the failure row, so no row
|
|
82
|
+
* references the fork (an aborted fresh child is the same shape). Deleting it is
|
|
83
|
+
* SAFE because resume only ever reattaches/forks a file some persisted row
|
|
84
|
+
* references — or `lastSession`, itself a referenced session — so an unreferenced
|
|
85
|
+
* file is never consulted; removing it cannot strand a resumable session.
|
|
86
|
+
*
|
|
87
|
+
* CONSERVATIVE by construction: a file is removed ONLY when its header id is
|
|
88
|
+
* positively read AND absent from `referenced`. An unreadable header keeps the
|
|
89
|
+
* file (a leftover orphan is the harmless status quo; deleting a referenced file
|
|
90
|
+
* is not). Best-effort — a missing dir or an unlink race never throws.
|
|
91
|
+
*/
|
|
92
|
+
export function pruneOrphanedChildSessions(cwd: string, runId: string, referenced: ReadonlySet<string>): void {
|
|
93
|
+
const dir = childSessionsDir(cwd, runId);
|
|
94
|
+
let entries: string[];
|
|
95
|
+
try {
|
|
96
|
+
entries = readdirSync(dir);
|
|
97
|
+
} catch {
|
|
98
|
+
return; // no child-sessions dir (no detached child ran) — nothing to sweep
|
|
99
|
+
}
|
|
100
|
+
for (const entry of entries) {
|
|
101
|
+
if (!entry.endsWith(".jsonl")) continue;
|
|
102
|
+
const path = join(dir, entry);
|
|
103
|
+
const id = headerIdOf(path);
|
|
104
|
+
if (id === undefined || referenced.has(id)) continue; // unidentifiable / referenced → keep
|
|
105
|
+
try {
|
|
106
|
+
rmSync(path);
|
|
107
|
+
} catch {
|
|
108
|
+
// best-effort — an already-removed file / concurrent reader is fine
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function isFile(path: string): boolean {
|
|
114
|
+
try {
|
|
115
|
+
return statSync(path).isFile();
|
|
116
|
+
} catch {
|
|
117
|
+
return false;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Bounded prefix read — session files run to tens of MB; the header is line one. */
|
|
122
|
+
const HEADER_PREFIX_BYTES = 8192;
|
|
123
|
+
|
|
124
|
+
/** First-line `id` of a Pi session file, or undefined on any read/parse miss. */
|
|
125
|
+
function headerIdOf(path: string): string | undefined {
|
|
126
|
+
let fd: number | undefined;
|
|
127
|
+
try {
|
|
128
|
+
fd = openSync(path, "r");
|
|
129
|
+
const buf = Buffer.alloc(HEADER_PREFIX_BYTES);
|
|
130
|
+
const bytes = readSync(fd, buf, 0, HEADER_PREFIX_BYTES, 0);
|
|
131
|
+
const firstLine = buf.toString("utf-8", 0, bytes).split("\n", 1)[0];
|
|
132
|
+
if (!firstLine) return undefined;
|
|
133
|
+
const parsed: unknown = JSON.parse(firstLine);
|
|
134
|
+
const id = (parsed as { id?: unknown } | null)?.id;
|
|
135
|
+
return typeof id === "string" ? id : undefined;
|
|
136
|
+
} catch {
|
|
137
|
+
return undefined;
|
|
138
|
+
} finally {
|
|
139
|
+
if (fd !== undefined) closeSync(fd);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session-backed resume continuation — runs INSIDE the interrupted stage's
|
|
3
|
+
* reopened child session (the `withSession` callback of `reattachChildSession`,
|
|
4
|
+
* which the host opens from the persisted session file; wired by
|
|
5
|
+
* `resumeWithSessionLadder` in runner/run-stage.ts). Companion to `sessions.ts`,
|
|
6
|
+
* reusing its exported pipeline pieces instead of duplicating them.
|
|
7
|
+
*
|
|
8
|
+
* Two arms, tried in order:
|
|
9
|
+
*
|
|
10
|
+
* 1. PROMOTION — adopt the session's existing branch and run the entire
|
|
11
|
+
* collector → parser → contract pipeline over it
|
|
12
|
+
* (`produceAndValidateOutput`, verbatim — including the frontmatter
|
|
13
|
+
* parser's disk-existence check). Success ⇒ a normal completed row via
|
|
14
|
+
* `recordStageSuccess` and the chain advances — the interrupted turn's
|
|
15
|
+
* work is adopted without sending anything. Deliberately NO
|
|
16
|
+
* `classifyStop` here: the old tail is an interrupted turn by
|
|
17
|
+
* definition; promotion only asks "did the artifact land".
|
|
18
|
+
*
|
|
19
|
+
* 2. REATTACH — on collector-fatal (the artifact pipeline found nothing),
|
|
20
|
+
* continue the session from its leaf with a nudge prompt, wait for the
|
|
21
|
+
* agent to settle, then run the standard `postStage` — from there the
|
|
22
|
+
* flow is byte-identical to live: stop classification, extraction
|
|
23
|
+
* (original offset, so a pre-interrupt announcement still counts),
|
|
24
|
+
* success persistence or halt. A second failure writes a normal
|
|
25
|
+
* failure row — itself session-backed, so the run stays resumable.
|
|
26
|
+
*
|
|
27
|
+
* Validation-exhausted from promotion halts exactly as live does.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
import { MSG_RESUME_PROMOTED, MSG_RESUME_REATTACHED, REATTACH_PROMPT } from "../messages.js";
|
|
31
|
+
import { readBranch, readSessionRef } from "../transcript.js";
|
|
32
|
+
import type { StageSession, WorkflowHostContext, WorkflowSessionContext } from "../types.js";
|
|
33
|
+
import { produceAndValidateOutput } from "./extraction.js";
|
|
34
|
+
import { haltStageWithValidationFailure } from "./halt-routing.js";
|
|
35
|
+
import { postStage } from "./sessions.js";
|
|
36
|
+
import { branchOffsetFor, resendIntoChild } from "./spawn.js";
|
|
37
|
+
import { recordStageSuccess } from "./success-persist.js";
|
|
38
|
+
|
|
39
|
+
// Same two-ctx split as `postStage`: `obsCtx` is the long-lived launcher/observer
|
|
40
|
+
// (user-facing notifications + record + the chain continuation that spawns the
|
|
41
|
+
// next stage); `child` is the reopened persisted session (branch reads + the
|
|
42
|
+
// reattach nudge).
|
|
43
|
+
export async function reattachStageSession(
|
|
44
|
+
obsCtx: WorkflowHostContext,
|
|
45
|
+
child: WorkflowSessionContext,
|
|
46
|
+
s: StageSession,
|
|
47
|
+
): Promise<void> {
|
|
48
|
+
// Promotion: extraction over the adopted branch, scoped by the SAME
|
|
49
|
+
// offset the interrupted activation ran under (persisted on its row and
|
|
50
|
+
// threaded back via `s.branchOffset`; fresh stages scan the whole branch).
|
|
51
|
+
const offset = branchOffsetFor(s.stage.sessionPolicy, s.branchOffset);
|
|
52
|
+
const session = readSessionRef(child, offset);
|
|
53
|
+
const result = await produceAndValidateOutput(child, s, readBranch(child), offset);
|
|
54
|
+
|
|
55
|
+
if (result.kind === "ok") {
|
|
56
|
+
obsCtx.ui.notify(MSG_RESUME_PROMOTED(s.skill), "info");
|
|
57
|
+
if (!(await recordStageSuccess(obsCtx, s, result.output, session))) return;
|
|
58
|
+
await s.onSuccess(obsCtx, result.output);
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
if (result.kind === "validation-exhausted") {
|
|
62
|
+
return haltStageWithValidationFailure(obsCtx, s, result.failureSummary, session);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// Promotion missed (collector-fatal) — reattach: nudge the session from
|
|
66
|
+
// its leaf, let the agent finish with full prior context, then run the
|
|
67
|
+
// standard post-session pipeline.
|
|
68
|
+
obsCtx.ui.notify(MSG_RESUME_REATTACHED(s.skill), "info");
|
|
69
|
+
await resendIntoChild(child, REATTACH_PROMPT(s.skill));
|
|
70
|
+
await postStage(obsCtx, child, s);
|
|
71
|
+
}
|
package/sessions/sessions.ts
CHANGED
|
@@ -1,213 +1,142 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Session execution — one Pi session per workflow stage /
|
|
3
|
-
* `runStageSession`
|
|
2
|
+
* Session execution — one Pi session per workflow stage / loop unit.
|
|
3
|
+
* `runStageSession` is the only public entry (loop units run through it too,
|
|
4
|
+
* threading their identity via `StageSession.unit`).
|
|
4
5
|
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
* — is policy-agnostic.
|
|
6
|
+
* Every stage runs in its own detached child session (`spawnChildAndRun`,
|
|
7
|
+
* spawn.ts); the only surviving policy divergence is the branch offset
|
|
8
|
+
* (`branchOffsetFor`). Everything in this file — post-processing, halt routing,
|
|
9
|
+
* success persistence, outcome reading — is policy-agnostic.
|
|
10
10
|
*
|
|
11
11
|
* Companion modules:
|
|
12
|
-
* - extraction.ts
|
|
13
|
-
*
|
|
14
|
-
* - spawn.ts
|
|
15
|
-
*
|
|
12
|
+
* - extraction.ts — produceAndValidateOutput + retry loop +
|
|
13
|
+
* outcome helpers (collector → parser pipeline).
|
|
14
|
+
* - spawn.ts — the child-spawn primitives (`spawnChildAndRun`,
|
|
15
|
+
* `reattachChildSession`, `resendIntoChild`) + `branchOffsetFor`.
|
|
16
|
+
* - halt-routing.ts — the halt pipeline (`haltStageOrSoftHalt` gate +
|
|
17
|
+
* the per-arm halt helpers + `auditFor`); consumed by
|
|
18
|
+
* `postStage` below and `reattach.ts`.
|
|
19
|
+
* - success-persist.ts — `recordStageSuccess` + `unitEventOf`; consumed by
|
|
20
|
+
* `postStage` below and `reattach.ts`.
|
|
21
|
+
* - reattach.ts — session-backed resume (promotion + reattach); reuses
|
|
22
|
+
* postStage / recordStageSuccess / the halt helpers
|
|
23
|
+
* exported below instead of duplicating them.
|
|
16
24
|
*/
|
|
17
25
|
|
|
18
|
-
import {
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
nowIso,
|
|
22
|
-
recordCancellation,
|
|
23
|
-
recordStage,
|
|
24
|
-
recordStopFailure,
|
|
25
|
-
recordTerminalFailure,
|
|
26
|
-
} from "../audit.js";
|
|
27
|
-
import { applyCompletedStage } from "../internal-utils.js";
|
|
28
|
-
import { buildLifecycleContext, skillStageRef } from "../lifecycle.js";
|
|
29
|
-
import {
|
|
30
|
-
ERR_AUDIT_WRITE_FAILED,
|
|
31
|
-
ERR_VALIDATION_FAILED,
|
|
32
|
-
MSG_AUDIT_WRITE_FAILED,
|
|
33
|
-
MSG_STAGE_COMPLETE,
|
|
34
|
-
MSG_STAGE_FAILED,
|
|
35
|
-
MSG_VALIDATION_EXHAUSTED,
|
|
36
|
-
} from "../messages.js";
|
|
37
|
-
import type { Output } from "../output.js";
|
|
38
|
-
import { type BranchEntry, classifyStop, readBranch, type StopSignal } from "../transcript.js";
|
|
39
|
-
import type { FanoutSession, SessionContext, StageSession, WorkflowHostContext } from "../types.js";
|
|
26
|
+
import { WorkflowAbortError } from "../internal-utils.js";
|
|
27
|
+
import { type BranchEntry, classifyStop, readBranch, readSessionRef, type StopSignal } from "../transcript.js";
|
|
28
|
+
import type { StageSession, WorkflowHostContext, WorkflowSessionContext } from "../types.js";
|
|
40
29
|
import { produceAndValidateOutput } from "./extraction.js";
|
|
41
|
-
import {
|
|
30
|
+
import { haltStageOrSoftHalt } from "./halt-routing.js";
|
|
31
|
+
import { branchOffsetFor, resendIntoChild, spawnChildAndRun } from "./spawn.js";
|
|
32
|
+
import { recordStageSuccess } from "./success-persist.js";
|
|
42
33
|
|
|
43
34
|
// ===========================================================================
|
|
44
35
|
// PUBLIC ENTRIES — what the orchestrator calls
|
|
45
36
|
// ===========================================================================
|
|
46
37
|
|
|
47
|
-
/** Execute one DAG stage in its own session. */
|
|
38
|
+
/** Execute one DAG stage (or loop unit) in its own detached child session. */
|
|
48
39
|
export async function runStageSession(ctx: WorkflowHostContext, s: StageSession): Promise<void> {
|
|
49
|
-
|
|
50
|
-
const { cancelled } = await handler.spawn(ctx, s.prompt, (sessionCtx) => postStage(sessionCtx, s), s.continueHost);
|
|
51
|
-
if (cancelled) await recordCancellation(ctx, auditFor(s));
|
|
40
|
+
await spawnChildAndRun(ctx, s, (child) => postStage(ctx, child, s));
|
|
52
41
|
}
|
|
53
42
|
|
|
54
|
-
/**
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
const result = await produceAndValidateOutput(ctx, s, outcome.branch, offset);
|
|
72
|
-
if (result.kind === "fatal") return haltStageWithExtractionError(ctx, s, result.message);
|
|
73
|
-
if (result.kind === "validation-exhausted") return haltStageWithValidationFailure(ctx, s, result.failureSummary);
|
|
74
|
-
|
|
75
|
-
if (!(await recordStageSuccess(ctx, s, result.output))) return;
|
|
76
|
-
await s.onSuccess(ctx, result.output.artifacts[0]);
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
/** Fanout-unit post-processing: classify outcome → persist bare row → chain. */
|
|
80
|
-
async function postFanout(ctx: WorkflowHostContext, s: FanoutSession): Promise<void> {
|
|
81
|
-
const outcome = readSessionOutcome(ctx, undefined);
|
|
82
|
-
if (outcome.stop !== "stop") return haltFanout(ctx, s, outcome.stop);
|
|
83
|
-
|
|
84
|
-
if (!(await recordFanoutSuccess(ctx, s))) return;
|
|
85
|
-
await s.onSuccess(ctx);
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
// ===========================================================================
|
|
89
|
-
// HALT HELPERS — turn a halt reason into the right audit-layer call
|
|
90
|
-
// ===========================================================================
|
|
91
|
-
|
|
92
|
-
async function haltStage(ctx: WorkflowHostContext, s: StageSession, stop: Exclude<StopSignal, "stop">): Promise<void> {
|
|
93
|
-
await recordStopFailure(ctx, auditFor(s), stop, `${s.skill} failed`, s.onFailure);
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
async function haltStageWithExtractionError(ctx: WorkflowHostContext, s: StageSession, message: string): Promise<void> {
|
|
97
|
-
await recordTerminalFailure(
|
|
98
|
-
ctx,
|
|
99
|
-
auditFor(s),
|
|
100
|
-
{ status: "failed", notifyMsg: MSG_STAGE_FAILED(s.skill), notifyLevel: "error", errMsg: message },
|
|
101
|
-
s.onFailure,
|
|
102
|
-
);
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
async function haltStageWithValidationFailure(
|
|
106
|
-
ctx: WorkflowHostContext,
|
|
43
|
+
/**
|
|
44
|
+
* Continue body — runs inside a FORKED child (`forkChildSession`, spawn.ts)
|
|
45
|
+
* carrying the predecessor's full transcript. Re-derive the inherited-prefix
|
|
46
|
+
* offset from the actual forked branch BEFORE the continuation turn is sent
|
|
47
|
+
* (the boundary past which only this stage's own output lives), send the turn
|
|
48
|
+
* via `resendIntoChild` (`/skill:` and templates expand through the rpiv-args
|
|
49
|
+
* input hook exactly as a fresh prompt would), then run the standard `postStage`
|
|
50
|
+
* scoped by that offset. From there the flow is byte-identical to a fresh stage —
|
|
51
|
+
* stop classification, extraction, persistence — only sliced past the prefix.
|
|
52
|
+
*
|
|
53
|
+
* The re-derived offset (not a launcher-branch read) flows into `postStage` →
|
|
54
|
+
* `readSessionRef`, so the continue stage's own row records the offset its forked
|
|
55
|
+
* branch ran under; resume re-applies that persisted value verbatim.
|
|
56
|
+
*/
|
|
57
|
+
export async function continueStageSession(
|
|
58
|
+
obsCtx: WorkflowHostContext,
|
|
59
|
+
child: WorkflowSessionContext,
|
|
107
60
|
s: StageSession,
|
|
108
|
-
failureSummary: string,
|
|
109
|
-
): Promise<void> {
|
|
110
|
-
await recordTerminalFailure(
|
|
111
|
-
ctx,
|
|
112
|
-
auditFor(s),
|
|
113
|
-
{
|
|
114
|
-
status: "failed",
|
|
115
|
-
notifyMsg: MSG_VALIDATION_EXHAUSTED(s.skill),
|
|
116
|
-
notifyLevel: "error",
|
|
117
|
-
errMsg: ERR_VALIDATION_FAILED(s.skill, failureSummary),
|
|
118
|
-
},
|
|
119
|
-
s.onFailure,
|
|
120
|
-
);
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
async function haltFanout(
|
|
124
|
-
ctx: WorkflowHostContext,
|
|
125
|
-
s: FanoutSession,
|
|
126
|
-
stop: Exclude<StopSignal, "stop">,
|
|
127
61
|
): Promise<void> {
|
|
128
|
-
|
|
62
|
+
const offset = readBranch(child).length;
|
|
63
|
+
await resendIntoChild(child, s.prompt);
|
|
64
|
+
await postStage(obsCtx, child, s, offset);
|
|
129
65
|
}
|
|
130
66
|
|
|
131
67
|
// ===========================================================================
|
|
132
|
-
//
|
|
68
|
+
// POST-PROCESSING — runs after the agent loop settles
|
|
133
69
|
// ===========================================================================
|
|
134
70
|
|
|
135
71
|
/**
|
|
136
|
-
*
|
|
137
|
-
*
|
|
138
|
-
*
|
|
139
|
-
*
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
if (assigned === undefined) return false;
|
|
155
|
-
if (row.output) s.state.output = row.output;
|
|
156
|
-
s.state.stagesCompleted++;
|
|
157
|
-
return true;
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
/**
|
|
161
|
-
* Returns true on successful write — caller gates `onSuccess` on this so the
|
|
162
|
-
* chain advances only when the audit row landed. On failure, leaves
|
|
163
|
-
* `state.output` / `state.primaryArtifact` at their prior values and sets
|
|
164
|
-
* `state.termination.error` to halt the run.
|
|
72
|
+
* Stage post-processing: classify outcome → produce & validate output →
|
|
73
|
+
* persist → chain. Exported to the `reattach.ts` companion — a reattached
|
|
74
|
+
* session's continuation runs this exact pipeline, byte-identical to live.
|
|
75
|
+
*
|
|
76
|
+
* TWO ctxs (detachment): `obsCtx` is the long-lived LAUNCHER/observer ctx the
|
|
77
|
+
* walk threads — it stays valid across every stage, so the user-facing recording
|
|
78
|
+
* (success/halt rows + notifications + lifecycle) AND the chain continuation
|
|
79
|
+
* (`onSuccess` → advance/step, which spawns the NEXT stage's child) all run on
|
|
80
|
+
* it, NOT on the per-stage child (whose UI is the lane binding — noOp in the
|
|
81
|
+
* background lane — and which is disposed when the stage ends). `child` is the
|
|
82
|
+
* in-session ctx: the agent transcript (`readBranch`/`readSessionRef`) and the
|
|
83
|
+
* validation-retry re-prompt (`produceAndValidateOutput` → `resendIntoChild`)
|
|
84
|
+
* read/write through it. Spawning the next stage off `obsCtx` is what keeps the
|
|
85
|
+
* launcher the single spawner (no nested-child chain).
|
|
86
|
+
*
|
|
87
|
+
* The backing `SessionRef` is captured ONCE at entry — every row this
|
|
88
|
+
* pipeline can write (success, stop-failure, extraction/validation failure)
|
|
89
|
+
* carries the same provenance value.
|
|
165
90
|
*/
|
|
166
|
-
async function
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
);
|
|
195
|
-
|
|
91
|
+
export async function postStage(
|
|
92
|
+
obsCtx: WorkflowHostContext,
|
|
93
|
+
child: WorkflowSessionContext,
|
|
94
|
+
s: StageSession,
|
|
95
|
+
// Defaults to the policy-derived offset (fresh ⇒ undefined; resume continue ⇒
|
|
96
|
+
// the persisted row's value). The live continue body passes the value it
|
|
97
|
+
// re-derived from the forked branch, which is authoritative there.
|
|
98
|
+
offset: number | undefined = branchOffsetFor(s.stage.sessionPolicy, s.branchOffset),
|
|
99
|
+
): Promise<void> {
|
|
100
|
+
const session = readSessionRef(child, offset);
|
|
101
|
+
const outcome = readSessionOutcome(child, offset);
|
|
102
|
+
// Abort surfaces as a STOP CLASSIFICATION, not a promise rejection:
|
|
103
|
+
// `session.abort()` makes the SDK RESOLVE `prompt()` with a
|
|
104
|
+
// `stopReason:"aborted"` transcript message, so an aborted in-flight child runs
|
|
105
|
+
// straight into here. Throw BEFORE haltStage/softHaltUnit/any row write so:
|
|
106
|
+
// (a) no `collected:true` row is written (else the resume fold marks the unit
|
|
107
|
+
// "don't re-dispatch" → permanent work loss), (b) the parallel fold's
|
|
108
|
+
// `isAbortError` branch leaves the slot unfilled, and (c) resume re-dispatches
|
|
109
|
+
// the unit cleanly.
|
|
110
|
+
//
|
|
111
|
+
// A genuine run/user abort (`s.signal` fired) ALWAYS re-dispatches on resume, so it
|
|
112
|
+
// takes the throw unconditionally. An `aborted` stop with the signal cold is examined
|
|
113
|
+
// for a watchdog tool-timeout (`child.toolTimeout`): the host aborted a runaway bash,
|
|
114
|
+
// which must route to the soft-halt gate (collect-all unit survives; else terminal
|
|
115
|
+
// fail) — NOT WorkflowAbortError, which would re-run the same runaway command on resume.
|
|
116
|
+
if (s.signal?.aborted) throw new WorkflowAbortError();
|
|
117
|
+
if (outcome.stop === "aborted") {
|
|
118
|
+
const timeout = child.toolTimeout?.();
|
|
119
|
+
if (timeout) return haltStageOrSoftHalt(obsCtx, s, { kind: "timeout", reason: timeout.reason }, session);
|
|
120
|
+
throw new WorkflowAbortError();
|
|
196
121
|
}
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
122
|
+
// Every halt below routes through the single `haltStageOrSoftHalt` gate: a
|
|
123
|
+
// fanout unit marked `collectAll` records a NON-terminal failed row + a sentinel
|
|
124
|
+
// slot instead of halting the run; everything else takes the arm's fail-fast
|
|
125
|
+
// halt. Recording + the continuation run on obsCtx (the launcher) — the per-stage
|
|
126
|
+
// child is disposed when the stage ends.
|
|
127
|
+
if (outcome.stop !== "stop") return haltStageOrSoftHalt(obsCtx, s, { kind: "stop", stop: outcome.stop }, session);
|
|
128
|
+
|
|
129
|
+
const result = await produceAndValidateOutput(child, s, outcome.branch, offset);
|
|
130
|
+
if (result.kind === "fatal")
|
|
131
|
+
return haltStageOrSoftHalt(obsCtx, s, { kind: "extraction", message: result.message }, session);
|
|
132
|
+
if (result.kind === "validation-exhausted")
|
|
133
|
+
return haltStageOrSoftHalt(obsCtx, s, { kind: "validation", failureSummary: result.failureSummary }, session);
|
|
134
|
+
|
|
135
|
+
if (!(await recordStageSuccess(obsCtx, s, result.output, session))) return;
|
|
136
|
+
// The validated Output goes to the continuation directly — loop drivers
|
|
137
|
+
// thread it into accumulated / feedForward without state back-reads. Runs on
|
|
138
|
+
// obsCtx so the next stage's child is spawned off the launcher.
|
|
139
|
+
await s.onSuccess(obsCtx, result.output);
|
|
211
140
|
}
|
|
212
141
|
|
|
213
142
|
// ===========================================================================
|
|
@@ -235,17 +164,3 @@ function readSessionOutcome(ctx: WorkflowHostContext, branchOffset: number | und
|
|
|
235
164
|
stop: classifyStop(branch, branchOffset),
|
|
236
165
|
};
|
|
237
166
|
}
|
|
238
|
-
|
|
239
|
-
// ===========================================================================
|
|
240
|
-
// Helpers
|
|
241
|
-
// ===========================================================================
|
|
242
|
-
|
|
243
|
-
const auditFor = (s: StageSession | FanoutSession): AuditCtx => ({
|
|
244
|
-
cwd: s.cwd,
|
|
245
|
-
runId: s.runId,
|
|
246
|
-
state: s.state,
|
|
247
|
-
stageName: "unitIndex" in s ? fanoutRowStage(s) : s.stageName,
|
|
248
|
-
skill: s.skill,
|
|
249
|
-
lifecycle: s.lifecycle,
|
|
250
|
-
runIdentity: s.runIdentity,
|
|
251
|
-
});
|