@juicesharp/rpiv-workflow 2.1.0 → 2.3.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 +16 -8
- package/audit-rows.ts +10 -0
- package/audit.ts +48 -26
- package/chain-state.ts +26 -1
- package/death-scene.ts +232 -0
- package/docs/embedding.md +1 -1
- package/docs/workflow-authoring.md +2 -2
- package/events.ts +3 -27
- package/execution-host.ts +9 -0
- package/failure-memos.ts +74 -0
- package/handle.ts +16 -1
- package/host.ts +13 -1
- package/internal.ts +1 -0
- package/loop-def.ts +9 -5
- package/loop-kinds.ts +16 -13
- package/loop-parallel.ts +116 -95
- package/loop-waves.ts +3 -3
- package/loop.ts +46 -43
- package/messages.ts +53 -14
- package/outcomes/collectors/workspace-diff.ts +3 -3
- package/outcomes/git-commit.ts +11 -4
- package/output-spec.ts +7 -7
- package/package.json +5 -2
- package/preview.ts +8 -1
- package/registration.ts +8 -3
- package/routing.ts +1 -41
- package/runner/chain-advance.ts +50 -32
- package/runner/errors.ts +1 -1
- package/runner/failure.ts +22 -23
- package/runner/preflight.ts +3 -6
- package/runner/resolve-stage.ts +3 -3
- package/runner/resume-entry.ts +5 -5
- package/runner/resume-loop.ts +5 -5
- package/runner/resume.ts +1 -1
- package/runner/run-context.ts +13 -3
- package/runner/run-stage.ts +134 -60
- package/runner/runner.ts +19 -9
- package/runner/script-stage.ts +17 -17
- package/sessions/bash-strikes.ts +182 -0
- package/sessions/extraction.ts +51 -37
- package/sessions/halt-routing.ts +18 -13
- package/sessions/index.ts +1 -1
- package/sessions/reattach.ts +10 -10
- package/sessions/sessions.ts +63 -19
- package/sessions/spawn.ts +5 -5
- package/sessions/success-persist.ts +9 -3
- package/stage-def.ts +2 -2
- package/stage-errors.ts +1 -1
- package/stage-identity.ts +43 -4
- package/state/index.ts +1 -1
- package/state/names.ts +1 -1
- package/state/reads.ts +1 -1
- package/state/state.ts +14 -4
- package/state/writes.ts +2 -2
- package/transcript.ts +30 -0
- package/types.ts +105 -15
- package/worktree-digest.ts +148 -0
package/audit-ctx.ts
CHANGED
|
@@ -19,10 +19,10 @@ import type { RunContext, SessionContext, UnitRef } from "./types.js";
|
|
|
19
19
|
/**
|
|
20
20
|
* Minimal bookkeeping ctx. Structurally derived from `SessionContext` so any
|
|
21
21
|
* future field added to the base lands here too — no duplicate
|
|
22
|
-
* maintenance. Every `
|
|
22
|
+
* maintenance. Every `StageSessionContext` (single stage or loop unit) collapses to this.
|
|
23
23
|
*
|
|
24
24
|
* `isScript` toggles the `onStageError` ref construction in
|
|
25
|
-
* `
|
|
25
|
+
* `recordFatalFailure` from `skillStageRef` to `scriptStageRef` (the
|
|
26
26
|
* script branch carries no `skill` field). Defaulting to `undefined`
|
|
27
27
|
* preserves the skill-path behaviour for every existing caller.
|
|
28
28
|
*
|
|
@@ -35,9 +35,17 @@ import type { RunContext, SessionContext, UnitRef } from "./types.js";
|
|
|
35
35
|
* lands verbatim on the JSONL row (`WorkflowStage.session`), which is what
|
|
36
36
|
* session-backed resume dispatches on.
|
|
37
37
|
*/
|
|
38
|
-
export type
|
|
38
|
+
export type AuditContext = 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;
|
|
@@ -46,7 +54,7 @@ export type AuditCtx = Pick<
|
|
|
46
54
|
|
|
47
55
|
/**
|
|
48
56
|
* The read-only run identity (`workflow` name + `totalStages` + `trigger`)
|
|
49
|
-
* threaded onto every `SessionContext` and `
|
|
57
|
+
* threaded onto every `SessionContext` and `AuditContext`. Single source for the
|
|
50
58
|
* `runIdentity` sub-literal that session/audit constructions across the runner
|
|
51
59
|
* would otherwise re-spell by hand.
|
|
52
60
|
*/
|
|
@@ -55,7 +63,7 @@ export function runIdentityOf(run: RunContext): SessionContext["runIdentity"] {
|
|
|
55
63
|
}
|
|
56
64
|
|
|
57
65
|
/**
|
|
58
|
-
* Build the `
|
|
66
|
+
* Build the `AuditContext` `recordFatalFailure` needs for a stage failure that
|
|
59
67
|
* escaped a session (preflight halts, downstream throws, routing errors,
|
|
60
68
|
* resume-time refusals). One source for the shape so every halt path records
|
|
61
69
|
* a uniform row. `isScript: true` drops the `skill` field from the JSONL row
|
|
@@ -64,7 +72,7 @@ export function runIdentityOf(run: RunContext): SessionContext["runIdentity"] {
|
|
|
64
72
|
* `session` is pinned to `null` here BY CONSTRUCTION: every caller of this
|
|
65
73
|
* builder records a failure that escaped (or never reached) a session —
|
|
66
74
|
* preflight halts, seam aborts, entry throws, routing errors, resume drift,
|
|
67
|
-
* script halts. In-session writers build their `
|
|
75
|
+
* script halts. In-session writers build their `AuditContext` via `auditFor`
|
|
68
76
|
* (sessions/sessions.ts), which threads the captured `SessionRef`.
|
|
69
77
|
*/
|
|
70
78
|
export function auditCtxFor(
|
|
@@ -72,7 +80,7 @@ export function auditCtxFor(
|
|
|
72
80
|
stageName: string,
|
|
73
81
|
skill: string,
|
|
74
82
|
opts?: { isScript?: boolean; unit?: UnitRef; allocatedStageNumber?: number },
|
|
75
|
-
):
|
|
83
|
+
): AuditContext {
|
|
76
84
|
return {
|
|
77
85
|
cwd: run.cwd,
|
|
78
86
|
runId: run.runId,
|
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
|
@@ -6,9 +6,9 @@
|
|
|
6
6
|
* the `onStageError` lifecycle fire.
|
|
7
7
|
*
|
|
8
8
|
* Depends on audit-rows + audit-ctx + state + messages + events + handle.
|
|
9
|
-
* The pure ctx half (`
|
|
9
|
+
* The pure ctx half (`AuditContext`, `runIdentityOf`, `auditCtxFor`,
|
|
10
10
|
* `currentStageRef`) now lives in `audit-ctx.ts`; the terminal-args builders
|
|
11
|
-
* (`failedArgs`/`abortedArgs`/`
|
|
11
|
+
* (`failedArgs`/`abortedArgs`/`FatalFailureArgs`) live in `messages.ts`.
|
|
12
12
|
* Both are re-exported below so existing audit-layer consumers keep one
|
|
13
13
|
* import site; new code may import `audit-ctx.ts` / `messages.ts` directly.
|
|
14
14
|
* Shared by the runner + sessions; neither imports back. Pure row
|
|
@@ -16,9 +16,11 @@
|
|
|
16
16
|
* `audit-rows.ts`.
|
|
17
17
|
*/
|
|
18
18
|
|
|
19
|
-
import type {
|
|
19
|
+
import type { AuditContext } 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 {
|
|
@@ -28,12 +30,12 @@ import {
|
|
|
28
30
|
FAIL_STAGE_NO_RESPONSE,
|
|
29
31
|
FAIL_STAGE_TOOL_STALLED,
|
|
30
32
|
FAIL_STAGE_TRUNCATED,
|
|
33
|
+
type FatalFailureArgs,
|
|
31
34
|
failedArgs,
|
|
32
35
|
MSG_FAILURE_ROW_DROPPED,
|
|
33
36
|
MSG_PARTIAL_ARTIFACTS,
|
|
34
37
|
MSG_STAGE_FAILED,
|
|
35
38
|
MSG_WORKFLOW_CANCELLED,
|
|
36
|
-
type TerminalFailureArgs,
|
|
37
39
|
} from "./messages.js";
|
|
38
40
|
import { listArtifacts } from "./state/index.js";
|
|
39
41
|
import type { StopSignal } from "./transcript.js";
|
|
@@ -41,20 +43,20 @@ import type { RunState, RunTermination, WorkflowHostContext } from "./types.js";
|
|
|
41
43
|
|
|
42
44
|
// Preserving barrel — the pre-split import surface is unchanged. Consumers
|
|
43
45
|
// (`sessions/`, `runner/`, `loop-kinds`, `loop-parallel`, `internal.ts`,
|
|
44
|
-
// `audit.test.ts`) keep importing `
|
|
45
|
-
// `currentStageRef`/`failedArgs`/`abortedArgs`/`
|
|
46
|
+
// `audit.test.ts`) keep importing `AuditContext`/`runIdentityOf`/`auditCtxFor`/
|
|
47
|
+
// `currentStageRef`/`failedArgs`/`abortedArgs`/`FatalFailureArgs` from
|
|
46
48
|
// "./audit.js" with no edit. Symbols now live in their post-split homes:
|
|
47
|
-
export type {
|
|
49
|
+
export type { AuditContext } from "./audit-ctx.js";
|
|
48
50
|
export { auditCtxFor, currentStageRef, runIdentityOf } from "./audit-ctx.js";
|
|
49
51
|
// Re-export the persistence half so existing audit-layer consumers keep one
|
|
50
52
|
// import site; new code may import audit-rows.js directly.
|
|
51
53
|
export { allocateStageNumber, decorateStage, recordStage, unitRowFields } from "./audit-rows.js";
|
|
52
|
-
export type {
|
|
54
|
+
export type { FatalFailureArgs } from "./messages.js";
|
|
53
55
|
export { abortedArgs, failedArgs } from "./messages.js";
|
|
54
56
|
|
|
55
57
|
/**
|
|
56
58
|
* `state.termination` mutator. Every terminal path — completion
|
|
57
|
-
* (`finalizeWorkflow`), failure/abort (`
|
|
59
|
+
* (`finalizeWorkflow`), failure/abort (`recordFatalFailure`), cancellation
|
|
58
60
|
* (`recordCancellation`), audit-write halts — lands its outcome through here,
|
|
59
61
|
* so the union can never be half-set and a new outcome variant has one
|
|
60
62
|
* write-site to thread through. Last write wins (a failure recorded after an
|
|
@@ -90,7 +92,7 @@ export function notifyPartialArtifacts(ctx: WorkflowHostContext, cwd: string, ru
|
|
|
90
92
|
/**
|
|
91
93
|
* Terminal/halt/cancellation row-write authority. `recordStage` + the
|
|
92
94
|
* dropped-row guard (notify + telemetry) — the side effects the three writers
|
|
93
|
-
* (`
|
|
95
|
+
* (`recordFatalFailure` / `recordUnitHalt` / `recordCancellation`) share.
|
|
94
96
|
* Each caller builds its row fields (terminal `args.status`; halt
|
|
95
97
|
* `collected:true`; cancellation `status:"skipped"`) and delegates the write +
|
|
96
98
|
* guard here, so the dropped-failure-row invariant — a dropped row corrupts
|
|
@@ -104,9 +106,9 @@ export function notifyPartialArtifacts(ctx: WorkflowHostContext, cwd: string, ru
|
|
|
104
106
|
* the graph-sink `edge.mode: "terminal"` (loop-constructors.ts). See the
|
|
105
107
|
* glossary on `stage-def.ts`'s `terminal` export.
|
|
106
108
|
*/
|
|
107
|
-
function
|
|
109
|
+
function recordFailureRow(
|
|
108
110
|
ctx: WorkflowHostContext,
|
|
109
|
-
audit:
|
|
111
|
+
audit: AuditContext,
|
|
110
112
|
row: Parameters<typeof recordStage>[2],
|
|
111
113
|
): number | undefined {
|
|
112
114
|
const written = recordStage(audit.cwd, audit.runId, row, audit.state, audit.allocatedStageNumber);
|
|
@@ -117,10 +119,28 @@ function writeFailureRow(
|
|
|
117
119
|
return written;
|
|
118
120
|
}
|
|
119
121
|
|
|
120
|
-
|
|
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 `recordFailureRow`; the two terminal writers
|
|
127
|
+
* (`recordFatalFailure`, `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: AuditContext, errMsg: string): void {
|
|
136
|
+
appendFailureMemo(audit.state, audit, errMsg);
|
|
137
|
+
writeDeathSceneArtifact(ctx, audit, errMsg);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export async function recordFatalFailure(
|
|
121
141
|
ctx: WorkflowHostContext,
|
|
122
|
-
audit:
|
|
123
|
-
args:
|
|
142
|
+
audit: AuditContext,
|
|
143
|
+
args: FatalFailureArgs,
|
|
124
144
|
onFailure?: (ctx: WorkflowHostContext) => void,
|
|
125
145
|
): Promise<void> {
|
|
126
146
|
// First-failure-wins: under parallel fanout dispatch with
|
|
@@ -131,7 +151,7 @@ export async function recordTerminalFailure(
|
|
|
131
151
|
// Harmless on the sequential path (always `"running"` at the
|
|
132
152
|
// first and only terminal failure).
|
|
133
153
|
if (audit.state.termination.status !== "running") return;
|
|
134
|
-
|
|
154
|
+
recordFailureRow(ctx, audit, {
|
|
135
155
|
stage: audit.stageName,
|
|
136
156
|
// Script-stage failure rows omit `skill` (the row split landed in A.0);
|
|
137
157
|
// skill rows continue to carry it. `undefined` is dropped by JSON.stringify.
|
|
@@ -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 });
|
|
@@ -156,15 +177,15 @@ export async function recordTerminalFailure(
|
|
|
156
177
|
/**
|
|
157
178
|
* Persist a NON-TERMINAL failed unit row (collect-all fanout): the unit halted,
|
|
158
179
|
* but the run survives and the synthesis stage sees a failed slot. Mirrors
|
|
159
|
-
* `
|
|
180
|
+
* `recordFatalFailure`'s `recordStage` write (same unit fields, same
|
|
160
181
|
* pre-allocated number) WITHOUT `terminate()` (the only state mutation it skips)
|
|
161
182
|
* and WITHOUT the `onStageError` fire (this is not a hard fail). The row carries
|
|
162
183
|
* `collected: true` so the resume fold can tell it apart from a hard
|
|
163
|
-
* `
|
|
184
|
+
* `recordFatalFailure` row (byte-identical otherwise) and rebuild the
|
|
164
185
|
* `failedOutput` sentinel by `unitIndex` instead of re-dispatching it.
|
|
165
186
|
*/
|
|
166
|
-
export function recordUnitHalt(ctx: WorkflowHostContext, audit:
|
|
167
|
-
|
|
187
|
+
export function recordUnitHalt(ctx: WorkflowHostContext, audit: AuditContext, errMsg: string): void {
|
|
188
|
+
recordFailureRow(ctx, audit, {
|
|
168
189
|
stage: audit.stageName,
|
|
169
190
|
skill: audit.isScript ? undefined : audit.skill,
|
|
170
191
|
status: "failed",
|
|
@@ -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
|
/**
|
|
@@ -184,15 +206,15 @@ export function recordUnitHalt(ctx: WorkflowHostContext, audit: AuditCtx, errMsg
|
|
|
184
206
|
*/
|
|
185
207
|
export async function recordStopFailure(
|
|
186
208
|
ctx: WorkflowHostContext,
|
|
187
|
-
audit:
|
|
209
|
+
audit: AuditContext,
|
|
188
210
|
stop: Exclude<StopSignal, "stop">,
|
|
189
211
|
errorMessage: string,
|
|
190
212
|
onFailure?: (ctx: WorkflowHostContext) => void,
|
|
191
213
|
): Promise<void> {
|
|
192
|
-
await
|
|
214
|
+
await recordFatalFailure(ctx, audit, stopFailureArgs(audit.skill, stop, errorMessage), onFailure);
|
|
193
215
|
}
|
|
194
216
|
|
|
195
|
-
function stopFailureArgs(skill: string, stop: Exclude<StopSignal, "stop">, errorMessage: string):
|
|
217
|
+
function stopFailureArgs(skill: string, stop: Exclude<StopSignal, "stop">, errorMessage: string): FatalFailureArgs {
|
|
196
218
|
switch (stop) {
|
|
197
219
|
case "aborted":
|
|
198
220
|
return abortedArgs(FAIL_STAGE_ABORTED(skill));
|
|
@@ -209,16 +231,16 @@ function stopFailureArgs(skill: string, stop: Exclude<StopSignal, "stop">, error
|
|
|
209
231
|
}
|
|
210
232
|
}
|
|
211
233
|
|
|
212
|
-
export function recordCancellation(ctx: WorkflowHostContext, audit:
|
|
234
|
+
export function recordCancellation(ctx: WorkflowHostContext, audit: AuditContext): void {
|
|
213
235
|
// Cancellation is a first-class termination outcome: the canonical in-memory
|
|
214
236
|
// name is `RunTermination.status: "cancelled"` (types.ts), but the JSONL row
|
|
215
237
|
// is written with the FROZEN `StageStatus: "skipped"` (state/state.ts) — a
|
|
216
238
|
// deliberate split (the row value is a versioned on-disk contract; renaming
|
|
217
239
|
// it would break resume + every past-run reader). THIS is the sole writer of
|
|
218
240
|
// a `"skipped"` row. `errMsg` is mirrored into the row so post-mortems work
|
|
219
|
-
// from the trail alone (same posture as `
|
|
241
|
+
// from the trail alone (same posture as `recordFatalFailure`).
|
|
220
242
|
const errMsg = `${audit.skill} cancelled by user`;
|
|
221
|
-
|
|
243
|
+
recordFailureRow(ctx, audit, {
|
|
222
244
|
stage: audit.stageName,
|
|
223
245
|
skill: audit.skill,
|
|
224
246
|
status: "skipped",
|
package/chain-state.ts
CHANGED
|
@@ -59,6 +59,17 @@ const usesOriginalInput = (def: StageDef, stageName: string, startStage: string)
|
|
|
59
59
|
const hasReads = (def: StageDef): def is StageDef & { reads: NonNullable<StageDef["reads"]> } =>
|
|
60
60
|
def.reads !== undefined && def.reads.length > 0;
|
|
61
61
|
|
|
62
|
+
/**
|
|
63
|
+
* Separator between the channel `name` and the `handle` in the stageEntryArgs
|
|
64
|
+
* dedup key (`${name}${DEDUP_KEY_SEPARATOR}${handle}`). The NUL byte cannot
|
|
65
|
+
* occur in either half — handles are inline-artifact strings or file paths,
|
|
66
|
+
* and names are channel identifiers — so two distinct (name, handle) pairs
|
|
67
|
+
* ("ab"+"cd" vs "a"+"bcd") can never concatenate into the same key; carrying
|
|
68
|
+
* `name` additionally preserves a cross-name fan-in repeat whose entries
|
|
69
|
+
* share a handle.
|
|
70
|
+
*/
|
|
71
|
+
const DEDUP_KEY_SEPARATOR = "\0";
|
|
72
|
+
|
|
62
73
|
/**
|
|
63
74
|
* The single arg-projection authority: the string a stage's
|
|
64
75
|
* `/skill:<name> <args>` prompt carries, derived purely from
|
|
@@ -83,6 +94,16 @@ export function stageEntryArgs(
|
|
|
83
94
|
if (usesOriginalInput(def, stageName, startStage)) return state.originalInput;
|
|
84
95
|
if (hasReads(def)) {
|
|
85
96
|
const parts: string[] = [];
|
|
97
|
+
// Duplicate-flag dedup: collapse two entries on the SAME channel whose
|
|
98
|
+
// handles stringify identically (the a777 cite-check symptom — a re-run
|
|
99
|
+
// fanout channel re-published the same fs path, emitting a duplicate
|
|
100
|
+
// `--code-cite-check <path>` flag). The key is `${name}${DEDUP_KEY_SEPARATOR}${handle}`:
|
|
101
|
+
// the DEDUP_KEY_SEPARATOR (NUL byte) avoids a concatenation collision (name "ab" + handle
|
|
102
|
+
// "cd" vs "a" + "bcd"), and carrying the channel `name` preserves a fanin
|
|
103
|
+
// repeat whose entries carry DISTINCT paths (e.g. per-cluster subplans) and
|
|
104
|
+
// a multi-artifact entry whose artifacts differ. The set spans every read
|
|
105
|
+
// of the call so two reads of the same name+handle also collapse.
|
|
106
|
+
const seen = new Set<string>();
|
|
86
107
|
for (const read of def.reads) {
|
|
87
108
|
const name = readName(read);
|
|
88
109
|
const slot = state.named[name];
|
|
@@ -105,7 +126,11 @@ export function stageEntryArgs(
|
|
|
105
126
|
for (const entry of entries) {
|
|
106
127
|
if (!entry || isFailedOutput(entry)) continue; // unfilled (pending) or failed → no args
|
|
107
128
|
for (const artifact of entry.artifacts) {
|
|
108
|
-
|
|
129
|
+
const handle = handleToString(artifact.handle);
|
|
130
|
+
const key = `${name}${DEDUP_KEY_SEPARATOR}${handle}`;
|
|
131
|
+
if (seen.has(key)) continue;
|
|
132
|
+
seen.add(key);
|
|
133
|
+
parts.push(`--${name}`, handle);
|
|
109
134
|
}
|
|
110
135
|
}
|
|
111
136
|
}
|
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 (`recordFatalFailure` /
|
|
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
|
+
* `AuditContext.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 `recordFailureRow`)
|
|
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 { AuditContext } 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: AuditContext): 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: AuditContext,
|
|
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 `recordFailureRow`, is never masked.
|
|
194
|
+
*
|
|
195
|
+
* Synchronous by design: the caller (`recordFatalFailure` /
|
|
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: AuditContext, 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` |
|
|
@@ -628,7 +628,7 @@ edges: {
|
|
|
628
628
|
}
|
|
629
629
|
```
|
|
630
630
|
|
|
631
|
-
**No-match is explicit, never silent.** With `opts.fallback` the unmatched value routes there; without one it terminates
|
|
631
|
+
**No-match is explicit, never silent.** With `opts.fallback` the unmatched value routes there; without one it terminates the run as **failed** — the runner records the `stop` routing decision (note included) plus a terminal failure row naming the gate's stage, so the run reads as blocked-awaiting-intervention, never as a completed ✓. Either way the no-match lands a routing-audit `note`.
|
|
632
632
|
|
|
633
633
|
**Routing on a panel's verdict** — `opts.from` reads the field from a named channel's latest output (`state.named[from].at(-1).data[field]`) instead of the stage's projected `output.data`. This is how `match` branches on a [panel](#adversarial-verification-panel)'s published fold (the fold lands on a channel, never on the stage's projected output):
|
|
634
634
|
|
|
@@ -806,7 +806,7 @@ This determines `sessionPolicy`.
|
|
|
806
806
|
| Nothing, and downstream must not inherit | `terminal()` | — | — |
|
|
807
807
|
| Session memory only | Upstream `acts`, downstream `sessionPolicy: "continue"` | — (no outcome on upstream) | — |
|
|
808
808
|
|
|
809
|
-
**When to author a custom collector.** The built-in collectors cover transcript scanning, tool-call observation, filesystem diffing, and git state. If the skill's output pattern doesn't map cleanly to any of these — for example, it writes a structured artifact with frontmatter you want to parse, or it produces an identifier embedded in a branch name — author a custom collector via `defineCollector` and an optional `defineParser`. Custom collectors are first-class; they receive the same `
|
|
809
|
+
**When to author a custom collector.** The built-in collectors cover transcript scanning, tool-call observation, filesystem diffing, and git state. If the skill's output pattern doesn't map cleanly to any of these — for example, it writes a structured artifact with frontmatter you want to parse, or it produces an identifier embedded in a branch name — author a custom collector via `defineCollector` and an optional `defineParser`. Custom collectors are first-class; they receive the same `CollectContext` and emit the same artifact shapes as built-ins.
|
|
810
810
|
|
|
811
811
|
### Validation decision rules
|
|
812
812
|
|