@juicesharp/rpiv-workflow 2.1.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/audit-ctx.ts +16 -8
  2. package/audit-rows.ts +10 -0
  3. package/audit.ts +48 -26
  4. package/chain-state.ts +26 -1
  5. package/death-scene.ts +232 -0
  6. package/docs/embedding.md +1 -1
  7. package/docs/workflow-authoring.md +2 -2
  8. package/events.ts +3 -27
  9. package/execution-host.ts +9 -0
  10. package/failure-memos.ts +74 -0
  11. package/handle.ts +16 -1
  12. package/host.ts +13 -1
  13. package/internal.ts +1 -0
  14. package/loop-def.ts +9 -5
  15. package/loop-kinds.ts +16 -13
  16. package/loop-parallel.ts +116 -95
  17. package/loop-waves.ts +3 -3
  18. package/loop.ts +46 -43
  19. package/messages.ts +53 -14
  20. package/outcomes/collectors/workspace-diff.ts +3 -3
  21. package/outcomes/git-commit.ts +11 -4
  22. package/output-spec.ts +7 -7
  23. package/package.json +5 -2
  24. package/preview.ts +8 -1
  25. package/registration.ts +8 -3
  26. package/routing.ts +1 -41
  27. package/runner/chain-advance.ts +50 -32
  28. package/runner/errors.ts +1 -1
  29. package/runner/failure.ts +22 -23
  30. package/runner/preflight.ts +3 -6
  31. package/runner/resolve-stage.ts +3 -3
  32. package/runner/resume-entry.ts +5 -5
  33. package/runner/resume-loop.ts +5 -5
  34. package/runner/resume.ts +1 -1
  35. package/runner/run-context.ts +13 -3
  36. package/runner/run-stage.ts +134 -60
  37. package/runner/runner.ts +19 -9
  38. package/runner/script-stage.ts +17 -17
  39. package/sessions/bash-strikes.ts +182 -0
  40. package/sessions/extraction.ts +51 -37
  41. package/sessions/halt-routing.ts +18 -13
  42. package/sessions/index.ts +1 -1
  43. package/sessions/reattach.ts +10 -10
  44. package/sessions/sessions.ts +63 -19
  45. package/sessions/spawn.ts +5 -5
  46. package/sessions/success-persist.ts +9 -3
  47. package/stage-def.ts +2 -2
  48. package/stage-errors.ts +1 -1
  49. package/stage-identity.ts +43 -4
  50. package/state/index.ts +1 -1
  51. package/state/names.ts +1 -1
  52. package/state/reads.ts +1 -1
  53. package/state/state.ts +14 -4
  54. package/state/writes.ts +2 -2
  55. package/transcript.ts +30 -0
  56. package/types.ts +105 -15
  57. package/worktree-digest.ts +148 -0
package/runner/failure.ts CHANGED
@@ -10,7 +10,7 @@ import {
10
10
  auditCtxFor,
11
11
  failedArgs,
12
12
  notifyPartialArtifacts,
13
- recordTerminalFailure,
13
+ recordFatalFailure,
14
14
  terminate,
15
15
  } from "../audit.js";
16
16
  import { formatError, isAbortError } from "../internal-utils.js";
@@ -20,7 +20,7 @@ import { StagePreflightError } from "./errors.js";
20
20
 
21
21
  /**
22
22
  * Explicit result of one chain-walk step, threaded up through
23
- * `advanceChain` / `runStage` / `runStageOrRecordFailure`. The walk's halt
23
+ * `advanceChain` / `dispatchStage` / `dispatchStageOrRecordFailure`. The walk's halt
24
24
  * protocol is record-then-halt, not record-then-quietly-unwind: with a
25
25
  * non-void return type, a branch that records a failure but forgets to stop
26
26
  * the walk no longer typechecks — every arm must RETURN an outcome, and
@@ -41,7 +41,7 @@ export type ChainOutcome = "halted" | "completed" | "dispatched";
41
41
  * path) so they never import the composition site back.
42
42
  */
43
43
  export type AdvanceFn = (
44
- curCtx: WorkflowHostContext,
44
+ hostCtx: WorkflowHostContext,
45
45
  completedName: string,
46
46
  completedIdx: number,
47
47
  run: RunContext,
@@ -52,20 +52,15 @@ export type AdvanceFn = (
52
52
  * halt idiom for walk arms: `return haltChain(...)`.
53
53
  */
54
54
  export async function haltChain(
55
- curCtx: WorkflowHostContext,
55
+ hostCtx: WorkflowHostContext,
56
56
  run: RunContext,
57
57
  stageName: string,
58
58
  skill: string,
59
- args: Parameters<typeof recordTerminalFailure>[2],
59
+ args: Parameters<typeof recordFatalFailure>[2],
60
60
  onFailure?: (ctx: WorkflowHostContext) => void,
61
61
  unit?: UnitRef,
62
62
  ): Promise<ChainOutcome> {
63
- await recordTerminalFailure(
64
- curCtx,
65
- auditCtxFor(run, stageName, skill, unit ? { unit } : undefined),
66
- args,
67
- onFailure,
68
- );
63
+ await recordFatalFailure(hostCtx, auditCtxFor(run, stageName, skill, unit ? { unit } : undefined), args, onFailure);
69
64
  return "halted";
70
65
  }
71
66
 
@@ -84,7 +79,7 @@ export async function haltChain(
84
79
  * `skill`, so the unit's identity is NOT folded into the `stage` name string.
85
80
  */
86
81
  export async function recordEntryThrow(
87
- curCtx: WorkflowHostContext,
82
+ hostCtx: WorkflowHostContext,
88
83
  name: string,
89
84
  run: RunContext,
90
85
  e: unknown,
@@ -92,7 +87,7 @@ export async function recordEntryThrow(
92
87
  ): Promise<ChainOutcome> {
93
88
  if (e instanceof StagePreflightError) {
94
89
  return haltChain(
95
- curCtx,
90
+ hostCtx,
96
91
  run,
97
92
  name,
98
93
  e.skill,
@@ -102,7 +97,7 @@ export async function recordEntryThrow(
102
97
  }
103
98
  const reason = formatError(e);
104
99
  return haltChain(
105
- curCtx,
100
+ hostCtx,
106
101
  run,
107
102
  name,
108
103
  unit?.skill ?? name,
@@ -120,8 +115,12 @@ export async function recordEntryThrow(
120
115
  * artifacts produced by earlier stages are surfaced so the operator sees them
121
116
  * instead of grepping the JSONL. No-op when no artifacts exist.
122
117
  */
123
- export function recordAbortedAtSeam(curCtx: WorkflowHostContext, name: string, run: RunContext): Promise<ChainOutcome> {
124
- return haltChain(curCtx, run, name, name, abortedArgs(FAIL_WORKFLOW_ABORTED(name)), (ctx) =>
118
+ export function recordAbortedAtSeam(
119
+ hostCtx: WorkflowHostContext,
120
+ name: string,
121
+ run: RunContext,
122
+ ): Promise<ChainOutcome> {
123
+ return haltChain(hostCtx, run, name, name, abortedArgs(FAIL_WORKFLOW_ABORTED(name)), (ctx) =>
125
124
  notifyPartialArtifacts(ctx, run.cwd, run.runId),
126
125
  );
127
126
  }
@@ -133,7 +132,7 @@ export function recordAbortedAtSeam(curCtx: WorkflowHostContext, name: string, r
133
132
  * anything else → terminal entry-throw row). Modeled after `advanceCursor`
134
133
  * (loop.ts): one shared authority, callers hold their own preconditions.
135
134
  *
136
- * The two call sites (`runStageOrRecordFailure` live, `resumeStageWithSession`
135
+ * The two call sites (`dispatchStageOrRecordFailure` live, `resumeStageWithSession`
137
136
  * resume) cover DISJOINT scopes — the resume catch protects the reattach ladder
138
137
  * (`resumeWithSessionLadder`) the live catch cannot reach — so both must exist.
139
138
  * This wrapper merges the CLASSIFICATION POLICY (which throw is an abort vs a
@@ -142,22 +141,22 @@ export function recordAbortedAtSeam(curCtx: WorkflowHostContext, name: string, r
142
141
  * cancel signal beyond `WorkflowAbortError`) is one edit, here.
143
142
  */
144
143
  export async function withStageEntryGuard(
145
- curCtx: WorkflowHostContext,
144
+ hostCtx: WorkflowHostContext,
146
145
  name: string,
147
146
  run: RunContext,
148
147
  inner: () => Promise<ChainOutcome>,
149
148
  ): Promise<ChainOutcome> {
150
- if (run.signal?.aborted) return recordAbortedAtSeam(curCtx, name, run);
149
+ if (run.signal?.aborted) return recordAbortedAtSeam(hostCtx, name, run);
151
150
  try {
152
151
  return await inner();
153
152
  } catch (e) {
154
- if (isAbortError(e)) return recordAbortedAtSeam(curCtx, name, run);
155
- return recordEntryThrow(curCtx, name, run, e);
153
+ if (isAbortError(e)) return recordAbortedAtSeam(hostCtx, name, run);
154
+ return recordEntryThrow(hostCtx, name, run, e);
156
155
  }
157
156
  }
158
157
 
159
- export function finalizeWorkflow(curCtx: WorkflowHostContext, run: RunContext): ChainOutcome {
160
- curCtx.ui.notify(MSG_WORKFLOW_COMPLETE(run.state.stagesCompleted), "info");
158
+ export function finalizeWorkflow(hostCtx: WorkflowHostContext, run: RunContext): ChainOutcome {
159
+ hostCtx.ui.notify(MSG_WORKFLOW_COMPLETE(run.state.stagesCompleted), "info");
161
160
  terminate(run.state, { status: "completed" });
162
161
  return "completed";
163
162
  }
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Runtime preflights for the per-stage pipeline — every check that gates a
3
3
  * stage BEFORE its body dispatches. Each check throws `StagePreflightError`
4
- * on failure; `runStageOrRecordFailure` (run-stage.ts) catches and
4
+ * on failure; `dispatchStageOrRecordFailure` (run-stage.ts) catches and
5
5
  * records the JSONL row. Schema-backed input validation (the two POST-prompt
6
6
  * checks) lives beside this in `input-validation.ts`.
7
7
  *
@@ -26,10 +26,7 @@ import type { ResolvedStage } from "./resolve-stage.js";
26
26
  * The skill-path preflight sequence, in its load-bearing order:
27
27
  * 1. ensureUpstreamArtifact — halt: missing inherited artifact.
28
28
  * 2. ensureNamedReads — halt: a `reads:` name has no published entry.
29
- * 3. enforceSessionInvariants — invariant: authoring-time-knowable throws
30
- * (precede the registry check so the structural violation surfaces
31
- * regardless of the runtime registry).
32
- * 4. ensureSkillRegistered — halt: skill not registered in Pi.
29
+ * 3. ensureSkillRegistered — halt: skill not registered in Pi.
33
30
  * (Input-schema validation runs after prompt prep — see input-validation.ts.)
34
31
  */
35
32
  export function runSingleStagePreflights(stage: ResolvedStage, run: RunContext): void {
@@ -47,7 +44,7 @@ export function runSingleStagePreflights(stage: ResolvedStage, run: RunContext):
47
44
  export function ensureLoopNotContinue(stage: ResolvedStage): void {
48
45
  if (stage.def.sessionPolicy !== "continue") return;
49
46
  const reason =
50
- `runStage: stage "${stage.name}" cannot combine loop with sessionPolicy "continue" — ` +
47
+ `dispatchStage: stage "${stage.name}" cannot combine loop with sessionPolicy "continue" — ` +
51
48
  "each unit requires an isolated session";
52
49
  throw invariantPreflight(stage.name, MSG_STAGE_THREW(stage.name, reason), reason);
53
50
  }
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Stage resolution — derive a stage's dispatch identity ONCE, at the top of
3
- * `runStage`, so the rest of the pipeline switches on data instead of
3
+ * `dispatchStage`, so the rest of the pipeline switches on data instead of
4
4
  * re-probing the def's optional slots (`loop`/`verify`/`run`/`prompt`). The
5
5
  * old probe-the-optionals ladder needed a "slot ordering (load-bearing)"
6
6
  * comment; the ordering now lives in exactly one place (`stageModeOf`).
@@ -21,7 +21,7 @@ import type { RunContext } from "../types.js";
21
21
  */
22
22
  export type StageDispatch = "script" | "prompt" | "skill";
23
23
 
24
- /** The top-level dispatch slot `runStage` switches on. */
24
+ /** The top-level dispatch slot `dispatchStage` switches on. */
25
25
  export type StageMode = "loop" | StageDispatch;
26
26
 
27
27
  export interface ResolvedStage {
@@ -50,7 +50,7 @@ export function resolveStage(currentName: string, idx: number, run: RunContext):
50
50
  const def = run.workflow.stages[currentName];
51
51
  if (!def) {
52
52
  // validateWorkflow should catch this; defensive for tests bypassing validation.
53
- throw new Error(`runStage: stage "${currentName}" referenced by edges but missing from workflow.stages`);
53
+ throw new Error(`dispatchStage: stage "${currentName}" referenced by edges but missing from workflow.stages`);
54
54
  }
55
55
  const loop = effectiveLoopOf(def);
56
56
  const dispatch = dispatchOf(def);
@@ -16,7 +16,7 @@ import type { RunContext, WorkflowHostContext } from "../types.js";
16
16
  import { recordEntryThrow } from "./failure.js";
17
17
  import type { ReconstructResult } from "./resume.js";
18
18
  import { recordLoopDriftFailure, resumeLoopStage } from "./resume-loop.js";
19
- import { advance, buildLoopDeps, resumeStageWithSession, runStageOrRecordFailure } from "./run-stage.js";
19
+ import { advance, buildLoopDeps, dispatchStageOrRecordFailure, resumeStageWithSession } from "./run-stage.js";
20
20
 
21
21
  /**
22
22
  * Pick the chain re-entry thunk from the trail trailer. Dispatch keys on the
@@ -83,11 +83,11 @@ export function selectResumeEntry(
83
83
  // tests in resume.test.ts).
84
84
  return last.session !== null
85
85
  ? () => resumeStageWithSession(ctx, last, idx, run)
86
- : () => runStageOrRecordFailure(ctx, last.stage, idx, run);
86
+ : () => dispatchStageOrRecordFailure(ctx, last.stage, idx, run);
87
87
  }
88
88
 
89
89
  /**
90
- * Resume-entry counterpart of `runStageOrRecordFailure`'s catch. The live
90
+ * Resume-entry counterpart of `dispatchStageOrRecordFailure`'s catch. The live
91
91
  * chain reaches user fns (loop `next`/`done`/`feedForward`, judge prompts,
92
92
  * route predicates) only under that catch; the resume-loop and route-onward
93
93
  * entry thunks call the same fns directly, so a throw would otherwise escape
@@ -95,7 +95,7 @@ export function selectResumeEntry(
95
95
  * caller loses the result envelope.
96
96
  */
97
97
  async function guardResumeEntry(
98
- curCtx: WorkflowHostContext,
98
+ hostCtx: WorkflowHostContext,
99
99
  name: string,
100
100
  run: RunContext,
101
101
  entry: () => Promise<unknown>,
@@ -103,7 +103,7 @@ async function guardResumeEntry(
103
103
  try {
104
104
  await entry();
105
105
  } catch (e) {
106
- await recordEntryThrow(curCtx, name, run, e);
106
+ await recordEntryThrow(hostCtx, name, run, e);
107
107
  }
108
108
  }
109
109
 
@@ -17,12 +17,12 @@
17
17
  * probe pull is the documented harmless deterministic double-pull.
18
18
  */
19
19
 
20
- import { auditCtxFor, failedArgs, recordTerminalFailure } from "../audit.js";
20
+ import { auditCtxFor, failedArgs, recordFatalFailure } from "../audit.js";
21
21
  import { resolveSkill } from "../chain-state.js";
22
22
  import { announceLoopStart, pendingFanoutIndices, runFanoutResume, runLoop } from "../loop.js";
23
23
  import { effectiveLoopOf, freezesEntryArgsOf } from "../loop-constructors.js";
24
24
  import { buildLoopEntry, type LoopDeps, sequentialStrategyOf } from "../loop-kinds.js";
25
- import { validateUnitDeps } from "../loop-waves.js";
25
+ import { ensureUnitDeps } from "../loop-waves.js";
26
26
  import { FAIL_MISSING_ARTIFACT, type FailureText, MSG_RESUME_LOOP_MISMATCH } from "../messages.js";
27
27
  import type { RunContext, WorkflowHostContext } from "../types.js";
28
28
  import type { LoopResumePoint } from "./resume.js";
@@ -73,7 +73,7 @@ export async function resumeLoopStage(
73
73
  // Re-validate the recomputed DAG: the id-only drift guard PASSES when a user edits
74
74
  // only a slice's `deps` (ids/titles unchanged), so a newly-introduced cycle would
75
75
  // otherwise reach the dispatcher. guardResumeEntry catches this throw → clean failure.
76
- validateUnitDeps(point.units!, point.parent);
76
+ ensureUnitDeps(point.units!, point.parent);
77
77
  const pending = pendingFanoutIndices(point.cursor, point.units!.length); // slots === undefined
78
78
  if (pending.length > 0) await announceLoopStart(ctx, run, entry);
79
79
  await runFanoutResume(ctx, entry, point.cursor, run, deps, pending);
@@ -88,7 +88,7 @@ export async function resumeLoopStage(
88
88
  /**
89
89
  * One refusal recorder — the shared 3-step body for the two resume recorders
90
90
  * (`recordMissingArtifactFailure` / `recordLoopDriftFailure`): resolve the
91
- * terminal args + build the audit ctx + `recordTerminalFailure`. Each caller
91
+ * terminal args + build the audit ctx + `recordFatalFailure`. Each caller
92
92
  * supplies its own descriptor — a `FailureText` (missing-artifact) or a
93
93
  * `[notifyMsg, errMsg]` tuple (loop drift).
94
94
  */
@@ -100,7 +100,7 @@ function recordResumeRefusal(
100
100
  descriptor: FailureText | [notifyMsg: string, errMsg: string],
101
101
  ): Promise<void> {
102
102
  const args = Array.isArray(descriptor) ? failedArgs(descriptor[0], descriptor[1]) : failedArgs(descriptor);
103
- return recordTerminalFailure(ctx, auditCtxFor(run, parent, skill), args);
103
+ return recordFatalFailure(ctx, auditCtxFor(run, parent, skill), args);
104
104
  }
105
105
 
106
106
  /** Recorded refusal for a corrupted/truncated trail (reuses the forward preflight's messages). */
package/runner/resume.ts CHANGED
@@ -360,7 +360,7 @@ async function foldUnitRow(
360
360
  // awaits BEFORE `executeRun` brackets the lifecycle — an escape here yields
361
361
  // no JSONL failure row and no `onWorkflowEnd`. The live driver's same
362
362
  // `advanceCursor`+`publishPanelVerdict` pair runs under
363
- // `runStageOrRecordFailure`'s catch (loop.ts `dispatchUnit`); this is its
363
+ // `dispatchStageOrRecordFailure`'s catch (loop.ts `dispatchUnit`); this is its
364
364
  // resume-side error boundary.
365
365
  await guarded(acc, gen.parent, () => {
366
366
  advanceCursor(gen.cursor, role, verdict, gen.loop);
@@ -10,6 +10,7 @@ import type { Workflow } from "../api.js";
10
10
  import { LifecycleDispatcher, type LifecycleListeners } from "../events.js";
11
11
  import type { ModelSelection, WorkflowHost } from "../host.js";
12
12
  import { getSkillContracts } from "../skill-contracts/index.js";
13
+ import type { BranchEntry } from "../transcript.js";
13
14
  import type { RunTrigger } from "../triggers.js";
14
15
  import type { RunContext, RunState } from "../types.js";
15
16
 
@@ -24,10 +25,10 @@ import type { RunContext, RunState } from "../types.js";
24
25
  * body) are NOT counted, and each destination stage owns its own budget
25
26
  * (`RunContext.revisits`), so the retry allowance is invariant to how many
26
27
  * decision edges the cycle crosses per iteration and unrelated loops never
27
- * share a pool. With 2: any given stage runs once unconditionally and may be
28
- * re-entered up to 2 more times — at most 3 executions per stage.
28
+ * share a pool. With 3: any given stage runs once unconditionally and may be
29
+ * re-entered up to 3 more times — at most 4 executions per stage.
29
30
  */
30
- export const MAX_BACKWARD_JUMPS = 2;
31
+ export const MAX_BACKWARD_JUMPS = 3;
31
32
 
32
33
  /**
33
34
  * Run-wide safety cap on loop units — the backstop for any loop kind whose
@@ -58,6 +59,11 @@ export function freshRunState(originalInput: string): RunState {
58
59
  stagesCompleted: 0,
59
60
  lastAllocatedStageNumber: 0,
60
61
  telemetry: { backwardJumps: 0, droppedRoutingRows: [], droppedFailureRows: [] },
62
+ failureMemos: [],
63
+ // Validation-retry gate memory — fresh on every entry point (operator
64
+ // resume starts with NO prior baseline ⇒ first qualifying dispatch
65
+ // proceeds, mirroring the fresh-strike-budget policy).
66
+ lastGatedDispatch: undefined,
61
67
  termination: { status: "running" },
62
68
  };
63
69
  }
@@ -84,6 +90,8 @@ export function buildRunContext(
84
90
  lifecycle?: LifecycleListeners;
85
91
  signal?: AbortSignal;
86
92
  resolveModel?: (id: { stage: string; skill: string }) => ModelSelection | undefined;
93
+ readSessionBranch?: (file: string) => BranchEntry[] | undefined;
94
+ worktreeDigest?: (cwd: string) => string | undefined;
87
95
  },
88
96
  identity: { runId: string; state: RunState; visited: Set<string>; trigger: RunTrigger },
89
97
  ): RunContext {
@@ -108,6 +116,8 @@ export function buildRunContext(
108
116
  lifecycle: new LifecycleDispatcher(options.lifecycle),
109
117
  signal: options.signal,
110
118
  resolveModel: options.resolveModel,
119
+ readSessionBranch: options.readSessionBranch,
120
+ worktreeDigest: options.worktreeDigest,
111
121
  };
112
122
  }
113
123