@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/runner/script-stage.ts
CHANGED
|
@@ -29,7 +29,7 @@
|
|
|
29
29
|
*/
|
|
30
30
|
|
|
31
31
|
import type { ScriptContext } from "../api.js";
|
|
32
|
-
import { auditCtxFor, failAuditWrite, failedArgs,
|
|
32
|
+
import { auditCtxFor, failAuditWrite, failedArgs, recordFatalFailure } from "../audit.js";
|
|
33
33
|
import { allocateStageNumber, persistStageSuccess } from "../audit-rows.js";
|
|
34
34
|
import { lifecycleCtxFor, scriptStageRef } from "../events.js";
|
|
35
35
|
import type { Artifact } from "../handle.js";
|
|
@@ -49,22 +49,22 @@ import type { ResolvedStage } from "./resolve-stage.js";
|
|
|
49
49
|
/**
|
|
50
50
|
* Drive a script stage: lifecycle-fire `onStageStart`, retry-loop the
|
|
51
51
|
* `run` body against `outputSchema`, then either persist + advance or
|
|
52
|
-
* record a terminal failure. Sole entry point — `
|
|
52
|
+
* record a terminal failure. Sole entry point — `dispatchStage` branches
|
|
53
53
|
* here on `mode === "script"`, passing the composed `advance`.
|
|
54
54
|
*
|
|
55
|
-
* Caller pre-conditions (held by `
|
|
55
|
+
* Caller pre-conditions (held by `dispatchStage`):
|
|
56
56
|
* - `ensureInputValid` already passed.
|
|
57
57
|
* - `mode === "script"` (a script stage cannot carry a `loop`).
|
|
58
58
|
*/
|
|
59
59
|
export async function runScript(
|
|
60
|
-
|
|
60
|
+
hostCtx: WorkflowHostContext,
|
|
61
61
|
stage: ResolvedStage,
|
|
62
62
|
idx: number,
|
|
63
63
|
run: RunContext,
|
|
64
64
|
advance: AdvanceFn,
|
|
65
65
|
): Promise<ChainOutcome> {
|
|
66
66
|
const ref = scriptStageRef(stage.name, stage.stageNumber);
|
|
67
|
-
await run.lifecycle.fire(
|
|
67
|
+
await run.lifecycle.fire(hostCtx, "onStageStart", ref, lifecycleCtxFor(run));
|
|
68
68
|
|
|
69
69
|
const scriptCtx: ScriptContext = {
|
|
70
70
|
cwd: run.cwd,
|
|
@@ -85,7 +85,7 @@ export async function runScript(
|
|
|
85
85
|
},
|
|
86
86
|
{
|
|
87
87
|
produce: async () => {
|
|
88
|
-
const invocation = await invokeRun(
|
|
88
|
+
const invocation = await invokeRun(hostCtx, stage, scriptCtx, run, stageNumber);
|
|
89
89
|
if (!invocation.ok) return { kind: "aborted", abort: "recorded" };
|
|
90
90
|
const output = finalizeOutput(
|
|
91
91
|
invocation.raw,
|
|
@@ -110,7 +110,7 @@ export async function runScript(
|
|
|
110
110
|
};
|
|
111
111
|
},
|
|
112
112
|
onRetry: async (attempt) => {
|
|
113
|
-
await run.lifecycle.fire(
|
|
113
|
+
await run.lifecycle.fire(hostCtx, "onStageRetry", ref, attempt, lifecycleCtxFor(run));
|
|
114
114
|
return { kind: "ok" };
|
|
115
115
|
},
|
|
116
116
|
},
|
|
@@ -119,8 +119,8 @@ export async function runScript(
|
|
|
119
119
|
if (result.kind === "aborted") return "halted";
|
|
120
120
|
if (result.kind === "exhausted") {
|
|
121
121
|
const failureSummary = result.failures.map(describeFailure).join("; ");
|
|
122
|
-
await
|
|
123
|
-
|
|
122
|
+
await recordFatalFailure(
|
|
123
|
+
hostCtx,
|
|
124
124
|
scriptAuditCtx(run, stage, stageNumber),
|
|
125
125
|
failedArgs(FAIL_VALIDATION_EXHAUSTED(stage.name, failureSummary)),
|
|
126
126
|
);
|
|
@@ -137,12 +137,12 @@ export async function runScript(
|
|
|
137
137
|
stage.def,
|
|
138
138
|
);
|
|
139
139
|
if (!persisted) {
|
|
140
|
-
failAuditWrite(
|
|
140
|
+
failAuditWrite(hostCtx, run.state, stage.name);
|
|
141
141
|
return "halted";
|
|
142
142
|
}
|
|
143
143
|
|
|
144
|
-
await run.lifecycle.fire(
|
|
145
|
-
return advance(
|
|
144
|
+
await run.lifecycle.fire(hostCtx, "onStageEnd", ref, output, lifecycleCtxFor(run));
|
|
145
|
+
return advance(hostCtx, stage.name, idx, run);
|
|
146
146
|
}
|
|
147
147
|
|
|
148
148
|
type ScriptInvocationResult =
|
|
@@ -157,7 +157,7 @@ type ScriptInvocationResult =
|
|
|
157
157
|
* failure attributed via `MSG_SCRIPT_THREW` + `ERR_SCRIPT_THREW`.
|
|
158
158
|
*/
|
|
159
159
|
async function invokeRun(
|
|
160
|
-
|
|
160
|
+
hostCtx: WorkflowHostContext,
|
|
161
161
|
stage: ResolvedStage,
|
|
162
162
|
scriptCtx: ScriptContext,
|
|
163
163
|
run: RunContext,
|
|
@@ -172,10 +172,10 @@ async function invokeRun(
|
|
|
172
172
|
return { ok: true, raw };
|
|
173
173
|
} catch (e) {
|
|
174
174
|
const reason = formatError(e);
|
|
175
|
-
// `
|
|
175
|
+
// `recordFatalFailure` fires `onStageError` itself — the caller must
|
|
176
176
|
// not fire a second time on the `ok: false` return.
|
|
177
|
-
await
|
|
178
|
-
|
|
177
|
+
await recordFatalFailure(
|
|
178
|
+
hostCtx,
|
|
179
179
|
scriptAuditCtx(run, stage, stageNumber),
|
|
180
180
|
failedArgs(FAIL_SCRIPT_THREW(stage.name, reason)),
|
|
181
181
|
);
|
|
@@ -184,7 +184,7 @@ async function invokeRun(
|
|
|
184
184
|
}
|
|
185
185
|
|
|
186
186
|
/**
|
|
187
|
-
* Build the `
|
|
187
|
+
* Build the `AuditContext`-shaped object `recordFatalFailure` needs for
|
|
188
188
|
* a script-stage halt. The `skill` field doubles as the lifecycle
|
|
189
189
|
* `onStageError` ref payload — using `stage.name` keeps the failure
|
|
190
190
|
* attribution aligned with the success row's `stage` identity.
|
|
@@ -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 { StageSessionContext } 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 `StageSessionContext`.
|
|
91
|
+
* Held in a module-level `WeakMap<StageSessionContext, 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 `StageSessionContext` 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<StageSessionContext, 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: StageSessionContext): 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: StageSessionContext, 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: StageSessionContext): 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: StageSessionContext): { 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
|
+
}
|
package/sessions/extraction.ts
CHANGED
|
@@ -20,13 +20,18 @@ 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 {
|
|
24
|
-
|
|
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
|
-
import type {
|
|
31
|
+
import type { CollectContext, Outcome } from "../output-spec.js";
|
|
32
|
+
import { effectiveOutputSchemaOf } from "../stage-identity.js";
|
|
28
33
|
import { type BranchEntry, readBranch } from "../transcript.js";
|
|
29
|
-
import type {
|
|
34
|
+
import type { StageSessionContext, WorkflowSessionContext } from "../types.js";
|
|
30
35
|
import {
|
|
31
36
|
DEFAULT_VALIDATION_RETRIES,
|
|
32
37
|
DEFAULT_VALIDATION_RETRY_TIMEOUT_MS,
|
|
@@ -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
|
/**
|
|
@@ -63,7 +69,7 @@ export type OutputProduction =
|
|
|
63
69
|
/** Retry loop re-produces against the latest branch after each fix request. */
|
|
64
70
|
export async function produceAndValidateOutput(
|
|
65
71
|
ctx: WorkflowSessionContext,
|
|
66
|
-
s:
|
|
72
|
+
s: StageSessionContext,
|
|
67
73
|
branch: BranchEntry[],
|
|
68
74
|
branchOffset: number | undefined,
|
|
69
75
|
): Promise<OutputProduction> {
|
|
@@ -101,7 +107,7 @@ function resolveOutcome(stage: StageDef, skill: string): Outcome {
|
|
|
101
107
|
return sideEffectOutcome;
|
|
102
108
|
case "produces":
|
|
103
109
|
throw new Error(
|
|
104
|
-
`
|
|
110
|
+
`dispatchStage: stage "${skill}" has kind "produces" but no \`outcome\` — ` +
|
|
105
111
|
"there is no framework default for produces stages (the `.rpiv/artifacts/` layout is " +
|
|
106
112
|
"an rpiv-pi convention). Either wire `outcome: rpivArtifactMdOutcome` (from @juicesharp/rpiv-pi) " +
|
|
107
113
|
"or supply your own `{ collector, parser? }`.",
|
|
@@ -118,7 +124,11 @@ function resolveOutcome(stage: StageDef, skill: string): Outcome {
|
|
|
118
124
|
* demand via the `branchOffset` field. Initial production and retry
|
|
119
125
|
* production use the same offset value.
|
|
120
126
|
*/
|
|
121
|
-
function buildCollectCtx(
|
|
127
|
+
function buildCollectCtx(
|
|
128
|
+
s: StageSessionContext,
|
|
129
|
+
branch: BranchEntry[],
|
|
130
|
+
branchOffset: number | undefined,
|
|
131
|
+
): CollectContext {
|
|
122
132
|
return {
|
|
123
133
|
cwd: s.cwd,
|
|
124
134
|
runId: s.runId,
|
|
@@ -131,7 +141,10 @@ function buildCollectCtx(s: StageSession, branch: BranchEntry[], branchOffset: n
|
|
|
131
141
|
};
|
|
132
142
|
}
|
|
133
143
|
|
|
134
|
-
function wrapOutput(
|
|
144
|
+
function wrapOutput(
|
|
145
|
+
s: StageSessionContext,
|
|
146
|
+
parts: { kind: string; artifacts: readonly Artifact[]; data: unknown },
|
|
147
|
+
): Output {
|
|
135
148
|
return finalizeOutput(
|
|
136
149
|
parts,
|
|
137
150
|
outputMeta({
|
|
@@ -161,7 +174,7 @@ type RunOutcomeResult = { kind: "ok"; output: Output } | Fatal;
|
|
|
161
174
|
*/
|
|
162
175
|
async function runOutcome(
|
|
163
176
|
outcome: Outcome,
|
|
164
|
-
ctx:
|
|
177
|
+
ctx: CollectContext,
|
|
165
178
|
finalize: (parts: { kind: string; artifacts: readonly Artifact[]; data: unknown }) => Output,
|
|
166
179
|
): Promise<RunOutcomeResult> {
|
|
167
180
|
let collected: Awaited<ReturnType<typeof outcome.collector.collect>>;
|
|
@@ -217,43 +230,23 @@ function enforceCompletionContract(
|
|
|
217
230
|
return { kind: "ok", output };
|
|
218
231
|
}
|
|
219
232
|
|
|
220
|
-
|
|
221
|
-
|
|
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
|
-
function shouldValidateOutput(s: StageSession, output: Output): boolean {
|
|
241
|
-
return !!(effectiveOutputSchema(s) && output.data !== undefined);
|
|
233
|
+
function shouldValidateOutput(s: StageSessionContext, output: Output): boolean {
|
|
234
|
+
return !!(effectiveOutputSchemaOf(s.stage, s.stageName, s.skillContracts) && output.data !== undefined);
|
|
242
235
|
}
|
|
243
236
|
|
|
244
237
|
interface RetryDeps {
|
|
245
238
|
outcome: Outcome;
|
|
246
|
-
collectCtx:
|
|
239
|
+
collectCtx: CollectContext;
|
|
247
240
|
finalize: (parts: { kind: string; artifacts: readonly Artifact[]; data: unknown }) => Output;
|
|
248
241
|
}
|
|
249
242
|
|
|
250
243
|
async function retryUntilValid(
|
|
251
244
|
ctx: WorkflowSessionContext,
|
|
252
|
-
s:
|
|
245
|
+
s: StageSessionContext,
|
|
253
246
|
deps: RetryDeps,
|
|
254
247
|
initial: Output,
|
|
255
248
|
): Promise<OutputProduction> {
|
|
256
|
-
const schema =
|
|
249
|
+
const schema = effectiveOutputSchemaOf(s.stage, s.stageName, s.skillContracts)!;
|
|
257
250
|
const maxRetries = clampRange(
|
|
258
251
|
s.stage.maxRetries,
|
|
259
252
|
MIN_VALIDATION_RETRIES,
|
|
@@ -293,7 +286,7 @@ async function retryUntilValid(
|
|
|
293
286
|
// no contract re-check (both ran before the loop opened).
|
|
294
287
|
if (attempt === 0) return { kind: "ok", value: initial };
|
|
295
288
|
const retryBranch = readBranch(ctx);
|
|
296
|
-
const retryCtx:
|
|
289
|
+
const retryCtx: CollectContext = { ...deps.collectCtx, branch: retryBranch };
|
|
297
290
|
const reRun = await runOutcome(deps.outcome, retryCtx, deps.finalize);
|
|
298
291
|
if (reRun.kind === "fatal") return { kind: "aborted", abort: reRun };
|
|
299
292
|
const contract = enforceCompletionContract(s.stage, s.skill, reRun.output);
|
|
@@ -306,6 +299,14 @@ async function retryUntilValid(
|
|
|
306
299
|
return { kind: "ok", result: validation.result };
|
|
307
300
|
},
|
|
308
301
|
onRetry: async (attempt, failures) => {
|
|
302
|
+
// Validation-retry mechanism-1: capture the worktree digest AT THE FAILED
|
|
303
|
+
// VALIDATE before the agent is re-prompted. Nothing mutates the tree
|
|
304
|
+
// between `validate` failing and `onRetry` opening, so this equals
|
|
305
|
+
// the digest at the failure. Captured per-retry (NOT once before the
|
|
306
|
+
// loop): a later retry's "before" state is the tree AFTER the prior
|
|
307
|
+
// retry's fix, so a single pre-loop baseline would compare against a
|
|
308
|
+
// stale tree and false-abort every later retry.
|
|
309
|
+
const baselineDigest = resolveDigest(s.worktreeDigest, s.cwd);
|
|
309
310
|
// onStageRetry fires before the agent is re-prompted; `attempt` is 1-based.
|
|
310
311
|
// Ref shares the activation's ALLOCATOR number (currentStageRef) so
|
|
311
312
|
// listeners can correlate this retry with the end/error event it
|
|
@@ -313,10 +314,23 @@ async function retryUntilValid(
|
|
|
313
314
|
await s.lifecycle.fire(ctx, "onStageRetry", currentStageRef(s), attempt, lifecycleCtxFromSession(s));
|
|
314
315
|
try {
|
|
315
316
|
await askAgentToFix(ctx, s, attempt, failures, timeoutMs);
|
|
316
|
-
return { kind: "ok" };
|
|
317
317
|
} catch (e) {
|
|
318
318
|
return { kind: "aborted", abort: { kind: "fatal", message: formatError(e) } };
|
|
319
319
|
}
|
|
320
|
+
// The agent was asked to fix but changed nothing observable in the
|
|
321
|
+
// worktree (tracked files OR gitignored artifacts under
|
|
322
|
+
// `.rpiv/artifacts/`, both hashed by `computeWorktreeDigest`), so the
|
|
323
|
+
// `produce(attempt)` re-read + re-validate cycle would just re-run the
|
|
324
|
+
// same failing validation — fail fast instead of looping. An unchanged
|
|
325
|
+
// `undefined` digest (non-repo / git missing) ALWAYS proceeds: degrade
|
|
326
|
+
// on a missing signal, never skip.
|
|
327
|
+
if (baselineDigest !== undefined && resolveDigest(s.worktreeDigest, s.cwd) === baselineDigest) {
|
|
328
|
+
return {
|
|
329
|
+
kind: "aborted",
|
|
330
|
+
abort: { kind: "fatal", message: ERR_VALIDATE_RETRY_UNCHANGED(s.skill) },
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
return { kind: "ok" };
|
|
320
334
|
},
|
|
321
335
|
},
|
|
322
336
|
);
|
|
@@ -365,7 +379,7 @@ async function validateOrFatal(
|
|
|
365
379
|
|
|
366
380
|
async function askAgentToFix(
|
|
367
381
|
ctx: WorkflowSessionContext,
|
|
368
|
-
s:
|
|
382
|
+
s: StageSessionContext,
|
|
369
383
|
attempt: number,
|
|
370
384
|
failures: SchemaValidationFailure[],
|
|
371
385
|
timeoutMs: number,
|
package/sessions/halt-routing.ts
CHANGED
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
* lifecycle signal borrows `unitEventOf` from here).
|
|
16
16
|
*/
|
|
17
17
|
|
|
18
|
-
import { type
|
|
18
|
+
import { type AuditContext, failedArgs, recordFatalFailure, recordStopFailure, recordUnitHalt } from "../audit.js";
|
|
19
19
|
import { allocateStageNumber } from "../audit-rows.js";
|
|
20
20
|
import { lifecycleCtxFromSession, skillStageRef } from "../events.js";
|
|
21
21
|
import { nowIso } from "../internal-utils.js";
|
|
@@ -23,7 +23,7 @@ import { FAIL_VALIDATION_EXHAUSTED, MSG_STAGE_FAILED } from "../messages.js";
|
|
|
23
23
|
import { failedOutput, type OutputMeta, outputMeta } from "../output.js";
|
|
24
24
|
import type { SessionRef } from "../state/index.js";
|
|
25
25
|
import type { StopSignal } from "../transcript.js";
|
|
26
|
-
import type {
|
|
26
|
+
import type { StageSessionContext, WorkflowHostContext } from "../types.js";
|
|
27
27
|
import { unitEventOf } from "./success-persist.js";
|
|
28
28
|
|
|
29
29
|
/**
|
|
@@ -48,7 +48,7 @@ type HaltReason =
|
|
|
48
48
|
*/
|
|
49
49
|
export async function haltStageOrSoftHalt(
|
|
50
50
|
ctx: WorkflowHostContext,
|
|
51
|
-
s:
|
|
51
|
+
s: StageSessionContext,
|
|
52
52
|
reason: HaltReason,
|
|
53
53
|
session: SessionRef | null,
|
|
54
54
|
): Promise<void> {
|
|
@@ -57,7 +57,7 @@ export async function haltStageOrSoftHalt(
|
|
|
57
57
|
}
|
|
58
58
|
|
|
59
59
|
/** Collect-all reason text per arm — byte-identical to the prior inline strings. */
|
|
60
|
-
function softHaltReason(s:
|
|
60
|
+
function softHaltReason(s: StageSessionContext, reason: HaltReason): string {
|
|
61
61
|
switch (reason.kind) {
|
|
62
62
|
case "stop":
|
|
63
63
|
return `${s.skill} stopped (${reason.stop})`;
|
|
@@ -73,7 +73,7 @@ function softHaltReason(s: StageSession, reason: HaltReason): string {
|
|
|
73
73
|
/** Fail-fast terminal halt per arm — dispatches to the existing helpers, unchanged. */
|
|
74
74
|
function failFastHalt(
|
|
75
75
|
ctx: WorkflowHostContext,
|
|
76
|
-
s:
|
|
76
|
+
s: StageSessionContext,
|
|
77
77
|
reason: HaltReason,
|
|
78
78
|
session: SessionRef | null,
|
|
79
79
|
): Promise<void> {
|
|
@@ -93,7 +93,7 @@ function failFastHalt(
|
|
|
93
93
|
|
|
94
94
|
async function haltStage(
|
|
95
95
|
ctx: WorkflowHostContext,
|
|
96
|
-
s:
|
|
96
|
+
s: StageSessionContext,
|
|
97
97
|
stop: Exclude<StopSignal, "stop">,
|
|
98
98
|
session: SessionRef | null,
|
|
99
99
|
): Promise<void> {
|
|
@@ -102,11 +102,11 @@ async function haltStage(
|
|
|
102
102
|
|
|
103
103
|
async function haltStageWithExtractionError(
|
|
104
104
|
ctx: WorkflowHostContext,
|
|
105
|
-
s:
|
|
105
|
+
s: StageSessionContext,
|
|
106
106
|
message: string,
|
|
107
107
|
session: SessionRef | null,
|
|
108
108
|
): Promise<void> {
|
|
109
|
-
await
|
|
109
|
+
await recordFatalFailure(
|
|
110
110
|
ctx,
|
|
111
111
|
auditFor(s, session),
|
|
112
112
|
{ status: "failed", notifyMsg: MSG_STAGE_FAILED(s.skill), notifyLevel: "error", errMsg: message },
|
|
@@ -125,7 +125,7 @@ async function haltStageWithExtractionError(
|
|
|
125
125
|
*/
|
|
126
126
|
async function softHaltUnit(
|
|
127
127
|
ctx: WorkflowHostContext,
|
|
128
|
-
s:
|
|
128
|
+
s: StageSessionContext,
|
|
129
129
|
reason: string,
|
|
130
130
|
session: SessionRef | null,
|
|
131
131
|
): Promise<void> {
|
|
@@ -150,7 +150,7 @@ async function softHaltUnit(
|
|
|
150
150
|
|
|
151
151
|
/** OutputMeta for a sentinel — same stage number the failed row carries, so the
|
|
152
152
|
* live sentinel and the resume-rebuilt one are byte-identical. */
|
|
153
|
-
function outputMetaFor(s:
|
|
153
|
+
function outputMetaFor(s: StageSessionContext): OutputMeta {
|
|
154
154
|
return outputMeta({
|
|
155
155
|
stage: s.stageName,
|
|
156
156
|
skill: s.skill,
|
|
@@ -163,11 +163,11 @@ function outputMetaFor(s: StageSession): OutputMeta {
|
|
|
163
163
|
/** Exported to the `reattach.ts` companion — a promotion's validation-exhausted halt is identical to live. */
|
|
164
164
|
export async function haltStageWithValidationFailure(
|
|
165
165
|
ctx: WorkflowHostContext,
|
|
166
|
-
s:
|
|
166
|
+
s: StageSessionContext,
|
|
167
167
|
failureSummary: string,
|
|
168
168
|
session: SessionRef | null,
|
|
169
169
|
): Promise<void> {
|
|
170
|
-
await
|
|
170
|
+
await recordFatalFailure(
|
|
171
171
|
ctx,
|
|
172
172
|
auditFor(s, session),
|
|
173
173
|
failedArgs(FAIL_VALIDATION_EXHAUSTED(s.skill, failureSummary)),
|
|
@@ -175,7 +175,7 @@ export async function haltStageWithValidationFailure(
|
|
|
175
175
|
);
|
|
176
176
|
}
|
|
177
177
|
|
|
178
|
-
const auditFor = (s:
|
|
178
|
+
const auditFor = (s: StageSessionContext, session: SessionRef | null): AuditContext => ({
|
|
179
179
|
cwd: s.cwd,
|
|
180
180
|
runId: s.runId,
|
|
181
181
|
state: s.state,
|
|
@@ -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 AuditContext. 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 } : {}),
|
package/sessions/index.ts
CHANGED
|
@@ -6,4 +6,4 @@
|
|
|
6
6
|
|
|
7
7
|
export { locateSessionFile, pruneOrphanedChildSessions } from "./locate.js";
|
|
8
8
|
export { reattachStageSession } from "./reattach.js";
|
|
9
|
-
export { continueStageSession,
|
|
9
|
+
export { continueStageSession, executeStageSession } from "./sessions.js";
|
package/sessions/reattach.ts
CHANGED
|
@@ -29,21 +29,21 @@
|
|
|
29
29
|
|
|
30
30
|
import { MSG_RESUME_PROMOTED, MSG_RESUME_REATTACHED, REATTACH_PROMPT } from "../messages.js";
|
|
31
31
|
import { readBranch, readSessionRef } from "../transcript.js";
|
|
32
|
-
import type {
|
|
32
|
+
import type { StageSessionContext, WorkflowHostContext, WorkflowSessionContext } from "../types.js";
|
|
33
33
|
import { produceAndValidateOutput } from "./extraction.js";
|
|
34
34
|
import { haltStageWithValidationFailure } from "./halt-routing.js";
|
|
35
35
|
import { postStage } from "./sessions.js";
|
|
36
36
|
import { branchOffsetFor, resendIntoChild } from "./spawn.js";
|
|
37
37
|
import { recordStageSuccess } from "./success-persist.js";
|
|
38
38
|
|
|
39
|
-
// Same two-ctx split as `postStage`: `
|
|
39
|
+
// Same two-ctx split as `postStage`: `observerCtx` is the long-lived launcher/observer
|
|
40
40
|
// (user-facing notifications + record + the chain continuation that spawns the
|
|
41
41
|
// next stage); `child` is the reopened persisted session (branch reads + the
|
|
42
42
|
// reattach nudge).
|
|
43
43
|
export async function reattachStageSession(
|
|
44
|
-
|
|
44
|
+
observerCtx: WorkflowHostContext,
|
|
45
45
|
child: WorkflowSessionContext,
|
|
46
|
-
s:
|
|
46
|
+
s: StageSessionContext,
|
|
47
47
|
): Promise<void> {
|
|
48
48
|
// Promotion: extraction over the adopted branch, scoped by the SAME
|
|
49
49
|
// offset the interrupted activation ran under (persisted on its row and
|
|
@@ -53,19 +53,19 @@ export async function reattachStageSession(
|
|
|
53
53
|
const result = await produceAndValidateOutput(child, s, readBranch(child), offset);
|
|
54
54
|
|
|
55
55
|
if (result.kind === "ok") {
|
|
56
|
-
|
|
57
|
-
if (!(await recordStageSuccess(
|
|
58
|
-
await s.onSuccess(
|
|
56
|
+
observerCtx.ui.notify(MSG_RESUME_PROMOTED(s.skill), "info");
|
|
57
|
+
if (!(await recordStageSuccess(observerCtx, s, result.output, session))) return;
|
|
58
|
+
await s.onSuccess(observerCtx, result.output);
|
|
59
59
|
return;
|
|
60
60
|
}
|
|
61
61
|
if (result.kind === "validation-exhausted") {
|
|
62
|
-
return haltStageWithValidationFailure(
|
|
62
|
+
return haltStageWithValidationFailure(observerCtx, s, result.failureSummary, session);
|
|
63
63
|
}
|
|
64
64
|
|
|
65
65
|
// Promotion missed (collector-fatal) — reattach: nudge the session from
|
|
66
66
|
// its leaf, let the agent finish with full prior context, then run the
|
|
67
67
|
// standard post-session pipeline.
|
|
68
|
-
|
|
68
|
+
observerCtx.ui.notify(MSG_RESUME_REATTACHED(s.skill), "info");
|
|
69
69
|
await resendIntoChild(child, REATTACH_PROMPT(s.skill));
|
|
70
|
-
await postStage(
|
|
70
|
+
await postStage(observerCtx, child, s);
|
|
71
71
|
}
|