@juicesharp/rpiv-workflow 2.2.0 → 2.3.1
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 +7 -7
- package/audit.ts +29 -29
- package/chain-state.ts +14 -3
- package/death-scene.ts +9 -9
- package/docs/workflow-authoring.md +2 -2
- package/events.ts +1 -1
- package/failure-memos.ts +4 -4
- package/handle.ts +16 -1
- package/host.ts +1 -1
- package/loop-def.ts +1 -1
- package/loop-kinds.ts +134 -91
- package/loop-parallel.ts +15 -15
- package/loop-waves.ts +3 -3
- package/loop.ts +54 -35
- package/messages.ts +30 -17
- package/outcomes/collectors/workspace-diff.ts +3 -3
- package/outcomes/git-commit.ts +11 -4
- package/output-spec.ts +7 -7
- package/package.json +2 -2
- package/preview.ts +8 -1
- package/registration.ts +3 -3
- package/routing.ts +1 -1
- package/runner/chain-advance.ts +66 -26
- package/runner/errors.ts +1 -1
- package/runner/failure.ts +22 -23
- package/runner/preflight.ts +20 -20
- 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 +198 -133
- package/runner/run-stage.ts +111 -88
- package/runner/runner.ts +4 -4
- package/runner/script-stage.ts +17 -17
- package/sessions/bash-strikes.ts +9 -9
- package/sessions/extraction.ts +135 -77
- package/sessions/halt-routing.ts +14 -14
- package/sessions/index.ts +1 -1
- package/sessions/reattach.ts +10 -10
- package/sessions/sessions.ts +93 -53
- package/sessions/spawn.ts +5 -5
- package/sessions/success-persist.ts +3 -3
- package/stage-def.ts +2 -2
- package/stage-errors.ts +1 -1
- package/state/index.ts +1 -1
- package/state/names.ts +1 -1
- package/state/reads.ts +1 -1
- package/state/state.ts +4 -4
- package/state/writes.ts +2 -2
- package/types.ts +16 -16
- package/validate/stage-rules.ts +42 -17
package/sessions/bash-strikes.ts
CHANGED
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
* (the resume fold's shape-filtered readers ignore it, like errMsg).
|
|
23
23
|
*/
|
|
24
24
|
|
|
25
|
-
import type {
|
|
25
|
+
import type { StageSessionContext } from "../types.js";
|
|
26
26
|
|
|
27
27
|
const DEFAULT_BASH_TIMEOUT_STRIKES = 2; // one retry of a hung command is the operator-grade default.
|
|
28
28
|
const MIN_BASH_TIMEOUT_STRIKES = 1; // at least one strike before any escalation.
|
|
@@ -87,12 +87,12 @@ export function bashTimeoutSteeringMessage(reason: string, strikesRemaining: num
|
|
|
87
87
|
|
|
88
88
|
/**
|
|
89
89
|
* Private per-activation strike budget: the mutable accounting (used counter +
|
|
90
|
-
* reasons accumulator) that previously lived as two fields on `
|
|
91
|
-
* Held in a module-level `WeakMap<
|
|
90
|
+
* reasons accumulator) that previously lived as two fields on `StageSessionContext`.
|
|
91
|
+
* Held in a module-level `WeakMap<StageSessionContext, StrikeBudget>` so the budget
|
|
92
92
|
* survives `postStage`'s tail-recursive recovery self-call
|
|
93
93
|
* (packages/rpiv-workflow/sessions/sessions.ts:134 — same `s` ⇒ same entry ⇒ the
|
|
94
94
|
* incremented counter is visible on the recursive turn) and is fresh on every
|
|
95
|
-
* new `
|
|
95
|
+
* new `StageSessionContext` for free (no entry ⇒ zero strikes). `ceiling` is resolved
|
|
96
96
|
* ONCE at first consume from the immutable `s.bashTimeoutStrikes ?? BASH_TIMEOUT_STRIKES`
|
|
97
97
|
* override and frozen into the budget.
|
|
98
98
|
*/
|
|
@@ -104,7 +104,7 @@ interface StrikeBudget {
|
|
|
104
104
|
|
|
105
105
|
// `let` (not `const`): `__resetStrikeBudgets()` reassigns this to a fresh map —
|
|
106
106
|
// `WeakMap` exposes no `.clear()`. Keyed by session identity (see StrikeBudget above).
|
|
107
|
-
let strikeBudgets: WeakMap<
|
|
107
|
+
let strikeBudgets: WeakMap<StageSessionContext, StrikeBudget> = new WeakMap();
|
|
108
108
|
|
|
109
109
|
/**
|
|
110
110
|
* The ONLY creator of a `StrikeBudget`: lazily allocated on the first consume,
|
|
@@ -114,7 +114,7 @@ let strikeBudgets: WeakMap<StageSession, StrikeBudget> = new WeakMap();
|
|
|
114
114
|
* because `bashTimeoutStrikeHistory` runs on every successful stage inside
|
|
115
115
|
* `recordStageSuccess` (packages/rpiv-workflow/sessions/success-persist.ts:49).
|
|
116
116
|
*/
|
|
117
|
-
function budgetForConsume(s:
|
|
117
|
+
function budgetForConsume(s: StageSessionContext): StrikeBudget {
|
|
118
118
|
let b = strikeBudgets.get(s);
|
|
119
119
|
if (!b) {
|
|
120
120
|
b = { ceiling: s.bashTimeoutStrikes ?? BASH_TIMEOUT_STRIKES, used: 0, reasons: [] };
|
|
@@ -133,7 +133,7 @@ function budgetForConsume(s: StageSession): StrikeBudget {
|
|
|
133
133
|
* field-on-session implementation; the `reasons` lazy-init collapses to a plain
|
|
134
134
|
* `push` (the budget initializes `reasons: []`).
|
|
135
135
|
*/
|
|
136
|
-
export function consumeBashStrike(s:
|
|
136
|
+
export function consumeBashStrike(s: StageSessionContext, reason: string): boolean {
|
|
137
137
|
const b = budgetForConsume(s);
|
|
138
138
|
if (b.used >= b.ceiling) return false; // exhausted — mutate nothing; caller escalates.
|
|
139
139
|
b.used += 1;
|
|
@@ -149,7 +149,7 @@ export function consumeBashStrike(s: StageSession, reason: string): boolean {
|
|
|
149
149
|
* override (the former `bashStrikeCeiling` helper's job — removed — moved into
|
|
150
150
|
* the budget's `ceiling` field + this fallback), allocating nothing.
|
|
151
151
|
*/
|
|
152
|
-
export function bashStrikesRemaining(s:
|
|
152
|
+
export function bashStrikesRemaining(s: StageSessionContext): number {
|
|
153
153
|
const b = strikeBudgets.get(s);
|
|
154
154
|
const ceiling = b?.ceiling ?? s.bashTimeoutStrikes ?? BASH_TIMEOUT_STRIKES;
|
|
155
155
|
return Math.max(0, ceiling - (b?.used ?? 0));
|
|
@@ -163,7 +163,7 @@ export function bashStrikesRemaining(s: StageSession): number {
|
|
|
163
163
|
* construction (invariant 2's 1st layer), not just by the `used <= 0` guard.
|
|
164
164
|
* `reasons` lists each consumed strike's host reason, in consumption order.
|
|
165
165
|
*/
|
|
166
|
-
export function bashTimeoutStrikeHistory(s:
|
|
166
|
+
export function bashTimeoutStrikeHistory(s: StageSessionContext): { count: number; reasons: string[] } | undefined {
|
|
167
167
|
const b = strikeBudgets.get(s);
|
|
168
168
|
if (!b || b.used <= 0) return undefined;
|
|
169
169
|
return { count: b.used, reasons: b.reasons };
|
package/sessions/extraction.ts
CHANGED
|
@@ -28,10 +28,10 @@ import {
|
|
|
28
28
|
} from "../messages.js";
|
|
29
29
|
import { sideEffectOutcome } from "../outcomes/index.js";
|
|
30
30
|
import { finalizeOutput, type Output, outputMeta } from "../output.js";
|
|
31
|
-
import type {
|
|
31
|
+
import type { CollectContext, Outcome } from "../output-spec.js";
|
|
32
32
|
import { effectiveOutputSchemaOf } from "../stage-identity.js";
|
|
33
33
|
import { type BranchEntry, readBranch } from "../transcript.js";
|
|
34
|
-
import type {
|
|
34
|
+
import type { StageSessionContext, WorkflowSessionContext } from "../types.js";
|
|
35
35
|
import {
|
|
36
36
|
DEFAULT_VALIDATION_RETRIES,
|
|
37
37
|
DEFAULT_VALIDATION_RETRY_TIMEOUT_MS,
|
|
@@ -69,7 +69,7 @@ export type OutputProduction =
|
|
|
69
69
|
/** Retry loop re-produces against the latest branch after each fix request. */
|
|
70
70
|
export async function produceAndValidateOutput(
|
|
71
71
|
ctx: WorkflowSessionContext,
|
|
72
|
-
s:
|
|
72
|
+
s: StageSessionContext,
|
|
73
73
|
branch: BranchEntry[],
|
|
74
74
|
branchOffset: number | undefined,
|
|
75
75
|
): Promise<OutputProduction> {
|
|
@@ -107,7 +107,7 @@ function resolveOutcome(stage: StageDef, skill: string): Outcome {
|
|
|
107
107
|
return sideEffectOutcome;
|
|
108
108
|
case "produces":
|
|
109
109
|
throw new Error(
|
|
110
|
-
`
|
|
110
|
+
`dispatchStage: stage "${skill}" has kind "produces" but no \`outcome\` — ` +
|
|
111
111
|
"there is no framework default for produces stages (the `.rpiv/artifacts/` layout is " +
|
|
112
112
|
"an rpiv-pi convention). Either wire `outcome: rpivArtifactMdOutcome` (from @juicesharp/rpiv-pi) " +
|
|
113
113
|
"or supply your own `{ collector, parser? }`.",
|
|
@@ -124,7 +124,11 @@ function resolveOutcome(stage: StageDef, skill: string): Outcome {
|
|
|
124
124
|
* demand via the `branchOffset` field. Initial production and retry
|
|
125
125
|
* production use the same offset value.
|
|
126
126
|
*/
|
|
127
|
-
function buildCollectCtx(
|
|
127
|
+
function buildCollectCtx(
|
|
128
|
+
s: StageSessionContext,
|
|
129
|
+
branch: BranchEntry[],
|
|
130
|
+
branchOffset: number | undefined,
|
|
131
|
+
): CollectContext {
|
|
128
132
|
return {
|
|
129
133
|
cwd: s.cwd,
|
|
130
134
|
runId: s.runId,
|
|
@@ -137,7 +141,10 @@ function buildCollectCtx(s: StageSession, branch: BranchEntry[], branchOffset: n
|
|
|
137
141
|
};
|
|
138
142
|
}
|
|
139
143
|
|
|
140
|
-
function wrapOutput(
|
|
144
|
+
function wrapOutput(
|
|
145
|
+
s: StageSessionContext,
|
|
146
|
+
parts: { kind: string; artifacts: readonly Artifact[]; data: unknown },
|
|
147
|
+
): Output {
|
|
141
148
|
return finalizeOutput(
|
|
142
149
|
parts,
|
|
143
150
|
outputMeta({
|
|
@@ -167,7 +174,7 @@ type RunOutcomeResult = { kind: "ok"; output: Output } | Fatal;
|
|
|
167
174
|
*/
|
|
168
175
|
async function runOutcome(
|
|
169
176
|
outcome: Outcome,
|
|
170
|
-
ctx:
|
|
177
|
+
ctx: CollectContext,
|
|
171
178
|
finalize: (parts: { kind: string; artifacts: readonly Artifact[]; data: unknown }) => Output,
|
|
172
179
|
): Promise<RunOutcomeResult> {
|
|
173
180
|
let collected: Awaited<ReturnType<typeof outcome.collector.collect>>;
|
|
@@ -223,19 +230,122 @@ function enforceCompletionContract(
|
|
|
223
230
|
return { kind: "ok", output };
|
|
224
231
|
}
|
|
225
232
|
|
|
226
|
-
function shouldValidateOutput(s:
|
|
233
|
+
function shouldValidateOutput(s: StageSessionContext, output: Output): boolean {
|
|
227
234
|
return !!(effectiveOutputSchemaOf(s.stage, s.stageName, s.skillContracts) && output.data !== undefined);
|
|
228
235
|
}
|
|
229
236
|
|
|
230
|
-
interface RetryDeps {
|
|
237
|
+
export interface RetryDeps {
|
|
231
238
|
outcome: Outcome;
|
|
232
|
-
collectCtx:
|
|
239
|
+
collectCtx: CollectContext;
|
|
233
240
|
finalize: (parts: { kind: string; artifacts: readonly Artifact[]; data: unknown }) => Output;
|
|
234
241
|
}
|
|
235
242
|
|
|
243
|
+
/**
|
|
244
|
+
* Validation-retry mechanism-1 gate: did the worktree stay byte-identical
|
|
245
|
+
* between the failed validate and the post-fix re-read? An UNCHANGED digest
|
|
246
|
+
* means the agent's fix touched nothing observable (tracked files OR
|
|
247
|
+
* gitignored artifacts under `.rpiv/artifacts/`, both hashed by
|
|
248
|
+
* `computeWorktreeDigest`), so the next `produce` → `validate` cycle would
|
|
249
|
+
* re-run the same failing validation — fail fast instead of looping.
|
|
250
|
+
*
|
|
251
|
+
* An `undefined` baseline (non-repo / git missing — `resolveDigest` degrades
|
|
252
|
+
* to `undefined`) ALWAYS proceeds: degrade on a missing signal, never skip.
|
|
253
|
+
*/
|
|
254
|
+
export const worktreeUnchangedSince = (baselineDigest: string | undefined, s: StageSessionContext): boolean =>
|
|
255
|
+
baselineDigest !== undefined && resolveDigest(s.worktreeDigest, s.cwd) === baselineDigest;
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* The retry-loop `produce` hook: re-production of the stage's output.
|
|
259
|
+
*
|
|
260
|
+
* `attempt === 0` is the fast-path — the initial output was already produced
|
|
261
|
+
* and contract-checked before the retry loop opened (`produceAndValidateOutput`
|
|
262
|
+
* ran `runOutcome` + `enforceCompletionContract` once), so it returns the
|
|
263
|
+
* `initial` Output WITHOUT re-collection or re-checking the contract.
|
|
264
|
+
*
|
|
265
|
+
* `attempt > 0` re-reads the branch (the agent's fix landed as new messages),
|
|
266
|
+
* re-runs the collector → parser pipeline (`runOutcome`), and re-checks the
|
|
267
|
+
* completion contract. A fatal collector/parser/contract result maps onto
|
|
268
|
+
* the engine's `{ kind: "aborted" }` arm (the loop halts with that message).
|
|
269
|
+
*/
|
|
270
|
+
export async function produceAttempt(
|
|
271
|
+
ctx: WorkflowSessionContext,
|
|
272
|
+
s: StageSessionContext,
|
|
273
|
+
deps: RetryDeps,
|
|
274
|
+
initial: Output,
|
|
275
|
+
attempt: number,
|
|
276
|
+
): Promise<{ kind: "ok"; value: Output } | { kind: "aborted"; abort: Fatal }> {
|
|
277
|
+
if (attempt === 0) return { kind: "ok", value: initial };
|
|
278
|
+
const retryBranch = readBranch(ctx);
|
|
279
|
+
const retryCtx: CollectContext = { ...deps.collectCtx, branch: retryBranch };
|
|
280
|
+
const reRun = await runOutcome(deps.outcome, retryCtx, deps.finalize);
|
|
281
|
+
if (reRun.kind === "fatal") return { kind: "aborted", abort: reRun };
|
|
282
|
+
const contract = enforceCompletionContract(s.stage, s.skill, reRun.output);
|
|
283
|
+
if (contract.kind === "fatal") return { kind: "aborted", abort: contract };
|
|
284
|
+
return { kind: "ok", value: contract.output };
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* The retry-loop `validate` hook: run the output schema against the produced
|
|
289
|
+
* data, guarded by `timeoutMs` (the same `validateTimeoutMs` budget that
|
|
290
|
+
* bounds `askAgentToFix`). Maps `validateOrFatal`'s `Fatal` outcome (a
|
|
291
|
+
* thrown/rejected/timed-out schema) onto the engine's `{ kind: "aborted" }`
|
|
292
|
+
* arm so a schema failure halts the loop instead of re-prompting the agent.
|
|
293
|
+
*/
|
|
294
|
+
export async function validateOutput(
|
|
295
|
+
schema: StageSchema,
|
|
296
|
+
skill: string,
|
|
297
|
+
timeoutMs: number,
|
|
298
|
+
output: Output,
|
|
299
|
+
): Promise<{ kind: "ok"; result: ValidationResult } | { kind: "aborted"; abort: Fatal }> {
|
|
300
|
+
const validation = await validateOrFatal(schema, output.data, skill, timeoutMs);
|
|
301
|
+
if (validation.kind === "fatal") return { kind: "aborted", abort: validation };
|
|
302
|
+
return { kind: "ok", result: validation.result };
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* The retry-loop `onRetry` hook: fired between a failed validate and the next
|
|
307
|
+
* produce (`attempt` is 1-based). Sequence:
|
|
308
|
+
* 1. Capture the worktree digest AT THE FAILED VALIDATE — nothing mutates
|
|
309
|
+
* the tree between `validate` failing and `onRetry` opening, so this
|
|
310
|
+
* equals the digest at the failure. Captured per-retry (NOT once before
|
|
311
|
+
* the loop): a later retry's "before" state is the tree AFTER the prior
|
|
312
|
+
* retry's fix, so a single pre-loop baseline would compare against a
|
|
313
|
+
* stale tree and false-abort every later retry.
|
|
314
|
+
* 2. Fire `onStageRetry` before the agent is re-prompted (the ref shares the
|
|
315
|
+
* activation's allocator number via `currentStageRef` so listeners
|
|
316
|
+
* correlate retry ↔ end; graph position `stageIndex + 1` diverges past
|
|
317
|
+
* any loop).
|
|
318
|
+
* 3. Re-prompt the agent (`askAgentToFix`); a throw becomes an abort.
|
|
319
|
+
* 4. Gate on `worktreeUnchangedSince` — if the fix changed nothing
|
|
320
|
+
* observable, abort with the unchanged-worktree message instead of
|
|
321
|
+
* re-running the same failing validation.
|
|
322
|
+
*/
|
|
323
|
+
export async function handleRetry(
|
|
324
|
+
ctx: WorkflowSessionContext,
|
|
325
|
+
s: StageSessionContext,
|
|
326
|
+
attempt: number,
|
|
327
|
+
failures: SchemaValidationFailure[],
|
|
328
|
+
timeoutMs: number,
|
|
329
|
+
): Promise<{ kind: "ok" } | { kind: "aborted"; abort: Fatal }> {
|
|
330
|
+
const baselineDigest = resolveDigest(s.worktreeDigest, s.cwd);
|
|
331
|
+
await s.lifecycle.fire(ctx, "onStageRetry", currentStageRef(s), attempt, lifecycleCtxFromSession(s));
|
|
332
|
+
try {
|
|
333
|
+
await askAgentToFix(ctx, s, attempt, failures, timeoutMs);
|
|
334
|
+
} catch (e) {
|
|
335
|
+
return { kind: "aborted", abort: { kind: "fatal", message: formatError(e) } };
|
|
336
|
+
}
|
|
337
|
+
if (worktreeUnchangedSince(baselineDigest, s)) {
|
|
338
|
+
return {
|
|
339
|
+
kind: "aborted",
|
|
340
|
+
abort: { kind: "fatal", message: ERR_VALIDATE_RETRY_UNCHANGED(s.skill) },
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
return { kind: "ok" };
|
|
344
|
+
}
|
|
345
|
+
|
|
236
346
|
async function retryUntilValid(
|
|
237
347
|
ctx: WorkflowSessionContext,
|
|
238
|
-
s:
|
|
348
|
+
s: StageSessionContext,
|
|
239
349
|
deps: RetryDeps,
|
|
240
350
|
initial: Output,
|
|
241
351
|
): Promise<OutputProduction> {
|
|
@@ -253,78 +363,26 @@ async function retryUntilValid(
|
|
|
253
363
|
MAX_VALIDATION_RETRY_TIMEOUT_MS,
|
|
254
364
|
);
|
|
255
365
|
|
|
256
|
-
// The retry policy
|
|
366
|
+
// The retry policy delegates to the SHARED `runValidationRetryLoop` engine
|
|
257
367
|
// (validate-output.ts) — the same produce → validate → retry structure the
|
|
258
|
-
// script path runs. The
|
|
259
|
-
//
|
|
260
|
-
//
|
|
261
|
-
//
|
|
262
|
-
//
|
|
263
|
-
//
|
|
264
|
-
// - `
|
|
265
|
-
//
|
|
266
|
-
// - `onRetry` → `onStageRetry` + `askAgentToFix`; a throw becomes an abort.
|
|
368
|
+
// script path runs. The three hooks are short named delegations:
|
|
369
|
+
// - `produceAttempt` — `produce(0)` returns the already-produced `initial`;
|
|
370
|
+
// `produce(n>0)` re-reads the branch, re-runs the collector/parser, and
|
|
371
|
+
// re-checks the completion contract.
|
|
372
|
+
// - `validateOutput` — `validateOrFatal`, mapping its `Fatal` onto the
|
|
373
|
+
// engine's `{ kind: "aborted" }` abort arm.
|
|
374
|
+
// - `handleRetry` — `onStageRetry` + `askAgentToFix`; a throw becomes an
|
|
375
|
+
// abort, and the `worktreeUnchangedSince` gate aborts a no-op fix.
|
|
267
376
|
// `failFast` mirrors the script path's stop-flag polarity —
|
|
268
377
|
// `(onInvalid ?? "retry") === "halt"` is byte-identical to today's
|
|
269
378
|
// `onInvalid !== "halt"` loop-continue condition, just expressed as the
|
|
270
379
|
// engine's stop flag. Total productions stay bounded by `maxRetries + 1`.
|
|
271
380
|
const outcome = await runValidationRetryLoop<Output, Fatal>(
|
|
381
|
+
{ maxRetries, failFast: (s.stage.onInvalid ?? "retry") === "halt" },
|
|
272
382
|
{
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
{
|
|
277
|
-
produce: async (attempt) => {
|
|
278
|
-
// `produce(0)` returns the already-produced initial — no re-collection,
|
|
279
|
-
// no contract re-check (both ran before the loop opened).
|
|
280
|
-
if (attempt === 0) return { kind: "ok", value: initial };
|
|
281
|
-
const retryBranch = readBranch(ctx);
|
|
282
|
-
const retryCtx: CollectCtx = { ...deps.collectCtx, branch: retryBranch };
|
|
283
|
-
const reRun = await runOutcome(deps.outcome, retryCtx, deps.finalize);
|
|
284
|
-
if (reRun.kind === "fatal") return { kind: "aborted", abort: reRun };
|
|
285
|
-
const contract = enforceCompletionContract(s.stage, s.skill, reRun.output);
|
|
286
|
-
if (contract.kind === "fatal") return { kind: "aborted", abort: contract };
|
|
287
|
-
return { kind: "ok", value: contract.output };
|
|
288
|
-
},
|
|
289
|
-
validate: async (output) => {
|
|
290
|
-
const validation = await validateOrFatal(schema, output.data, s.skill, timeoutMs);
|
|
291
|
-
if (validation.kind === "fatal") return { kind: "aborted", abort: validation };
|
|
292
|
-
return { kind: "ok", result: validation.result };
|
|
293
|
-
},
|
|
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);
|
|
303
|
-
// onStageRetry fires before the agent is re-prompted; `attempt` is 1-based.
|
|
304
|
-
// Ref shares the activation's ALLOCATOR number (currentStageRef) so
|
|
305
|
-
// listeners can correlate this retry with the end/error event it
|
|
306
|
-
// belongs to — graph position (`stageIndex + 1`) diverges past any loop.
|
|
307
|
-
await s.lifecycle.fire(ctx, "onStageRetry", currentStageRef(s), attempt, lifecycleCtxFromSession(s));
|
|
308
|
-
try {
|
|
309
|
-
await askAgentToFix(ctx, s, attempt, failures, timeoutMs);
|
|
310
|
-
} catch (e) {
|
|
311
|
-
return { kind: "aborted", abort: { kind: "fatal", message: formatError(e) } };
|
|
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" };
|
|
327
|
-
},
|
|
383
|
+
produce: (attempt) => produceAttempt(ctx, s, deps, initial, attempt),
|
|
384
|
+
validate: (output) => validateOutput(schema, s.skill, timeoutMs, output),
|
|
385
|
+
onRetry: (attempt, failures) => handleRetry(ctx, s, attempt, failures, timeoutMs),
|
|
328
386
|
},
|
|
329
387
|
);
|
|
330
388
|
|
|
@@ -372,7 +430,7 @@ async function validateOrFatal(
|
|
|
372
430
|
|
|
373
431
|
async function askAgentToFix(
|
|
374
432
|
ctx: WorkflowSessionContext,
|
|
375
|
-
s:
|
|
433
|
+
s: StageSessionContext,
|
|
376
434
|
attempt: number,
|
|
377
435
|
failures: SchemaValidationFailure[],
|
|
378
436
|
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,
|
|
@@ -190,7 +190,7 @@ const auditFor = (s: StageSession, session: SessionRef | null): AuditCtx => ({
|
|
|
190
190
|
// began) — a failure row reuses it instead of burning a second number.
|
|
191
191
|
allocatedStageNumber: s.allocatedStageNumber,
|
|
192
192
|
// Host-injected persisted-session branch reader — the death-scene artifact
|
|
193
|
-
// writer reads it off
|
|
193
|
+
// writer reads it off AuditContext. Absent for programmatic embedders / no
|
|
194
194
|
// provider (the writer degrades silently). Conditional spread keeps the
|
|
195
195
|
// common case (reader present) byte-clean and the no-provider case undefined.
|
|
196
196
|
...(s.readSessionBranch ? { readSessionBranch: s.readSessionBranch } : {}),
|
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
|
}
|