@juicesharp/rpiv-pi 2.7.1 → 2.9.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 (34) hide show
  1. package/README.md +2 -2
  2. package/docs/architecture.md +3 -3
  3. package/docs/skills.md +8 -6
  4. package/docs/workflows.md +3 -3
  5. package/extensions/rpiv-core/agent-enablement.ts +164 -0
  6. package/extensions/rpiv-core/agents.ts +98 -12
  7. package/extensions/rpiv-core/built-in-workflows.ts +373 -142
  8. package/extensions/rpiv-core/built-ins/gates.ts +38 -15
  9. package/extensions/rpiv-core/built-ins/goal-baseline.ts +43 -1
  10. package/extensions/rpiv-core/built-ins/grade-panel.ts +98 -29
  11. package/extensions/rpiv-core/built-ins/index.ts +1 -0
  12. package/extensions/rpiv-core/built-ins/priors.ts +208 -38
  13. package/extensions/rpiv-core/built-ins/reconcile-directives.d.mts +29 -0
  14. package/extensions/rpiv-core/built-ins/reconcile-directives.mjs +338 -0
  15. package/extensions/rpiv-core/built-ins/reconcile.ts +88 -130
  16. package/extensions/rpiv-core/built-ins/slices.ts +5 -1
  17. package/extensions/rpiv-core/frontmatter.ts +22 -0
  18. package/extensions/rpiv-core/lane-relay-ui.ts +25 -1
  19. package/extensions/rpiv-core/models-config.ts +86 -6
  20. package/extensions/rpiv-core/outcome-derivation.ts +1 -0
  21. package/extensions/rpiv-core/package-checks.ts +13 -0
  22. package/extensions/rpiv-core/pipeline-pointer.ts +1 -1
  23. package/extensions/rpiv-core/workflow-execution-host.ts +3 -2
  24. package/package.json +3 -3
  25. package/skills/_shared/reconcile-lint.mjs +125 -0
  26. package/skills/acceptance/SKILL.md +123 -0
  27. package/skills/elaborate/SKILL.md +3 -3
  28. package/skills/grade/SKILL.md +8 -7
  29. package/skills/implement/SKILL.md +17 -2
  30. package/skills/quick-plan/SKILL.md +19 -2
  31. package/skills/research/SKILL.md +28 -1
  32. package/skills/slice/SKILL.md +4 -4
  33. package/skills/synthesize/SKILL.md +1 -1
  34. package/skills/validate/SKILL.md +11 -5
package/README.md CHANGED
@@ -11,7 +11,7 @@
11
11
 
12
12
  Turn "build this feature" into a run of named stages — discover → research → design →
13
13
  plan → implement → validate → code-review → commit — each one writing a reviewable
14
- Markdown artifact under `.rpiv/artifacts/` that the next stage consumes. rpiv-pi adds 29
14
+ Markdown artifact under `.rpiv/artifacts/` that the next stage consumes. rpiv-pi adds 30
15
15
  skills, 15 specialist subagents, and four ready-made `/wf` pipelines to
16
16
  [Pi Agent](https://github.com/badlogic/pi-mono), and runs every stage in a detached child
17
17
  session you watch from a lane dock below your editor. It is for developers who want
@@ -100,7 +100,7 @@ no overrides.
100
100
 
101
101
  ## Reference
102
102
 
103
- - [docs/skills.md](./docs/skills.md) — all 29 skills: what each consumes, what it writes,
103
+ - [docs/skills.md](./docs/skills.md) — all 30 skills: what each consumes, what it writes,
104
104
  and which ones the model may pick on its own.
105
105
  - [docs/workflows.md](./docs/workflows.md) — the four `/wf` pipelines stage by stage,
106
106
  plus hand-driven recipes for when you don't want a whole pipeline.
@@ -9,7 +9,7 @@ extending the package.
9
9
  ```
10
10
  rpiv-pi/
11
11
  ├── extensions/rpiv-core/ the one extension: hooks, commands, lanes, guidance, model config
12
- ├── skills/ 29 contract-carrying skills, one directory each
12
+ ├── skills/ 30 contract-carrying skills, one directory each
13
13
  ├── agents/ 15 subagent profiles, copied to ~/.pi/agent/agents/ at runtime
14
14
  └── scripts/ deterministic helpers skills shell out to (Node built-ins only)
15
15
  ```
@@ -39,7 +39,7 @@ the siblings contribute capability.
39
39
  | `/rpiv-models` | always | Interactive only |
40
40
  | `/lanes` | always | No-ops with a notice when nothing is running |
41
41
  | `ctrl+q` | conditionally | Skipped entirely when `RPIV_LANES_HOTKEY` disables it |
42
- | `/skill:<name>` × 29 | Pi, from the manifest | |
42
+ | `/skill:<name>` × 30 | Pi, from the manifest | |
43
43
  | `--rpiv-debug` flag | always | Reveals the hidden injected messages below |
44
44
 
45
45
  Session events subscribed: `session_start`, `session_compact`, `session_shutdown`,
@@ -88,7 +88,7 @@ changes. When `git config user.name` is empty, `$USER` is used, then `unknown`.
88
88
 
89
89
  ## Pipeline pointer
90
90
 
91
- 20 of the 29 skills set `disable-model-invocation: true`, which hides them from the
91
+ 21 of the 30 skills set `disable-model-invocation: true`, which hides them from the
92
92
  model's skill list so it cannot wander into a design pass mid-conversation. To keep them
93
93
  discoverable, a roughly 120-token stage index is injected at `session_start` and folded
94
94
  into the first real user turn after compaction — hidden by default, visible under
package/docs/skills.md CHANGED
@@ -8,7 +8,7 @@ whether the model may reach for it on its own.
8
8
  - **Invoke** — `/skill:<name>` from inside a Pi session, or as a stage of a `/wf`
9
9
  workflow (see [workflows.md](./workflows.md)).
10
10
  - **Auto** — ✓ means the model may select the skill by itself from your prompt.
11
- 20 of the 29 skills set `disable-model-invocation: true` and are marked —;
11
+ 21 of the 30 skills set `disable-model-invocation: true` and are marked —;
12
12
  those run *only* on an explicit `/skill:<name>` or a workflow dispatch. A short
13
13
  stage index is injected at session start so the model still knows they exist and
14
14
  can suggest one.
@@ -42,7 +42,8 @@ whether the model may reach for it on its own.
42
42
  | --- | :---: | --- | --- | --- |
43
43
  | `plan` | — | a `design` artifact | `plans/` | Converts a design into parallelized atomic phases with explicit success criteria. Prefer it when a straightforward phased breakdown is enough. |
44
44
  | `blueprint` | — | `research` or `solutions` (optional) | `plans/` | Fuses design + plan in one pass: vertical-slice decomposition with developer micro-checkpoints between phases, emitting an implement-ready plan. Lighter subagent fan-out than `design` — it trusts the research artifact's integration and precedent sections. |
45
- | `quick-plan` | — | a `research` artifact (+ the verbatim `goal` brief under `ship`) | `plans/` | One lightweight plan for a small, well-understood task: at most a single targeted `codebase-pattern-finder` dispatch, then a single `status: ready` phased plan — no slice decomposition, no risk flags, no questions; goal asks it doesn't cover are explicitly deferred under `## Out of Scope`. The `ship` pipeline's plan stage. |
45
+ | `acceptance` | — | the verbatim `goal` brief (+ a `research` artifact for evidence grounding) | `acceptance/` | Derives the executable acceptance inventory from the goal — ID'd observable outcomes, each with a runnable evidence command where one can be derived — frozen BEFORE planning so the standard of completion cannot inherit the plan's scope. The completeness grade anchors on it; validate executes it. Dispatched by `ship` and `build` between research and planning. |
46
+ | `quick-plan` | — | a `research` artifact (+ the verbatim `goal` brief and `acceptance` inventory under `ship`) | `plans/` | One lightweight plan for a small, well-understood task: at most a single targeted `codebase-pattern-finder` dispatch, then a single `status: ready` phased plan — no slice decomposition, no risk flags, no questions; goal asks it doesn't cover are explicitly deferred under `## Out of Scope`. The `ship` pipeline's plan stage. |
46
47
  | `elaborate` | — | a `plan` artifact | `elaborations/` | Writes implement-ready code into ONE phase of a synthesized plan. A fanout unit; the results are stitched back into the plan. |
47
48
  | `revise` | — | a `plan` (+ optional `reviews`) | `plans/` | Surgically updates an existing plan after review feedback, a mid-implement blocker, or a scope change — preserving structure instead of rewriting. |
48
49
  | `amend` | — | one artifact + its `grade` verdicts | same artifact | Fixes only the failing dimensions a grade panel flagged and re-emits the artifact in place. Single-pass, no subagents; a gate's revise stage. |
@@ -79,10 +80,11 @@ Everything lands under `.rpiv/artifacts/` in the project you are working in:
79
80
  ```
80
81
  .rpiv/artifacts/
81
82
  ├── goal/ discover/ research/
82
- ├── solutions/ slices/ designs/
83
- ├── elaborations/ plans/ subplans/
84
- ├── verdicts/ reviews/ validation/
85
- └── architecture-reviews/ triage/ handoffs/
83
+ ├── acceptance/ solutions/ slices/
84
+ ├── designs/ elaborations/ plans/
85
+ ├── subplans/ verdicts/ reviews/
86
+ ├── validation/ architecture-reviews/
87
+ └── triage/ handoffs/
86
88
  ```
87
89
 
88
90
  The directory is created lazily by the first skill that writes into it.
package/docs/workflows.md CHANGED
@@ -37,7 +37,7 @@ each phase's plan must build on the ones before it.
37
37
 
38
38
  ### `build`
39
39
 
40
- `goal → research → slice → slice gate (+ fix loop) → design-slice (parallel fanout) → design-review → synthesize → plan gate → elaborate (parallel fanout) → re-grade → implement → validate → commit`
40
+ `goal → research → acceptance → slice → slice gate (+ fix loop) → design-slice (parallel fanout) → design-review → synthesize → plan gate → elaborate (parallel fanout) → re-grade → implement → validate → commit`
41
41
 
42
42
  Your brief, sliced. It captures your brief verbatim as a goal artifact — the north star the
43
43
  quality gates and `validate` anchor against — then decomposes the work into vertical
@@ -47,9 +47,9 @@ code is elaborated into it. Three automated gates plus one human checkpoint.
47
47
 
48
48
  ### `ship`
49
49
 
50
- `goal → research → plan → plan-cite-check → grade → implement → implement-scope-check → reconcile → validate → commit`
50
+ `goal → research → acceptance → plan → plan-cite-check → grade → implement → implement-scope-check → reconcile → validate → (validate-fix, once) | commit`
51
51
 
52
- Ship a small, well-understood task in one lightweight forward pass. The verbatim brief is the goal artifact; a trimmed research stage (at most two `codebase-analyzer` dispatches — not a full `/skill:research` pass) grounds a single unsliced plan from `quick-plan`, which receives the verbatim goal alongside the research doc and must explicitly defer any goal ask it narrows out; a deterministic citation floor and one tier-independent three-dimension grade (correctness, completeness, architecture-fit — architecture-fit cannot be dropped from a light roster) gate the plan before `implement`. The citation floor stops the run only on a phase body edit missing from its `files:` declaration (an undeclared write corrupts implement's dependency derivation); every citation-resolution finding — unresolved path, ambiguity, line drift — is advisory (recorded on the verdict, severity `low`) and rides to the grade panel, whose correctness unit receives the floor's verdict as `--cite-check` and adjudicates each finding by symbol instead of the run dying over a resolver limitation. Every gate is stop-on-fail — no fix loops, confirm panels, snapshots, or code-elaboration lane — and a red gate surfaces as `stopped at <gate>: <reason>` in the end-of-run toast and lane recap (never a ✓); a goal-anchored `validate` judges the landing before `commit`. Best for tasks small enough to plan in one pass; prefer `build` for anything needing decomposition.
52
+ Ship a small, well-understood task in one lightweight forward pass. The verbatim brief is the goal artifact; a trimmed research stage sized to the brief's pre-chewedness (none or one verify-only `codebase-analyzer` dispatch when the brief names the root cause, files, or fix; at most two targeted dispatches otherwise — never a full `/skill:research` pass) grounds it; an `acceptance` stage then derives the executable standard of completion from the goal — ID'd observable outcomes with runnable evidence commands, frozen BEFORE planning so the standard cannot inherit the plan's scope (research grounds only the evidence, never the item set). A single unsliced plan from `quick-plan` receives the verbatim goal and the inventory alongside the research doc, records a per-item disposition (`implemented` naming the phase, or `deferred` with a reason), and must explicitly defer any goal ask it narrows out; a deterministic citation floor and one tier-independent three-dimension grade (correctness, completeness, architecture-fit — architecture-fit cannot be dropped from a light roster) gate the plan before `implement`. The citation floor stops the run only on a phase body edit missing from its `files:` declaration (an undeclared write corrupts implement's dependency derivation); every citation-resolution finding — unresolved path, ambiguity, line drift — is advisory (recorded on the verdict, severity `low`) and rides to the grade panel, whose correctness unit receives the floor's verdict as `--cite-check` and adjudicates each finding by symbol instead of the run dying over a resolver limitation. Every gate is stop-on-fail — no confirm panels, snapshots, or code-elaboration lane — and a red gate surfaces as `stopped at <gate>: <reason>` in the end-of-run toast and lane recap (never a ✓); hand-repair, then resume with `/wf @<run-id>` to re-run the halted gate against the repaired tree, reusing every upstream artifact. A goal-anchored `validate` judges the landing before `commit` — and EXECUTES the acceptance inventory's evidence commands against the finished tree (a failing item forces `verdict: fail` and lands as a structured, remediable blocker) — with the preset's one sanctioned repair arm: a validate `fail` carrying structured remediable handles (a `pass: false` risk ruling or a `blockers:` entry) buys ONE bounded `remediate` hop — re-verified end-to-end through the scope floor and reconcile — before any remaining fail halts; a prose-only fail halts immediately. Best for tasks small enough to plan in one pass; prefer `build` for anything needing decomposition.
53
53
 
54
54
  ## Review loops
55
55
 
@@ -0,0 +1,164 @@
1
+ /**
2
+ * Agent enablement — declarative knowledge of which bundled agents gain
3
+ * sibling-provided `ext:` tools when the providing sibling is installed,
4
+ * plus the pure gate/merge primitives that drive the conditional
5
+ * frontmatter injection in agents.ts.
6
+ *
7
+ * Pure utility: no ExtensionAPI, no filesystem reads, never throws. The
8
+ * enablement map names sibling extensions and tool selectors as plain
9
+ * strings — presence detection stays in package-checks.ts (the SIBLINGS
10
+ * registry is the single detection source; zero runtime imports of
11
+ * sibling packages).
12
+ */
13
+
14
+ /** What an agent gains when its enablement is active. */
15
+ export interface AgentEnablement {
16
+ /** Sibling extension names the agent must be allowed to load. */
17
+ readonly extensions: readonly string[];
18
+ /** Tool selectors appended to the agent's `tools` frontmatter. */
19
+ readonly tools: readonly string[];
20
+ }
21
+
22
+ /**
23
+ * Configurable per-agent override fields — a structural subset of the
24
+ * resolved models.json agent entry, kept local so this module stays
25
+ * dependency-free.
26
+ */
27
+ export interface AgentEnablementOverride {
28
+ readonly extensions?: readonly string[];
29
+ readonly tools?: readonly string[];
30
+ }
31
+
32
+ /**
33
+ * Bundled-agent tool/extension grants, keyed by agent basename (sans .md).
34
+ * A grant activates only while every named sibling is installed (the
35
+ * install gate) — tool selectors byte-match the granting sibling's
36
+ * registered tool names and its registry `provides` line.
37
+ *
38
+ * Currently EMPTY: the machinery ships dormant. The rpiv-lsp experiment
39
+ * (preserved on the backup/lsp-experiment branch) is the reference
40
+ * implementation for populating it when a sibling next ships agent-facing
41
+ * tools; per-agent grants also remain fully reachable through models.json
42
+ * `agents.<name>.tools/extensions` config with no map entry at all.
43
+ */
44
+ export const AGENT_ENABLEMENT_GRANTS: Readonly<Record<string, AgentEnablement>> = {};
45
+
46
+ /**
47
+ * Resolve the effective enablement for one agent, or undefined when
48
+ * inactive. Configured arrays replace the map's field wholesale (an
49
+ * explicit `[]` suppresses that field). Inactive when there is no
50
+ * effective content, when no installed-extensions set was supplied (gate
51
+ * closed), or when any named provider — the extensions list plus the
52
+ * sibling prefix of each `ext:` tool selector — is not installed.
53
+ * `grants` is injectable for tests; production call sites use the module
54
+ * map default.
55
+ */
56
+ export function resolveAgentEnablement(
57
+ agentKey: string,
58
+ config: AgentEnablementOverride | undefined,
59
+ installedExtensions: ReadonlySet<string> | undefined,
60
+ grants: Readonly<Record<string, AgentEnablement>> = AGENT_ENABLEMENT_GRANTS,
61
+ ): AgentEnablement | undefined {
62
+ const base = grants[agentKey];
63
+ const extensions = config?.extensions !== undefined ? config.extensions : (base?.extensions ?? []);
64
+ const tools = config?.tools !== undefined ? config.tools : (base?.tools ?? []);
65
+ if (extensions.length === 0 && tools.length === 0) return undefined;
66
+ if (installedExtensions === undefined) return undefined;
67
+ for (const name of extensions) {
68
+ if (!installedExtensions.has(name)) return undefined;
69
+ }
70
+ for (const selector of tools) {
71
+ if (!selector.startsWith("ext:")) continue;
72
+ const provider = selector.slice("ext:".length).split("/")[0];
73
+ if (provider !== "" && !installedExtensions.has(provider)) return undefined;
74
+ }
75
+ return { extensions, tools };
76
+ }
77
+
78
+ /** Split a comma-separated scalar into trimmed, non-empty items. */
79
+ function csvItems(value: string): string[] {
80
+ return value
81
+ .split(",")
82
+ .map((item) => item.trim())
83
+ .filter((item) => item !== "");
84
+ }
85
+
86
+ /** Trim additions the same way existing items are parsed. */
87
+ function trimmedAdditions(additions: readonly string[]): string[] {
88
+ return additions.map((item) => item.trim()).filter((item) => item !== "");
89
+ }
90
+
91
+ /** Boolean/null-like scalars — merging into them would silently flip semantics. */
92
+ function isSentinelScalar(value: string): boolean {
93
+ const lowered = value.toLowerCase();
94
+ return lowered === "true" || lowered === "false" || lowered === "none";
95
+ }
96
+
97
+ /** Deduplicate preserving first-occurrence order. */
98
+ function dedupePreservingOrder(items: readonly string[]): string[] {
99
+ return [...new Set(items)];
100
+ }
101
+
102
+ /**
103
+ * Merge `additions` into an existing CSV scalar (the `tools:` form).
104
+ * Parses the existing value as a comma-separated list (a bare scalar is a
105
+ * one-item list), dedupes preserving first-occurrence order, appends absent
106
+ * additions in given order, and joins with `", "`. An `undefined` existing
107
+ * value yields the additions alone. Boolean-ish sentinels (`true`/`false`/
108
+ * `none`), empty scalars (a block-sequence head), and flow-sequence forms
109
+ * return undefined — the caller skips the key (fail-soft, nothing emitted).
110
+ */
111
+ export function mergeCsvAdditions(existing: string | undefined, additions: readonly string[]): string | undefined {
112
+ if (existing === undefined) {
113
+ const adds = trimmedAdditions(additions);
114
+ return adds.length > 0 ? adds.join(", ") : undefined;
115
+ }
116
+ const trimmed = existing.trim();
117
+ if (trimmed === "" || isSentinelScalar(trimmed)) return undefined;
118
+ if (trimmed.startsWith("[")) return undefined;
119
+ const items = dedupePreservingOrder([...csvItems(trimmed), ...trimmedAdditions(additions)]);
120
+ return items.length > 0 ? items.join(", ") : undefined;
121
+ }
122
+
123
+ /**
124
+ * Merge `additions` into an existing YAML flow sequence (the `extensions:`
125
+ * form). Accepts `[a, b]` or a bare scalar as the base, dedupes preserving
126
+ * first-occurrence order, appends absent additions, and renders `[a, b]`.
127
+ * An `undefined` existing value yields the additions alone. Sentinels,
128
+ * empty scalars, CSV forms, and unclosed brackets return undefined — the
129
+ * caller skips the key.
130
+ */
131
+ export function mergeFlowSeqAdditions(existing: string | undefined, additions: readonly string[]): string | undefined {
132
+ if (existing === undefined) {
133
+ const adds = trimmedAdditions(additions);
134
+ return adds.length > 0 ? `[${adds.join(", ")}]` : undefined;
135
+ }
136
+ const trimmed = existing.trim();
137
+ if (trimmed === "" || isSentinelScalar(trimmed)) return undefined;
138
+ let inner: string;
139
+ if (trimmed.startsWith("[")) {
140
+ if (!trimmed.endsWith("]")) return undefined;
141
+ inner = trimmed.slice(1, -1);
142
+ } else {
143
+ if (trimmed.includes(",")) return undefined;
144
+ inner = trimmed;
145
+ }
146
+ const items = dedupePreservingOrder([...csvItems(inner), ...trimmedAdditions(additions)]);
147
+ return items.length > 0 ? `[${items.join(", ")}]` : undefined;
148
+ }
149
+
150
+ /**
151
+ * Derive installed extension names from package spec strings:
152
+ * `npm:@juicesharp/rpiv-warp` → `rpiv-warp` — the last path segment after
153
+ * any protocol prefix, lowercased (the directory ↔ npm ↔ extension-name
154
+ * family convention). Non-string entries are the caller's to filter.
155
+ */
156
+ export function installedExtensionNames(pkgs: readonly string[]): ReadonlySet<string> {
157
+ const names = new Set<string>();
158
+ for (const entry of pkgs) {
159
+ const noProto = entry.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:/, "");
160
+ const base = noProto.split("/").filter(Boolean).pop();
161
+ if (base !== undefined) names.add(base.toLowerCase());
162
+ }
163
+ return names;
164
+ }
@@ -27,8 +27,15 @@ import {
27
27
  } from "node:fs";
28
28
  import { isAbsolute, join, resolve, sep } from "node:path";
29
29
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
30
- import { parseFrontmatterBounds } from "./frontmatter.js";
30
+ import {
31
+ installedExtensionNames,
32
+ mergeCsvAdditions,
33
+ mergeFlowSeqAdditions,
34
+ resolveAgentEnablement,
35
+ } from "./agent-enablement.js";
36
+ import { parseFrontmatterBounds, readFrontmatterKey } from "./frontmatter.js";
31
37
  import { getAgentModelConfig, loadModelsConfig, type ModelsConfig } from "./models-config.js";
38
+ import { findInstalledSiblings } from "./package-checks.js";
32
39
  import { BUNDLED_AGENTS_DIR } from "./paths.js";
33
40
  import { isPlainObject, toErrorMessage } from "./utils.js";
34
41
 
@@ -324,23 +331,48 @@ function applyKeyUpdates(
324
331
  }
325
332
 
326
333
  /**
327
- * Inject model/thinking frontmatter into agent .md content.
334
+ * Install-gate context for conditional frontmatter injection.
335
+ *
336
+ * `installedExtensions` is the set of installed sibling extension names,
337
+ * derived from ONE settings read per sync pass. An absent context closes
338
+ * the enablement gate entirely — today's model/thinking-only behavior,
339
+ * byte-for-byte.
340
+ */
341
+ export interface AgentInjectionContext {
342
+ readonly installedExtensions: ReadonlySet<string>;
343
+ }
344
+
345
+ /**
346
+ * Inject model/thinking + conditional enablement frontmatter into agent .md content.
328
347
  *
329
- * Idempotent: re-injecting produces identical bytes. The function finds
330
- * the closing `---` of the YAML frontmatter block and inserts or replaces
331
- * `model:` and `thinking:` lines deterministically.
348
+ * Idempotent: re-injecting produces identical bytes, with the gate open or
349
+ * closed. The function finds the closing `---` of the YAML frontmatter
350
+ * block and deterministically inserts or replaces keys.
332
351
  *
333
- * If no override is configured for this agent, returns content unchanged.
352
+ * Enablement (fourth arg): when the context names every sibling provider an
353
+ * agent's enablement requires as installed, the agent additionally gains
354
+ * the merged `tools` CSV, an `extensions: [...]` flow sequence, and — only
355
+ * when the shipped file carries `isolated: true` — the `isolated: false` +
356
+ * `skills: false` pair. No override and no active enablement ⇒ content
357
+ * unchanged.
334
358
  *
335
359
  * Exported so the idempotency invariant can be unit-tested directly:
336
360
  * `inject(inject(x)) === inject(x)` (see Verification Notes).
337
361
  */
338
- export function injectModelFrontmatter(content: string, agentFile: string, config: ModelsConfig): string {
362
+ export function injectModelFrontmatter(
363
+ content: string,
364
+ agentFile: string,
365
+ config: ModelsConfig,
366
+ injection?: AgentInjectionContext,
367
+ ): string {
339
368
  // Strip .md extension — source entries are filenames like "codebase-analyzer.md"
340
369
  // but models.json keys are agent names like "codebase-analyzer".
341
370
  const agentKey = agentFile.replace(/\.md$/, "");
342
371
  const override = getAgentModelConfig(config, agentKey);
343
- if (!override || (override.model === undefined && override.thinking === undefined)) {
372
+ const enablement = resolveAgentEnablement(agentKey, override, injection?.installedExtensions);
373
+ // Tools-only entries must not be skipped: enablement alone proceeds.
374
+ const hasModelKeys = override?.model !== undefined || override?.thinking !== undefined;
375
+ if (!hasModelKeys && enablement === undefined) {
344
376
  return content;
345
377
  }
346
378
 
@@ -354,8 +386,43 @@ export function injectModelFrontmatter(content: string, agentFile: string, confi
354
386
  // — re-injecting produces identical bytes by construction; the idempotency
355
387
  // invariant at injectModelFrontmatter's JSDoc strengthens from "deterministic
356
388
  // translation" to "byte pass-through".
357
- if (override.model !== undefined) keysToSet.push({ key: "model", value: override.model });
358
- if (override.thinking !== undefined) keysToSet.push({ key: "thinking", value: override.thinking });
389
+ if (override?.model !== undefined) keysToSet.push({ key: "model", value: override.model });
390
+ if (override?.thinking !== undefined) keysToSet.push({ key: "thinking", value: override.thinking });
391
+
392
+ if (enablement !== undefined) {
393
+ // Fixed order [model?, thinking?, tools, extensions, isolated?, skills?]:
394
+ // in-place replacements keep their shipped position; absent keys append
395
+ // before the closing fence in this order.
396
+ const mergedTools = mergeCsvAdditions(readFrontmatterKey(lines, bounds, "tools"), enablement.tools);
397
+ const mergedExtensions = mergeFlowSeqAdditions(
398
+ readFrontmatterKey(lines, bounds, "extensions"),
399
+ enablement.extensions,
400
+ );
401
+ // ATOMIC transform (review 2026-08-31 I2): a merge that fail-soft-skips
402
+ // an unmergeable frontmatter form (block-sequence, sentinel) while its
403
+ // additions are non-empty means the grant CANNOT land — applying the
404
+ // remaining keys anyway would flip `isolated`/`skills` off while
405
+ // granting nothing, silently un-scoping the agent on every sync. Skip
406
+ // the whole enablement key set and warn loudly instead.
407
+ const toolsMergeFailed = enablement.tools.length > 0 && mergedTools === undefined;
408
+ const extensionsMergeFailed = enablement.extensions.length > 0 && mergedExtensions === undefined;
409
+ if (toolsMergeFailed || extensionsMergeFailed) {
410
+ console.warn(
411
+ `[rpiv-pi] agent enablement skipped for ${agentFile}: the ${toolsMergeFailed ? "tools" : "extensions"} frontmatter form is not mergeable (block sequence or sentinel value) — rewrite it as a ${toolsMergeFailed ? "single-line CSV scalar" : "flow sequence"} to receive the grant`,
412
+ );
413
+ } else {
414
+ if (mergedTools !== undefined) keysToSet.push({ key: "tools", value: mergedTools });
415
+ if (mergedExtensions !== undefined) keysToSet.push({ key: "extensions", value: mergedExtensions });
416
+ // Flipping isolation is the point of enablement (`ext:` selectors are
417
+ // dropped while isolated) — but derive the pair only when the source
418
+ // declares `isolated: true`: re-injecting an already-injected form pushes
419
+ // neither key (idempotency), and non-isolated agents stay untouched.
420
+ if (readFrontmatterKey(lines, bounds, "isolated")?.toLowerCase() === "true") {
421
+ keysToSet.push({ key: "isolated", value: "false" });
422
+ keysToSet.push({ key: "skills", value: "false" });
423
+ }
424
+ }
425
+ }
359
426
 
360
427
  const updated = applyKeyUpdates(lines, bounds, keysToSet);
361
428
  return updated.join("\n");
@@ -377,6 +444,14 @@ function processSourceEntries(
377
444
  // Hoisted above the loop: loadModelsConfig() reads+parses JSON, so calling it
378
445
  // per-entry would re-read the file once per agent (~15×) every session_start.
379
446
  const config = loadModelsConfig();
447
+ // One settings read per sync pass for the enablement gate. The SAME
448
+ // context must flow into every injectModelFrontmatter call in this pass —
449
+ // the manifest records hash-after-transform, so a gate that flipped
450
+ // mid-pass would tear the recorded hashes and falsely flag agents
451
+ // diverged.
452
+ const injection: AgentInjectionContext = {
453
+ installedExtensions: installedExtensionNames(findInstalledSiblings().map((s) => s.pkg)),
454
+ };
380
455
 
381
456
  for (const entry of sourceEntries) {
382
457
  const src = join(BUNDLED_AGENTS_DIR, entry);
@@ -400,7 +475,7 @@ function processSourceEntries(
400
475
  // manifest hash matches what actually lands on disk (hash-after-transform).
401
476
  // injectModelFrontmatter strips .md from entry for config lookup and is a
402
477
  // no-op when no override is configured.
403
- const injected = injectModelFrontmatter(srcContent.toString("utf-8"), entry, config);
478
+ const injected = injectModelFrontmatter(srcContent.toString("utf-8"), entry, config, injection);
404
479
  const srcHash = sha256(injected);
405
480
 
406
481
  if (!existsSync(dest)) {
@@ -614,6 +689,12 @@ export function cleanupPerCwdAgents(cwd: string): CleanupResult {
614
689
  // Hoisted config read (same reasoning as processSourceEntries): one JSON
615
690
  // read for the whole cleanup pass, not one per managed file.
616
691
  const cleanupConfig = loadModelsConfig();
692
+ // Same shared-gate rule as processSourceEntries: the legacy-dir comparison
693
+ // must use one settings read for the whole pass — the identical gate a
694
+ // sync pass with the same settings would have used.
695
+ const cleanupInjection: AgentInjectionContext = {
696
+ installedExtensions: installedExtensionNames(findInstalledSiblings().map((s) => s.pkg)),
697
+ };
617
698
  for (const [name] of Object.entries(manifest)) {
618
699
  const srcPath = safeJoin(BUNDLED_AGENTS_DIR, name);
619
700
  const destPath = safeJoin(perCwdDir, name);
@@ -650,7 +731,12 @@ export function cleanupPerCwdAgents(cwd: string): CleanupResult {
650
731
  // Compare against the injected form — the dest holds injected content,
651
732
  // so comparing raw source would falsely flag every configured agent
652
733
  // as diverged. injectModelFrontmatter strips .md from name for lookup.
653
- const cleanupInjected = injectModelFrontmatter(srcContent.toString("utf-8"), name, cleanupConfig);
734
+ const cleanupInjected = injectModelFrontmatter(
735
+ srcContent.toString("utf-8"),
736
+ name,
737
+ cleanupConfig,
738
+ cleanupInjection,
739
+ );
654
740
  if (sha256(destContent) !== sha256(cleanupInjected)) {
655
741
  // User edited this file — conservative gate.
656
742
  result.skipped.push({ dir: perCwdDir, reason: CLEANUP_SKIP_REASON.DIVERGED });