@juicesharp/rpiv-pi 2.13.3 → 2.13.5

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
@@ -0,0 +1,405 @@
1
+ /**
2
+ * Agent sync — the engine.
3
+ *
4
+ * Layer 5 of the agents-*.ts family (top of the stack): orchestrates
5
+ * copy/update/remove of bundled agents into ~/.pi/agent/agents/ plus the
6
+ * legacy per-cwd cleanup. Imports only the layers above (agents-types,
7
+ * agents-allowlist, agents-manifest, agents-inject) and the local utility
8
+ * modules. Pure utility: no ExtensionAPI interactions.
9
+ */
10
+
11
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
12
+ import { join } from "node:path";
13
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
14
+ import { installedExtensionNames } from "./agent-enablement.js";
15
+ import { safeJoin } from "./agents-allowlist.js";
16
+ import { type AgentInjectionContext, injectModelFrontmatter } from "./agents-inject.js";
17
+ import { MANIFEST_FILE, type Manifest, readManifest, sha256, writeManifest } from "./agents-manifest.js";
18
+ import {
19
+ CLEANUP_SKIP_REASON,
20
+ type CleanupResult,
21
+ emptyCleanupResult,
22
+ emptySyncResult,
23
+ SYNC_OP,
24
+ type SyncResult,
25
+ } from "./agents-types.js";
26
+ import { loadModelsConfig } from "./models-config.js";
27
+ import { findInstalledSiblings } from "./package-checks.js";
28
+ import { BUNDLED_AGENTS_DIR } from "./paths.js";
29
+ import { toErrorMessage } from "./utils.js";
30
+
31
+ // ---------------------------------------------------------------------------
32
+ // Predicate consolidation
33
+ // ---------------------------------------------------------------------------
34
+
35
+ /**
36
+ * Unified safety gate for destructive operations (update + remove): safe to
37
+ * auto-apply only when the recorded hash matches the destination (we installed
38
+ * those bytes and the user hasn't edited them). No recorded hash → gated.
39
+ */
40
+ export function isSafeDestructiveOp(opts: { knownHash: string; destHash: string }): boolean {
41
+ const { knownHash, destHash } = opts;
42
+ return knownHash !== "" && destHash === knownHash;
43
+ }
44
+
45
+ // ---------------------------------------------------------------------------
46
+ // Agent Sync Engine — extracted helpers
47
+ // ---------------------------------------------------------------------------
48
+
49
+ /**
50
+ * Enumerate source .md files from the bundled agents directory.
51
+ * Returns null (with error pushed) on failure.
52
+ */
53
+ function enumerateSourceFiles(result: SyncResult): string[] | null {
54
+ try {
55
+ return readdirSync(BUNDLED_AGENTS_DIR).filter((f) => f.endsWith(".md"));
56
+ } catch {
57
+ result.errors.push({ op: SYNC_OP.READ_SRC, message: "Failed to read bundled agents directory" });
58
+ return null;
59
+ }
60
+ }
61
+
62
+ /**
63
+ * Process each source file — copy new, record unchanged, update or gate.
64
+ * Returns the new manifest built from source entries.
65
+ */
66
+ function processSourceEntries(
67
+ sourceEntries: string[],
68
+ targetDir: string,
69
+ manifest: Manifest,
70
+ apply: boolean,
71
+ result: SyncResult,
72
+ ): Manifest {
73
+ const newManifest: Manifest = {};
74
+
75
+ // Hoisted above the loop: loadModelsConfig() reads+parses JSON, so calling it
76
+ // per-entry would re-read the file once per agent (~15×) every session_start.
77
+ const config = loadModelsConfig();
78
+ // One settings read per sync pass for the enablement gate. The SAME
79
+ // context must flow into every injectModelFrontmatter call in this pass —
80
+ // the manifest records hash-after-transform, so a gate that flipped
81
+ // mid-pass would tear the recorded hashes and falsely flag agents
82
+ // diverged.
83
+ const injection: AgentInjectionContext = {
84
+ installedExtensions: installedExtensionNames(findInstalledSiblings().map((s) => s.pkg)),
85
+ };
86
+
87
+ for (const entry of sourceEntries) {
88
+ const src = join(BUNDLED_AGENTS_DIR, entry);
89
+ const dest = safeJoin(targetDir, entry);
90
+ const knownHash = manifest[entry] ?? "";
91
+ if (dest === null) {
92
+ result.errors.push({ file: entry, op: SYNC_OP.COPY, message: "rejected unsafe path" });
93
+ newManifest[entry] = knownHash;
94
+ continue;
95
+ }
96
+
97
+ let srcContent: Buffer;
98
+ try {
99
+ srcContent = readFileSync(src);
100
+ } catch (e) {
101
+ result.errors.push({ file: entry, op: SYNC_OP.READ_SRC, message: toErrorMessage(e) });
102
+ newManifest[entry] = knownHash;
103
+ continue;
104
+ }
105
+ // Inject configured model/thinking frontmatter BEFORE hashing so the
106
+ // manifest hash matches what actually lands on disk (hash-after-transform).
107
+ // injectModelFrontmatter strips .md from entry for config lookup and is a
108
+ // no-op when no override is configured.
109
+ const injected = injectModelFrontmatter(srcContent.toString("utf-8"), entry, config, injection);
110
+ const srcHash = sha256(injected);
111
+
112
+ if (!existsSync(dest)) {
113
+ try {
114
+ writeFileSync(dest, injected, "utf-8");
115
+ result.added.push(entry);
116
+ newManifest[entry] = srcHash;
117
+ } catch (e) {
118
+ result.errors.push({ file: entry, op: SYNC_OP.COPY, message: toErrorMessage(e) });
119
+ newManifest[entry] = knownHash;
120
+ }
121
+ continue;
122
+ }
123
+
124
+ let destContent: Buffer;
125
+ try {
126
+ destContent = readFileSync(dest);
127
+ } catch (e) {
128
+ result.errors.push({ file: entry, op: SYNC_OP.READ_DEST, message: toErrorMessage(e) });
129
+ newManifest[entry] = knownHash;
130
+ continue;
131
+ }
132
+ const destHash = sha256(destContent);
133
+
134
+ if (srcHash === destHash) {
135
+ result.unchanged.push(entry);
136
+ newManifest[entry] = srcHash;
137
+ continue;
138
+ }
139
+
140
+ if (apply || isSafeDestructiveOp({ knownHash, destHash })) {
141
+ try {
142
+ writeFileSync(dest, injected, "utf-8");
143
+ result.updated.push(entry);
144
+ newManifest[entry] = srcHash;
145
+ } catch (e) {
146
+ result.errors.push({ file: entry, op: SYNC_OP.COPY, message: toErrorMessage(e) });
147
+ newManifest[entry] = knownHash;
148
+ }
149
+ } else {
150
+ result.pendingUpdate.push(entry);
151
+ newManifest[entry] = knownHash;
152
+ }
153
+ }
154
+
155
+ return newManifest;
156
+ }
157
+
158
+ /**
159
+ * Classify stale entries (in manifest but absent from source).
160
+ * Returns entries to unlink; pushes pendingRemove for gated entries.
161
+ */
162
+ function classifyStaleEntries(
163
+ manifest: Manifest,
164
+ sourceNames: Set<string>,
165
+ targetDir: string,
166
+ apply: boolean,
167
+ newManifest: Manifest,
168
+ result: SyncResult,
169
+ ): { name: string; destPath: string }[] {
170
+ const toUnlink: { name: string; destPath: string }[] = [];
171
+
172
+ for (const name of Object.keys(manifest)) {
173
+ if (sourceNames.has(name)) continue;
174
+
175
+ const knownHash = manifest[name];
176
+ const destPath = safeJoin(targetDir, name);
177
+ if (destPath === null) {
178
+ result.errors.push({ file: name, op: SYNC_OP.REMOVE, message: "rejected unsafe path" });
179
+ continue;
180
+ }
181
+ if (!existsSync(destPath)) {
182
+ // Vanished tracked file: tidy from manifest AND surface as removed.
183
+ result.removed.push(name);
184
+ continue;
185
+ }
186
+
187
+ let destContent: Buffer;
188
+ try {
189
+ destContent = readFileSync(destPath);
190
+ } catch (e) {
191
+ result.errors.push({ file: name, op: SYNC_OP.READ_DEST, message: toErrorMessage(e) });
192
+ newManifest[name] = knownHash;
193
+ continue;
194
+ }
195
+ const destHash = sha256(destContent);
196
+
197
+ if (apply || isSafeDestructiveOp({ knownHash, destHash })) {
198
+ toUnlink.push({ name, destPath });
199
+ } else {
200
+ result.pendingRemove.push(name);
201
+ newManifest[name] = knownHash;
202
+ }
203
+ }
204
+
205
+ return toUnlink;
206
+ }
207
+
208
+ /**
209
+ * Commit unlink operations after the manifest is durable.
210
+ * Re-introduces failed entries into newManifest so a future run retries.
211
+ */
212
+ function commitStaleUnlinks(
213
+ toUnlink: { name: string; destPath: string }[],
214
+ manifest: Manifest,
215
+ newManifest: Manifest,
216
+ targetDir: string,
217
+ result: SyncResult,
218
+ ): void {
219
+ for (const { name, destPath } of toUnlink) {
220
+ try {
221
+ unlinkSync(destPath);
222
+ result.removed.push(name);
223
+ } catch (e) {
224
+ result.errors.push({ file: name, op: SYNC_OP.REMOVE, message: toErrorMessage(e) });
225
+ // Re-introduce the entry into the manifest on disk so a future run retries.
226
+ newManifest[name] = manifest[name];
227
+ }
228
+ }
229
+ if (result.errors.some((e) => e.op === SYNC_OP.REMOVE)) {
230
+ writeManifest(targetDir, newManifest, result);
231
+ }
232
+ }
233
+
234
+ // ---------------------------------------------------------------------------
235
+ // Agent Sync Engine — orchestrator
236
+ // ---------------------------------------------------------------------------
237
+
238
+ /**
239
+ * Synchronize bundled agents from <PACKAGE_ROOT>/agents/ into ~/.pi/agent/agents/.
240
+ *
241
+ * Resolution policy (apply=false, session_start):
242
+ * - New source files → always copied.
243
+ * - Existing files, dest === src → unchanged, hash recorded.
244
+ * - Existing files, dest ≠ src:
245
+ * - dest === recorded hash → auto-update (smart gate).
246
+ * - otherwise (no recorded hash, or dest differs from it) → pendingUpdate
247
+ * (gated; respects user edits).
248
+ * - Stale managed files: same decision applied to removal.
249
+ *
250
+ * apply=true (/rpiv-update-agents): force adds/updates/removes regardless of
251
+ * recorded hash (manual override; user-edited files are overwritten).
252
+ *
253
+ * Atomicity: writeManifest runs BEFORE the destructive unlink loop so a crash
254
+ * mid-sync leaves the manifest claiming files-already-removed (next run picks
255
+ * those up via the vanish branch and reports them in result.removed).
256
+ *
257
+ * Never throws — errors are collected in `result.errors`.
258
+ */
259
+ export function syncBundledAgents(apply: boolean): SyncResult {
260
+ const result = emptySyncResult();
261
+
262
+ if (!existsSync(BUNDLED_AGENTS_DIR)) {
263
+ return result;
264
+ }
265
+
266
+ const targetDir = join(getAgentDir(), "agents");
267
+ try {
268
+ mkdirSync(targetDir, { recursive: true });
269
+ } catch (e) {
270
+ result.errors.push({
271
+ op: SYNC_OP.MKDIR,
272
+ message: toErrorMessage(e, "Failed to create target directory"),
273
+ });
274
+ return result;
275
+ }
276
+
277
+ const sourceEntries = enumerateSourceFiles(result);
278
+ if (sourceEntries === null) return result;
279
+
280
+ const sourceNames = new Set(sourceEntries);
281
+ const manifest = readManifest(targetDir);
282
+
283
+ const newManifest = processSourceEntries(sourceEntries, targetDir, manifest, apply, result);
284
+
285
+ const toUnlink = classifyStaleEntries(manifest, sourceNames, targetDir, apply, newManifest, result);
286
+
287
+ // Persist the manifest before destructive ops.
288
+ writeManifest(targetDir, newManifest, result);
289
+
290
+ // Commit unlinks after the manifest is durable.
291
+ commitStaleUnlinks(toUnlink, manifest, newManifest, targetDir, result);
292
+
293
+ return result;
294
+ }
295
+
296
+ /**
297
+ * Clean up per-cwd agent directories from pre-global-sync installs.
298
+ *
299
+ * Conservative all-or-nothing gate: removes `<cwd>/.pi/agents/` only when:
300
+ * 1. A manifest exists (we installed these files)
301
+ * 2. Every managed file matches current source content
302
+ * 3. No non-managed files exist in the directory
303
+ *
304
+ * If any check fails, the directory is left intact. Never throws — errors
305
+ * are collected in the CleanupResult.
306
+ */
307
+ export function cleanupPerCwdAgents(cwd: string): CleanupResult {
308
+ const result = emptyCleanupResult();
309
+ const perCwdDir = join(cwd, ".pi", "agents");
310
+
311
+ if (!existsSync(perCwdDir)) return result;
312
+ const manifest = readManifest(perCwdDir);
313
+ if (Object.keys(manifest).length === 0) {
314
+ // No manifest (never synced by us, or hand-managed)
315
+ result.skipped.push({ dir: perCwdDir, reason: CLEANUP_SKIP_REASON.UNMANAGED });
316
+ return result;
317
+ }
318
+
319
+ // Verify all managed files match current source content.
320
+ // Hoisted config read (same reasoning as processSourceEntries): one JSON
321
+ // read for the whole cleanup pass, not one per managed file.
322
+ const cleanupConfig = loadModelsConfig();
323
+ // Same shared-gate rule as processSourceEntries: the legacy-dir comparison
324
+ // must use one settings read for the whole pass — the identical gate a
325
+ // sync pass with the same settings would have used.
326
+ const cleanupInjection: AgentInjectionContext = {
327
+ installedExtensions: installedExtensionNames(findInstalledSiblings().map((s) => s.pkg)),
328
+ };
329
+ for (const [name] of Object.entries(manifest)) {
330
+ const srcPath = safeJoin(BUNDLED_AGENTS_DIR, name);
331
+ const destPath = safeJoin(perCwdDir, name);
332
+ if (srcPath === null || destPath === null) {
333
+ // Crafted manifest key would escape allowlist — treat as unmanaged.
334
+ result.skipped.push({ dir: perCwdDir, reason: CLEANUP_SKIP_REASON.UNMANAGED });
335
+ return result;
336
+ }
337
+
338
+ let srcContent: Buffer;
339
+ try {
340
+ srcContent = readFileSync(srcPath);
341
+ } catch {
342
+ // Source file no longer exists — can't verify against bundle, treat as diverged.
343
+ result.skipped.push({ dir: perCwdDir, reason: CLEANUP_SKIP_REASON.DIVERGED });
344
+ return result;
345
+ }
346
+
347
+ if (!existsSync(destPath)) {
348
+ // Managed file missing from disk — user deleted it, treat as diverged.
349
+ result.skipped.push({ dir: perCwdDir, reason: CLEANUP_SKIP_REASON.DIVERGED });
350
+ return result;
351
+ }
352
+
353
+ let destContent: Buffer;
354
+ try {
355
+ destContent = readFileSync(destPath);
356
+ } catch (e) {
357
+ // Hard failure — surface as error only (do not double-count in skipped).
358
+ result.errors.push({ op: SYNC_OP.READ_DEST, message: toErrorMessage(e) });
359
+ return result;
360
+ }
361
+
362
+ // Compare against the injected form — the dest holds injected content,
363
+ // so comparing raw source would falsely flag every configured agent
364
+ // as diverged. injectModelFrontmatter strips .md from name for lookup.
365
+ const cleanupInjected = injectModelFrontmatter(
366
+ srcContent.toString("utf-8"),
367
+ name,
368
+ cleanupConfig,
369
+ cleanupInjection,
370
+ );
371
+ if (sha256(destContent) !== sha256(cleanupInjected)) {
372
+ // User edited this file — conservative gate.
373
+ result.skipped.push({ dir: perCwdDir, reason: CLEANUP_SKIP_REASON.DIVERGED });
374
+ return result;
375
+ }
376
+ }
377
+
378
+ // Check for non-managed files
379
+ try {
380
+ const allFiles = readdirSync(perCwdDir);
381
+ const managedNames = new Set(Object.keys(manifest));
382
+ for (const f of allFiles) {
383
+ if (!managedNames.has(f) && f !== MANIFEST_FILE) {
384
+ // Non-managed file present (user custom agent or other content)
385
+ result.skipped.push({ dir: perCwdDir, reason: CLEANUP_SKIP_REASON.CUSTOM_FILES });
386
+ return result;
387
+ }
388
+ }
389
+ } catch (e) {
390
+ // Hard failure — surface as error only (do not double-count in skipped).
391
+ result.errors.push({ op: SYNC_OP.READ_DEST, message: toErrorMessage(e) });
392
+ return result;
393
+ }
394
+
395
+ // Happy path: all checks passed, safe to remove
396
+ try {
397
+ rmSync(perCwdDir, { recursive: true, force: true });
398
+ result.cleanedUp.push(perCwdDir);
399
+ } catch (e) {
400
+ // Hard failure — surface as error only (do not double-count in skipped).
401
+ result.errors.push({ op: SYNC_OP.REMOVE, message: toErrorMessage(e) });
402
+ }
403
+
404
+ return result;
405
+ }
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Agent sync — shared result types and summary helpers.
3
+ *
4
+ * Layer 1 of the agents-*.ts family: zero imports. The layers above
5
+ * (agents-allowlist, agents-manifest, agents-inject, agents-sync) build on
6
+ * these shapes; agents.ts is the public barrel over the family.
7
+ */
8
+
9
+ // ---------------------------------------------------------------------------
10
+ // Types
11
+ // ---------------------------------------------------------------------------
12
+
13
+ /** Named constants for sync operation identifiers. */
14
+ export const SYNC_OP = {
15
+ READ_SRC: "read-src",
16
+ READ_DEST: "read-dest",
17
+ COPY: "copy",
18
+ REMOVE: "remove",
19
+ MANIFEST_WRITE: "manifest-write",
20
+ MKDIR: "mkdir",
21
+ } as const;
22
+
23
+ /** String union derived from SYNC_OP. */
24
+ export type SyncOp = (typeof SYNC_OP)[keyof typeof SYNC_OP];
25
+
26
+ export interface SyncError {
27
+ file?: string;
28
+ op: SyncOp;
29
+ message: string;
30
+ }
31
+
32
+ export interface SyncResult {
33
+ /** New files copied (present in source, absent from destination). */
34
+ added: string[];
35
+ /** Existing managed files overwritten with updated source content. */
36
+ updated: string[];
37
+ /** Managed files whose destination content matches source exactly. */
38
+ unchanged: string[];
39
+ /** Stale managed files removed (present in manifest but absent from source). */
40
+ removed: string[];
41
+ /** Managed files with different destination content (detected but not applied). */
42
+ pendingUpdate: string[];
43
+ /** Managed files no longer in source (detected but not removed). */
44
+ pendingRemove: string[];
45
+ /** Per-file errors collected during sync. */
46
+ errors: SyncError[];
47
+ }
48
+
49
+ /** Create an empty SyncResult with all arrays initialized. */
50
+ export function emptySyncResult(): SyncResult {
51
+ return {
52
+ added: [],
53
+ updated: [],
54
+ unchanged: [],
55
+ removed: [],
56
+ pendingUpdate: [],
57
+ pendingRemove: [],
58
+ errors: [],
59
+ };
60
+ }
61
+
62
+ /** Discriminant for why a per-cwd directory was left intact. */
63
+ export const CLEANUP_SKIP_REASON = {
64
+ /** No manifest present — directory was never installed by rpiv (hand-managed). */
65
+ UNMANAGED: "unmanaged",
66
+ /** Managed file content diverges from current bundle source (user edit, deletion, or source change). */
67
+ DIVERGED: "diverged",
68
+ /** Directory contains non-managed files (user added custom agents). */
69
+ CUSTOM_FILES: "custom-files",
70
+ } as const;
71
+
72
+ export type CleanupSkipReason = (typeof CLEANUP_SKIP_REASON)[keyof typeof CLEANUP_SKIP_REASON];
73
+
74
+ export interface CleanupSkip {
75
+ dir: string;
76
+ reason: CleanupSkipReason;
77
+ }
78
+
79
+ export interface CleanupResult {
80
+ /** Per-cwd agent directories successfully removed (all managed files matched source). */
81
+ cleanedUp: string[];
82
+ /** Directories preserved with discriminated reason — see CLEANUP_SKIP_REASON. */
83
+ skipped: CleanupSkip[];
84
+ /** Per-file errors collected during cleanup. */
85
+ errors: SyncError[];
86
+ }
87
+
88
+ /** Create an empty CleanupResult with all arrays initialized. */
89
+ export function emptyCleanupResult(): CleanupResult {
90
+ return {
91
+ cleanedUp: [],
92
+ skipped: [],
93
+ errors: [],
94
+ };
95
+ }
96
+
97
+ /**
98
+ * Format skip counts as a comma-joined parts list ("N edited, M with custom files").
99
+ * Shared by session_start notifyCleanup and /rpiv-update-agents handler so the
100
+ * two consumer surfaces describe preserved directories identically.
101
+ */
102
+ export function summarizeCleanupSkips(skipped: CleanupSkip[]): string {
103
+ if (skipped.length === 0) return "";
104
+ const counts: Record<CleanupSkipReason, number> = {
105
+ unmanaged: 0,
106
+ diverged: 0,
107
+ "custom-files": 0,
108
+ };
109
+ for (const s of skipped) counts[s.reason]++;
110
+ const parts: string[] = [];
111
+ if (counts.unmanaged > 0) parts.push(`${counts.unmanaged} unmanaged`);
112
+ if (counts.diverged > 0) parts.push(`${counts.diverged} with user edits`);
113
+ if (counts["custom-files"] > 0) parts.push(`${counts["custom-files"]} with custom files`);
114
+ return parts.join(", ");
115
+ }