@juicesharp/rpiv-pi 2.6.4 → 2.7.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.
Files changed (33) hide show
  1. package/docs/skills.md +1 -1
  2. package/extensions/rpiv-core/agents.ts +10 -13
  3. package/extensions/rpiv-core/artifact-collector.ts +111 -6
  4. package/extensions/rpiv-core/bash-timeout.ts +12 -2
  5. package/extensions/rpiv-core/built-in-workflows.ts +329 -3528
  6. package/extensions/rpiv-core/built-ins/citations.ts +357 -0
  7. package/extensions/rpiv-core/built-ins/gates.ts +613 -0
  8. package/extensions/rpiv-core/built-ins/goal-baseline.ts +269 -0
  9. package/extensions/rpiv-core/built-ins/grade-panel.ts +199 -0
  10. package/extensions/rpiv-core/built-ins/index.ts +47 -0
  11. package/extensions/rpiv-core/built-ins/plan-cite.ts +219 -0
  12. package/extensions/rpiv-core/built-ins/plan-phases.ts +424 -0
  13. package/extensions/rpiv-core/built-ins/priors.ts +352 -0
  14. package/extensions/rpiv-core/built-ins/reconcile.ts +283 -0
  15. package/extensions/rpiv-core/built-ins/remediation.ts +96 -0
  16. package/extensions/rpiv-core/built-ins/scope-checks.ts +378 -0
  17. package/extensions/rpiv-core/built-ins/shared.ts +17 -1
  18. package/extensions/rpiv-core/built-ins/slice-checks.ts +420 -0
  19. package/extensions/rpiv-core/built-ins/slices.ts +288 -0
  20. package/extensions/rpiv-core/constants.ts +5 -1
  21. package/extensions/rpiv-core/lane-console.ts +9 -2
  22. package/extensions/rpiv-core/lane-list.ts +10 -1
  23. package/extensions/rpiv-core/question-lifecycle.ts +2 -2
  24. package/extensions/rpiv-core/register-built-in-workflows.ts +2 -2
  25. package/extensions/rpiv-core/run-lane-registry.ts +83 -83
  26. package/package.json +2 -2
  27. package/skills/elaborate/SKILL.md +1 -1
  28. package/skills/implement/SKILL.md +1 -0
  29. package/skills/plan/SKILL.md +3 -1
  30. package/skills/remediate/SKILL.md +18 -15
  31. package/skills/synthesize/SKILL.md +1 -0
  32. package/skills/validate/SKILL.md +26 -19
  33. package/skills/validate/templates/validation.md +1 -1
@@ -0,0 +1,288 @@
1
+ /**
2
+ * The slice-map grammar and slice-DAG layer: frontmatter parsing, dependency
3
+ * edges, clustering, coverage units, and the design/subplan fanouts built on
4
+ * them.
5
+ */
6
+ import { basename } from "node:path";
7
+ import { parseFrontmatter } from "@earendil-works/pi-coding-agent";
8
+ import { fanout, handleToString, type RunView } from "@juicesharp/rpiv-workflow/registration";
9
+ import { countHeadingsOutsideFences } from "./markdown-fence.js";
10
+ import { haltPreflight, latestFsArtifact, MAX_PHASES, type PhaseRecord, readArtifactFile } from "./shared.js";
11
+
12
+ /** `## Slice N:` headings — the source of truth a slice map's `slices:` array is derived from. */
13
+ const SLICE_HEADING_RE = /^## Slice (\d+):/gm;
14
+
15
+ /**
16
+ * Parse a slice map's `slices:` frontmatter into `{ n, title }` records,
17
+ * derive-checked against the body's `## Slice N:` headings and the required
18
+ * `slice_count` scalar — the slices twin of `planPhaseRecords`. A mismatch means
19
+ * the producer's rebuild was skipped or the array went stale; throw rather than
20
+ * dispatch a wrong unit list.
21
+ */
22
+ const sliceRecords = (content: string, who: string, path: string): readonly PhaseRecord[] => {
23
+ const { frontmatter } = parseFrontmatter(content);
24
+ const fm = frontmatter as Record<string, unknown>;
25
+ const raw = fm.slices;
26
+ const slices = Array.isArray(raw) ? raw : [];
27
+ const headingCount = countHeadingsOutsideFences(content, SLICE_HEADING_RE);
28
+ if (slices.length !== headingCount) {
29
+ throw haltPreflight(
30
+ who,
31
+ `${who}: slice map ${path} has mismatched slices`,
32
+ `${who}: slice map ${path} frontmatter slices (${slices.length}) ≠ '## Slice N:' headings (${headingCount}) — the derived array is stale against the body`,
33
+ );
34
+ }
35
+ if ((slices.length > 0 || fm.slice_count !== undefined) && fm.slice_count !== slices.length) {
36
+ throw haltPreflight(
37
+ who,
38
+ `${who}: slice map ${path} has invalid slice_count`,
39
+ `${who}: slice map ${path} frontmatter slice_count (${String(fm.slice_count)}) ≠ slices length (${slices.length}) — rebuild slice_count from the '## Slice N:' headings`,
40
+ );
41
+ }
42
+ return slices.map((entry, index) => {
43
+ const e = (entry ?? {}) as Record<string, unknown>;
44
+ return {
45
+ entry: e,
46
+ n: typeof e.n === "number" ? e.n : index + 1,
47
+ title: typeof e.title === "string" ? e.title : "",
48
+ index,
49
+ total: slices.length,
50
+ };
51
+ });
52
+ };
53
+
54
+ /** The slice-number deps a slice-map entry declares (empty when absent). */
55
+ const sliceDeps = (entry: Record<string, unknown>): number[] => {
56
+ const raw = entry.deps;
57
+ return Array.isArray(raw) ? raw.filter((d): d is number => typeof d === "number") : [];
58
+ };
59
+
60
+ /** Fan `design-slice` out over the latest slice map's `slices:` array — one design
61
+ * session per slice, dependency-ordered. `deps` (slice-N unit ids) drive the wave
62
+ * scheduler; `depArtifactFlag` injects each completed dependency's design path as
63
+ * `--upstream <path>` so a dependent slice reads its dependency's decided Key Interfaces. */
64
+ const SLICE_DESIGN_FANOUT = fanout({
65
+ source: "slices",
66
+ unit: { by: "frontmatter-array", pattern: "slices" },
67
+ max: MAX_PHASES,
68
+ depArtifactFlag: "--upstream",
69
+ units: ({ state, cwd }) => {
70
+ const doc = latestFsArtifact(state, "slices");
71
+ if (doc?.handle.kind !== "fs") return [];
72
+ const path = doc.handle.path;
73
+ const promptPath = handleToString(doc.handle);
74
+ return sliceRecords(readArtifactFile(path, cwd), "SLICE_DESIGN_FANOUT", path).map((r) => ({
75
+ prompt: `${promptPath} Slice ${r.n}: ${r.title}`.trimEnd(),
76
+ label: `slice ${r.index + 1}/${r.total}`,
77
+ id: `slice-${r.n}`,
78
+ deps: sliceDeps(r.entry).map((n) => `slice-${n}`), // directed edges → unit ids (slice-N)
79
+ }));
80
+ },
81
+ });
82
+
83
+ /** Max slices per synth cluster — a context-budget proxy; oversized DAG components split by this. */
84
+ const MAX_CLUSTER_SLICES = 6;
85
+
86
+ /**
87
+ * Group slices into clusters = connected components of the `deps` DAG (a slice
88
+ * and everything it transitively depends on / that depends on it land together),
89
+ * so coupled slices reconcile inside ONE subplan pass and only cross-cluster
90
+ * seams reach the root. Components larger than `MAX_CLUSTER_SLICES` are chunked
91
+ * (by slice number) to bound each pass's context. Returns clusters of slice
92
+ * numbers, each sorted ascending; components ordered by their smallest slice.
93
+ */
94
+ const clusterSliceDag = (records: readonly PhaseRecord[]): number[][] => {
95
+ const ns = records.map((r) => r.n);
96
+ const parent = new Map<number, number>(ns.map((n) => [n, n]));
97
+ const find = (x: number): number => {
98
+ let root = x;
99
+ while (parent.get(root) !== root) root = parent.get(root) ?? root;
100
+ let cur = x;
101
+ while (parent.get(cur) !== root) {
102
+ const next = parent.get(cur) ?? root;
103
+ parent.set(cur, root);
104
+ cur = next;
105
+ }
106
+ return root;
107
+ };
108
+ const union = (a: number, b: number): void => {
109
+ const ra = find(a);
110
+ const rb = find(b);
111
+ if (ra !== rb) parent.set(ra, rb);
112
+ };
113
+ for (const r of records) for (const d of sliceDeps(r.entry)) if (parent.has(d)) union(r.n, d);
114
+ const byRoot = new Map<number, number[]>();
115
+ for (const n of ns) {
116
+ const root = find(n);
117
+ const arr = byRoot.get(root);
118
+ if (arr) arr.push(n);
119
+ else byRoot.set(root, [n]);
120
+ }
121
+ const clusters: number[][] = [];
122
+ for (const comp of [...byRoot.values()].sort((a, b) => (a[0] ?? 0) - (b[0] ?? 0))) {
123
+ const sorted = [...comp].sort((a, b) => a - b);
124
+ for (let i = 0; i < sorted.length; i += MAX_CLUSTER_SLICES) {
125
+ clusters.push(sorted.slice(i, i + MAX_CLUSTER_SLICES));
126
+ }
127
+ }
128
+ return clusters;
129
+ };
130
+
131
+ /**
132
+ * A directed dependency cycle in the slice DAG (`A→B→…→A`), returned as the slice
133
+ * numbers on the cycle; empty when acyclic. `clusterSliceDag` groups by the
134
+ * UNDIRECTED connected component, which a directed cycle survives — so the
135
+ * design-readiness gate needs this separate directed check. A cycle is the true
136
+ * independence defect (slices in a cycle cannot be designed independently); the
137
+ * deterministic floor catches it without an LLM coin-flip.
138
+ */
139
+ const sliceDepCycle = (records: readonly PhaseRecord[]): number[] => {
140
+ const deps = new Map<number, number[]>(records.map((r) => [r.n, sliceDeps(r.entry)]));
141
+ const WHITE = 0;
142
+ const GRAY = 1;
143
+ const BLACK = 2;
144
+ const color = new Map<number, number>();
145
+ const stack: number[] = [];
146
+ let cycle: number[] = [];
147
+ const visit = (n: number): boolean => {
148
+ color.set(n, GRAY);
149
+ stack.push(n);
150
+ for (const d of deps.get(n) ?? []) {
151
+ if (!deps.has(d)) continue; // a dangling dep is a derive/numbering concern, not a cycle
152
+ const c = color.get(d) ?? WHITE;
153
+ if (c === GRAY) {
154
+ cycle = stack.slice(stack.indexOf(d));
155
+ return true;
156
+ }
157
+ if (c === WHITE && visit(d)) return true;
158
+ }
159
+ stack.pop();
160
+ color.set(n, BLACK);
161
+ return false;
162
+ };
163
+ for (const r of records) if ((color.get(r.n) ?? WHITE) === WHITE && visit(r.n)) break;
164
+ return cycle;
165
+ };
166
+
167
+ /**
168
+ * One frozen coverage unit — the brief's ID'd decomposition, set once at the
169
+ * first (human-confirmed) cut and conserved across every reslice. The conserved
170
+ * quantity the gate was missing: a reslice may REDISTRIBUTE units across slices,
171
+ * never DROP one — which is what closes the "pass by simplifying / shrinking
172
+ * scope" escape hatch the sizing dimensions can't see.
173
+ */
174
+ interface CoverageUnit {
175
+ id: string;
176
+ brief: string;
177
+ }
178
+
179
+ /** Parse a slice map's `coverage:` frontmatter into `{ id, brief }` units (empty when absent). */
180
+ const sliceCoverageUnits = (content: string): CoverageUnit[] => {
181
+ const { frontmatter } = parseFrontmatter(content);
182
+ const raw = (frontmatter as Record<string, unknown>).coverage;
183
+ if (!Array.isArray(raw)) return [];
184
+ return raw.flatMap((e) => {
185
+ const o = (e ?? {}) as Record<string, unknown>;
186
+ return typeof o.id === "string" ? [{ id: o.id, brief: typeof o.brief === "string" ? o.brief : "" }] : [];
187
+ });
188
+ };
189
+
190
+ /** The coverage-unit ids a slice entry claims to deliver (its `covers:` array). */
191
+ const sliceCovers = (entry: Record<string, unknown>): string[] => {
192
+ const raw = entry.covers;
193
+ return Array.isArray(raw) ? raw.filter((c): c is string => typeof c === "string") : [];
194
+ };
195
+
196
+ /** A design filename encodes its slice as `…slice-<N>…` — the design-fanout naming convention. */
197
+ const DESIGN_SLICE_RE = /slice-(\d+)/;
198
+
199
+ /**
200
+ * Map slice number → its design artifact path, from the design fanout's published
201
+ * outputs. An identity resolver: it maps an ARTIFACT to a slice NUMBER. It FAILS
202
+ * LOUD only when identity is genuinely UNRESOLVABLE — a design filename that
203
+ * carries no `slice-<N>` token, where a positional `idx + 1` guess would scramble
204
+ * the cluster→design wiring and drop slices.
205
+ *
206
+ * A slice claimed by MORE THAN ONE output is NOT ambiguous: the `designs` channel
207
+ * legitimately accumulates several entries per slice — `slice-design` emits it,
208
+ * then `design-review` re-emits the accepted/edited design on the SAME channel
209
+ * (its documented "latest-wins, same paths" contract, so `subplan`/`synthesize`
210
+ * read the accepted docs). So the newest entry wins, deterministically — throwing
211
+ * on a duplicate would halt every normal run at `subplan`. (The resume re-dispatch
212
+ * that once left CONFLICTING designs on the channel is fixed at its source,
213
+ * so there is no corruption left to fail loud on here.)
214
+ */
215
+ const designPathsBySlice = (state: RunView): Map<number, string> => {
216
+ const bySlice = new Map<number, string>();
217
+ for (const out of state.named.designs ?? []) {
218
+ for (const a of out.artifacts) {
219
+ if (a.handle.kind !== "fs") continue;
220
+ const name = basename(a.handle.path);
221
+ const match = DESIGN_SLICE_RE.exec(name);
222
+ if (!match) {
223
+ throw haltPreflight(
224
+ "designPathsBySlice",
225
+ `designPathsBySlice: design ${name} has no slice number`,
226
+ `designPathsBySlice: design artifact ${a.handle.path} carries no 'slice-<N>' token — cannot resolve which slice it designs; a positional guess would mis-route the cluster→design mapping and drop slices`,
227
+ );
228
+ }
229
+ // Latest design per slice wins — the channel holds multiple entries per
230
+ // slice by design (design-review re-emits), and the newest is authoritative.
231
+ bySlice.set(Number(match[1]), handleToString(a.handle));
232
+ }
233
+ }
234
+ return bySlice;
235
+ };
236
+
237
+ /**
238
+ * Fan `subplan` out over slice-DAG clusters. Each unit merges ONE cluster's
239
+ * per-slice designs into a sub-plan (`--as-subplan`), so no single pass holds
240
+ * every design — the context-bounding twin of the flat fan-in `synthesize`.
241
+ */
242
+ const SYNTH_CLUSTER_FANOUT = fanout({
243
+ source: "designs",
244
+ unit: { by: "slice-dag-cluster", pattern: "clusters" },
245
+ max: MAX_PHASES,
246
+ units: ({ state, cwd }) => {
247
+ const doc = latestFsArtifact(state, "slices");
248
+ if (doc?.handle.kind !== "fs") return [];
249
+ const records = sliceRecords(readArtifactFile(doc.handle.path, cwd), "SYNTH_CLUSTER_FANOUT", doc.handle.path);
250
+ const designBySlice = designPathsBySlice(state);
251
+ // Thread the research the slices rest on into every cluster's subplan pass,
252
+ // so cross-slice constraints and acceptance criteria reach synthesis DIRECTLY
253
+ // (not only via each design's refraction). `synthesize` accepts `--research`
254
+ // in partial mode; the flat `synthesize` fan-in already received it, but the
255
+ // hierarchical cluster fanout dropped it.
256
+ const research = latestFsArtifact(state, "research");
257
+ const researchFlag = research?.handle.kind === "fs" ? ` --research ${handleToString(research.handle)}` : "";
258
+ return clusterSliceDag(records)
259
+ .map((cluster, i) => {
260
+ const designs = cluster
261
+ .map((n) => designBySlice.get(n))
262
+ .filter((p): p is string => p !== undefined)
263
+ .map((p) => `--designs ${p}`);
264
+ if (!designs.length) return undefined;
265
+ return {
266
+ // Stamp each cluster's ordinal into its prompt so the partial-mode pass
267
+ // writes a distinct `_cluster-<k>.md` — a re-dispatched unit must never
268
+ // reuse a sibling's filename and clobber it. `<k>` matches `id: cluster-<k>`.
269
+ prompt: `${designs.join(" ")}${researchFlag} --cluster ${i + 1} --as-subplan`,
270
+ label: `cluster ${i + 1} (slices ${cluster.join(",")})`,
271
+ id: `cluster-${i + 1}`,
272
+ };
273
+ })
274
+ .filter((u): u is { prompt: string; label: string; id: string } => u !== undefined);
275
+ },
276
+ });
277
+
278
+ export {
279
+ clusterSliceDag,
280
+ DESIGN_SLICE_RE,
281
+ designPathsBySlice,
282
+ SLICE_DESIGN_FANOUT,
283
+ SYNTH_CLUSTER_FANOUT,
284
+ sliceCoverageUnits,
285
+ sliceCovers,
286
+ sliceDepCycle,
287
+ sliceRecords,
288
+ };
@@ -3,7 +3,11 @@ export const MSG_TYPE_GIT_CONTEXT = "rpiv-git-context";
3
3
  export const MSG_TYPE_GUIDANCE = "rpiv-guidance";
4
4
  export const MSG_TYPE_PIPELINE_INDEX = "rpiv-pipeline-index";
5
5
  export const MSG_TYPE_POST_COMPACT_CONTEXT = "rpiv-post-compact-context";
6
- /** Timeout for git exec calls (milliseconds). */
6
+ /**
7
+ * Timeout for git exec calls (milliseconds). Mirrors `GIT_EXEC_TIMEOUT_MS` in
8
+ * `packages/rpiv-workflow/outcomes/exec.ts` (stage-time git outcome collectors) —
9
+ * same value, separately owned by design.
10
+ */
7
11
  export const GIT_EXEC_TIMEOUT_MS = 5000;
8
12
  /** Grace period before SIGKILL when terminating a timed-out pi install process. */
9
13
  export const SIGKILL_GRACE_MS = 5000;
@@ -47,6 +47,7 @@ import type { ExtensionUIContext, KeybindingsManager, Theme } from "@earendil-wo
47
47
  import { type Component, Key, matchesKey, type TUI, truncateToWidth } from "@earendil-works/pi-tui";
48
48
  import {
49
49
  computeLaneLayout,
50
+ FALLBACK_ROWS,
50
51
  renderLaneList,
51
52
  renderLiveOutputBorder,
52
53
  renderRecap,
@@ -72,7 +73,13 @@ import {
72
73
  unitNeedsInput,
73
74
  } from "./run-lane-registry.js";
74
75
 
76
+ /** The console renders IN-FLOW, so 0.9 leaves the bottom ~10% of the terminal for the primary
77
+ * footer that keeps rendering below it (a full-screen ratio would push the footer off-screen). */
75
78
  const MAX_HEIGHT_RATIO = 0.9;
79
+ /** Floor on the rendered surface height: the 0.9 ratio of a tiny or unreported terminal would
80
+ * collapse the surface below the chrome it must always show (live-output border + a minimal
81
+ * transcript band + the lane block). */
82
+ const MIN_SURFACE_ROWS = 8;
76
83
  /** The PageUp/PageDown transcript-scroll page size. (The armed band reclaims the full surface
77
84
  * up to `maxRows − chrome`, so this no longer floors the transcript region.) */
78
85
  const TRANSCRIPT_MIN = 4;
@@ -324,8 +331,8 @@ export class LaneConsole implements Component {
324
331
  // ---------------------------------------------------------------------------
325
332
 
326
333
  render(width: number): string[] {
327
- const realRows = (this.tui.terminal as { rows?: number }).rows ?? 24;
328
- const maxRows = Math.max(8, Math.floor(realRows * MAX_HEIGHT_RATIO));
334
+ const realRows = (this.tui.terminal as { rows?: number }).rows ?? FALLBACK_ROWS;
335
+ const maxRows = Math.max(MIN_SURFACE_ROWS, Math.floor(realRows * MAX_HEIGHT_RATIO));
329
336
  const rows = listLanesForDisplay();
330
337
  // Defensive clamp — the row set can shrink between a sync() and this render().
331
338
  const selection = rows.length > 0 ? Math.min(this.selection, rows.length - 1) : 0;
@@ -62,7 +62,16 @@ const RETRY_GLYPH = "⟲";
62
62
  // constant DISPLAY width so the status region starts at the same column on every row.
63
63
  const TAG_COL = 12;
64
64
  const MAX_LABEL_WIDTH = 40;
65
- const LABEL_LEADING = 4 + TAG_COL + 2;
65
+ /** Cells the lane-row head `renderLaneRow` builds: the 2-cell selection gutter
66
+ * (`CURSOR_SELECTED`/`CURSOR_UNSELECTED`) + the status glyph + its trailing space. */
67
+ const LANE_HEAD_CELLS = 4;
68
+ /** The two single-space inter-column separators following the tag and label columns. */
69
+ const LABEL_SEPARATORS = 2;
70
+ /** The label column's fixed lane-row overhead (head + tag column + separators). The measure
71
+ * is lane-row-EXACT but unit-row-APPROXIMATE — `renderUnitRow` leads with 6 cells and no
72
+ * tag column — so the `labelWidth` clamp in `renderLaneList` is deliberately approximate;
73
+ * do not re-derive it from unit rows. */
74
+ const LABEL_LEADING = LANE_HEAD_CELLS + TAG_COL + LABEL_SEPARATORS;
66
75
  const PROGRESS_MIN_WIDTH = 12;
67
76
 
68
77
  /** Per-status glyph; needs-input overrides it (see renderLaneRow). */
@@ -125,8 +125,8 @@ export function emitQuestionAsked(
125
125
 
126
126
  /**
127
127
  * Emit a `resolved` event — call AFTER the registry's `notify()` so a subscriber
128
- * observes the committed settle. Called by `dequeueInput` (`"answered"`) and every
129
- * teardown settle loop (`"cleared"`).
128
+ * observes the committed settle. Called by `dequeueInput` (`"answered"`) and the
129
+ * registry's teardown settle helper `settleAndEmitCleared` (`"cleared"`).
130
130
  */
131
131
  export function emitQuestionResolved(runId: string, unitIndex: number, reason: QuestionResolveReason): void {
132
132
  publish({ kind: "resolved", runId, unitIndex, reason, at: Date.now() });
@@ -21,7 +21,7 @@
21
21
  import { isModuleNotFound } from "./utils.js";
22
22
 
23
23
  /**
24
- * Register the three built-in workflows (build / polish / vet)
24
+ * Register the four built-in workflows (build / polish / vet / ship)
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 three
32
+ // `built-in-workflows.js` (the authoring-DSL graph) builds the four
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");
@@ -295,6 +295,37 @@ function notify(): void {
295
295
  }
296
296
  }
297
297
 
298
+ /**
299
+ * The single teardown settle-and-emit epilogue shared by `recordRun` (resume
300
+ * reactivation), `retireRun`, `evictRun`, and `clearUnitLanes`. Ordering contract:
301
+ * capture each unit with a parked question BEFORE settling (the settle drains the
302
+ * queue that identifies it, so the index must be read first — captured units stay
303
+ * addressable for a `cleared` emit after notify); settle every parked resolver with
304
+ * `undefined` BEFORE the site mutation (a stalled child must never hang on a dangling
305
+ * resolver, whatever teardown follows); run the site-specific mutation (`afterSettle`);
306
+ * `notify()` BEFORE any `cleared` emit — notify listeners run synchronously inline, so
307
+ * a lane subscriber must observe the fully committed teardown, not a half-settled one;
308
+ * then emit `cleared` for ONLY the units that had parked input — a settle that parked
309
+ * nothing publishes nothing, so a fresh `recordRun` notifies without emitting. An
310
+ * undefined `entry` skips the settle loop entirely (the fresh-recordRun path). The
311
+ * unconditional queue truncation is a deliberate dead store at the sites whose queue
312
+ * dies with its map or lane inside `afterSettle`; `retireRun` is the one site whose
313
+ * units survive the settle and rely on it.
314
+ */
315
+ function settleAndEmitCleared(runId: string, entry: LaneEntry | undefined, afterSettle: () => void): void {
316
+ const cleared: number[] = [];
317
+ if (entry) {
318
+ for (const unit of entry.units.values()) {
319
+ if (unit.pendingInput.length > 0) cleared.push(unit.index);
320
+ for (const p of unit.pendingInput) p.resolve(undefined); // never strand a child's resolver
321
+ unit.pendingInput.length = 0;
322
+ }
323
+ }
324
+ afterSettle();
325
+ notify();
326
+ for (const idx of cleared) emitQuestionResolved(runId, idx, "cleared");
327
+ }
328
+
298
329
  // ---------------------------------------------------------------------------
299
330
  // Mutations — every one notifies.
300
331
  // ---------------------------------------------------------------------------
@@ -312,42 +343,31 @@ function notify(): void {
312
343
  export function recordRun(runId: string, name: string, meta?: { workflow?: string; input?: string }): void {
313
344
  const { lanes } = state();
314
345
  const existing = lanes.get(runId);
315
- // Units with a parked question, captured BEFORE the reactivation settle clears
316
- // them so each affected unit is addressable for a `cleared` emit after notify().
317
- const cleared: number[] = [];
318
- if (existing) {
319
- existing.name = name;
320
- existing.workflow = meta?.workflow ?? existing.workflow;
321
- existing.input = meta?.input ?? existing.input;
322
- existing.status = "running"; // reactivate a retained terminal lane (resume)
323
- // Settle any queued input before clearing units — mirrors retireRun/evictRun/
324
- // clearUnitLanes so a child can never hang on a dangling resolver across reactivation.
325
- for (const unit of existing.units.values()) {
326
- if (unit.pendingInput.length > 0) cleared.push(unit.index);
327
- for (const p of unit.pendingInput) p.resolve(undefined);
346
+ settleAndEmitCleared(runId, existing, () => {
347
+ if (existing) {
348
+ existing.name = name;
349
+ existing.workflow = meta?.workflow ?? existing.workflow;
350
+ existing.input = meta?.input ?? existing.input;
351
+ existing.status = "running"; // reactivate a retained terminal lane (resume)
352
+ existing.units.clear(); // drop the prior run's per-unit sessions + terminal snapshots
353
+ existing.error = undefined; // clear the prior run's terminal failure reason
354
+ existing.lastArtifact = undefined; // clear the prior run's primary artifact path
355
+ existing.recap = undefined; // clear the prior run's end-of-run summary
356
+ existing.progress = undefined; // clear stale stage progress
357
+ existing.needsInputSince = undefined; // clear any stale needs-input clock
358
+ } else {
359
+ lanes.set(runId, {
360
+ runId,
361
+ name,
362
+ workflow: meta?.workflow,
363
+ input: meta?.input,
364
+ status: "running",
365
+ units: new Map<number, UnitLane>(),
366
+ stageUsage: new Map<string, LaneUsage>(),
367
+ progress: undefined,
368
+ });
328
369
  }
329
- existing.units.clear(); // drop the prior run's per-unit sessions + terminal snapshots
330
- existing.error = undefined; // clear the prior run's terminal failure reason
331
- existing.lastArtifact = undefined; // clear the prior run's primary artifact path
332
- existing.recap = undefined; // clear the prior run's end-of-run summary
333
- existing.progress = undefined; // clear stale stage progress
334
- existing.needsInputSince = undefined; // clear any stale needs-input clock
335
- } else {
336
- lanes.set(runId, {
337
- runId,
338
- name,
339
- workflow: meta?.workflow,
340
- input: meta?.input,
341
- status: "running",
342
- units: new Map<number, UnitLane>(),
343
- stageUsage: new Map<string, LaneUsage>(),
344
- progress: undefined,
345
- });
346
- }
347
- notify();
348
- // Emit AFTER notify() — only a reactivation that settled parked questions publishes;
349
- // a brand-new run has an empty `cleared` and publishes nothing.
350
- for (const idx of cleared) emitQuestionResolved(runId, idx, "cleared");
370
+ });
351
371
  }
352
372
 
353
373
  /**
@@ -446,27 +466,20 @@ export function retireRun(
446
466
  entry.status = status;
447
467
  if (error !== undefined) entry.error = error; // terminal failure reason
448
468
  if (lastArtifact !== undefined) entry.lastArtifact = lastArtifact; // primary artifact path (completed runs)
449
- // Capture units with a parked question BEFORE the settle loop clears pendingInput,
450
- // so each affected unit is addressable for a `cleared` emit after notify().
451
- const cleared: number[] = [];
452
- for (const unit of entry.units.values()) {
453
- if (unit.pendingInput.length > 0) cleared.push(unit.index);
454
- // Snapshot from a STILL-LIVE session if one is attached (the `x` path). In the
455
- // normal detached path the host already captured per unit via
456
- // `captureFinalSnapshot` and dropped the session, so `currentSession` is
457
- // undefined here — DON'T re-snapshot (now per unit).
458
- if (unit.currentSession) captureSnapshotInto(unit, unit.currentSession);
459
- unit.currentSession = undefined; // drop the live session; KEEP finalBranch
460
- // A never-ended unit reads terminal — including a pending unit that never fired
461
- // onUnitStart (a fanout generation that retired before its units dispatched).
462
- if (unit.status === "running" || unit.status === "pending") unit.status = "done";
463
- for (const p of unit.pendingInput) p.resolve(undefined); // never strand a child's resolver
464
- unit.pendingInput.length = 0;
465
- }
466
- entry.needsInputSince = undefined;
467
- notify();
468
- // Emit AFTER notify() — only units that HAD pending input publish a `cleared`.
469
- for (const idx of cleared) emitQuestionResolved(runId, idx, "cleared");
469
+ settleAndEmitCleared(runId, entry, () => {
470
+ for (const unit of entry.units.values()) {
471
+ // Snapshot from a STILL-LIVE session if one is attached (the `x` path). In the
472
+ // normal detached path the host already captured per unit via
473
+ // `captureFinalSnapshot` and dropped the session, so `currentSession` is
474
+ // undefined here — DON'T re-snapshot (now per unit).
475
+ if (unit.currentSession) captureSnapshotInto(unit, unit.currentSession);
476
+ unit.currentSession = undefined; // drop the live session; KEEP finalBranch
477
+ // A never-ended unit reads terminal — including a pending unit that never fired
478
+ // onUnitStart (a fanout generation that retired before its units dispatched).
479
+ if (unit.status === "running" || unit.status === "pending") unit.status = "done";
480
+ }
481
+ entry.needsInputSince = undefined;
482
+ });
470
483
  }
471
484
 
472
485
  /**
@@ -540,17 +553,9 @@ export function evictRun(runId: string): void {
540
553
  const { lanes } = state();
541
554
  const entry = lanes.get(runId);
542
555
  if (!entry) return;
543
- // Capture units with a parked question BEFORE the settle, so each affected unit is
544
- // addressable for a `cleared` emit after notify().
545
- const cleared: number[] = [];
546
- for (const unit of entry.units.values()) {
547
- if (unit.pendingInput.length > 0) cleared.push(unit.index);
548
- for (const p of unit.pendingInput) p.resolve(undefined);
549
- }
550
- lanes.delete(runId);
551
- notify();
552
- // Emit AFTER notify() — only units that HAD pending input publish a `cleared`.
553
- for (const idx of cleared) emitQuestionResolved(runId, idx, "cleared");
556
+ settleAndEmitCleared(runId, entry, () => {
557
+ lanes.delete(runId);
558
+ });
554
559
  }
555
560
 
556
561
  /** Update a lane's status (best-effort — a missing lane is a no-op). */
@@ -626,18 +631,10 @@ export function sweepRunningUnits(runId: string, status: "done" | "failed"): voi
626
631
  export function clearUnitLanes(runId: string): void {
627
632
  const entry = state().lanes.get(runId);
628
633
  if (!entry || entry.units.size === 0) return;
629
- // Capture units with a parked question BEFORE the settle, so each affected unit is
630
- // addressable for a `cleared` emit after notify().
631
- const cleared: number[] = [];
632
- for (const unit of entry.units.values()) {
633
- if (unit.pendingInput.length > 0) cleared.push(unit.index);
634
- for (const p of unit.pendingInput) p.resolve(undefined);
635
- }
636
- entry.units.clear();
637
- entry.needsInputSince = undefined;
638
- notify();
639
- // Emit AFTER notify() — only units that HAD pending input publish a `cleared`.
640
- for (const idx of cleared) emitQuestionResolved(runId, idx, "cleared");
634
+ settleAndEmitCleared(runId, entry, () => {
635
+ entry.units.clear();
636
+ entry.needsInputSince = undefined;
637
+ });
641
638
  }
642
639
 
643
640
  /** Pairwise-accumulate one stage's usage into the `stageUsage` bucket for `runId` +
@@ -700,11 +697,14 @@ export function setLaneProgress(runId: string, progress: LaneProgress | undefine
700
697
  /** Enqueue a deferred foreground-stage UI request onto a UNIT's queue (relay).
701
698
  * Stamps the LANE-level needs-input clock on the FIRST enqueue across the
702
699
  * lane that finds it unset (held across a transient drain→refill so the aging
703
- * heading never resets mid-wait). A missing run settles immediately so the child
704
- * never hangs. */
700
+ * heading never resets mid-wait). A missing run — or a retired (non-"running")
701
+ * lane — settles immediately so the child never hangs: the x-key abort races
702
+ * the child's relay park, and a park landing AFTER retireRun's settle pass
703
+ * would strand forever (first-retire-wins means no later settle runs), pinning
704
+ * the needs-input clock and the warp Blocked badge until manual evict/answer. */
705
705
  export function enqueueInput(runId: string, index: number, pending: PendingInput): void {
706
706
  const entry = state().lanes.get(runId);
707
- if (!entry) {
707
+ if (entry?.status !== "running") {
708
708
  pending.resolve(undefined);
709
709
  return;
710
710
  }
@@ -712,7 +712,7 @@ export function enqueueInput(runId: string, index: number, pending: PendingInput
712
712
  upsertUnit(entry, index).pendingInput.push(pending);
713
713
  notify();
714
714
  // Emit AFTER notify() so a lifecycle subscriber observes the committed park. The
715
- // missing-run early-return above emits nothing (no question was ever parked).
715
+ // settle-immediately early-return above emits nothing (no question was ever parked).
716
716
  emitQuestionAsked(runId, index, entry.name, entry.workflow, entry.input);
717
717
  }
718
718
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juicesharp/rpiv-pi",
3
- "version": "2.6.4",
3
+ "version": "2.7.1",
4
4
  "description": "A skill-based development workflow for Pi Agent. 29 contract-carrying skills (discover → research → design → plan → implement → validate → code-review → commit, and more), the 15 named subagents they dispatch, and four built-in /wf workflows that chain them end to end in detached parallel runs.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -50,7 +50,7 @@
50
50
  ]
51
51
  },
52
52
  "dependencies": {
53
- "@juicesharp/rpiv-config": "^2.6.4",
53
+ "@juicesharp/rpiv-config": "^2.7.1",
54
54
  "typebox": "^1.1.24"
55
55
  },
56
56
  "peerDependencies": {
@@ -63,7 +63,7 @@ Copy values verbatim. `<iso>` is the first tab-separated field (use as `date`);
63
63
  - **Guard.** `git status --porcelain` MUST equal the pre-probe snapshot byte-for-byte when you emit. ANY residue (a missed revert, an untracked file, a mode change) is a BLOCKING error: fail the elaboration, emit nothing, and surface the residue.
64
64
  - **Fix → re-emit.** From the attributed errors, fix the drafted code blocks in the elaboration; re-probe is optional, but emit ONLY blocks that passed every applicable check above. A clean phase still emits unchanged — the self-check is a no-op pass that reverts byte-identical.
65
65
  7. **Write the elaboration doc** (below), `status: ready`. Its filename pairs to the plan so the splice can fold it back deterministically — see Output document.
66
- 8. **Print the path**, then a one-line summary: `Phase N elaborated: <k> files, <m> code blocks`.
66
+ 8. **Print the path**, then a one-line summary: `Phase N elaborated: <k> files, <m> code blocks`. **Your path must be the LAST full `.rpiv/artifacts/...` path in your reply** — refer to any other artifact (a sibling phase's elaboration, the plan) by basename only, never by full path. The workflow collector takes the last full artifact path in your final message as YOUR artifact; a full sibling path after yours misattributes the stage's output.
67
67
 
68
68
  ## Output document
69
69
 
@@ -33,6 +33,7 @@ Rules:
33
33
  - **Never implement, create, or edit another phase's files** — not even if one is missing. You are one unit of a sequenced run; back-filling another phase's work duplicates it and corrupts the next lane.
34
34
  - **A genuinely missing prerequisite is a hard error, not a decision.** If a file your phase must read or edit (one an earlier phase owns) is absent, **STOP and fail** with `prerequisite missing: <path> (expected from an earlier phase)`. Do **not** create it, do **not** `ask_user_question` about it, and do **not** defer your own edits — fail loudly so the run surfaces the ordering defect.
35
35
  - **Never silently defer your phase's own edits.** Apply every change the named phase owns, or fail. A phase that writes a partial slice and checks off nothing is worse than a clean failure.
36
+ - **Repo-located scratch lives under `.rpiv/tmp/`, nowhere else.** Any file you create that is not in your phase's `files:` — a probe script, a fixture, a captured payload — goes under `.rpiv/tmp/` (exempt from the workflow's scope floor) or outside the repo entirely. The floor counts **untracked** files too (`git status -uall`): a scratch file left at the repo root or in an undeclared directory is an undeclared write the downstream `implement-scope-check` flags. Delete repo-located scratch when you're done with it regardless.
36
37
  - Do not read, edit, or check off other phases' sections. Stop and print the closing block as soon as the named phase's own success criteria pass.
37
38
  - **Record a `#### Reconciliation` directive for cross-phase test updates you can't apply yourself.** Under build/vet's parallel implement lane, a correct change in YOUR phase can invalidate a test expectation that lives in a SIBLING phase's landed section — and single-phase mode forbids editing another phase's files. Do NOT edit the sibling's file and do NOT silently skip it: record a `#### Reconciliation` directive in your OWN phase's section. The directive is a machine-findable, machine-applicable `find → replace` against a single repo-root-relative test target, so the downstream `reconcile` stage can apply it write-restricted to test-expectation files:
38
39
  ```