@juicesharp/rpiv-pi 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 (45) hide show
  1. package/README.md +9 -8
  2. package/docs/lanes.md +3 -2
  3. package/docs/models-config.md +6 -6
  4. package/docs/workflows.md +4 -18
  5. package/extensions/rpiv-core/artifact-collector.ts +2 -2
  6. package/extensions/rpiv-core/bash-timeout.ts +16 -0
  7. package/extensions/rpiv-core/built-in-workflows.ts +2289 -318
  8. package/extensions/rpiv-core/guidance.ts +35 -19
  9. package/extensions/rpiv-core/index.ts +2 -2
  10. package/extensions/rpiv-core/lane-console.ts +62 -5
  11. package/extensions/rpiv-core/lane-list.ts +84 -32
  12. package/extensions/rpiv-core/lane-progress.ts +13 -77
  13. package/extensions/rpiv-core/lane-switcher.ts +114 -33
  14. package/extensions/rpiv-core/lane-usage.ts +25 -0
  15. package/extensions/rpiv-core/models-config-validate.ts +1 -1
  16. package/extensions/rpiv-core/models-config.ts +38 -3
  17. package/extensions/rpiv-core/register-built-in-workflows.ts +2 -2
  18. package/extensions/rpiv-core/run-lane-registry.ts +80 -69
  19. package/extensions/rpiv-core/sdk-workflow-host.ts +43 -3
  20. package/extensions/rpiv-core/subagent-usage.ts +147 -0
  21. package/extensions/rpiv-core/workflow-execution-host.ts +24 -7
  22. package/package.json +3 -3
  23. package/skills/amend/SKILL.md +7 -3
  24. package/skills/annotate-guidance/SKILL.md +1 -0
  25. package/skills/architecture-review/SKILL.md +1 -0
  26. package/skills/blueprint/SKILL.md +10 -4
  27. package/skills/changelog/SKILL.md +1 -0
  28. package/skills/commit/SKILL.md +1 -0
  29. package/skills/design/SKILL.md +4 -3
  30. package/skills/design-review/SKILL.md +1 -0
  31. package/skills/design-slice/SKILL.md +2 -1
  32. package/skills/discover/SKILL.md +1 -1
  33. package/skills/elaborate/SKILL.md +21 -9
  34. package/skills/elaborate/_helpers/validate-workflow-invariant.mjs +88 -0
  35. package/skills/explore/SKILL.md +1 -0
  36. package/skills/frontend-design/SKILL.md +1 -0
  37. package/skills/grade/SKILL.md +24 -6
  38. package/skills/implement/SKILL.md +10 -2
  39. package/skills/plan/SKILL.md +10 -6
  40. package/skills/research/SKILL.md +9 -8
  41. package/skills/resume-handoff/SKILL.md +1 -0
  42. package/skills/revise/SKILL.md +1 -0
  43. package/skills/slice/SKILL.md +4 -3
  44. package/skills/synthesize/SKILL.md +16 -7
  45. package/skills/validate/SKILL.md +1 -0
@@ -12,8 +12,14 @@
12
12
  * inline question answering — so the belowEditor dock is never itself "activated".
13
13
  */
14
14
 
15
- import type { ExtensionAPI, ExtensionUIContext, KeybindingsManager } from "@earendil-works/pi-coding-agent";
15
+ import type {
16
+ ExtensionAPI,
17
+ ExtensionContext,
18
+ ExtensionUIContext,
19
+ KeybindingsManager,
20
+ } from "@earendil-works/pi-coding-agent";
16
21
  import type { EditorTheme, KeyId, TUI } from "@earendil-works/pi-tui";
22
+ import type { WorkflowHostContext } from "@juicesharp/rpiv-workflow";
17
23
  import { showLaneConsole } from "./lane-console.js";
18
24
  import { LaneDock } from "./lane-dock.js";
19
25
  import { LaneDockEditor } from "./lane-dock-editor.js";
@@ -26,6 +32,7 @@ import {
26
32
  setFocusedRun,
27
33
  subscribeLanes,
28
34
  } from "./run-lane-registry.js";
35
+ import { isModuleNotFound } from "./utils.js";
29
36
 
30
37
  /**
31
38
  * Root hotkey that opens the lane switcher, registered via Pi's `registerShortcut`
@@ -54,6 +61,16 @@ let unsubscribe: (() => void) | undefined;
54
61
  /** The launcher UI that owns the dock editor — kept so __resetLaneSwitcher can
55
62
  * restore Pi's default editor. Set once per ctx identity at session_start. */
56
63
  let editorCtx: ExtensionUIContext | undefined;
64
+ /** The rerun callback the lane console calls on `r` — built in session_start (where pi/ui
65
+ * are in scope) from the captured launcher cwd + sessionManager. Undefined before the first
66
+ * root session_start (the console passes a no-op then). */
67
+ let rerunCallback: ((runId: string) => void) | undefined;
68
+ /** Launcher cwd captured at session_start — the WorkflowHostContext.cwd the rerun's
69
+ * resumeWorkflowByRunId resolves the run-id against (resolveRun/loadWorkflows read it). */
70
+ let launcherCwd: string | undefined;
71
+ /** Launcher sessionManager captured at session_start — the WorkflowHostContext.sessionManager
72
+ * the detached executor host borrows as its live observer. */
73
+ let launcherSessionManager: ExtensionContext["sessionManager"] | undefined;
57
74
  /** Guard so a second ⏎ never stacks a second console (re-entrancy belt-and-braces;
58
75
  * while a console is open the editor isn't focused, so this rarely trips). */
59
76
  let switchingLane = false;
@@ -70,7 +87,7 @@ function stepIn(ui: ExtensionUIContext): void {
70
87
  const top = listLanesForDisplay()[0];
71
88
  if (!top) return;
72
89
  const unitIndex = top.kind === "unit" ? top.unit.index : SINGLE_UNIT_KEY;
73
- void switchIntoLane(ui, top.lane.runId, unitIndex);
90
+ void switchIntoLane(ui, top.lane.runId, unitIndex, rerunCallback ?? (() => {}));
74
91
  }
75
92
 
76
93
  /**
@@ -83,7 +100,12 @@ function stepIn(ui: ExtensionUIContext): void {
83
100
  * can't strand focus (which would leave Ctrl-C hijacked at root). Called by the dock editor's
84
101
  * `onOpen` and by `stepIn`.
85
102
  */
86
- export async function switchIntoLane(ui: ExtensionUIContext, runId: string, unitIndex: number): Promise<void> {
103
+ export async function switchIntoLane(
104
+ ui: ExtensionUIContext,
105
+ runId: string,
106
+ unitIndex: number,
107
+ onRerun: (runId: string) => void = () => {},
108
+ ): Promise<void> {
87
109
  if (switchingLane) return; // never stack two consoles
88
110
  switchingLane = true;
89
111
  setFocusedRun(runId);
@@ -91,7 +113,7 @@ export async function switchIntoLane(ui: ExtensionUIContext, runId: string, unit
91
113
  // dock below would duplicate it — hide it for the duration.
92
114
  dock?.setSuppressed(true);
93
115
  try {
94
- await showLaneConsole(ui, runId, unitIndex); // the lane browser: spine + transcript + inline question
116
+ await showLaneConsole(ui, runId, unitIndex, onRerun); // the lane browser: spine + transcript + inline question
95
117
  } finally {
96
118
  dock?.setSuppressed(false);
97
119
  setFocusedRun(undefined);
@@ -102,35 +124,91 @@ export async function switchIntoLane(ui: ExtensionUIContext, runId: string, unit
102
124
  export function registerLaneSwitcher(pi: ExtensionAPI): void {
103
125
  const hotkey = resolveHotkey();
104
126
 
105
- pi.on("session_start", async (_event: unknown, ctx: { hasUI?: boolean; ui?: ExtensionUIContext }) => {
106
- // A detached child re-loads rpiv-core and re-fires this hook with its
107
- // bound relay ui. Skip it — only the ROOT launcher owns the ambient dock +
108
- // registry subscription. A child mounting its own dock would re-point the
109
- // shared singleton at its relay and clobber the launcher's `rpiv-lanes` widget.
110
- if (!ctx.hasUI || !ctx.ui || isLaneRelayUiContext(ctx.ui)) return;
111
- const ui = ctx.ui;
112
- dock ??= new LaneDock();
113
- dock.setUICtx(ui);
114
- dock.update();
115
- // Subscribe once: re-render the dock on any registry change (run recorded/
116
- // evicted, status, current session, needs-input, dock selection).
117
- unsubscribe ??= subscribeLanes(() => dock?.update());
118
- // Install the dock editor once per ctx identity (re-install on /reload). It
119
- // proxies dock navigation; ⏎ on a selected lane switches into it. The host
120
- // preserves editor text + app keybindings across the swap.
121
- if (ui !== editorCtx) {
122
- editorCtx = ui;
123
- ui.setEditorComponent(
124
- (tui: TUI, theme: EditorTheme, keybindings: KeybindingsManager) =>
125
- new LaneDockEditor(
126
- tui,
127
- theme,
128
- keybindings,
129
- (runId, unitIndex) => void switchIntoLane(ui, runId, unitIndex),
130
- ),
131
- );
132
- }
133
- });
127
+ pi.on(
128
+ "session_start",
129
+ async (
130
+ _event: unknown,
131
+ ctx: {
132
+ hasUI?: boolean;
133
+ ui?: ExtensionUIContext;
134
+ cwd?: string;
135
+ sessionManager?: ExtensionContext["sessionManager"];
136
+ },
137
+ ) => {
138
+ // A detached child re-loads rpiv-core and re-fires this hook with its
139
+ // bound relay ui. Skip it — only the ROOT launcher owns the ambient dock +
140
+ // registry subscription. A child mounting its own dock would re-point the
141
+ // shared singleton at its relay and clobber the launcher's `rpiv-lanes` widget.
142
+ if (!ctx.hasUI || !ctx.ui || isLaneRelayUiContext(ctx.ui)) return;
143
+ const ui = ctx.ui;
144
+ // Capture the launcher cwd + sessionManager so the `r` rerun callback can build the
145
+ // observer-only WorkflowHostContext resumeWorkflowByRunId needs (resolveRun +
146
+ // loadWorkflows read cwd; the detached executor host borrows sessionManager as its
147
+ // live observer). Re-captured on every root session_start (/reload) like editorCtx.
148
+ launcherCwd = ctx.cwd;
149
+ launcherSessionManager = ctx.sessionManager;
150
+ // Build the rerun callback here (ui in scope): resume a failed/aborted/cancelled run
151
+ // by its run-id via a guarded dynamic import of the workflow runner. Degrades silently
152
+ // when rpiv-workflow is absent (isModuleNotFound) — /rpiv-setup guides the user. The
153
+ // async resume is fire-and-forget; the failed→running lane flip is subscription-driven
154
+ // (recordRun reactivation via the lane lifecycle), so the console does NOT await it.
155
+ rerunCallback = (runId: string): void => {
156
+ void (async () => {
157
+ try {
158
+ // Guarded dynamic import — degrades silently when rpiv-workflow is absent
159
+ // (isModuleNotFound); /rpiv-setup guides the user. The /runner entry keeps the
160
+ // loader/DSL graph off the import (sibling-import-graph permits the dynamic form).
161
+ const runner = await import("@juicesharp/rpiv-workflow/runner");
162
+ // Observer-only ctx: the detached executor provider supplies spawnChild/
163
+ // maxConcurrency (registered on the root session_start by workflow-execution-host).
164
+ // The double cast is required — the object omits spawnChild/maxConcurrency, so a
165
+ // single `as WorkflowHostContext` fails TS2352 (mirrors the as-unknown-as cast in
166
+ // workflow-execution-host.ts). cwd/sessionManager are the real captured launcher values.
167
+ const hostCtx = {
168
+ cwd: launcherCwd,
169
+ hasUI: true,
170
+ ui: { notify: (m: string, l?: "info" | "warning" | "error") => ui.notify(m, l) },
171
+ sessionManager: launcherSessionManager,
172
+ waitForIdle: () => Promise.resolve(),
173
+ } as unknown as WorkflowHostContext;
174
+ void runner
175
+ .resumeWorkflowByRunId(hostCtx, runId)
176
+ .then((r) => {
177
+ // Surface ONLY a pre-run refusal (no JSONL created) — an in-run failure is
178
+ // notified by the stage machinery; a success reactivates the lane reactively.
179
+ // r.runId === undefined distinguishes a refusal (resolveRun/load miss).
180
+ if (!r.success && r.runId === undefined && r.error) ui.notify(r.error, "error");
181
+ })
182
+ .catch((e) => ui.notify(`rpiv: resume failed — ${String(e)}`, "error"));
183
+ } catch (err) {
184
+ if (!isModuleNotFound(err)) console.error("[rpiv-core] failed to load workflow runner:", err);
185
+ return; // sibling absent — /rpiv-setup guides the user
186
+ }
187
+ })();
188
+ };
189
+ dock ??= new LaneDock();
190
+ dock.setUICtx(ui);
191
+ dock.update();
192
+ // Subscribe once: re-render the dock on any registry change (run recorded/
193
+ // evicted, status, current session, needs-input, dock selection).
194
+ unsubscribe ??= subscribeLanes(() => dock?.update());
195
+ // Install the dock editor once per ctx identity (re-install on /reload). It
196
+ // proxies dock navigation; ⏎ on a selected lane switches into it. The host
197
+ // preserves editor text + app keybindings across the swap.
198
+ if (ui !== editorCtx) {
199
+ editorCtx = ui;
200
+ ui.setEditorComponent(
201
+ (tui: TUI, theme: EditorTheme, keybindings: KeybindingsManager) =>
202
+ new LaneDockEditor(
203
+ tui,
204
+ theme,
205
+ keybindings,
206
+ (runId, unitIndex) => void switchIntoLane(ui, runId, unitIndex, rerunCallback ?? (() => {})),
207
+ ),
208
+ );
209
+ }
210
+ },
211
+ );
134
212
 
135
213
  pi.registerCommand("lanes", {
136
214
  description: "Open the workflow run lane browser",
@@ -173,4 +251,7 @@ export function __resetLaneSwitcher(): void {
173
251
  editorCtx = undefined;
174
252
  dock?.dispose();
175
253
  dock = undefined;
254
+ rerunCallback = undefined;
255
+ launcherCwd = undefined;
256
+ launcherSessionManager = undefined;
176
257
  }
@@ -81,6 +81,31 @@ export function toLaneUsage(stats: unknown): LaneUsage | undefined {
81
81
  return usage;
82
82
  }
83
83
 
84
+ /**
85
+ * Pairwise sum of two `LaneUsage` (or the defined side when one is `undefined`):
86
+ * sums the 4 token dimensions + recomputes `total` (= sum of all four), threads the
87
+ * scalar `cost` when EITHER side carries it, and drops `percent` (a context-window
88
+ * fill ratio is not meaningfully summable). Returns `undefined` only when BOTH are
89
+ * absent — the identity element of the sum — so folding through it is a no-op.
90
+ *
91
+ * Created once here and consumed by every token-accounting consumer —
92
+ * the single canonical pairwise sum, so the per-row tally, the run grand total, and
93
+ * the stage breakdown can never diverge. `addLaneUsage(undefined, x) === x`, so it
94
+ * composes a run/stage/lane roll-up uniformly whether a side carries usage or not.
95
+ */
96
+ export function addLaneUsage(a?: LaneUsage, b?: LaneUsage): LaneUsage | undefined {
97
+ if (!a && !b) return undefined;
98
+ if (!a) return b;
99
+ if (!b) return a;
100
+ const input = a.input + b.input;
101
+ const output = a.output + b.output;
102
+ const cacheRead = a.cacheRead + b.cacheRead;
103
+ const cacheWrite = a.cacheWrite + b.cacheWrite;
104
+ const result: LaneUsage = { input, output, cacheRead, cacheWrite, total: input + output + cacheRead + cacheWrite };
105
+ if (a.cost !== undefined || b.cost !== undefined) result.cost = (a.cost ?? 0) + (b.cost ?? 0);
106
+ return result;
107
+ }
108
+
84
109
  /**
85
110
  * Format a token count in pi's footer idiom — ported verbatim from the SDK's
86
111
  * `footer.js:17-29` (`formatTokens`): `<1e3` bare · `<1e4` `N.Nk` · `<1e6`
@@ -2,7 +2,7 @@
2
2
  * models-config-validate — session_start warn-on-miss for models.json keys.
3
3
  *
4
4
  * Record-key typos (`skills.committ`, `agents.codebase-analzyer`,
5
- * `presets.shipp`) pass TypeBox validation (records are structurally dynamic)
5
+ * `presets.buildd`) pass TypeBox validation (records are structurally dynamic)
6
6
  * and silently fall through to the defaults cascade — the override the user
7
7
  * meant to set just never applies, with no feedback. This hook surfaces them
8
8
  * once per process via `console.warn`.
@@ -35,6 +35,15 @@ export type ThinkingLevelValue = (typeof THINKING_LEVEL_VALUES)[number];
35
35
  export const MODEL_THINKING_LEVEL_VALUES = ["off", ...THINKING_LEVEL_VALUES] as const;
36
36
  export type ModelThinkingLevelValue = (typeof MODEL_THINKING_LEVEL_VALUES)[number];
37
37
 
38
+ /**
39
+ * Background-lane concurrency cap fallback. The fail-soft default applied by
40
+ * `resolveMaxConcurrency` when `~/.config/rpiv-pi/models.json` is absent or
41
+ * carries no valid `maxConcurrency`. Rate limits, not CPU, are the real cap —
42
+ * 4 background lanes is the safe default. Re-exported from
43
+ * packages/rpiv-pi/extensions/rpiv-core/workflow-execution-host.ts to preserve the tested public surface.
44
+ */
45
+ export const DEFAULT_MAX_CONCURRENCY = 4;
46
+
38
47
  // ---------------------------------------------------------------------------
39
48
  // TypeBox schemas
40
49
  // ---------------------------------------------------------------------------
@@ -109,7 +118,7 @@ const PresetSchema = Type.Object(
109
118
  * names within that workflow.
110
119
  *
111
120
  * `Type.Record(Type.String(), …)` wrappers are structurally dynamic and cannot
112
- * stamp `additionalProperties: false` — record-key typos (`presets.shipp`,
121
+ * stamp `additionalProperties: false` — record-key typos (`presets.buildd`,
113
122
  * `skills.committ`) pass schema validation by design and fall through to the
114
123
  * defaults cascade at lookup. `findUnknownModelKeys` (wired into session_start
115
124
  * by models-config-validate.ts) is the runtime warn-on-miss safety net.
@@ -121,6 +130,13 @@ const ModelsConfigSchema = Type.Object(
121
130
  stages: Type.Optional(Type.Record(Type.String(), ModelEntrySchema)),
122
131
  skills: Type.Optional(Type.Record(Type.String(), ModelEntrySchema)),
123
132
  presets: Type.Optional(Type.Record(Type.String(), PresetSchema)),
133
+ maxConcurrency: Type.Optional(
134
+ Type.Integer({
135
+ minimum: 1,
136
+ description:
137
+ "Background-lane concurrency cap (fail-soft default applied by resolveMaxConcurrency when absent/invalid)",
138
+ }),
139
+ ),
124
140
  },
125
141
  { additionalProperties: false },
126
142
  );
@@ -145,6 +161,8 @@ export interface ModelsConfig {
145
161
  stages?: Record<string, ResolvedModelConfig>;
146
162
  skills?: Record<string, ResolvedModelConfig>;
147
163
  presets?: Record<string, { stages?: Record<string, ResolvedModelConfig> }>;
164
+ /** Background-lane concurrency cap. Absent/invalid ⇒ DEFAULT_MAX_CONCURRENCY (via resolveMaxConcurrency). */
165
+ maxConcurrency?: number;
148
166
  }
149
167
 
150
168
  // ---------------------------------------------------------------------------
@@ -237,6 +255,7 @@ export function loadModelsConfig(): ModelsConfig {
237
255
  stages: Object.keys(stages).length > 0 ? stages : undefined,
238
256
  skills: Object.keys(skills).length > 0 ? skills : undefined,
239
257
  presets: Object.keys(presets).length > 0 ? presets : undefined,
258
+ maxConcurrency: validated.maxConcurrency,
240
259
  };
241
260
  modelsConfigCache = result;
242
261
  return result;
@@ -318,6 +337,22 @@ export function resolveStageModel(
318
337
  return config.defaults;
319
338
  }
320
339
 
340
+ /**
341
+ * Resolve the background-lane concurrency cap from `~/.config/rpiv-pi/models.json`.
342
+ * Returns `DEFAULT_MAX_CONCURRENCY` (4) when the key is absent OR holds an invalid
343
+ * value (non-integer, < 1).
344
+ *
345
+ * NOTE: `Value.Clean` (typebox@1.3.6) does NOT strip invalid scalars — it only
346
+ * strips unknown keys, leaving `null` in place — so a configured
347
+ * `maxConcurrency: 0` / `-1` / `4.5` / `"4"` / `null` survives schema
348
+ * validation. This guard is therefore the fail-soft boundary, not the schema's
349
+ * `minimum: 1`. (`undefined` reaches the guard only from an absent key.)
350
+ */
351
+ export function resolveMaxConcurrency(config: ModelsConfig): number {
352
+ const v = config.maxConcurrency;
353
+ return v !== undefined && Number.isInteger(v) && v >= 1 ? v : DEFAULT_MAX_CONCURRENCY;
354
+ }
355
+
321
356
  // ---------------------------------------------------------------------------
322
357
  // Warn-on-miss — surface record-key typos that schema validation can't catch.
323
358
  // ---------------------------------------------------------------------------
@@ -339,8 +374,8 @@ export interface KnownModelKeys {
339
374
 
340
375
  /**
341
376
  * Return dotted paths of configured models.json keys that match no known key —
342
- * e.g. `skills.committ`, `agents.codebase-analzyer`, `presets.shipp`,
343
- * `presets.ship.stages.plann`. Record-key typos pass TypeBox validation
377
+ * e.g. `skills.committ`, `agents.codebase-analzyer`, `presets.buildd`,
378
+ * `presets.build.stages.plann`. Record-key typos pass TypeBox validation
344
379
  * (records are structurally dynamic) and silently fall through to the defaults
345
380
  * cascade; this surfaces them. Axes with an `undefined` known-list are skipped;
346
381
  * an unknown preset workflow short-circuits (its inner stages aren't validated
@@ -21,7 +21,7 @@
21
21
  import { isModuleNotFound } from "./utils.js";
22
22
 
23
23
  /**
24
- * Register the five built-in workflows (arch / build / ship / vet / polish)
24
+ * Register the three built-in workflows (build / polish / vet)
25
25
  * with the rpiv-workflow runtime, if that sibling is installed. A missing
26
26
  * sibling resolves to a no-op; any other failure is re-thrown so genuine bugs
27
27
  * surface rather than hiding behind the absent-sibling path.
@@ -29,7 +29,7 @@ import { isModuleNotFound } from "./utils.js";
29
29
  export async function registerBuiltInWorkflows(): Promise<void> {
30
30
  try {
31
31
  // Thin `/startup` entry (~9ms, no DSL/runner). Register a LAZY provider so
32
- // `built-in-workflows.js` (the ~180ms authoring-DSL graph) builds the five
32
+ // `built-in-workflows.js` (the ~180ms authoring-DSL graph) builds the three
33
33
  // definitions on first `/wf`, not at startup. Missing sibling →
34
34
  // ERR_MODULE_NOT_FOUND → no-op (no `/wf` without it).
35
35
  const { registerBuiltInsProvider, registerBuiltIns } = await import("@juicesharp/rpiv-workflow/startup");
@@ -16,8 +16,7 @@
16
16
 
17
17
  import type { ExtensionUIContext } from "@earendil-works/pi-coding-agent";
18
18
 
19
- import type { LaneUsage } from "./lane-usage.js";
20
- import { toLaneUsage } from "./lane-usage.js";
19
+ import { addLaneUsage, type LaneUsage, toLaneUsage } from "./lane-usage.js";
21
20
  import { emitQuestionAsked, emitQuestionResolved } from "./question-lifecycle.js";
22
21
 
23
22
  /** Lane status taxonomy — mirrors rpiv-workflow's RunTermination.status (types.ts:145-149). */
@@ -137,26 +136,6 @@ export interface UnitLane {
137
136
  * `streaming…` label. Absent (undefined) before the first stage starts.
138
137
  */
139
138
  export interface LaneProgress {
140
- /**
141
- * Path ordinal — the count of stage ACTIVATIONS along the executed walk
142
- * (`idx + 1`), so it climbs on every loop-back / re-entry and is unbounded by
143
- * graph size. This is the "lap" number (`↻7`), NOT a fraction numerator: it is
144
- * incommensurable with `totalStages` (distance travelled vs. map size).
145
- */
146
- stageNumber: number;
147
- /** Distinct reachable stage NODES in the workflow graph (static, BFS at launch). */
148
- totalStages: number;
149
- /**
150
- * Distinct stage nodes VISITED so far (≤ totalStages) — the one quantity for
151
- * which `visited/totalStages ≤ 1` holds, so it (not `stageNumber`) is the
152
- * progress-fraction numerator. Counts nodes actually entered PLUS the recovery
153
- * arms a gate bypassed for good (build's slice-fix/plan-fix/code-fix, credited via onRoute's
154
- * `bypassed`), so a clean run reaches `totalStages` while its terminal stage
155
- * runs instead of capping below until the onWorkflowEnd snap. Undefined for
156
- * snapshots built outside the lifecycle bridge; the renderer falls back to
157
- * `min(stageNumber, totalStages)`.
158
- */
159
- visited?: number;
160
139
  stageName: string;
161
140
  /** Glyph selector: running spinner · ⟲ retry · ✗ error. */
162
141
  phase: "running" | "retry" | "error";
@@ -202,17 +181,16 @@ export interface LaneEntry {
202
181
  * generation only; the final generation's snapshots survive retirement.
203
182
  */
204
183
  readonly units: Map<number, UnitLane>;
184
+ /** Per-stage orchestrator token usage, keyed by stage name in execution (insertion)
185
+ * order. Folded by `foldStageUsage` at each stage transition (BEFORE `clearUnitLanes`
186
+ * empties `units`), so a completed stage's tokens survive even though its units are
187
+ * gone. The CURRENT running stage's tokens are NOT yet folded — they read live off
188
+ * `units` at render time (`renderStageBreakdown`). Survives resume reactivation
189
+ * (`recordRun` clears `units`, not this). Never mixed with subagent tokens
190
+ * (`subagent-usage.ts`) — unified only at render time. */
191
+ readonly stageUsage: Map<string, LaneUsage>;
205
192
  /** Live stage progress; undefined until the first onStageStart. */
206
193
  progress: LaneProgress | undefined;
207
- /**
208
- * Distinct stage names entered over this run's life — the accumulator behind
209
- * `LaneProgress.visited`. Lives on the entry (not the per-event progress
210
- * snapshot, which the bridge rebuilds wholesale) so a cyclic walk that revisits
211
- * a stage never inflates the count. Retained across a same-session resume
212
- * (those stages WERE visited); only a launcher restart resets it, which resets
213
- * the whole lane anyway. Lazily created by `noteVisitedStage`.
214
- */
215
- visitedStages?: Set<string>;
216
194
  /**
217
195
  * Terminal failure cause — `result.termination.error` captured at
218
196
  * `retireRun`, the readable reason a `failed`/`aborted`/`cancelled` run ended.
@@ -220,6 +198,17 @@ export interface LaneEntry {
220
198
  * full. Absent for a `completed` run (no error) and while still running.
221
199
  */
222
200
  error?: string;
201
+ /**
202
+ * Primary artifact path at run termination — `RunWorkflowResult.lastArtifact`
203
+ * captured at `retireRun` (the runner's terminal `onWorkflowEnd`), so a completed
204
+ * lane row can surface `→ .rpiv/artifacts/<bucket>/<file>.md` as a trailing
205
+ * segment. Undefined for a side-effect-only run (no `produces` stage emitted a
206
+ * primary artifact) and for aborted/failed runs (the terminal writers pass ≤3
207
+ * args). Cleared on resume (`recordRun` reactivation) so a resumed run never
208
+ * leaks the prior run's path — mirroring the `error`/`progress`/`needsInputSince`
209
+ * clears.
210
+ */
211
+ lastArtifact?: string;
223
212
  /**
224
213
  * When this lane first started waiting on a deferred foreground question
225
214
  * — `Date.now()` stamped on the FIRST enqueue that finds the clock
@@ -327,6 +316,7 @@ export function recordRun(runId: string, name: string, meta?: { workflow?: strin
327
316
  }
328
317
  existing.units.clear(); // drop the prior run's per-unit sessions + terminal snapshots
329
318
  existing.error = undefined; // clear the prior run's terminal failure reason
319
+ existing.lastArtifact = undefined; // clear the prior run's primary artifact path
330
320
  existing.progress = undefined; // clear stale stage progress
331
321
  existing.needsInputSince = undefined; // clear any stale needs-input clock
332
322
  } else {
@@ -337,6 +327,7 @@ export function recordRun(runId: string, name: string, meta?: { workflow?: strin
337
327
  input: meta?.input,
338
328
  status: "running",
339
329
  units: new Map<number, UnitLane>(),
330
+ stageUsage: new Map<string, LaneUsage>(),
340
331
  progress: undefined,
341
332
  });
342
333
  }
@@ -422,7 +413,12 @@ function captureSnapshotInto(unit: UnitLane, session: LaneSession): void {
422
413
  }
423
414
  }
424
415
 
425
- export function retireRun(runId: string, status: Exclude<LaneStatus, "running">, error?: string): void {
416
+ export function retireRun(
417
+ runId: string,
418
+ status: Exclude<LaneStatus, "running">,
419
+ error?: string,
420
+ lastArtifact?: string,
421
+ ): void {
426
422
  const entry = state().lanes.get(runId);
427
423
  if (!entry) return;
428
424
  // Idempotent: FIRST retire wins. A lane can be retired by more than one path —
@@ -436,6 +432,7 @@ export function retireRun(runId: string, status: Exclude<LaneStatus, "running">,
436
432
  if (entry.status !== "running") return;
437
433
  entry.status = status;
438
434
  if (error !== undefined) entry.error = error; // terminal failure reason
435
+ if (lastArtifact !== undefined) entry.lastArtifact = lastArtifact; // primary artifact path (completed runs)
439
436
  // Capture units with a parked question BEFORE the settle loop clears pendingInput,
440
437
  // so each affected unit is addressable for a `cleared` emit after notify().
441
438
  const cleared: number[] = [];
@@ -467,11 +464,35 @@ export function retireRun(runId: string, status: Exclude<LaneStatus, "running">,
467
464
  * (with `currentSession` already gone), the snapshot is already in place. Best-effort:
468
465
  * a missing/evicted lane is a no-op. Does NOT notify — the paired `setCurrentSession`
469
466
  * that immediately follows in the host does.
467
+ *
468
+ * Capture-side fold-at-overwrite: a sequential multi-child stage parks EVERY child
469
+ * on the SAME `SINGLE_UNIT_KEY` slot, so `captureSnapshotInto`'s `finalUsage =`
470
+ * overwrite would evict each OUTGOING child's tokens before the stage-end
471
+ * `foldStageUsage` can count them (losing all but the last). Fold the unit's
472
+ * already-parked `finalUsage` (the outgoing child) into the CURRENT stage bucket
473
+ * BEFORE the overwrite; the overwrite then EVICTS it from the slot, so
474
+ * `foldStageUsage` cannot re-count it. Capture-time (children 1..N-1) and stage-end
475
+ * (surviving last child N) touch disjoint sets → fold-exactly-once, no double-count.
476
+ * Fail-soft by composition: no parked `finalUsage` (first capture / a failed
477
+ * getUsage) skips the fold, and `addStageUsage`'s own guard drops an unset
478
+ * stageName (pre-first-stage capture). Usage-only — `finalBranch`/`finalCwd`/
479
+ * `finalToolDefs` stay last-writer-wins across the overwrite.
480
+ *
481
+ * The fold is gated on a LIVE lane (`status === "running"`): the dock's optimistic
482
+ * `x` cancel calls `retireRun` BEFORE this teardown capture, and retire's own
483
+ * snapshot parks the SAME still-live child's usage onto the slot — so the parked
484
+ * value here is a same-child re-capture, not an outgoing sibling. Folding it would
485
+ * count the child twice (once in the bucket, once via the retained unit at render).
486
+ * Post-retirement the overwrite-only path is exactly right.
470
487
  */
471
488
  export function captureFinalSnapshot(runId: string, index: number, session: LaneSession): void {
472
489
  const entry = state().lanes.get(runId);
473
490
  if (!entry) return;
474
- captureSnapshotInto(upsertUnit(entry, index), session);
491
+ const unit = upsertUnit(entry, index);
492
+ if (unit.finalUsage && entry.status === "running") {
493
+ addStageUsage(runId, entry.progress?.stageName, unit.finalUsage);
494
+ }
495
+ captureSnapshotInto(unit, session);
475
496
  }
476
497
 
477
498
  /**
@@ -594,6 +615,32 @@ export function clearUnitLanes(runId: string): void {
594
615
  for (const idx of cleared) emitQuestionResolved(runId, idx, "cleared");
595
616
  }
596
617
 
618
+ /** Pairwise-accumulate one stage's usage into the `stageUsage` bucket for `runId` +
619
+ * `stageName` via `addLaneUsage` (so a re-folded stage SUMS, never overwrites). No-op
620
+ * on undefined usage / missing lane / undefined stageName — a pre-first-stage fold, or a
621
+ * lane with no live progress, records nothing. Does NOT notify (the paired
622
+ * `clearUnitLanes`/`setLaneProgress` that follows in the bridge does). */
623
+ export function addStageUsage(runId: string, stageName: string | undefined, usage: LaneUsage | undefined): void {
624
+ if (usage === undefined || stageName === undefined) return;
625
+ const entry = state().lanes.get(runId);
626
+ if (!entry) return;
627
+ const existing = entry.stageUsage.get(stageName);
628
+ entry.stageUsage.set(stageName, existing ? addLaneUsage(existing, usage)! : usage);
629
+ }
630
+
631
+ /** Fold the CURRENT stage's per-unit orchestrator tokens into its `stageUsage` bucket.
632
+ * Reads the OUTGOING stage name off `progress.stageName` (the bridge calls this BEFORE
633
+ * `setLaneProgress` flips to the next name and BEFORE `clearUnitLanes` empties `units`),
634
+ * then folds each unit's effective `unitUsage` (teardown snapshot else live child) into
635
+ * that stage's bucket via `addStageUsage`. No-op when the stage name is unset or `units`
636
+ * is empty. Does NOT notify — the paired `clearUnitLanes`/`setLaneProgress` does. */
637
+ export function foldStageUsage(runId: string): void {
638
+ const lane = state().lanes.get(runId);
639
+ const stageName = lane?.progress?.stageName;
640
+ if (!lane || stageName === undefined || lane.units.size === 0) return;
641
+ for (const unit of lane.units.values()) addStageUsage(runId, stageName, unitUsage(unit));
642
+ }
643
+
597
644
  /** Seed the CURRENT fan-out generation's unit sub-rows as PENDING (bridge `onLoopStart`
598
645
  * for a fanout): each declared unit's sub-lane is created FRESH with `status: "pending"`
599
646
  * keyed by its declared array `index`, so the dock fans out the generation the instant
@@ -625,42 +672,6 @@ export function setLaneProgress(runId: string, progress: LaneProgress | undefine
625
672
  notify();
626
673
  }
627
674
 
628
- /**
629
- * Record a stage entry and return the running count of DISTINCT stages visited
630
- * for this run — the `LaneProgress.visited` numerator. Idempotent per stage name
631
- * (a `Set`), so the bridge can call it from every per-stage event (start, retry,
632
- * unit-end) and always read back the correct distinct count without inflating it
633
- * on a loop-back. Returns 0 for a missing/evicted run (best-effort, like
634
- * `setLaneProgress`). Does NOT `notify()` — the paired `setLaneProgress` does.
635
- */
636
- export function noteVisitedStage(runId: string, stageName: string): number {
637
- const entry = state().lanes.get(runId);
638
- if (!entry) return 0;
639
- const visited = entry.visitedStages ?? new Set<string>();
640
- visited.add(stageName);
641
- entry.visitedStages = visited;
642
- return visited.size;
643
- }
644
-
645
- /**
646
- * Seed the distinct-visited accumulator with stage names the engine already walked
647
- * — the reconstructed `RunContext.visited` carried on `onWorkflowStart`'s
648
- * `LifecycleContext.visited`. UNIONS into the set (never replaces), so it composes
649
- * with `noteVisitedStage`: a fresh run seeds an empty list (no-op), while a RESUMED
650
- * run seeds its reconstructed walk so the first post-resume `noteVisitedStage` reads
651
- * back the true distinct count instead of recounting from zero (the `1/17`-near-done
652
- * bug). Idempotent + best-effort (a missing/evicted run no-ops). Returns the running
653
- * size. Does NOT `notify()` — the numerator surfaces on the next `setLaneProgress`.
654
- */
655
- export function seedVisitedStages(runId: string, names: readonly string[]): number {
656
- const entry = state().lanes.get(runId);
657
- if (!entry) return 0;
658
- const visited = entry.visitedStages ?? new Set<string>();
659
- for (const name of names) visited.add(name);
660
- entry.visitedStages = visited;
661
- return visited.size;
662
- }
663
-
664
675
  /** Enqueue a deferred foreground-stage UI request onto a UNIT's queue (relay).
665
676
  * Stamps the LANE-level needs-input clock on the FIRST enqueue across the
666
677
  * lane that finds it unset (held across a transient drain→refill so the aging