@juicesharp/rpiv-pi 1.19.1 → 2.0.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 (95) hide show
  1. package/README.md +15 -5
  2. package/agents/integration-scanner.md +1 -1
  3. package/extensions/rpiv-core/agents.ts +24 -77
  4. package/extensions/rpiv-core/artifact-collector.ts +24 -7
  5. package/extensions/rpiv-core/banner.ts +23 -0
  6. package/extensions/rpiv-core/bash-timeout.ts +110 -0
  7. package/extensions/rpiv-core/built-in-workflows.ts +1503 -100
  8. package/extensions/rpiv-core/constants.ts +1 -0
  9. package/extensions/rpiv-core/index.ts +52 -19
  10. package/extensions/rpiv-core/lane-console.ts +566 -0
  11. package/extensions/rpiv-core/lane-dock-editor.ts +184 -0
  12. package/extensions/rpiv-core/lane-dock.ts +197 -0
  13. package/extensions/rpiv-core/lane-failure.ts +28 -0
  14. package/extensions/rpiv-core/lane-list.ts +414 -0
  15. package/extensions/rpiv-core/lane-progress.ts +330 -0
  16. package/extensions/rpiv-core/lane-relay-ui.ts +101 -0
  17. package/extensions/rpiv-core/lane-streaming.ts +68 -0
  18. package/extensions/rpiv-core/lane-switcher.ts +176 -0
  19. package/extensions/rpiv-core/lane-tool-defs.ts +73 -0
  20. package/extensions/rpiv-core/lane-transcript-disk.ts +91 -0
  21. package/extensions/rpiv-core/lane-transcript-view.ts +172 -0
  22. package/extensions/rpiv-core/lane-transcript.ts +277 -0
  23. package/extensions/rpiv-core/lane-usage.ts +96 -0
  24. package/extensions/rpiv-core/models-config.ts +7 -7
  25. package/extensions/rpiv-core/outcome-derivation.ts +37 -4
  26. package/extensions/rpiv-core/pipeline-pointer.ts +47 -0
  27. package/extensions/rpiv-core/question-lifecycle.ts +157 -0
  28. package/extensions/rpiv-core/register-built-in-workflows.ts +2 -2
  29. package/extensions/rpiv-core/rpiv-models/command.ts +3 -3
  30. package/extensions/rpiv-core/rpiv-models/items.ts +3 -8
  31. package/extensions/rpiv-core/run-lane-registry.ts +839 -0
  32. package/extensions/rpiv-core/sdk-workflow-host.ts +481 -0
  33. package/extensions/rpiv-core/{model-override.ts → session-capture.ts} +75 -142
  34. package/extensions/rpiv-core/session-hooks.ts +24 -80
  35. package/extensions/rpiv-core/skill-bracket.ts +9 -19
  36. package/extensions/rpiv-core/skill-contracts-source.ts +90 -13
  37. package/extensions/rpiv-core/workflow-execution-host.ts +184 -0
  38. package/extensions/rpiv-core/workflow-question-warp-bridge.ts +161 -0
  39. package/package.json +7 -5
  40. package/skills/_shared/git-changes.mjs +52 -1
  41. package/skills/_shared/slice-overlap.mjs +6 -8
  42. package/skills/_shared/stitch-elaborations.mjs +160 -0
  43. package/skills/amend/SKILL.md +48 -0
  44. package/skills/architecture-review/SKILL.md +2 -1
  45. package/skills/architecture-review/templates/architecture-review.md +1 -1
  46. package/skills/blueprint/SKILL.md +2 -1
  47. package/skills/code-review/SKILL.md +47 -17
  48. package/skills/code-review/_helpers/review-range.mjs +160 -3
  49. package/skills/commit/SKILL.md +12 -4
  50. package/skills/design/SKILL.md +2 -1
  51. package/skills/design-review/SKILL.md +77 -0
  52. package/skills/design-slice/SKILL.md +114 -0
  53. package/skills/discover/SKILL.md +1 -0
  54. package/skills/elaborate/SKILL.md +112 -0
  55. package/skills/explore/SKILL.md +1 -0
  56. package/skills/frontend-design/SKILL.md +1 -0
  57. package/skills/grade/SKILL.md +142 -0
  58. package/skills/implement/SKILL.md +16 -8
  59. package/skills/plan/SKILL.md +1 -0
  60. package/skills/pr-triage/SKILL.md +6 -3
  61. package/skills/research/SKILL.md +3 -1
  62. package/skills/revise/SKILL.md +1 -0
  63. package/skills/slice/SKILL.md +160 -0
  64. package/skills/synthesize/SKILL.md +165 -0
  65. package/skills/validate/SKILL.md +28 -5
  66. package/extensions/rpiv-core/agents.test.ts +0 -1037
  67. package/extensions/rpiv-core/built-in-workflows.test.ts +0 -1300
  68. package/extensions/rpiv-core/constants.test.ts +0 -14
  69. package/extensions/rpiv-core/frontmatter.test.ts +0 -51
  70. package/extensions/rpiv-core/git-context.matcher.test.ts +0 -47
  71. package/extensions/rpiv-core/git-context.test.ts +0 -109
  72. package/extensions/rpiv-core/guidance.test.ts +0 -140
  73. package/extensions/rpiv-core/model-override.test.ts +0 -559
  74. package/extensions/rpiv-core/models-config-validate.test.ts +0 -131
  75. package/extensions/rpiv-core/models-config.test.ts +0 -461
  76. package/extensions/rpiv-core/models-picker.test.ts +0 -136
  77. package/extensions/rpiv-core/outcome-derivation.test.ts +0 -417
  78. package/extensions/rpiv-core/package-checks.test.ts +0 -68
  79. package/extensions/rpiv-core/paths.test.ts +0 -58
  80. package/extensions/rpiv-core/pi-installer.test.ts +0 -100
  81. package/extensions/rpiv-core/prune-legacy-siblings.test.ts +0 -183
  82. package/extensions/rpiv-core/register-built-in-workflows.test.ts +0 -69
  83. package/extensions/rpiv-core/rpiv-models/units.test.ts +0 -136
  84. package/extensions/rpiv-core/rpiv-models-command.test.ts +0 -797
  85. package/extensions/rpiv-core/session-hooks.test.ts +0 -646
  86. package/extensions/rpiv-core/setup-command.test.ts +0 -213
  87. package/extensions/rpiv-core/siblings.test.ts +0 -96
  88. package/extensions/rpiv-core/skill-bracket.test.ts +0 -251
  89. package/extensions/rpiv-core/skill-contracts-source.test.ts +0 -469
  90. package/extensions/rpiv-core/update-agents-command.test.ts +0 -106
  91. package/extensions/rpiv-core/utils.test.ts +0 -214
  92. package/skills/_shared/git-changes.test.ts +0 -107
  93. package/skills/_shared/git-context.test.ts +0 -90
  94. package/skills/_shared/list-recent.test.ts +0 -77
  95. package/skills/_shared/now.test.ts +0 -48
package/README.md CHANGED
@@ -19,7 +19,7 @@ Skill-based development workflow for [Pi Agent](https://github.com/badlogic/pi-m
19
19
  ## What you get
20
20
 
21
21
  - **A pipeline of chained AI skills** - discover → research → design → plan → implement → validate, each producing a reviewable artifact under `.rpiv/artifacts/`.
22
- - **Named subagents for parallel analysis** - `codebase-analyzer`, `codebase-locator`, `codebase-pattern-finder`, `claim-verifier`, and 8 more, dispatched automatically by skills.
22
+ - **Named subagents for parallel analysis** - `codebase-analyzer`, `codebase-locator`, `codebase-pattern-finder`, `claim-verifier`, and 11 more, dispatched automatically by skills.
23
23
  - **Session lifecycle hooks** - agent profiles and guidance files install themselves on first launch.
24
24
 
25
25
  ## Prerequisites
@@ -84,7 +84,7 @@ pi install npm:@juicesharp/rpiv-pi
84
84
  4. *(Optional)* Configure web search:
85
85
 
86
86
  ```
87
- /web-search-config
87
+ /web-tools
88
88
  ```
89
89
 
90
90
  ### First Session
@@ -162,7 +162,11 @@ Invoke via `/skill:<name>` from inside a Pi Agent session.
162
162
  | Skill | Description |
163
163
  |---|---|
164
164
  | `code-review` | Comprehensive code reviews using specialist row-only agents (`diff-auditor`, `peer-comparator`, `claim-verifier`) at narrativisation-prone dispatch sites |
165
+ | `architecture-review` | Top-down, layer-by-layer architecture review with a uniform 10-dimension checklist per layer; emits a phased polish plan under `.rpiv/artifacts/architecture-reviews/` |
166
+ | `pr-triage` | Read-only triage of a GitHub PR: disposition (Review / Request changes / Hold / Decline) plus a security tier (0 SAFE / 1 REVIEW / 2 BLOCK); never mutates the working tree |
165
167
  | `commit` | Structured git commits grouped by logical change |
168
+ | `changelog` | Regenerate `[Unreleased]` CHANGELOG.md sections from Conventional-Commit history - Keep-a-Changelog style, monorepo-aware, idempotent |
169
+ | `frontend-design` | Inject tailored visual design guidance for web-frontend work; auto-adapts from a 2-question micro-interview to scan-only injection based on the project's style system |
166
170
  | `create-handoff` | Context-preserving handoff documents for session transitions |
167
171
  | `resume-handoff` | Resume work from a handoff document |
168
172
 
@@ -176,7 +180,9 @@ Invoke via `/skill:<name>` from inside a Pi Agent session.
176
180
  | `/btw` | Ask a side question without polluting the main conversation _(requires `@juicesharp/rpiv-btw`, opt-in)_ |
177
181
  | `/languages` | Pick the UI language for rpiv-* TUI strings (Deutsch / English / Español / Français / Português / Português (Brasil) / Русский / Українська) |
178
182
  | `/todos` | Show current todo list |
179
- | `/web-search-config` | Pick the active search provider and set its API key |
183
+ | `/web-tools` | Pick the active search provider and set its API key |
184
+ | `/wf` | Run a workflow: `/wf` previews every flow, `/wf <name>` shows one's graph, `/wf <name> "task"` runs it, `/wf @<run-id>` resumes _(ships with `@juicesharp/rpiv-workflow`, installed by `/rpiv-setup`)_ |
185
+ | `/rpiv-models` | Pick model + reasoning-effort overrides per default, agent, skill, workflow stage, or preset stage (see **Model configuration** below) |
180
186
 
181
187
  ### Agents
182
188
 
@@ -192,6 +198,10 @@ Agents are dispatched automatically by skills via the `Agent` tool - you don't i
192
198
  | `integration-scanner` | Maps inbound references, outbound dependencies, config registrations, and event subscriptions for a component |
193
199
  | `peer-comparator` | Compares a new file against a peer sibling and tags each invariant Mirrored / Missing / Diverged / Intentionally-absent |
194
200
  | `precedent-locator` | Finds similar past changes in git history - commits, blast radius, and follow-up fixes |
201
+ | `scope-tracer` | Sweeps anchor terms and reads key files to bound a research investigation - returns a Discovery Summary plus dense numbered questions |
202
+ | `slice-verifier` | Adversarially audits each freshly-generated slice of a phased plan or design before it is locked - catches forward-references, cross-slice symbol mismatches, and decision drift |
203
+ | `artifact-code-reviewer` | Reviews each slice code fence in a finalized artifact for code quality, codebase fit, and actionability - one severity-tagged row per finding |
204
+ | `artifact-coverage-reviewer` | Verifies every Verification Note and Precedent entry in a finalized artifact lands somewhere actionable - success criterion or emitted code |
195
205
  | `artifacts-analyzer` | Performs deep-dive analysis on a research topic in `.rpiv/artifacts/` |
196
206
  | `artifacts-locator` | Discovers relevant documents in the `.rpiv/artifacts/` directory |
197
207
  | `web-search-researcher` | Researches modern web-only information via deep search and fetch |
@@ -210,7 +220,7 @@ Pi Agent discovers extensions via `"extensions": ["./extensions"]` and skills vi
210
220
 
211
221
  ## Configuration
212
222
 
213
- - **Web search** - run `/web-search-config` to pick a provider (Brave, Tavily, Serper, Exa, Jina, or Firecrawl) and set its API key; the per-provider env var (e.g. `BRAVE_SEARCH_API_KEY`, `EXA_API_KEY`) also works and takes precedence
223
+ - **Web search** - run `/web-tools` to pick a provider (Brave, Tavily, Serper, Exa, You.com, Jina, Firecrawl, Perplexity, SearXNG, or Ollama) and set its API key; the per-provider env var (e.g. `BRAVE_SEARCH_API_KEY`, `EXA_API_KEY`) also works and takes precedence
214
224
  - **Advisor** - run `/advisor` to select a reviewer model and reasoning effort
215
225
  - **Models & reasoning effort** - run `/rpiv-models` to pick a model and reasoning level for the global default, a specific bundled agent, a workflow stage, a skill, or a per-preset stage; the picker writes `~/.config/rpiv-pi/models.json`. See **Model configuration** below for the cascade ladder and worked examples.
216
226
  - **Side questions** _(opt-in: `pi install npm:@juicesharp/rpiv-btw`)_ - type `/btw <question>` anytime (even mid-stream) to ask the primary model a one-off question; answer appears in a borderless bottom overlay and never enters the main conversation
@@ -287,7 +297,7 @@ With this file, `/wf ship plan` and `/wf ship design` use GPT-5.5; `/wf polish p
287
297
  | Warning about missing siblings on session start | Sibling plugins not installed | Run `/rpiv-setup` |
288
298
  | `/rpiv-setup` fails on a package | Network or registry issue | Check connection, retry with `pi install npm:<pkg>`, re-run `/rpiv-setup` |
289
299
  | `/rpiv-setup` says "requires interactive mode" | Running in headless mode | Install manually: `pi install npm:<pkg>` for each sibling |
290
- | `web_search` or `web_fetch` errors | Active provider's API key not configured | Run `/web-search-config` or set the matching env var (e.g. `BRAVE_SEARCH_API_KEY`, `EXA_API_KEY`) |
300
+ | `web_search` or `web_fetch` errors | Active provider's API key not configured | Run `/web-tools` or set the matching env var (e.g. `BRAVE_SEARCH_API_KEY`, `EXA_API_KEY`) |
291
301
  | `advisor` tool not available after upgrade | Advisor model selection lost | Run `/advisor` to re-select a model |
292
302
  | Skills hang or serialize agent calls | Agent concurrency too low | Open `/agents`, raise `Settings → Max concurrency` |
293
303
 
@@ -50,7 +50,7 @@ You are a specialist at finding CONNECTIONS to and from a component or area. You
50
50
 
51
51
  ## Output Format
52
52
 
53
- CRITICAL: Use EXACTLY this format. Never use markdown tables. Use relative paths (strip the workspace root prefix).
53
+ CRITICAL: Use EXACTLY this format. Never use markdown tables. Use repo-root-relative paths — strip only the absolute prefix up to the repository root, never a package or subdirectory prefix (`packages/billing/src/invoice.ts:42`, not `src/invoice.ts:42`).
54
54
 
55
55
  ```
56
56
  ## Connections: {Component}
@@ -141,7 +141,7 @@ export function summarizeCleanupSkips(skipped: CleanupSkip[]): string {
141
141
  }
142
142
 
143
143
  // ---------------------------------------------------------------------------
144
- // Path-traversal allowlist (I2 — hardens the manifest reader boundary)
144
+ // Path-traversal allowlist (hardens the manifest reader boundary)
145
145
  // ---------------------------------------------------------------------------
146
146
 
147
147
  /**
@@ -183,50 +183,17 @@ function safeJoin(targetDir: string, name: string): string | null {
183
183
  // ---------------------------------------------------------------------------
184
184
 
185
185
  const MANIFEST_FILE = ".rpiv-managed.json";
186
- /**
187
- * V2-active sentinel: empty sidecar file written the first time syncBundledAgents
188
- * commits a v2-shaped manifest. Decouples "v2 active" from manifest contents so
189
- * JSON corruption, partial writes, or empty-hash collapse cannot re-arm the
190
- * legacy-migration "package wins" branch.
191
- */
192
- const V2_MARKER_FILE = ".rpiv-managed.v2";
193
186
 
194
- /** Filename → sha256 hex of the content we last installed. Empty string = legacy / unknown. */
187
+ /** Filename → sha256 hex of the content we last installed. Empty string = unknown. */
195
188
  type Manifest = Record<string, string>;
196
189
 
197
- /**
198
- * `hasV2Data` derives from this marker, NOT from manifest content. The marker
199
- * is created exactly once per project — on the first successful writeManifest
200
- * after migration — and survives JSON corruption, partial writes, and
201
- * empty-hash collapse. This makes the legacy-migration window deterministically
202
- * one-shot per project.
203
- */
204
- function hasV2Marker(targetDir: string): boolean {
205
- return existsSync(join(targetDir, V2_MARKER_FILE));
206
- }
207
-
208
- /**
209
- * Commit the V2 sentinel marker. Fail-soft: a write failure leaves the marker
210
- * absent, so the next run will retry. Worst case the legacy-migration branch
211
- * re-arms exactly once more.
212
- */
213
- function writeV2Marker(targetDir: string): void {
214
- try {
215
- writeFileSync(join(targetDir, V2_MARKER_FILE), "", "utf-8");
216
- } catch {
217
- // non-fatal — see comment above.
218
- }
219
- }
220
-
221
190
  function sha256(buf: Buffer | string): string {
222
191
  return createHash("sha256").update(buf).digest("hex");
223
192
  }
224
193
 
225
194
  /**
226
- * Read the managed-file manifest from the target directory.
227
- * Supports both v1 (string[]) and v2 (Record<string,string>) formats. v1 entries
228
- * migrate as `{name: ""}` — the empty hash marks them as unknown, forcing the
229
- * manual gate until a `/rpiv-update-agents` run baselines the real hash.
195
+ * Read the managed-file manifest (`Record<filename, sha256>`) from the target
196
+ * directory. Any other shape (missing, corrupt JSON, non-object) reads as `{}`.
230
197
  *
231
198
  * Hardened against path-traversal: keys failing `isManagedAgentName` are dropped
232
199
  * silently. A subsequent `writeManifest` rewrites the on-disk manifest without
@@ -240,11 +207,6 @@ function readManifest(targetDir: string): Manifest {
240
207
  try {
241
208
  const raw = readFileSync(manifestPath, "utf-8");
242
209
  const parsed = JSON.parse(raw);
243
- if (Array.isArray(parsed)) {
244
- const out: Manifest = {};
245
- for (const e of parsed) if (typeof e === "string" && isManagedAgentName(e)) out[e] = "";
246
- return out;
247
- }
248
210
  if (isPlainObject(parsed)) {
249
211
  const out: Manifest = {};
250
212
  for (const [k, v] of Object.entries(parsed)) {
@@ -259,7 +221,7 @@ function readManifest(targetDir: string): Manifest {
259
221
  }
260
222
 
261
223
  /**
262
- * Write the managed-file manifest to the target directory (v2 format).
224
+ * Write the managed-file manifest to the target directory.
263
225
  * Pushes a `{ op: "manifest-write" }` SyncError on failure so consumers
264
226
  * (notifyAgentSyncDrift, /rpiv-update-agents) can surface it instead of
265
227
  * silently swallowing permission / disk-full errors.
@@ -299,16 +261,13 @@ function writeManifest(targetDir: string, manifest: Manifest, result: SyncResult
299
261
  // ---------------------------------------------------------------------------
300
262
 
301
263
  /**
302
- * Unified safety gate for destructive operations (update + remove).
303
- * Returns true when the operation is safe to auto-apply without user consent:
304
- * - Smart gate: recorded hash matches destination (user hasn't edited)
305
- * - Legacy gate: no v2 marker and no recorded hash (pre-migration)
264
+ * Unified safety gate for destructive operations (update + remove): safe to
265
+ * auto-apply only when the recorded hash matches the destination (we installed
266
+ * those bytes and the user hasn't edited them). No recorded hash → gated.
306
267
  */
307
- export function isSafeDestructiveOp(opts: { hasV2Data: boolean; knownHash: string; destHash: string }): boolean {
308
- const { hasV2Data, knownHash, destHash } = opts;
309
- const safeSmart = knownHash !== "" && destHash === knownHash;
310
- const safeLegacy = !hasV2Data && knownHash === "";
311
- return safeSmart || safeLegacy;
268
+ export function isSafeDestructiveOp(opts: { knownHash: string; destHash: string }): boolean {
269
+ const { knownHash, destHash } = opts;
270
+ return knownHash !== "" && destHash === knownHash;
312
271
  }
313
272
 
314
273
  // ---------------------------------------------------------------------------
@@ -390,7 +349,7 @@ export function injectModelFrontmatter(content: string, agentFile: string, confi
390
349
  if (!bounds) return content;
391
350
 
392
351
  const keysToSet: { key: string; value: string }[] = [];
393
- // D9 (post-slash-canonical migration): models.json values are byte-equal to
352
+ // (post-slash-canonical migration): models.json values are byte-equal to
394
353
  // the agent frontmatter form (both `provider/modelId`). No translation step
395
354
  // — re-injecting produces identical bytes by construction; the idempotency
396
355
  // invariant at injectModelFrontmatter's JSDoc strengthens from "deterministic
@@ -410,7 +369,6 @@ function processSourceEntries(
410
369
  sourceEntries: string[],
411
370
  targetDir: string,
412
371
  manifest: Manifest,
413
- hasV2Data: boolean,
414
372
  apply: boolean,
415
373
  result: SyncResult,
416
374
  ): Manifest {
@@ -439,7 +397,7 @@ function processSourceEntries(
439
397
  continue;
440
398
  }
441
399
  // Inject configured model/thinking frontmatter BEFORE hashing so the
442
- // manifest hash matches what actually lands on disk (D4: hash-after-transform).
400
+ // manifest hash matches what actually lands on disk (hash-after-transform).
443
401
  // injectModelFrontmatter strips .md from entry for config lookup and is a
444
402
  // no-op when no override is configured.
445
403
  const injected = injectModelFrontmatter(srcContent.toString("utf-8"), entry, config);
@@ -473,7 +431,7 @@ function processSourceEntries(
473
431
  continue;
474
432
  }
475
433
 
476
- if (apply || isSafeDestructiveOp({ hasV2Data, knownHash, destHash })) {
434
+ if (apply || isSafeDestructiveOp({ knownHash, destHash })) {
477
435
  try {
478
436
  writeFileSync(dest, injected, "utf-8");
479
437
  result.updated.push(entry);
@@ -499,7 +457,6 @@ function classifyStaleEntries(
499
457
  manifest: Manifest,
500
458
  sourceNames: Set<string>,
501
459
  targetDir: string,
502
- hasV2Data: boolean,
503
460
  apply: boolean,
504
461
  newManifest: Manifest,
505
462
  result: SyncResult,
@@ -516,7 +473,7 @@ function classifyStaleEntries(
516
473
  continue;
517
474
  }
518
475
  if (!existsSync(destPath)) {
519
- // Vanished tracked file: tidy from manifest AND surface as removed (Q5).
476
+ // Vanished tracked file: tidy from manifest AND surface as removed.
520
477
  result.removed.push(name);
521
478
  continue;
522
479
  }
@@ -531,7 +488,7 @@ function classifyStaleEntries(
531
488
  }
532
489
  const destHash = sha256(destContent);
533
490
 
534
- if (apply || isSafeDestructiveOp({ hasV2Data, knownHash, destHash })) {
491
+ if (apply || isSafeDestructiveOp({ knownHash, destHash })) {
535
492
  toUnlink.push({ name, destPath });
536
493
  } else {
537
494
  result.pendingRemove.push(name);
@@ -580,14 +537,9 @@ function commitStaleUnlinks(
580
537
  * - Existing files, dest === src → unchanged, hash recorded.
581
538
  * - Existing files, dest ≠ src:
582
539
  * - dest === recorded hash → auto-update (smart gate).
583
- * - V2 marker absent (legacy v1, missing, or never-installed) → auto-update;
584
- * package wins. Triggers exactly while transitioning to v2; the marker
585
- * file (.rpiv-managed.v2) is written once committed and never re-fires
586
- * for this installation, surviving JSON corruption / partial writes / empty-
587
- * hash collapse.
588
- * - otherwise (V2 marker present, dest differs from recorded hash) →
589
- * pendingUpdate (gated; respects user edits).
590
- * - Stale managed files: same three-way decision applied to removal.
540
+ * - otherwise (no recorded hash, or dest differs from it) → pendingUpdate
541
+ * (gated; respects user edits).
542
+ * - Stale managed files: same decision applied to removal.
591
543
  *
592
544
  * apply=true (/rpiv-update-agents): force adds/updates/removes regardless of
593
545
  * recorded hash (manual override; user-edited files are overwritten).
@@ -622,19 +574,15 @@ export function syncBundledAgents(apply: boolean): SyncResult {
622
574
 
623
575
  const sourceNames = new Set(sourceEntries);
624
576
  const manifest = readManifest(targetDir);
625
- const hasV2Data = hasV2Marker(targetDir);
626
577
 
627
578
  // 2. Process each source file
628
- const newManifest = processSourceEntries(sourceEntries, targetDir, manifest, hasV2Data, apply, result);
579
+ const newManifest = processSourceEntries(sourceEntries, targetDir, manifest, apply, result);
629
580
 
630
581
  // 3. Stale-removal: Pass A (classify) → Pass B (write manifest) → Pass C (commit unlinks).
631
- const toUnlink = classifyStaleEntries(manifest, sourceNames, targetDir, hasV2Data, apply, newManifest, result);
582
+ const toUnlink = classifyStaleEntries(manifest, sourceNames, targetDir, apply, newManifest, result);
632
583
 
633
584
  // Pass B — persist manifest before destructive ops.
634
585
  writeManifest(targetDir, newManifest, result);
635
- if (!hasV2Data && !result.errors.some((e) => e.op === SYNC_OP.MANIFEST_WRITE)) {
636
- writeV2Marker(targetDir);
637
- }
638
586
 
639
587
  // Pass C — commit unlinks after the manifest is durable.
640
588
  commitStaleUnlinks(toUnlink, manifest, newManifest, targetDir, result);
@@ -702,8 +650,8 @@ export function cleanupPerCwdAgents(cwd: string): CleanupResult {
702
650
  return result;
703
651
  }
704
652
 
705
- // Compare against the injected form — the dest holds injected content
706
- // (D4), so comparing raw source would falsely flag every configured agent
653
+ // Compare against the injected form — the dest holds injected content,
654
+ // so comparing raw source would falsely flag every configured agent
707
655
  // as diverged. injectModelFrontmatter strips .md from name for lookup.
708
656
  const cleanupInjected = injectModelFrontmatter(srcContent.toString("utf-8"), name, cleanupConfig);
709
657
  if (sha256(destContent) !== sha256(cleanupInjected)) {
@@ -717,9 +665,8 @@ export function cleanupPerCwdAgents(cwd: string): CleanupResult {
717
665
  try {
718
666
  const allFiles = readdirSync(perCwdDir);
719
667
  const managedNames = new Set(Object.keys(manifest));
720
- const managedMetadata = new Set([MANIFEST_FILE, V2_MARKER_FILE]);
721
668
  for (const f of allFiles) {
722
- if (!managedNames.has(f) && !managedMetadata.has(f)) {
669
+ if (!managedNames.has(f) && f !== MANIFEST_FILE) {
723
670
  // Non-managed file present (user custom agent or other content)
724
671
  result.skipped.push({ dir: perCwdDir, reason: CLEANUP_SKIP_REASON.CUSTOM_FILES });
725
672
  return result;
@@ -31,7 +31,7 @@ import {
31
31
  type ArtifactCollector,
32
32
  type ArtifactParser,
33
33
  defineParser,
34
- type OutputSpec,
34
+ type Outcome,
35
35
  type ParseCtx,
36
36
  transcriptPathCollector,
37
37
  // Runner-free entry — keeps the ~530ms engine off the startup path.
@@ -59,8 +59,18 @@ export function rpivBucketCollector(bucket: string): ArtifactCollector {
59
59
 
60
60
  /**
61
61
  * Reads YAML frontmatter from the primary fs artifact. Files without
62
- * frontmatter produce `data: {}`. Fatals when the announced path
63
- * doesn't exist on disk (the agent claimed to write but didn't).
62
+ * frontmatter — or with frontmatter the YAML parser chokes on — produce
63
+ * `data: {}`. Fatals only when the announced path doesn't exist on disk
64
+ * (the agent claimed to write but didn't).
65
+ *
66
+ * Fail-soft on malformed YAML is deliberate: `parseFrontmatter` throws on
67
+ * an agent-authored scalar that smuggles in a bare `: ` (e.g.
68
+ * `target: foo (lane UI: L0–L2)` reads as a nested mapping). Letting that
69
+ * throw escape converts a single stray colon — in the LAST write of a
70
+ * multi-hour stage — into a fatal that halts the whole workflow. Degrading
71
+ * to `{}` keeps the artifact (the real work) and defers any missing-field
72
+ * judgement to the stage's `outputSchema` validation, exactly as a file
73
+ * with no frontmatter at all already does.
64
74
  */
65
75
  export const frontmatterParser: ArtifactParser<undefined, "artifact-md", Record<string, unknown>> = defineParser({
66
76
  parse(ctx: ParseCtx<undefined>) {
@@ -79,7 +89,14 @@ export const frontmatterParser: ArtifactParser<undefined, "artifact-md", Record<
79
89
  };
80
90
  }
81
91
  const content = readFileSync(abs, "utf-8");
82
- const { frontmatter } = parseFrontmatter(content);
92
+ let frontmatter: unknown;
93
+ try {
94
+ ({ frontmatter } = parseFrontmatter(content));
95
+ } catch {
96
+ // Malformed YAML (unquoted `: ` in a scalar, bad indentation, …) →
97
+ // degrade to no-frontmatter rather than killing the chain.
98
+ frontmatter = undefined;
99
+ }
83
100
  return {
84
101
  kind: "ok",
85
102
  payload: {
@@ -91,11 +108,11 @@ export const frontmatterParser: ArtifactParser<undefined, "artifact-md", Record<
91
108
  });
92
109
 
93
110
  // ---------------------------------------------------------------------------
94
- // OutputSpec — pre-bundled wiring rpiv-pi workflows plug in
111
+ // Outcome — pre-bundled wiring rpiv-pi workflows plug in
95
112
  // ---------------------------------------------------------------------------
96
113
 
97
114
  /** Default rpiv-pi produces outcome — bucket-agnostic text scan + frontmatter parse. */
98
- export const rpivArtifactMdOutcome: OutputSpec<unknown, "artifact-md", Record<string, unknown>> = {
115
+ export const rpivArtifactMdOutcome: Outcome<unknown, "artifact-md", Record<string, unknown>> = {
99
116
  collector: rpivArtifactCollector,
100
117
  parser: frontmatterParser,
101
118
  };
@@ -107,6 +124,6 @@ export const rpivArtifactMdOutcome: OutputSpec<unknown, "artifact-md", Record<st
107
124
  * restating the bucket on each producing stage. Multiple stages wiring
108
125
  * the same bucket converge to one named slot (latest entry wins on read).
109
126
  */
110
- export function rpivBucketOutcome(bucket: string): OutputSpec<unknown, "artifact-md", Record<string, unknown>> {
127
+ export function rpivBucketOutcome(bucket: string): Outcome<unknown, "artifact-md", Record<string, unknown>> {
111
128
  return { name: bucket, collector: rpivBucketCollector(bucket), parser: frontmatterParser };
112
129
  }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Boxed notification banner — the rounded-corner frame used for
3
+ * action-required session notices (missing siblings, agent drift).
4
+ * Pure string rendering; callers pass the result to `ui.notify`.
5
+ */
6
+
7
+ /**
8
+ * Render `title` and `body` lines inside a rounded box. Width hugs the
9
+ * longest line. Body lines render verbatim — pass `""` for a spacer line.
10
+ *
11
+ * ╭─ title ────────────╮
12
+ * │ body line │
13
+ * │ │
14
+ * │ call to action │
15
+ * ╰────────────────────╯
16
+ */
17
+ export function renderBanner(title: string, body: string[]): string {
18
+ const total = Math.max(title.length + 6, ...body.map((l) => l.length + 4));
19
+ const top = `╭─ ${title} ${"─".repeat(total - title.length - 5)}╮`;
20
+ const middle = body.map((l) => `│ ${l.padEnd(total - 4)}│`);
21
+ const bottom = `╰${"─".repeat(total - 2)}╯`;
22
+ return [top, ...middle, bottom].join("\n");
23
+ }
@@ -0,0 +1,110 @@
1
+ /**
2
+ * bash-timeout — a per-command wall-clock watchdog over a child AgentSession's bash
3
+ * tool calls, the host's defense against a runaway command stranding a fan-out gate.
4
+ *
5
+ * A workflow stage runs in a detached child session (sdk-workflow-host); the SDK's
6
+ * bash tool honours an AbortSignal but enforces NO timeout of its own, so a model that
7
+ * issues e.g. `find / ...` blocks the unit for as long as the scan runs. A fan-out
8
+ * gate finalizes only once EVERY unit settles, so one wedged bash freezes the whole
9
+ * run with nothing to break it.
10
+ *
11
+ * `armBashWatchdog` subscribes to the child's `tool_execution_start`/`_end` stream and,
12
+ * per bash call, arms a timer; the matching result disarms it. On expiry it records the
13
+ * reason and `session.abort()`s — which signals the in-flight subprocess AND resolves
14
+ * the turn with `stopReason:"aborted"`. The host exposes the recorded reason to the
15
+ * runner via `WorkflowSessionContext.toolTimeout`, where `postStage` routes it to the
16
+ * soft-halt gate (collect-all unit survives; non-fan-out stage fails terminally) rather
17
+ * than re-dispatching the same command on resume.
18
+ *
19
+ * Per-command, not per-unit: the clock is the time a SINGLE bash call has been running,
20
+ * so a stage may issue many quick commands without ever tripping it; only one that
21
+ * overruns on its own does.
22
+ */
23
+
24
+ import type { AgentSession } from "@earendil-works/pi-coding-agent";
25
+
26
+ /** The event the session's subscribe listener receives — derived from the SDK signature
27
+ * so this module imports no SDK event-type value (mirrors lane-streaming.ts). */
28
+ type AgentSessionEvent = Parameters<Parameters<AgentSession["subscribe"]>[0]>[0];
29
+
30
+ /** Only the slice of AgentSession the watchdog touches — keeps the unit test trivial to fake. */
31
+ type WatchableSession = Pick<AgentSession, "subscribe" | "abort">;
32
+
33
+ const DEFAULT_BASH_TOOL_TIMEOUT_MS = 180_000; // 3 min — tight enough to cut a wedged scan well before it strands a gate.
34
+ const MIN_BASH_TOOL_TIMEOUT_MS = 5_000; // a sub-5s ceiling would scythe ordinary commands.
35
+ const MAX_BASH_TOOL_TIMEOUT_MS = 30 * 60_000; // 30 min — the hard upper bound (mirrors the workflow validation-retry cap).
36
+
37
+ /**
38
+ * The resolved per-command ceiling: the 3-minute default, overridable via
39
+ * `RPIV_BASH_TIMEOUT_MS` and clamped to [5s, 30min]. A non-numeric / non-positive
40
+ * override falls back to the default. Resolved once at module load (env is fixed for a
41
+ * process); tests pass an explicit `timeoutMs` to `armBashWatchdog` instead of mutating env.
42
+ */
43
+ export const BASH_TOOL_TIMEOUT_MS = resolveBashTimeoutMs(process.env.RPIV_BASH_TIMEOUT_MS);
44
+
45
+ export function resolveBashTimeoutMs(raw: string | undefined): number {
46
+ const parsed = Number(raw);
47
+ if (!Number.isFinite(parsed) || parsed <= 0) return DEFAULT_BASH_TOOL_TIMEOUT_MS;
48
+ return Math.min(Math.max(parsed, MIN_BASH_TOOL_TIMEOUT_MS), MAX_BASH_TOOL_TIMEOUT_MS);
49
+ }
50
+
51
+ /** Operator-grade row text — names the ceiling and echoes the offending command (truncated). */
52
+ export function bashTimeoutReason(command: string, timeoutMs: number): string {
53
+ const secs = Math.round(timeoutMs / 1000);
54
+ const snippet = command.length > 120 ? `${command.slice(0, 117)}...` : command;
55
+ return `bash command exceeded the ${secs}s per-command timeout and was aborted${snippet ? `: \`${snippet}\`` : ""}`;
56
+ }
57
+
58
+ export interface BashWatchdog {
59
+ /** The recorded timeout reason once the watchdog has fired, else `undefined`. Wired to
60
+ * `WorkflowSessionContext.toolTimeout` so the runner can divert the abort to soft-halt. */
61
+ timedOut(): { reason: string } | undefined;
62
+ /** Unsubscribe + clear any pending timers. The host calls this in its per-stage `finally`. */
63
+ dispose(): void;
64
+ }
65
+
66
+ /**
67
+ * Arm the watchdog on `session`. Returns a handle whose `timedOut()` reports the reason
68
+ * (once) and whose `dispose()` tears the subscription + timers down. The FIRST overrun
69
+ * wins — concurrent bash calls (parallel tool execution) each get their own timer, but
70
+ * only one abort + reason is recorded.
71
+ */
72
+ export function armBashWatchdog(session: WatchableSession, timeoutMs: number = BASH_TOOL_TIMEOUT_MS): BashWatchdog {
73
+ let fired: { reason: string } | undefined;
74
+ const timers = new Map<string, ReturnType<typeof setTimeout>>();
75
+
76
+ const clear = (id: string): void => {
77
+ const timer = timers.get(id);
78
+ if (timer) {
79
+ clearTimeout(timer);
80
+ timers.delete(id);
81
+ }
82
+ };
83
+
84
+ const unsubscribe = session.subscribe((event: AgentSessionEvent) => {
85
+ if (event.type === "tool_execution_start" && event.toolName === "bash") {
86
+ const id = event.toolCallId;
87
+ const command = typeof event.args?.command === "string" ? event.args.command : "";
88
+ const timer = setTimeout(() => {
89
+ timers.delete(id);
90
+ if (fired) return; // first overrun wins — one abort, one reason.
91
+ fired = { reason: bashTimeoutReason(command, timeoutMs) };
92
+ void session.abort();
93
+ }, timeoutMs);
94
+ // Don't let a pending watchdog keep the event loop alive on its own.
95
+ timer.unref?.();
96
+ timers.set(id, timer);
97
+ } else if (event.type === "tool_execution_end") {
98
+ clear(event.toolCallId);
99
+ }
100
+ });
101
+
102
+ return {
103
+ timedOut: () => fired,
104
+ dispose: () => {
105
+ unsubscribe();
106
+ for (const timer of timers.values()) clearTimeout(timer);
107
+ timers.clear();
108
+ },
109
+ };
110
+ }