@juicesharp/rpiv-workflow 2.1.0 → 2.2.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/audit-ctx.ts +9 -1
- package/audit-rows.ts +10 -0
- package/audit.ts +22 -0
- package/chain-state.ts +15 -1
- package/death-scene.ts +232 -0
- package/docs/embedding.md +1 -1
- package/events.ts +2 -26
- package/execution-host.ts +9 -0
- package/failure-memos.ts +74 -0
- package/host.ts +12 -0
- package/internal.ts +1 -0
- package/loop-def.ts +8 -4
- package/loop-kinds.ts +4 -1
- package/loop-parallel.ts +107 -86
- package/loop.ts +16 -15
- package/messages.ts +26 -0
- package/package.json +5 -2
- package/registration.ts +5 -0
- package/routing.ts +0 -40
- package/runner/chain-advance.ts +3 -9
- package/runner/run-context.ts +13 -3
- package/runner/run-stage.ts +71 -2
- package/runner/runner.ts +15 -5
- package/sessions/bash-strikes.ts +182 -0
- package/sessions/extraction.ts +32 -25
- package/sessions/halt-routing.ts +5 -0
- package/sessions/sessions.ts +39 -1
- package/sessions/success-persist.ts +6 -0
- package/stage-identity.ts +43 -4
- package/state/state.ts +10 -0
- package/transcript.ts +30 -0
- package/types.ts +96 -6
- package/worktree-digest.ts +148 -0
package/audit-ctx.ts
CHANGED
|
@@ -37,7 +37,15 @@ import type { RunContext, SessionContext, UnitRef } from "./types.js";
|
|
|
37
37
|
*/
|
|
38
38
|
export type AuditCtx = Pick<
|
|
39
39
|
SessionContext,
|
|
40
|
-
|
|
40
|
+
| "cwd"
|
|
41
|
+
| "runId"
|
|
42
|
+
| "state"
|
|
43
|
+
| "stageName"
|
|
44
|
+
| "skill"
|
|
45
|
+
| "lifecycle"
|
|
46
|
+
| "runIdentity"
|
|
47
|
+
| "allocatedStageNumber"
|
|
48
|
+
| "readSessionBranch"
|
|
41
49
|
> & {
|
|
42
50
|
session: SessionRef | null;
|
|
43
51
|
isScript?: boolean;
|
package/audit-rows.ts
CHANGED
|
@@ -130,6 +130,12 @@ export function persistStageSuccess(
|
|
|
130
130
|
unit?: UnitRef;
|
|
131
131
|
/** The activation's pre-allocated number (output-producing paths). */
|
|
132
132
|
preAllocated?: number;
|
|
133
|
+
/**
|
|
134
|
+
* Strike history — written onto the completed row ONLY when the caller
|
|
135
|
+
* supplies it (a session that consumed bash strikes). Zero strikes ⇒ the
|
|
136
|
+
* caller omits it ⇒ spread below contributes nothing ⇒ byte-identical row.
|
|
137
|
+
*/
|
|
138
|
+
bashTimeoutStrikes?: { count: number; reasons: string[] };
|
|
133
139
|
},
|
|
134
140
|
def: StageDef,
|
|
135
141
|
): boolean {
|
|
@@ -144,6 +150,10 @@ export function persistStageSuccess(
|
|
|
144
150
|
output: row.output,
|
|
145
151
|
session: row.session,
|
|
146
152
|
...unitRowFields(row.unit),
|
|
153
|
+
// Propagate the additive strike-history field onto the persisted
|
|
154
|
+
// completed WorkflowStage row ONLY when the caller supplied it (zero strikes
|
|
155
|
+
// ⇒ undefined ⇒ spread contributes nothing ⇒ byte-identical row).
|
|
156
|
+
...(row.bashTimeoutStrikes ? { bashTimeoutStrikes: row.bashTimeoutStrikes } : {}),
|
|
147
157
|
},
|
|
148
158
|
state,
|
|
149
159
|
row.preAllocated,
|
package/audit.ts
CHANGED
|
@@ -18,7 +18,9 @@
|
|
|
18
18
|
|
|
19
19
|
import type { AuditCtx } from "./audit-ctx.js";
|
|
20
20
|
import { recordStage, unitRowFields } from "./audit-rows.js";
|
|
21
|
+
import { writeDeathSceneArtifact } from "./death-scene.js";
|
|
21
22
|
import { lifecycleCtxFromSession, scriptStageRef, skillStageRef } from "./events.js";
|
|
23
|
+
import { appendFailureMemo } from "./failure-memos.js";
|
|
22
24
|
import { handleToString } from "./handle.js";
|
|
23
25
|
import { assertNever, nowIso } from "./internal-utils.js";
|
|
24
26
|
import {
|
|
@@ -117,6 +119,24 @@ function writeFailureRow(
|
|
|
117
119
|
return written;
|
|
118
120
|
}
|
|
119
121
|
|
|
122
|
+
/**
|
|
123
|
+
* Record the two failure-forensics sidecars for a failed stage/unit — the
|
|
124
|
+
* in-memory failure memo (`appendFailureMemo`) and the death-scene `.md`
|
|
125
|
+
* artifact (`writeDeathSceneArtifact`) — immediately after the failure-row
|
|
126
|
+
* write. Peer helper to `writeFailureRow`; the two terminal writers
|
|
127
|
+
* (`recordTerminalFailure`, `recordUnitHalt`) both delegate here.
|
|
128
|
+
*
|
|
129
|
+
* Fail-soft: the death-scene artifact reads the just-failed session's persisted
|
|
130
|
+
* JSONL via the host-injected `audit.readSessionBranch`; skips silently when
|
|
131
|
+
* sessionless / no reader; notifies + continues on any miss/throw so the
|
|
132
|
+
* already-persisted failure row is never masked. The memo append is in-memory
|
|
133
|
+
* only and does not throw.
|
|
134
|
+
*/
|
|
135
|
+
function recordFailureForensics(ctx: WorkflowHostContext, audit: AuditCtx, errMsg: string): void {
|
|
136
|
+
appendFailureMemo(audit.state, audit, errMsg);
|
|
137
|
+
writeDeathSceneArtifact(ctx, audit, errMsg);
|
|
138
|
+
}
|
|
139
|
+
|
|
120
140
|
export async function recordTerminalFailure(
|
|
121
141
|
ctx: WorkflowHostContext,
|
|
122
142
|
audit: AuditCtx,
|
|
@@ -144,6 +164,7 @@ export async function recordTerminalFailure(
|
|
|
144
164
|
session: audit.session,
|
|
145
165
|
...unitRowFields(audit.unit),
|
|
146
166
|
});
|
|
167
|
+
recordFailureForensics(ctx, audit, args.errMsg);
|
|
147
168
|
ctx.ui.notify(args.notifyMsg, args.notifyLevel);
|
|
148
169
|
onFailure?.(ctx);
|
|
149
170
|
terminate(audit.state, { status: args.status, error: args.errMsg });
|
|
@@ -174,6 +195,7 @@ export function recordUnitHalt(ctx: WorkflowHostContext, audit: AuditCtx, errMsg
|
|
|
174
195
|
session: audit.session,
|
|
175
196
|
...unitRowFields(audit.unit),
|
|
176
197
|
});
|
|
198
|
+
recordFailureForensics(ctx, audit, errMsg);
|
|
177
199
|
}
|
|
178
200
|
|
|
179
201
|
/**
|
package/chain-state.ts
CHANGED
|
@@ -83,6 +83,16 @@ export function stageEntryArgs(
|
|
|
83
83
|
if (usesOriginalInput(def, stageName, startStage)) return state.originalInput;
|
|
84
84
|
if (hasReads(def)) {
|
|
85
85
|
const parts: string[] = [];
|
|
86
|
+
// Duplicate-flag dedup: collapse two entries on the SAME channel whose
|
|
87
|
+
// handles stringify identically (the a777 cite-check symptom — a re-run
|
|
88
|
+
// fanout channel re-published the same fs path, emitting a duplicate
|
|
89
|
+
// `--code-cite-check <path>` flag). The key is `${name}\0${handle}`:
|
|
90
|
+
// the \0 separator avoids a concatenation collision (name "ab" + handle
|
|
91
|
+
// "cd" vs "a" + "bcd"), and carrying the channel `name` preserves a fanin
|
|
92
|
+
// repeat whose entries carry DISTINCT paths (e.g. per-cluster subplans) and
|
|
93
|
+
// a multi-artifact entry whose artifacts differ. The set spans every read
|
|
94
|
+
// of the call so two reads of the same name+handle also collapse.
|
|
95
|
+
const seen = new Set<string>();
|
|
86
96
|
for (const read of def.reads) {
|
|
87
97
|
const name = readName(read);
|
|
88
98
|
const slot = state.named[name];
|
|
@@ -105,7 +115,11 @@ export function stageEntryArgs(
|
|
|
105
115
|
for (const entry of entries) {
|
|
106
116
|
if (!entry || isFailedOutput(entry)) continue; // unfilled (pending) or failed → no args
|
|
107
117
|
for (const artifact of entry.artifacts) {
|
|
108
|
-
|
|
118
|
+
const handle = handleToString(artifact.handle);
|
|
119
|
+
const key = `${name}\0${handle}`;
|
|
120
|
+
if (seen.has(key)) continue;
|
|
121
|
+
seen.add(key);
|
|
122
|
+
parts.push(`--${name}`, handle);
|
|
109
123
|
}
|
|
110
124
|
}
|
|
111
125
|
}
|
package/death-scene.ts
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* death-scene.ts — forensic Markdown artifact written on stage/unit failure.
|
|
3
|
+
*
|
|
4
|
+
* On any transition to failed (terminal failure or a collect-all unit soft-halt),
|
|
5
|
+
* the two failure-record writers (`recordTerminalFailure` /
|
|
6
|
+
* `recordUnitHalt` in `audit.ts`) call `writeDeathSceneArtifact` immediately
|
|
7
|
+
* after they persist the JSONL failure row. The writer locates the just-failed
|
|
8
|
+
* session's persisted JSONL, re-reads its branch through the host-injected
|
|
9
|
+
* `AuditCtx.readSessionBranch` (NO live-session re-query — the child is already
|
|
10
|
+
* torn down), extracts the forensic scene, and writes a sidecar `.md` under
|
|
11
|
+
* `<cwd>/.rpiv/artifacts/failures/`.
|
|
12
|
+
*
|
|
13
|
+
* Fail-soft throughout and SYNCHRONOUS: the entire body is try/caught, and on
|
|
14
|
+
* ANY failure (locate miss, reader throw, write error) it warns via
|
|
15
|
+
* `ctx.ui.notify(..., "warning")` and
|
|
16
|
+
* continues — the original failure (already persisted by `writeFailureRow`)
|
|
17
|
+
* is never masked. Skips SILENTLY (no throw, no artifact, no warning) when
|
|
18
|
+
* `audit.session === null` (sessionless failures: entry throws, seam aborts
|
|
19
|
+
* via `auditCtxFor`) or `audit.readSessionBranch === undefined` (programmatic
|
|
20
|
+
* embedder / no provider).
|
|
21
|
+
*
|
|
22
|
+
* No JSONL row is written — the artifact is a sidecar `.md`, never read by the
|
|
23
|
+
* resume fold, so `STATE_SCHEMA_VERSION` is NOT bumped.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import { mkdirSync, writeFileSync } from "node:fs";
|
|
27
|
+
import { dirname, join } from "node:path";
|
|
28
|
+
import type { AuditCtx } from "./audit-ctx.js";
|
|
29
|
+
import type { WorkflowHostContext } from "./host.js";
|
|
30
|
+
import { locateSessionFile } from "./sessions/locate.js";
|
|
31
|
+
import { type BranchEntry, iterToolUses, lastAssistantText } from "./transcript.js";
|
|
32
|
+
|
|
33
|
+
/** How many trailing tool calls the artifact carries (most-recent first wins via slice). */
|
|
34
|
+
export const DEATH_SCENE_MAX_TOOL_CALLS = 5;
|
|
35
|
+
|
|
36
|
+
/** Per-tool-call args JSON cap; a trailing "…" marks a truncation. */
|
|
37
|
+
export const DEATH_SCENE_TOOL_ARG_MAX_CHARS = 500;
|
|
38
|
+
|
|
39
|
+
/** One tool call in the death scene — name + args JSON (truncated). */
|
|
40
|
+
export interface DeathSceneToolCall {
|
|
41
|
+
name: string;
|
|
42
|
+
args: string;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** The forensic payload rendered into the sidecar Markdown. */
|
|
46
|
+
export interface DeathScene {
|
|
47
|
+
runId: string;
|
|
48
|
+
stage: string;
|
|
49
|
+
stageNumber: number;
|
|
50
|
+
/** Present iff the failure belongs to a loop unit (`audit.unit.id`). */
|
|
51
|
+
unitId?: string;
|
|
52
|
+
errMsg: string;
|
|
53
|
+
/** Final assistant text (`lastAssistantText`); omitted when empty/absent. */
|
|
54
|
+
finalText?: string;
|
|
55
|
+
/** Last-N tool calls (name + truncated args). */
|
|
56
|
+
toolCalls: DeathSceneToolCall[];
|
|
57
|
+
/** Absolute on-disk path of the persisted session JSONL. */
|
|
58
|
+
sessionFile: string;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Sanitize an author-controlled segment (stage name / unit id / runId) for use
|
|
63
|
+
* as a single filename component: strip path separators + control chars (so the
|
|
64
|
+
* segment can't escape `failures/` or mangle the filename) and collapse
|
|
65
|
+
* whitespace runs to `_`. Falls back to `"stage"` for an all-disallowed input.
|
|
66
|
+
*/
|
|
67
|
+
function sanitizeSegment(segment: string): string {
|
|
68
|
+
const cleaned = segment.replace(/[\\/\u0000-\u001f]/g, "_").replace(/\s+/g, "_");
|
|
69
|
+
return cleaned || "stage";
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* The artifact path: `<cwd>/.rpiv/artifacts/failures/<runId>_<stageNumber>_<unitId-or-stage>.md`.
|
|
74
|
+
* The unit segment is the unit's stable id when present (`audit.unit.id`), else
|
|
75
|
+
* the stage name — BOTH sanitized: real unit ids carry path separators
|
|
76
|
+
* (`"phase 2/5"`), which would otherwise nest the artifact in a surprise
|
|
77
|
+
* subdirectory. Pure — no I/O.
|
|
78
|
+
*/
|
|
79
|
+
export function deathSceneFilePath(cwd: string, audit: AuditCtx): string {
|
|
80
|
+
const stageNumber = audit.allocatedStageNumber ?? audit.state.lastAllocatedStageNumber;
|
|
81
|
+
// `unit.id` is the stable disambiguator when present (fanout/iterate). Assess-loop units
|
|
82
|
+
// carry no id (identified by `(role, round)`); append `_u<index>` so filename uniqueness
|
|
83
|
+
// does NOT depend on the decorated stageName's `r{index}·{phase}` tag — the decoration
|
|
84
|
+
// disambiguates today, but display strings are not a uniqueness contract. The whole segment
|
|
85
|
+
// (index included) is routed through sanitizeSegment so it cannot escape failures/.
|
|
86
|
+
const unitBase = audit.unit?.id ?? (audit.unit ? `${audit.stageName}_u${audit.unit.index}` : audit.stageName);
|
|
87
|
+
const unitSegment = sanitizeSegment(unitBase);
|
|
88
|
+
const runSegment = sanitizeSegment(audit.runId);
|
|
89
|
+
return join(cwd, ".rpiv", "artifacts", "failures", `${runSegment}_${stageNumber}_${unitSegment}.md`);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* JSON-stringify a tool-call's input, truncated to the args cap. A trailing "…"
|
|
94
|
+
* marks a truncation; an un-stringifiable input degrades to `String(input)`.
|
|
95
|
+
*/
|
|
96
|
+
function truncateArgs(input: Record<string, unknown>): string {
|
|
97
|
+
let json: string;
|
|
98
|
+
try {
|
|
99
|
+
json = JSON.stringify(input);
|
|
100
|
+
} catch {
|
|
101
|
+
json = String(input);
|
|
102
|
+
}
|
|
103
|
+
if (json.length <= DEATH_SCENE_TOOL_ARG_MAX_CHARS) return json;
|
|
104
|
+
return `${json.slice(0, DEATH_SCENE_TOOL_ARG_MAX_CHARS)}…`;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Pure extractor — assemble a `DeathScene` from the persisted branch + the
|
|
109
|
+
* failure's audit identity. No I/O. `toolCalls` are the LAST
|
|
110
|
+
* `DEATH_SCENE_MAX_TOOL_CALLS` tool uses in branch order (forward scan via
|
|
111
|
+
* `iterToolUses`, then tail slice); `finalText` is the last assistant message's
|
|
112
|
+
* joined text parts (via `lastAssistantText`), omitted when empty.
|
|
113
|
+
*/
|
|
114
|
+
export function extractDeathScene(
|
|
115
|
+
audit: AuditCtx,
|
|
116
|
+
errMsg: string,
|
|
117
|
+
branch: BranchEntry[],
|
|
118
|
+
sessionFile: string,
|
|
119
|
+
): DeathScene {
|
|
120
|
+
const all: DeathSceneToolCall[] = [];
|
|
121
|
+
for (const use of iterToolUses(branch)) {
|
|
122
|
+
all.push({ name: use.name, args: truncateArgs(use.input) });
|
|
123
|
+
}
|
|
124
|
+
const toolCalls = all.slice(-DEATH_SCENE_MAX_TOOL_CALLS);
|
|
125
|
+
const finalText = lastAssistantText(branch);
|
|
126
|
+
const stageNumber = audit.allocatedStageNumber ?? audit.state.lastAllocatedStageNumber;
|
|
127
|
+
return {
|
|
128
|
+
runId: audit.runId,
|
|
129
|
+
stage: audit.stageName,
|
|
130
|
+
stageNumber,
|
|
131
|
+
...(audit.unit?.id ? { unitId: audit.unit.id } : {}),
|
|
132
|
+
errMsg,
|
|
133
|
+
...(finalText ? { finalText } : {}),
|
|
134
|
+
toolCalls,
|
|
135
|
+
sessionFile,
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Pure formatter — render a `DeathScene` as forensic Markdown. No I/O. The body
|
|
141
|
+
* carries runId, stage (+number), unit (when present), errMsg, the absolute
|
|
142
|
+
* session-file path, the final assistant text, and the last-N tool calls (each
|
|
143
|
+
* with its truncated args under a fenced block).
|
|
144
|
+
*/
|
|
145
|
+
export function formatDeathScene(scene: DeathScene): string {
|
|
146
|
+
const lines: string[] = [];
|
|
147
|
+
lines.push(`# Death scene: ${scene.stage}`);
|
|
148
|
+
lines.push("");
|
|
149
|
+
lines.push(`- **Run:** \`${scene.runId}\``);
|
|
150
|
+
lines.push(`- **Stage:** \`${scene.stage}\` (#${scene.stageNumber})`);
|
|
151
|
+
if (scene.unitId) lines.push(`- **Unit:** \`${scene.unitId}\``);
|
|
152
|
+
lines.push(`- **Error:** ${scene.errMsg}`);
|
|
153
|
+
lines.push(`- **Session file:** \`${scene.sessionFile}\``);
|
|
154
|
+
lines.push("");
|
|
155
|
+
lines.push("## Final assistant text");
|
|
156
|
+
lines.push("");
|
|
157
|
+
lines.push(scene.finalText?.trim() ? scene.finalText.trim() : "_(none)_");
|
|
158
|
+
lines.push("");
|
|
159
|
+
const callCount = scene.toolCalls.length;
|
|
160
|
+
lines.push(`## Last ${callCount} tool call${callCount === 1 ? "" : "s"}`);
|
|
161
|
+
lines.push("");
|
|
162
|
+
if (callCount === 0) {
|
|
163
|
+
lines.push("_(none)_");
|
|
164
|
+
} else {
|
|
165
|
+
for (const call of scene.toolCalls) {
|
|
166
|
+
// Fence one backtick longer than the longest backtick run in the args, so
|
|
167
|
+
// a ``` inside a tool arg cannot break out of its fenced block.
|
|
168
|
+
const longestRun = call.args.match(/`+/g)?.reduce((max, run) => Math.max(max, run.length), 0) ?? 0;
|
|
169
|
+
const fence = "`".repeat(Math.max(3, longestRun + 1));
|
|
170
|
+
lines.push(`- \`${call.name}\``);
|
|
171
|
+
lines.push(` ${fence}`);
|
|
172
|
+
lines.push(` ${call.args}`);
|
|
173
|
+
lines.push(` ${fence}`);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
lines.push("");
|
|
177
|
+
return lines.join("\n");
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Impure orchestrator — write the death-scene artifact for a failed stage/unit.
|
|
182
|
+
*
|
|
183
|
+
* SKIPS silently (no throw, no artifact, no warning) when:
|
|
184
|
+
* - `audit.session === null` — sessionless failures (entry throws, seam aborts
|
|
185
|
+
* via `auditCtxFor`, which never populates `readSessionBranch`); there is no
|
|
186
|
+
* persisted session to read.
|
|
187
|
+
* - `audit.readSessionBranch === undefined` — programmatic embedder / no
|
|
188
|
+
* provider; the host never injected the reader.
|
|
189
|
+
*
|
|
190
|
+
* WARNS + continues (`ctx.ui.notify(..., "warning")`) when
|
|
191
|
+
* `locateSessionFile` returns null, the reader returns
|
|
192
|
+
* undefined/an empty branch, or any step throws — the original failure, already
|
|
193
|
+
* persisted by `writeFailureRow`, is never masked.
|
|
194
|
+
*
|
|
195
|
+
* Synchronous by design: the caller (`recordTerminalFailure` /
|
|
196
|
+
* `recordUnitHalt`) has already persisted the failure row; the artifact is a
|
|
197
|
+
* best-effort sidecar, not a reconstruction input, so it never blocks the run's
|
|
198
|
+
* terminal bookkeeping.
|
|
199
|
+
*/
|
|
200
|
+
export function writeDeathSceneArtifact(ctx: WorkflowHostContext, audit: AuditCtx, errMsg: string): void {
|
|
201
|
+
// Sessionless failures carry no persisted session — nothing to read, no artifact.
|
|
202
|
+
if (audit.session === null) return;
|
|
203
|
+
// No host-injected reader ⇒ degrade silently (programmatic embedder / no provider).
|
|
204
|
+
const readSessionBranch = audit.readSessionBranch;
|
|
205
|
+
if (readSessionBranch === undefined) return;
|
|
206
|
+
|
|
207
|
+
try {
|
|
208
|
+
const sessionFile = locateSessionFile(audit.session, audit.runId, audit.cwd);
|
|
209
|
+
if (!sessionFile) {
|
|
210
|
+
ctx.ui.notify(
|
|
211
|
+
`[rpiv-workflow] death-scene artifact skipped: session file not located for stage "${audit.stageName}"`,
|
|
212
|
+
"warning",
|
|
213
|
+
);
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
const branch = readSessionBranch(sessionFile);
|
|
217
|
+
if (!branch || branch.length === 0) {
|
|
218
|
+
ctx.ui.notify(
|
|
219
|
+
`[rpiv-workflow] death-scene artifact skipped: empty transcript for stage "${audit.stageName}"`,
|
|
220
|
+
"warning",
|
|
221
|
+
);
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
const scene = extractDeathScene(audit, errMsg, branch, sessionFile);
|
|
225
|
+
const artifactPath = deathSceneFilePath(audit.cwd, audit);
|
|
226
|
+
mkdirSync(dirname(artifactPath), { recursive: true });
|
|
227
|
+
writeFileSync(artifactPath, formatDeathScene(scene), "utf8");
|
|
228
|
+
} catch (e) {
|
|
229
|
+
const reason = e instanceof Error ? e.message : String(e);
|
|
230
|
+
ctx.ui.notify(`[rpiv-workflow] death-scene artifact failed: ${reason}`, "warning");
|
|
231
|
+
}
|
|
232
|
+
}
|
package/docs/embedding.md
CHANGED
|
@@ -280,7 +280,7 @@ The same bundle shape is accepted per-call as `RunWorkflowOptions.lifecycle`.
|
|
|
280
280
|
| `onStageEnd(stage, output, ctx)` | After the stage's success row lands; `output` is the validated envelope |
|
|
281
281
|
| `onStageRetry(stage, attempt, ctx)` | After an `outputSchema` rejection, before the re-prompt; `attempt` is 1-based |
|
|
282
282
|
| `onStageError(stage, error, ctx)` | After a `"failed"` / `"aborted"` row lands. Terminal for the run |
|
|
283
|
-
| `onRoute(from, to, ctx
|
|
283
|
+
| `onRoute(from, to, ctx)` | After an `EdgeFn` picks and its routing row lands. `to` may be the `"stop"` sentinel |
|
|
284
284
|
| `onLoopStart(stage, info, ctx)` | After `onStageStart`, before unit 1 (after the unit list is computed for fan-out) |
|
|
285
285
|
| `onUnitStart(stage, unit, ctx)` | Per unit, before the unit's session opens — produce **and** judge units |
|
|
286
286
|
| `onUnitEnd(stage, unit, output, ctx)` | Per unit, after the unit's row lands. Loop units never fire `onStageEnd` |
|
package/events.ts
CHANGED
|
@@ -47,21 +47,6 @@ export interface LifecycleContext {
|
|
|
47
47
|
/** What triggered this run; defaulted at `runWorkflow` entry if `options.trigger` was omitted. */
|
|
48
48
|
trigger: RunTrigger;
|
|
49
49
|
state: RunView;
|
|
50
|
-
/**
|
|
51
|
-
* Distinct stage names already executed in this run — the engine's
|
|
52
|
-
* authoritative `RunContext.visited`, RECONSTRUCTED from the JSONL trail on a
|
|
53
|
-
* resume. Populated only on the run-level projection (`lifecycleCtxFor`, which
|
|
54
|
-
* backs `onWorkflowStart`/`onWorkflowEnd`, script-stage `onStageStart`, and the
|
|
55
|
-
* loop/route fires); UNDEFINED on session-fired events (`lifecycleCtxFromSession`
|
|
56
|
-
* carries `runIdentity` only, never the live visited set).
|
|
57
|
-
*
|
|
58
|
-
* Exists so a status-line bridge can SEED its own distinct-visited accumulator
|
|
59
|
-
* at `onWorkflowStart`: a resumed run kicks the chain at its reconstructed walk
|
|
60
|
-
* position (a deep `stageNumber`), but only re-fires per-stage events from that
|
|
61
|
-
* point forward — without this, the bridge would recount `visited` from zero and
|
|
62
|
-
* a near-done resume would render a misleadingly tiny `visited/totalStages`.
|
|
63
|
-
*/
|
|
64
|
-
visited?: readonly string[];
|
|
65
50
|
}
|
|
66
51
|
|
|
67
52
|
/**
|
|
@@ -185,13 +170,9 @@ export interface LifecycleListeners {
|
|
|
185
170
|
|
|
186
171
|
/**
|
|
187
172
|
* After an `EdgeFn` picks and its routing-decision row lands. `to` may be the
|
|
188
|
-
* `STOP` sentinel literal `"stop"`.
|
|
189
|
-
* not-taken RECOVERY arms — failure loops the chosen arm skipped for good (see
|
|
190
|
-
* `bypassedRecoveryArms` in routing.ts). A progress listener credits them so
|
|
191
|
-
* the bar reaches full while the terminal stage runs; empty for deterministic
|
|
192
|
-
* (string) edges and gates with no loop-back alternative.
|
|
173
|
+
* `STOP` sentinel literal `"stop"`.
|
|
193
174
|
*/
|
|
194
|
-
onRoute?(from: StageRef, to: string, ctx: LifecycleContext
|
|
175
|
+
onRoute?(from: StageRef, to: string, ctx: LifecycleContext): void | Promise<void>;
|
|
195
176
|
|
|
196
177
|
/** After `onStageStart`, before unit 1's session (after the unit list is computed for fanout). */
|
|
197
178
|
onLoopStart?(stage: StageRef, info: LoopStartInfo, ctx: LifecycleContext): void | Promise<void>;
|
|
@@ -330,7 +311,6 @@ export function buildLifecycleContext(args: {
|
|
|
330
311
|
totalStages: number;
|
|
331
312
|
trigger: RunTrigger;
|
|
332
313
|
state: RunView;
|
|
333
|
-
visited?: readonly string[];
|
|
334
314
|
}): LifecycleContext {
|
|
335
315
|
return args;
|
|
336
316
|
}
|
|
@@ -350,7 +330,6 @@ export function lifecycleCtxFor(run: {
|
|
|
350
330
|
totalStages: number;
|
|
351
331
|
trigger: RunTrigger;
|
|
352
332
|
state: RunView;
|
|
353
|
-
visited: ReadonlySet<string>;
|
|
354
333
|
}): LifecycleContext {
|
|
355
334
|
return buildLifecycleContext({
|
|
356
335
|
cwd: run.cwd,
|
|
@@ -359,9 +338,6 @@ export function lifecycleCtxFor(run: {
|
|
|
359
338
|
totalStages: run.totalStages,
|
|
360
339
|
trigger: run.trigger,
|
|
361
340
|
state: run.state,
|
|
362
|
-
// Snapshot the live set — listeners must not mutate the engine's accumulator,
|
|
363
|
-
// and a fired ctx is captured per fire so a later `visited.add` is irrelevant.
|
|
364
|
-
visited: [...run.visited],
|
|
365
341
|
});
|
|
366
342
|
}
|
|
367
343
|
|
package/execution-host.ts
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
*/
|
|
9
9
|
import type { ModelSelection, WorkflowHostContext } from "./host.js";
|
|
10
10
|
import { globalSlot } from "./internal-utils.js";
|
|
11
|
+
import type { BranchEntry } from "./transcript.js";
|
|
11
12
|
|
|
12
13
|
/** What the provider hands back per run: the detached executor, an optional
|
|
13
14
|
* cancellation `signal` (rpiv-pi wires it from `ctx.ui.onTerminalInput`),
|
|
@@ -42,6 +43,14 @@ export interface WorkflowExecutionProvider {
|
|
|
42
43
|
/** Per-stage model resolution (rpiv-pi's resolveStageModel) — threaded onto
|
|
43
44
|
* RunContext.resolveModel so the dispatcher fills each child's ModelSelection. */
|
|
44
45
|
resolveModel?(id: { stage: string; skill: string }): ModelSelection | undefined;
|
|
46
|
+
/** Re-open a persisted child-session JSONL and return its branch
|
|
47
|
+
* (`SessionManager.open(file).getBranch()` on the rpiv-pi side), narrowed
|
|
48
|
+
* to `BranchEntry[]`. Threaded onto `RunContext.readSessionBranch` so the
|
|
49
|
+
* death-scene artifact writer can read the just-failed session's transcript
|
|
50
|
+
* WITHOUT re-querying the live child (which is already torn down). Returns
|
|
51
|
+
* `undefined` on any open/read failure (fail-soft). Absent for programmatic
|
|
52
|
+
* embedders / no provider ⇒ the writer degrades silently. */
|
|
53
|
+
readSessionBranch?(file: string): BranchEntry[] | undefined;
|
|
45
54
|
}
|
|
46
55
|
|
|
47
56
|
// Use the SAME globalThis[Symbol.for(...)] slot mechanism as
|
package/failure-memos.ts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* failure-memos.ts — bounded log of stage/unit failures, surfaced as an
|
|
3
|
+
* additive prompt suffix on every subsequently-built stage/unit session.
|
|
4
|
+
*
|
|
5
|
+
* Two writers feed it: `recordTerminalFailure` (the terminal path — first
|
|
6
|
+
* failure wins) and `recordUnitHalt` (a collect-all fanout soft-halt). The
|
|
7
|
+
* suffix is appended at the two session-construction chokepoints
|
|
8
|
+
* (`buildSingleStageSession` + `buildUnitSession`). Zero memos ⇒ the suffix
|
|
9
|
+
* is `""` ⇒ byte-identical prompt to a clean run.
|
|
10
|
+
*
|
|
11
|
+
* Leaf module: type-only imports of `RunState`/`FailureMemo` (types.js) and
|
|
12
|
+
* `AuditCtx` (audit-ctx.js), value import of `nowIso` (internal-utils.js).
|
|
13
|
+
* No back-edges — the value-import DAG stays acyclic.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import type { AuditCtx } from "./audit-ctx.js";
|
|
17
|
+
import { nowIso } from "./internal-utils.js";
|
|
18
|
+
import type { FailureMemo, RunState } from "./types.js";
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Maximum number of memos retained on `RunState.failureMemos`. The array is
|
|
22
|
+
* bounded so a long collect-all fanout with many failing units does not grow
|
|
23
|
+
* the suffix without limit; the OLDEST entry is dropped when the cap is
|
|
24
|
+
* exceeded. The rendered block lists at most this many, newest-first.
|
|
25
|
+
*/
|
|
26
|
+
export const MAX_FAILURE_MEMOS = 3;
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Maximum character length of a single memo's `errMsg`. Longer messages are
|
|
30
|
+
* truncated to this length with a trailing ellipsis so the prompt suffix stays
|
|
31
|
+
* bounded even when the failure reason is a multi-KB stack trace.
|
|
32
|
+
*/
|
|
33
|
+
export const MAX_FAILURE_MEMO_ERR_LEN = 500;
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Append a failure memo to `state.failureMemos`, bounded by `MAX_FAILURE_MEMOS`
|
|
37
|
+
* (oldest dropped) and with `errMsg` length-bounded by `MAX_FAILURE_MEMO_ERR_LEN`.
|
|
38
|
+
*
|
|
39
|
+
* `stage` resolves to the unit's PARENT (machine identity) for a loop-unit
|
|
40
|
+
* failure and to the audit `stageName` for a non-unit failure. `unitId` is set
|
|
41
|
+
* only for a loop-unit failure (the unit's stable audit id).
|
|
42
|
+
*/
|
|
43
|
+
export function appendFailureMemo(state: RunState, audit: AuditCtx, errMsg: string): void {
|
|
44
|
+
const memo: FailureMemo = {
|
|
45
|
+
stage: audit.unit?.parent ?? audit.stageName,
|
|
46
|
+
...(audit.unit?.id ? { unitId: audit.unit.id } : {}),
|
|
47
|
+
errMsg: truncateErr(errMsg),
|
|
48
|
+
ts: nowIso(),
|
|
49
|
+
};
|
|
50
|
+
state.failureMemos.push(memo);
|
|
51
|
+
if (state.failureMemos.length > MAX_FAILURE_MEMOS) {
|
|
52
|
+
state.failureMemos.shift(); // drop oldest — newest memos win the bounded slot
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Render the additive prompt suffix for `state.failureMemos`, newest-first.
|
|
58
|
+
* Returns `""` when there are no memos so the host prompt is byte-identical to
|
|
59
|
+
* a clean run (no separator, no fence, no newline).
|
|
60
|
+
*/
|
|
61
|
+
export function failureMemoSuffix(state: RunState): string {
|
|
62
|
+
const memos = state.failureMemos;
|
|
63
|
+
if (memos.length === 0) return "";
|
|
64
|
+
const lines = [...memos]
|
|
65
|
+
.reverse()
|
|
66
|
+
.map((m) => `- ${m.unitId ? `${m.stage} (unit ${m.unitId})` : m.stage}: ${m.errMsg}`);
|
|
67
|
+
return `\n\nPrior failures in this run (do not repeat these — the run already tried them and they failed):\n${lines.join("\n")}`;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Truncate `errMsg` to `MAX_FAILURE_MEMO_ERR_LEN` with a trailing ellipsis when longer. */
|
|
71
|
+
function truncateErr(errMsg: string): string {
|
|
72
|
+
if (errMsg.length <= MAX_FAILURE_MEMO_ERR_LEN) return errMsg;
|
|
73
|
+
return `${errMsg.slice(0, MAX_FAILURE_MEMO_ERR_LEN)}…`;
|
|
74
|
+
}
|
package/host.ts
CHANGED
|
@@ -192,4 +192,16 @@ export interface WorkflowSessionContext extends WorkflowHostContext {
|
|
|
192
192
|
* watchdog omits it and every abort stays a plain abort.
|
|
193
193
|
*/
|
|
194
194
|
toolTimeout?(): { reason: string } | undefined;
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Recovery-side twin of `toolTimeout`: clears the recorded verdict so the runner can
|
|
198
|
+
* re-arm the watchdog for the resumed turn's next bash call. Set by a watchdog-equipped
|
|
199
|
+
* host (rpiv-pi) alongside `toolTimeout`. The strike-recovery branch consumes a strike
|
|
200
|
+
* BEFORE calling this, then re-prompts the SAME child; omitting it on a watchdog host
|
|
201
|
+
* would leave a stale verdict that re-halts immediately. Optional + safe to widen: only
|
|
202
|
+
* two implementors of this port exist (the SDK host + the test mock), and a host without
|
|
203
|
+
* a watchdog still routes every abort as a plain abort (the strike branch never fires
|
|
204
|
+
* because `toolTimeout()` returns `undefined`).
|
|
205
|
+
*/
|
|
206
|
+
resetToolTimeout?(): void;
|
|
195
207
|
}
|
package/internal.ts
CHANGED
|
@@ -35,6 +35,7 @@ export { __resetBuiltIns, flushBuiltInProviders, getBuiltIns } from "./built-ins
|
|
|
35
35
|
export { __resetLifecycleRegistry } from "./events.js";
|
|
36
36
|
export { __resetWorkflowExecutionHost } from "./execution-host.js";
|
|
37
37
|
export { __resetLoadCache } from "./load/cache.js";
|
|
38
|
+
export { __resetStrikeBudgets } from "./sessions/bash-strikes.js";
|
|
38
39
|
export {
|
|
39
40
|
__resetSkillContracts,
|
|
40
41
|
buildEffectiveContracts,
|
package/loop-def.ts
CHANGED
|
@@ -216,10 +216,14 @@ export interface FanoutLoop extends LoopCommon {
|
|
|
216
216
|
units: FanoutFn;
|
|
217
217
|
/** Per-fanout concurrency ceiling. Caps in-flight units to
|
|
218
218
|
* `min(concurrency, host maxConcurrency)`; `1` SERIALIZES the loop — the safe
|
|
219
|
-
* model for a
|
|
220
|
-
*
|
|
221
|
-
*
|
|
222
|
-
*
|
|
219
|
+
* model for a fanout whose units mutate SHARED state AND whose write-sets are
|
|
220
|
+
* unknown (so the scheduler cannot derive dep edges and no lane-level scope
|
|
221
|
+
* floor guards the declared set). Absent ⇒ the host cap governs. A fanout
|
|
222
|
+
* whose units carry a declared write-set (`files:`) AND derived `deps` edges
|
|
223
|
+
* AND a lane-level scope floor MAY omit `concurrency`: disjoint-write units run
|
|
224
|
+
* concurrently, a write-overlap edge orders the waves, and the scope floor
|
|
225
|
+
* guards the declared set. Must be an integer ≥ 1 (validated at construction +
|
|
226
|
+
* load). */
|
|
223
227
|
concurrency?: number;
|
|
224
228
|
/** Opt out of collect-all: any unit failure halts the run. Default (absent) ⇒
|
|
225
229
|
* collect-all. Under parallel dispatch, the first failing unit halts the
|
package/loop-kinds.ts
CHANGED
|
@@ -30,6 +30,7 @@ import { decorateStage, runIdentityOf } from "./audit.js";
|
|
|
30
30
|
// reconstruct byte-identical declared-order state regardless of
|
|
31
31
|
// completion/resume order. iterate/assess keep advanceCursor (sequential).
|
|
32
32
|
import { placeFanoutOutput, resolveStagePrompt } from "./chain-state.js";
|
|
33
|
+
import { failureMemoSuffix } from "./failure-memos.js";
|
|
33
34
|
import { type Artifact, handleToString } from "./handle.js";
|
|
34
35
|
import { isPanel, type Judge, type PanelJudge, panelMembers, resolveJudgePrompt } from "./judge.js";
|
|
35
36
|
import { MSG_LOOP_CURSOR_CORRUPT } from "./messages.js";
|
|
@@ -493,7 +494,7 @@ export function buildUnitSession(
|
|
|
493
494
|
cwd: run.cwd,
|
|
494
495
|
runId: run.runId,
|
|
495
496
|
state: run.state,
|
|
496
|
-
prompt: u.prompt,
|
|
497
|
+
prompt: u.prompt + failureMemoSuffix(run.state),
|
|
497
498
|
stageName: decorateStage(e.name, u.tag), // DISPLAY only — machine identity is `unit`
|
|
498
499
|
skill: u.skill,
|
|
499
500
|
lifecycle: run.lifecycle,
|
|
@@ -506,6 +507,8 @@ export function buildUnitSession(
|
|
|
506
507
|
unit: { parent: e.name, role: u.role, index, id: u.id, label: u.label },
|
|
507
508
|
model: run.resolveModel?.({ stage: e.name, skill: u.skill }),
|
|
508
509
|
signal,
|
|
510
|
+
readSessionBranch: run.readSessionBranch,
|
|
511
|
+
worktreeDigest: run.worktreeDigest,
|
|
509
512
|
collectAll: shouldCollectAll(e.loop),
|
|
510
513
|
laneUnitIndex: laneIndexFor(e.loop, index),
|
|
511
514
|
onFailure: undefined,
|