@lmzhen/dsh-evolution-core 0.1.0-rc.7 → 0.1.0-rc.70

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.
package/lib/index.js CHANGED
@@ -1,16 +1,28 @@
1
- import { dirname, join } from "node:path";
2
- import { cp, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
1
+ import { basename, dirname, join } from "node:path";
2
+ import { cp, lstat, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
3
3
  import { createHash, randomBytes } from "node:crypto";
4
4
  import { homedir } from "node:os";
5
- import { readFileSync } from "node:fs";
6
5
  //#region lib/types/io.js
7
6
  /**
8
- * Structural IO seam for the legacy facade stores.
7
+ * Structural IO seam for the evolution plugin family.
9
8
  *
10
- * The facade accepts any object exposing this small async file-tree surface.
11
- * Native DSH packages pass `ctx.evolutionIo.provider()`; standalone consumers
12
- * (and the facade's own tests) can use `nodeEvolutionIo`.
9
+ * Every evolution package passes `ctx.evolutionIo.provider()`; standalone
10
+ * consumers (and the core's own tests) can use `nodeEvolutionIo`.
13
11
  */
12
+ /**
13
+ * Run `task` inside `io.transact` when the backend provides it; otherwise fall
14
+ * back to a plain read → task → write/remove sequence (no cross-process lock —
15
+ * callers keep their single-process serialize chain as the second layer).
16
+ */
17
+ async function transactIo(io, path, task) {
18
+ if (io.transact) {
19
+ await io.transact(path, task);
20
+ return;
21
+ }
22
+ const next = await task(await io.readText(path));
23
+ if (next === null) await io.remove(path);
24
+ else await io.writeText(path, next);
25
+ }
14
26
  /** Lazy adapter over an IO provider registry, shared by every evolution consumer. */
15
27
  function evolutionIoAdapter(provider) {
16
28
  return {
@@ -20,23 +32,112 @@ function evolutionIoAdapter(provider) {
20
32
  list: (path) => provider().list(path),
21
33
  exists: (path) => provider().exists(path),
22
34
  rename: (path, destination) => provider().rename(path, destination),
23
- copy: (path, destination) => provider().copy(path, destination)
35
+ copy: (path, destination) => provider().copy(path, destination),
36
+ size: (path) => {
37
+ const io = provider();
38
+ return io.size ? io.size(path) : Promise.resolve(null);
39
+ },
40
+ transact: (path, task) => {
41
+ const io = provider();
42
+ return io.transact ? io.transact(path, task) : transactIo(io, path, task);
43
+ },
44
+ isSymlink: (path) => {
45
+ const io = provider();
46
+ return io.isSymlink ? io.isSymlink(path) : Promise.resolve(null);
47
+ }
24
48
  };
25
49
  }
26
50
  function nodeEvolutionIo() {
51
+ const isMissing = (error) => {
52
+ const code = error?.code;
53
+ return code === "ENOENT" || code === "ENOTDIR";
54
+ };
55
+ /** True when the pid is alive (EPERM = alive but unowned; ESRCH = gone). */
56
+ const isAlive = (pid) => {
57
+ try {
58
+ process.kill(pid, 0);
59
+ return true;
60
+ } catch (error) {
61
+ return error?.code === "EPERM";
62
+ }
63
+ };
64
+ /**
65
+ * Cross-process write lock (claw `withFileLock` parity): an O_EXCL lock file
66
+ * guards the atomic write. A >5s-old lock is taken over ONLY after probing
67
+ * the holder pid it carries (rc.66): a LIVE holder is never stolen, so a
68
+ * slow writer no longer loses its lock to a peer at the 5s mark (the
69
+ * takeover is the only best-effort surface; the retry budget fails loud —
70
+ * rc.65 — instead of ever proceeding unlocked). Budget = 40 * 50ms (~2s,
71
+ * rc.69): 8-writer contention bursts on a loaded CI runner exceed 10
72
+ * attempts (500ms), and a fail-loud throw was observed instead of a clean
73
+ * serialization.
74
+ */
75
+ const withWriteLock = async (path, task) => {
76
+ const lock = `${path}.lock`;
77
+ for (let attempt = 0; attempt < 40; attempt += 1) try {
78
+ await writeFile(lock, String(process.pid), { flag: "wx" });
79
+ try {
80
+ return await task();
81
+ } finally {
82
+ await rm(lock, { force: true }).catch(() => {});
83
+ }
84
+ } catch (error) {
85
+ const code = error?.code;
86
+ if (code !== "EEXIST" && code !== "EPERM") throw error;
87
+ try {
88
+ const st = await stat(lock);
89
+ if (Date.now() - st.mtimeMs > 5e3) {
90
+ const holder = Number(await readFile(lock, "utf8").catch(() => ""));
91
+ if (!(Number.isInteger(holder) && holder > 0 && isAlive(holder))) {
92
+ try {
93
+ await rm(lock, { force: true });
94
+ } catch {}
95
+ continue;
96
+ }
97
+ }
98
+ } catch {
99
+ continue;
100
+ }
101
+ await new Promise((resolve) => setTimeout(resolve, 50));
102
+ }
103
+ throw new Error(`could not acquire write lock for ${path} after 40 attempts`);
104
+ };
27
105
  return {
28
106
  async readText(path) {
29
107
  try {
30
108
  return await readFile(path, "utf8");
31
- } catch {
32
- return null;
109
+ } catch (error) {
110
+ if (isMissing(error)) return null;
111
+ throw error;
33
112
  }
34
113
  },
35
114
  async writeText(path, content) {
36
115
  await mkdir(dirname(path), { recursive: true });
37
- const tmp = `${path}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
38
- await writeFile(tmp, content, "utf8");
39
- await rename(tmp, path);
116
+ await withWriteLock(path, async () => {
117
+ const tmp = `${path}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
118
+ await writeFile(tmp, content, "utf8");
119
+ await rename(tmp, path);
120
+ });
121
+ },
122
+ async transact(path, task) {
123
+ await mkdir(dirname(path), { recursive: true });
124
+ await withWriteLock(path, async () => {
125
+ let current;
126
+ try {
127
+ current = await readFile(path, "utf8");
128
+ } catch (error) {
129
+ if (isMissing(error)) current = null;
130
+ else throw error;
131
+ }
132
+ const next = await task(current);
133
+ if (next === null) {
134
+ await rm(path, { force: true });
135
+ return;
136
+ }
137
+ const tmp = `${path}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
138
+ await writeFile(tmp, next, "utf8");
139
+ await rename(tmp, path);
140
+ });
40
141
  },
41
142
  async remove(path) {
42
143
  await rm(path, {
@@ -47,16 +148,18 @@ function nodeEvolutionIo() {
47
148
  async list(path) {
48
149
  try {
49
150
  return await readdir(path);
50
- } catch {
51
- return [];
151
+ } catch (error) {
152
+ if (isMissing(error)) return [];
153
+ throw error;
52
154
  }
53
155
  },
54
156
  async exists(path) {
55
157
  try {
56
158
  await stat(path);
57
159
  return true;
58
- } catch {
59
- return false;
160
+ } catch (error) {
161
+ if (isMissing(error)) return false;
162
+ throw error;
60
163
  }
61
164
  },
62
165
  async rename(path, destination) {
@@ -69,13 +172,24 @@ function nodeEvolutionIo() {
69
172
  recursive: true,
70
173
  force: true
71
174
  });
175
+ },
176
+ async size(path) {
177
+ try {
178
+ return (await stat(path)).size;
179
+ } catch (error) {
180
+ if (isMissing(error)) return null;
181
+ throw error;
182
+ }
183
+ },
184
+ async isSymlink(path) {
185
+ try {
186
+ return (await lstat(path)).isSymbolicLink();
187
+ } catch {
188
+ return null;
189
+ }
72
190
  }
73
191
  };
74
192
  }
75
- /** Absolute path helper kept separate so stores stay platform-correct. */
76
- function childPath(parent, ...parts) {
77
- return join(parent, ...parts);
78
- }
79
193
  //#endregion
80
194
  //#region lib/types/usage.js
81
195
  /**
@@ -100,22 +214,106 @@ function emptyRecord() {
100
214
  archived_at: null
101
215
  };
102
216
  }
103
- async function loadUsage(root, io = nodeEvolutionIo()) {
217
+ /** A timestamp passes only when `Date.parse` yields a finite epoch (N-3): a bare
218
+ * string check let garbage like "not-a-date" propagate as Invalid Date → NaN
219
+ * into quality math and lifecycle comparisons. */
220
+ const validTimestamp = (value) => typeof value === "string" && Number.isFinite(Date.parse(value));
221
+ const nullableTimestamp = (value) => value === null || validTimestamp(value);
222
+ /**
223
+ * Field-level normalization for one sidecar record (rc.42 audit P2-3): the
224
+ * spread used to copy any junk through verbatim, so a corrupted file could
225
+ * carry `use_count: "3"` into the quality math and lifecycle comparisons as
226
+ * NaN. Every field falls back to its `emptyRecord()` baseline unless it has
227
+ * exactly the declared type; an invalid `created_at` anchors the age clock at
228
+ * now (first-sight defer semantics for a record whose age is unknowable).
229
+ * Timestamps additionally require a parseable date (N-3): `"not-a-date"`
230
+ * would otherwise survive the type check as Invalid Date.
231
+ * Pure — exported for unit tests; `loadUsage` is the production caller.
232
+ */
233
+ function normalizeUsageRecord(record) {
234
+ const base = emptyRecord();
235
+ if (!record || typeof record !== "object" || Array.isArray(record)) return base;
236
+ const raw = record;
237
+ const num = (value, fallback) => typeof value === "number" && Number.isFinite(value) ? value : fallback;
238
+ const bool = (value, fallback) => typeof value === "boolean" ? value : fallback;
239
+ return {
240
+ created_by: typeof raw.created_by === "string" ? raw.created_by : null,
241
+ use_count: num(raw.use_count, base.use_count),
242
+ view_count: num(raw.view_count, base.view_count),
243
+ patch_count: num(raw.patch_count, base.patch_count),
244
+ last_used_at: nullableTimestamp(raw.last_used_at) ? raw.last_used_at : base.last_used_at,
245
+ last_viewed_at: nullableTimestamp(raw.last_viewed_at) ? raw.last_viewed_at : base.last_viewed_at,
246
+ last_patched_at: nullableTimestamp(raw.last_patched_at) ? raw.last_patched_at : base.last_patched_at,
247
+ created_at: validTimestamp(raw.created_at) ? raw.created_at : base.created_at,
248
+ state: raw.state === "stale" || raw.state === "archived" ? raw.state : "active",
249
+ pinned: bool(raw.pinned, base.pinned),
250
+ archived_at: nullableTimestamp(raw.archived_at) ? raw.archived_at : base.archived_at,
251
+ quality_score: typeof raw.quality_score === "number" && Number.isFinite(raw.quality_score) ? raw.quality_score : void 0,
252
+ quality_warn: typeof raw.quality_warn === "boolean" ? raw.quality_warn : void 0
253
+ };
254
+ }
255
+ /** Parse a raw usage sidecar; malformed content reads as empty (best-effort telemetry). */
256
+ function parseUsage(raw) {
104
257
  const map = /* @__PURE__ */ new Map();
105
- const raw = await io.readText(usageFile(root));
106
- if (raw !== null) try {
258
+ if (raw === null) return map;
259
+ try {
107
260
  const parsed = JSON.parse(raw);
108
- for (const [name, record] of Object.entries(parsed)) {
109
- const base = emptyRecord();
110
- map.set(name, {
111
- ...base,
112
- ...record,
113
- state: record.state === "stale" || record.state === "archived" ? record.state : "active"
114
- });
115
- }
261
+ for (const [name, record] of Object.entries(parsed)) map.set(name, normalizeUsageRecord(record));
116
262
  } catch {}
117
263
  return map;
118
264
  }
265
+ async function loadUsage(root, io = nodeEvolutionIo()) {
266
+ return parseUsage(await io.readText(usageFile(root)));
267
+ }
268
+ /**
269
+ * Atomic read-modify-write on the usage sidecar (rc.50 P2-2): `task` receives
270
+ * the map parsed from the current on-disk state and may mutate it; the result
271
+ * is persisted inside the same transact so a second process sharing DSH_HOME
272
+ * cannot interleave its RMW and lose a counter update. Callers keep their own
273
+ * single-process serialize chain as the second layer.
274
+ */
275
+ async function mutateUsage(root, io, task) {
276
+ await transactIo(io, usageFile(root), async (current) => {
277
+ if (current !== null) try {
278
+ JSON.parse(current);
279
+ } catch {
280
+ return current;
281
+ }
282
+ const map = parseUsage(current);
283
+ await task(map);
284
+ return JSON.stringify(Object.fromEntries(map.entries()), null, 2);
285
+ });
286
+ }
287
+ /**
288
+ * Curator-owned usage fields (rc.67 K-2): the curator writes ONLY this set —
289
+ * lifecycle state, archive stamp, the six-factor quality pair, and the
290
+ * marker-mirrored pin flag. Counter and activity-stamp fields belong to the
291
+ * tool-telemetry side (skill-usage / tool-skill-manage), which bumps them
292
+ * through its own transact-backed RMW. A whole-record overwrite by either
293
+ * side would clobber the other side's concurrent increment, so cross-side
294
+ * folds copy this set only.
295
+ */
296
+ function applyCuratorFields(disk, curated) {
297
+ disk.state = curated.state;
298
+ disk.archived_at = curated.archived_at;
299
+ disk.quality_score = curated.quality_score;
300
+ disk.quality_warn = curated.quality_warn;
301
+ disk.pinned = curated.pinned;
302
+ }
303
+ /**
304
+ * Fold a curator run-start snapshot onto the current on-disk map (rc.67 K-2):
305
+ * each curated record is projected onto its disk peer by copying only the
306
+ * curator-owned fields, so a concurrent tool-side bump between snapshot and
307
+ * save survives. Records absent from the snapshot are left untouched; a
308
+ * curated record with no disk peer is seeded from the snapshot.
309
+ */
310
+ function foldCuratorFields(disk, curated) {
311
+ for (const [name, record] of curated) {
312
+ const diskRecord = disk.get(name);
313
+ if (diskRecord) applyCuratorFields(diskRecord, record);
314
+ else disk.set(name, { ...record });
315
+ }
316
+ }
119
317
  async function saveUsage(root, map, io = nodeEvolutionIo()) {
120
318
  const obj = Object.fromEntries(map.entries());
121
319
  await io.writeText(usageFile(root), JSON.stringify(obj, null, 2));
@@ -155,15 +353,174 @@ function latestActivityAt(record) {
155
353
  if (values.length === 0) return null;
156
354
  return values.sort().reverse()[0] ?? null;
157
355
  }
356
+ /**
357
+ * Curator suppression sidecar: built-in skills the curator has archived stay
358
+ * suppressed across re-seeds, so the lifecycle never fights a re-created
359
+ * bundled skill. Best-effort load/save, mirroring the usage sidecar posture.
360
+ * Versioned shape ({ version, names }) with legacy plain-array compat.
361
+ */
362
+ const SUPPRESSED_FILE_VERSION = 1;
363
+ function suppressedFile(root) {
364
+ return join(root, ".curator-suppressed.json");
365
+ }
366
+ async function loadSuppressedNames(root, io = nodeEvolutionIo()) {
367
+ return parseSuppressed(await io.readText(suppressedFile(root)));
368
+ }
369
+ function parseSuppressed(raw) {
370
+ if (raw === null) return /* @__PURE__ */ new Set();
371
+ try {
372
+ const parsed = JSON.parse(raw);
373
+ const names = Array.isArray(parsed) ? parsed : typeof parsed === "object" && parsed !== null && Array.isArray(parsed.names) ? parsed.names : [];
374
+ return new Set(names.filter((entry) => typeof entry === "string"));
375
+ } catch {
376
+ return /* @__PURE__ */ new Set();
377
+ }
378
+ }
379
+ async function saveSuppressedNames(root, names, io = nodeEvolutionIo()) {
380
+ await io.writeText(suppressedFile(root), JSON.stringify({
381
+ version: 1,
382
+ names: [...names].sort()
383
+ }, null, 2));
384
+ }
385
+ /**
386
+ * Atomic read-modify-write on the suppression sidecar (rc.50 P2-2): `task`
387
+ * receives the set parsed from the current on-disk state and may mutate it;
388
+ * the result is persisted inside the same transact so a second process
389
+ * sharing DSH_HOME cannot interleave its RMW. Best-effort posture unchanged.
390
+ */
391
+ async function updateSuppressedNames(root, io, task) {
392
+ await transactIo(io, suppressedFile(root), async (current) => {
393
+ if (current !== null) try {
394
+ JSON.parse(current);
395
+ } catch {
396
+ return current;
397
+ }
398
+ const names = parseSuppressed(current);
399
+ await task(names);
400
+ return JSON.stringify({
401
+ version: 1,
402
+ names: [...names].sort()
403
+ }, null, 2);
404
+ });
405
+ }
406
+ //#endregion
407
+ //#region lib/types/constants.js
408
+ /**
409
+ * Shared constants for the dsh-evolution plugin family.
410
+ *
411
+ * Two classes of value live here, deliberately separated by section so future
412
+ * edits do not blur the semantic boundary:
413
+ *
414
+ * 1. **Fixed protocol/format/security invariants** — changing these breaks an
415
+ * on-disk format, a naming/format contract, a path-security boundary, or a
416
+ * cross-component invariant. They are NOT exposed as deployment config.
417
+ *
418
+ * 2. **Cross-package shared tunable defaults** — the same semantic default is
419
+ * read (with a config override path) by more than one package (e.g.
420
+ * `evolution-policy` and `evolution-curator` both default `staleAfterDays`
421
+ * to 30). Centralizing them here means one authoritative default: a config
422
+ * override still applies per package, but the fallback is single-sourced.
423
+ *
424
+ * Package-private tunables (used by exactly one package) stay in that package,
425
+ * not here — see evolution-replay's `DEFAULT_WEIGHTS` and evolution-feedback's
426
+ * threshold, which are intentionally left where they are used.
427
+ * @module @lmzhen/dsh-evolution-core
428
+ */
429
+ /** Skill frontmatter `name` validated for the file name (lowercase + hyphen). */
430
+ const SKILL_NAME_RE = /^[a-z0-9][a-z0-9-]*$/;
431
+ /** Allowed skill support-file subdirectories (path-traversal boundary). */
432
+ const SUPPORT_DIRS = [
433
+ "references",
434
+ "templates",
435
+ "scripts",
436
+ "assets"
437
+ ];
438
+ /** Delimiter between durable memory entries (on-disk storage format). */
439
+ const ENTRY_DELIMITER = "\n§\n";
440
+ /** Built-in skill names the curator must never lifecycle-manage. */
441
+ const PROTECTED_BUILTIN_SKILLS = new Set(["plan"]);
442
+ const MAX_SKILL_NAME_LENGTH = 64;
443
+ const MAX_DESCRIPTION_LENGTH = 1024;
444
+ const MAX_SKILL_CONTENT_CHARS = 1e5;
445
+ const MAX_SKILL_FILE_BYTES = 1048576;
446
+ const DEFAULT_REVIEW_MEMORY_INTERVAL = 10;
447
+ const DEFAULT_REVIEW_SKILL_INTERVAL = 10;
448
+ /** Skill-review completion channel trigger mode: 'cadence' | 'completion' | 'both'. */
449
+ const DEFAULT_SKILL_REVIEW_TRIGGER = "both";
450
+ /** Cumulative session tool calls before a session counts as "proven long" for the completion channel. */
451
+ const DEFAULT_SKILL_REVIEW_COMPLETION_MIN_TOOL_CALLS = 20;
452
+ const DEFAULT_SUBSTANTIVE_MIN_TOOL_CALLS = 3;
453
+ const DEFAULT_SUBSTANTIVE_MIN_USER_CHARS = 200;
454
+ const DEFAULT_SUBSTANTIVE_MIN_AGENT_CHARS = 500;
455
+ const DEFAULT_MAX_OPS_PER_PLAN = 32;
456
+ const DEFAULT_CURATOR_INTERVAL_HOURS = 168;
457
+ const DEFAULT_MIN_IDLE_HOURS = 2;
458
+ const DEFAULT_STALE_AFTER_DAYS = 30;
459
+ const DEFAULT_ARCHIVE_AFTER_DAYS = 90;
460
+ const DEFAULT_MEMORY_CHAR_LIMIT = 2200;
461
+ const DEFAULT_USER_CHAR_LIMIT = 1375;
462
+ /** Consolidation-failure backoff cap, shared by MemoryStore and memory-files' Config default. */
463
+ const DEFAULT_CONSOLIDATION_FAILURES = 3;
464
+ const DEFAULT_SKILL_CONTENT_CHARS = 1e5;
465
+ //#endregion
466
+ //#region lib/types/gates.js
467
+ /**
468
+ * The control-plane protection sets, held once and queried everywhere
469
+ * (decision B, rc.44 plan M2): the lifecycle engine, the scope view, the LLM
470
+ * nomination gate and the control-plane consolidate all answer "is this name
471
+ * off limits — and why" from the same instance, so the gate sets can never
472
+ * drift apart the way the three pre-rc.46 implementations did.
473
+ *
474
+ * Scope boundary: a GateSet covers NAME-SET protections only. Marker-based
475
+ * protections (pinned / bundled / hub-installed) are file markers resolved by
476
+ * `SkillLibrary.writeProtection` / `deleteProtection` — they depend on the
477
+ * filesystem and the write origin, not on a name list.
478
+ * @module @lmzhen/dsh-evolution-core
479
+ */
480
+ var EvolutionGateSet = class {
481
+ exclude;
482
+ referenced;
483
+ suppressed;
484
+ constructor(inputs = {}) {
485
+ this.exclude = inputs.exclude ?? /* @__PURE__ */ new Set();
486
+ this.referenced = inputs.referenced ?? /* @__PURE__ */ new Set();
487
+ this.suppressed = inputs.suppressed ?? /* @__PURE__ */ new Set();
488
+ }
489
+ /**
490
+ * The first protection blocking this name, or null. Any hit blocks — the
491
+ * order is diagnostic only, so a name in two sets reports the first.
492
+ */
493
+ blockReason(name) {
494
+ if (this.exclude.has(name)) return "excluded";
495
+ if (this.referenced.has(name)) return "referenced";
496
+ if (this.suppressed.has(name)) return "suppressed";
497
+ if (PROTECTED_BUILTIN_SKILLS.has(name)) return "protected-builtin";
498
+ return null;
499
+ }
500
+ isBlocked(name) {
501
+ return this.blockReason(name) !== null;
502
+ }
503
+ };
504
+ /** Build a GateSet from the curator-style config field names. */
505
+ function createGateSet(config) {
506
+ return new EvolutionGateSet({
507
+ exclude: config.excludeSkillNames,
508
+ referenced: config.referencedSkillNames,
509
+ suppressed: config.suppressedNames
510
+ });
511
+ }
158
512
  //#endregion
159
513
  //#region lib/types/curator.js
160
514
  /**
161
515
  * Deterministic skill curator: active → stale → archived transitions.
162
- * Pure function; file moves are performed by SkillLibrary.
516
+ * Pure function with one deliberate side effect: records in the passed
517
+ * `usage` map are MUTATED (state/archived_at) to carry the transition — the
518
+ * caller owns the map and decides whether to clone first (dry-run) or persist
519
+ * after. File moves are performed by SkillLibrary.
163
520
  */
164
- const PROTECTED_BUILTIN_SKILLS = new Set(["plan"]);
165
521
  function buildCuratorRunReport(input) {
166
522
  return {
523
+ schemaVersion: 1,
167
524
  runId: input.runId,
168
525
  startedAt: input.startedAt,
169
526
  finishedAt: input.finishedAt,
@@ -172,25 +529,145 @@ function buildCuratorRunReport(input) {
172
529
  archiveCandidates: [...input.archiveCandidates],
173
530
  archived: [...input.archived],
174
531
  failed: [...input.failed],
175
- ...input.snapshotPath === void 0 ? {} : { snapshotPath: input.snapshotPath }
532
+ ...input.consolidated === void 0 ? {} : { consolidated: [...input.consolidated] },
533
+ ...input.snapshotPath === void 0 ? {} : { snapshotPath: input.snapshotPath },
534
+ ...input.llmReviewEnabled === void 0 ? {} : { llmReviewEnabled: input.llmReviewEnabled }
535
+ };
536
+ }
537
+ /**
538
+ * Render a curator run report as a compact human-readable markdown digest
539
+ * (G6): run metadata first, then the notable sections (archived / failed /
540
+ * stale candidates / LLM nominations).
541
+ */
542
+ function renderCuratorReportMarkdown(report) {
543
+ const lines = [
544
+ `# Curator run ${report.runId}`,
545
+ "",
546
+ `- **Started** ${report.startedAt}`,
547
+ `- **Finished** ${report.finishedAt}`,
548
+ `- **Stale candidates**: ${report.staleCandidates.length}`,
549
+ `- **LLM nominations**: ${report.llmNominations.length}`,
550
+ `- **Archived**: ${report.archived.length}`,
551
+ `- **Failed**: ${report.failed.length}`,
552
+ ...report.snapshotPath === void 0 ? [] : [`- **Snapshot**: ${report.snapshotPath}`],
553
+ ...report.llmReviewEnabled === void 0 ? [] : [`- **llmReview**: ${report.llmReviewEnabled}`]
554
+ ];
555
+ const section = (title, items) => items.length === 0 ? [] : [
556
+ "",
557
+ `## ${title}`,
558
+ "",
559
+ ...items.map((item) => `- ${item}`)
560
+ ];
561
+ return [
562
+ ...lines,
563
+ ...section("Archived", report.archived.map((item) => `${item.name} (${item.reason})`)),
564
+ ...section("Failed", report.failed.map((item) => `${item.name}: ${item.reason}`)),
565
+ ...section("Stale candidates", report.staleCandidates),
566
+ ...section("LLM nominations", report.llmNominations),
567
+ ""
568
+ ].join("\n");
569
+ }
570
+ const NOMINATION_NAME_RE = /^[a-z0-9][a-z0-9-]*$/;
571
+ /**
572
+ * Parse the curator LLM's YAML nomination block (consolidations + prunings).
573
+ * Line-oriented and lenient by design: the LLM output is advisory, every name
574
+ * is re-validated against the tree before any file move happens downstream.
575
+ */
576
+ function parseCuratorNominations(text) {
577
+ const prunings = [];
578
+ const consolidations = [];
579
+ let section = null;
580
+ let currentFrom = "";
581
+ for (const line of text.split("\n")) {
582
+ const consolidated = /^\s*-\s*from:\s*([a-z0-9][a-z0-9-]*)\s*$/.exec(line);
583
+ if (consolidated) {
584
+ section = "consolidations";
585
+ currentFrom = consolidated[1] ?? "";
586
+ continue;
587
+ }
588
+ const into = /^\s*into:\s*([a-z0-9][a-z0-9-]*)\s*$/.exec(line);
589
+ if (into) {
590
+ const intoName = into[1] ?? "";
591
+ if (section === "consolidations" && currentFrom !== "" && currentFrom !== intoName) consolidations.push({
592
+ from: currentFrom,
593
+ into: intoName
594
+ });
595
+ currentFrom = "";
596
+ continue;
597
+ }
598
+ const pruned = /^\s*-\s*name:\s*([a-z0-9][a-z0-9-]*)\s*$/.exec(line);
599
+ if (pruned) {
600
+ section = "prunings";
601
+ const name = pruned[1];
602
+ if (name) prunings.push(name);
603
+ }
604
+ }
605
+ const valid = (name) => NOMINATION_NAME_RE.test(name);
606
+ return {
607
+ prunings: prunings.filter(valid),
608
+ consolidations: consolidations.filter((item) => valid(item.from) && valid(item.into))
609
+ };
610
+ }
611
+ /**
612
+ * The lifecycle-candidate gate, shared by the transition engine and the scope
613
+ * view so the two can never disagree: records failing ANY of these gates are
614
+ * outside the managed scope.
615
+ */
616
+ function lifecycleCandidate(name, record, config, bundled, gates = createGateSet(config)) {
617
+ if (record.pinned) return false;
618
+ if (gates.isBlocked(name)) return false;
619
+ if (!(record.created_by === "agent" || config.manageUnmanaged === true) && !(config.pruneBuiltins === true && bundled)) return false;
620
+ if (record.state === "archived") return false;
621
+ return true;
622
+ }
623
+ /**
624
+ * Read-only scope classification, derived from the SAME gate the transition
625
+ * engine uses (`lifecycleCandidate`), so the view always predicts what a
626
+ * curator pass may touch. `protectedNames` carries the marker info the usage
627
+ * records lack (bundled / hub-installed / pinned from `SkillLibrary.list()`).
628
+ */
629
+ function computeScopeView(usage, config, protectedNames, gates) {
630
+ const managed = [];
631
+ const watched = [];
632
+ const qualityWarned = [];
633
+ const exempted = [];
634
+ const protectedSet = /* @__PURE__ */ new Set();
635
+ const gateSet = gates ?? createGateSet(config);
636
+ for (const [name, record] of usage) {
637
+ if (gateSet.exclude.has(name) || gateSet.referenced.has(name)) {
638
+ exempted.push(name);
639
+ continue;
640
+ }
641
+ const bundled = config.bundledNames?.has(name) === true;
642
+ const suppressed = gateSet.suppressed.has(name);
643
+ if (record.pinned || bundled || suppressed || protectedNames?.has(name) === true) protectedSet.add(name);
644
+ if (lifecycleCandidate(name, record, config, bundled, gateSet)) {
645
+ managed.push(name);
646
+ if (record.state === "stale" || record.quality_warn === true) watched.push(name);
647
+ if (record.quality_warn === true) qualityWarned.push(name);
648
+ }
649
+ }
650
+ return {
651
+ managed: managed.sort(),
652
+ watched: watched.sort(),
653
+ qualityWarned: qualityWarned.sort(),
654
+ exempted: exempted.sort(),
655
+ protected: [...protectedSet].sort()
176
656
  };
177
657
  }
178
658
  function daysSince(iso, created, now) {
179
659
  return (now - new Date(iso ?? created).getTime()) / 864e5;
180
660
  }
181
- function computeLifecycleTransitions(usage, config, now = /* @__PURE__ */ new Date()) {
661
+ function computeLifecycleTransitions(usage, config, now = /* @__PURE__ */ new Date(), gates) {
182
662
  const result = {
183
663
  transitions: [],
184
664
  archive: [],
185
665
  reactivate: [],
186
666
  markStale: []
187
667
  };
668
+ const gateSet = gates ?? createGateSet(config);
188
669
  for (const [name, record] of usage) {
189
- if (record.pinned) continue;
190
- if (config.excludeSkillNames?.has(name)) continue;
191
- if (record.created_by !== "agent" && config.manageUnmanaged !== true) continue;
192
- if (PROTECTED_BUILTIN_SKILLS.has(name)) continue;
193
- if (record.state === "archived") continue;
670
+ if (!lifecycleCandidate(name, record, config, config.bundledNames?.has(name) === true, gateSet)) continue;
194
671
  const age = daysSince(null, record.created_at, now.getTime());
195
672
  if (record.use_count === 0 && age < config.staleAfterDays) continue;
196
673
  const idle = daysSince(latestActivityAt(record), record.created_at, now.getTime());
@@ -242,6 +719,426 @@ function computeLifecycleTransitions(usage, config, now = /* @__PURE__ */ new Da
242
719
  return result;
243
720
  }
244
721
  //#endregion
722
+ //#region lib/types/evolution-events.js
723
+ /**
724
+ * Self-evolution event log (rc.68): an append-only sidecar under
725
+ * `$DSH_HOME/evolution/events.json` that is the single source of truth for
726
+ * the self-improvement loop. Feedback increments and learn actions share one
727
+ * ordered timeline (`seq` is the ordering key), so "feedback before/after a
728
+ * learn on target X" is answerable. The aggregate `feedback.json` is a
729
+ * rebuildable boot cache, never the truth.
730
+ *
731
+ * The malformed-refusal posture matches the whole sidecar family (rc.65): an
732
+ * append NEVER rewrites a corrupt log — the bytes stay untouched.
733
+ */
734
+ const EVENT_LOG_VERSION = 1;
735
+ function eventsFile(home) {
736
+ return join(home, "evolution", "events.json");
737
+ }
738
+ function isEventRecord(event) {
739
+ return typeof event === "object" && event !== null && typeof event.seq === "number";
740
+ }
741
+ /**
742
+ * Parse an event log body. A missing file, a whitespace-only file (rc.69:
743
+ * rebuildable, NOT malformed) or a corrupt one reads as empty; corrupt content
744
+ * is still refused on append, never overwritten.
745
+ *
746
+ * Per-entry normalization (rc.70 F-1): entries without a numeric `seq` are
747
+ * skipped here and dropped at the next append — valid entries survive, the
748
+ * damaged record is the only loss (self-heal semantics, matching the usage
749
+ * sidecar's per-field normalization on read).
750
+ */
751
+ function parseEvolutionEvents(raw) {
752
+ if (raw === null || raw.trim() === "") return [];
753
+ try {
754
+ const parsed = JSON.parse(raw);
755
+ if (!Array.isArray(parsed.events)) return [];
756
+ return parsed.events.filter(isEventRecord);
757
+ } catch {
758
+ return [];
759
+ }
760
+ }
761
+ /**
762
+ * Append one event under the write lock (rc.68): `seq` = current max + 1
763
+ * computed inside the transact, so two processes appending concurrently never
764
+ * collide. A malformed log is refused (bytes preserved) and the append fails.
765
+ * Returns the assigned seq.
766
+ */
767
+ async function appendEvolutionEvent(io, path, event) {
768
+ let assigned = 0;
769
+ await transactIo(io, path, (current) => {
770
+ if (current !== null && current.trim() !== "") try {
771
+ JSON.parse(current);
772
+ } catch {
773
+ return Promise.resolve(current);
774
+ }
775
+ const events = parseEvolutionEvents(current);
776
+ const maxSeq = events.reduce((max, entry) => Math.max(max, entry.seq), 0);
777
+ const record = {
778
+ ...event,
779
+ seq: maxSeq + 1,
780
+ at: (/* @__PURE__ */ new Date()).toISOString()
781
+ };
782
+ assigned = record.seq;
783
+ return Promise.resolve(JSON.stringify({
784
+ version: 1,
785
+ events: [...events, record]
786
+ }, null, 2));
787
+ });
788
+ if (assigned === 0) throw new Error(`evolution event log is malformed and was not touched: ${path}`);
789
+ return assigned;
790
+ }
791
+ /** Read the event log; a missing/whitespace-only file reads as empty,
792
+ * corrupt content is flagged (and refused on append). */
793
+ async function readEvolutionEvents(io, path) {
794
+ const raw = await io.readText(path);
795
+ if (raw === null || raw.trim() === "") return {
796
+ events: [],
797
+ malformed: false
798
+ };
799
+ try {
800
+ const parsed = JSON.parse(raw);
801
+ if (!Array.isArray(parsed.events)) return {
802
+ events: [],
803
+ malformed: false
804
+ };
805
+ return {
806
+ events: parsed.events.filter(isEventRecord),
807
+ malformed: false
808
+ };
809
+ } catch {
810
+ return {
811
+ events: [],
812
+ malformed: true
813
+ };
814
+ }
815
+ }
816
+ //#endregion
817
+ //#region lib/types/prompts.js
818
+ /**
819
+ * Review and curation prompts adapted from Hermes Agent
820
+ * `agent/background_review.py`, `agent/curator.py`, and
821
+ * `agent/learn_prompt.py`, with tool names translated to the DSH-native
822
+ * catalog (`memory`, `skill_manage`, `skill`, `bash`, `str_replace_editor`).
823
+ *
824
+ * Alignment policy (2026-08-29): the OPERATIONAL steps and instructions the
825
+ * model follows mirror the Hermes originals structurally (signal list,
826
+ * preference order, support-file taxonomy, curator package integrity,
827
+ * consolidated/pruned reporting block). Tool and platform differences are
828
+ * DSH-adapted (native tool names, pinned-within-review semantics, this
829
+ * platform's index cap), and DSH-only additions are marked as such.
830
+ *
831
+ * Every prompt is pinned in a versioned bundle. Review workers verify the
832
+ * bundle digest before spending a model call, so a partially-patched
833
+ * deployment fails closed instead of silently running a truncated prompt.
834
+ */
835
+ /**
836
+ * Prompt bundle identity. Bump both id and version whenever a prompt's text
837
+ * changes semantically: the bundle digest is the fail-closed signal for
838
+ * review workers, so a stale id across deployments must be distinguishable.
839
+ */
840
+ const PROMPT_BUNDLE_ID = "dsh-evolution@7";
841
+ const PROMPT_BUNDLE_VERSION = 7;
842
+ const MEMORY_REVIEW_PROMPT = `[Auto-review — Memory]
843
+ Review the conversation above and consider saving to memory if appropriate.
844
+
845
+ Focus on:
846
+ 1. Has the user revealed things about themselves — persona, desires, preferences, or personal details worth remembering?
847
+ 2. Has the user expressed expectations about how you should behave, their work style, or ways they want you to operate?
848
+
849
+ If something stands out, save it using the memory tool.
850
+ If nothing is worth saving, just say "Nothing to save." and stop.`;
851
+ const SKILL_REVIEW_PROMPT = `[Auto-review — Skills]
852
+ Review the conversation above and update the skill library. Be ACTIVE — most sessions produce at least one skill update, even if small. A pass that does nothing is a missed learning opportunity, not a neutral outcome.
853
+
854
+ Target shape of the library: CLASS-LEVEL skills, each with a rich SKILL.md and a references/ directory for session-specific detail. Not a long flat list of narrow one-session-one-skill entries. This shapes HOW you update, not WHETHER you update.
855
+
856
+ Signals to look for (any one of these warrants action):
857
+ • User corrected your style, tone, format, legibility, or verbosity. Frustration signals like 'stop doing X', 'this is too verbose', 'don't format like this', 'why are you explaining', 'just give me the answer', 'you always do Y and I hate it', or an explicit 'remember this' are FIRST-CLASS skill signals, not just memory signals. Update the relevant skill(s) to embed the preference so the next session starts already knowing.
858
+ • User corrected your workflow, approach, or sequence of steps. Encode the correction as a pitfall or explicit step in the skill that governs that class of task.
859
+ • Non-trivial technique, fix, workaround, debugging path, or tool-usage pattern emerged that a future session would benefit from. Capture it.
860
+ • A skill that got loaded or consulted this session turned out to be wrong, missing a step, or outdated. Patch it NOW.
861
+
862
+ Read-before-write (enforced by this channel): update, patch, delete, or write support files ONLY into skills you loaded or read in THIS session — ops on unread skills are dropped; CREATE of a brand-new umbrella is the only exception.
863
+
864
+ Preference order — prefer the earliest action that fits, but do pick one when a signal above fired:
865
+ 1. UPDATE A CURRENTLY-LOADED SKILL. Look back through the conversation for skills the user loaded or you read. If any of them covers the territory of the new learning, PATCH that one first. It is the skill that was in play, so it's the right one to extend.
866
+ 2. UPDATE AN EXISTING UMBRELLA. If no loaded skill fits but an existing class-level skill does, patch it. Add a subsection, a pitfall, or broaden a trigger.
867
+ 3. ADD A SUPPORT FILE under an existing umbrella. Skills can be packaged with three kinds of support files — use the right directory per kind:
868
+ • references/<topic>.md — session-specific detail (error transcripts, reproduction recipes, provider quirks) AND condensed knowledge banks: quoted research, API docs, external authoritative excerpts, or domain notes you found while working on the problem. Write it concise and for the value of the task, not as a full mirror of upstream docs.
869
+ • templates/<name>.<ext> — starter files meant to be copied and modified (boilerplate configs, scaffolding, a known-good example the agent can reproduce with modifications).
870
+ • scripts/<name>.<ext> — statically re-runnable actions the skill can invoke directly (verification scripts, fixture generators, deterministic probes, anything the agent should run rather than hand-type each time).
871
+ Add support files via skill_manage action=write_file with file_path starting 'references/', 'templates/', or 'scripts/'. The umbrella's SKILL.md should gain a one-line pointer to any new support file so future agents know it exists.
872
+ 4. CREATE A NEW CLASS-LEVEL UMBRELLA SKILL when no existing skill covers the class. The name MUST be at the class level. The name MUST NOT be a specific PR number, error string, feature codename, library-alone name, or 'fix-X / debug-Y / audit-Z-today' session artifact. If the proposed name only makes sense for today's task, it's wrong — fall back to (1), (2), or (3).
873
+
874
+ User-preference embedding (important): when the user expressed a style/format/workflow preference, the update belongs in the SKILL.md body, not just in memory. Memory captures 'who the user is and what the current situation and state of your operations are'; skills capture 'how to do this class of task for this user'. When they complain about how you handled a task, the skill that governs that task needs to carry the lesson.
875
+
876
+ If you notice two existing skills that overlap, note it in your reply — the background curator handles consolidation at scale.
877
+
878
+ Two-tier deposition discipline (DSH addition, same spirit as the umbrella rule): before writing, classify the knowledge:
879
+ • PATTERN (reusable — symptom → mechanism → fix → verification, still valuable next session) belongs in the SKILL.md body.
880
+ • LOG (one-off — commit SHAs, npm/profile states, what this release changed, this session's process narrative) belongs in a references/ file, never the body. Body density IS reuse rate. Keep new entries tight: a pattern fits in 2-8 physical lines; prefer changing the current-state pointer over appending history.
881
+
882
+ Protected skills (DO NOT edit these):
883
+ • Bundled skills (shipped with the platform).
884
+ • Hub-installed skills (installed from a hub).
885
+ Pinned skills are read-only to THIS background review pass — the pinned write guard refuses background changes, so only the foreground may update or archive them. Foreground and delegated-subagent writes to pinned skills remain allowed.
886
+ If the only skills that need updating are protected, say 'Nothing to save.' and stop.
887
+
888
+ Do NOT capture (these become persistent self-imposed constraints that bite you later when the environment changes):
889
+ • Environment-dependent failures: missing binaries, fresh-install errors, post-migration path mismatches, 'command not found', unconfigured credentials, uninstalled packages. The user can fix these — they are not durable rules.
890
+ • Negative claims about tools or features ('browser tools do not work', 'X tool is broken', 'cannot use Y'). These harden into refusals the agent cites against itself for months after the actual problem was fixed.
891
+ • Session-specific transient errors that resolved before the conversation ended. If retrying worked, the lesson is the retry pattern, not the original failure.
892
+ • One-off task narratives. A user asking 'summarize today's market' or 'analyze this PR' is not a class of work that warrants a skill.
893
+
894
+ If a tool failed because of setup state, capture the FIX (install command, config step, env var to set) under an existing setup or troubleshooting skill — never 'this tool does not work' as a standalone constraint.
895
+
896
+ 'Nothing to save.' is a real option but should NOT be the default. If the session ran smoothly with no corrections and produced no new technique, just say 'Nothing to save.' and stop. Otherwise, act.`;
897
+ const COMBINED_REVIEW_PROMPT = `[Auto-review]
898
+ Review the conversation above and update two things:
899
+
900
+ **Memory**: who the user is. Did the user reveal persona, desires, preferences, personal details, or expectations about how you should behave? Save facts about the user and durable preferences with the memory tool.
901
+
902
+ **Skills**: how to do this class of task. Be ACTIVE — most sessions produce at least one skill update. A pass that does nothing is a missed learning opportunity, not a neutral outcome.
903
+
904
+ Target shape of the skill library: CLASS-LEVEL skills with a rich SKILL.md and a references/ directory for session-specific detail. Not a long flat list of narrow one-session-one-skill entries.
905
+
906
+ Signals that warrant a skill update (any one is enough):
907
+ • User corrected your style, tone, format, legibility, verbosity, or approach. Frustration is a FIRST-CLASS skill signal, not just a memory signal. 'stop doing X', 'don't format like this', 'I hate when you Y' — embed the lesson in the skill that governs that task so the next session starts fixed.
908
+ • Non-trivial technique, fix, workaround, or debugging path emerged.
909
+ • A skill that was loaded or consulted turned out wrong, missing, or outdated — patch it now.
910
+
911
+ Read-before-write (enforced by this channel): update, patch, delete, or write support files ONLY into skills you loaded or read in THIS session — ops on unread skills are dropped; CREATE of a brand-new umbrella is the only exception.
912
+
913
+ Preference order for skills — pick the earliest that fits:
914
+ 1. UPDATE A CURRENTLY-LOADED SKILL. Check what skills were loaded or read in the conversation. If one of them covers the learning, PATCH it first. It was in play; it's the right place.
915
+ 2. UPDATE AN EXISTING UMBRELLA. Patch it.
916
+ 3. ADD A SUPPORT FILE under an existing umbrella via skill_manage action=write_file. Three kinds: references/<topic>.md for session-specific detail OR condensed knowledge banks (quoted research, API docs excerpts, domain notes) written concise and task-focused; templates/<name>.<ext> for starter files meant to be copied and modified; scripts/<name>.<ext> for statically re-runnable actions (verification, fixture generators, probes). Add a one-line pointer in SKILL.md so future agents find them.
917
+ 4. CREATE A NEW CLASS-LEVEL UMBRELLA when nothing exists. Name at the class level — NOT a PR number, error string, codename, library-alone name, or 'fix-X / debug-Y' session artifact. If the name only fits today's task, fall back to (1), (2), or (3).
918
+
919
+ Two-tier deposition discipline (DSH addition): classify before writing — PATTERN (symptom → mechanism → fix → verification) goes in the SKILL.md body; LOG (commit SHAs, npm/profile states, this release's change list, this session's narrative) goes in a references/ file. Body density IS reuse rate; a pattern fits in 2-8 physical lines.
920
+
921
+ User-preference embedding: when the user complains about how you handled a task, update the skill that governs that task — memory alone isn't enough. Memory says 'who the user is and what the current situation and state of your operations are'; skills say 'how to do this class of task for this user'. Both should carry user-preference lessons when relevant.
922
+
923
+ If you notice overlapping existing skills, mention it — the background curator handles consolidation.
924
+
925
+ Protected skills (DO NOT edit these):
926
+ • Bundled skills (shipped with the platform).
927
+ • Hub-installed skills (installed from a hub).
928
+ Pinned skills are read-only to THIS background review pass — the pinned write guard refuses background changes, so only the foreground may update or archive them. Foreground and delegated-subagent writes to pinned skills remain allowed.
929
+ If the only skills that need updating are protected, say 'Nothing to save.' and stop.
930
+
931
+ Do NOT capture as skills (these become persistent self-imposed constraints that bite you later when the environment changes):
932
+ • Environment-dependent failures: missing binaries, fresh-install errors, post-migration path mismatches, 'command not found', unconfigured credentials, uninstalled packages. The user can fix these — they are not durable rules.
933
+ • Negative claims about tools or features ('browser tools do not work', 'X tool is broken', 'cannot use Y'). These harden into refusals the agent cites against itself for months after the actual problem was fixed.
934
+ • Session-specific transient errors that resolved before the conversation ended. If retrying worked, the lesson is the retry pattern, not the original failure.
935
+ • One-off task narratives. A user asking 'summarize today's market' or 'analyze this PR' is not a class of work that warrants a skill.
936
+
937
+ If a tool failed because of setup state, capture the FIX (install command, config step, env var to set) under an existing setup or troubleshooting skill — never 'this tool does not work' as a standalone constraint.
938
+
939
+ Act on whichever of the two dimensions has real signal. If genuinely nothing stands out on either, say 'Nothing to save.' and stop — but don't reach for that conclusion as a default.`;
940
+ const CURATOR_PROMPT = `You are the skill curator. Maintain a healthy, class-level skill library, not a flat pile of narrow one-session skills.
941
+
942
+ This is an UMBRELLA-BUILDING consolidation pass, not a passive audit and not a duplicate-finder.
943
+
944
+ The goal is a LIBRARY OF CLASS-LEVEL INSTRUCTIONS. A skill collection of many narrow skills where each captures one session's specific bug is a FAILURE of the library. An agent searching skills matches on descriptions, not exact names; one broad umbrella with labeled subsections beats five narrow siblings for discoverability.
945
+
946
+ Right target shape: class-level skills with rich SKILL.md + references/, templates/, scripts/ support files for session-specific detail.
947
+
948
+ Hard rules:
949
+ 1. NEVER hard-delete a skill. Archive (moving to .archive/) is the maximum destructive action; archives are recoverable, deletion is not.
950
+ 2. Do not touch bundled, hub-installed, pinned, or scheduled-task-referenced (referenced) skills. Referenced skills are fully protected — never consolidated, never pruned (there is no scheduled-task reference-rewriting pass; a referenced skill stays in place by design).
951
+ 3. Do not archive recently-created or never-used skills without strong evidence. "use=0" is NOT evidence either way — it only means the trigger has not come up yet. Never archive a never-used skill unless it is at least 30 days old AND its content is genuinely obsolete or fully absorbed elsewhere.
952
+ 4. Do NOT reject consolidation on the grounds that "each skill has a distinct trigger". The right bar is: would a human maintainer write this as N separate skills, or one skill with N labeled subsections? When the answer is the latter, merge.
953
+ 5. Judge overlap on CONTENT, not on usage counters.
954
+ 6. Before archiving a merged skill, ensure its unique content was preserved in the umbrella.
955
+
956
+ How to work:
957
+ 1. Scan the candidate list. Identify PREFIX CLUSTERS — skills sharing a first word or domain keyword. Expected cluster count scales with the library: a large collection may show 10-25 prefix clusters, a small one often has none — a clean "nothing to consolidate" summary is the correct small-library outcome, not a shortage of ambition.
958
+ 2. For each cluster with 2+ members, ask "what is the UMBRELLA CLASS these skills serve?" and consolidate:
959
+ a. MERGE INTO AN EXISTING UMBRELLA (patch a labeled section for each sibling's unique insight, then archive the siblings).
960
+ b. CREATE A NEW UMBRELLA SKILL.md covering the shared workflow with short labeled subsections, then archive the absorbed siblings.
961
+ c. DEMOTE session-specific detail to references/, templates/, or scripts/ under the umbrella. Use the right directory per kind:
962
+ • references/<topic>.md — session-specific detail OR condensed knowledge banks (quoted research, API docs excerpts, domain notes, provider quirks, reproduction recipes) written concise and task-focused.
963
+ • templates/<name>.<ext> — starter files meant to be copied and modified.
964
+ • scripts/<name>.<ext> — statically re-runnable actions (verification scripts, fixture generators, probes).
965
+ 3. Package integrity — not optional: inspect each skill as a COMPLETE directory package, not just SKILL.md. A skill root may include references/, templates/, scripts/, and assets/. If the source skill has support files OR its SKILL.md contains relative links to them, DO NOT flatten only SKILL.md into <umbrella>/references/<old>.md. Choose one safe path instead: keep it as a standalone skill, OR fully merge by re-homing every needed support file into the umbrella's canonical directories AND rewriting the destination instructions to the new paths, OR archive the entire original skill package unchanged. Never leave demoted instructions pointing at files left behind under the old skill directory.
966
+ 4. Flag skills whose NAME is too narrow (contains a PR number, a feature codename, a specific error string, an 'audit'/'diagnosis'/'salvage' session artifact) — they almost always belong as a subsection or support file under a class-level umbrella.
967
+ 5. Iterate. After one consolidation round, scan the remaining set and look for the NEXT umbrella opportunity. Don't stop after 3 merges.
968
+
969
+ You are a NOMINATOR, not an executor: this channel has NO tools. Your single deliverable is the structured YAML block below. Never narrate actions you did not take ("merged", "patched", "archived") — you are proposing, and the deterministic engine executes only names from the candidate pool it gave you. (A future execution view would expose skill_manage; today it does not.)
970
+
971
+ 'keep' is a legitimate decision ONLY when the skill is already a class-level umbrella and none of the proposed merges would improve discoverability. 'This is narrow but distinct from its siblings' is NOT a reason to keep — it's a reason to move it under an umbrella as a subsection or support file.
972
+
973
+ Expected output: real umbrella-ification. Process every obvious cluster. If you end the pass with obvious clusters still untouched, you stopped too early — go back and look at the clusters you left alone.
974
+
975
+ Keep the umbrella body tight and scannable: exact commands, verbatim paths, ~100-200 lines; never invent flags or APIs.
976
+
977
+ When done, write a human summary THEN the structured machine-readable block. The block is the contract: every skill you would move to .archive/ MUST appear in exactly one of the two lists. Return ONLY the YAML block after the summary — no post-block prose. Format EXACTLY:
978
+
979
+ ## Structured summary (required)
980
+ \`\`\`yaml
981
+ consolidations:
982
+ - from: <old-skill-name>
983
+ into: <umbrella-skill-name>
984
+ reason: <one short sentence — why merged, not just 'similar'>
985
+ prunings:
986
+ - name: <skill-name>
987
+ reason: <one short sentence — why archived with no merge target>
988
+ \`\`\`
989
+
990
+ Every skill you would move to .archive/ MUST appear in exactly one of the two lists. If you consolidated X into umbrella Y (patched Y, wrote a references file to Y, or created Y with X's content absorbed), X goes under consolidations with into: Y. If you archived X with no absorption — truly stale, irrelevant, or obsolete — X goes under prunings. Leave a list empty (consolidations: []) if none. Do not omit the block. The block comes AFTER your human-readable summary of clusters processed, patches made, and decisions left alone.`;
991
+ const CURATOR_DRY_RUN_BANNER = `═══════════════════════════════════════════════════════════════
992
+ DRY-RUN — REPORT ONLY. DO NOT MUTATE THE SKILL LIBRARY.
993
+ ═══════════════════════════════════════════════════════════════
994
+
995
+ This is a PREVIEW pass. Follow every instruction above EXCEPT:
996
+ • Do NOT call skill_manage with action=create, update, patch, delete, write_file, or remove_file.
997
+ • Do NOT move, copy, or rewrite any file under the skills tree.
998
+
999
+ Your output IS the deliverable: produce the exact same human-readable summary and YAML block you would on a live run, describing the actions you WOULD take. A reviewer will decide whether to approve a live run.
1000
+
1001
+ If you accidentally take a mutating action, say so explicitly in the summary.`;
1002
+ const COMPLETION_SKILL_REVIEW_PROMPT = `[Auto-review — Skills · task complete]
1003
+ Your current task now appears complete. Before wrapping up, review the approach and update the skill library via skill_manage.
1004
+
1005
+ Follow the skills review policy: be ACTIVE, prefer class-level umbrellas, patch ONLY skills loaded or read this session, and capture non-trivial techniques and user corrections. Do NOT capture environment-dependent failures, negative claims about tools, or one-off task narratives.
1006
+
1007
+ Do NOT modify output files or re-run the task. If you are still mid-task, ignore this.`;
1008
+ /**
1009
+ * System-prompt guidance section (Hermes `SKILLS_GUIDANCE`, DSH-adapted).
1010
+ * Registered as a system-prompt section by tool-skill-manage (it mounts
1011
+ * exactly when `skill_manage` is available — the DSH analogue of Hermes'
1012
+ * `if "skill_manage" in agent.valid_tool_names` condition). Instructs the
1013
+ * model to save/repair skills on its own initiative.
1014
+ */
1015
+ const SKILLS_GUIDANCE = `Skills guidance:
1016
+ • After completing a complex task (5+ tool calls), fixing a tricky error, or discovering a non-trivial workflow, save the approach as a skill with skill_manage so you can reuse it next time.
1017
+ • When using a skill and finding it outdated, incomplete, or wrong, patch it immediately with skill_manage (action='patch') — don't wait to be asked. Skills that aren't maintained become liabilities.`;
1018
+ const PLAN_CHANNEL_NOTE = `
1019
+
1020
+ CHANNEL (subagent): this review channel mounts only the read-only \`skill\` tool — you have NO \`skill_manage\`, NO \`memory\`. Your deliverable is the structured JSON plan below (outputSchema). Describe the patches/creates you RECOMMEND in the plan; never narrate actions you took.`;
1021
+ /** Subagent-channel variant: same review policy, channel-limited deliverable (M-2). */
1022
+ const SKILL_REVIEW_PLAN_PROMPT = `${SKILL_REVIEW_PROMPT}${PLAN_CHANNEL_NOTE}`;
1023
+ /** Subagent-channel variant of the combined review (M-2). */
1024
+ const COMBINED_REVIEW_PLAN_PROMPT = `${COMBINED_REVIEW_PROMPT}${PLAN_CHANNEL_NOTE}`;
1025
+ function reviewPrompt(kind, channel = "agent") {
1026
+ if (kind === "memory") return MEMORY_REVIEW_PROMPT;
1027
+ if (channel === "plan") return kind === "skill" ? SKILL_REVIEW_PLAN_PROMPT : COMBINED_REVIEW_PLAN_PROMPT;
1028
+ if (kind === "skill") return SKILL_REVIEW_PROMPT;
1029
+ return COMBINED_REVIEW_PROMPT;
1030
+ }
1031
+ function sha256(text) {
1032
+ return createHash("sha256").update(text).digest("hex");
1033
+ }
1034
+ function createPromptBundle(prompts) {
1035
+ const canonical = JSON.stringify({
1036
+ id: PROMPT_BUNDLE_ID,
1037
+ version: 7,
1038
+ prompts: Object.fromEntries(Object.entries(prompts).sort())
1039
+ });
1040
+ return Object.freeze({
1041
+ id: PROMPT_BUNDLE_ID,
1042
+ version: 7,
1043
+ prompts: Object.freeze({ ...prompts }),
1044
+ sha256: sha256(canonical)
1045
+ });
1046
+ }
1047
+ const PROMPT_BUNDLE = createPromptBundle({
1048
+ memory: MEMORY_REVIEW_PROMPT,
1049
+ skill: SKILL_REVIEW_PROMPT,
1050
+ combined: COMBINED_REVIEW_PROMPT,
1051
+ skillPlan: SKILL_REVIEW_PLAN_PROMPT,
1052
+ combinedPlan: COMBINED_REVIEW_PLAN_PROMPT,
1053
+ curator: CURATOR_PROMPT,
1054
+ completion: COMPLETION_SKILL_REVIEW_PROMPT,
1055
+ skillsGuidance: SKILLS_GUIDANCE
1056
+ });
1057
+ function verifyPromptBundle(bundle = PROMPT_BUNDLE) {
1058
+ if (bundle.id !== "dsh-evolution@7" || bundle.version !== 7) return false;
1059
+ const canonical = JSON.stringify({
1060
+ id: PROMPT_BUNDLE_ID,
1061
+ version: 7,
1062
+ prompts: Object.fromEntries(Object.entries(bundle.prompts).sort())
1063
+ });
1064
+ return bundle.sha256 === sha256(canonical);
1065
+ }
1066
+ const DSH_AUTHORING_STANDARDS = `Follow the Hermes skill-authoring standards, translated to DSH tools.
1067
+
1068
+ Frontmatter:
1069
+ - name: lowercase-hyphenated, <=64 chars, no spaces.
1070
+ - description: ONE sentence, <=60 characters, ends with a period. State the capability, not the implementation. No marketing words. Do NOT repeat the skill name. Count the characters before saving. If the description contains a colon, wrap the whole value in double quotes.
1071
+ - version: 0.1.0
1072
+ - author: always the literal value "Hermes". NEVER fill it from the environment, git config, or any identity you can probe — an environment-derived name is a privacy leak the user never opted into (skills get shared and published), and the skill names itself as Hermes.
1073
+ - platforms: declare [macos], [linux], and/or [windows] only when the skill is genuinely OS-bound (osascript/apt/systemctl => the matching OS; /proc, signal.SIGKILL => linux; fcntl/termios => POSIX). Prefer fixing it cross-platform first (tempdir, pathlib, pure-Node); omit the field for portable skills.
1074
+ - metadata.hermes.tags: a few Capitalized, Relevant, Tags.
1075
+ - metadata.hermes.related_skills: [a, b] — name sibling skills this one builds on or is referenced by (optional; feeds the quality references factor).
1076
+
1077
+ Body section order (omit only when empty):
1078
+ 1. "# <Human Title>" then a 2-3 sentence intro: what it does, what it does NOT do, key dependency stance.
1079
+ 2. "## When to Use" — concrete trigger phrases.
1080
+ 3. "## Prerequisites" — exact env vars, install steps, credentials.
1081
+ 4. "## How to Run" — canonical invocation framed through DSH tools.
1082
+ 5. "## Quick Reference" — flat command/endpoint list.
1083
+ 6. "## Procedure" — numbered steps with copy-paste-exact commands.
1084
+ 7. "## Pitfalls" — known limits and rate limits.
1085
+ 8. "## Verification" — one check proving the skill worked.
1086
+
1087
+ DSH-tool framing:
1088
+ - Reference DSH tools by name in backticks: \`bash\`, \`str_replace_editor\`, \`write\`, \`skill\`, \`skill_manage\`, \`memory\`.
1089
+ - Do not name wrapped shell utilities when a DSH tool already covers them.
1090
+ - Larger scripts belong under \`scripts/\` (written with \`skill_manage write_file\`) and are referenced from SKILL.md by relative path.
1091
+
1092
+ Quality bar:
1093
+ - Prefer verbatim flags, paths, and APIs from the source. Never invent them.
1094
+ - Keep it tight: ~100 lines simple, ~200 complex.
1095
+ - No router/index/hub skills that only point at other skills.
1096
+ - References go in \`references/\`, templates in \`templates/\`.
1097
+
1098
+ Learn workflow (when the user asks you to learn a reusable skill, or you decide to turn a source/request into one):
1099
+ 1. Gather every source named (files, URLs, "what we just did", pasted notes) with the tools you already have — and treat prose after a source as authoring requirements, not noise.
1100
+ 2. Apply every requirement and constraint from the request to the SKILL.md you author.
1101
+ 3. Author exactly ONE SKILL.md and save it with \`skill_manage\` (action=create); non-trivial scripts go under \`scripts/\`.
1102
+ 4. When done, tell the user the skill name, its category, and a one-line summary of what it captured.`;
1103
+ //#endregion
1104
+ //#region lib/types/learn-prompt.js
1105
+ /**
1106
+ * Open-ended `/evolution learn` prompt builder.
1107
+ *
1108
+ * `learn` is open-ended: the user can name anything they can describe — a
1109
+ * directory of code, an API doc URL, a workflow they just walked the agent
1110
+ * through, or pasted notes. The prompt instructs the live agent to gather the
1111
+ * named sources with its existing tools, then author a single SKILL.md via
1112
+ * `skill_manage` following `DSH_AUTHORING_STANDARDS`. There is no separate
1113
+ * distillation engine and no model-tool footprint.
1114
+ */
1115
+ /**
1116
+ * Build the agent prompt for an open-ended `/evolution learn` request.
1117
+ *
1118
+ * @param userRequest free-text the user gave after `/evolution learn`; an
1119
+ * empty string falls back to "the workflow we just went through".
1120
+ * @returns a complete instruction the agent runs as a normal turn.
1121
+ */
1122
+ function buildLearnPrompt(userRequest) {
1123
+ return [
1124
+ "[/learn] The user wants you to learn a reusable skill from the request below, and save it.",
1125
+ "",
1126
+ "THE REQUEST:",
1127
+ userRequest.trim() || "the workflow we just went through in this conversation — review the steps taken and distill them into a reusable skill",
1128
+ "",
1129
+ "The request is open-ended and may mix two kinds of content, in any order: SOURCES to gather (directories, file paths, URLs, \"what we just did\", pasted notes) AND REQUIREMENTS that shape the skill (what to focus on, what to leave out, scope, naming, the angle to take). Treat EVERY part of the request as load-bearing. In particular, prose that comes after a path or link is NOT incidental — it is the user telling you what they want from that source. A request like `<url> focus on the auth flow, skip the deprecated endpoints` means: gather the URL AND honor \"focus on auth, skip deprecated\" as authoring requirements. Never fetch the first source and ignore the rest.",
1130
+ "",
1131
+ "Do this:",
1132
+ "1. Gather every source the user named, using the tools you already have — reads and searches for local files or directories, web access for URLs, this conversation history if they referred to something you just did, and the text they pasted as-is. If the request is ambiguous about scope, make a reasonable choice and note it; do not stall.",
1133
+ "2. Author ONE SKILL.md, applying every requirement, focus, and constraint in the request — these govern what the SKILL.md covers and emphasizes, not just which sources you read.",
1134
+ "3. Save it with the `skill_manage` tool (action=\"create\"). Pick a sensible category. If the procedure needs a non-trivial script, add it under the skill's `scripts/` with `skill_manage` write_file and reference it by relative path.",
1135
+ "",
1136
+ DSH_AUTHORING_STANDARDS,
1137
+ "",
1138
+ "When done, tell the user the skill name, its category, and a one-line summary of what it captured."
1139
+ ].join("\n");
1140
+ }
1141
+ //#endregion
245
1142
  //#region lib/types/threats.js
246
1143
  /**
247
1144
  * Threat scanning for agent-authored memory and skill content.
@@ -417,10 +1314,12 @@ const SCOPE_ORDER = {
417
1314
  context: 2,
418
1315
  strict: 3
419
1316
  };
1317
+ const NO_SCAN_OPTIONS = {};
420
1318
  /**
421
1319
  * Scan text at `scope`. Patterns are cumulative: `strict` includes all scopes.
1320
+ * `options.excludeLabels` removes matching patterns without changing `scope`.
422
1321
  */
423
- function scanThreats(text, scope = "strict", maxScanChars = 65536) {
1322
+ function scanThreats(text, scope = "strict", maxScanChars = 65536, options = NO_SCAN_OPTIONS) {
424
1323
  const findings = [];
425
1324
  if (ZERO_WIDTH_CHARS.test(text)) findings.push({
426
1325
  label: "unicode_zero_width",
@@ -433,8 +1332,10 @@ function scanThreats(text, scope = "strict", maxScanChars = 65536) {
433
1332
  scope
434
1333
  });
435
1334
  const normalized = text.normalize("NFKC").slice(0, maxScanChars);
1335
+ const excluded = new Set(options.excludeLabels ?? []);
436
1336
  for (const pattern of PATTERNS) {
437
1337
  if (SCOPE_ORDER[pattern.scope] > SCOPE_ORDER[scope]) continue;
1338
+ if (excluded.has(pattern.label)) continue;
438
1339
  if (pattern.regex.test(normalized)) findings.push({
439
1340
  label: pattern.label,
440
1341
  category: pattern.category,
@@ -444,24 +1345,24 @@ function scanThreats(text, scope = "strict", maxScanChars = 65536) {
444
1345
  return findings;
445
1346
  }
446
1347
  /** Blocking policy: any hit blocks. `severity` is deliberately not a gate. */
447
- function evaluateThreat(text, scope = "strict", maxScanChars = 65536) {
448
- const findings = scanThreats(text, scope, maxScanChars);
1348
+ function evaluateThreat(text, scope = "strict", maxScanChars = 65536, options = NO_SCAN_OPTIONS) {
1349
+ const findings = scanThreats(text, scope, maxScanChars, options);
449
1350
  return {
450
1351
  blocked: findings.length > 0,
451
1352
  findings
452
1353
  };
453
1354
  }
454
1355
  /** User-facing block message for memory writes. */
455
- function scanMemoryThreats(text, maxScanChars = 65536) {
456
- const { blocked, findings } = evaluateThreat(text, "strict", maxScanChars);
1356
+ function scanMemoryThreats(text, maxScanChars = 65536, options = NO_SCAN_OPTIONS) {
1357
+ const { blocked, findings } = evaluateThreat(text, "strict", maxScanChars, options);
457
1358
  if (!blocked) return null;
458
1359
  const pattern = findings.find((f) => f.category !== "unicode_obfuscation");
459
1360
  if (pattern) return `Blocked by security scan (${pattern.label}). Rephrase without instruction-like language.`;
460
1361
  return "Blocked by security scan: invisible or potentially malicious Unicode detected.";
461
1362
  }
462
1363
  /** User-facing block message for skill content writes. */
463
- function scanContentThreats(text, maxScanChars = 65536) {
464
- const { blocked, findings } = evaluateThreat(text, "strict", maxScanChars);
1364
+ function scanContentThreats(text, maxScanChars = 65536, options = NO_SCAN_OPTIONS) {
1365
+ const { blocked, findings } = evaluateThreat(text, "strict", maxScanChars, options);
465
1366
  if (!blocked) return null;
466
1367
  return `Blocked by security scan (${findings[0]?.label ?? "unknown"}). This content appears to contain potentially malicious instructions.`;
467
1368
  }
@@ -471,7 +1372,39 @@ function scanContentThreats(text, maxScanChars = 65536) {
471
1372
  * File-backed durable memory with Hermes-compatible semantics.
472
1373
  * Stores are MEMORY.md and USER.md under $DSH_HOME/memories (~/.dsh/memories).
473
1374
  */
474
- const ENTRY_DELIMITER = "\n§\n";
1375
+ /**
1376
+ * Read-guard factor: a memory file larger than this multiple of its target's
1377
+ * char limit is treated as externally corrupted and skipped instead of being
1378
+ * read whole (aligned with claw `tools/memory.ts` size guard, which uses the
1379
+ * same 10× bound around a file that should never exceed the store limit).
1380
+ */
1381
+ const READ_GUARD_FACTOR = 10;
1382
+ /**
1383
+ * Consolidation-failure backoff window (package-private, rc.42 audit P2-1):
1384
+ * only failures inside the window count toward `maxConsolidationFailures`.
1385
+ * The store cannot observe turn boundaries, so the model-facing "this turn"
1386
+ * phrasing is approximated with ten minutes — generous enough to cover one
1387
+ * turn's retry loop, short enough that a failure yesterday never makes today's
1388
+ * first refusal say "stop retrying".
1389
+ */
1390
+ const FAILURE_WINDOW_MS = 10 * 6e4;
1391
+ /**
1392
+ * Recoverable-error preview bounds (B-line G5, Hermes `_previews` parity):
1393
+ * failed replace/remove/batch calls echo the current entries so the model can
1394
+ * self-recover without re-reading the store. Bounded to five entries of eighty
1395
+ * characters each; package-private because it is an error-message shape, not a
1396
+ * behavior switch.
1397
+ */
1398
+ const ERROR_PREVIEW_ENTRIES = 5;
1399
+ const ERROR_PREVIEW_WIDTH = 80;
1400
+ function previewEntries(entries) {
1401
+ if (entries.length === 0) return "";
1402
+ const shown = entries.slice(0, ERROR_PREVIEW_ENTRIES).map((entry) => {
1403
+ return `- ${entry.length > ERROR_PREVIEW_WIDTH ? `${entry.slice(0, ERROR_PREVIEW_WIDTH)}…` : entry}`;
1404
+ });
1405
+ const more = entries.length > ERROR_PREVIEW_ENTRIES ? `\n (+${entries.length - ERROR_PREVIEW_ENTRIES} more)` : "";
1406
+ return `\n\nCurrent entries (preview):\n${shown.join("\n")}${more}`;
1407
+ }
475
1408
  function memoryRoot(env = process.env) {
476
1409
  return join(env.DSH_HOME ?? join(homedir(), ".dsh"), "memories");
477
1410
  }
@@ -495,6 +1428,7 @@ var MemoryStore = class {
495
1428
  maxFailures;
496
1429
  io;
497
1430
  failureCount = 0;
1431
+ lastFailureAt = 0;
498
1432
  constructor(options = {}) {
499
1433
  this.io = options.io ?? nodeEvolutionIo();
500
1434
  this.memoryLimit = options.memoryCharLimit ?? 2200;
@@ -506,7 +1440,24 @@ var MemoryStore = class {
506
1440
  limitFor(target) {
507
1441
  return target === "memory" ? this.memoryLimit : this.userLimit;
508
1442
  }
1443
+ /**
1444
+ * Read-guard probe: `{ size, limit }` when the on-disk file exceeds
1445
+ * `limit * READ_GUARD_FACTOR` bytes, `null` when it is absent, unknown
1446
+ * (backend without a size probe), under the bound, or the target has no
1447
+ * limit configured.
1448
+ */
1449
+ async oversizedFile(target) {
1450
+ const size = await this.io.size?.(fileFor(this.root, target));
1451
+ if (size === null || size === void 0) return null;
1452
+ const limit = this.limitFor(target);
1453
+ if (limit <= 0) return null;
1454
+ return size > limit * READ_GUARD_FACTOR ? {
1455
+ size,
1456
+ limit
1457
+ } : null;
1458
+ }
509
1459
  async read(target) {
1460
+ if (await this.oversizedFile(target)) return [];
510
1461
  const raw = await this.io.readText(fileFor(this.root, target));
511
1462
  return raw === null ? [] : [...new Set(normalizeEntries(raw))];
512
1463
  }
@@ -517,133 +1468,168 @@ var MemoryStore = class {
517
1468
  this.failureCount = 0;
518
1469
  }
519
1470
  failure(target, message, entries) {
1471
+ if (Date.now() - this.lastFailureAt > FAILURE_WINDOW_MS) this.failureCount = 0;
1472
+ this.lastFailureAt = Date.now();
520
1473
  this.failureCount += 1;
521
1474
  const chars = entries.join(ENTRY_DELIMITER).length;
522
1475
  if (this.failureCount > this.maxFailures) return {
523
1476
  ok: false,
524
- message: `Memory consolidation failed ${this.failureCount} times this turn. Stop retrying memory calls and continue with the user's task.`,
1477
+ message: `Memory consolidation failed ${this.failureCount} times this turn. Stop retrying memory calls and continue with the user's task.${previewEntries(entries)}`,
525
1478
  entries,
526
1479
  chars,
527
1480
  limit: this.limitFor(target)
528
1481
  };
529
1482
  return {
530
1483
  ok: false,
531
- message,
1484
+ message: `${message}${previewEntries(entries)}`,
532
1485
  entries,
533
1486
  chars,
534
1487
  limit: this.limitFor(target)
535
1488
  };
536
1489
  }
537
- async add(target, facts) {
538
- const content = facts.trim();
539
- if (!content) return {
1490
+ /**
1491
+ * StorageHint percentage must clamp at 100 like the render header: a drifted
1492
+ * entry can push chars past the limit, and "Storage at 125%" contradicts the
1493
+ * clamped usage indicator.
1494
+ */
1495
+ storageHint(target, chars) {
1496
+ const limit = this.limitFor(target);
1497
+ if (limit <= 0) return "";
1498
+ const percent = Math.min(100, Math.floor(chars * 100 / limit));
1499
+ return percent >= 80 ? ` ⚠️ Storage at ${percent}% (${chars}/${limit} chars).` : "";
1500
+ }
1501
+ /**
1502
+ * Best-effort raw-copy backup of the on-disk file to `<file>.bak.<stamp>`
1503
+ * before a refusal, so an externally modified (or oversized) file stays
1504
+ * recoverable. Copies bytes instead of reading them so a pathologically
1505
+ * large file is never loaded just to back it up. Failure to back up does
1506
+ * not change the refusal semantics.
1507
+ */
1508
+ async backupFile(target) {
1509
+ const path = fileFor(this.root, target);
1510
+ const unique = `${(/* @__PURE__ */ new Date()).toISOString().replace(/[-:T]/g, "").slice(0, 14)}-${Math.random().toString(36).slice(2, 8)}`;
1511
+ try {
1512
+ await this.io.copy(path, `${path}.bak.${unique}`);
1513
+ return `${path}.bak.${unique}`;
1514
+ } catch {
1515
+ return null;
1516
+ }
1517
+ }
1518
+ /**
1519
+ * Read-guard refusal for write paths. Returns the refusal result when the
1520
+ * target file is oversized, `null` otherwise. The file is skipped for
1521
+ * reading (never loaded), backed up by raw copy, and the model is told to
1522
+ * fix it manually — mirroring the drift refusal so corrupted state is never
1523
+ * silently overwritten.
1524
+ */
1525
+ async oversizedRefusal(target) {
1526
+ const oversized = await this.oversizedFile(target);
1527
+ if (!oversized) return null;
1528
+ const backup = await this.backupFile(target);
1529
+ const suffix = backup ? ` A backup was saved to ${basename(backup)}.` : "";
1530
+ return {
540
1531
  ok: false,
541
- message: "Content cannot be empty.",
1532
+ message: `Memory file is ${oversized.size} bytes (limit ${oversized.limit * READ_GUARD_FACTOR}) — skipping read.${suffix} Fix the file manually, then retry.`,
542
1533
  entries: [],
543
1534
  chars: 0,
544
1535
  limit: this.limitFor(target)
545
1536
  };
546
- const threat = scanMemoryThreats(content);
547
- if (threat) return {
1537
+ }
1538
+ async add(target, facts) {
1539
+ if (!facts.trim()) return {
548
1540
  ok: false,
549
- message: threat,
1541
+ message: "Content cannot be empty.",
550
1542
  entries: [],
551
1543
  chars: 0,
552
1544
  limit: this.limitFor(target)
553
1545
  };
554
- const entries = await this.read(target);
555
- if (entries.some((entry) => stripDatePrefix(entry) === content)) {
556
- this.resetFailures();
1546
+ const path = fileFor(this.root, target);
1547
+ const refusal = await this.oversizedRefusal(target);
1548
+ if (refusal) return refusal;
1549
+ let outcome;
1550
+ await transactIo(this.io, path, async (current) => {
1551
+ const core = await this.addCore(target, facts, current ?? "");
1552
+ outcome = core.result;
1553
+ return core.write ?? current ?? null;
1554
+ });
1555
+ return outcome;
1556
+ }
1557
+ /**
1558
+ * Single-entry add inside the transaction: shared checks (oversized,
1559
+ * drift, threat) and the content computation. `raw` is the locked view
1560
+ * (`current`) — never a second IO read. `write: null` means "no change".
1561
+ */
1562
+ async addCore(target, facts, raw) {
1563
+ const content = facts.trim();
1564
+ if (!content) return {
1565
+ result: this.failure(target, "Content cannot be empty.", []),
1566
+ write: null
1567
+ };
1568
+ if (this.driftFromRaw(target, raw)) {
1569
+ const backup = await this.backupFile(target);
557
1570
  return {
558
- ok: true,
559
- message: "Entry already exists (no duplicate added).",
560
- entries,
561
- chars: entries.join(ENTRY_DELIMITER).length,
562
- limit: this.limitFor(target)
1571
+ result: {
1572
+ ok: false,
1573
+ message: `External drift detected in memory file.${backup ? ` A backup was saved to ${basename(backup)}.` : ""} Resolve the drift before retrying.`,
1574
+ entries: [],
1575
+ chars: 0,
1576
+ limit: this.limitFor(target)
1577
+ },
1578
+ write: null
563
1579
  };
564
1580
  }
565
- const next = [...entries, this.addDatePrefix ? `## ${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}\n${content}` : content];
566
- const total = next.join(ENTRY_DELIMITER).length;
567
- if (total > this.limitFor(target)) return this.failure(target, `Adding this entry would exceed the ${this.limitFor(target)} char limit. Consolidate or remove stale entries, then retry.`, entries);
568
- await this.write(target, next);
569
- this.resetFailures();
570
- return {
571
- ok: true,
572
- message: "Entry added.",
573
- entries: next,
574
- chars: total,
575
- limit: this.limitFor(target)
576
- };
577
- }
578
- async replace(target, oldText, facts) {
579
- return this.mutate(target, oldText, "replace", facts);
580
- }
581
- async remove(target, oldText) {
582
- return this.mutate(target, oldText, "remove", void 0);
583
- }
584
- async mutate(target, oldText, action, facts) {
585
- const needle = oldText.trim();
586
- if (!needle) return {
587
- ok: false,
588
- message: "old_text cannot be empty.",
589
- entries: [],
590
- chars: 0,
591
- limit: this.limitFor(target)
592
- };
593
- const content = action === "replace" ? (facts ?? "").trim() : "";
594
- if (action === "replace" && !content) return {
595
- ok: false,
596
- message: "facts is required for replace; use remove to delete.",
597
- entries: [],
598
- chars: 0,
599
- limit: this.limitFor(target)
600
- };
601
- if (action === "replace") {
602
- const threat = scanMemoryThreats(content);
603
- if (threat) return {
1581
+ const threat = scanMemoryThreats(content);
1582
+ if (threat) return {
1583
+ result: {
604
1584
  ok: false,
605
1585
  message: threat,
606
1586
  entries: [],
607
1587
  chars: 0,
608
1588
  limit: this.limitFor(target)
1589
+ },
1590
+ write: null
1591
+ };
1592
+ const entries = [...new Set(normalizeEntries(raw))];
1593
+ if (entries.some((entry) => stripDatePrefix(entry) === content)) {
1594
+ this.resetFailures();
1595
+ return {
1596
+ result: {
1597
+ ok: true,
1598
+ message: `Entry already exists (no duplicate added).${this.storageHint(target, entries.join(ENTRY_DELIMITER).length)}`,
1599
+ entries,
1600
+ chars: entries.join(ENTRY_DELIMITER).length,
1601
+ limit: this.limitFor(target)
1602
+ },
1603
+ write: null
609
1604
  };
610
1605
  }
611
- if (await this.detectDrift(target)) return {
612
- ok: false,
613
- message: "External drift detected in memory file. Resolve the drift before retrying.",
614
- entries: [],
615
- chars: 0,
616
- limit: this.limitFor(target)
617
- };
618
- const entries = await this.read(target);
619
- const matches = entries.map((entry, index) => ({
620
- entry,
621
- index
622
- })).filter(({ entry }) => entry.includes(needle));
623
- if (matches.length === 0) return this.failure(target, `No entry matching "${needle}" found.`, entries);
624
- if (new Set(matches.map((m) => m.entry)).size > 1) return {
625
- ok: false,
626
- message: `Multiple distinct entries matched "${needle}". Be more specific.`,
627
- entries,
628
- chars: entries.join(ENTRY_DELIMITER).length,
629
- limit: this.limitFor(target)
630
- };
631
- const index = matches[0]?.index ?? -1;
632
- const next = [...entries];
633
- if (action === "remove") next.splice(index, 1);
634
- else next[index] = content;
1606
+ const next = [...entries, this.addDatePrefix ? `## ${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}\n${content}` : content];
635
1607
  const total = next.join(ENTRY_DELIMITER).length;
636
- if (total > this.limitFor(target)) return this.failure(target, `Resulting memory would exceed the ${this.limitFor(target)} char limit.`, entries);
637
- await this.write(target, next);
1608
+ const addLimit = this.limitFor(target);
1609
+ if (addLimit > 0 && total > addLimit) return {
1610
+ result: this.failure(target, `Adding this entry would exceed the ${addLimit} char limit. Consolidate or remove stale entries, then retry.`, entries),
1611
+ write: null
1612
+ };
638
1613
  this.resetFailures();
639
1614
  return {
640
- ok: true,
641
- message: `Entry ${action === "remove" ? "removed" : "replaced"}.`,
642
- entries: next,
643
- chars: total,
644
- limit: this.limitFor(target)
1615
+ result: {
1616
+ ok: true,
1617
+ message: `Entry added.${this.storageHint(target, total)}`,
1618
+ entries: next,
1619
+ chars: total,
1620
+ limit: this.limitFor(target)
1621
+ },
1622
+ write: render(next)
645
1623
  };
646
1624
  }
1625
+ /** Canonical-form drift check derived from the locked view (same formula as `detectDrift`, no second read). */
1626
+ driftFromRaw(target, raw) {
1627
+ if (raw.trim() === "") return false;
1628
+ const entries = normalizeEntries(raw);
1629
+ const limit = this.limitFor(target);
1630
+ if (limit > 0 && entries.some((entry) => entry.length > limit)) return true;
1631
+ return render(entries) !== raw;
1632
+ }
647
1633
  async applyBatch(target, operations) {
648
1634
  if (operations.length === 0) return {
649
1635
  ok: false,
@@ -652,261 +1638,402 @@ var MemoryStore = class {
652
1638
  chars: 0,
653
1639
  limit: this.limitFor(target)
654
1640
  };
655
- if (await this.detectDrift(target)) return {
656
- ok: false,
657
- message: "External drift detected in memory file. Resolve the drift before retrying.",
658
- entries: [],
659
- chars: 0,
660
- limit: this.limitFor(target)
661
- };
662
- const entries = await this.read(target);
1641
+ const path = fileFor(this.root, target);
1642
+ const refusal = await this.oversizedRefusal(target);
1643
+ if (refusal) return refusal;
1644
+ let outcome;
1645
+ await transactIo(this.io, path, async (current) => {
1646
+ const core = await this.applyBatchCore(target, operations, current ?? "");
1647
+ outcome = core.result;
1648
+ return core.write ?? current ?? null;
1649
+ });
1650
+ return outcome;
1651
+ }
1652
+ /** Batch RMW inside the transaction. `write: null` = failure/no-op, disk untouched. */
1653
+ async applyBatchCore(target, operations, raw) {
1654
+ if (this.driftFromRaw(target, raw)) {
1655
+ const backup = await this.backupFile(target);
1656
+ return {
1657
+ result: {
1658
+ ok: false,
1659
+ message: `External drift detected in memory file.${backup ? ` A backup was saved to ${basename(backup)}.` : ""} Resolve the drift before retrying.`,
1660
+ entries: [],
1661
+ chars: 0,
1662
+ limit: this.limitFor(target)
1663
+ },
1664
+ write: null
1665
+ };
1666
+ }
1667
+ const entries = [...new Set(normalizeEntries(raw))];
663
1668
  const working = [...entries];
664
1669
  for (const [index, op] of operations.entries()) {
665
1670
  const position = index + 1;
666
1671
  if (op.action === "add") {
667
1672
  const body = (op.facts ?? "").trim();
668
1673
  if (!body) return {
669
- ok: false,
670
- message: `Operation ${position} (add): facts is required. No operations were applied.`,
671
- entries,
672
- chars: entries.join(ENTRY_DELIMITER).length,
673
- limit: this.limitFor(target)
1674
+ result: {
1675
+ ok: false,
1676
+ message: `Operation ${position} (add): facts is required. No operations were applied.${previewEntries(entries)}`,
1677
+ entries,
1678
+ chars: entries.join(ENTRY_DELIMITER).length,
1679
+ limit: this.limitFor(target)
1680
+ },
1681
+ write: null
674
1682
  };
675
1683
  const threat = scanMemoryThreats(body);
676
1684
  if (threat) return {
677
- ok: false,
678
- message: `Operation ${position}: ${threat}`,
679
- entries,
680
- chars: entries.join(ENTRY_DELIMITER).length,
681
- limit: this.limitFor(target)
1685
+ result: {
1686
+ ok: false,
1687
+ message: `Operation ${position}: ${threat}`,
1688
+ entries,
1689
+ chars: entries.join(ENTRY_DELIMITER).length,
1690
+ limit: this.limitFor(target)
1691
+ },
1692
+ write: null
682
1693
  };
683
1694
  if (!working.some((entry) => stripDatePrefix(entry) === body)) working.push(this.addDatePrefix ? `## ${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}\n${body}` : body);
684
1695
  continue;
685
1696
  }
686
1697
  const needle = (op.old_text ?? "").trim();
687
1698
  if (!needle) return {
688
- ok: false,
689
- message: `Operation ${position} (${op.action}): old_text is required. No operations were applied.`,
690
- entries,
691
- chars: entries.join(ENTRY_DELIMITER).length,
692
- limit: this.limitFor(target)
1699
+ result: {
1700
+ ok: false,
1701
+ message: `Operation ${position} (${op.action}): old_text is required. No operations were applied.${previewEntries(entries)}`,
1702
+ entries,
1703
+ chars: entries.join(ENTRY_DELIMITER).length,
1704
+ limit: this.limitFor(target)
1705
+ },
1706
+ write: null
693
1707
  };
694
1708
  const matches = working.map((entry, matchIndex) => ({
695
1709
  entry,
696
1710
  matchIndex
697
1711
  })).filter(({ entry }) => entry.includes(needle));
698
- if (matches.length === 0) return this.failure(target, `Operation ${position}: no entry matching "${needle}" found. No operations were applied.`, entries);
1712
+ if (matches.length === 0) return {
1713
+ result: this.failure(target, `Operation ${position}: no entry matching "${needle}" found. No operations were applied.`, entries),
1714
+ write: null
1715
+ };
699
1716
  if (new Set(matches.map((m) => m.entry)).size > 1) return {
700
- ok: false,
701
- message: `Operation ${position}: "${needle}" matched multiple distinct entries. No operations were applied.`,
702
- entries,
703
- chars: entries.join(ENTRY_DELIMITER).length,
704
- limit: this.limitFor(target)
1717
+ result: {
1718
+ ok: false,
1719
+ message: `Operation ${position}: "${needle}" matched multiple distinct entries. No operations were applied.${previewEntries(entries)}`,
1720
+ entries,
1721
+ chars: entries.join(ENTRY_DELIMITER).length,
1722
+ limit: this.limitFor(target)
1723
+ },
1724
+ write: null
705
1725
  };
706
1726
  const matchIndex = matches[0]?.matchIndex ?? -1;
707
1727
  if (op.action === "remove") working.splice(matchIndex, 1);
708
1728
  else {
709
1729
  const body = (op.facts ?? "").trim();
710
1730
  if (!body) return {
711
- ok: false,
712
- message: `Operation ${position} (replace): facts is required.`,
713
- entries,
714
- chars: entries.join(ENTRY_DELIMITER).length,
715
- limit: this.limitFor(target)
1731
+ result: {
1732
+ ok: false,
1733
+ message: `Operation ${position} (replace): facts is required.${previewEntries(entries)}`,
1734
+ entries,
1735
+ chars: entries.join(ENTRY_DELIMITER).length,
1736
+ limit: this.limitFor(target)
1737
+ },
1738
+ write: null
716
1739
  };
717
1740
  const threat = scanMemoryThreats(body);
718
1741
  if (threat) return {
719
- ok: false,
720
- message: `Operation ${position}: ${threat}`,
721
- entries,
722
- chars: entries.join(ENTRY_DELIMITER).length,
723
- limit: this.limitFor(target)
1742
+ result: {
1743
+ ok: false,
1744
+ message: `Operation ${position}: ${threat}`,
1745
+ entries,
1746
+ chars: entries.join(ENTRY_DELIMITER).length,
1747
+ limit: this.limitFor(target)
1748
+ },
1749
+ write: null
724
1750
  };
725
1751
  working[matchIndex] = body;
726
1752
  }
727
1753
  }
728
1754
  const total = working.join(ENTRY_DELIMITER).length;
729
- if (total > this.limitFor(target)) return this.failure(target, `Batch result (${total} chars) exceeds the ${this.limitFor(target)} limit. Remove or shorten more entries in the same batch.`, entries);
730
- await this.write(target, working);
1755
+ const batchLimit = this.limitFor(target);
1756
+ if (batchLimit > 0 && total > batchLimit) return {
1757
+ result: this.failure(target, `Batch result (${total} chars) exceeds the ${batchLimit} limit. Remove or shorten more entries in the same batch.`, entries),
1758
+ write: null
1759
+ };
731
1760
  this.resetFailures();
732
1761
  return {
733
- ok: true,
734
- message: `Applied ${operations.length} operation(s).`,
735
- entries: working,
736
- chars: total,
737
- limit: this.limitFor(target)
1762
+ result: {
1763
+ ok: true,
1764
+ message: `Applied ${operations.length} operation(s).${this.storageHint(target, total)}`,
1765
+ entries: working,
1766
+ chars: total,
1767
+ limit: this.limitFor(target)
1768
+ },
1769
+ write: render(working)
738
1770
  };
739
1771
  }
740
1772
  async renderContext() {
741
1773
  const memory = await this.read("memory");
742
1774
  const user = await this.read("user");
743
1775
  const parts = [];
744
- for (const [target, entries] of [["Memory", memory], ["User Profile", user]]) {
1776
+ for (const [target, label, entries] of [[
1777
+ "memory",
1778
+ "Memory",
1779
+ memory
1780
+ ], [
1781
+ "user",
1782
+ "User Profile",
1783
+ user
1784
+ ]]) {
1785
+ const oversized = entries.length === 0 ? await this.oversizedFile(target) : null;
1786
+ if (oversized) {
1787
+ parts.push(`## ${label} — file skipped: ${oversized.size} bytes (limit ${oversized.limit * READ_GUARD_FACTOR}); not read`);
1788
+ continue;
1789
+ }
745
1790
  const safe = entries.filter((entry) => !scanMemoryThreats(entry));
746
1791
  if (safe.length > 0) {
747
1792
  const body = safe.join(ENTRY_DELIMITER);
1793
+ const limit = this.limitFor(target);
1794
+ const pct = limit > 0 ? Math.min(100, Math.floor(body.length * 100 / limit)) : 0;
748
1795
  const note = safe.length === entries.length ? "" : ` (${entries.length - safe.length} threat-matched entries filtered)`;
749
- parts.push(`## ${target} (${safe.length} entries)${note}\n${body}`);
1796
+ parts.push(`## ${label} (${safe.length} entries) [${pct}% — ${body.length}/${limit} chars]${note}\n${body}`);
750
1797
  }
751
1798
  }
752
1799
  return parts.join("\n\n");
753
1800
  }
754
- async snapshot() {
755
- const [memory, user] = await Promise.all([this.read("memory"), this.read("user")]);
756
- return {
757
- memory,
758
- user
759
- };
760
- }
761
- async restoreSnapshot(snapshot) {
762
- await this.write("memory", snapshot.memory);
763
- await this.write("user", snapshot.user);
764
- }
1801
+ /**
1802
+ * Detect on-disk drift: true when the file is not in the canonical
1803
+ * `render(normalizeEntries(raw))` form. This catches structural anomalies
1804
+ * the writer would quietly normalize away (empty/`§`-only entries, stray
1805
+ * blank lines, leading/trailing delimiters) that indicate the file was
1806
+ * edited outside MemoryStore. Purely single-canonical content reaches the
1807
+ * same serialization and returns false, so a normal write is never flagged.
1808
+ *
1809
+ * An absent, empty, or whitespace-only file is the "never written" state
1810
+ * (rc.42 audit P1-6): it parses to zero entries, so the canonical form
1811
+ * `'\n'` can never byte-match it and every write path was permanently
1812
+ * refused with "External drift detected" — including the repairs the model
1813
+ * would need to make. Such files are adopted instead of flagged.
1814
+ */
765
1815
  async detectDrift(target) {
1816
+ if (await this.oversizedFile(target)) return true;
766
1817
  const raw = await this.io.readText(fileFor(this.root, target));
767
- if (raw === null) return false;
768
- return normalizeEntries(raw).join(ENTRY_DELIMITER) !== raw.trim();
1818
+ if (raw === null || raw.trim() === "") return false;
1819
+ const entries = normalizeEntries(raw);
1820
+ const limit = this.limitFor(target);
1821
+ if (limit > 0 && entries.some((entry) => entry.length > limit)) return true;
1822
+ return render(entries) !== raw;
769
1823
  }
770
1824
  };
771
1825
  //#endregion
772
- //#region lib/types/prompts.js
1826
+ //#region lib/types/mutations.js
773
1827
  /**
774
- * Review and curation prompts adapted from Hermes Agent
775
- * `agent/background_review.py`, `agent/curator.py`, and
776
- * `agent/learn_prompt.py`, with tool names translated to the DSH-native
777
- * catalog (`memory`, `skill_manage`, `skill`, `bash`, `str_replace_editor`).
778
- *
779
- * Every prompt is pinned in a versioned bundle. Review workers verify the
780
- * bundle digest before spending a model call, so a partially-patched
781
- * deployment fails closed instead of silently running a truncated prompt.
1828
+ * Curator/author audit trail: `.mutations.json` records every skill mutation
1829
+ * with before/after content hashes so any automated edit is reviewable and
1830
+ * replayable. Best-effort persistence, mirroring the usage sidecar posture.
1831
+ * @module @lmzhen/dsh-evolution-core
782
1832
  */
783
- const PROMPT_BUNDLE_ID = "dsh-evolution@1";
784
- const MEMORY_REVIEW_PROMPT = `[Auto-review — Memory]
785
- Review the conversation above and consider saving to memory if appropriate.
786
-
787
- Focus on:
788
- 1. Has the user revealed things about themselves — persona, desires, preferences, or personal details worth remembering?
789
- 2. Has the user expressed expectations about how you should behave, their work style, or ways they want you to operate?
790
-
791
- If something stands out, save it using the memory tool.
792
- If nothing is worth saving, just say "Nothing to save." and stop.`;
793
- const SKILL_REVIEW_PROMPT = `[Auto-review — Skills]
794
- Review the conversation above and update the skill library. Be ACTIVE — most sessions produce at least one skill update, even if small.
795
-
796
- Target shape: CLASS-LEVEL skills with a rich SKILL.md and a references/ directory for session-specific detail. Not a flat list of narrow one-session skills.
797
-
798
- Signals that warrant action:
799
- - The user corrected your style, tone, format, verbosity, workflow, or approach.
800
- - A non-trivial technique, fix, workaround, or debugging path emerged.
801
- - A loaded skill turned out wrong, missing, or outdated — patch it now.
802
-
803
- Preference order:
804
- 1. Patch a skill that was loaded or read this session.
805
- 2. Patch an existing umbrella skill.
806
- 3. Add references/, templates/, or scripts/ support under an existing skill.
807
- 4. Create a new class-level umbrella skill only when nothing fits.
808
-
809
- Protected skills (bundled/hub-installed) must not be edited. Pinned skills may be patched but not archived.
810
-
811
- Do NOT capture:
812
- - Environment-dependent failures (missing binaries, unconfigured credentials).
813
- - Negative claims about tools ("browser tools do not work").
814
- - Transient errors that resolved during the session.
815
- - One-off task narratives.
816
-
817
- If a tool failed because of setup state, capture the FIX under an existing setup skill — never "this tool does not work" as a standalone constraint.
818
-
819
- "Nothing to save." is a real option but should NOT be the default.`;
820
- const COMBINED_REVIEW_PROMPT = `[Auto-review]
821
- Review the conversation above and update two things.
822
-
823
- **Memory**: who the user is. Save durable user preferences, personal details, and expectations with the memory tool.
824
-
825
- **Skills**: how to do this class of task. Be ACTIVE. Follow the same class-level umbrella policy, preference order, protected-skill rules, and do-not-capture list as a skill review.
826
-
827
- Act on whichever dimension has real signal. If genuinely nothing stands out on either, say "Nothing to save." and stop — but don't reach for that conclusion as a default.`;
828
- const CURATOR_PROMPT = `You are the skill curator. Maintain a healthy, class-level skill library.
829
-
830
- Rules:
831
- 1. NEVER hard-delete a skill. Archive is the maximum destructive action.
832
- 2. Do not touch bundled, hub-installed, or pinned skills.
833
- 3. Do not archive recently-created or never-used skills without strong evidence.
834
- 4. Prefer merging narrow skills into class-level umbrellas.
835
- 5. Before archiving a merged skill, ensure its unique content was preserved.
836
-
837
- Produce a YAML summary:
838
- consolidations:
839
- - from: <old-skill-name>
840
- into: <umbrella-skill-name>
841
- reason: <one short sentence>
842
- prunings:
843
- - name: <skill-name>
844
- reason: <one short sentence>`;
845
- function reviewPrompt(kind) {
846
- if (kind === "memory") return MEMORY_REVIEW_PROMPT;
847
- if (kind === "skill") return SKILL_REVIEW_PROMPT;
848
- return COMBINED_REVIEW_PROMPT;
1833
+ const DEFAULT_MUTATION_CAP = 500;
1834
+ /** Version of the `.mutations.json` file shape; writers always emit the current one. */
1835
+ const MUTATIONS_FILE_VERSION = 1;
1836
+ function mutationsFile(root) {
1837
+ return join(root, ".mutations.json");
1838
+ }
1839
+ function contentHash(content) {
1840
+ return createHash("sha256").update(content).digest("hex");
1841
+ }
1842
+ /**
1843
+ * Parse a raw mutations sidecar; malformed content reads as empty (auditing is
1844
+ * best-effort). Versioned shape ({ version, records }) with legacy
1845
+ * plain-array compat, plus a field-level guard for records without the
1846
+ * required identity/timestamp fields (rc.42 audit P2-3).
1847
+ */
1848
+ function parseMutationRecords(raw) {
1849
+ if (raw === null) return [];
1850
+ try {
1851
+ const parsed = JSON.parse(raw);
1852
+ return (Array.isArray(parsed) ? parsed : typeof parsed === "object" && parsed !== null && Array.isArray(parsed.records) ? parsed.records : []).filter((entry) => typeof entry === "object" && entry !== null && typeof entry.skillName === "string" && typeof entry.action === "string" && typeof entry.at === "string");
1853
+ } catch {
1854
+ return [];
1855
+ }
1856
+ }
1857
+ async function loadMutations(root, io = nodeEvolutionIo()) {
1858
+ return parseMutationRecords(await io.readText(mutationsFile(root)));
1859
+ }
1860
+ /** Append one record, trim to `cap`, and write atomically (versioned shape). */
1861
+ async function recordMutation(root, io, record, cap = 500) {
1862
+ await transactIo(io, mutationsFile(root), async (current) => {
1863
+ if (current !== null) try {
1864
+ JSON.parse(current);
1865
+ } catch {
1866
+ return current;
1867
+ }
1868
+ const existing = parseMutationRecords(current);
1869
+ existing.push(record);
1870
+ const trimmed = existing.length > cap ? existing.slice(existing.length - cap) : existing;
1871
+ return Promise.resolve(JSON.stringify({
1872
+ version: 1,
1873
+ records: trimmed
1874
+ }, null, 2));
1875
+ });
849
1876
  }
850
- function sha256(text) {
851
- return createHash("sha256").update(text).digest("hex");
1877
+ //#endregion
1878
+ //#region lib/types/quality.js
1879
+ /**
1880
+ * Quality scoring and near-duplicate detection for the curated skill library.
1881
+ *
1882
+ * Pure functions over data inputs so the scoring policy is unit-testable and
1883
+ * the same math feeds the usage sidecar, the `skill_manage review` surface and
1884
+ * the learning graph. Weights follow the Hermes/hermes-claw six-factor model;
1885
+ * mutation maturity is a documented DSH approximation (single per-month patch
1886
+ * trend ratio replaces the claw timestamp-trend formula, since DSH usage
1887
+ * records only carry the last patched timestamp).
1888
+ * @module @lmzhen/dsh-evolution-core
1889
+ */
1890
+ const QUALITY_WEIGHTS = {
1891
+ usageFrequency: .25,
1892
+ stability: .2,
1893
+ recency: .2,
1894
+ references: .1,
1895
+ mutationMaturity: .2,
1896
+ richness: .05
1897
+ };
1898
+ /** Score below which a skill is flagged for review. */
1899
+ const LOW_QUALITY_THRESHOLD = .3;
1900
+ function clamp01(value) {
1901
+ return Math.max(0, Math.min(1, value));
852
1902
  }
853
- function createPromptBundle(prompts) {
854
- const canonical = JSON.stringify({
855
- id: PROMPT_BUNDLE_ID,
856
- version: 1,
857
- prompts: Object.fromEntries(Object.entries(prompts).sort())
858
- });
859
- return Object.freeze({
860
- id: PROMPT_BUNDLE_ID,
861
- version: 1,
862
- prompts: Object.freeze({ ...prompts }),
863
- sha256: sha256(canonical)
864
- });
1903
+ function daysBetween(from, now) {
1904
+ return Math.max(0, (now.getTime() - new Date(from).getTime()) / 864e5);
865
1905
  }
866
- const PROMPT_BUNDLE = createPromptBundle({
867
- memory: MEMORY_REVIEW_PROMPT,
868
- skill: SKILL_REVIEW_PROMPT,
869
- combined: COMBINED_REVIEW_PROMPT,
870
- curator: CURATOR_PROMPT
871
- });
872
- function verifyPromptBundle(bundle = PROMPT_BUNDLE) {
873
- const canonical = JSON.stringify({
874
- id: bundle.id,
875
- version: bundle.version,
876
- prompts: Object.fromEntries(Object.entries(bundle.prompts).sort())
877
- });
878
- return bundle.sha256 === sha256(canonical);
1906
+ function computeQualityScores(input) {
1907
+ const now = input.now ?? /* @__PURE__ */ new Date();
1908
+ const scores = /* @__PURE__ */ new Map();
1909
+ for (const [name, record] of input.usage) {
1910
+ const ageDays = Math.max(1, daysBetween(record.created_at, now));
1911
+ const idleDays = daysBetween(latestActivityAt(record) ?? record.created_at, now);
1912
+ const patchCount = record.patch_count;
1913
+ const useCount = record.use_count;
1914
+ const usageFrequency = clamp01(useCount / ageDays);
1915
+ const stability = useCount === 0 ? 1 : clamp01(1 - patchCount / useCount);
1916
+ const recency = idleDays < 30 ? 1 : clamp01(1 - (idleDays - 30) / 150);
1917
+ const references = clamp01((input.referenceCounts?.get(name) ?? 0) / 3);
1918
+ const mutationMaturity = patchCount === 0 ? .3 : patchCount === 1 ? .4 : clamp01((patchCount - 1) / Math.max(1, ageDays / 30));
1919
+ const richness = clamp01((input.supportDirs?.get(name) ?? 0) * .175);
1920
+ const factors = {
1921
+ usageFrequency,
1922
+ stability,
1923
+ recency,
1924
+ references,
1925
+ mutationMaturity,
1926
+ richness
1927
+ };
1928
+ const score = usageFrequency * QUALITY_WEIGHTS.usageFrequency + stability * QUALITY_WEIGHTS.stability + recency * QUALITY_WEIGHTS.recency + references * QUALITY_WEIGHTS.references + mutationMaturity * QUALITY_WEIGHTS.mutationMaturity + richness * QUALITY_WEIGHTS.richness;
1929
+ scores.set(name, {
1930
+ score,
1931
+ factors,
1932
+ warn: score < LOW_QUALITY_THRESHOLD
1933
+ });
1934
+ }
1935
+ return scores;
1936
+ }
1937
+ function normalize(content) {
1938
+ return content.toLowerCase().replace(/\s+/g, " ").trim();
1939
+ }
1940
+ function contentHash$1(content) {
1941
+ return createHash("sha256").update(normalize(content)).digest("hex");
1942
+ }
1943
+ function tokenize(content) {
1944
+ return new Set(normalize(content).split(/[^a-z0-9\u4e00-\u9fff]+/).filter(Boolean));
1945
+ }
1946
+ function jaccard(a, b) {
1947
+ if (a.size === 0 || b.size === 0) return 0;
1948
+ let intersection = 0;
1949
+ for (const token of a) if (b.has(token)) intersection += 1;
1950
+ return intersection / (a.size + b.size - intersection);
1951
+ }
1952
+ /**
1953
+ * Two-phase near-duplicate clustering: exact normalized-hash groups first,
1954
+ * then token-Jaccard edges at {@link DEDUP_SIMILARITY_THRESHOLD} with a token
1955
+ * ratio guard, union-find across the whole set.
1956
+ */
1957
+ function computeDedupGroups(input) {
1958
+ const threshold = input.threshold ?? .95;
1959
+ const names = [...input.contents.keys()];
1960
+ const hashes = /* @__PURE__ */ new Map();
1961
+ for (const name of names) {
1962
+ const hash = contentHash$1(input.contents.get(name) ?? "");
1963
+ const bucket = hashes.get(hash);
1964
+ if (bucket) bucket.push(name);
1965
+ else hashes.set(hash, [name]);
1966
+ }
1967
+ const parent = /* @__PURE__ */ new Map();
1968
+ const find = (x) => {
1969
+ const root = parent.get(x) ?? x;
1970
+ if (root !== x) parent.set(x, find(root));
1971
+ return parent.get(x) ?? x;
1972
+ };
1973
+ const union = (a, b) => {
1974
+ const [ra, rb] = [find(a), find(b)];
1975
+ if (ra !== rb) parent.set(rb, ra);
1976
+ };
1977
+ for (const [hash, bucketNames] of hashes) {
1978
+ const first = bucketNames[0];
1979
+ if (first === void 0 || bucketNames.length === 1) continue;
1980
+ for (let index = 1; index < bucketNames.length; index += 1) {
1981
+ const peer = bucketNames[index];
1982
+ if (peer) union(first, peer);
1983
+ }
1984
+ }
1985
+ const tokens = /* @__PURE__ */ new Map();
1986
+ const tokenSet = (name) => {
1987
+ let set = tokens.get(name);
1988
+ if (!set) {
1989
+ set = tokenize(input.contents.get(name) ?? "");
1990
+ tokens.set(name, set);
1991
+ }
1992
+ return set;
1993
+ };
1994
+ for (let index = 0; index < names.length; index += 1) {
1995
+ const a = names[index];
1996
+ if (a === void 0) continue;
1997
+ for (let other = index + 1; other < names.length; other += 1) {
1998
+ const b = names[other];
1999
+ if (b === void 0) continue;
2000
+ const [ta, tb] = [tokenSet(a), tokenSet(b)];
2001
+ if (Math.max(ta.size, tb.size) / Math.max(1, Math.min(ta.size, tb.size)) > 5) continue;
2002
+ if (jaccard(ta, tb) >= threshold) union(a, b);
2003
+ }
2004
+ }
2005
+ const groups = /* @__PURE__ */ new Map();
2006
+ for (const name of names) {
2007
+ const root = find(name);
2008
+ const group = groups.get(root);
2009
+ if (group) group.push(name);
2010
+ else groups.set(root, [name]);
2011
+ }
2012
+ return [...groups.values()].filter((group) => group.length > 1);
2013
+ }
2014
+ /**
2015
+ * Prefix-cluster index over a name set (rc.67 merge heuristic, input side):
2016
+ * the curator prompt asks the model to identify "prefix clusters — skills
2017
+ * sharing a first word or domain keyword"; the deterministic index supplies
2018
+ * stable ground truth instead of letting the model infer clusters from the
2019
+ * raw list. Key = first alphanumeric run of the lowercased name; groups with
2020
+ * at least two members, largest first then alphabetical. Orientation-only:
2021
+ * nomination authority stays with the LLM and the candidate-pool gates.
2022
+ */
2023
+ function computePrefixClusters(names) {
2024
+ const groups = /* @__PURE__ */ new Map();
2025
+ for (const name of names) {
2026
+ const key = name.toLowerCase().split(/[^a-z0-9]+/)[0];
2027
+ if (!key) continue;
2028
+ const bucket = groups.get(key);
2029
+ if (bucket) bucket.push(name);
2030
+ else groups.set(key, [name]);
2031
+ }
2032
+ return [...groups.entries()].filter(([, members]) => members.length >= 2).map(([key, members]) => ({
2033
+ key,
2034
+ members
2035
+ })).sort((a, b) => b.members.length - a.members.length || a.key.localeCompare(b.key));
879
2036
  }
880
- const DSH_AUTHORING_STANDARDS = `Follow the Hermes skill-authoring standards, translated to DSH tools.
881
-
882
- Frontmatter:
883
- - name: lowercase-hyphenated, <=64 chars, no spaces.
884
- - description: ONE sentence, <=60 characters, ends with a period. State the capability, not the implementation. No marketing words. Do NOT repeat the skill name. Count the characters before saving.
885
- - version: 0.1.0
886
- - author: always the literal value "Hermes". NEVER fill it from the environment, git config, or any identity you can probe.
887
- - platforms: declare [macos], [linux], and/or [windows] only when the skill is genuinely OS-bound; omit for portable skills.
888
- - metadata.hermes.tags: a few Capitalized, Relevant, Tags.
889
-
890
- Body section order (omit only when empty):
891
- 1. "# <Human Title>" then a 2-3 sentence intro: what it does, what it does NOT do, key dependency stance.
892
- 2. "## When to Use" — concrete trigger phrases.
893
- 3. "## Prerequisites" — exact env vars, install steps, credentials.
894
- 4. "## How to Run" — canonical invocation framed through DSH tools.
895
- 5. "## Quick Reference" — flat command/endpoint list.
896
- 6. "## Procedure" — numbered steps with copy-paste-exact commands.
897
- 7. "## Pitfalls" — known limits and rate limits.
898
- 8. "## Verification" — one check proving the skill worked.
899
-
900
- DSH-tool framing:
901
- - Reference DSH tools by name in backticks: \`bash\`, \`str_replace_editor\`, \`write\`, \`skill\`, \`skill_manage\`, \`memory\`.
902
- - Do not name wrapped shell utilities when a DSH tool already covers them.
903
- - Larger scripts belong under \`scripts/\` (written with \`skill_manage write_file\`) and are referenced from SKILL.md by relative path.
904
-
905
- Quality bar:
906
- - Prefer verbatim flags, paths, and APIs from the source. Never invent them.
907
- - Keep it tight: ~100 lines simple, ~200 complex.
908
- - No router/index/hub skills that only point at other skills.
909
- - References go in \`references/\`, templates in \`templates/\`.`;
910
2037
  //#endregion
911
2038
  //#region lib/types/signals.js
912
2039
  /**
@@ -994,31 +2121,53 @@ function foldTurn(session, fromSeq) {
994
2121
  * it created unless a `.hermes-managed` marker opts a skill in. Archival is a
995
2122
  * move to `.archive/` — never a hard delete.
996
2123
  */
997
- const SKILL_NAME_RE = /^[a-z0-9][a-z0-9-]*$/;
998
- const MAX_SKILL_NAME_LENGTH = 64;
999
- const MAX_DESCRIPTION_LENGTH = 1024;
1000
- const MAX_SKILL_CONTENT_CHARS = 1e5;
1001
- const MAX_SKILL_FILE_BYTES = 1048576;
1002
2124
  const DEFAULT_SKILL_LIMITS = {
1003
2125
  maxNameLength: 64,
1004
2126
  maxDescriptionLength: MAX_DESCRIPTION_LENGTH,
1005
2127
  maxSkillContentChars: MAX_SKILL_CONTENT_CHARS,
1006
2128
  maxSkillFileBytes: MAX_SKILL_FILE_BYTES
1007
2129
  };
1008
- const SUPPORT_DIRS = [
1009
- "references",
1010
- "templates",
1011
- "scripts",
1012
- "assets"
1013
- ];
2130
+ /** Extra file name carried inside a snapshot's `extras/` directory. */
2131
+ const SNAPSHOT_EXTRA_NAME_RE = /^[a-z0-9][a-z0-9._-]*$/;
1014
2132
  function skillsRoot(env = process.env) {
1015
2133
  return join(env.DSH_HOME ?? join(homedir(), ".dsh"), "skills");
1016
2134
  }
2135
+ /**
2136
+ * Map a requesting session onto the two origin surfaces (rc.44 plan M2-2.3):
2137
+ * the APPROVAL surface treats every delegated subagent as the autonomous
2138
+ * review channel, while the LIBRARY surface keeps the Hermes distinction -
2139
+ * the review fork is 'background_review' (the pinned guard blocks its
2140
+ * writes) and any other subagent is 'subagent' (agent-authored, not
2141
+ * review-channel). `isReview` marks the caller as the background review
2142
+ * pipeline itself. Single source: the two tools and the review executor all
2143
+ * read this table instead of re-deriving it.
2144
+ */
2145
+ function resolveOrigins(headerOrigin, isReview = false) {
2146
+ if (isReview) return {
2147
+ approval: "background_review",
2148
+ library: "background_review"
2149
+ };
2150
+ if (headerOrigin === "subagent") return {
2151
+ approval: "background_review",
2152
+ library: "subagent"
2153
+ };
2154
+ return {
2155
+ approval: "foreground",
2156
+ library: "foreground"
2157
+ };
2158
+ }
1017
2159
  function skillDir(root, name) {
1018
2160
  return join(root, name);
1019
2161
  }
2162
+ /** Dot-prefixed on-disk marker name. SINGLE source: `list()` matches directory
2163
+ * entries against this name, and path builders must never hardcode a marker
2164
+ * literal (N-1: the rc.49 exists()-probe convergence dropped the dot,
2165
+ * poisoning every protectedBy/managed report). */
2166
+ function markerEntryName(marker) {
2167
+ return `.${marker}`;
2168
+ }
1020
2169
  function markerPath(dir, marker) {
1021
- return join(dir, `.${marker}`);
2170
+ return join(dir, markerEntryName(marker));
1022
2171
  }
1023
2172
  function parseFrontmatter(content) {
1024
2173
  if (!content.trimStart().startsWith("---")) return null;
@@ -1040,6 +2189,26 @@ function parseFrontmatter(content) {
1040
2189
  body
1041
2190
  };
1042
2191
  }
2192
+ /**
2193
+ * Skill names referenced by a SKILL.md's `related_skills` frontmatter
2194
+ * (B-line G3, rc.44): the single parsing source for the quality references
2195
+ * factor and the learning-graph edges. The DSH frontmatter parser keeps the
2196
+ * YAML value as a string (`"[a, b]"`), so names are scanned out of it; each
2197
+ * must satisfy the skill-name shape and the referencing skill itself is
2198
+ * excluded. Pure and deduplicated.
2199
+ */
2200
+ function relatedSkillNames(content, exclude) {
2201
+ const parsed = parseFrontmatter(content);
2202
+ if (!parsed) return [];
2203
+ const raw = parsed.frontmatter["related_skills"];
2204
+ if (typeof raw !== "string") return [];
2205
+ const names = /* @__PURE__ */ new Set();
2206
+ for (const match of Array.from(raw.matchAll(/[a-z0-9][a-z0-9-]*/g))) {
2207
+ const target = match[0];
2208
+ if (target && SKILL_NAME_RE.test(target) && target !== exclude) names.add(target);
2209
+ }
2210
+ return [...names];
2211
+ }
1043
2212
  function validateFrontmatter(content, expectedName, limits = DEFAULT_SKILL_LIMITS) {
1044
2213
  const parsed = parseFrontmatter(content);
1045
2214
  if (!parsed) return "SKILL.md must start and end with YAML frontmatter and include a body.";
@@ -1052,6 +2221,31 @@ function validateFrontmatter(content, expectedName, limits = DEFAULT_SKILL_LIMIT
1052
2221
  if (content.length > limits.maxSkillContentChars) return `SKILL.md content exceeds ${limits.maxSkillContentChars} characters.`;
1053
2222
  return null;
1054
2223
  }
2224
+ /** Hermes authoring quality bar for descriptions (the 60-char Rule). The
2225
+ * platform's own index limit stays in `validateFrontmatter`; this bar is the
2226
+ * target the authoring standard names, enforced as ADVISORY feedback. */
2227
+ const AUTHORING_DESCRIPTION_BAR = 60;
2228
+ /**
2229
+ * Advisory authoring feedback (P0): evaluate frontmatter against the
2230
+ * authoring bar WITHOUT changing platform validation semantics. The bar is
2231
+ * the quality target, `validateFrontmatter`'s limits are the compatibility
2232
+ * floor, and this bridge layer tells the model when its text would be
2233
+ * truncated or route-poor instead of silently shipping it.
2234
+ */
2235
+ function authoringFeedback(frontmatter) {
2236
+ const description = frontmatter.description ?? "";
2237
+ const over60 = description.length > 60;
2238
+ const hasColon = description.includes(":");
2239
+ const lines = [];
2240
+ lines.push(over60 ? `Description is ${description.length}/60 characters — exceeds the 60-char authoring bar (Hermes standard; the catalog truncates at the configured platform cap).` : `Description ${description.length}/60 characters — within the authoring bar.`);
2241
+ if (hasColon) lines.push("Description contains a colon — wrap the whole value in double quotes.");
2242
+ return {
2243
+ descriptionChars: description.length,
2244
+ over60,
2245
+ hasColon,
2246
+ lines
2247
+ };
2248
+ }
1055
2249
  async function listNames(root, io) {
1056
2250
  const entries = await io.list(root);
1057
2251
  const names = [];
@@ -1069,65 +2263,274 @@ function validateSupportPath(filePath) {
1069
2263
  if (parts.length < 2) return "Provide a file name, not just a directory.";
1070
2264
  return null;
1071
2265
  }
2266
+ /**
2267
+ * Index of `pattern` inside `content`, treating whitespace runs (spaces/tabs)
2268
+ * as flexible and literal escape sequences (`\n`, `\t`, `\r`) as their real
2269
+ * characters: a PATTERN whitespace run matches any content run of any length
2270
+ * (even empty), while extra whitespace that only exists in the content is not
2271
+ * skipped — the flexibility is one-sided on the pattern, and a backslash-
2272
+ * escaped char in the pattern matches the real char in the content
2273
+ * (model-copy drift). Returns the [start, end) range in the ORIGINAL content
2274
+ * so a patch can replace exactly the matched span and keep every other byte
2275
+ * intact. Returns null when no fuzzy match exists.
2276
+ */
2277
+ function fuzzyIndexOf(content, pattern, from = 0) {
2278
+ const isSpace = (char) => char !== void 0 && /[ \t]/.test(char);
2279
+ const escaped = (char) => {
2280
+ if (char === "n") return "\n";
2281
+ if (char === "t") return " ";
2282
+ if (char === "r") return "\r";
2283
+ return null;
2284
+ };
2285
+ for (let start = from; start < content.length; start += 1) {
2286
+ let contentIndex = start;
2287
+ let patternIndex = 0;
2288
+ while (patternIndex < pattern.length && contentIndex < content.length) {
2289
+ const patternChar = pattern[patternIndex];
2290
+ const contentChar = content[contentIndex];
2291
+ if (isSpace(patternChar)) {
2292
+ while (patternIndex < pattern.length && isSpace(pattern[patternIndex])) patternIndex += 1;
2293
+ while (contentIndex < content.length && isSpace(content[contentIndex])) contentIndex += 1;
2294
+ continue;
2295
+ }
2296
+ const escapedChar = patternChar === "\\" ? escaped(pattern[patternIndex + 1]) : null;
2297
+ if (escapedChar !== null && contentChar === escapedChar) {
2298
+ patternIndex += 2;
2299
+ contentIndex += 1;
2300
+ continue;
2301
+ }
2302
+ if (patternChar === contentChar) {
2303
+ contentIndex += 1;
2304
+ patternIndex += 1;
2305
+ continue;
2306
+ }
2307
+ break;
2308
+ }
2309
+ if (patternIndex === pattern.length) return [start, contentIndex];
2310
+ }
2311
+ return null;
2312
+ }
2313
+ /** Trim leading whitespace of the first line and trailing whitespace of the last line. */
2314
+ function trimPatternBoundaries(pattern) {
2315
+ const from = pattern.search(/\S/);
2316
+ const trimmed = from < 0 ? pattern : pattern.slice(from);
2317
+ const trailing = trimmed.search(/\s+$/);
2318
+ return trailing < 0 ? trimmed : trimmed.slice(0, trailing);
2319
+ }
2320
+ /** Replace only the fuzzy-matched span, preserving all surrounding bytes. */
2321
+ function fuzzyReplace(content, oldString, newString, replaceAll) {
2322
+ let current = content;
2323
+ let scanFrom = 0;
2324
+ for (;;) {
2325
+ const match = fuzzyIndexOf(current, oldString, scanFrom);
2326
+ if (match === null) return current;
2327
+ const [start, end] = match;
2328
+ const next = current.slice(0, start) + newString + current.slice(end);
2329
+ if (!replaceAll) return next;
2330
+ current = next;
2331
+ scanFrom = start + newString.length;
2332
+ }
2333
+ }
1072
2334
  function fuzzyPatch(content, oldString, newString, replaceAll = false) {
2335
+ if (oldString === "") return null;
1073
2336
  if (content.includes(oldString)) return replaceAll ? content.split(oldString).join(newString) : content.replace(oldString, newString);
1074
- const trimmed = content.replaceAll(/[ ]+$/gm, "");
1075
- if (trimmed.includes(oldString)) return trimmed.replace(oldString, newString);
1076
- const whitespace = content.replaceAll(/[ ]+/g, " ");
1077
- if (whitespace.includes(oldString)) return whitespace.replace(oldString, newString);
2337
+ const boundary = trimPatternBoundaries(oldString);
2338
+ if (boundary === "") return null;
2339
+ if (boundary !== oldString) {
2340
+ if (fuzzyIndexOf(content, boundary) !== null) {
2341
+ const patched = fuzzyReplace(content, boundary, newString, replaceAll);
2342
+ return patched === content ? null : patched;
2343
+ }
2344
+ }
2345
+ if (fuzzyIndexOf(content, oldString) !== null) {
2346
+ const patched = fuzzyReplace(content, oldString, newString, replaceAll);
2347
+ return patched === content ? null : patched;
2348
+ }
1078
2349
  return null;
1079
2350
  }
1080
2351
  var SkillLibrary = class {
1081
2352
  root;
1082
2353
  limits;
1083
2354
  io;
1084
- constructor(root = skillsRoot(), io = nodeEvolutionIo(), limits = DEFAULT_SKILL_LIMITS) {
2355
+ onMutation;
2356
+ constructor(root = skillsRoot(), io = nodeEvolutionIo(), limits = DEFAULT_SKILL_LIMITS, onMutation) {
1085
2357
  this.root = root;
1086
2358
  this.io = io;
1087
2359
  this.limits = limits;
2360
+ this.onMutation = onMutation;
2361
+ }
2362
+ /** Notify the mutation observer after a successful write; observers must never fail the mutation. */
2363
+ notifyMutation(event) {
2364
+ try {
2365
+ this.onMutation?.(event);
2366
+ } catch {}
1088
2367
  }
1089
2368
  async list() {
1090
2369
  const summaries = [];
1091
2370
  for (const name of await listNames(this.root, this.io)) {
1092
- const dir = skillDir(this.root, name);
2371
+ const dir = this.dirOf(name);
1093
2372
  const md = await this.io.readText(join(dir, "SKILL.md"));
1094
2373
  if (!md) continue;
1095
2374
  const parsed = parseFrontmatter(md);
1096
- const protectedBy = await this.deleteProtection(name);
1097
- const managed = await this.io.exists(markerPath(dir, "hermes-managed"));
2375
+ let entries = [];
2376
+ try {
2377
+ entries = await this.io.list(dir);
2378
+ } catch {}
2379
+ const has = (marker) => entries.includes(markerEntryName(marker));
2380
+ const protectedBy = has("bundled") ? "bundled" : has("hub-installed") ? "hub-installed" : has("pinned") ? "pinned" : null;
1098
2381
  summaries.push({
1099
2382
  name,
1100
2383
  description: parsed?.frontmatter.description ?? "",
1101
2384
  path: dir,
1102
2385
  protectedBy,
1103
- managed,
2386
+ managed: has("hermes-managed"),
1104
2387
  archived: false
1105
2388
  });
1106
2389
  }
1107
2390
  return summaries;
1108
2391
  }
1109
- async read(name) {
1110
- return this.io.readText(join(skillDir(this.root, name), "SKILL.md"));
2392
+ async read(rawName) {
2393
+ const name = rawName.trim();
2394
+ if (this.badName(name) !== null) return null;
2395
+ return this.io.readText(join(this.dirOf(name), "SKILL.md"));
2396
+ }
2397
+ /**
2398
+
2399
+ * Single path-building choke point (rc.42 audit P2-5): every directory path
2400
+
2401
+ * is built from the TRIMMED name, so a name that passes `badName` (which
2402
+
2403
+ * trims before validating) can never mint a second, whitespace-padded
2404
+
2405
+ * directory next to the real one. Callers keep passing raw user input.
2406
+
2407
+ */
2408
+ dirOf(name) {
2409
+ return skillDir(this.root, name.trim());
2410
+ }
2411
+ /** Name-format guard shared by every path-building mutator/reader. */
2412
+ badName(name) {
2413
+ const normalized = name.trim();
2414
+ if (!SKILL_NAME_RE.test(normalized) || normalized.length > this.limits.maxNameLength) return `Invalid skill name "${normalized}". Use lowercase letters, digits, and hyphens (<= ${this.limits.maxNameLength}).`;
2415
+ return null;
1111
2416
  }
1112
- async writeProtection(name) {
1113
- const dir = skillDir(this.root, name);
2417
+ async writeProtection(rawName, origin = "foreground") {
2418
+ const name = rawName.trim();
2419
+ const dir = this.dirOf(name);
1114
2420
  for (const marker of ["bundled", "hub-installed"]) if (await this.io.exists(markerPath(dir, marker))) return marker;
2421
+ if (origin === "background_review" && await this.io.exists(markerPath(dir, "pinned"))) return "pinned";
1115
2422
  return null;
1116
2423
  }
1117
- async deleteProtection(name) {
1118
- const dir = skillDir(this.root, name);
1119
- for (const marker of [
2424
+ async deleteProtection(rawName, options = {}) {
2425
+ const name = rawName.trim();
2426
+ const dir = this.dirOf(name);
2427
+ const markers = options.allowBundled ? ["hub-installed", "pinned"] : [
1120
2428
  "bundled",
1121
2429
  "hub-installed",
1122
2430
  "pinned"
1123
- ]) if (await this.io.exists(markerPath(dir, marker))) return marker;
2431
+ ];
2432
+ for (const marker of markers) if (await this.io.exists(markerPath(dir, marker))) return marker;
1124
2433
  return null;
1125
2434
  }
1126
- async isManaged(name) {
1127
- const dir = skillDir(this.root, name);
2435
+ async isManaged(rawName) {
2436
+ const name = rawName.trim();
2437
+ const dir = this.dirOf(name);
1128
2438
  return await this.io.exists(markerPath(dir, "hermes-managed"));
1129
2439
  }
1130
- async create(name, content, origin) {
2440
+ /** Whether the skill carries the bundled marker (curator prune-builtins eligibility). */
2441
+ async isBundled(rawName) {
2442
+ const name = rawName.trim();
2443
+ if (this.badName(name) !== null) return false;
2444
+ const dir = this.dirOf(name);
2445
+ return await this.io.exists(markerPath(dir, "bundled"));
2446
+ }
2447
+ /** Whether the skill carries the pinned marker (the marker is the factual source; usage.pinned mirrors it). */
2448
+ async isPinned(rawName) {
2449
+ const name = rawName.trim();
2450
+ if (this.badName(name) !== null) return false;
2451
+ const dir = this.dirOf(name);
2452
+ return await this.io.exists(markerPath(dir, "pinned"));
2453
+ }
2454
+ /** Count non-empty support subdirectories (richness input for quality scoring). */
2455
+ async countSupportDirs(rawName) {
2456
+ const name = rawName.trim();
2457
+ if (this.badName(name) !== null) return 0;
2458
+ const dir = this.dirOf(name);
2459
+ let entries;
2460
+ try {
2461
+ entries = await this.io.list(dir);
2462
+ } catch {
2463
+ return 0;
2464
+ }
2465
+ let count = 0;
2466
+ for (const subdir of SUPPORT_DIRS) {
2467
+ if (!entries.includes(subdir)) continue;
2468
+ try {
2469
+ if ((await this.io.list(join(dir, subdir))).some((file) => file !== ".gitkeep")) count += 1;
2470
+ } catch {}
2471
+ }
2472
+ return count;
2473
+ }
2474
+ /** Best-effort audit trail entry; never blocks the mutation. */
2475
+ async audit(skillName, action, before, after, summary) {
2476
+ try {
2477
+ await recordMutation(this.root, this.io, {
2478
+ skillName,
2479
+ action,
2480
+ ...before === null ? {} : { beforeHash: contentHash(before) },
2481
+ ...after === null ? {} : { afterHash: contentHash(after) },
2482
+ summary,
2483
+ at: (/* @__PURE__ */ new Date()).toISOString()
2484
+ });
2485
+ } catch {}
2486
+ }
2487
+ /** Recent mutation audit records (read-only inspection surface). */
2488
+ async listMutations() {
2489
+ return await loadMutations(this.root, this.io);
2490
+ }
2491
+ /**
2492
+ * Pin or unpin a skill (`.pinned` marker). Pinned skills are protected from
2493
+ * deletion, from background-review writes, and from the lifecycle — a
2494
+ * protective mutation, so the autonomous pipeline may never call it. The
2495
+ * marker write is the only state change; content is untouched.
2496
+ */
2497
+ async setPinned(name, pinned, origin = "foreground") {
2498
+ const normalized = name.trim();
2499
+ if (!SKILL_NAME_RE.test(normalized) || normalized.length > this.limits.maxNameLength) return {
2500
+ ok: false,
2501
+ message: `Invalid skill name "${normalized}". Use lowercase letters, digits, and hyphens (<= ${this.limits.maxNameLength}).`
2502
+ };
2503
+ if (origin === "background_review") return {
2504
+ ok: false,
2505
+ message: "Only the foreground (user or the main agent) may pin or unpin skills."
2506
+ };
2507
+ const dir = this.dirOf(normalized);
2508
+ const marker = markerPath(dir, "pinned");
2509
+ const existing = await this.io.exists(marker);
2510
+ if (pinned && existing) return {
2511
+ ok: true,
2512
+ message: `Skill "${normalized}" is already pinned.`,
2513
+ path: dir
2514
+ };
2515
+ if (!pinned && !existing) return {
2516
+ ok: true,
2517
+ message: `Skill "${normalized}" is not pinned; nothing to do.`,
2518
+ path: dir
2519
+ };
2520
+ if (!await this.io.exists(join(dir, "SKILL.md"))) return {
2521
+ ok: false,
2522
+ message: `Skill "${normalized}" not found.`
2523
+ };
2524
+ if (pinned) await this.io.writeText(marker, "");
2525
+ else await this.io.remove(marker);
2526
+ await this.audit(normalized, pinned ? "pin" : "unpin", null, null, pinned ? "pinned" : "unpinned");
2527
+ return {
2528
+ ok: true,
2529
+ message: pinned ? `Skill "${normalized}" pinned: protected from deletion, background review, and the lifecycle.` : `Skill "${normalized}" unpinned.`,
2530
+ path: dir
2531
+ };
2532
+ }
2533
+ async create(name, content, origin = "foreground") {
1131
2534
  const normalized = name.trim();
1132
2535
  if (!SKILL_NAME_RE.test(normalized) || normalized.length > this.limits.maxNameLength) return {
1133
2536
  ok: false,
@@ -1143,26 +2546,39 @@ var SkillLibrary = class {
1143
2546
  ok: false,
1144
2547
  message: threat
1145
2548
  };
1146
- const dir = skillDir(this.root, normalized);
2549
+ const dir = this.dirOf(normalized);
1147
2550
  if (await this.io.exists(join(dir, "SKILL.md"))) return {
1148
2551
  ok: false,
1149
2552
  message: `Skill "${normalized}" already exists.`
1150
2553
  };
1151
2554
  await this.io.writeText(join(dir, "SKILL.md"), content.trimEnd() + "\n");
1152
- if (origin === "background_review") await this.io.writeText(markerPath(dir, "hermes-managed"), "");
2555
+ if (origin !== "foreground") await this.io.writeText(markerPath(dir, "hermes-managed"), "");
2556
+ await this.audit(normalized, "create", null, content, "created");
2557
+ this.notifyMutation({
2558
+ action: "create",
2559
+ name: normalized,
2560
+ filePath: dir
2561
+ });
1153
2562
  return {
1154
2563
  ok: true,
1155
2564
  message: `Skill "${normalized}" created.`,
1156
2565
  path: dir
1157
2566
  };
1158
2567
  }
1159
- async update(name, content) {
1160
- const dir = skillDir(this.root, name);
1161
- if (!await this.io.readText(join(dir, "SKILL.md"))) return {
2568
+ async update(rawName, content, origin = "foreground") {
2569
+ const name = rawName.trim();
2570
+ const badName = this.badName(name);
2571
+ if (badName) return {
2572
+ ok: false,
2573
+ message: badName
2574
+ };
2575
+ const dir = this.dirOf(name);
2576
+ const md = await this.io.readText(join(dir, "SKILL.md"));
2577
+ if (!md) return {
1162
2578
  ok: false,
1163
2579
  message: `Skill "${name}" not found.`
1164
2580
  };
1165
- const protection = await this.writeProtection(name);
2581
+ const protection = await this.writeProtection(name, origin);
1166
2582
  if (protection) return {
1167
2583
  ok: false,
1168
2584
  message: `Skill "${name}" is protected (${protection}).`
@@ -1178,20 +2594,32 @@ var SkillLibrary = class {
1178
2594
  message: threat
1179
2595
  };
1180
2596
  await this.io.writeText(join(dir, "SKILL.md"), content.trimEnd() + "\n");
2597
+ await this.audit(name, "update", md, content, "updated");
2598
+ this.notifyMutation({
2599
+ action: "update",
2600
+ name,
2601
+ filePath: dir
2602
+ });
1181
2603
  return {
1182
2604
  ok: true,
1183
2605
  message: `Skill "${name}" updated.`,
1184
2606
  path: dir
1185
2607
  };
1186
2608
  }
1187
- async patch(name, oldString, newString, filePath = "", replaceAll = false) {
1188
- const dir = skillDir(this.root, name);
2609
+ async patch(rawName, oldString, newString, filePath = "", replaceAll = false, origin = "foreground") {
2610
+ const name = rawName.trim();
2611
+ const badName = this.badName(name);
2612
+ if (badName) return {
2613
+ ok: false,
2614
+ message: badName
2615
+ };
2616
+ const dir = this.dirOf(name);
1189
2617
  const skillMd = join(dir, "SKILL.md");
1190
2618
  if (!await this.io.exists(skillMd)) return {
1191
2619
  ok: false,
1192
2620
  message: `Skill "${name}" not found.`
1193
2621
  };
1194
- const protection = await this.writeProtection(name);
2622
+ const protection = await this.writeProtection(name, origin);
1195
2623
  if (protection) return {
1196
2624
  ok: false,
1197
2625
  message: `Skill "${name}" is protected (${protection}).`
@@ -1213,7 +2641,7 @@ var SkillLibrary = class {
1213
2641
  message: `File not found: ${patchLabel}`
1214
2642
  };
1215
2643
  const patched = fuzzyPatch(md, oldString, newString, replaceAll);
1216
- if (!patched) return {
2644
+ if (patched === null) return {
1217
2645
  ok: false,
1218
2646
  message: `Could not find old_string in "${name}/${patchLabel}". Use update for a full rewrite.`
1219
2647
  };
@@ -1238,40 +2666,69 @@ var SkillLibrary = class {
1238
2666
  message: threat
1239
2667
  };
1240
2668
  await this.io.writeText(target, patched.trimEnd() + "\n");
2669
+ await this.audit(name, "patch", md, patched, `patched ${patchLabel}`);
2670
+ this.notifyMutation({
2671
+ action: "patch",
2672
+ name,
2673
+ filePath: dir
2674
+ });
1241
2675
  return {
1242
2676
  ok: true,
1243
2677
  message: `Skill "${name}" patched (${patchLabel}).`,
1244
2678
  path: dir
1245
2679
  };
1246
2680
  }
1247
- async archive(name, absorbedInto = "") {
1248
- const dir = skillDir(this.root, name);
1249
- if (!await this.io.readText(join(dir, "SKILL.md"))) return {
2681
+ async archive(rawName, options = {}) {
2682
+ const name = rawName.trim();
2683
+ const badName = this.badName(name);
2684
+ if (badName) return {
2685
+ ok: false,
2686
+ message: badName
2687
+ };
2688
+ const dir = this.dirOf(name);
2689
+ const md = await this.io.readText(join(dir, "SKILL.md"));
2690
+ if (!md) return {
1250
2691
  ok: false,
1251
2692
  message: `Skill "${name}" not found.`
1252
2693
  };
1253
- const protection = await this.deleteProtection(name);
2694
+ const protection = await this.deleteProtection(name, options.allowBundled === void 0 ? {} : { allowBundled: options.allowBundled });
1254
2695
  if (protection) return {
1255
2696
  ok: false,
1256
2697
  message: `Skill "${name}" is protected (${protection}).`
1257
2698
  };
1258
- if (absorbedInto) {
1259
- if (!await this.io.readText(join(skillDir(this.root, absorbedInto), "SKILL.md"))) return {
2699
+ if (options.absorbedInto) {
2700
+ if (!await this.io.readText(join(this.dirOf(options.absorbedInto), "SKILL.md"))) return {
1260
2701
  ok: false,
1261
- message: `absorbed_into="${absorbedInto}" does not exist.`
2702
+ message: `absorbed_into="${options.absorbedInto}" does not exist.`
1262
2703
  };
1263
2704
  }
1264
2705
  const archiveRoot = join(this.root, ".archive");
1265
- let dest = join(archiveRoot, name);
1266
- if (await this.io.exists(dest)) dest = join(archiveRoot, `${name}-${(/* @__PURE__ */ new Date()).toISOString().replace(/[-:T]/g, "").slice(0, 14)}`);
2706
+ let dest = join(archiveRoot, name.trim());
2707
+ if (await this.io.exists(dest)) {
2708
+ const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[-:T]/g, "").slice(0, 14);
2709
+ dest = join(archiveRoot, `${name.trim()}-${stamp}`);
2710
+ while (await this.io.exists(dest)) dest = join(archiveRoot, `${name.trim()}-${stamp}-${Math.random().toString(36).slice(2, 8)}`);
2711
+ }
2712
+ if (this.io.isSymlink) {
2713
+ if (await this.io.isSymlink(dir) === true) return {
2714
+ ok: false,
2715
+ message: `Skill "${name}" is a symlink; refusing to archive it.`
2716
+ };
2717
+ }
1267
2718
  try {
1268
2719
  await this.io.rename(dir, dest);
1269
2720
  } catch {
1270
2721
  await this.io.copy(dir, dest);
1271
2722
  await this.io.remove(dir);
1272
2723
  }
1273
- const reason = absorbedInto ? `Consolidated into ${absorbedInto}` : "Archived by self-evolution curator";
2724
+ const reason = options.reason ?? (options.absorbedInto ? `Consolidated into ${options.absorbedInto}` : "Archived by self-evolution curator");
1274
2725
  await this.io.writeText(join(dest, ".archive-reason"), `${(/* @__PURE__ */ new Date()).toISOString()}: ${reason}\n`);
2726
+ await this.audit(name, "archive", md, null, reason);
2727
+ this.notifyMutation({
2728
+ action: "archive",
2729
+ name,
2730
+ archivedPath: dest
2731
+ });
1275
2732
  return {
1276
2733
  ok: true,
1277
2734
  message: `Skill "${name}" archived to .archive.`,
@@ -1283,26 +2740,27 @@ var SkillLibrary = class {
1283
2740
  * an absorbed-into marker. Hermes-style consolidation: overlapping skills
1284
2741
  * collapse into one, and the originals stay recoverable under `.archive/`.
1285
2742
  */
1286
- async consolidate(target, sources) {
1287
- const normalizedSources = [...new Set(sources)].filter((name) => name !== target);
2743
+ async consolidate(target, sources, origin = "foreground") {
2744
+ const targetName = target.trim();
2745
+ const normalizedSources = [...new Set(sources.map((name) => name.trim()))].filter((name) => name !== targetName);
1288
2746
  if (normalizedSources.length === 0) return {
1289
2747
  ok: false,
1290
2748
  message: "Consolidation requires at least one distinct source skill."
1291
2749
  };
1292
- for (const name of [target, ...normalizedSources]) if (!SKILL_NAME_RE.test(name)) return {
2750
+ for (const name of [targetName, ...normalizedSources]) if (!SKILL_NAME_RE.test(name)) return {
1293
2751
  ok: false,
1294
2752
  message: `Invalid skill name "${name}". Use lowercase letters, digits, and hyphens.`
1295
2753
  };
1296
- const targetDir = skillDir(this.root, target);
2754
+ const targetDir = this.dirOf(targetName);
1297
2755
  const targetMd = await this.io.readText(join(targetDir, "SKILL.md"));
1298
2756
  if (!targetMd) return {
1299
2757
  ok: false,
1300
- message: `Skill "${target}" not found.`
2758
+ message: `Skill "${targetName}" not found.`
1301
2759
  };
1302
- const targetProtection = await this.writeProtection(target);
2760
+ const targetProtection = await this.writeProtection(targetName, origin);
1303
2761
  if (targetProtection) return {
1304
2762
  ok: false,
1305
- message: `Skill "${target}" is protected (${targetProtection}).`
2763
+ message: `Skill "${targetName}" is protected (${targetProtection}).`
1306
2764
  };
1307
2765
  const parts = [];
1308
2766
  for (const source of normalizedSources) {
@@ -1311,7 +2769,7 @@ var SkillLibrary = class {
1311
2769
  ok: false,
1312
2770
  message: `Skill "${source}" is protected (${protection}).`
1313
2771
  };
1314
- const sourceMd = await this.io.readText(join(skillDir(this.root, source), "SKILL.md"));
2772
+ const sourceMd = await this.io.readText(join(this.dirOf(source), "SKILL.md"));
1315
2773
  if (!sourceMd) return {
1316
2774
  ok: false,
1317
2775
  message: `Skill "${source}" not found.`
@@ -1324,7 +2782,7 @@ var SkillLibrary = class {
1324
2782
  parts.push(`\n<!-- consolidated from ${source} at ${(/* @__PURE__ */ new Date()).toISOString()} -->\n${parsed.body.trim()}`);
1325
2783
  }
1326
2784
  const merged = targetMd.trimEnd() + parts.join("\n") + "\n";
1327
- const validation = validateFrontmatter(merged, target, this.limits);
2785
+ const validation = validateFrontmatter(merged, targetName, this.limits);
1328
2786
  if (validation) return {
1329
2787
  ok: false,
1330
2788
  message: `Consolidation rejected: ${validation}`
@@ -1334,14 +2792,30 @@ var SkillLibrary = class {
1334
2792
  ok: false,
1335
2793
  message: threat
1336
2794
  };
1337
- await this.io.writeText(join(targetDir, "SKILL.md"), merged);
1338
- for (const source of normalizedSources) {
1339
- const archived = await this.archive(source, target);
1340
- if (!archived.ok) return archived;
2795
+ const archived = [];
2796
+ try {
2797
+ for (const source of normalizedSources) {
2798
+ const result = await this.archive(source, { absorbedInto: targetName });
2799
+ if (!result.ok) throw new Error(result.message);
2800
+ archived.push(source);
2801
+ }
2802
+ await this.io.writeText(join(targetDir, "SKILL.md"), merged);
2803
+ } catch (error) {
2804
+ await this.io.writeText(join(targetDir, "SKILL.md"), targetMd).catch(() => {});
2805
+ for (const source of archived.reverse()) await this.restoreFromArchive(source).catch(() => {});
2806
+ return {
2807
+ ok: false,
2808
+ message: `Consolidation failed and was rolled back: ${error instanceof Error ? error.message : String(error)}`
2809
+ };
1341
2810
  }
2811
+ this.notifyMutation({
2812
+ action: "consolidate",
2813
+ name: targetName,
2814
+ filePath: targetDir
2815
+ });
1342
2816
  return {
1343
2817
  ok: true,
1344
- message: `Consolidated ${normalizedSources.join(", ")} into "${target}".`,
2818
+ message: `Consolidated ${normalizedSources.join(", ")} into "${targetName}".`,
1345
2819
  path: targetDir
1346
2820
  };
1347
2821
  }
@@ -1350,12 +2824,13 @@ var SkillLibrary = class {
1350
2824
  * recoverability: archival never deletes, and this is the control-plane
1351
2825
  * path back. The `.archive-reason` marker is dropped on restore.
1352
2826
  */
1353
- async restoreFromArchive(name) {
2827
+ async restoreFromArchive(rawName) {
2828
+ const name = rawName.trim();
1354
2829
  if (!SKILL_NAME_RE.test(name)) return {
1355
2830
  ok: false,
1356
2831
  message: `Invalid skill name "${name}". Use lowercase letters, digits, and hyphens.`
1357
2832
  };
1358
- if (await this.io.exists(join(skillDir(this.root, name), "SKILL.md"))) return {
2833
+ if (await this.io.exists(join(this.dirOf(name), "SKILL.md"))) return {
1359
2834
  ok: false,
1360
2835
  message: `Skill "${name}" already exists in the active root; refusing to overwrite.`
1361
2836
  };
@@ -1375,7 +2850,13 @@ var SkillLibrary = class {
1375
2850
  message: `Skill "${name}" is not in .archive.`
1376
2851
  };
1377
2852
  const source = join(archiveRoot, chosen);
1378
- const dest = skillDir(this.root, name);
2853
+ const dest = this.dirOf(name);
2854
+ if (this.io.isSymlink) {
2855
+ if (await this.io.isSymlink(source) === true) return {
2856
+ ok: false,
2857
+ message: `Archived entry "${chosen}" is a symlink; refusing to restore it.`
2858
+ };
2859
+ }
1379
2860
  try {
1380
2861
  await this.io.rename(source, dest);
1381
2862
  } catch {
@@ -1383,19 +2864,30 @@ var SkillLibrary = class {
1383
2864
  await this.io.remove(source);
1384
2865
  }
1385
2866
  if (await this.io.exists(join(dest, ".archive-reason"))) await this.io.remove(join(dest, ".archive-reason"));
2867
+ this.notifyMutation({
2868
+ action: "restore",
2869
+ name,
2870
+ filePath: dest
2871
+ });
1386
2872
  return {
1387
2873
  ok: true,
1388
2874
  message: `Skill "${name}" restored from .archive.`,
1389
2875
  path: dest
1390
2876
  };
1391
2877
  }
1392
- async writeSupportFile(name, filePath, content) {
1393
- const dir = skillDir(this.root, name);
2878
+ async writeSupportFile(rawName, filePath, content, origin = "foreground") {
2879
+ const name = rawName.trim();
2880
+ const badName = this.badName(name);
2881
+ if (badName) return {
2882
+ ok: false,
2883
+ message: badName
2884
+ };
2885
+ const dir = this.dirOf(name);
1394
2886
  if (!await this.io.exists(join(dir, "SKILL.md"))) return {
1395
2887
  ok: false,
1396
2888
  message: `Skill "${name}" not found.`
1397
2889
  };
1398
- const protection = await this.writeProtection(name);
2890
+ const protection = await this.writeProtection(name, origin);
1399
2891
  if (protection) return {
1400
2892
  ok: false,
1401
2893
  message: `Skill "${name}" is protected (${protection}).`
@@ -1415,20 +2907,33 @@ var SkillLibrary = class {
1415
2907
  message: threat
1416
2908
  };
1417
2909
  const target = join(dir, ...filePath.replace(/\\/g, "/").split("/").filter(Boolean));
2910
+ const existing = await this.io.readText(target).catch(() => null);
1418
2911
  await this.io.writeText(target, content);
2912
+ await this.audit(name, "write_file", existing, content, `wrote ${filePath}`);
2913
+ this.notifyMutation({
2914
+ action: "write_file",
2915
+ name,
2916
+ filePath: target
2917
+ });
1419
2918
  return {
1420
2919
  ok: true,
1421
2920
  message: `Support file "${filePath}" written to "${name}".`,
1422
2921
  path: target
1423
2922
  };
1424
2923
  }
1425
- async removeSupportFile(name, filePath) {
1426
- const dir = skillDir(this.root, name);
2924
+ async removeSupportFile(rawName, filePath, origin = "foreground") {
2925
+ const name = rawName.trim();
2926
+ const badName = this.badName(name);
2927
+ if (badName) return {
2928
+ ok: false,
2929
+ message: badName
2930
+ };
2931
+ const dir = this.dirOf(name);
1427
2932
  if (!await this.io.exists(join(dir, "SKILL.md"))) return {
1428
2933
  ok: false,
1429
2934
  message: `Skill "${name}" not found.`
1430
2935
  };
1431
- const protection = await this.writeProtection(name);
2936
+ const protection = await this.writeProtection(name, origin);
1432
2937
  if (protection) return {
1433
2938
  ok: false,
1434
2939
  message: `Skill "${name}" is protected (${protection}).`
@@ -1443,24 +2948,88 @@ var SkillLibrary = class {
1443
2948
  ok: false,
1444
2949
  message: `File "${filePath}" not found in skill "${name}".`
1445
2950
  };
2951
+ const before = await this.io.readText(target).catch(() => null);
1446
2952
  await this.io.remove(target);
2953
+ await this.audit(name, "remove_file", before, null, `removed ${filePath}`);
2954
+ this.notifyMutation({
2955
+ action: "remove_file",
2956
+ name,
2957
+ filePath: target
2958
+ });
1447
2959
  return {
1448
2960
  ok: true,
1449
2961
  message: `Support file "${filePath}" removed from "${name}".`,
1450
2962
  path: target
1451
2963
  };
1452
2964
  }
1453
- async snapshotAll(reason = "pre-mutation") {
1454
- const dest = join(join(this.root, ".backups"), `skills-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}`);
2965
+ /**
2966
+ * Snapshot the recoverable skills state: active tree, usage/suppression
2967
+ * sidecars, `.archive/` and caller-supplied extras. `extras` are opaque
2968
+ * side files the Snapshot owner cares about (curator state); they are
2969
+ * listed in the manifest and only those names are ever read back.
2970
+ */
2971
+ async snapshotAll(reason = "pre-mutation", extras = []) {
2972
+ const backupRoot = join(this.root, ".backups");
2973
+ const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
2974
+ let dest = join(backupRoot, `skills-${stamp}`);
2975
+ while (await this.io.exists(dest)) dest = join(backupRoot, `skills-${stamp}-${Math.random().toString(36).slice(2, 8)}`);
1455
2976
  const names = await listNames(this.root, this.io);
1456
- for (const name of names) await this.io.copy(skillDir(this.root, name), join(dest, name));
2977
+ await Promise.all(names.map(async (name) => {
2978
+ await this.io.copy(this.dirOf(name), join(dest, name));
2979
+ }));
2980
+ const sidecars = [];
2981
+ for (const sidecar of [usageFile(this.root), suppressedFile(this.root)]) if (await this.io.exists(sidecar)) {
2982
+ const name = basename(sidecar);
2983
+ await this.io.copy(sidecar, join(dest, name));
2984
+ sidecars.push(name);
2985
+ }
2986
+ const archiveRoot = join(this.root, ".archive");
2987
+ let hasArchive = false;
2988
+ if (await this.io.exists(archiveRoot)) {
2989
+ await this.io.copy(archiveRoot, join(dest, ".archive"));
2990
+ hasArchive = true;
2991
+ }
2992
+ const validExtras = extras.filter((extra) => SNAPSHOT_EXTRA_NAME_RE.test(extra.name));
2993
+ const extraNames = validExtras.map((extra) => extra.name);
2994
+ await Promise.all(validExtras.map(async (extra) => {
2995
+ await this.io.writeText(join(dest, "extras", extra.name), extra.content);
2996
+ }));
1457
2997
  await this.io.writeText(join(dest, "manifest.json"), JSON.stringify({
1458
2998
  reason,
1459
2999
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1460
- skills: names
3000
+ skills: names,
3001
+ sidecars,
3002
+ hasArchive,
3003
+ extras: extraNames
1461
3004
  }, null, 2));
3005
+ await this.retainSnapshots(5);
1462
3006
  return dest;
1463
3007
  }
3008
+ /** Read and normalize a snapshot manifest; null when the file is missing or unparsable. */
3009
+ async readSnapshotManifest(path) {
3010
+ const raw = await this.io.readText(join(path, "manifest.json"));
3011
+ if (raw === null) return null;
3012
+ try {
3013
+ const manifest = JSON.parse(raw);
3014
+ return {
3015
+ reason: typeof manifest.reason === "string" ? manifest.reason : "",
3016
+ createdAt: typeof manifest.createdAt === "string" ? manifest.createdAt : "",
3017
+ skills: Array.isArray(manifest.skills) ? manifest.skills : [],
3018
+ sidecars: Array.isArray(manifest.sidecars) ? manifest.sidecars : [],
3019
+ ...typeof manifest.hasArchive === "boolean" ? { hasArchive: manifest.hasArchive } : {},
3020
+ extras: Array.isArray(manifest.extras) ? manifest.extras : []
3021
+ };
3022
+ } catch {
3023
+ return null;
3024
+ }
3025
+ }
3026
+ /** Keep only the newest N snapshots (Hermes keep=5 parity); older ones are removed outright. */
3027
+ async retainSnapshots(keep) {
3028
+ const snapshots = await this.listSnapshots();
3029
+ for (const snapshot of snapshots.slice(keep)) try {
3030
+ await this.io.remove(snapshot.path);
3031
+ } catch {}
3032
+ }
1464
3033
  async listSnapshots() {
1465
3034
  const backupRoot = join(this.root, ".backups");
1466
3035
  let entries;
@@ -1472,96 +3041,93 @@ var SkillLibrary = class {
1472
3041
  const out = [];
1473
3042
  for (const name of entries.sort().reverse()) {
1474
3043
  if (!name.startsWith("skills-")) continue;
1475
- try {
1476
- const raw = await this.io.readText(join(backupRoot, name, "manifest.json"));
1477
- if (raw === null) continue;
1478
- const manifest = JSON.parse(raw);
1479
- out.push({
1480
- path: join(backupRoot, name),
1481
- createdAt: manifest.createdAt ?? "",
1482
- reason: manifest.reason ?? ""
1483
- });
1484
- } catch {}
3044
+ const manifest = await this.readSnapshotManifest(join(backupRoot, name));
3045
+ if (manifest === null) continue;
3046
+ out.push({
3047
+ path: join(backupRoot, name),
3048
+ createdAt: manifest.createdAt,
3049
+ reason: manifest.reason
3050
+ });
1485
3051
  }
1486
3052
  return out;
1487
3053
  }
1488
- async restoreLatestSnapshot() {
3054
+ /**
3055
+ * Read the extras of a snapshot, restricted to the names declared in the
3056
+ * manifest — an `extras/` directory is never listed directly, so unknown
3057
+ * files cannot leak back as state on the next restore.
3058
+ */
3059
+ async readSnapshotExtras(path) {
3060
+ const manifest = await this.readSnapshotManifest(path);
3061
+ if (manifest === null) return [];
3062
+ const extras = [];
3063
+ for (const name of manifest.extras) {
3064
+ if (!SNAPSHOT_EXTRA_NAME_RE.test(name)) continue;
3065
+ const content = await this.io.readText(join(path, "extras", name));
3066
+ if (content !== null) extras.push({
3067
+ name,
3068
+ content
3069
+ });
3070
+ }
3071
+ return extras;
3072
+ }
3073
+ /**
3074
+ * Manifest-driven restore of the latest snapshot: active tree, sidecars,
3075
+ * `.archive/` and (for full-state snapshots) the extras read back by the
3076
+ * caller. `extras` are additionally written into the pre-rollback safety
3077
+ * snapshot so the rollback itself is undoable with the same state.
3078
+ */
3079
+ async restoreLatestSnapshot(extras = []) {
1489
3080
  const latest = (await this.listSnapshots())[0];
1490
3081
  if (!latest) return {
1491
3082
  ok: false,
1492
3083
  message: "No skill snapshot available."
1493
3084
  };
1494
- await this.snapshotAll("pre-rollback");
1495
- for (const name of await listNames(this.root, this.io)) await this.io.remove(skillDir(this.root, name));
1496
- const entries = await this.io.list(latest.path);
1497
- for (const entry of entries) {
1498
- if (entry === "manifest.json") continue;
3085
+ await this.snapshotAll("pre-rollback", extras);
3086
+ let rootEntries;
3087
+ try {
3088
+ rootEntries = await this.io.list(this.root);
3089
+ } catch {
3090
+ rootEntries = [];
3091
+ }
3092
+ for (const entry of rootEntries) {
3093
+ if (entry.startsWith(".")) continue;
3094
+ await this.io.remove(join(this.root, entry));
3095
+ }
3096
+ const manifest = await this.readSnapshotManifest(latest.path);
3097
+ if (manifest === null) for (const entry of await this.io.list(latest.path)) {
3098
+ if (entry === "manifest.json" || entry === "extras") continue;
1499
3099
  await this.io.copy(join(latest.path, entry), join(this.root, entry));
1500
3100
  }
3101
+ else {
3102
+ for (const name of manifest.skills) await this.io.copy(join(latest.path, name), join(this.root, name));
3103
+ for (const sidecar of manifest.sidecars) await this.io.copy(join(latest.path, sidecar), join(this.root, sidecar));
3104
+ const archiveRoot = join(this.root, ".archive");
3105
+ if (manifest.hasArchive === true) {
3106
+ await this.io.remove(archiveRoot);
3107
+ await this.io.copy(join(latest.path, ".archive"), archiveRoot);
3108
+ } else if (manifest.hasArchive === false) await this.io.remove(archiveRoot);
3109
+ }
3110
+ const snapshotExtras = await this.readSnapshotExtras(latest.path);
3111
+ this.notifyMutation({
3112
+ action: "restore",
3113
+ name: "snapshot"
3114
+ });
1501
3115
  return {
1502
3116
  ok: true,
1503
3117
  message: `Restored skill tree from ${latest.path}`,
1504
- path: latest.path
3118
+ path: latest.path,
3119
+ ...snapshotExtras.length === 0 ? {} : { extras: snapshotExtras }
1505
3120
  };
1506
3121
  }
1507
3122
  };
1508
3123
  //#endregion
1509
3124
  //#region lib/types/state-store.js
1510
3125
  /**
1511
- * Small crash-safe JSON state store for plugin-owned sidecar state.
1512
- * Writes are atomic (temp + rename). Reads are synchronous for startup use.
3126
+ * Evolution home path helper: `$DSH_HOME/evolution` for plugin-owned sidecar
3127
+ * state (reports, activity store, feedback file, state-domain data).
1513
3128
  */
1514
3129
  function evolutionHome(env = process.env) {
1515
3130
  return join(env.DSH_HOME ?? join(homedir(), ".dsh"), "evolution");
1516
3131
  }
1517
- var JsonState = class {
1518
- initial;
1519
- path;
1520
- value;
1521
- constructor(name, initial, env = process.env) {
1522
- this.initial = initial;
1523
- this.path = join(evolutionHome(env), name);
1524
- this.value = this.loadSync();
1525
- }
1526
- loadSync() {
1527
- try {
1528
- const raw = readFileSync(this.path, "utf8");
1529
- const parsed = JSON.parse(raw);
1530
- return {
1531
- ...this.initial,
1532
- ...parsed
1533
- };
1534
- } catch {
1535
- return { ...this.initial };
1536
- }
1537
- }
1538
- get() {
1539
- return this.value;
1540
- }
1541
- set(value) {
1542
- this.value = value;
1543
- }
1544
- update(mutator) {
1545
- mutator(this.value);
1546
- }
1547
- async flush() {
1548
- await mkdir(dirname(this.path), { recursive: true });
1549
- const tmp = `${this.path}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
1550
- await writeFile(tmp, JSON.stringify(this.value, null, 2), "utf8");
1551
- await rename(tmp, this.path);
1552
- }
1553
- /** Merge-on-load helper for persisted maps/records. */
1554
- async reload() {
1555
- try {
1556
- const raw = await readFile(this.path, "utf8");
1557
- this.value = {
1558
- ...this.initial,
1559
- ...JSON.parse(raw)
1560
- };
1561
- } catch {
1562
- this.value = { ...this.initial };
1563
- }
1564
- }
1565
- };
1566
3132
  //#endregion
1567
- export { COMBINED_REVIEW_PROMPT, CURATOR_PROMPT, DEFAULT_SKILL_LIMITS, DSH_AUTHORING_STANDARDS, ENTRY_DELIMITER, JsonState, MAX_DESCRIPTION_LENGTH, MAX_SKILL_CONTENT_CHARS, MAX_SKILL_FILE_BYTES, MAX_SKILL_NAME_LENGTH, MEMORY_REVIEW_PROMPT, MemoryStore, PROMPT_BUNDLE, PROMPT_BUNDLE_ID, PROTECTED_BUILTIN_SKILLS, SKILL_NAME_RE, SKILL_REVIEW_PROMPT, SUPPORT_DIRS, SkillLibrary, advanceReview, buildCuratorRunReport, bumpPatch, bumpUse, bumpView, childPath, computeLifecycleTransitions, emptyRecord, evaluateThreat, evolutionHome, evolutionIoAdapter, foldTurn, getRecord, latestActivityAt, loadUsage, markAgentCreated, memoryRoot, nodeEvolutionIo, observeEvent, parseFrontmatter, reviewPrompt, saveUsage, scanContentThreats, scanMemoryThreats, scanThreats, skillsRoot, usageFile, validateFrontmatter, verifyPromptBundle };
3133
+ export { AUTHORING_DESCRIPTION_BAR, COMBINED_REVIEW_PLAN_PROMPT, COMBINED_REVIEW_PROMPT, COMPLETION_SKILL_REVIEW_PROMPT, CURATOR_DRY_RUN_BANNER, CURATOR_PROMPT, DEFAULT_ARCHIVE_AFTER_DAYS, DEFAULT_CONSOLIDATION_FAILURES, DEFAULT_CURATOR_INTERVAL_HOURS, DEFAULT_MAX_OPS_PER_PLAN, DEFAULT_MEMORY_CHAR_LIMIT, DEFAULT_MIN_IDLE_HOURS, DEFAULT_MUTATION_CAP, DEFAULT_REVIEW_MEMORY_INTERVAL, DEFAULT_REVIEW_SKILL_INTERVAL, DEFAULT_SKILL_CONTENT_CHARS, DEFAULT_SKILL_LIMITS, DEFAULT_SKILL_REVIEW_COMPLETION_MIN_TOOL_CALLS, DEFAULT_SKILL_REVIEW_TRIGGER, DEFAULT_STALE_AFTER_DAYS, DEFAULT_SUBSTANTIVE_MIN_AGENT_CHARS, DEFAULT_SUBSTANTIVE_MIN_TOOL_CALLS, DEFAULT_SUBSTANTIVE_MIN_USER_CHARS, DEFAULT_USER_CHAR_LIMIT, DSH_AUTHORING_STANDARDS, ENTRY_DELIMITER, EVENT_LOG_VERSION, EvolutionGateSet, LOW_QUALITY_THRESHOLD, MAX_DESCRIPTION_LENGTH, MAX_SKILL_CONTENT_CHARS, MAX_SKILL_FILE_BYTES, MAX_SKILL_NAME_LENGTH, MEMORY_REVIEW_PROMPT, MUTATIONS_FILE_VERSION, MemoryStore, PROMPT_BUNDLE, PROMPT_BUNDLE_ID, PROMPT_BUNDLE_VERSION, PROTECTED_BUILTIN_SKILLS, QUALITY_WEIGHTS, SKILLS_GUIDANCE, SKILL_NAME_RE, SKILL_REVIEW_PLAN_PROMPT, SKILL_REVIEW_PROMPT, SNAPSHOT_EXTRA_NAME_RE, SUPPORT_DIRS, SUPPRESSED_FILE_VERSION, SkillLibrary, advanceReview, appendEvolutionEvent, applyCuratorFields, authoringFeedback, buildCuratorRunReport, buildLearnPrompt, bumpPatch, bumpUse, bumpView, computeDedupGroups, computeLifecycleTransitions, computePrefixClusters, computeQualityScores, computeScopeView, contentHash, createGateSet, emptyRecord, evaluateThreat, eventsFile, evolutionHome, evolutionIoAdapter, foldCuratorFields, foldTurn, getRecord, latestActivityAt, lifecycleCandidate, loadMutations, loadSuppressedNames, loadUsage, markAgentCreated, memoryRoot, mutateUsage, mutationsFile, nodeEvolutionIo, normalizeUsageRecord, observeEvent, parseCuratorNominations, parseEvolutionEvents, parseFrontmatter, readEvolutionEvents, recordMutation, relatedSkillNames, renderCuratorReportMarkdown, resolveOrigins, reviewPrompt, saveSuppressedNames, saveUsage, scanContentThreats, scanMemoryThreats, scanThreats, skillsRoot, suppressedFile, transactIo, updateSuppressedNames, usageFile, validateFrontmatter, verifyPromptBundle };