peaks-loop-mut 0.1.51 → 0.1.53

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 (43) hide show
  1. package/dist/index.d.ts +1 -1
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +1 -1
  4. package/dist/services/agent/ecc-archive-safety.d.ts +25 -0
  5. package/dist/services/agent/ecc-archive-safety.d.ts.map +1 -0
  6. package/dist/services/agent/ecc-archive-safety.js +131 -0
  7. package/dist/services/agent/ecc-cache-cleanup.d.ts +26 -0
  8. package/dist/services/agent/ecc-cache-cleanup.d.ts.map +1 -0
  9. package/dist/services/agent/ecc-cache-cleanup.js +90 -0
  10. package/dist/services/agent/ecc-cache-config.d.ts +66 -0
  11. package/dist/services/agent/ecc-cache-config.d.ts.map +1 -0
  12. package/dist/services/agent/ecc-cache-config.js +72 -0
  13. package/dist/services/agent/ecc-cache-manifest.d.ts +22 -0
  14. package/dist/services/agent/ecc-cache-manifest.d.ts.map +1 -0
  15. package/dist/services/agent/ecc-cache-manifest.js +136 -0
  16. package/dist/services/agent/ecc-cache-service.d.ts +6 -113
  17. package/dist/services/agent/ecc-cache-service.d.ts.map +1 -1
  18. package/dist/services/agent/ecc-cache-service.js +28 -645
  19. package/dist/services/agent/ecc-fetch.d.ts +31 -0
  20. package/dist/services/agent/ecc-fetch.d.ts.map +1 -0
  21. package/dist/services/agent/ecc-fetch.js +95 -0
  22. package/dist/services/agent/ecc-materialize.d.ts +35 -0
  23. package/dist/services/agent/ecc-materialize.d.ts.map +1 -0
  24. package/dist/services/agent/ecc-materialize.js +110 -0
  25. package/dist/services/agent/ecc-materialized-readers.d.ts +31 -0
  26. package/dist/services/agent/ecc-materialized-readers.d.ts.map +1 -0
  27. package/dist/services/agent/ecc-materialized-readers.js +107 -0
  28. package/dist/services/mut/assert-scanner.d.ts.map +1 -1
  29. package/dist/services/mut/assert-scanner.js +8 -4
  30. package/dist/services/mut/index.d.ts +3 -3
  31. package/dist/services/mut/index.d.ts.map +1 -1
  32. package/dist/services/mut/index.js +2 -2
  33. package/dist/services/mut/mut-runner.js +4 -4
  34. package/dist/services/mut/production-stryker.d.ts.map +1 -1
  35. package/dist/services/mut/production-stryker.js +17 -13
  36. package/dist/services/mut/report-builder.d.ts.map +1 -1
  37. package/dist/services/mut/report-builder.js +6 -6
  38. package/dist/services/mut/report-loader.d.ts.map +1 -1
  39. package/dist/services/mut/report-loader.js +2 -1
  40. package/dist/services/mut/thresholds.js +4 -4
  41. package/dist/services/mut/types.d.ts.map +1 -1
  42. package/dist/services/mut/types.js +14 -10
  43. package/package.json +1 -1
@@ -46,267 +46,19 @@
46
46
  * `.png` assets) but kept as last resort in case a future
47
47
  * release ships the asset again.
48
48
  */
49
- import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync, } from 'node:fs';
50
- import { join } from 'node:path';
51
- import { homedir } from 'node:os';
52
- import { parseFrontmatter } from '../../shared/frontmatter.js';
53
- export const ECC_REPO_OWNER = 'affaan-m';
54
- // Upstream renamed `everything-claude-code` -> `ECC` on 2026-09; GitHub
55
- // 301-redirects the old name but we keep the current one to avoid the hop.
56
- export const ECC_REPO_NAME = 'ECC';
57
- const ECC_CACHE_VERSION = '1';
58
- const ECC_MATERIALIZE_VERSION = '1';
59
- const ECC_TARBALL_BASENAME = 'ecc.tar.gz';
60
- // GitHub's API tarball endpoint 415s on `application/octet-stream`.
61
- const GITHUB_API_ACCEPT = 'application/vnd.github+json';
62
- /**
63
- * Cache dir resolution — single source of truth. Tests inject
64
- * via `dirOverride` on the functions that take one.
65
- */
66
- export function resolveEccCacheDir() {
67
- return join(homedir(), '.peaks', 'cache');
68
- }
69
- export function resolveManifestPath(dirOverride) {
70
- return join(dirOverride ?? resolveEccCacheDir(), 'ecc-installed.json');
71
- }
72
- export function resolveShaDir(sha, dirOverride) {
73
- return join(dirOverride ?? resolveEccCacheDir(), `ecc-${sha}`);
74
- }
75
- export function resolveAgentsDir(sha, dirOverride) {
76
- return join(resolveShaDir(sha, dirOverride), 'agents');
77
- }
78
- /**
79
- * Plugin-free materialize target: `~/.peaks/agents/ecc/`.
80
- *
81
- * Deliberately NOT under `~/.claude/` — peaks-loop must never write into
82
- * the user's Claude Code tree (user direction 2026-09-09). The LLM reads
83
- * `<target>/<agent-name>.md` directly when the ECC Claude Code plugin is
84
- * absent, then dispatches a generic sub-agent with that body.
85
- */
86
- export function resolveEccMaterializedDir() {
87
- return join(homedir(), '.peaks', 'agents', 'ecc');
88
- }
89
- export function resolveEccMaterializedManifestPath(dirOverride) {
90
- return join(dirOverride ?? resolveEccMaterializedDir(), 'ecc-agents.json');
91
- }
92
- /**
93
- * Best-effort chmod 0o700 on POSIX; no-op on Windows (NTFS uses
94
- * ACLs, not POSIX mode bits). Swallows errors with WARN so a
95
- * permissions failure never blocks the CLI.
96
- */
97
- export function setCacheDirPermissions(cacheDir) {
98
- if (process.platform === 'win32')
99
- return;
100
- try {
101
- chmodSync(cacheDir, 0o700);
102
- }
103
- catch {
104
- /* best-effort */
105
- }
106
- }
107
- function isSafeAgentName(name) {
108
- return /^[a-z][a-z0-9-]*$/.test(name);
109
- }
110
- /**
111
- * GitHub prefixes every tarball entry with a synthetic root dir —
112
- * `<repo>-<sha>` on codeload, `<owner>-<repo>-<sha>` on the API tarball
113
- * endpoint. Match on shape, not on the repo name, so a rename (or either
114
- * endpoint) cannot silently zero out the extraction.
115
- */
116
- function stripTarballRootSegments(entryName) {
117
- const segments = entryName.split('/');
118
- if (segments.length >= 3 && segments[0] !== 'agents')
119
- segments.shift();
120
- return segments;
121
- }
122
- function isSafeArchiveEntry(entryName) {
123
- if (entryName.length === 0)
124
- return false;
125
- if (entryName.startsWith('/') || /^[a-zA-Z]:[\\/]/.test(entryName))
126
- return false;
127
- if (entryName.includes('..'))
128
- return false;
129
- // After dropping the synthetic root, everything must be exactly
130
- // "agents/<name>.md" at a single level.
131
- const segments = stripTarballRootSegments(entryName);
132
- if (segments.length !== 2)
133
- return false;
134
- return segments[0] === 'agents' && segments[1]?.endsWith('.md') === true;
135
- }
136
- function safeAgentNameFromEntry(entryName) {
137
- const segments = stripTarballRootSegments(entryName);
138
- const file = segments[segments.length - 1] ?? '';
139
- const base = file.replace(/\.md$/i, '');
140
- return isSafeAgentName(base) ? base : null;
141
- }
142
- /**
143
- * Best-effort fetch of the upstream release JSON. Returns the
144
- * parsed body, or null on any network/parse error. Used as the
145
- * D-010 fallback path.
146
- */
147
- async function fetchReleaseJson(apiBase) {
148
- try {
149
- const res = await fetch(apiBase, {
150
- headers: { accept: 'application/vnd.github+json', 'user-agent': 'peaks-loop' },
151
- });
152
- if (!res.ok)
153
- return null;
154
- return (await res.json());
155
- }
156
- catch {
157
- return null;
158
- }
159
- }
160
- /**
161
- * Resolve a 40-char commit SHA for `tag`. Prefers the GitHub
162
- * releases API (which dereferences annotated tags to commit SHA
163
- * via `target_commitish`). Falls back to the tag name if the
164
- * upstream returns a non-SHA-shaped identifier (older tags).
165
- */
166
- async function resolveCommitSha(ref) {
167
- const apiBase = `https://api.github.com/repos/${ECC_REPO_OWNER}/${ECC_REPO_NAME}/releases/tags/${encodeURIComponent(ref)}`;
168
- const release = await fetchReleaseJson(apiBase);
169
- const tagName = release?.tag_name ?? ref;
170
- if (/^[0-9a-f]{40}$/.test(tagName))
171
- return tagName;
172
- return tagName;
173
- }
174
- function asSha(value) {
175
- return /^[0-9a-f]{40}$/.test(value) ? value : value;
176
- }
177
- /**
178
- * Tiny tar.gz extractor. Public-domain-compatible tar parser:
179
- * - reads 512-byte header blocks
180
- * - validates name + size
181
- * - rejects anything that is not a regular file at a safe path
182
- * - filters to the `agents/*.md` allowlist via isSafeArchiveEntry
183
- *
184
- * We do NOT decompress gzip via a third-party lib; Node's
185
- * `node:zlib` ships with `gunzip` so the implementation is
186
- * self-contained.
187
- */
188
- async function extractAgentsFromTarGz(buffer, outDir) {
189
- if (!existsSync(outDir))
190
- mkdirSync(outDir, { recursive: true });
191
- const extracted = [];
192
- // Lazy import to keep the cold path cheap.
193
- const { gunzipSync } = await import('node:zlib');
194
- let tar;
195
- try {
196
- tar = gunzipSync(buffer);
197
- }
198
- catch {
199
- return [];
200
- }
201
- const BLOCK = 512;
202
- let offset = 0;
203
- while (offset + BLOCK <= tar.length) {
204
- const header = tar.subarray(offset, offset + BLOCK);
205
- // Two consecutive zero blocks mark end-of-archive.
206
- if (header.every((b) => b === 0))
207
- break;
208
- const name = readCString(header, 0, 100);
209
- if (name === null || name.length === 0)
210
- break;
211
- const sizeOctal = readCString(header, 124, 12);
212
- if (sizeOctal === null)
213
- break;
214
- const size = parseOctal(sizeOctal);
215
- if (size === null)
216
- break;
217
- const typeFlag = String.fromCharCode(header[156] ?? 0);
218
- // '0' or '\0' = regular file. Reject symlinks (2), dirs (5), etc.
219
- if (typeFlag !== '0' && typeFlag !== '\0') {
220
- offset += BLOCK + Math.ceil(size / BLOCK) * BLOCK;
221
- continue;
222
- }
223
- if (!isSafeArchiveEntry(name)) {
224
- offset += BLOCK + Math.ceil(size / BLOCK) * BLOCK;
225
- continue;
226
- }
227
- const safeName = safeAgentNameFromEntry(name);
228
- if (safeName === null) {
229
- offset += BLOCK + Math.ceil(size / BLOCK) * BLOCK;
230
- continue;
231
- }
232
- const data = tar.subarray(offset + BLOCK, offset + BLOCK + size);
233
- writeFileSync(join(outDir, `${safeName}.md`), data);
234
- extracted.push(safeName);
235
- offset += BLOCK + Math.ceil(size / BLOCK) * BLOCK;
236
- }
237
- return extracted;
238
- }
239
- function readCString(buf, start, len) {
240
- let end = start;
241
- while (end < start + len && buf[end] !== 0)
242
- end += 1;
243
- if (end === start)
244
- return '';
245
- try {
246
- return Buffer.from(buf.subarray(start, end)).toString('utf8');
247
- }
248
- catch {
249
- return null;
250
- }
251
- }
252
- function parseOctal(value) {
253
- const trimmed = value.trim().replace(/\0+$/g, '');
254
- if (trimmed.length === 0)
255
- return 0;
256
- const n = Number.parseInt(trimmed, 8);
257
- return Number.isFinite(n) && n >= 0 ? n : null;
258
- }
259
- /**
260
- * Binary fetch with an explicit, overridable `accept`.
261
- *
262
- * Do NOT default to `application/octet-stream`: GitHub's
263
- * `api.github.com/.../tarball/<ref>` endpoint rejects it with 415.
264
- * Omitting `accept` entirely is fine for release-asset / codeload
265
- * URLs, which always serve the bytes.
266
- */
267
- async function fetchBuffer(url, accept) {
268
- try {
269
- const headers = { 'user-agent': 'peaks-loop' };
270
- if (accept !== undefined)
271
- headers.accept = accept;
272
- const res = await fetch(url, { headers });
273
- if (!res.ok)
274
- return null;
275
- const ab = await res.arrayBuffer();
276
- return new Uint8Array(ab);
277
- }
278
- catch {
279
- return null;
280
- }
281
- }
282
- async function downloadTarball(ref, sha, outDir) {
283
- // D-010 order (2026-09-09): tarball_url -> release asset -> PRD URL.
284
- // See the module header for why each step exists and which one works.
285
- let buffer = null;
286
- const release = await fetchReleaseJson(`https://api.github.com/repos/${ECC_REPO_OWNER}/${ECC_REPO_NAME}/releases/tags/${encodeURIComponent(ref)}`);
287
- // 1. API tarball. Requires the GitHub JSON accept header (octet-stream 415s).
288
- const tarballUrl = release?.tarball_url;
289
- if (typeof tarballUrl === 'string' && tarballUrl.length > 0) {
290
- buffer = await fetchBuffer(tarballUrl, GITHUB_API_ACCEPT);
291
- }
292
- // 2. Release asset, if this release happens to ship one.
293
- if (buffer === null && Array.isArray(release?.assets)) {
294
- const asset = release.assets.find((a) => a.name === ECC_TARBALL_BASENAME) ??
295
- release.assets.find((a) => a.name === `${ECC_REPO_NAME}-universal-${ref}.tgz`) ??
296
- release.assets.find((a) => a.name.endsWith('.tgz') || a.name.endsWith('.tar.gz'));
297
- if (asset)
298
- buffer = await fetchBuffer(asset.browser_download_url);
299
- }
300
- // 3. PRD asset URL — last resort, dead upstream today.
301
- if (buffer === null) {
302
- const prdUrl = `https://github.com/${ECC_REPO_OWNER}/${ECC_REPO_NAME}/releases/download/${encodeURIComponent(ref)}/${ECC_TARBALL_BASENAME}`;
303
- buffer = await fetchBuffer(prdUrl);
304
- }
305
- if (buffer === null) {
306
- throw new Error('fetch-failed');
307
- }
308
- return extractAgentsFromTarGz(buffer, outDir);
309
- }
49
+ // ---------------------------------------------------------------------
50
+ // 2026-10-03 wave 11 slice A: this file is the facade for the split. The
51
+ // implementation lives in the sibling modules beside it; this module keeps
52
+ // the download orchestration plus the FULL original export surface, because
53
+ // `tests/unit/services/ecc/*` import this exact path after mocking
54
+ // `node:os` (T2) and `src/index.ts` re-exports it. Do not move these files
55
+ // without reading `.peaks/docs/lint-gate.md` §4e/§4r first.
56
+ // ---------------------------------------------------------------------
57
+ import { existsSync, mkdirSync, readdirSync } from 'node:fs';
58
+ import { ECC_CACHE_VERSION, ECC_REPO_OWNER, ECC_REPO_NAME, resolveEccCacheDir, resolveAgentsDir, setCacheDirPermissions, asSha } from './ecc-cache-config.js';
59
+ import { fetchReleaseJson, resolveCommitSha, downloadTarball } from './ecc-fetch.js';
60
+ import { writeManifest } from './ecc-cache-manifest.js';
61
+ import { materializeBestEffort } from './ecc-materialize.js';
310
62
  /**
311
63
  * Download ECC into `~/.peaks/cache/ecc-<sha>/agents/`. Returns
312
64
  * the resolved SHA + the number of agents extracted.
@@ -323,10 +75,10 @@ export async function downloadToCache({ ref } = {}) {
323
75
  if (typeof tag !== 'string' || tag.length === 0) {
324
76
  throw new Error('fetch-failed');
325
77
  }
326
- resolvedSha = asSha(await resolveCommitSha(tag) ?? tag);
78
+ resolvedSha = asSha((await resolveCommitSha(tag)) ?? tag);
327
79
  }
328
80
  else {
329
- resolvedSha = asSha(await resolveCommitSha(requestedRef) ?? requestedRef);
81
+ resolvedSha = asSha((await resolveCommitSha(requestedRef)) ?? requestedRef);
330
82
  }
331
83
  const cacheDir = resolveEccCacheDir();
332
84
  if (!existsSync(cacheDir))
@@ -338,7 +90,12 @@ export async function downloadToCache({ ref } = {}) {
338
90
  const agents = readdirSync(agentsDir)
339
91
  .filter((f) => f.endsWith('.md'))
340
92
  .map((f) => f.replace(/\.md$/i, ''));
341
- writeManifest({ version: ECC_CACHE_VERSION, sha: resolvedSha, fetchedAt: new Date().toISOString(), agents });
93
+ writeManifest({
94
+ version: ECC_CACHE_VERSION,
95
+ sha: resolvedSha,
96
+ fetchedAt: new Date().toISOString(),
97
+ agents
98
+ });
342
99
  materializeBestEffort(cacheDir);
343
100
  return { sha: resolvedSha, agents: agents.length };
344
101
  }
@@ -347,389 +104,15 @@ export async function downloadToCache({ ref } = {}) {
347
104
  version: ECC_CACHE_VERSION,
348
105
  sha: resolvedSha,
349
106
  fetchedAt: new Date().toISOString(),
350
- agents: extracted,
107
+ agents: extracted
351
108
  };
352
109
  writeManifest(manifest);
353
110
  materializeBestEffort(cacheDir);
354
111
  return { sha: resolvedSha, agents: extracted.length };
355
112
  }
356
- /**
357
- * Refresh the plugin-free copy after a successful download. Swallows every
358
- * error: `peaks ecc install` succeeds even when the materialize step cannot
359
- * write (read-only home, disk full, ...) — the caller falls back to inline
360
- * review in that case.
361
- */
362
- function materializeBestEffort(cacheDir) {
363
- try {
364
- materializeEccAgents({ cacheDir });
365
- }
366
- catch {
367
- /* best-effort */
368
- }
369
- }
370
- function writeManifest(manifest) {
371
- const path = resolveManifestPath();
372
- writeFileSync(path, JSON.stringify(manifest, null, 2));
373
- }
374
- export function readCacheManifest() {
375
- return readManifestAt();
376
- }
377
- function readManifestAt(dirOverride) {
378
- const path = resolveManifestPath(dirOverride);
379
- if (!existsSync(path))
380
- return null;
381
- try {
382
- const raw = readFileSync(path, 'utf8');
383
- const parsed = JSON.parse(raw);
384
- if (typeof parsed.version === 'string' &&
385
- typeof parsed.sha === 'string' &&
386
- typeof parsed.fetchedAt === 'string' &&
387
- Array.isArray(parsed.agents)) {
388
- return parsed;
389
- }
390
- return null;
391
- }
392
- catch {
393
- return null;
394
- }
395
- }
396
- let warnedAboutFallback = false;
397
- function fallbackMetadata(fileName) {
398
- const base = fileName.replace(/\.md$/i, '');
399
- let description = '';
400
- try {
401
- const body = readFileSync(join(resolveManifestDirForAgents(), fileName), 'utf8');
402
- const lines = body.split(/\r?\n/);
403
- let inFrontmatter = false;
404
- let seenClosing = false;
405
- for (const raw of lines) {
406
- const line = raw.trim();
407
- if (!seenClosing) {
408
- if (!inFrontmatter && line === '---') {
409
- inFrontmatter = true;
410
- continue;
411
- }
412
- if (inFrontmatter && line === '---') {
413
- seenClosing = true;
414
- continue;
415
- }
416
- continue;
417
- }
418
- if (line.length === 0)
419
- continue;
420
- description = line;
421
- break;
422
- }
423
- }
424
- catch {
425
- /* best-effort */
426
- }
427
- if (description.length > 80)
428
- description = `${description.slice(0, 77)}...`;
429
- if (!warnedAboutFallback) {
430
- try {
431
- process.stderr.write(`warning: cached agent "${base}" has malformed frontmatter; falling back to filename + first body line\n`);
432
- }
433
- catch {
434
- /* best-effort */
435
- }
436
- warnedAboutFallback = true;
437
- }
438
- return { name: base, description };
439
- }
440
- function resolveManifestDirForAgents() {
441
- const manifest = readCacheManifest();
442
- if (manifest === null)
443
- return '';
444
- return resolveAgentsDir(manifest.sha);
445
- }
446
- export function listCachedAgents() {
447
- const manifest = readCacheManifest();
448
- if (manifest === null)
449
- return [];
450
- const agentsDir = resolveAgentsDir(manifest.sha);
451
- if (!existsSync(agentsDir))
452
- return [];
453
- const out = [];
454
- for (const file of readdirSync(agentsDir).sort()) {
455
- if (!file.endsWith('.md'))
456
- continue;
457
- const fullPath = join(agentsDir, file);
458
- let meta;
459
- try {
460
- const raw = readFileSync(fullPath, 'utf8');
461
- const fm = parseFrontmatter(raw);
462
- meta = { name: fm.name, description: fm.description };
463
- }
464
- catch {
465
- // D-009 fallback — name from filename, description from first body line.
466
- meta = fallbackMetadata(file);
467
- }
468
- out.push(meta);
469
- }
470
- return out;
471
- }
472
- export function readAgentSkill(name) {
473
- if (!isSafeAgentName(name))
474
- return null;
475
- const manifest = readCacheManifest();
476
- if (manifest === null)
477
- return null;
478
- const file = join(resolveAgentsDir(manifest.sha), `${name}.md`);
479
- if (!existsSync(file))
480
- return null;
481
- try {
482
- return readFileSync(file, 'utf8');
483
- }
484
- catch {
485
- return null;
486
- }
487
- }
488
- // ---------------------------------------------------------------------
489
- // Plugin-free materialize layer (Slice A of 2026-09-09-ecc-dynamic)
490
- //
491
- // `peaks ecc install` downloads ECC `agents/*.md` into the sha cache, but
492
- // that path is plugin-independent only in storage — the RD fan-out still
493
- // needed `Agent({subagent_type: 'everything-claude-code:code-review'})` (old retired id),
494
- // which requires the ECC Claude Code plugin. Materializing a normalized
495
- // copy under `~/.peaks/agents/ecc/` gives the RD loop a plugin-free read
496
- // target so a fresh machine without the ECC plugin can still run the
497
- // review via a generic sub-agent.
498
- // ---------------------------------------------------------------------
499
- export function readEccMaterializeManifest(dirOverride) {
500
- const path = resolveEccMaterializedManifestPath(dirOverride);
501
- if (!existsSync(path))
502
- return null;
503
- try {
504
- const parsed = JSON.parse(readFileSync(path, 'utf8'));
505
- if (typeof parsed.version === 'string' &&
506
- typeof parsed.sha === 'string' &&
507
- typeof parsed.materializedAt === 'string' &&
508
- Array.isArray(parsed.agents)) {
509
- return parsed;
510
- }
511
- return null;
512
- }
513
- catch {
514
- return null;
515
- }
516
- }
517
- export function listMaterializedAgents(dirOverride) {
518
- const dir = dirOverride ?? resolveEccMaterializedDir();
519
- if (!existsSync(dir))
520
- return [];
521
- try {
522
- return readdirSync(dir)
523
- .filter((f) => f.endsWith('.md'))
524
- .map((f) => f.replace(/\.md$/i, ''))
525
- .filter((name) => isSafeAgentName(name))
526
- .sort();
527
- }
528
- catch {
529
- return [];
530
- }
531
- }
532
- export function hasMaterializedEccAgents(dirOverride) {
533
- return listMaterializedAgents(dirOverride).length > 0;
534
- }
535
- /**
536
- * Resolve the materialized ECC agent name for a logical role.
537
- *
538
- * Upstream ECC names its agents `<lang>-reviewer` (`code-reviewer.md`),
539
- * NOT `code-review.md` — so no caller may hardcode a single filename.
540
- * Resolution order (deterministic; `listMaterializedAgents` is sorted):
541
- * 1. the caller's explicit candidates, in declared priority order
542
- * (e.g. `['code-reviewer', 'code-review']` — real upstream name
543
- * first, legacy/forward-compat second);
544
- * 2. a fallback over the materialized list: the exact
545
- * `<stem>-reviewer`, else the first `<stem>-*` whose name contains
546
- * `reviewer`, where `stem` is the candidate minus a `-reviewer`
547
- * suffix (`code-reviewer` -> `code`).
548
- *
549
- * Returns `null` when nothing matches — the caller degrades to inline
550
- * review instead of dispatching a non-existent agent.
551
- */
552
- export function resolveMaterializedAgentName(candidates, dirOverride) {
553
- const available = listMaterializedAgents(dirOverride);
554
- if (available.length === 0)
555
- return null;
556
- for (const candidate of candidates) {
557
- if (available.includes(candidate))
558
- return candidate;
559
- }
560
- for (const candidate of candidates) {
561
- const stem = candidate.replace(/-reviewer$/, '');
562
- const exact = available.find((name) => name === `${stem}-reviewer`);
563
- if (exact !== undefined)
564
- return exact;
565
- const reviewerish = available.find((name) => name.startsWith(`${stem}-`) && name.includes('reviewer'));
566
- if (reviewerish !== undefined)
567
- return reviewerish;
568
- }
569
- return null;
570
- }
571
- export function readMaterializedAgent(name, dirOverride) {
572
- if (!isSafeAgentName(name))
573
- return null;
574
- const file = join(dirOverride ?? resolveEccMaterializedDir(), `${name}.md`);
575
- if (!existsSync(file))
576
- return null;
577
- try {
578
- return readFileSync(file, 'utf8');
579
- }
580
- catch {
581
- return null;
582
- }
583
- }
584
- /**
585
- * Copy the active cache's `agents/*.md` into a stable, peaks-owned
586
- * directory (`~/.peaks/agents/ecc/` by default) and write a small
587
- * manifest. Fail-soft: an empty/missing cache yields
588
- * `{ sha: null, materialized: [] }` and never throws — `peaks ecc install`
589
- * must not fail because materialization did.
590
- *
591
- * `targetDir` is the ONLY write root (plus `mkdirSync` on it). Nothing in
592
- * this function can reach `~/.claude/`.
593
- */
594
- export function materializeEccAgents({ cacheDir, targetDir } = {}) {
595
- const resolvedTarget = targetDir ?? resolveEccMaterializedDir();
596
- const manifest = readManifestAt(cacheDir);
597
- if (manifest === null) {
598
- return { targetDir: resolvedTarget, sha: null, materialized: [] };
599
- }
600
- const agentsDir = resolveAgentsDir(manifest.sha, cacheDir);
601
- if (!existsSync(agentsDir)) {
602
- return { targetDir: resolvedTarget, sha: null, materialized: [] };
603
- }
604
- let entries;
605
- try {
606
- entries = readdirSync(agentsDir);
607
- }
608
- catch {
609
- return { targetDir: resolvedTarget, sha: null, materialized: [] };
610
- }
611
- try {
612
- if (!existsSync(resolvedTarget))
613
- mkdirSync(resolvedTarget, { recursive: true });
614
- setCacheDirPermissions(resolvedTarget);
615
- }
616
- catch {
617
- return { targetDir: resolvedTarget, sha: null, materialized: [] };
618
- }
619
- const materialized = [];
620
- for (const file of entries) {
621
- if (!file.endsWith('.md'))
622
- continue;
623
- const name = file.replace(/\.md$/i, '');
624
- if (!isSafeAgentName(name))
625
- continue;
626
- try {
627
- const body = readFileSync(join(agentsDir, file), 'utf8');
628
- writeFileSync(join(resolvedTarget, `${name}.md`), body);
629
- materialized.push(name);
630
- }
631
- catch {
632
- /* fail-soft per agent */
633
- }
634
- }
635
- materialized.sort();
636
- // Prune stale copies so `readMaterializedAgent` cannot serve an agent
637
- // the active cache no longer ships.
638
- try {
639
- for (const existing of readdirSync(resolvedTarget)) {
640
- if (!existing.endsWith('.md'))
641
- continue;
642
- const name = existing.replace(/\.md$/i, '');
643
- if (!materialized.includes(name)) {
644
- rmSync(join(resolvedTarget, existing), { force: true });
645
- }
646
- }
647
- }
648
- catch {
649
- /* fail-soft */
650
- }
651
- const nextManifest = {
652
- version: ECC_MATERIALIZE_VERSION,
653
- sha: manifest.sha,
654
- materializedAt: new Date().toISOString(),
655
- agents: materialized,
656
- };
657
- try {
658
- writeFileSync(resolveEccMaterializedManifestPath(resolvedTarget), JSON.stringify(nextManifest, null, 2));
659
- }
660
- catch {
661
- /* fail-soft */
662
- }
663
- return { targetDir: resolvedTarget, sha: manifest.sha, materialized };
664
- }
665
- /**
666
- * 7-day TTL sweep over `ecc-<sha>/` directories.
667
- *
668
- * - Active cache (per manifest `sha`): use `fetchedAt` as the
669
- * age source; remove if older than `retentionDays`.
670
- * - Orphan caches (any other `ecc-<40hex>` directory): use
671
- * directory `mtimeMs` as the age source.
672
- * - If the active cache is removed, invalidate the manifest.
673
- *
674
- * Returns the absolute paths of the removed directories.
675
- */
676
- export function cleanupStaleCache({ retentionDays, nowMs, dirOverride, }) {
677
- const cacheDir = dirOverride ?? resolveEccCacheDir();
678
- if (!existsSync(cacheDir))
679
- return { removed: [] };
680
- const dayMs = 24 * 60 * 60 * 1000;
681
- const cutoff = nowMs - retentionDays * dayMs;
682
- const manifest = readCacheManifest();
683
- const activeSha = manifest?.sha ?? null;
684
- const activeFetchedAt = manifest?.fetchedAt ? Date.parse(manifest.fetchedAt) : NaN;
685
- const removed = [];
686
- let names;
687
- try {
688
- names = readdirSync(cacheDir);
689
- }
690
- catch {
691
- return { removed: [] };
692
- }
693
- for (const name of names) {
694
- const match = /^ecc-([0-9a-f]{40})$/.exec(name);
695
- if (match === null)
696
- continue;
697
- const sha = match[1] ?? '';
698
- const fullPath = join(cacheDir, name);
699
- let stat;
700
- try {
701
- stat = statSync(fullPath);
702
- }
703
- catch {
704
- continue;
705
- }
706
- if (!stat.isDirectory())
707
- continue;
708
- let ageMs;
709
- if (sha === activeSha && Number.isFinite(activeFetchedAt)) {
710
- ageMs = nowMs - activeFetchedAt;
711
- }
712
- else {
713
- ageMs = nowMs - stat.mtimeMs;
714
- }
715
- if (ageMs > retentionDays * dayMs) {
716
- try {
717
- rmSync(fullPath, { recursive: true, force: true });
718
- removed.push(fullPath);
719
- }
720
- catch {
721
- /* best-effort */
722
- }
723
- }
724
- }
725
- // Invalidate manifest if active cache was removed.
726
- if (activeSha !== null && removed.some((p) => p.includes(`ecc-${activeSha}`))) {
727
- try {
728
- rmSync(resolveManifestPath(cacheDir), { force: true });
729
- }
730
- catch {
731
- /* best-effort */
732
- }
733
- }
734
- return { removed };
735
- }
113
+ // Re-exports — the exact public surface of the pre-split module.
114
+ export { ECC_REPO_OWNER, ECC_REPO_NAME, resolveEccCacheDir, resolveManifestPath, resolveShaDir, resolveAgentsDir, resolveEccMaterializedDir, resolveEccMaterializedManifestPath, setCacheDirPermissions } from './ecc-cache-config.js';
115
+ export { readCacheManifest, listCachedAgents, readAgentSkill } from './ecc-cache-manifest.js';
116
+ export { readEccMaterializeManifest, listMaterializedAgents, hasMaterializedEccAgents, resolveMaterializedAgentName, readMaterializedAgent } from './ecc-materialized-readers.js';
117
+ export { materializeEccAgents } from './ecc-materialize.js';
118
+ export { cleanupStaleCache } from './ecc-cache-cleanup.js';