@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.
@@ -21,9 +21,10 @@
21
21
  */
22
22
 
23
23
  import type { StageDef, Unit } from "../api.js";
24
- import { failedArgs, notifyPartialArtifacts, runIdentityOf } from "../audit.js";
24
+ import { auditCtxFor, failedArgs, notifyPartialArtifacts, recordTerminalFailure, runIdentityOf } from "../audit.js";
25
25
  import { currentPrimaryArtifact, resolveStagePrompt, stageEntryArgs } from "../chain-state.js";
26
26
  import { lifecycleCtxFor, skillStageRef } from "../events.js";
27
+ import { failureMemoSuffix } from "../failure-memos.js";
27
28
  import { formatError } from "../internal-utils.js";
28
29
  import { announceLoopStart, runLoop } from "../loop.js";
29
30
  import { freezesEntryArgsOf } from "../loop-constructors.js";
@@ -31,6 +32,7 @@ import { buildLoopEntry, freshCursor, type LoopDeps, type LoopEntry } from "../l
31
32
  import { validateUnitDeps } from "../loop-waves.js";
32
33
  import {
33
34
  FAIL_LOOP_CAP_HALT,
35
+ FAIL_VALIDATE_GATE_SKIPPED,
34
36
  FAIL_VERIFY_FAILED,
35
37
  MSG_CONTINUE_FALLBACK,
36
38
  MSG_RESUME_SESSION_FALLBACK,
@@ -38,8 +40,10 @@ import {
38
40
  } from "../messages.js";
39
41
  import { continueStageSession, locateSessionFile, reattachStageSession, runStageSession } from "../sessions/index.js";
40
42
  import { forkChildSession, reattachChildSession } from "../sessions/spawn.js";
43
+ import { effectiveOutputSchemaOf } from "../stage-identity.js";
41
44
  import type { WorkflowStage } from "../state/index.js";
42
45
  import type { RunContext, StageSession, WorkflowHostContext } from "../types.js";
46
+ import { resolveDigest } from "../worktree-digest.js";
43
47
  import { advanceChain, type ChainDeps } from "./chain-advance.js";
44
48
  import { type ChainOutcome, haltChain, recordAbortedAtSeam, recordEntryThrow, withStageEntryGuard } from "./failure.js";
45
49
  import { ensureContractInputValid, ensureInputValid } from "./input-validation.js";
@@ -186,7 +190,7 @@ function buildSingleStageSession(
186
190
  cwd: run.cwd,
187
191
  runId: run.runId,
188
192
  state: run.state,
189
- prompt: prep.prompt,
193
+ prompt: prep.prompt + failureMemoSuffix(run.state),
190
194
  stageName: stage.name,
191
195
  skill: stage.skill,
192
196
  lifecycle: run.lifecycle,
@@ -197,6 +201,8 @@ function buildSingleStageSession(
197
201
  snapshot: prep.snapshot,
198
202
  model: run.resolveModel?.({ stage: stage.name, skill: stage.skill }),
199
203
  signal: run.signal,
204
+ readSessionBranch: run.readSessionBranch,
205
+ worktreeDigest: run.worktreeDigest,
200
206
  branchOffset,
201
207
  onFailure: (freshCtx) => notifyPartialArtifacts(freshCtx, run.cwd, run.runId),
202
208
  onSuccess: (freshCtx) => advance(freshCtx, stage.name, idx, run),
@@ -223,6 +229,63 @@ function announceSingleStageStart(
223
229
  );
224
230
  }
225
231
 
232
+ /**
233
+ * Validation-retry mechanism-2: fail-fast a re-dispatch of a schema-validated
234
+ * produces stage against an UNCHANGED worktree (no observable fix since the last
235
+ * validation failure at the same progress point) — WITHOUT dispatching the
236
+ * session or running preflights. Returns `true` when the stage is halted (the
237
+ * caller short-circuits with `return "halted"`); `false` to proceed.
238
+ *
239
+ * Operator resume is excluded: session-backed resume never reaches
240
+ * `runSingleStage`, and a cold re-run under `trigger.meta.resumedFrom` is
241
+ * bypassed by `isOperatorResume`. The terminal skip carries the failure memo
242
+ * for free through the shared `recordTerminalFailure` writer
243
+ * (`packages/rpiv-workflow/audit.ts:122`). An `undefined` digest (non-repo / git
244
+ * missing) ALWAYS proceeds — degrade on a missing signal, never skip.
245
+ *
246
+ * The qualifying predicate — "a produces stage with an effective output schema"
247
+ * — is the shared `effectiveOutputSchemaOf`
248
+ * (`packages/rpiv-workflow/stage-identity.ts`): the single RUNTIME spelling also
249
+ * consumed by the extraction retry loop (`sessions/extraction.ts`), so the gate
250
+ * and the retry loop agree on what "schema-validated" means and can no longer
251
+ * drift on the precedence order or the contract key.
252
+ */
253
+ export async function gateValidationRedispatch(
254
+ curCtx: WorkflowHostContext,
255
+ stage: ResolvedStage,
256
+ run: RunContext,
257
+ ): Promise<boolean> {
258
+ const isOperatorResume = run.trigger.meta?.resumedFrom !== undefined;
259
+ const qualifies =
260
+ stage.def.kind === "produces" && !!effectiveOutputSchemaOf(stage.def, stage.name, run.skillContracts);
261
+ if (!isOperatorResume && qualifies) {
262
+ const digest = resolveDigest(run.worktreeDigest, run.cwd);
263
+ const baseline = run.state.lastGatedDispatch;
264
+ if (
265
+ baseline &&
266
+ baseline.stage === stage.name &&
267
+ digest !== undefined &&
268
+ digest === baseline.digest &&
269
+ run.state.stagesCompleted === baseline.stagesCompleted
270
+ ) {
271
+ await recordTerminalFailure(
272
+ curCtx,
273
+ auditCtxFor(run, stage.name, stage.skill),
274
+ failedArgs(FAIL_VALIDATE_GATE_SKIPPED(stage.skill)),
275
+ );
276
+ return true;
277
+ }
278
+ // Overwrite the baseline on every qualifying dispatch with a defined
279
+ // digest, so the NEXT dispatch of this stage compares against the most
280
+ // recent state (the "tree changed" / "fix ran" proceed arms both land
281
+ // here after the non-matching halt check above).
282
+ if (digest !== undefined) {
283
+ run.state.lastGatedDispatch = { stage: stage.name, digest, stagesCompleted: run.state.stagesCompleted };
284
+ }
285
+ }
286
+ return false;
287
+ }
288
+
226
289
  /**
227
290
  * The single-session path (prompt + skill dispatch): preflights → prompt
228
291
  * prep → input validation → snapshot → session.
@@ -242,6 +305,12 @@ async function runSingleStage(
242
305
  idx: number,
243
306
  run: RunContext,
244
307
  ): Promise<ChainOutcome> {
308
+ // Validation-retry mechanism-2 lives in `gateValidationRedispatch` (above) —
309
+ // fail-fast an unchanged-tree re-dispatch of a schema-validated produces
310
+ // stage BEFORE preflights or the session open. `true` ⇒ already recorded a
311
+ // terminal failure row; halt here.
312
+ if (await gateValidationRedispatch(curCtx, stage, run)) return "halted";
313
+
245
314
  const prep = await prepareSingleStage(curCtx, stage, idx, run);
246
315
 
247
316
  // onStageStart fires after preflight, before the Pi session opens.
package/runner/runner.ts CHANGED
@@ -43,6 +43,7 @@ import {
43
43
  writeHeader,
44
44
  } from "../state/index.js";
45
45
  import { childSessionsDir } from "../state/paths.js";
46
+ import type { BranchEntry } from "../transcript.js";
46
47
  import { DEFAULT_TRIGGER } from "../triggers.js";
47
48
  import type { RunContext, RunWorkflowOptions, RunWorkflowResult } from "../types.js";
48
49
  import { reconstructState } from "./resume.js";
@@ -120,6 +121,7 @@ function referencedSessionIds(run: RunContext): Set<string> {
120
121
  interface DetachedExecutor {
121
122
  execCtx: WorkflowHostContext;
122
123
  resolveModel?: (id: { stage: string; skill: string }) => ModelSelection | undefined;
124
+ readSessionBranch?: (file: string) => BranchEntry[] | undefined;
123
125
  signal?: AbortSignal;
124
126
  dispose?: () => void;
125
127
  }
@@ -148,6 +150,7 @@ async function detachExecutor(
148
150
  runId: string,
149
151
  options: {
150
152
  resolveModel?: (id: { stage: string; skill: string }) => ModelSelection | undefined;
153
+ readSessionBranch?: (file: string) => BranchEntry[] | undefined;
151
154
  signal?: AbortSignal;
152
155
  name?: string; // lane display name (run --name ?? workflow name)
153
156
  /** Workflow name (the dock's dim `workflow:` tag); threaded from workflow.name / header.workflow. */
@@ -157,7 +160,13 @@ async function detachExecutor(
157
160
  },
158
161
  ): Promise<DetachedExecutor> {
159
162
  const provider = getWorkflowExecutionProvider();
160
- if (!provider) return { execCtx: ctx, resolveModel: options.resolveModel, signal: options.signal };
163
+ if (!provider)
164
+ return {
165
+ execCtx: ctx,
166
+ resolveModel: options.resolveModel,
167
+ readSessionBranch: options.readSessionBranch,
168
+ signal: options.signal,
169
+ };
161
170
  // Resolve the run-scoped session dir here (internal layout helper) and hand the
162
171
  // provider a concrete string; rpiv-pi never imports childSessionsDir.
163
172
  const exec = await provider.createHost(ctx, {
@@ -171,6 +180,7 @@ async function detachExecutor(
171
180
  execCtx: exec.host,
172
181
  dispose: exec.dispose,
173
182
  resolveModel: options.resolveModel ?? provider.resolveModel,
183
+ readSessionBranch: options.readSessionBranch ?? provider.readSessionBranch,
174
184
  signal: options.signal ?? exec.signal, // provider-owned abort handle
175
185
  };
176
186
  }
@@ -237,7 +247,7 @@ export async function runWorkflow(ctx: WorkflowHostContext, options: RunWorkflow
237
247
  }
238
248
 
239
249
  // Detach to the executor host (the executor relays UI back to the live session).
240
- const { execCtx, resolveModel, signal, dispose } = await detachExecutor(ctx, cwd, runId, {
250
+ const { execCtx, resolveModel, readSessionBranch, signal, dispose } = await detachExecutor(ctx, cwd, runId, {
241
251
  ...options,
242
252
  name: options.name ?? workflow.name,
243
253
  workflow: workflow.name,
@@ -251,7 +261,7 @@ export async function runWorkflow(ctx: WorkflowHostContext, options: RunWorkflow
251
261
  const run = buildRunContext(
252
262
  cwd,
253
263
  workflow,
254
- { ...options, resolveModel, signal },
264
+ { ...options, resolveModel, readSessionBranch, signal },
255
265
  {
256
266
  runId,
257
267
  state: freshRunState(options.input),
@@ -324,7 +334,7 @@ export async function resumeWorkflow(
324
334
  // pending-fanout re-dispatch, or a cold-routed continue fork) runs against the
325
335
  // real executor, not the bare launcher ctx. Same run id ⇒ same childSessionsDir,
326
336
  // so reattach/fork resolve the original run's persisted child sessions.
327
- const { execCtx, resolveModel, signal, dispose } = await detachExecutor(ctx, cwd, header.runId, {
337
+ const { execCtx, resolveModel, readSessionBranch, signal, dispose } = await detachExecutor(ctx, cwd, header.runId, {
328
338
  ...options,
329
339
  name: header.name ?? header.workflow,
330
340
  workflow: header.workflow,
@@ -337,7 +347,7 @@ export async function resumeWorkflow(
337
347
  const run = buildRunContext(
338
348
  cwd,
339
349
  workflow,
340
- { ...options, resolveModel, signal },
350
+ { ...options, resolveModel, readSessionBranch, signal },
341
351
  {
342
352
  runId: header.runId, // SAME run — new rows append to the same file
343
353
  state: recon.state,
@@ -0,0 +1,182 @@
1
+ /**
2
+ * bash-strikes — the per-activation strike-ceiling policy for in-place
3
+ * bash-overrun recovery. A watchdog tool-timeout is a recoverable tool event
4
+ * INSIDE the live (never-failed) child session: while strikes remain, the
5
+ * runner resets the watchdog verdict and re-prompts the SAME child with
6
+ * operator-grade steering, then tail-recurses `postStage`; once strikes are
7
+ * exhausted, the UNCHANGED `haltStageOrSoftHalt({ kind: "timeout" })` seam
8
+ * fires (so the failure-row writers later phases hook still attach for free).
9
+ *
10
+ * This module owns the POLICY + the per-session accounting (the host/watchdog
11
+ * owns only the per-command ceiling + the verdict). The first `process.env`
12
+ * read in rpiv-workflow production: the no-cross-import boundary forbids
13
+ * value-importing rpiv-pi, so the ceiling override is read here and clamped to
14
+ * `[1,5]` (default 2). Mirrors `resolveBashTimeoutMs` (packages/rpiv-pi/extensions/rpiv-core/bash-timeout.ts:43-48)
15
+ * for the resolve-once-at-module-load pattern.
16
+ *
17
+ * Strike-history observability is satisfied here: each consumed strike appends its
18
+ * reason to the per-session `StrikeBudget` (a module-level WeakMap keyed off
19
+ * session identity), and `bashTimeoutStrikeHistory(s)` surfaces
20
+ * `{ count; reasons }` (or `undefined` at zero strikes) for the completed
21
+ * `WorkflowStage` row to carry — an ADDITIVE optional field, NOT a new row kind
22
+ * (the resume fold's shape-filtered readers ignore it, like errMsg).
23
+ */
24
+
25
+ import type { StageSession } from "../types.js";
26
+
27
+ const DEFAULT_BASH_TIMEOUT_STRIKES = 2; // one retry of a hung command is the operator-grade default.
28
+ const MIN_BASH_TIMEOUT_STRIKES = 1; // at least one strike before any escalation.
29
+ const MAX_BASH_TIMEOUT_STRIKES = 5; // hard cap on in-place retries before a runaway wedges the gate again.
30
+
31
+ /**
32
+ * The resolved per-activation strike ceiling: the default 2, overridable via
33
+ * `RPIV_BASH_TIMEOUT_STRIKES` and clamped to [1,5]. A non-numeric / non-positive
34
+ * override falls back to the default. Strikes are a COUNT, so the parsed value is
35
+ * truncated to an integer before clamping. Resolved once at module load (env is
36
+ * fixed for a process); tests pin an explicit `s.bashTimeoutStrikes` override
37
+ * instead of mutating env. This is the first `process.env` read in rpiv-workflow
38
+ * production (see the module header above + L3.4-04).
39
+ */
40
+ export const BASH_TIMEOUT_STRIKES = resolveBashTimeoutStrikes(process.env.RPIV_BASH_TIMEOUT_STRIKES);
41
+
42
+ export function resolveBashTimeoutStrikes(raw: string | undefined): number {
43
+ const parsed = Number(raw);
44
+ if (!Number.isFinite(parsed) || parsed <= 0) return DEFAULT_BASH_TIMEOUT_STRIKES;
45
+ return Math.min(Math.max(Math.trunc(parsed), MIN_BASH_TIMEOUT_STRIKES), MAX_BASH_TIMEOUT_STRIKES);
46
+ }
47
+
48
+ // --- Steering-message guidance (module-owned prose, composed over the host reason) ---
49
+
50
+ /** the command is hung, not merely slow — waiting will not help. */
51
+ const MSG_HUNG_NOT_SLOW =
52
+ "This command appears to be HUNG, not merely slow — continuing to wait will not make it finish.";
53
+
54
+ /** do not rerun the offending command verbatim; it will wedge the same way. */
55
+ const MSG_DO_NOT_RERUN_VERBATIM = "Do NOT rerun the same command verbatim — it will hang again the same way.";
56
+
57
+ /** diagnose the blockage or surface it so the workflow can route around it. */
58
+ const MSG_DIAGNOSE_OR_REPORT =
59
+ "Diagnose the blockage (inspect the code under test, narrow the command's scope, or use a different verification), or report the blockage explicitly in the stage output.";
60
+
61
+ /** final-strike warning — one more identical overrun fails this activation. */
62
+ const MSG_FINAL_STRIKE =
63
+ "WARNING: rerunning the same command again will consume the FINAL strike and fail this stage/unit.";
64
+
65
+ /**
66
+ * Compose the steering message resent into the recovering child. The host's
67
+ * operator-grade `reason` (which already carries the killed-command snippet +
68
+ * ceiling seconds via `bashTimeoutReason`) is echoed verbatim, then the
69
+ * diagnostic guidance prose is APPENDED — the guidance is module-owned and
70
+ * never duplicates the snippet/ceiling (those come only from `reason`).
71
+ * `strikesRemaining` is surfaced; the final-strike warning appears
72
+ * ONLY when `isFinalStrike` (i.e. `strikesRemaining === 0`).
73
+ */
74
+ export function bashTimeoutSteeringMessage(reason: string, strikesRemaining: number, isFinalStrike: boolean): string {
75
+ const lines = [
76
+ reason,
77
+ `Strikes remaining after this one: ${strikesRemaining}.`,
78
+ MSG_HUNG_NOT_SLOW,
79
+ MSG_DO_NOT_RERUN_VERBATIM,
80
+ MSG_DIAGNOSE_OR_REPORT,
81
+ ];
82
+ if (isFinalStrike) lines.push(MSG_FINAL_STRIKE);
83
+ return lines.join("\n\n");
84
+ }
85
+
86
+ // --- Per-session strike accounting (private StrikeBudget, keyed off session identity) ---
87
+
88
+ /**
89
+ * Private per-activation strike budget: the mutable accounting (used counter +
90
+ * reasons accumulator) that previously lived as two fields on `StageSession`.
91
+ * Held in a module-level `WeakMap<StageSession, StrikeBudget>` so the budget
92
+ * survives `postStage`'s tail-recursive recovery self-call
93
+ * (packages/rpiv-workflow/sessions/sessions.ts:134 — same `s` ⇒ same entry ⇒ the
94
+ * incremented counter is visible on the recursive turn) and is fresh on every
95
+ * new `StageSession` for free (no entry ⇒ zero strikes). `ceiling` is resolved
96
+ * ONCE at first consume from the immutable `s.bashTimeoutStrikes ?? BASH_TIMEOUT_STRIKES`
97
+ * override and frozen into the budget.
98
+ */
99
+ interface StrikeBudget {
100
+ readonly ceiling: number;
101
+ used: number;
102
+ reasons: string[];
103
+ }
104
+
105
+ // `let` (not `const`): `__resetStrikeBudgets()` reassigns this to a fresh map —
106
+ // `WeakMap` exposes no `.clear()`. Keyed by session identity (see StrikeBudget above).
107
+ let strikeBudgets: WeakMap<StageSession, StrikeBudget> = new WeakMap();
108
+
109
+ /**
110
+ * The ONLY creator of a `StrikeBudget`: lazily allocated on the first consume,
111
+ * capturing the ceiling once from the immutable per-activation override.
112
+ * `bashStrikesRemaining` and `bashTimeoutStrikeHistory` use a non-creating
113
+ * `.get()` so a clean completion (no consume) allocates nothing — important
114
+ * because `bashTimeoutStrikeHistory` runs on every successful stage inside
115
+ * `recordStageSuccess` (packages/rpiv-workflow/sessions/success-persist.ts:49).
116
+ */
117
+ function budgetForConsume(s: StageSession): StrikeBudget {
118
+ let b = strikeBudgets.get(s);
119
+ if (!b) {
120
+ b = { ceiling: s.bashTimeoutStrikes ?? BASH_TIMEOUT_STRIKES, used: 0, reasons: [] };
121
+ strikeBudgets.set(s, b);
122
+ }
123
+ return b;
124
+ }
125
+
126
+ /**
127
+ * Consume one strike if any remain: increment the budget's `used` and append
128
+ * `reason` to `reasons`, then return `true`. Returns `false` (mutating nothing)
129
+ * when the ceiling is exhausted — the caller then takes the unchanged
130
+ * soft-halt/terminal seam (packages/rpiv-workflow/sessions/sessions.ts:136).
131
+ * Consumes-then-increments: with a default-2 ceiling, strikes 1 and 2 recover;
132
+ * strike 3 returns false. Behavior byte-identical to the pre-encapsulation
133
+ * field-on-session implementation; the `reasons` lazy-init collapses to a plain
134
+ * `push` (the budget initializes `reasons: []`).
135
+ */
136
+ export function consumeBashStrike(s: StageSession, reason: string): boolean {
137
+ const b = budgetForConsume(s);
138
+ if (b.used >= b.ceiling) return false; // exhausted — mutate nothing; caller escalates.
139
+ b.used += 1;
140
+ b.reasons.push(reason);
141
+ return true;
142
+ }
143
+
144
+ /**
145
+ * Strikes remaining AFTER the current consumption (0 on the final-strike resume).
146
+ * Computed from the budget's post-increment counter, so it pairs with
147
+ * `consumeBashStrike` having just run. NON-CREATING `.get()`: a session that
148
+ * never consumed (or has no budget yet) reads its ceiling from the immutable
149
+ * override (the former `bashStrikeCeiling` helper's job — removed — moved into
150
+ * the budget's `ceiling` field + this fallback), allocating nothing.
151
+ */
152
+ export function bashStrikesRemaining(s: StageSession): number {
153
+ const b = strikeBudgets.get(s);
154
+ const ceiling = b?.ceiling ?? s.bashTimeoutStrikes ?? BASH_TIMEOUT_STRIKES;
155
+ return Math.max(0, ceiling - (b?.used ?? 0));
156
+ }
157
+
158
+ /**
159
+ * The strike history for the completed `WorkflowStage` row —
160
+ * `{ count; reasons }` when the session consumed ≥1 strike, else `undefined`
161
+ * (so a clean completion omits the field and the row is byte-identical to today).
162
+ * NON-CREATING `.get()`: "no entry" ≡ "zero strikes" ≡ `undefined` holds by
163
+ * construction (invariant 2's 1st layer), not just by the `used <= 0` guard.
164
+ * `reasons` lists each consumed strike's host reason, in consumption order.
165
+ */
166
+ export function bashTimeoutStrikeHistory(s: StageSession): { count: number; reasons: string[] } | undefined {
167
+ const b = strikeBudgets.get(s);
168
+ if (!b || b.used <= 0) return undefined;
169
+ return { count: b.used, reasons: b.reasons };
170
+ }
171
+
172
+ /**
173
+ * Test-only: reset the module-level `strikeBudgets` WeakMap to a fresh instance.
174
+ * The displaced map becomes unreachable and is GC'd with its entries. Re-exported
175
+ * via `./internal.js` and invoked from `test/setup.ts` `beforeEach` (the
176
+ * module-level-singleton contract; the identity-keyed map cannot leak across
177
+ * tests in practice, but the reset makes the fresh-on-resume guarantee
178
+ * deterministic in the regression test).
179
+ */
180
+ export function __resetStrikeBudgets(): void {
181
+ strikeBudgets = new WeakMap();
182
+ }
@@ -20,11 +20,16 @@ import { allocateStageNumber, currentStageRef } from "../audit.js";
20
20
  import { lifecycleCtxFromSession } from "../events.js";
21
21
  import type { Artifact } from "../handle.js";
22
22
  import { assertNever, formatError, nowIso, withTimeout } from "../internal-utils.js";
23
- import { isJsonSchemaObject, jsonSchemaToStandard } from "../json-schema.js";
24
- import { ERR_COLLECTOR_THREW, ERR_PARSER_THREW, ERR_SCHEMA_TIMEOUT } from "../messages.js";
23
+ import {
24
+ ERR_COLLECTOR_THREW,
25
+ ERR_PARSER_THREW,
26
+ ERR_SCHEMA_TIMEOUT,
27
+ ERR_VALIDATE_RETRY_UNCHANGED,
28
+ } from "../messages.js";
25
29
  import { sideEffectOutcome } from "../outcomes/index.js";
26
30
  import { finalizeOutput, type Output, outputMeta } from "../output.js";
27
31
  import type { CollectCtx, Outcome } from "../output-spec.js";
32
+ import { effectiveOutputSchemaOf } from "../stage-identity.js";
28
33
  import { type BranchEntry, readBranch } from "../transcript.js";
29
34
  import type { StageSession, WorkflowSessionContext } from "../types.js";
30
35
  import {
@@ -41,6 +46,7 @@ import {
41
46
  validateOutputData,
42
47
  } from "../validate-output.js";
43
48
  import { clampRange } from "../validation-bounds.js";
49
+ import { resolveDigest } from "../worktree-digest.js";
44
50
  import { resendIntoChild } from "./spawn.js";
45
51
 
46
52
  /**
@@ -217,28 +223,8 @@ function enforceCompletionContract(
217
223
  return { kind: "ok", output };
218
224
  }
219
225
 
220
- /**
221
- * The schema output is validated against: the stage's own `outputSchema` if it
222
- * declares one, otherwise the dispatched skill's contract `produces.data`
223
- * (sourced from the registered-contract registry threaded onto the session).
224
- *
225
- * Degrades exactly like the input-side runtime mirror (`ensureContractInputValid`):
226
- * a non-object / unparseable `produces.data` is treated as absent (no schema),
227
- * never thrown. Returns `undefined` when neither source supplies a schema.
228
- */
229
- function effectiveOutputSchema(s: StageSession): StageSchema | undefined {
230
- if (s.stage.outputSchema) return s.stage.outputSchema;
231
- // `s.skill` is resolved via `resolveSkill(def, stageName)` in `resolveStage`
232
- // (run-stage.ts), matching the contract map key used by
233
- // `validate-workflow.ts` and `harvestStageContracts`. The single helper
234
- // ensures load-time lint and runtime agree on which contract covers the stage.
235
- const producesData = s.skillContracts?.get(s.skill)?.produces?.data;
236
- if (!isJsonSchemaObject(producesData)) return undefined;
237
- return jsonSchemaToStandard(producesData);
238
- }
239
-
240
226
  function shouldValidateOutput(s: StageSession, output: Output): boolean {
241
- return !!(effectiveOutputSchema(s) && output.data !== undefined);
227
+ return !!(effectiveOutputSchemaOf(s.stage, s.stageName, s.skillContracts) && output.data !== undefined);
242
228
  }
243
229
 
244
230
  interface RetryDeps {
@@ -253,7 +239,7 @@ async function retryUntilValid(
253
239
  deps: RetryDeps,
254
240
  initial: Output,
255
241
  ): Promise<OutputProduction> {
256
- const schema = effectiveOutputSchema(s)!;
242
+ const schema = effectiveOutputSchemaOf(s.stage, s.stageName, s.skillContracts)!;
257
243
  const maxRetries = clampRange(
258
244
  s.stage.maxRetries,
259
245
  MIN_VALIDATION_RETRIES,
@@ -306,6 +292,14 @@ async function retryUntilValid(
306
292
  return { kind: "ok", result: validation.result };
307
293
  },
308
294
  onRetry: async (attempt, failures) => {
295
+ // Validation-retry mechanism-1: capture the worktree digest AT THE FAILED
296
+ // VALIDATE before the agent is re-prompted. Nothing mutates the tree
297
+ // between `validate` failing and `onRetry` opening, so this equals
298
+ // the digest at the failure. Captured per-retry (NOT once before the
299
+ // loop): a later retry's "before" state is the tree AFTER the prior
300
+ // retry's fix, so a single pre-loop baseline would compare against a
301
+ // stale tree and false-abort every later retry.
302
+ const baselineDigest = resolveDigest(s.worktreeDigest, s.cwd);
309
303
  // onStageRetry fires before the agent is re-prompted; `attempt` is 1-based.
310
304
  // Ref shares the activation's ALLOCATOR number (currentStageRef) so
311
305
  // listeners can correlate this retry with the end/error event it
@@ -313,10 +307,23 @@ async function retryUntilValid(
313
307
  await s.lifecycle.fire(ctx, "onStageRetry", currentStageRef(s), attempt, lifecycleCtxFromSession(s));
314
308
  try {
315
309
  await askAgentToFix(ctx, s, attempt, failures, timeoutMs);
316
- return { kind: "ok" };
317
310
  } catch (e) {
318
311
  return { kind: "aborted", abort: { kind: "fatal", message: formatError(e) } };
319
312
  }
313
+ // The agent was asked to fix but changed nothing observable in the
314
+ // worktree (tracked files OR gitignored artifacts under
315
+ // `.rpiv/artifacts/`, both hashed by `computeWorktreeDigest`), so the
316
+ // `produce(attempt)` re-read + re-validate cycle would just re-run the
317
+ // same failing validation — fail fast instead of looping. An unchanged
318
+ // `undefined` digest (non-repo / git missing) ALWAYS proceeds: degrade
319
+ // on a missing signal, never skip.
320
+ if (baselineDigest !== undefined && resolveDigest(s.worktreeDigest, s.cwd) === baselineDigest) {
321
+ return {
322
+ kind: "aborted",
323
+ abort: { kind: "fatal", message: ERR_VALIDATE_RETRY_UNCHANGED(s.skill) },
324
+ };
325
+ }
326
+ return { kind: "ok" };
320
327
  },
321
328
  },
322
329
  );
@@ -189,6 +189,11 @@ const auditFor = (s: StageSession, session: SessionRef | null): AuditCtx => ({
189
189
  // The activation's pre-allocated stage number (set once output production
190
190
  // began) — a failure row reuses it instead of burning a second number.
191
191
  allocatedStageNumber: s.allocatedStageNumber,
192
+ // Host-injected persisted-session branch reader — the death-scene artifact
193
+ // writer reads it off AuditCtx. Absent for programmatic embedders / no
194
+ // provider (the writer degrades silently). Conditional spread keeps the
195
+ // common case (reader present) byte-clean and the no-provider case undefined.
196
+ ...(s.readSessionBranch ? { readSessionBranch: s.readSessionBranch } : {}),
192
197
  // Loop units thread their identity onto failure/cancellation rows so failed
193
198
  // trailers carry the structured fields the resume drift guard consumes.
194
199
  ...(s.unit ? { unit: s.unit } : {}),
@@ -26,6 +26,7 @@
26
26
  import { WorkflowAbortError } from "../internal-utils.js";
27
27
  import { type BranchEntry, classifyStop, readBranch, readSessionRef, type StopSignal } from "../transcript.js";
28
28
  import type { StageSession, 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";
@@ -116,7 +117,17 @@ 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(obsCtx, child, s, offset, timeout.reason);
128
+ }
129
+ return haltStageOrSoftHalt(obsCtx, 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
@@ -139,6 +150,33 @@ export async function postStage(
139
150
  await s.onSuccess(obsCtx, result.output);
140
151
  }
141
152
 
153
+ // ===========================================================================
154
+ // STRIKE-ARM RECOVERY — single-caller helper for postStage's watchdog arm
155
+ // ===========================================================================
156
+
157
+ /**
158
+ * Strike-arm recovery: re-arm the watchdog, re-prompt the SAME child with
159
+ * operator-grade steering, then tail-recurse `postStage` (offset threaded
160
+ * verbatim — the exact shape the continue body uses). Called ONLY when
161
+ * `consumeBashStrike(s, reason)` returned true, so this helper performs the
162
+ * reset → re-prompt → tail-recurse sequence byte-identically to the inline arm
163
+ * it replaces; strike exhaustion stays routed by the caller (`postStage`) to
164
+ * the UNCHANGED `haltStageOrSoftHalt({ kind: "timeout" })` seam, where the
165
+ * failure-row writers (memo + death-scene artifact) fire for free.
166
+ */
167
+ async function retryStageAfterBashStrike(
168
+ obsCtx: WorkflowHostContext,
169
+ child: WorkflowSessionContext,
170
+ s: StageSession,
171
+ offset: number | undefined,
172
+ reason: string,
173
+ ): Promise<void> {
174
+ child.resetToolTimeout?.();
175
+ const remaining = bashStrikesRemaining(s);
176
+ await resendIntoChild(child, bashTimeoutSteeringMessage(reason, remaining, remaining === 0));
177
+ return postStage(obsCtx, child, s, offset);
178
+ }
179
+
142
180
  // ===========================================================================
143
181
  // OUTCOME READER
144
182
  // ===========================================================================
@@ -15,6 +15,7 @@ import { lifecycleCtxFromSession, skillStageRef, type UnitEvent } from "../event
15
15
  import type { Output } from "../output.js";
16
16
  import type { SessionRef } from "../state/index.js";
17
17
  import type { StageSession, 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
@@ -42,6 +43,10 @@ export async function recordStageSuccess(
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
  );
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