@juicesharp/rpiv-workflow 2.0.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 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
- "cwd" | "runId" | "state" | "stageName" | "skill" | "lifecycle" | "runIdentity" | "allocatedStageNumber"
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
- parts.push(`--${name}`, handleToString(artifact.handle));
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
+ }