@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.
Files changed (57) hide show
  1. package/audit-ctx.ts +16 -8
  2. package/audit-rows.ts +10 -0
  3. package/audit.ts +48 -26
  4. package/chain-state.ts +26 -1
  5. package/death-scene.ts +232 -0
  6. package/docs/embedding.md +1 -1
  7. package/docs/workflow-authoring.md +2 -2
  8. package/events.ts +3 -27
  9. package/execution-host.ts +9 -0
  10. package/failure-memos.ts +74 -0
  11. package/handle.ts +16 -1
  12. package/host.ts +13 -1
  13. package/internal.ts +1 -0
  14. package/loop-def.ts +9 -5
  15. package/loop-kinds.ts +16 -13
  16. package/loop-parallel.ts +116 -95
  17. package/loop-waves.ts +3 -3
  18. package/loop.ts +46 -43
  19. package/messages.ts +53 -14
  20. package/outcomes/collectors/workspace-diff.ts +3 -3
  21. package/outcomes/git-commit.ts +11 -4
  22. package/output-spec.ts +7 -7
  23. package/package.json +5 -2
  24. package/preview.ts +8 -1
  25. package/registration.ts +8 -3
  26. package/routing.ts +1 -41
  27. package/runner/chain-advance.ts +50 -32
  28. package/runner/errors.ts +1 -1
  29. package/runner/failure.ts +22 -23
  30. package/runner/preflight.ts +3 -6
  31. package/runner/resolve-stage.ts +3 -3
  32. package/runner/resume-entry.ts +5 -5
  33. package/runner/resume-loop.ts +5 -5
  34. package/runner/resume.ts +1 -1
  35. package/runner/run-context.ts +13 -3
  36. package/runner/run-stage.ts +134 -60
  37. package/runner/runner.ts +19 -9
  38. package/runner/script-stage.ts +17 -17
  39. package/sessions/bash-strikes.ts +182 -0
  40. package/sessions/extraction.ts +51 -37
  41. package/sessions/halt-routing.ts +18 -13
  42. package/sessions/index.ts +1 -1
  43. package/sessions/reattach.ts +10 -10
  44. package/sessions/sessions.ts +63 -19
  45. package/sessions/spawn.ts +5 -5
  46. package/sessions/success-persist.ts +9 -3
  47. package/stage-def.ts +2 -2
  48. package/stage-errors.ts +1 -1
  49. package/stage-identity.ts +43 -4
  50. package/state/index.ts +1 -1
  51. package/state/names.ts +1 -1
  52. package/state/reads.ts +1 -1
  53. package/state/state.ts +14 -4
  54. package/state/writes.ts +2 -2
  55. package/transcript.ts +30 -0
  56. package/types.ts +105 -15
  57. package/worktree-digest.ts +148 -0
@@ -1,7 +1,7 @@
1
1
  /**
2
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`).
3
+ * `executeStageSession` is the only public entry (loop units run through it too,
4
+ * threading their identity via `StageSessionContext.unit`).
5
5
  *
6
6
  * Every stage runs in its own detached child session (`spawnChildAndRun`,
7
7
  * spawn.ts); the only surviving policy divergence is the branch offset
@@ -25,7 +25,8 @@
25
25
 
26
26
  import { WorkflowAbortError } from "../internal-utils.js";
27
27
  import { type BranchEntry, classifyStop, readBranch, readSessionRef, type StopSignal } from "../transcript.js";
28
- import type { StageSession, WorkflowHostContext, WorkflowSessionContext } from "../types.js";
28
+ import type { StageSessionContext, WorkflowHostContext, WorkflowSessionContext } from "../types.js";
29
+ import { bashStrikesRemaining, bashTimeoutSteeringMessage, consumeBashStrike } from "./bash-strikes.js";
29
30
  import { produceAndValidateOutput } from "./extraction.js";
30
31
  import { haltStageOrSoftHalt } from "./halt-routing.js";
31
32
  import { branchOffsetFor, resendIntoChild, spawnChildAndRun } from "./spawn.js";
@@ -36,7 +37,7 @@ import { recordStageSuccess } from "./success-persist.js";
36
37
  // ===========================================================================
37
38
 
38
39
  /** Execute one DAG stage (or loop unit) in its own detached child session. */
39
- export async function runStageSession(ctx: WorkflowHostContext, s: StageSession): Promise<void> {
40
+ export async function executeStageSession(ctx: WorkflowHostContext, s: StageSessionContext): Promise<void> {
40
41
  await spawnChildAndRun(ctx, s, (child) => postStage(ctx, child, s));
41
42
  }
42
43
 
@@ -55,13 +56,13 @@ export async function runStageSession(ctx: WorkflowHostContext, s: StageSession)
55
56
  * branch ran under; resume re-applies that persisted value verbatim.
56
57
  */
57
58
  export async function continueStageSession(
58
- obsCtx: WorkflowHostContext,
59
+ observerCtx: WorkflowHostContext,
59
60
  child: WorkflowSessionContext,
60
- s: StageSession,
61
+ s: StageSessionContext,
61
62
  ): Promise<void> {
62
63
  const offset = readBranch(child).length;
63
64
  await resendIntoChild(child, s.prompt);
64
- await postStage(obsCtx, child, s, offset);
65
+ await postStage(observerCtx, child, s, offset);
65
66
  }
66
67
 
67
68
  // ===========================================================================
@@ -73,7 +74,7 @@ export async function continueStageSession(
73
74
  * persist → chain. Exported to the `reattach.ts` companion — a reattached
74
75
  * session's continuation runs this exact pipeline, byte-identical to live.
75
76
  *
76
- * TWO ctxs (detachment): `obsCtx` is the long-lived LAUNCHER/observer ctx the
77
+ * TWO ctxs (detachment): `observerCtx` is the long-lived LAUNCHER/observer ctx the
77
78
  * walk threads — it stays valid across every stage, so the user-facing recording
78
79
  * (success/halt rows + notifications + lifecycle) AND the chain continuation
79
80
  * (`onSuccess` → advance/step, which spawns the NEXT stage's child) all run on
@@ -81,7 +82,7 @@ export async function continueStageSession(
81
82
  * background lane — and which is disposed when the stage ends). `child` is the
82
83
  * in-session ctx: the agent transcript (`readBranch`/`readSessionRef`) and the
83
84
  * validation-retry re-prompt (`produceAndValidateOutput` → `resendIntoChild`)
84
- * read/write through it. Spawning the next stage off `obsCtx` is what keeps the
85
+ * read/write through it. Spawning the next stage off `observerCtx` is what keeps the
85
86
  * launcher the single spawner (no nested-child chain).
86
87
  *
87
88
  * The backing `SessionRef` is captured ONCE at entry — every row this
@@ -89,9 +90,9 @@ export async function continueStageSession(
89
90
  * carries the same provenance value.
90
91
  */
91
92
  export async function postStage(
92
- obsCtx: WorkflowHostContext,
93
+ observerCtx: WorkflowHostContext,
93
94
  child: WorkflowSessionContext,
94
- s: StageSession,
95
+ s: StageSessionContext,
95
96
  // Defaults to the policy-derived offset (fresh ⇒ undefined; resume continue ⇒
96
97
  // the persisted row's value). The live continue body passes the value it
97
98
  // re-derived from the forked branch, which is authoritative there.
@@ -116,27 +117,70 @@ export async function postStage(
116
117
  if (s.signal?.aborted) throw new WorkflowAbortError();
117
118
  if (outcome.stop === "aborted") {
118
119
  const timeout = child.toolTimeout?.();
119
- if (timeout) return haltStageOrSoftHalt(obsCtx, s, { kind: "timeout", reason: timeout.reason }, session);
120
+ if (timeout) {
121
+ // Strike-based recovery: a watchdog tool-timeout is a recoverable tool
122
+ // event INSIDE the live child. While strikes remain, the single-caller
123
+ // helper resets → re-prompts → tail-recurses postStage (offset threaded
124
+ // verbatim); exhaustion falls through to the UNCHANGED soft-halt/terminal
125
+ // seam below, where the failure-row writers (memo + death-scene) fire for free.
126
+ if (consumeBashStrike(s, timeout.reason)) {
127
+ return retryStageAfterBashStrike(observerCtx, child, s, offset, timeout.reason);
128
+ }
129
+ return haltStageOrSoftHalt(observerCtx, s, { kind: "timeout", reason: timeout.reason }, session);
130
+ }
120
131
  throw new WorkflowAbortError();
121
132
  }
122
133
  // Every halt below routes through the single `haltStageOrSoftHalt` gate: a
123
134
  // fanout unit marked `collectAll` records a NON-terminal failed row + a sentinel
124
135
  // 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
136
+ // halt. Recording + the continuation run on observerCtx (the launcher) — the per-stage
126
137
  // child is disposed when the stage ends.
127
- if (outcome.stop !== "stop") return haltStageOrSoftHalt(obsCtx, s, { kind: "stop", stop: outcome.stop }, session);
138
+ if (outcome.stop !== "stop")
139
+ return haltStageOrSoftHalt(observerCtx, s, { kind: "stop", stop: outcome.stop }, session);
128
140
 
129
141
  const result = await produceAndValidateOutput(child, s, outcome.branch, offset);
130
142
  if (result.kind === "fatal")
131
- return haltStageOrSoftHalt(obsCtx, s, { kind: "extraction", message: result.message }, session);
143
+ return haltStageOrSoftHalt(observerCtx, s, { kind: "extraction", message: result.message }, session);
132
144
  if (result.kind === "validation-exhausted")
133
- return haltStageOrSoftHalt(obsCtx, s, { kind: "validation", failureSummary: result.failureSummary }, session);
145
+ return haltStageOrSoftHalt(
146
+ observerCtx,
147
+ s,
148
+ { kind: "validation", failureSummary: result.failureSummary },
149
+ session,
150
+ );
134
151
 
135
- if (!(await recordStageSuccess(obsCtx, s, result.output, session))) return;
152
+ if (!(await recordStageSuccess(observerCtx, s, result.output, session))) return;
136
153
  // The validated Output goes to the continuation directly — loop drivers
137
154
  // 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);
155
+ // observerCtx so the next stage's child is spawned off the launcher.
156
+ await s.onSuccess(observerCtx, result.output);
157
+ }
158
+
159
+ // ===========================================================================
160
+ // STRIKE-ARM RECOVERY — single-caller helper for postStage's watchdog arm
161
+ // ===========================================================================
162
+
163
+ /**
164
+ * Strike-arm recovery: re-arm the watchdog, re-prompt the SAME child with
165
+ * operator-grade steering, then tail-recurse `postStage` (offset threaded
166
+ * verbatim — the exact shape the continue body uses). Called ONLY when
167
+ * `consumeBashStrike(s, reason)` returned true, so this helper performs the
168
+ * reset → re-prompt → tail-recurse sequence byte-identically to the inline arm
169
+ * it replaces; strike exhaustion stays routed by the caller (`postStage`) to
170
+ * the UNCHANGED `haltStageOrSoftHalt({ kind: "timeout" })` seam, where the
171
+ * failure-row writers (memo + death-scene artifact) fire for free.
172
+ */
173
+ async function retryStageAfterBashStrike(
174
+ observerCtx: WorkflowHostContext,
175
+ child: WorkflowSessionContext,
176
+ s: StageSessionContext,
177
+ offset: number | undefined,
178
+ reason: string,
179
+ ): Promise<void> {
180
+ child.resetToolTimeout?.();
181
+ const remaining = bashStrikesRemaining(s);
182
+ await resendIntoChild(child, bashTimeoutSteeringMessage(reason, remaining, remaining === 0));
183
+ return postStage(observerCtx, child, s, offset);
140
184
  }
141
185
 
142
186
  // ===========================================================================
package/sessions/spawn.ts CHANGED
@@ -19,7 +19,7 @@
19
19
  */
20
20
 
21
21
  import type { SessionPolicy } from "../api.js";
22
- import type { StageSession, WorkflowHostContext, WorkflowSessionContext } from "../types.js";
22
+ import type { StageSessionContext, WorkflowHostContext, WorkflowSessionContext } from "../types.js";
23
23
 
24
24
  /**
25
25
  * The per-policy branch offset — fresh ignores the stage-captured value;
@@ -54,7 +54,7 @@ type OpenMode = { reattach: { sessionFile: string } } | { fork: { sessionFile: s
54
54
  */
55
55
  function openChild(
56
56
  ctx: WorkflowHostContext,
57
- s: Pick<StageSession, "prompt" | "model" | "signal" | "laneUnitIndex">,
57
+ s: Pick<StageSessionContext, "prompt" | "model" | "signal" | "laneUnitIndex">,
58
58
  body: (child: WorkflowSessionContext) => Promise<void>,
59
59
  mode?: OpenMode,
60
60
  ): Promise<void> {
@@ -81,7 +81,7 @@ function openChild(
81
81
  */
82
82
  export function spawnChildAndRun(
83
83
  ctx: WorkflowHostContext,
84
- s: Pick<StageSession, "prompt" | "model" | "signal" | "laneUnitIndex">,
84
+ s: Pick<StageSessionContext, "prompt" | "model" | "signal" | "laneUnitIndex">,
85
85
  body: (child: WorkflowSessionContext) => Promise<void>,
86
86
  ): Promise<void> {
87
87
  return openChild(ctx, s, body);
@@ -102,7 +102,7 @@ export function spawnChildAndRun(
102
102
  */
103
103
  export function reattachChildSession(
104
104
  ctx: WorkflowHostContext,
105
- s: Pick<StageSession, "prompt" | "model" | "signal" | "laneUnitIndex">,
105
+ s: Pick<StageSessionContext, "prompt" | "model" | "signal" | "laneUnitIndex">,
106
106
  sessionFile: string,
107
107
  body: (child: WorkflowSessionContext) => Promise<void>,
108
108
  ): Promise<void> {
@@ -127,7 +127,7 @@ export function reattachChildSession(
127
127
  */
128
128
  export function forkChildSession(
129
129
  ctx: WorkflowHostContext,
130
- s: Pick<StageSession, "prompt" | "model" | "signal" | "laneUnitIndex">,
130
+ s: Pick<StageSessionContext, "prompt" | "model" | "signal" | "laneUnitIndex">,
131
131
  sessionFile: string,
132
132
  body: (child: WorkflowSessionContext) => Promise<void>,
133
133
  ): Promise<void> {
@@ -14,7 +14,8 @@ import { persistStageSuccess, rollLastSession } from "../audit-rows.js";
14
14
  import { lifecycleCtxFromSession, skillStageRef, type UnitEvent } from "../events.js";
15
15
  import type { Output } from "../output.js";
16
16
  import type { SessionRef } from "../state/index.js";
17
- import type { StageSession, WorkflowHostContext } from "../types.js";
17
+ import type { StageSessionContext, WorkflowHostContext } from "../types.js";
18
+ import { bashTimeoutStrikeHistory } from "./bash-strikes.js";
18
19
 
19
20
  /**
20
21
  * Returns true on successful write — caller gates `onSuccess` on this so the
@@ -38,10 +39,14 @@ import type { StageSession, WorkflowHostContext } from "../types.js";
38
39
  */
39
40
  export async function recordStageSuccess(
40
41
  ctx: WorkflowHostContext,
41
- s: StageSession,
42
+ s: StageSessionContext,
42
43
  output: Output,
43
44
  session: SessionRef | null,
44
45
  ): Promise<boolean> {
46
+ // The strike history (count + per-strike reasons) lands on the completed
47
+ // row ONLY when the session consumed bash strikes; zero strikes ⇒ undefined ⇒ the
48
+ // spread contributes nothing ⇒ byte-identical row to today.
49
+ const strikeHistory = bashTimeoutStrikeHistory(s);
45
50
  const persisted = persistStageSuccess(
46
51
  s.state,
47
52
  {
@@ -53,6 +58,7 @@ export async function recordStageSuccess(
53
58
  session,
54
59
  unit: s.unit,
55
60
  preAllocated: s.allocatedStageNumber,
61
+ ...(strikeHistory ? { bashTimeoutStrikes: strikeHistory } : {}),
56
62
  },
57
63
  s.stage,
58
64
  );
@@ -83,7 +89,7 @@ export async function recordStageSuccess(
83
89
  }
84
90
 
85
91
  /** Public `UnitEvent` payload from the session's `UnitRef` + dispatched skill. */
86
- export function unitEventOf(s: StageSession): UnitEvent {
92
+ export function unitEventOf(s: StageSessionContext): UnitEvent {
87
93
  const u = s.unit!;
88
94
  return { role: u.role, index: u.index, unitId: u.id, label: u.label, skill: s.skill };
89
95
  }
package/stage-def.ts CHANGED
@@ -515,7 +515,7 @@ function actsScript<TIn = unknown>(opts: ActsScriptOptions<TIn>): StageDef<TIn,
515
515
  // / `{ kind: "stop" }` in routing.ts: no outgoing edge OR explicit `STOP`;
516
516
  // orthogonal to this factory — a `terminal()` stage can route onward, and a
517
517
  // plain stage can be a sink) and SENSE 3 (run-outcome prose — "terminal
518
- // failure/outcome" = a halt that ends the run, e.g. audit.ts `writeFailureRow`).
518
+ // failure/outcome" = a halt that ends the run, e.g. audit.ts `recordFailureRow`).
519
519
  // See the `terminal` export doc below for the full glossary.
520
520
  function terminalFn(overrides: Partial<StageDef> = {}): StageDef {
521
521
  return withDefaults("side-effect", { ...overrides, inheritsArtifacts: false });
@@ -589,7 +589,7 @@ export const acts = Object.assign(actsFn, { script: actsScript, prompt: actsProm
589
589
  * factory — a `terminal()` stage can route onward, a plain stage can be a
590
590
  * sink.
591
591
  * 3. RUN OUTCOME ("terminal failure/outcome" prose, e.g. audit.ts
592
- * `writeFailureRow` / `recordTerminalFailure`): a failure/cancellation/
592
+ * `recordFailureRow` / `recordFatalFailure`): a failure/cancellation/
593
593
  * abort that ends the run.
594
594
  */
595
595
  export const terminal = Object.assign(terminalFn, { script: terminalScript });
package/stage-errors.ts CHANGED
@@ -14,7 +14,7 @@ import type { FailureText } from "./messages.js";
14
14
 
15
15
  /**
16
16
  * Thrown by a preflight check on failure; carries the recorded-row
17
- * attribution + notify/err messages so `runStageOrRecordFailure` can land
17
+ * attribution + notify/err messages so `dispatchStageOrRecordFailure` can land
18
18
  * a uniform JSONL row regardless of which slot tripped.
19
19
  *
20
20
  * `kind` annotates the violation class for diagnostics only — control
package/stage-identity.ts CHANGED
@@ -1,18 +1,23 @@
1
1
  /**
2
2
  * Stage-identity derivations — the pure projections off a `StageDef` that the
3
3
  * runtime and the load-time validators must agree on (effective skill, publish
4
- * name, dispatch-vs-body classification).
4
+ * name, dispatch-vs-body classification, effective output schema).
5
5
  *
6
- * A dependency-free LEAF (imports only `StageDef`/`SkillStage` TYPES): so the
6
+ * A LEAF on internal edges: it imports only TYPES from `./api.js` and
7
+ * `./skill-contract.js`, plus VALUE helpers from `./json-schema.js` (which is
8
+ * itself a leaf — `@standard-schema/spec` + `typebox` only, no internal `./`
9
+ * imports — so this value edge introduces no cycle). That lets the
7
10
  * definition/compile-time context (`load/`, `validate/`, `skill-contracts/harvest`)
8
- * can consume these without importing `chain-state.ts` — a RUNTIME-STATE module
11
+ * consume these without importing `chain-state.ts` — a RUNTIME-STATE module
9
12
  * (it imports `RunState` and houses `applyCompletedStage(state, …)` mutators).
10
13
  * Co-locating these projections there forced a structural edge from the loader +
11
14
  * validators into the execution context, enforced by nothing but convention.
12
15
  * `chain-state.ts` re-exports them so its own runtime callers keep one import.
13
16
  */
14
17
 
15
- import type { SkillStage, StageDef } from "./api.js";
18
+ import type { SkillStage, StageDef, StageSchema } from "./api.js";
19
+ import { isJsonSchemaObject, jsonSchemaToStandard } from "./json-schema.js";
20
+ import type { SkillContractMap } from "./skill-contract.js";
16
21
 
17
22
  /**
18
23
  * Resolve the `state.named` key a produces stage appends its `Output`
@@ -38,6 +43,40 @@ export function resolveSkill(def: StageDef, stageName: string): string {
38
43
  return def.skill ?? stageName;
39
44
  }
40
45
 
46
+ /**
47
+ * Resolve the schema a produces stage's output is validated against: the
48
+ * stage's own `outputSchema` if it declares one (precedence — NOT `??`), else
49
+ * the dispatched skill's contract `produces.data` (sourced from the
50
+ * registered-contract registry threaded onto the session / run).
51
+ *
52
+ * The SINGLE runtime spelling of this predicate. Both RUNTIME call sites
53
+ * consume it — `sessions/extraction.ts` (`shouldValidateOutput` +
54
+ * `retryUntilValid`) and `runner/run-stage.ts` (`gateValidationRedispatch`) — so
55
+ * the two can no longer drift on the precedence order, the contract key, or the
56
+ * fail-soft guard. (The load-time twin in
57
+ * `validate/contract-compat.ts:checkPredicateSchemas` is a separate, stricter
58
+ * `isDispatchingStage`-guarded policy and stays distinct by design.)
59
+ *
60
+ * `resolveSkill(def, stageName)` is the SAME registry key
61
+ * `validate-workflow.ts` and `harvestStageContracts` key the map by — and the
62
+ * same key the prior private twin derived indirectly through `s.skill`
63
+ * (= `resolveSkill` applied once in `resolveStage`).
64
+ *
65
+ * Degrades exactly like the input-side runtime mirror: a non-object /
66
+ * unparseable `produces.data` is treated as absent (no schema), never thrown.
67
+ * Returns `undefined` when neither source supplies a schema.
68
+ */
69
+ export function effectiveOutputSchemaOf(
70
+ def: StageDef,
71
+ stageName: string,
72
+ skillContracts: SkillContractMap | undefined,
73
+ ): StageSchema | undefined {
74
+ if (def.outputSchema) return def.outputSchema;
75
+ const producesData = skillContracts?.get(resolveSkill(def, stageName))?.produces?.data;
76
+ if (!isJsonSchemaObject(producesData)) return undefined;
77
+ return jsonSchemaToStandard(producesData);
78
+ }
79
+
41
80
  /**
42
81
  * A stage dispatches a `/skill:<name>` exactly when it carries neither a `run`
43
82
  * (script body) nor a `prompt` (raw-text body). `fanout`/`iterate` stages carry
package/state/index.ts CHANGED
@@ -16,6 +16,7 @@ export type {
16
16
  WorkflowStage,
17
17
  } from "./state.js";
18
18
  export {
19
+ appendHeader,
19
20
  appendLoopCap,
20
21
  appendRoutingDecision,
21
22
  appendStage,
@@ -40,5 +41,4 @@ export {
40
41
  STATE_SCHEMA_VERSION,
41
42
  stateFilePath,
42
43
  VALID_NAME,
43
- writeHeader,
44
44
  } from "./state.js";
package/state/names.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  *
6
6
  * Internal module — not re-exported from registration.ts. The runner reserves
7
7
  * names through `claimName` (the single in-process door: validate →
8
- * collision-check → persist) BEFORE `writeHeader`. External consumers resolve
8
+ * collision-check → persist) BEFORE `appendHeader`. External consumers resolve
9
9
  * names through `resolveRun`.
10
10
  *
11
11
  * Durability: every write goes through `writeNamesIndex` — temp file +
package/state/reads.ts CHANGED
@@ -27,7 +27,7 @@ import type { LoopCapRow, RoutingDecision, RunSummary, WorkflowHeader, WorkflowS
27
27
  * Reads every line, filters by shape (not position). Header has no
28
28
  * `stageNumber`; routing rows carry `type: "routing"`; stage rows have
29
29
  * `stageNumber: number` and no `type`. Starting at line 0 keeps the first
30
- * stage row recoverable even if a transient writeHeader failure left the
30
+ * stage row recoverable even if a transient appendHeader failure left the
31
31
  * file without its header.
32
32
  *
33
33
  * Each line's `JSON.parse` runs in its own try/catch — a truncated trailing
package/state/state.ts CHANGED
@@ -12,7 +12,7 @@
12
12
  *
13
13
  * Internally split into three modules:
14
14
  * - paths.ts — runsDir + stateFilePath + generateRunId
15
- * - writes.ts — tryAppendJsonl + writeHeader + appendStage +
15
+ * - writes.ts — tryAppendJsonl + appendHeader + appendStage +
16
16
  * appendRoutingDecision
17
17
  * - reads.ts — readLastStage + readAllStages + readRoutingDecisions +
18
18
  * listArtifacts + readHeader + listRuns
@@ -103,12 +103,22 @@ export interface WorkflowStage {
103
103
  output?: Output;
104
104
  /**
105
105
  * Reason a terminal-failure row was written — mirrors the
106
- * `state.termination.error` set by `recordTerminalFailure`. Present
106
+ * `state.termination.error` set by `recordFatalFailure`. Present
107
107
  * only on `status: "failed" | "aborted"` rows; absent on completed /
108
108
  * skipped rows. Persisting it here means post-mortems work from
109
109
  * JSONL alone, without depending on a transient `ctx.ui.notify` toast.
110
110
  */
111
111
  errMsg?: string;
112
+ /**
113
+ * Strike-history observability — present ONLY on a `status: "completed"`
114
+ * row whose session recovered from one or more bash overruns: `count` is the
115
+ * strikes consumed, `reasons` lists each consumed strike's host reason. An
116
+ * ADDITIVE optional field (NOT a new row kind): absent ⇒ `JSON.stringify`
117
+ * drops it ⇒ byte-identical row to pre-feature; the resume fold's
118
+ * shape-filtered readers ignore it (like `errMsg`), so no
119
+ * `STATE_SCHEMA_VERSION` bump.
120
+ */
121
+ bashTimeoutStrikes?: { count: number; reasons: string[] };
112
122
  /**
113
123
  * REQUIRED: the Pi session that backed this activation, or `null` as an
114
124
  * explicit statement that no session was involved (script stages,
@@ -126,7 +136,7 @@ export interface WorkflowStage {
126
136
  /**
127
137
  * Marks a NON-terminal collect-all fanout unit halt (`recordUnitHalt`):
128
138
  * the unit failed but the run survives and a `failedOutput` sentinel fills its
129
- * declared slot. Distinguishes a SOFT halt from a hard `recordTerminalFailure`
139
+ * declared slot. Distinguishes a SOFT halt from a hard `recordFatalFailure`
130
140
  * row (byte-identical otherwise) so the resume fold rebuilds the
131
141
  * sentinel by `unitIndex` rather than re-dispatching the unit. Absent on every
132
142
  * other row (`undefined` is dropped by `JSON.stringify`).
@@ -248,4 +258,4 @@ export {
248
258
  readRoutingDecisions,
249
259
  } from "./reads.js";
250
260
  export { resolveRun } from "./resolve.js";
251
- export { appendLoopCap, appendRoutingDecision, appendStage, writeHeader } from "./writes.js";
261
+ export { appendHeader, appendLoopCap, appendRoutingDecision, appendStage } from "./writes.js";
package/state/writes.ts CHANGED
@@ -7,7 +7,7 @@
7
7
  * swapping the backend means touching all of `state/` (a `RunStore` port
8
8
  * is a known possible follow-up, deliberately deferred).
9
9
  *
10
- * writeHeader — boolean; the runner refuses the run start on failure.
10
+ * appendHeader — boolean; the runner refuses the run start on failure.
11
11
  * appendStage — boolean; allocator gates monotonic counters on it.
12
12
  * appendRoutingDecision — boolean; telemetry-not-state, dropped rows surface up.
13
13
  */
@@ -42,7 +42,7 @@ function tryAppendJsonl(cwd: string, runId: string, row: unknown): boolean {
42
42
  * while stage rows still land — so `runWorkflow` refuses the run start on
43
43
  * false, before anything has executed.
44
44
  */
45
- export function writeHeader(cwd: string, header: WorkflowHeader): boolean {
45
+ export function appendHeader(cwd: string, header: WorkflowHeader): boolean {
46
46
  return tryAppendJsonl(cwd, header.runId, header);
47
47
  }
48
48
 
package/transcript.ts CHANGED
@@ -114,6 +114,36 @@ export function lastAssistantStopReason(branch: BranchEntry[], offsetStart?: num
114
114
  return undefined;
115
115
  }
116
116
 
117
+ /**
118
+ * The concatenated `text` parts of the LAST assistant message in `branch`
119
+ * (reverse scan — the agent's final spoken turn is usually the actionable
120
+ * one), trimmed; `undefined` when the branch has no assistant message or its
121
+ * text parts are empty/absent. Pure — no I/O.
122
+ *
123
+ * Mirrors `lastAssistantStopReason` (`:106`) but joins the message's `text`
124
+ * parts instead of reading its stop reason. Used by the death-scene artifact
125
+ * writer (`death-scene.ts`) to capture the agent's final words at failure time.
126
+ * `offsetStart` — continue-policy stages pass the prior branch length so
127
+ * prior-stage entries don't leak into the result.
128
+ */
129
+ export function lastAssistantText(branch: BranchEntry[], offsetStart?: number): string | undefined {
130
+ const start = Math.max(offsetStart ?? 0, 0);
131
+ for (let i = branch.length - 1; i >= start; i--) {
132
+ const entry = branch[i]!;
133
+ if (entry.type !== "message") continue;
134
+ if (entry.message?.role !== "assistant") continue;
135
+ const content = entry.message.content;
136
+ if (!Array.isArray(content)) return undefined;
137
+ const text = content
138
+ .filter((part) => part.type === "text" && typeof part.text === "string")
139
+ .map((part) => part.text!)
140
+ .join("\n")
141
+ .trim();
142
+ return text.length > 0 ? text : undefined;
143
+ }
144
+ return undefined;
145
+ }
146
+
117
147
  // ---------------------------------------------------------------------------
118
148
  // Shared collector building blocks
119
149
  // ---------------------------------------------------------------------------