@juicesharp/rpiv-pi 2.8.0 → 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.
@@ -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 });
@@ -301,6 +301,97 @@ const scopeFloorGate = (): EdgeFn => {
301
301
  return route;
302
302
  };
303
303
 
304
+ /**
305
+ * The reconciliation gate — pass ⇒ validate; fail ⇒ the `reconcile-fix` repair
306
+ * arm; missing/corrupt verdict ⇒ STOP (integrity clause, exactly the `match` it
307
+ * replaces). The arm exists because every reconcile failure class — a malformed
308
+ * directive, a stale `find`, a non-test target — is a defect in the PLAN's
309
+ * directive text, which is `amend`'s exact authority ("fix the artifact, never
310
+ * the repo"); the old no-arm route stopped the run on a fail that hand-repairing
311
+ * the TREE could never clear (run 2026-08-31_15-21-14-57d0: a multi-line
312
+ * directive re-failed every resume because the defect lived in the plan
313
+ * artifact, which nothing in the pipeline could edit). Reconcile itself stays
314
+ * the sole test-file writer — the arm only repairs directives; the loop
315
+ * re-enters reconcile to apply them.
316
+ *
317
+ * A factory for the validateGate/scopeFloorGate reason — each workflow's
318
+ * route-note symbol must never alias the other's. `maxFixRounds` caps the
319
+ * amend hops a fail may buy, counted from the `reconcile-fix` channel — the
320
+ * channel ONLY the arm itself writes (its outcome publishes there, not on
321
+ * `plans`), mirroring validateGate's `remediation`-channel cap. It must NOT
322
+ * count reconcile-channel entries: reconcile re-executes on paths that spend
323
+ * no amend hop — ship's validate-fix loop re-enters through
324
+ * implement-scope-check → reconcile, and a resume replays entries — so an
325
+ * entry-count budget let the validate-fix loop spend the arm's only round
326
+ * before the arm ever ran, with a stop-note claiming a fix round that never
327
+ * happened (review 2026-08-31 I1; the fourth instance of the cap-must-read-a-
328
+ * channel-the-arm-writes lesson). Build/vet pass no cap (the runner's
329
+ * per-destination backward-jump budget on `reconcile-fix` is theirs, the
330
+ * plan-fix precedent); ship caps at ONE — the same single bounded hop its
331
+ * stop-on-fail identity concedes at the validate gate.
332
+ */
333
+ const reconcileGate = (opts?: { maxFixRounds?: number }): EdgeFn => {
334
+ const maxFixRounds = opts?.maxFixRounds ?? Number.POSITIVE_INFINITY;
335
+ const route: EdgeFn = defineRoute(
336
+ ["validate", "reconcile-fix", "stop"],
337
+ ({ state }) => {
338
+ const verdict = (state.named.reconcile?.at(-1)?.data as { verdict?: unknown } | undefined)?.verdict;
339
+ if (verdict === "pass") return "validate";
340
+ if (verdict !== "fail") {
341
+ setRouteNote(
342
+ route,
343
+ `reconcile verdict ${JSON.stringify(verdict ?? null)} matched no branch — terminated (no fallback)`,
344
+ );
345
+ return "stop";
346
+ }
347
+ const roundsSpent = state.named["reconcile-fix"]?.length ?? 0;
348
+ if (roundsSpent >= maxFixRounds) {
349
+ setRouteNote(
350
+ route,
351
+ `reconcile still fails after ${roundsSpent} amend round${roundsSpent === 1 ? "" : "s"} — repair the #### Reconciliation directives in the PLAN artifact by hand (the failure lives in the plan text, not the tree), then resume`,
352
+ );
353
+ return "stop";
354
+ }
355
+ return "reconcile-fix";
356
+ },
357
+ { readsData: false },
358
+ );
359
+ return route;
360
+ };
361
+
362
+ /**
363
+ * The `reconcile-fix` arm's dispatch — `/skill:amend` over the latest plan and
364
+ * the reconcile verdict. A PROMPT stage (owning its whole message, the
365
+ * VALIDATE_PLANS_PROMPT precedent) because amend's generic flag parser keys
366
+ * verdict inputs on the `-verdicts` name suffix, and reconcile's script stage
367
+ * publishes on its stage-key channel `reconcile` — a `reads: ["reconcile"]`
368
+ * skill stage would thread `--reconcile <path>`, which amend reads as a SECOND
369
+ * artifact flag and refuses. The explicit `--reconcile-verdicts` spelling
370
+ * parses as exactly one artifact (`--plans`) + one verdicts flag. The gate only
371
+ * dispatches this arm on a fail verdict, so both channel reads are present by
372
+ * construction; a torn state degrades to amend's own front-door refusal
373
+ * (exactly-one-artifact + at-least-one-verdicts), never a silent guess.
374
+ */
375
+ const RECONCILE_FIX_PROMPT: PromptFn = ({ state }) => {
376
+ const parts = ["/skill:amend"];
377
+ const plan = latestFsArtifact(state, "plans");
378
+ if (plan) parts.push("--plans", handleToString(plan.handle));
379
+ const verdict = state.named.reconcile?.at(-1)?.artifacts.find((a) => a.handle.kind === "fs");
380
+ if (verdict) parts.push("--reconcile-verdicts", handleToString(verdict.handle));
381
+ return parts.join(" ");
382
+ };
383
+
384
+ /**
385
+ * The arm's outcome — the plans-bucket collector publishing on the arm's OWN
386
+ * `reconcile-fix` channel. Amend re-emits the plan IN PLACE (same path, its
387
+ * hard rule), so the `plans` channel's latest entry stays correct without a
388
+ * republish; what the channel choice buys is the round counter ONLY the arm
389
+ * increments, which `reconcileGate`'s cap reads (the validateGate/
390
+ * `remediation` pattern — see the gate doc for why counting reconcile
391
+ * executions instead let the validate-fix loop spend the budget).
392
+ */
393
+ const RECONCILE_FIX_OUTCOME = { ...rpivBucketOutcome("plans"), name: "reconcile-fix" };
394
+
304
395
  const vetWorkflow = defineWorkflow({
305
396
  name: "vet",
306
397
  description:
@@ -349,11 +440,16 @@ const vetWorkflow = defineWorkflow({
349
440
  "scope-quarantine": produces.script({ reads: ["implement-scope-check"], run: scopeQuarantine }),
350
441
  // Deterministic post-implement reconciliation (no LLM) — the SAME `reconcile`
351
442
  // run-function as build (no vet twin): applies every `#### Reconciliation`
352
- // directive (write-restricted to test files) + re-runs every per-phase
353
- // `#### Automated Verification:` command, fail-soft. Pass ⇒ validate; fail/
354
- // missing ⇒ STOP (no fallback). `reads: ["plans"]` only — no run-start goal
355
- // baseline. The `from` form suppresses the READS_DATA outputSchema lint.
443
+ // directive (write-restricted to the plan's declared write-set), fail-soft. Pass ⇒ validate;
444
+ // fail ⇒ the reconcile-fix arm (see reconcileGate); missing ⇒ STOP.
445
+ // `reads: ["plans"]` only — no run-start goal baseline.
356
446
  reconcile: produces.script({ reads: ["plans"], run: reconcile }),
447
+ // Repair arm for the reconciliation gate: /skill:amend over the plan's
448
+ // directives from the reconcile verdict (a prompt stage — see
449
+ // RECONCILE_FIX_PROMPT), re-emitting the plan latest-wins, then back
450
+ // through reconcile to apply. Bounded by the runner's per-destination
451
+ // backward-jump budget (the plan-fix precedent).
452
+ "reconcile-fix": produces.prompt({ prompt: RECONCILE_FIX_PROMPT, outcome: RECONCILE_FIX_OUTCOME }),
357
453
  validate: produces(),
358
454
  commit: acts({ outcome: gitCommitOutcome }),
359
455
  },
@@ -379,10 +475,14 @@ const vetWorkflow = defineWorkflow({
379
475
  // either passes or reveals tracked drift. At most one quarantine hop per
380
476
  // gate entry; no new loop budget.
381
477
  "scope-quarantine": "implement-scope-check",
382
- // Reconciliation gate. Pass ⇒ validate; a `fail` (non-test directive target /
383
- // absent find / failed AV command) or a missing verdict ⇒ STOP (no fix arm —
384
- // a reconciliation failure is plan-vs-tree drift the agent reconciles manually).
385
- reconcile: match("verdict", { validate: "pass" }, { from: "reconcile" }),
478
+ // Reconciliation gate. Pass ⇒ validate; a `fail` (malformed directive /
479
+ // absent find / non-test target — all plan-TEXT defects) ⇒ the
480
+ // reconcile-fix amend arm; a missing verdict ⇒ STOP (integrity clause).
481
+ reconcile: reconcileGate(),
482
+ // Deterministic re-entry after the amend arm: reconcile re-parses the
483
+ // repaired directives and applies them (a plain string edge — the
484
+ // counted decision is the gate's reconcile-fix pick).
485
+ "reconcile-fix": "reconcile",
386
486
  // Backward edge: validate → code-review creates the review-fix loop —
387
487
  // UNCHANGED. The scope-check inserts before validate, so a failing scope
388
488
  // verdict halts before re-review, and a passing one flows into validate and
@@ -709,15 +809,20 @@ const buildWorkflow = defineWorkflow({
709
809
  // and publish a manifest, then re-enter the floor — see scopeQuarantine.
710
810
  "scope-quarantine": produces.script({ reads: ["implement-scope-check"], run: scopeQuarantine }),
711
811
  // Deterministic post-implement reconciliation (no LLM): applies every
712
- // `#### Reconciliation` directive (find→replace, write-restricted to test
713
- // files) and re-runs every per-phase `#### Automated Verification:`
714
- // command, fail-soft — a coherence backstop the parallel implement lane
715
- // needs (a phase's correct change can invalidate a sibling's test, and the
812
+ // `#### Reconciliation` directive (find→replace, write-restricted to the
813
+ // plan's declared write-set), fail-soft — a coherence backstop the parallel
814
+ // implement lane needs (a phase's correct change can invalidate a sibling's test, and the
716
815
  // combined tree can break in ways no single phase's checks surface). Pass ⇒
717
- // validate; fail/missing ⇒ STOP (no fallback). `reads: ["plans"]` only — no
718
- // run-start goal baseline (the scope floor already proved the write-set). The
719
- // `from` form suppresses the READS_DATA outputSchema lint.
816
+ // validate; fail ⇒ the reconcile-fix arm (see reconcileGate); missing ⇒
817
+ // STOP. `reads: ["plans"]` only — no run-start goal baseline (the scope
818
+ // floor already proved the write-set).
720
819
  reconcile: produces.script({ reads: ["plans"], run: reconcile }),
820
+ // Repair arm for the reconciliation gate: /skill:amend over the plan's
821
+ // directives from the reconcile verdict (a prompt stage — see
822
+ // RECONCILE_FIX_PROMPT), re-emitting the plan latest-wins, then back
823
+ // through reconcile to apply. Bounded by the runner's per-destination
824
+ // backward-jump budget (the plan-fix precedent).
825
+ "reconcile-fix": produces.prompt({ prompt: RECONCILE_FIX_PROMPT, outcome: RECONCILE_FIX_OUTCOME }),
721
826
  validate: produces({ prompt: VALIDATE_GOAL_PROMPT }),
722
827
  // Repair arm the validate gate dispatches on a remediable `verdict: "fail"`.
723
828
  // `acts()` (not `produces()`) because remediate is `side-effect`/`code-mutation`
@@ -886,12 +991,16 @@ const buildWorkflow = defineWorkflow({
886
991
  // reveals tracked drift. At most one quarantine hop per gate entry; no new
887
992
  // loop budget.
888
993
  "scope-quarantine": "implement-scope-check",
889
- // Reconciliation gate. Pass ⇒ validate; a `fail` (non-test directive target
890
- // / absent find / failed AV command) or a missing verdict ⇒ STOP (no fix
891
- // arm — a reconciliation failure is plan-vs-tree drift the agent reconciles
892
- // manually). Safe by construction: the sole path onward is an explicit
893
- // `verdict: "pass"`. Sourced from the reconcile channel via the `from` form.
894
- reconcile: match("verdict", { validate: "pass" }, { from: "reconcile" }),
994
+ // Reconciliation gate. Pass ⇒ validate; a `fail` (malformed directive /
995
+ // absent find / non-test target — all plan-TEXT defects) ⇒ the
996
+ // reconcile-fix amend arm; a missing verdict ⇒ STOP (integrity clause).
997
+ // Safe by construction: the sole path onward to validate is an explicit
998
+ // `verdict: "pass"`.
999
+ reconcile: reconcileGate(),
1000
+ // Deterministic re-entry after the amend arm: reconcile re-parses the
1001
+ // repaired directives and applies them (a plain string edge — the
1002
+ // counted decision is the gate's reconcile-fix pick).
1003
+ "reconcile-fix": "reconcile",
895
1004
  // Gate commit on validate's own verdict — see `validateGate`. `pass` ⇒
896
1005
  // commit; a `fail` WITH remediable handles (a `pass: false` risk ruling or a
897
1006
  // structured `blockers:` entry) ⇒ validate-fix, which re-enters at
@@ -1010,7 +1119,7 @@ const shipGradeGate: EdgeFn = defineRoute(
1010
1119
  const shipWorkflow = defineWorkflow({
1011
1120
  name: "ship",
1012
1121
  description:
1013
- "Ship, unsliced: capture the verbatim brief as a goal artifact → ground it with a brief-sized research pass (none or one verify-only codebase-analyzer dispatch when the brief names root cause, files, or fix; at most two targeted dispatches otherwise — no /skill:research) → derive a goal-anchored acceptance inventory (the executable standard of completion, frozen before planning; quick-plan records a per-item disposition, the completeness gate anchors on it, validate executes its evidence commands) → one lightweight quick-plan pass → deterministic citation floor (files: coverage gaps stop; citation-resolution findings are advisory and adjudicated by the grade panel) → single tier-independent quality gate (correctness/completeness/architecture-fit, stop-on-fail) → implement → implement-scope-check → reconcile → validate → commit. Every gate halts the run on fail (hand-repair, then resume with /wf @<runId> to re-run the gate) — except a validate fail carrying structured remediable handles, which buys ONE bounded remediation hop before halting.",
1122
+ "Ship, unsliced: capture the verbatim brief as a goal artifact → ground it with a brief-sized research pass (none or one verify-only codebase-analyzer dispatch when the brief names root cause, files, or fix; at most two targeted dispatches otherwise — no /skill:research) → derive a goal-anchored acceptance inventory (the executable standard of completion, frozen before planning; quick-plan records a per-item disposition, the completeness gate anchors on it, validate executes its evidence commands) → one lightweight quick-plan pass → deterministic citation floor (files: coverage gaps stop; citation-resolution findings are advisory and adjudicated by the grade panel) → single tier-independent quality gate (correctness/completeness/architecture-fit, stop-on-fail) → implement → implement-scope-check → reconcile → validate → commit. Every gate halts the run on fail (hand-repair, then resume with /wf @<runId> to re-run the gate) — except a reconcile fail (a plan-text directive defect), which buys ONE bounded amend hop over the plan's directives, and a validate fail carrying structured remediable handles, which buys ONE bounded remediation hop before halting.",
1014
1123
  start: "goal",
1015
1124
  stages: {
1016
1125
  // build's verbatim goal capture — the brief on its own channel, plus the
@@ -1076,8 +1185,15 @@ const shipWorkflow = defineWorkflow({
1076
1185
  // declared write-set is the whole contract). Pass ⇒ reconcile; fail ⇒ STOP.
1077
1186
  "implement-scope-check": produces.script({ reads: ["plans", "goal"], run: implementScopeCheck }),
1078
1187
  // Deterministic post-implement reconciliation — build's run-function
1079
- // verbatim. Pass ⇒ validate; fail/missing ⇒ STOP (no fallback).
1188
+ // verbatim. Pass ⇒ validate; fail ⇒ ONE bounded reconcile-fix hop
1189
+ // (maxFixRounds: 1 — the validate-gate concession's twin); missing ⇒ STOP.
1080
1190
  reconcile: produces.script({ reads: ["plans"], run: reconcile }),
1191
+ // Repair arm — build's prompt stage verbatim; ship's reconcile gate
1192
+ // dispatches it at most ONCE. Kept despite the stop-on-fail identity for
1193
+ // the same reason as validate-fix: a reconcile fail is a plan-TEXT defect
1194
+ // a hand-repair of the TREE can never clear, so the terminal stop was
1195
+ // unresumable without hand-editing the plan artifact.
1196
+ "reconcile-fix": produces.prompt({ prompt: RECONCILE_FIX_PROMPT, outcome: RECONCILE_FIX_OUTCOME }),
1081
1197
  validate: produces({ prompt: VALIDATE_GOAL_PROMPT }),
1082
1198
  // Repair arm — build's stage verbatim; ship's validate gate dispatches it
1083
1199
  // at most ONCE (maxFixRounds: 1). Kept because the terminal gate is where
@@ -1106,9 +1222,15 @@ const shipWorkflow = defineWorkflow({
1106
1222
  // the stage's own channel via the `from` form (suppresses the READS_DATA
1107
1223
  // outputSchema lint).
1108
1224
  "implement-scope-check": match("verdict", { reconcile: "pass" }, { from: "implement-scope-check" }),
1109
- // Reconciliation gate — build's route verbatim: pass ⇒ validate;
1110
- // fail/missing ⇒ STOP (plan-vs-tree drift the agent reconciles manually).
1111
- reconcile: match("verdict", { validate: "pass" }, { from: "reconcile" }),
1225
+ // Reconciliation gate — build's route, capped at ONE amend round (the
1226
+ // reconcile channel's entry count IS the rounds spent): pass ⇒ validate;
1227
+ // first fail ⇒ reconcile-fix; a fail after the spent round, or a missing
1228
+ // verdict ⇒ STOP with a route note naming the plan artifact as the
1229
+ // repair site.
1230
+ reconcile: reconcileGate({ maxFixRounds: 1 }),
1231
+ // Re-entry after the amend arm — reconcile re-parses and applies the
1232
+ // repaired directives; the spent round now stops any remaining fail.
1233
+ "reconcile-fix": "reconcile",
1112
1234
  // Validate gate — build's classifying gate, capped at ONE remediation
1113
1235
  // round: `pass` ⇒ commit; a `fail` WITH structured remediable handles and
1114
1236
  // no remediation spent ⇒ validate-fix; every other fail (prose-only, or
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Typed surface of reconcile-directives.mjs for the TS consumer
3
+ * (extensions/rpiv-core/built-ins/reconcile.ts). Keep in lockstep with the
4
+ * .mjs exports — the runtime source of truth.
5
+ */
6
+
7
+ /** One `#### Reconciliation` directive parsed from a plan body. */
8
+ export interface ReconciliationDirective {
9
+ /** Repo-root-relative target declared in the plan's write-set. */
10
+ target: string;
11
+ /** Substring to find (replaced exactly once via `String.replace`). */
12
+ find: string;
13
+ /** Replacement string. */
14
+ replace: string;
15
+ }
16
+
17
+ /** What applying a directive to the target's current content would do. */
18
+ export type ApplicationClass = "already-applied" | "apply" | "deletion-satisfied" | "missing";
19
+
20
+ export declare function reconciliationRecords(body: string): {
21
+ directives: ReconciliationDirective[];
22
+ malformed: string[];
23
+ };
24
+
25
+ export declare function classifyApplication(directive: ReconciliationDirective, content: string): ApplicationClass;
26
+
27
+ export declare function declaredWriteSet(body: string): Set<string>;
28
+
29
+ export declare function phaseSection(body: string, n: number | string): string | undefined;