@juicesharp/rpiv-pi 2.13.4 → 2.13.6

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 (29) hide show
  1. package/README.md +1 -1
  2. package/extensions/rpiv-core/agents-allowlist.ts +47 -0
  3. package/extensions/rpiv-core/agents-inject.ts +151 -0
  4. package/extensions/rpiv-core/agents-manifest.ts +102 -0
  5. package/extensions/rpiv-core/agents-sync.ts +405 -0
  6. package/extensions/rpiv-core/agents-types.ts +115 -0
  7. package/extensions/rpiv-core/agents.ts +35 -773
  8. package/extensions/rpiv-core/built-in-workflows.ts +13 -1426
  9. package/extensions/rpiv-core/built-ins/citations.ts +1 -1
  10. package/extensions/rpiv-core/built-ins/gate-passes.ts +498 -0
  11. package/extensions/rpiv-core/built-ins/gate-rosters.ts +275 -0
  12. package/extensions/rpiv-core/built-ins/gates.ts +34 -951
  13. package/extensions/rpiv-core/built-ins/index.ts +5 -3
  14. package/extensions/rpiv-core/built-ins/reconcile.ts +1 -1
  15. package/extensions/rpiv-core/built-ins/slice-checks.ts +3 -3
  16. package/extensions/rpiv-core/built-ins/verdict-core.ts +202 -0
  17. package/extensions/rpiv-core/outcome-derivation.ts +2 -1
  18. package/extensions/rpiv-core/pi-compat.ts +59 -0
  19. package/extensions/rpiv-core/run-lane-registry.ts +28 -225
  20. package/extensions/rpiv-core/run-lane-types.ts +240 -0
  21. package/extensions/rpiv-core/sdk-workflow-host.ts +46 -18
  22. package/extensions/rpiv-core/workflows/build.ts +695 -0
  23. package/extensions/rpiv-core/workflows/polish.ts +62 -0
  24. package/extensions/rpiv-core/workflows/shared.ts +300 -0
  25. package/extensions/rpiv-core/workflows/ship.ts +329 -0
  26. package/extensions/rpiv-core/workflows/vet.ts +133 -0
  27. package/package.json +3 -2
  28. package/skills/_shared/stitch-elaborations.mjs +1 -1
  29. package/skills/elaborate/_helpers/validate-workflow-invariant.mjs +7 -5
@@ -1,774 +1,36 @@
1
1
  /**
2
- * Agent auto-copy — copies bundled agents into ~/.pi/agent/agents/.
3
- *
4
- * Pure utility. No ExtensionAPI interactions.
5
- *
6
- * Concurrency: NOT safe across multiple Pi sessions sharing one target dir.
7
- * The temp+rename atomic write in writeManifest guarantees the on-disk manifest
8
- * file is always a complete valid JSON (no truncated/half-written content), but
9
- * the read-modify-write lost-update problem remains: two sessions both reading
10
- * the manifest before either writes will race, and the second writer overwrites
11
- * the first's entries with its own stale snapshot. Advisory locking is a
12
- * deferred follow-up. The path allowlist in
13
- * readManifest neutralises the worst-case (arbitrary-path unlink) regardless of
14
- * concurrency.
15
- */
16
-
17
- import { createHash } from "node:crypto";
18
- import {
19
- existsSync,
20
- mkdirSync,
21
- readdirSync,
22
- readFileSync,
23
- renameSync,
24
- rmSync,
25
- unlinkSync,
26
- writeFileSync,
27
- } from "node:fs";
28
- import { isAbsolute, join, resolve, sep } from "node:path";
29
- import { getAgentDir } from "@earendil-works/pi-coding-agent";
30
- import {
31
- installedExtensionNames,
32
- mergeCsvAdditions,
33
- mergeFlowSeqAdditions,
34
- resolveAgentEnablement,
35
- } from "./agent-enablement.js";
36
- import { parseFrontmatterBounds, readFrontmatterKey } from "./frontmatter.js";
37
- import { getAgentModelConfig, loadModelsConfig, type ModelsConfig } from "./models-config.js";
38
- import { findInstalledSiblings } from "./package-checks.js";
39
- import { BUNDLED_AGENTS_DIR } from "./paths.js";
40
- import { isPlainObject, toErrorMessage } from "./utils.js";
41
-
42
- // ---------------------------------------------------------------------------
43
- // Types
44
- // ---------------------------------------------------------------------------
45
-
46
- /** Named constants for sync operation identifiers. */
47
- export const SYNC_OP = {
48
- READ_SRC: "read-src",
49
- READ_DEST: "read-dest",
50
- COPY: "copy",
51
- REMOVE: "remove",
52
- MANIFEST_WRITE: "manifest-write",
53
- MKDIR: "mkdir",
54
- } as const;
55
-
56
- /** String union derived from SYNC_OP. */
57
- export type SyncOp = (typeof SYNC_OP)[keyof typeof SYNC_OP];
58
-
59
- export interface SyncError {
60
- file?: string;
61
- op: SyncOp;
62
- message: string;
63
- }
64
-
65
- export interface SyncResult {
66
- /** New files copied (present in source, absent from destination). */
67
- added: string[];
68
- /** Existing managed files overwritten with updated source content. */
69
- updated: string[];
70
- /** Managed files whose destination content matches source exactly. */
71
- unchanged: string[];
72
- /** Stale managed files removed (present in manifest but absent from source). */
73
- removed: string[];
74
- /** Managed files with different destination content (detected but not applied). */
75
- pendingUpdate: string[];
76
- /** Managed files no longer in source (detected but not removed). */
77
- pendingRemove: string[];
78
- /** Per-file errors collected during sync. */
79
- errors: SyncError[];
80
- }
81
-
82
- /** Create an empty SyncResult with all arrays initialized. */
83
- function emptySyncResult(): SyncResult {
84
- return {
85
- added: [],
86
- updated: [],
87
- unchanged: [],
88
- removed: [],
89
- pendingUpdate: [],
90
- pendingRemove: [],
91
- errors: [],
92
- };
93
- }
94
-
95
- /** Discriminant for why a per-cwd directory was left intact. */
96
- export const CLEANUP_SKIP_REASON = {
97
- /** No manifest present — directory was never installed by rpiv (hand-managed). */
98
- UNMANAGED: "unmanaged",
99
- /** Managed file content diverges from current bundle source (user edit, deletion, or source change). */
100
- DIVERGED: "diverged",
101
- /** Directory contains non-managed files (user added custom agents). */
102
- CUSTOM_FILES: "custom-files",
103
- } as const;
104
-
105
- export type CleanupSkipReason = (typeof CLEANUP_SKIP_REASON)[keyof typeof CLEANUP_SKIP_REASON];
106
-
107
- export interface CleanupSkip {
108
- dir: string;
109
- reason: CleanupSkipReason;
110
- }
111
-
112
- export interface CleanupResult {
113
- /** Per-cwd agent directories successfully removed (all managed files matched source). */
114
- cleanedUp: string[];
115
- /** Directories preserved with discriminated reason — see CLEANUP_SKIP_REASON. */
116
- skipped: CleanupSkip[];
117
- /** Per-file errors collected during cleanup. */
118
- errors: SyncError[];
119
- }
120
-
121
- /** Create an empty CleanupResult with all arrays initialized. */
122
- function emptyCleanupResult(): CleanupResult {
123
- return {
124
- cleanedUp: [],
125
- skipped: [],
126
- errors: [],
127
- };
128
- }
129
-
130
- /**
131
- * Format skip counts as a comma-joined parts list ("N edited, M with custom files").
132
- * Shared by session_start notifyCleanup and /rpiv-update-agents handler so the
133
- * two consumer surfaces describe preserved directories identically.
134
- */
135
- export function summarizeCleanupSkips(skipped: CleanupSkip[]): string {
136
- if (skipped.length === 0) return "";
137
- const counts: Record<CleanupSkipReason, number> = {
138
- unmanaged: 0,
139
- diverged: 0,
140
- "custom-files": 0,
141
- };
142
- for (const s of skipped) counts[s.reason]++;
143
- const parts: string[] = [];
144
- if (counts.unmanaged > 0) parts.push(`${counts.unmanaged} unmanaged`);
145
- if (counts.diverged > 0) parts.push(`${counts.diverged} with user edits`);
146
- if (counts["custom-files"] > 0) parts.push(`${counts["custom-files"]} with custom files`);
147
- return parts.join(", ");
148
- }
149
-
150
- // ---------------------------------------------------------------------------
151
- // Path-traversal allowlist (hardens the manifest reader boundary)
152
- // ---------------------------------------------------------------------------
153
-
154
- /**
155
- * Allowlist for managed-agent filenames.
156
- *
157
- * Hardens the manifest reader against crafted keys that would otherwise drive
158
- * `readFileSync` / `unlinkSync` to a path-traversed target. Required: the value
159
- * must be a single basename (no separators), must not contain `..` or NUL, must
160
- * not be absolute, and must end in `.md`.
161
- */
162
- function isManagedAgentName(name: string): boolean {
163
- if (typeof name !== "string" || name.length === 0) return false;
164
- if (name.includes("\0")) return false;
165
- if (name.includes("/") || name.includes("\\")) return false;
166
- if (name === "." || name === "..") return false;
167
- if (name.includes("..")) return false;
168
- if (isAbsolute(name)) return false;
169
- if (!name.endsWith(".md")) return false;
170
- return true;
171
- }
172
-
173
- /**
174
- * Resolve a managed-agent destination path under targetDir, asserting it stays
175
- * within targetDir. Defence-in-depth alongside `isManagedAgentName` — if a
176
- * future code path constructs a destPath without going through `readManifest`,
177
- * this still blocks the traversal.
178
- *
179
- * Returns `null` if the resolved path escapes `targetDir`.
180
- */
181
- function safeJoin(targetDir: string, name: string): string | null {
182
- const resolved = resolve(targetDir, name);
183
- const root = resolve(targetDir) + sep;
184
- if (!resolved.startsWith(root)) return null;
185
- return resolved;
186
- }
187
-
188
- // ---------------------------------------------------------------------------
189
- // Manifest
190
- // ---------------------------------------------------------------------------
191
-
192
- const MANIFEST_FILE = ".rpiv-managed.json";
193
-
194
- /** Filename → sha256 hex of the content we last installed. Empty string = unknown. */
195
- type Manifest = Record<string, string>;
196
-
197
- function sha256(buf: Buffer | string): string {
198
- return createHash("sha256").update(buf).digest("hex");
199
- }
200
-
201
- /**
202
- * Read the managed-file manifest (`Record<filename, sha256>`) from the target
203
- * directory. Any other shape (missing, corrupt JSON, non-object) reads as `{}`.
204
- *
205
- * Hardened against path-traversal: keys failing `isManagedAgentName` are dropped
206
- * silently. A subsequent `writeManifest` rewrites the on-disk manifest without
207
- * the rejected keys.
208
- *
209
- * Fail-soft: never throws.
210
- */
211
- function readManifest(targetDir: string): Manifest {
212
- const manifestPath = join(targetDir, MANIFEST_FILE);
213
- if (!existsSync(manifestPath)) return {};
214
- try {
215
- const raw = readFileSync(manifestPath, "utf-8");
216
- const parsed = JSON.parse(raw);
217
- if (isPlainObject(parsed)) {
218
- const out: Manifest = {};
219
- for (const [k, v] of Object.entries(parsed)) {
220
- if (typeof v === "string" && isManagedAgentName(k)) out[k] = v;
221
- }
222
- return out;
223
- }
224
- return {};
225
- } catch {
226
- return {};
227
- }
228
- }
229
-
230
- /**
231
- * Write the managed-file manifest to the target directory.
232
- * Pushes a `{ op: "manifest-write" }` SyncError on failure so consumers
233
- * (notifyAgentSyncDrift, /rpiv-update-agents) can surface it instead of
234
- * silently swallowing permission / disk-full errors.
235
- */
236
- function writeManifest(targetDir: string, manifest: Manifest, result: SyncResult): void {
237
- const manifestPath = join(targetDir, MANIFEST_FILE);
238
- try {
239
- const ordered: Manifest = {};
240
- for (const k of Object.keys(manifest).sort()) ordered[k] = manifest[k];
241
- const content = `${JSON.stringify(ordered, null, 2)}\n`;
242
- // Atomic write: tmp file in same dir + renameSync (POSIX same-filesystem guarantee).
243
- // Prevents write-write corruption under widened concurrency (global target).
244
- // Pid-suffixed so concurrent sessions don't unlink each other's in-flight tmp files
245
- // on the failure path (see catch's unlinkSync below).
246
- const tmpFile = join(targetDir, `${MANIFEST_FILE}.${process.pid}.tmp`);
247
- try {
248
- writeFileSync(tmpFile, content, "utf-8");
249
- renameSync(tmpFile, manifestPath);
250
- } catch (inner) {
251
- try {
252
- unlinkSync(tmpFile);
253
- } catch {
254
- /* ignore */
255
- }
256
- throw inner;
257
- }
258
- } catch (e) {
259
- result.errors.push({
260
- op: SYNC_OP.MANIFEST_WRITE,
261
- message: toErrorMessage(e),
262
- });
263
- }
264
- }
265
-
266
- // ---------------------------------------------------------------------------
267
- // Predicate consolidation
268
- // ---------------------------------------------------------------------------
269
-
270
- /**
271
- * Unified safety gate for destructive operations (update + remove): safe to
272
- * auto-apply only when the recorded hash matches the destination (we installed
273
- * those bytes and the user hasn't edited them). No recorded hash → gated.
274
- */
275
- export function isSafeDestructiveOp(opts: { knownHash: string; destHash: string }): boolean {
276
- const { knownHash, destHash } = opts;
277
- return knownHash !== "" && destHash === knownHash;
278
- }
279
-
280
- // ---------------------------------------------------------------------------
281
- // Agent Sync Engine — extracted helpers
282
- // ---------------------------------------------------------------------------
283
-
284
- /**
285
- * Enumerate source .md files from the bundled agents directory.
286
- * Returns null (with error pushed) on failure.
287
- */
288
- function enumerateSourceFiles(result: SyncResult): string[] | null {
289
- try {
290
- return readdirSync(BUNDLED_AGENTS_DIR).filter((f) => f.endsWith(".md"));
291
- } catch {
292
- result.errors.push({ op: SYNC_OP.READ_SRC, message: "Failed to read bundled agents directory" });
293
- return null;
294
- }
295
- }
296
-
297
- /**
298
- * Apply key-value updates to frontmatter lines.
299
- *
300
- * For each key in `keysToSet`, replaces the existing line if present
301
- * (within the frontmatter bounds), or inserts a new line before the
302
- * closing `---`. Returns the (possibly modified) lines array.
303
- *
304
- * The closing-fence index (`bounds.end`) is stable across in-place
305
- * replacements — only the value changes, not the line count — so the
306
- * insertion point remains correct without re-scanning.
307
- */
308
- function applyKeyUpdates(
309
- lines: string[],
310
- bounds: { start: number; end: number },
311
- keysToSet: { key: string; value: string }[],
312
- ): string[] {
313
- const result = [...lines];
314
- const insertLines: string[] = [];
315
-
316
- for (const { key, value } of keysToSet) {
317
- const prefix = `${key}: `;
318
- const existingIdx = result.findIndex((line, i) => i > 0 && i < bounds.end && line.startsWith(prefix));
319
- if (existingIdx !== -1) {
320
- result[existingIdx] = `${prefix}${value}`;
321
- } else {
322
- insertLines.push(`${prefix}${value}`);
323
- }
324
- }
325
-
326
- if (insertLines.length > 0) {
327
- result.splice(bounds.end, 0, ...insertLines);
328
- }
329
-
330
- return result;
331
- }
332
-
333
- /**
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.
347
- *
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.
351
- *
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.
358
- *
359
- * Exported so the idempotency invariant can be unit-tested directly:
360
- * `inject(inject(x)) === inject(x)` (see Verification Notes).
361
- */
362
- export function injectModelFrontmatter(
363
- content: string,
364
- agentFile: string,
365
- config: ModelsConfig,
366
- injection?: AgentInjectionContext,
367
- ): string {
368
- // Strip .md extension — source entries are filenames like "codebase-analyzer.md"
369
- // but models.json keys are agent names like "codebase-analyzer".
370
- const agentKey = agentFile.replace(/\.md$/, "");
371
- const override = getAgentModelConfig(config, agentKey);
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) {
376
- return content;
377
- }
378
-
379
- const lines = content.split("\n");
380
- const bounds = parseFrontmatterBounds(lines);
381
- if (!bounds) return content;
382
-
383
- const keysToSet: { key: string; value: string }[] = [];
384
- // (post-slash-canonical migration): models.json values are byte-equal to
385
- // the agent frontmatter form (both `provider/modelId`). No translation step
386
- // — re-injecting produces identical bytes by construction; the idempotency
387
- // invariant at injectModelFrontmatter's JSDoc strengthens from "deterministic
388
- // translation" to "byte pass-through".
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
- }
426
-
427
- const updated = applyKeyUpdates(lines, bounds, keysToSet);
428
- return updated.join("\n");
429
- }
430
-
431
- /**
432
- * Process each source file — copy new, record unchanged, update or gate.
433
- * Returns the new manifest built from source entries.
434
- */
435
- function processSourceEntries(
436
- sourceEntries: string[],
437
- targetDir: string,
438
- manifest: Manifest,
439
- apply: boolean,
440
- result: SyncResult,
441
- ): Manifest {
442
- const newManifest: Manifest = {};
443
-
444
- // Hoisted above the loop: loadModelsConfig() reads+parses JSON, so calling it
445
- // per-entry would re-read the file once per agent (~15×) every session_start.
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
- };
455
-
456
- for (const entry of sourceEntries) {
457
- const src = join(BUNDLED_AGENTS_DIR, entry);
458
- const dest = safeJoin(targetDir, entry);
459
- const knownHash = manifest[entry] ?? "";
460
- if (dest === null) {
461
- result.errors.push({ file: entry, op: SYNC_OP.COPY, message: "rejected unsafe path" });
462
- newManifest[entry] = knownHash;
463
- continue;
464
- }
465
-
466
- let srcContent: Buffer;
467
- try {
468
- srcContent = readFileSync(src);
469
- } catch (e) {
470
- result.errors.push({ file: entry, op: SYNC_OP.READ_SRC, message: toErrorMessage(e) });
471
- newManifest[entry] = knownHash;
472
- continue;
473
- }
474
- // Inject configured model/thinking frontmatter BEFORE hashing so the
475
- // manifest hash matches what actually lands on disk (hash-after-transform).
476
- // injectModelFrontmatter strips .md from entry for config lookup and is a
477
- // no-op when no override is configured.
478
- const injected = injectModelFrontmatter(srcContent.toString("utf-8"), entry, config, injection);
479
- const srcHash = sha256(injected);
480
-
481
- if (!existsSync(dest)) {
482
- try {
483
- writeFileSync(dest, injected, "utf-8");
484
- result.added.push(entry);
485
- newManifest[entry] = srcHash;
486
- } catch (e) {
487
- result.errors.push({ file: entry, op: SYNC_OP.COPY, message: toErrorMessage(e) });
488
- newManifest[entry] = knownHash;
489
- }
490
- continue;
491
- }
492
-
493
- let destContent: Buffer;
494
- try {
495
- destContent = readFileSync(dest);
496
- } catch (e) {
497
- result.errors.push({ file: entry, op: SYNC_OP.READ_DEST, message: toErrorMessage(e) });
498
- newManifest[entry] = knownHash;
499
- continue;
500
- }
501
- const destHash = sha256(destContent);
502
-
503
- if (srcHash === destHash) {
504
- result.unchanged.push(entry);
505
- newManifest[entry] = srcHash;
506
- continue;
507
- }
508
-
509
- if (apply || isSafeDestructiveOp({ knownHash, destHash })) {
510
- try {
511
- writeFileSync(dest, injected, "utf-8");
512
- result.updated.push(entry);
513
- newManifest[entry] = srcHash;
514
- } catch (e) {
515
- result.errors.push({ file: entry, op: SYNC_OP.COPY, message: toErrorMessage(e) });
516
- newManifest[entry] = knownHash;
517
- }
518
- } else {
519
- result.pendingUpdate.push(entry);
520
- newManifest[entry] = knownHash;
521
- }
522
- }
523
-
524
- return newManifest;
525
- }
526
-
527
- /**
528
- * Classify stale entries (in manifest but absent from source).
529
- * Returns entries to unlink; pushes pendingRemove for gated entries.
530
- */
531
- function classifyStaleEntries(
532
- manifest: Manifest,
533
- sourceNames: Set<string>,
534
- targetDir: string,
535
- apply: boolean,
536
- newManifest: Manifest,
537
- result: SyncResult,
538
- ): { name: string; destPath: string }[] {
539
- const toUnlink: { name: string; destPath: string }[] = [];
540
-
541
- for (const name of Object.keys(manifest)) {
542
- if (sourceNames.has(name)) continue;
543
-
544
- const knownHash = manifest[name];
545
- const destPath = safeJoin(targetDir, name);
546
- if (destPath === null) {
547
- result.errors.push({ file: name, op: SYNC_OP.REMOVE, message: "rejected unsafe path" });
548
- continue;
549
- }
550
- if (!existsSync(destPath)) {
551
- // Vanished tracked file: tidy from manifest AND surface as removed.
552
- result.removed.push(name);
553
- continue;
554
- }
555
-
556
- let destContent: Buffer;
557
- try {
558
- destContent = readFileSync(destPath);
559
- } catch (e) {
560
- result.errors.push({ file: name, op: SYNC_OP.READ_DEST, message: toErrorMessage(e) });
561
- newManifest[name] = knownHash;
562
- continue;
563
- }
564
- const destHash = sha256(destContent);
565
-
566
- if (apply || isSafeDestructiveOp({ knownHash, destHash })) {
567
- toUnlink.push({ name, destPath });
568
- } else {
569
- result.pendingRemove.push(name);
570
- newManifest[name] = knownHash;
571
- }
572
- }
573
-
574
- return toUnlink;
575
- }
576
-
577
- /**
578
- * Commit unlink operations after the manifest is durable.
579
- * Re-introduces failed entries into newManifest so a future run retries.
580
- */
581
- function commitStaleUnlinks(
582
- toUnlink: { name: string; destPath: string }[],
583
- manifest: Manifest,
584
- newManifest: Manifest,
585
- targetDir: string,
586
- result: SyncResult,
587
- ): void {
588
- for (const { name, destPath } of toUnlink) {
589
- try {
590
- unlinkSync(destPath);
591
- result.removed.push(name);
592
- } catch (e) {
593
- result.errors.push({ file: name, op: SYNC_OP.REMOVE, message: toErrorMessage(e) });
594
- // Re-introduce the entry into the manifest on disk so a future run retries.
595
- newManifest[name] = manifest[name];
596
- }
597
- }
598
- if (result.errors.some((e) => e.op === SYNC_OP.REMOVE)) {
599
- writeManifest(targetDir, newManifest, result);
600
- }
601
- }
602
-
603
- // ---------------------------------------------------------------------------
604
- // Agent Sync Engine — orchestrator
605
- // ---------------------------------------------------------------------------
606
-
607
- /**
608
- * Synchronize bundled agents from <PACKAGE_ROOT>/agents/ into ~/.pi/agent/agents/.
609
- *
610
- * Resolution policy (apply=false, session_start):
611
- * - New source files → always copied.
612
- * - Existing files, dest === src → unchanged, hash recorded.
613
- * - Existing files, dest ≠ src:
614
- * - dest === recorded hash → auto-update (smart gate).
615
- * - otherwise (no recorded hash, or dest differs from it) → pendingUpdate
616
- * (gated; respects user edits).
617
- * - Stale managed files: same decision applied to removal.
618
- *
619
- * apply=true (/rpiv-update-agents): force adds/updates/removes regardless of
620
- * recorded hash (manual override; user-edited files are overwritten).
621
- *
622
- * Atomicity: writeManifest runs BEFORE the destructive unlink loop so a crash
623
- * mid-sync leaves the manifest claiming files-already-removed (next run picks
624
- * those up via the vanish branch and reports them in result.removed).
625
- *
626
- * Never throws — errors are collected in `result.errors`.
627
- */
628
- export function syncBundledAgents(apply: boolean): SyncResult {
629
- const result = emptySyncResult();
630
-
631
- if (!existsSync(BUNDLED_AGENTS_DIR)) {
632
- return result;
633
- }
634
-
635
- const targetDir = join(getAgentDir(), "agents");
636
- try {
637
- mkdirSync(targetDir, { recursive: true });
638
- } catch (e) {
639
- result.errors.push({
640
- op: SYNC_OP.MKDIR,
641
- message: toErrorMessage(e, "Failed to create target directory"),
642
- });
643
- return result;
644
- }
645
-
646
- const sourceEntries = enumerateSourceFiles(result);
647
- if (sourceEntries === null) return result;
648
-
649
- const sourceNames = new Set(sourceEntries);
650
- const manifest = readManifest(targetDir);
651
-
652
- const newManifest = processSourceEntries(sourceEntries, targetDir, manifest, apply, result);
653
-
654
- const toUnlink = classifyStaleEntries(manifest, sourceNames, targetDir, apply, newManifest, result);
655
-
656
- // Persist the manifest before destructive ops.
657
- writeManifest(targetDir, newManifest, result);
658
-
659
- // Commit unlinks after the manifest is durable.
660
- commitStaleUnlinks(toUnlink, manifest, newManifest, targetDir, result);
661
-
662
- return result;
663
- }
664
-
665
- /**
666
- * Clean up per-cwd agent directories from pre-global-sync installs.
667
- *
668
- * Conservative all-or-nothing gate: removes `<cwd>/.pi/agents/` only when:
669
- * 1. A manifest exists (we installed these files)
670
- * 2. Every managed file matches current source content
671
- * 3. No non-managed files exist in the directory
672
- *
673
- * If any check fails, the directory is left intact. Never throws — errors
674
- * are collected in the CleanupResult.
675
- */
676
- export function cleanupPerCwdAgents(cwd: string): CleanupResult {
677
- const result = emptyCleanupResult();
678
- const perCwdDir = join(cwd, ".pi", "agents");
679
-
680
- if (!existsSync(perCwdDir)) return result;
681
- const manifest = readManifest(perCwdDir);
682
- if (Object.keys(manifest).length === 0) {
683
- // No manifest (never synced by us, or hand-managed)
684
- result.skipped.push({ dir: perCwdDir, reason: CLEANUP_SKIP_REASON.UNMANAGED });
685
- return result;
686
- }
687
-
688
- // Verify all managed files match current source content.
689
- // Hoisted config read (same reasoning as processSourceEntries): one JSON
690
- // read for the whole cleanup pass, not one per managed file.
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
- };
698
- for (const [name] of Object.entries(manifest)) {
699
- const srcPath = safeJoin(BUNDLED_AGENTS_DIR, name);
700
- const destPath = safeJoin(perCwdDir, name);
701
- if (srcPath === null || destPath === null) {
702
- // Crafted manifest key would escape allowlist — treat as unmanaged.
703
- result.skipped.push({ dir: perCwdDir, reason: CLEANUP_SKIP_REASON.UNMANAGED });
704
- return result;
705
- }
706
-
707
- let srcContent: Buffer;
708
- try {
709
- srcContent = readFileSync(srcPath);
710
- } catch {
711
- // Source file no longer exists — can't verify against bundle, treat as diverged.
712
- result.skipped.push({ dir: perCwdDir, reason: CLEANUP_SKIP_REASON.DIVERGED });
713
- return result;
714
- }
715
-
716
- if (!existsSync(destPath)) {
717
- // Managed file missing from disk — user deleted it, treat as diverged.
718
- result.skipped.push({ dir: perCwdDir, reason: CLEANUP_SKIP_REASON.DIVERGED });
719
- return result;
720
- }
721
-
722
- let destContent: Buffer;
723
- try {
724
- destContent = readFileSync(destPath);
725
- } catch (e) {
726
- // Hard failure — surface as error only (do not double-count in skipped).
727
- result.errors.push({ op: SYNC_OP.READ_DEST, message: toErrorMessage(e) });
728
- return result;
729
- }
730
-
731
- // Compare against the injected form — the dest holds injected content,
732
- // so comparing raw source would falsely flag every configured agent
733
- // as diverged. injectModelFrontmatter strips .md from name for lookup.
734
- const cleanupInjected = injectModelFrontmatter(
735
- srcContent.toString("utf-8"),
736
- name,
737
- cleanupConfig,
738
- cleanupInjection,
739
- );
740
- if (sha256(destContent) !== sha256(cleanupInjected)) {
741
- // User edited this file — conservative gate.
742
- result.skipped.push({ dir: perCwdDir, reason: CLEANUP_SKIP_REASON.DIVERGED });
743
- return result;
744
- }
745
- }
746
-
747
- // Check for non-managed files
748
- try {
749
- const allFiles = readdirSync(perCwdDir);
750
- const managedNames = new Set(Object.keys(manifest));
751
- for (const f of allFiles) {
752
- if (!managedNames.has(f) && f !== MANIFEST_FILE) {
753
- // Non-managed file present (user custom agent or other content)
754
- result.skipped.push({ dir: perCwdDir, reason: CLEANUP_SKIP_REASON.CUSTOM_FILES });
755
- return result;
756
- }
757
- }
758
- } catch (e) {
759
- // Hard failure — surface as error only (do not double-count in skipped).
760
- result.errors.push({ op: SYNC_OP.READ_DEST, message: toErrorMessage(e) });
761
- return result;
762
- }
763
-
764
- // Happy path: all checks passed, safe to remove
765
- try {
766
- rmSync(perCwdDir, { recursive: true, force: true });
767
- result.cleanedUp.push(perCwdDir);
768
- } catch (e) {
769
- // Hard failure — surface as error only (do not double-count in skipped).
770
- result.errors.push({ op: SYNC_OP.REMOVE, message: toErrorMessage(e) });
771
- }
772
-
773
- return result;
774
- }
2
+ * Agent auto-copy subsystem — public barrel.
3
+ *
4
+ * Copies bundled agents into ~/.pi/agent/agents/. Pure utility. No
5
+ * ExtensionAPI interactions.
6
+ *
7
+ * The implementation lives in the agents-*.ts family, layered so each module
8
+ * imports only the layers above it:
9
+ * 1. agents-types.ts — SYNC_OP / CLEANUP_SKIP_REASON pairs, result
10
+ * shapes, summarizeCleanupSkips (zero imports)
11
+ * 2. agents-allowlist.ts — isManagedAgentName / safeJoin path-traversal gate
12
+ * 3. agents-manifest.ts — sha256 manifest read/write, atomic tmp+rename
13
+ * (owns the inter-process race caveat)
14
+ * 4. agents-inject.ts — injectModelFrontmatter pure transform
15
+ * 5. agents-sync.ts — syncBundledAgents / cleanupPerCwdAgents /
16
+ * isSafeDestructiveOp engine
17
+ *
18
+ * This barrel re-exports exactly the pre-split public surface — col-0
19
+ * re-export statements keep every child on the extension's static import
20
+ * graph. Internal layer symbols (safeJoin, readManifest, writeManifest,
21
+ * sha256, the result factories, …) are intentionally NOT re-exported.
22
+ * Consumers import "./agents.js" unchanged.
23
+ */
24
+
25
+ export type { AgentInjectionContext } from "./agents-inject.js";
26
+ export { injectModelFrontmatter } from "./agents-inject.js";
27
+ export { cleanupPerCwdAgents, isSafeDestructiveOp, syncBundledAgents } from "./agents-sync.js";
28
+ export type {
29
+ CleanupResult,
30
+ CleanupSkip,
31
+ CleanupSkipReason,
32
+ SyncError,
33
+ SyncOp,
34
+ SyncResult,
35
+ } from "./agents-types.js";
36
+ export { CLEANUP_SKIP_REASON, SYNC_OP, summarizeCleanupSkips } from "./agents-types.js";