@lmzhen/dsh-evolution-core 0.1.0-rc.6 → 0.1.0-rc.60

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,95 @@ 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
+ /**
56
+ * Cross-process write lock (claw `withFileLock` parity): an O_EXCL lock file
57
+ * guards the atomic write; a >5s-old lock is treated as stale and taken
58
+ * over. After the retry budget the write proceeds unlocked — the lock is a
59
+ * best-effort accommodation for multi-process deployments, never a read of
60
+ * availability.
61
+ */
62
+ const withWriteLock = async (path, task) => {
63
+ const lock = `${path}.lock`;
64
+ for (let attempt = 0; attempt < 10; attempt += 1) try {
65
+ await writeFile(lock, String(process.pid), { flag: "wx" });
66
+ try {
67
+ return await task();
68
+ } finally {
69
+ await rm(lock, { force: true }).catch(() => {});
70
+ }
71
+ } catch (error) {
72
+ if (error?.code !== "EEXIST") throw error;
73
+ try {
74
+ const st = await stat(lock);
75
+ if (Date.now() - st.mtimeMs > 5e3) {
76
+ try {
77
+ await rm(lock, { force: true });
78
+ } catch {}
79
+ continue;
80
+ }
81
+ } catch {
82
+ continue;
83
+ }
84
+ await new Promise((resolve) => setTimeout(resolve, 50));
85
+ }
86
+ return await task();
87
+ };
27
88
  return {
28
89
  async readText(path) {
29
90
  try {
30
91
  return await readFile(path, "utf8");
31
- } catch {
32
- return null;
92
+ } catch (error) {
93
+ if (isMissing(error)) return null;
94
+ throw error;
33
95
  }
34
96
  },
35
97
  async writeText(path, content) {
36
98
  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);
99
+ await withWriteLock(path, async () => {
100
+ const tmp = `${path}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
101
+ await writeFile(tmp, content, "utf8");
102
+ await rename(tmp, path);
103
+ });
104
+ },
105
+ async transact(path, task) {
106
+ await mkdir(dirname(path), { recursive: true });
107
+ await withWriteLock(path, async () => {
108
+ let current;
109
+ try {
110
+ current = await readFile(path, "utf8");
111
+ } catch (error) {
112
+ if (isMissing(error)) current = null;
113
+ else throw error;
114
+ }
115
+ const next = await task(current);
116
+ if (next === null) {
117
+ await rm(path, { force: true });
118
+ return;
119
+ }
120
+ const tmp = `${path}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
121
+ await writeFile(tmp, next, "utf8");
122
+ await rename(tmp, path);
123
+ });
40
124
  },
41
125
  async remove(path) {
42
126
  await rm(path, {
@@ -47,16 +131,18 @@ function nodeEvolutionIo() {
47
131
  async list(path) {
48
132
  try {
49
133
  return await readdir(path);
50
- } catch {
51
- return [];
134
+ } catch (error) {
135
+ if (isMissing(error)) return [];
136
+ throw error;
52
137
  }
53
138
  },
54
139
  async exists(path) {
55
140
  try {
56
141
  await stat(path);
57
142
  return true;
58
- } catch {
59
- return false;
143
+ } catch (error) {
144
+ if (isMissing(error)) return false;
145
+ throw error;
60
146
  }
61
147
  },
62
148
  async rename(path, destination) {
@@ -69,13 +155,24 @@ function nodeEvolutionIo() {
69
155
  recursive: true,
70
156
  force: true
71
157
  });
158
+ },
159
+ async size(path) {
160
+ try {
161
+ return (await stat(path)).size;
162
+ } catch (error) {
163
+ if (isMissing(error)) return null;
164
+ throw error;
165
+ }
166
+ },
167
+ async isSymlink(path) {
168
+ try {
169
+ return (await lstat(path)).isSymbolicLink();
170
+ } catch {
171
+ return null;
172
+ }
72
173
  }
73
174
  };
74
175
  }
75
- /** Absolute path helper kept separate so stores stay platform-correct. */
76
- function childPath(parent, ...parts) {
77
- return join(parent, ...parts);
78
- }
79
176
  //#endregion
80
177
  //#region lib/types/usage.js
81
178
  /**
@@ -100,22 +197,71 @@ function emptyRecord() {
100
197
  archived_at: null
101
198
  };
102
199
  }
103
- async function loadUsage(root, io = nodeEvolutionIo()) {
200
+ /** A timestamp passes only when `Date.parse` yields a finite epoch (N-3): a bare
201
+ * string check let garbage like "not-a-date" propagate as Invalid Date → NaN
202
+ * into quality math and lifecycle comparisons. */
203
+ const validTimestamp = (value) => typeof value === "string" && Number.isFinite(Date.parse(value));
204
+ const nullableTimestamp = (value) => value === null || validTimestamp(value);
205
+ /**
206
+ * Field-level normalization for one sidecar record (rc.42 audit P2-3): the
207
+ * spread used to copy any junk through verbatim, so a corrupted file could
208
+ * carry `use_count: "3"` into the quality math and lifecycle comparisons as
209
+ * NaN. Every field falls back to its `emptyRecord()` baseline unless it has
210
+ * exactly the declared type; an invalid `created_at` anchors the age clock at
211
+ * now (first-sight defer semantics for a record whose age is unknowable).
212
+ * Timestamps additionally require a parseable date (N-3): `"not-a-date"`
213
+ * would otherwise survive the type check as Invalid Date.
214
+ * Pure — exported for unit tests; `loadUsage` is the production caller.
215
+ */
216
+ function normalizeUsageRecord(record) {
217
+ const base = emptyRecord();
218
+ if (!record || typeof record !== "object" || Array.isArray(record)) return base;
219
+ const raw = record;
220
+ const num = (value, fallback) => typeof value === "number" && Number.isFinite(value) ? value : fallback;
221
+ const bool = (value, fallback) => typeof value === "boolean" ? value : fallback;
222
+ return {
223
+ created_by: typeof raw.created_by === "string" ? raw.created_by : null,
224
+ use_count: num(raw.use_count, base.use_count),
225
+ view_count: num(raw.view_count, base.view_count),
226
+ patch_count: num(raw.patch_count, base.patch_count),
227
+ last_used_at: nullableTimestamp(raw.last_used_at) ? raw.last_used_at : base.last_used_at,
228
+ last_viewed_at: nullableTimestamp(raw.last_viewed_at) ? raw.last_viewed_at : base.last_viewed_at,
229
+ last_patched_at: nullableTimestamp(raw.last_patched_at) ? raw.last_patched_at : base.last_patched_at,
230
+ created_at: validTimestamp(raw.created_at) ? raw.created_at : base.created_at,
231
+ state: raw.state === "stale" || raw.state === "archived" ? raw.state : "active",
232
+ pinned: bool(raw.pinned, base.pinned),
233
+ archived_at: nullableTimestamp(raw.archived_at) ? raw.archived_at : base.archived_at,
234
+ quality_score: typeof raw.quality_score === "number" && Number.isFinite(raw.quality_score) ? raw.quality_score : void 0,
235
+ quality_warn: typeof raw.quality_warn === "boolean" ? raw.quality_warn : void 0
236
+ };
237
+ }
238
+ /** Parse a raw usage sidecar; malformed content reads as empty (best-effort telemetry). */
239
+ function parseUsage(raw) {
104
240
  const map = /* @__PURE__ */ new Map();
105
- const raw = await io.readText(usageFile(root));
106
- if (raw !== null) try {
241
+ if (raw === null) return map;
242
+ try {
107
243
  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
- }
244
+ for (const [name, record] of Object.entries(parsed)) map.set(name, normalizeUsageRecord(record));
116
245
  } catch {}
117
246
  return map;
118
247
  }
248
+ async function loadUsage(root, io = nodeEvolutionIo()) {
249
+ return parseUsage(await io.readText(usageFile(root)));
250
+ }
251
+ /**
252
+ * Atomic read-modify-write on the usage sidecar (rc.50 P2-2): `task` receives
253
+ * the map parsed from the current on-disk state and may mutate it; the result
254
+ * is persisted inside the same transact so a second process sharing DSH_HOME
255
+ * cannot interleave its RMW and lose a counter update. Callers keep their own
256
+ * single-process serialize chain as the second layer.
257
+ */
258
+ async function mutateUsage(root, io, task) {
259
+ await transactIo(io, usageFile(root), async (current) => {
260
+ const map = parseUsage(current);
261
+ await task(map);
262
+ return JSON.stringify(Object.fromEntries(map.entries()), null, 2);
263
+ });
264
+ }
119
265
  async function saveUsage(root, map, io = nodeEvolutionIo()) {
120
266
  const obj = Object.fromEntries(map.entries());
121
267
  await io.writeText(usageFile(root), JSON.stringify(obj, null, 2));
@@ -155,15 +301,169 @@ function latestActivityAt(record) {
155
301
  if (values.length === 0) return null;
156
302
  return values.sort().reverse()[0] ?? null;
157
303
  }
304
+ /**
305
+ * Curator suppression sidecar: built-in skills the curator has archived stay
306
+ * suppressed across re-seeds, so the lifecycle never fights a re-created
307
+ * bundled skill. Best-effort load/save, mirroring the usage sidecar posture.
308
+ * Versioned shape ({ version, names }) with legacy plain-array compat.
309
+ */
310
+ const SUPPRESSED_FILE_VERSION = 1;
311
+ function suppressedFile(root) {
312
+ return join(root, ".curator-suppressed.json");
313
+ }
314
+ async function loadSuppressedNames(root, io = nodeEvolutionIo()) {
315
+ return parseSuppressed(await io.readText(suppressedFile(root)));
316
+ }
317
+ function parseSuppressed(raw) {
318
+ if (raw === null) return /* @__PURE__ */ new Set();
319
+ try {
320
+ const parsed = JSON.parse(raw);
321
+ const names = Array.isArray(parsed) ? parsed : typeof parsed === "object" && parsed !== null && Array.isArray(parsed.names) ? parsed.names : [];
322
+ return new Set(names.filter((entry) => typeof entry === "string"));
323
+ } catch {
324
+ return /* @__PURE__ */ new Set();
325
+ }
326
+ }
327
+ async function saveSuppressedNames(root, names, io = nodeEvolutionIo()) {
328
+ await io.writeText(suppressedFile(root), JSON.stringify({
329
+ version: 1,
330
+ names: [...names].sort()
331
+ }, null, 2));
332
+ }
333
+ /**
334
+ * Atomic read-modify-write on the suppression sidecar (rc.50 P2-2): `task`
335
+ * receives the set parsed from the current on-disk state and may mutate it;
336
+ * the result is persisted inside the same transact so a second process
337
+ * sharing DSH_HOME cannot interleave its RMW. Best-effort posture unchanged.
338
+ */
339
+ async function updateSuppressedNames(root, io, task) {
340
+ await transactIo(io, suppressedFile(root), async (current) => {
341
+ const names = parseSuppressed(current);
342
+ await task(names);
343
+ return JSON.stringify({
344
+ version: 1,
345
+ names: [...names].sort()
346
+ }, null, 2);
347
+ });
348
+ }
349
+ //#endregion
350
+ //#region lib/types/constants.js
351
+ /**
352
+ * Shared constants for the dsh-evolution plugin family.
353
+ *
354
+ * Two classes of value live here, deliberately separated by section so future
355
+ * edits do not blur the semantic boundary:
356
+ *
357
+ * 1. **Fixed protocol/format/security invariants** — changing these breaks an
358
+ * on-disk format, a naming/format contract, a path-security boundary, or a
359
+ * cross-component invariant. They are NOT exposed as deployment config.
360
+ *
361
+ * 2. **Cross-package shared tunable defaults** — the same semantic default is
362
+ * read (with a config override path) by more than one package (e.g.
363
+ * `evolution-policy` and `evolution-curator` both default `staleAfterDays`
364
+ * to 30). Centralizing them here means one authoritative default: a config
365
+ * override still applies per package, but the fallback is single-sourced.
366
+ *
367
+ * Package-private tunables (used by exactly one package) stay in that package,
368
+ * not here — see evolution-replay's `DEFAULT_WEIGHTS` and evolution-feedback's
369
+ * threshold, which are intentionally left where they are used.
370
+ * @module @lmzhen/dsh-evolution-core
371
+ */
372
+ /** Skill frontmatter `name` validated for the file name (lowercase + hyphen). */
373
+ const SKILL_NAME_RE = /^[a-z0-9][a-z0-9-]*$/;
374
+ /** Allowed skill support-file subdirectories (path-traversal boundary). */
375
+ const SUPPORT_DIRS = [
376
+ "references",
377
+ "templates",
378
+ "scripts",
379
+ "assets"
380
+ ];
381
+ /** Delimiter between durable memory entries (on-disk storage format). */
382
+ const ENTRY_DELIMITER = "\n§\n";
383
+ /** Built-in skill names the curator must never lifecycle-manage. */
384
+ const PROTECTED_BUILTIN_SKILLS = new Set(["plan"]);
385
+ const MAX_SKILL_NAME_LENGTH = 64;
386
+ const MAX_DESCRIPTION_LENGTH = 1024;
387
+ const MAX_SKILL_CONTENT_CHARS = 1e5;
388
+ const MAX_SKILL_FILE_BYTES = 1048576;
389
+ const DEFAULT_REVIEW_MEMORY_INTERVAL = 10;
390
+ const DEFAULT_REVIEW_SKILL_INTERVAL = 10;
391
+ /** Skill-review completion channel trigger mode: 'cadence' | 'completion' | 'both'. */
392
+ const DEFAULT_SKILL_REVIEW_TRIGGER = "both";
393
+ /** Cumulative session tool calls before a session counts as "proven long" for the completion channel. */
394
+ const DEFAULT_SKILL_REVIEW_COMPLETION_MIN_TOOL_CALLS = 20;
395
+ const DEFAULT_SUBSTANTIVE_MIN_TOOL_CALLS = 3;
396
+ const DEFAULT_SUBSTANTIVE_MIN_USER_CHARS = 200;
397
+ const DEFAULT_SUBSTANTIVE_MIN_AGENT_CHARS = 500;
398
+ const DEFAULT_MAX_OPS_PER_PLAN = 32;
399
+ const DEFAULT_CURATOR_INTERVAL_HOURS = 168;
400
+ const DEFAULT_MIN_IDLE_HOURS = 2;
401
+ const DEFAULT_STALE_AFTER_DAYS = 30;
402
+ const DEFAULT_ARCHIVE_AFTER_DAYS = 90;
403
+ const DEFAULT_MEMORY_CHAR_LIMIT = 2200;
404
+ const DEFAULT_USER_CHAR_LIMIT = 1375;
405
+ /** Consolidation-failure backoff cap, shared by MemoryStore and memory-files' Config default. */
406
+ const DEFAULT_CONSOLIDATION_FAILURES = 3;
407
+ const DEFAULT_SKILL_CONTENT_CHARS = 1e5;
408
+ //#endregion
409
+ //#region lib/types/gates.js
410
+ /**
411
+ * The control-plane protection sets, held once and queried everywhere
412
+ * (decision B, rc.44 plan M2): the lifecycle engine, the scope view, the LLM
413
+ * nomination gate and the control-plane consolidate all answer "is this name
414
+ * off limits — and why" from the same instance, so the gate sets can never
415
+ * drift apart the way the three pre-rc.46 implementations did.
416
+ *
417
+ * Scope boundary: a GateSet covers NAME-SET protections only. Marker-based
418
+ * protections (pinned / bundled / hub-installed) are file markers resolved by
419
+ * `SkillLibrary.writeProtection` / `deleteProtection` — they depend on the
420
+ * filesystem and the write origin, not on a name list.
421
+ * @module @lmzhen/dsh-evolution-core
422
+ */
423
+ var EvolutionGateSet = class {
424
+ exclude;
425
+ referenced;
426
+ suppressed;
427
+ constructor(inputs = {}) {
428
+ this.exclude = inputs.exclude ?? /* @__PURE__ */ new Set();
429
+ this.referenced = inputs.referenced ?? /* @__PURE__ */ new Set();
430
+ this.suppressed = inputs.suppressed ?? /* @__PURE__ */ new Set();
431
+ }
432
+ /**
433
+ * The first protection blocking this name, or null. Any hit blocks — the
434
+ * order is diagnostic only, so a name in two sets reports the first.
435
+ */
436
+ blockReason(name) {
437
+ if (this.exclude.has(name)) return "excluded";
438
+ if (this.referenced.has(name)) return "referenced";
439
+ if (this.suppressed.has(name)) return "suppressed";
440
+ if (PROTECTED_BUILTIN_SKILLS.has(name)) return "protected-builtin";
441
+ return null;
442
+ }
443
+ isBlocked(name) {
444
+ return this.blockReason(name) !== null;
445
+ }
446
+ };
447
+ /** Build a GateSet from the curator-style config field names. */
448
+ function createGateSet(config) {
449
+ return new EvolutionGateSet({
450
+ exclude: config.excludeSkillNames,
451
+ referenced: config.referencedSkillNames,
452
+ suppressed: config.suppressedNames
453
+ });
454
+ }
158
455
  //#endregion
159
456
  //#region lib/types/curator.js
160
457
  /**
161
458
  * Deterministic skill curator: active → stale → archived transitions.
162
- * Pure function; file moves are performed by SkillLibrary.
459
+ * Pure function with one deliberate side effect: records in the passed
460
+ * `usage` map are MUTATED (state/archived_at) to carry the transition — the
461
+ * caller owns the map and decides whether to clone first (dry-run) or persist
462
+ * after. File moves are performed by SkillLibrary.
163
463
  */
164
- const PROTECTED_BUILTIN_SKILLS = new Set(["plan"]);
165
464
  function buildCuratorRunReport(input) {
166
465
  return {
466
+ schemaVersion: 1,
167
467
  runId: input.runId,
168
468
  startedAt: input.startedAt,
169
469
  finishedAt: input.finishedAt,
@@ -172,25 +472,145 @@ function buildCuratorRunReport(input) {
172
472
  archiveCandidates: [...input.archiveCandidates],
173
473
  archived: [...input.archived],
174
474
  failed: [...input.failed],
175
- ...input.snapshotPath === void 0 ? {} : { snapshotPath: input.snapshotPath }
475
+ ...input.consolidated === void 0 ? {} : { consolidated: [...input.consolidated] },
476
+ ...input.snapshotPath === void 0 ? {} : { snapshotPath: input.snapshotPath },
477
+ ...input.llmReviewEnabled === void 0 ? {} : { llmReviewEnabled: input.llmReviewEnabled }
478
+ };
479
+ }
480
+ /**
481
+ * Render a curator run report as a compact human-readable markdown digest
482
+ * (G6): run metadata first, then the notable sections (archived / failed /
483
+ * stale candidates / LLM nominations).
484
+ */
485
+ function renderCuratorReportMarkdown(report) {
486
+ const lines = [
487
+ `# Curator run ${report.runId}`,
488
+ "",
489
+ `- **Started** ${report.startedAt}`,
490
+ `- **Finished** ${report.finishedAt}`,
491
+ `- **Stale candidates**: ${report.staleCandidates.length}`,
492
+ `- **LLM nominations**: ${report.llmNominations.length}`,
493
+ `- **Archived**: ${report.archived.length}`,
494
+ `- **Failed**: ${report.failed.length}`,
495
+ ...report.snapshotPath === void 0 ? [] : [`- **Snapshot**: ${report.snapshotPath}`],
496
+ ...report.llmReviewEnabled === void 0 ? [] : [`- **llmReview**: ${report.llmReviewEnabled}`]
497
+ ];
498
+ const section = (title, items) => items.length === 0 ? [] : [
499
+ "",
500
+ `## ${title}`,
501
+ "",
502
+ ...items.map((item) => `- ${item}`)
503
+ ];
504
+ return [
505
+ ...lines,
506
+ ...section("Archived", report.archived.map((item) => `${item.name} (${item.reason})`)),
507
+ ...section("Failed", report.failed.map((item) => `${item.name}: ${item.reason}`)),
508
+ ...section("Stale candidates", report.staleCandidates),
509
+ ...section("LLM nominations", report.llmNominations),
510
+ ""
511
+ ].join("\n");
512
+ }
513
+ const NOMINATION_NAME_RE = /^[a-z0-9][a-z0-9-]*$/;
514
+ /**
515
+ * Parse the curator LLM's YAML nomination block (consolidations + prunings).
516
+ * Line-oriented and lenient by design: the LLM output is advisory, every name
517
+ * is re-validated against the tree before any file move happens downstream.
518
+ */
519
+ function parseCuratorNominations(text) {
520
+ const prunings = [];
521
+ const consolidations = [];
522
+ let section = null;
523
+ let currentFrom = "";
524
+ for (const line of text.split("\n")) {
525
+ const consolidated = /^\s*-\s*from:\s*([a-z0-9][a-z0-9-]*)\s*$/.exec(line);
526
+ if (consolidated) {
527
+ section = "consolidations";
528
+ currentFrom = consolidated[1] ?? "";
529
+ continue;
530
+ }
531
+ const into = /^\s*into:\s*([a-z0-9][a-z0-9-]*)\s*$/.exec(line);
532
+ if (into) {
533
+ const intoName = into[1] ?? "";
534
+ if (section === "consolidations" && currentFrom !== "" && currentFrom !== intoName) consolidations.push({
535
+ from: currentFrom,
536
+ into: intoName
537
+ });
538
+ currentFrom = "";
539
+ continue;
540
+ }
541
+ const pruned = /^\s*-\s*name:\s*([a-z0-9][a-z0-9-]*)\s*$/.exec(line);
542
+ if (pruned) {
543
+ section = "prunings";
544
+ const name = pruned[1];
545
+ if (name) prunings.push(name);
546
+ }
547
+ }
548
+ const valid = (name) => NOMINATION_NAME_RE.test(name);
549
+ return {
550
+ prunings: prunings.filter(valid),
551
+ consolidations: consolidations.filter((item) => valid(item.from) && valid(item.into))
552
+ };
553
+ }
554
+ /**
555
+ * The lifecycle-candidate gate, shared by the transition engine and the scope
556
+ * view so the two can never disagree: records failing ANY of these gates are
557
+ * outside the managed scope.
558
+ */
559
+ function lifecycleCandidate(name, record, config, bundled, gates = createGateSet(config)) {
560
+ if (record.pinned) return false;
561
+ if (gates.isBlocked(name)) return false;
562
+ if (!(record.created_by === "agent" || config.manageUnmanaged === true) && !(config.pruneBuiltins === true && bundled)) return false;
563
+ if (record.state === "archived") return false;
564
+ return true;
565
+ }
566
+ /**
567
+ * Read-only scope classification, derived from the SAME gate the transition
568
+ * engine uses (`lifecycleCandidate`), so the view always predicts what a
569
+ * curator pass may touch. `protectedNames` carries the marker info the usage
570
+ * records lack (bundled / hub-installed / pinned from `SkillLibrary.list()`).
571
+ */
572
+ function computeScopeView(usage, config, protectedNames, gates) {
573
+ const managed = [];
574
+ const watched = [];
575
+ const qualityWarned = [];
576
+ const exempted = [];
577
+ const protectedSet = /* @__PURE__ */ new Set();
578
+ const gateSet = gates ?? createGateSet(config);
579
+ for (const [name, record] of usage) {
580
+ if (gateSet.exclude.has(name) || gateSet.referenced.has(name)) {
581
+ exempted.push(name);
582
+ continue;
583
+ }
584
+ const bundled = config.bundledNames?.has(name) === true;
585
+ const suppressed = gateSet.suppressed.has(name);
586
+ if (record.pinned || bundled || suppressed || protectedNames?.has(name) === true) protectedSet.add(name);
587
+ if (lifecycleCandidate(name, record, config, bundled, gateSet)) {
588
+ managed.push(name);
589
+ if (record.state === "stale" || record.quality_warn === true) watched.push(name);
590
+ if (record.quality_warn === true) qualityWarned.push(name);
591
+ }
592
+ }
593
+ return {
594
+ managed: managed.sort(),
595
+ watched: watched.sort(),
596
+ qualityWarned: qualityWarned.sort(),
597
+ exempted: exempted.sort(),
598
+ protected: [...protectedSet].sort()
176
599
  };
177
600
  }
178
601
  function daysSince(iso, created, now) {
179
602
  return (now - new Date(iso ?? created).getTime()) / 864e5;
180
603
  }
181
- function computeLifecycleTransitions(usage, config, now = /* @__PURE__ */ new Date()) {
604
+ function computeLifecycleTransitions(usage, config, now = /* @__PURE__ */ new Date(), gates) {
182
605
  const result = {
183
606
  transitions: [],
184
607
  archive: [],
185
608
  reactivate: [],
186
609
  markStale: []
187
610
  };
611
+ const gateSet = gates ?? createGateSet(config);
188
612
  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;
613
+ if (!lifecycleCandidate(name, record, config, config.bundledNames?.has(name) === true, gateSet)) continue;
194
614
  const age = daysSince(null, record.created_at, now.getTime());
195
615
  if (record.use_count === 0 && age < config.staleAfterDays) continue;
196
616
  const idle = daysSince(latestActivityAt(record), record.created_at, now.getTime());
@@ -242,6 +662,319 @@ function computeLifecycleTransitions(usage, config, now = /* @__PURE__ */ new Da
242
662
  return result;
243
663
  }
244
664
  //#endregion
665
+ //#region lib/types/prompts.js
666
+ /**
667
+ * Review and curation prompts adapted from Hermes Agent
668
+ * `agent/background_review.py`, `agent/curator.py`, and
669
+ * `agent/learn_prompt.py`, with tool names translated to the DSH-native
670
+ * catalog (`memory`, `skill_manage`, `skill`, `bash`, `str_replace_editor`).
671
+ *
672
+ * Alignment policy (2026-08-29): the OPERATIONAL steps and instructions the
673
+ * model follows mirror the Hermes originals structurally (signal list,
674
+ * preference order, support-file taxonomy, curator package integrity,
675
+ * consolidated/pruned reporting block). Tool and platform differences are
676
+ * DSH-adapted (native tool names, pinned-within-review semantics, this
677
+ * platform's index cap), and DSH-only additions are marked as such.
678
+ *
679
+ * Every prompt is pinned in a versioned bundle. Review workers verify the
680
+ * bundle digest before spending a model call, so a partially-patched
681
+ * deployment fails closed instead of silently running a truncated prompt.
682
+ */
683
+ /**
684
+ * Prompt bundle identity. Bump both id and version whenever a prompt's text
685
+ * changes semantically: the bundle digest is the fail-closed signal for
686
+ * review workers, so a stale id across deployments must be distinguishable.
687
+ */
688
+ const PROMPT_BUNDLE_ID = "dsh-evolution@5";
689
+ const PROMPT_BUNDLE_VERSION = 5;
690
+ const MEMORY_REVIEW_PROMPT = `[Auto-review — Memory]
691
+ Review the conversation above and consider saving to memory if appropriate.
692
+
693
+ Focus on:
694
+ 1. Has the user revealed things about themselves — persona, desires, preferences, or personal details worth remembering?
695
+ 2. Has the user expressed expectations about how you should behave, their work style, or ways they want you to operate?
696
+
697
+ If something stands out, save it using the memory tool.
698
+ If nothing is worth saving, just say "Nothing to save." and stop.`;
699
+ const SKILL_REVIEW_PROMPT = `[Auto-review — Skills]
700
+ 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.
701
+
702
+ 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.
703
+
704
+ Signals to look for (any one of these warrants action):
705
+ • 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.
706
+ • 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.
707
+ • Non-trivial technique, fix, workaround, debugging path, or tool-usage pattern emerged that a future session would benefit from. Capture it.
708
+ • A skill that got loaded or consulted this session turned out to be wrong, missing a step, or outdated. Patch it NOW.
709
+
710
+ Preference order — prefer the earliest action that fits, but do pick one when a signal above fired:
711
+ 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.
712
+ 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.
713
+ 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:
714
+ • 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.
715
+ • templates/<name>.<ext> — starter files meant to be copied and modified (boilerplate configs, scaffolding, a known-good example the agent can reproduce with modifications).
716
+ • 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).
717
+ 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.
718
+ 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).
719
+
720
+ 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.
721
+
722
+ If you notice two existing skills that overlap, note it in your reply — the background curator handles consolidation at scale.
723
+
724
+ Two-tier deposition discipline (DSH addition, same spirit as the umbrella rule): before writing, classify the knowledge:
725
+ • PATTERN (reusable — symptom → mechanism → fix → verification, still valuable next session) belongs in the SKILL.md body.
726
+ • 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.
727
+
728
+ Protected skills (DO NOT edit these):
729
+ • Bundled skills (shipped with the platform).
730
+ • Hub-installed skills (installed from a hub).
731
+ 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.
732
+ If the only skills that need updating are protected, say 'Nothing to save.' and stop.
733
+
734
+ Do NOT capture (these become persistent self-imposed constraints that bite you later when the environment changes):
735
+ • 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.
736
+ • 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.
737
+ • Session-specific transient errors that resolved before the conversation ended. If retrying worked, the lesson is the retry pattern, not the original failure.
738
+ • 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.
739
+
740
+ 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.
741
+
742
+ '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.`;
743
+ const COMBINED_REVIEW_PROMPT = `[Auto-review]
744
+ Review the conversation above and update two things:
745
+
746
+ **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.
747
+
748
+ **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.
749
+
750
+ 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.
751
+
752
+ Signals that warrant a skill update (any one is enough):
753
+ • 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.
754
+ • Non-trivial technique, fix, workaround, or debugging path emerged.
755
+ • A skill that was loaded or consulted turned out wrong, missing, or outdated — patch it now.
756
+
757
+ Preference order for skills — pick the earliest that fits:
758
+ 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.
759
+ 2. UPDATE AN EXISTING UMBRELLA. Patch it.
760
+ 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.
761
+ 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).
762
+
763
+ 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.
764
+
765
+ 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.
766
+
767
+ If you notice overlapping existing skills, mention it — the background curator handles consolidation.
768
+
769
+ Protected skills (DO NOT edit these):
770
+ • Bundled skills (shipped with the platform).
771
+ • Hub-installed skills (installed from a hub).
772
+ 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.
773
+ If the only skills that need updating are protected, say 'Nothing to save.' and stop.
774
+
775
+ Do NOT capture as skills (these become persistent self-imposed constraints that bite you later when the environment changes):
776
+ • 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.
777
+ • 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.
778
+ • Session-specific transient errors that resolved before the conversation ended. If retrying worked, the lesson is the retry pattern, not the original failure.
779
+ • 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.
780
+
781
+ 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.
782
+
783
+ 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.`;
784
+ const CURATOR_PROMPT = `You are the skill curator. Maintain a healthy, class-level skill library, not a flat pile of narrow one-session skills.
785
+
786
+ This is an UMBRELLA-BUILDING consolidation pass, not a passive audit and not a duplicate-finder.
787
+
788
+ 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.
789
+
790
+ Right target shape: class-level skills with rich SKILL.md + references/, templates/, scripts/ support files for session-specific detail.
791
+
792
+ Hard rules:
793
+ 1. NEVER hard-delete a skill. Archive (moving to .archive/) is the maximum destructive action; archives are recoverable, deletion is not.
794
+ 2. Do not touch bundled, hub-installed, pinned, or scheduled-task-referenced (referenced) skills. Referenced skills MAY be consolidated into an umbrella — but only because the curator rewrites scheduled-task skill references to follow consolidations; never simply prune them.
795
+ 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.
796
+ 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.
797
+ 5. Judge overlap on CONTENT, not on usage counters.
798
+ 6. Before archiving a merged skill, ensure its unique content was preserved in the umbrella.
799
+
800
+ How to work:
801
+ 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.
802
+ 2. For each cluster with 2+ members, ask "what is the UMBRELLA CLASS these skills serve?" and consolidate:
803
+ a. MERGE INTO AN EXISTING UMBRELLA (patch a labeled section for each sibling's unique insight, then archive the siblings).
804
+ b. CREATE A NEW UMBRELLA SKILL.md covering the shared workflow with short labeled subsections, then archive the absorbed siblings.
805
+ c. DEMOTE session-specific detail to references/, templates/, or scripts/ under the umbrella. Use the right directory per kind:
806
+ • 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.
807
+ • templates/<name>.<ext> — starter files meant to be copied and modified.
808
+ • scripts/<name>.<ext> — statically re-runnable actions (verification scripts, fixture generators, probes).
809
+ 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.
810
+ 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.
811
+ 5. Iterate. After one consolidation round, scan the remaining set and look for the NEXT umbrella opportunity. Don't stop after 3 merges.
812
+
813
+ Your toolset:
814
+ - skill_manage action=list / review — read the current landscape.
815
+ - skill_manage action=patch — add sections to the umbrella.
816
+ - skill_manage action=create — create a new umbrella SKILL.md.
817
+ - skill_manage action=write_file — add a references/, templates/, or scripts/ file under an existing skill (the skill must already exist).
818
+ - skill_manage action=delete — archive a skill. MUST pass absorbed_into=<umbrella> when you've merged its content into another skill, or absorbed_into="" when you're truly pruning with no forwarding target.
819
+ - skill_manage action=consolidate — merge source bodies into a target and archive the sources when patching by hand is error-prone.
820
+ - skill_manage action=restore — bring one archived skill back (recoverability is the archive's contract).
821
+ - For moving support files, keep it inside the skill tree: support files move via reading and writing through skill_manage write_file/remove_file.
822
+
823
+ '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.
824
+
825
+ 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.
826
+
827
+ Keep the umbrella body tight and scannable: exact commands, verbatim paths, ~100-200 lines; never invent flags or APIs.
828
+
829
+ When done, write a human summary AND a structured machine-readable block so downstream tooling can distinguish consolidation from pruning. Format EXACTLY:
830
+
831
+ ## Structured summary (required)
832
+ \`\`\`yaml
833
+ consolidations:
834
+ - from: <old-skill-name>
835
+ into: <umbrella-skill-name>
836
+ reason: <one short sentence — why merged, not just 'similar'>
837
+ prunings:
838
+ - name: <skill-name>
839
+ reason: <one short sentence — why archived with no merge target>
840
+ \`\`\`
841
+
842
+ Every skill you moved 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.`;
843
+ const CURATOR_DRY_RUN_BANNER = `═══════════════════════════════════════════════════════════════
844
+ DRY-RUN — REPORT ONLY. DO NOT MUTATE THE SKILL LIBRARY.
845
+ ═══════════════════════════════════════════════════════════════
846
+
847
+ This is a PREVIEW pass. Follow every instruction above EXCEPT:
848
+ • Do NOT call skill_manage with action=create, update, patch, delete, write_file, or remove_file.
849
+ • Do NOT move, copy, or rewrite any file under the skills tree.
850
+
851
+ 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.
852
+
853
+ If you accidentally take a mutating action, say so explicitly in the summary.`;
854
+ const COMPLETION_SKILL_REVIEW_PROMPT = `[Auto-review — Skills · task complete]
855
+ Your current task now appears complete. Before wrapping up, review the approach and update the skill library via skill_manage.
856
+
857
+ 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.
858
+
859
+ Do NOT modify output files or re-run the task. If you are still mid-task, ignore this.`;
860
+ /**
861
+ * System-prompt guidance section (Hermes `SKILLS_GUIDANCE`, DSH-adapted).
862
+ * Registered as a system-prompt section by tool-skill-manage (it mounts
863
+ * exactly when `skill_manage` is available — the DSH analogue of Hermes'
864
+ * `if "skill_manage" in agent.valid_tool_names` condition). Instructs the
865
+ * model to save/repair skills on its own initiative.
866
+ */
867
+ const SKILLS_GUIDANCE = `Skills guidance:
868
+ • 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.
869
+ • 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.`;
870
+ function reviewPrompt(kind) {
871
+ if (kind === "memory") return MEMORY_REVIEW_PROMPT;
872
+ if (kind === "skill") return SKILL_REVIEW_PROMPT;
873
+ return COMBINED_REVIEW_PROMPT;
874
+ }
875
+ function sha256(text) {
876
+ return createHash("sha256").update(text).digest("hex");
877
+ }
878
+ function createPromptBundle(prompts) {
879
+ const canonical = JSON.stringify({
880
+ id: PROMPT_BUNDLE_ID,
881
+ version: 5,
882
+ prompts: Object.fromEntries(Object.entries(prompts).sort())
883
+ });
884
+ return Object.freeze({
885
+ id: PROMPT_BUNDLE_ID,
886
+ version: 5,
887
+ prompts: Object.freeze({ ...prompts }),
888
+ sha256: sha256(canonical)
889
+ });
890
+ }
891
+ const PROMPT_BUNDLE = createPromptBundle({
892
+ memory: MEMORY_REVIEW_PROMPT,
893
+ skill: SKILL_REVIEW_PROMPT,
894
+ combined: COMBINED_REVIEW_PROMPT,
895
+ curator: CURATOR_PROMPT,
896
+ completion: COMPLETION_SKILL_REVIEW_PROMPT,
897
+ skillsGuidance: SKILLS_GUIDANCE
898
+ });
899
+ function verifyPromptBundle(bundle = PROMPT_BUNDLE) {
900
+ if (bundle.id !== "dsh-evolution@5" || bundle.version !== 5) return false;
901
+ const canonical = JSON.stringify({
902
+ id: PROMPT_BUNDLE_ID,
903
+ version: 5,
904
+ prompts: Object.fromEntries(Object.entries(bundle.prompts).sort())
905
+ });
906
+ return bundle.sha256 === sha256(canonical);
907
+ }
908
+ const DSH_AUTHORING_STANDARDS = `Follow the Hermes skill-authoring standards, translated to DSH tools.
909
+
910
+ Frontmatter:
911
+ - name: lowercase-hyphenated, <=64 chars, no spaces.
912
+ - 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.
913
+ - version: 0.1.0
914
+ - 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.
915
+ - 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.
916
+ - metadata.hermes.tags: a few Capitalized, Relevant, Tags.
917
+ - metadata.hermes.related_skills: [a, b] — name sibling skills this one builds on or is referenced by (optional; feeds the quality references factor).
918
+
919
+ Body section order (omit only when empty):
920
+ 1. "# <Human Title>" then a 2-3 sentence intro: what it does, what it does NOT do, key dependency stance.
921
+ 2. "## When to Use" — concrete trigger phrases.
922
+ 3. "## Prerequisites" — exact env vars, install steps, credentials.
923
+ 4. "## How to Run" — canonical invocation framed through DSH tools.
924
+ 5. "## Quick Reference" — flat command/endpoint list.
925
+ 6. "## Procedure" — numbered steps with copy-paste-exact commands.
926
+ 7. "## Pitfalls" — known limits and rate limits.
927
+ 8. "## Verification" — one check proving the skill worked.
928
+
929
+ DSH-tool framing:
930
+ - Reference DSH tools by name in backticks: \`bash\`, \`str_replace_editor\`, \`write\`, \`skill\`, \`skill_manage\`, \`memory\`.
931
+ - Do not name wrapped shell utilities when a DSH tool already covers them.
932
+ - Larger scripts belong under \`scripts/\` (written with \`skill_manage write_file\`) and are referenced from SKILL.md by relative path.
933
+
934
+ Quality bar:
935
+ - Prefer verbatim flags, paths, and APIs from the source. Never invent them.
936
+ - Keep it tight: ~100 lines simple, ~200 complex.
937
+ - No router/index/hub skills that only point at other skills.
938
+ - References go in \`references/\`, templates in \`templates/\`.`;
939
+ //#endregion
940
+ //#region lib/types/learn-prompt.js
941
+ /**
942
+ * Open-ended `/evolution learn` prompt builder.
943
+ *
944
+ * `learn` is open-ended: the user can name anything they can describe — a
945
+ * directory of code, an API doc URL, a workflow they just walked the agent
946
+ * through, or pasted notes. The prompt instructs the live agent to gather the
947
+ * named sources with its existing tools, then author a single SKILL.md via
948
+ * `skill_manage` following `DSH_AUTHORING_STANDARDS`. There is no separate
949
+ * distillation engine and no model-tool footprint.
950
+ */
951
+ /**
952
+ * Build the agent prompt for an open-ended `/evolution learn` request.
953
+ *
954
+ * @param userRequest free-text the user gave after `/evolution learn`; an
955
+ * empty string falls back to "the workflow we just went through".
956
+ * @returns a complete instruction the agent runs as a normal turn.
957
+ */
958
+ function buildLearnPrompt(userRequest) {
959
+ return [
960
+ "[/learn] The user wants you to learn a reusable skill from the request below, and save it.",
961
+ "",
962
+ "THE REQUEST:",
963
+ userRequest.trim() || "the workflow we just went through in this conversation — review the steps taken and distill them into a reusable skill",
964
+ "",
965
+ "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.",
966
+ "",
967
+ "Do this:",
968
+ "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.",
969
+ "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.",
970
+ "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.",
971
+ "",
972
+ DSH_AUTHORING_STANDARDS,
973
+ "",
974
+ "When done, tell the user the skill name, its category, and a one-line summary of what it captured."
975
+ ].join("\n");
976
+ }
977
+ //#endregion
245
978
  //#region lib/types/threats.js
246
979
  /**
247
980
  * Threat scanning for agent-authored memory and skill content.
@@ -417,10 +1150,12 @@ const SCOPE_ORDER = {
417
1150
  context: 2,
418
1151
  strict: 3
419
1152
  };
1153
+ const NO_SCAN_OPTIONS = {};
420
1154
  /**
421
1155
  * Scan text at `scope`. Patterns are cumulative: `strict` includes all scopes.
1156
+ * `options.excludeLabels` removes matching patterns without changing `scope`.
422
1157
  */
423
- function scanThreats(text, scope = "strict", maxScanChars = 65536) {
1158
+ function scanThreats(text, scope = "strict", maxScanChars = 65536, options = NO_SCAN_OPTIONS) {
424
1159
  const findings = [];
425
1160
  if (ZERO_WIDTH_CHARS.test(text)) findings.push({
426
1161
  label: "unicode_zero_width",
@@ -433,8 +1168,10 @@ function scanThreats(text, scope = "strict", maxScanChars = 65536) {
433
1168
  scope
434
1169
  });
435
1170
  const normalized = text.normalize("NFKC").slice(0, maxScanChars);
1171
+ const excluded = new Set(options.excludeLabels ?? []);
436
1172
  for (const pattern of PATTERNS) {
437
1173
  if (SCOPE_ORDER[pattern.scope] > SCOPE_ORDER[scope]) continue;
1174
+ if (excluded.has(pattern.label)) continue;
438
1175
  if (pattern.regex.test(normalized)) findings.push({
439
1176
  label: pattern.label,
440
1177
  category: pattern.category,
@@ -444,24 +1181,24 @@ function scanThreats(text, scope = "strict", maxScanChars = 65536) {
444
1181
  return findings;
445
1182
  }
446
1183
  /** 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);
1184
+ function evaluateThreat(text, scope = "strict", maxScanChars = 65536, options = NO_SCAN_OPTIONS) {
1185
+ const findings = scanThreats(text, scope, maxScanChars, options);
449
1186
  return {
450
1187
  blocked: findings.length > 0,
451
1188
  findings
452
1189
  };
453
1190
  }
454
1191
  /** User-facing block message for memory writes. */
455
- function scanMemoryThreats(text, maxScanChars = 65536) {
456
- const { blocked, findings } = evaluateThreat(text, "strict", maxScanChars);
1192
+ function scanMemoryThreats(text, maxScanChars = 65536, options = NO_SCAN_OPTIONS) {
1193
+ const { blocked, findings } = evaluateThreat(text, "strict", maxScanChars, options);
457
1194
  if (!blocked) return null;
458
1195
  const pattern = findings.find((f) => f.category !== "unicode_obfuscation");
459
1196
  if (pattern) return `Blocked by security scan (${pattern.label}). Rephrase without instruction-like language.`;
460
1197
  return "Blocked by security scan: invisible or potentially malicious Unicode detected.";
461
1198
  }
462
1199
  /** User-facing block message for skill content writes. */
463
- function scanContentThreats(text, maxScanChars = 65536) {
464
- const { blocked, findings } = evaluateThreat(text, "strict", maxScanChars);
1200
+ function scanContentThreats(text, maxScanChars = 65536, options = NO_SCAN_OPTIONS) {
1201
+ const { blocked, findings } = evaluateThreat(text, "strict", maxScanChars, options);
465
1202
  if (!blocked) return null;
466
1203
  return `Blocked by security scan (${findings[0]?.label ?? "unknown"}). This content appears to contain potentially malicious instructions.`;
467
1204
  }
@@ -471,7 +1208,39 @@ function scanContentThreats(text, maxScanChars = 65536) {
471
1208
  * File-backed durable memory with Hermes-compatible semantics.
472
1209
  * Stores are MEMORY.md and USER.md under $DSH_HOME/memories (~/.dsh/memories).
473
1210
  */
474
- const ENTRY_DELIMITER = "\n§\n";
1211
+ /**
1212
+ * Read-guard factor: a memory file larger than this multiple of its target's
1213
+ * char limit is treated as externally corrupted and skipped instead of being
1214
+ * read whole (aligned with claw `tools/memory.ts` size guard, which uses the
1215
+ * same 10× bound around a file that should never exceed the store limit).
1216
+ */
1217
+ const READ_GUARD_FACTOR = 10;
1218
+ /**
1219
+ * Consolidation-failure backoff window (package-private, rc.42 audit P2-1):
1220
+ * only failures inside the window count toward `maxConsolidationFailures`.
1221
+ * The store cannot observe turn boundaries, so the model-facing "this turn"
1222
+ * phrasing is approximated with ten minutes — generous enough to cover one
1223
+ * turn's retry loop, short enough that a failure yesterday never makes today's
1224
+ * first refusal say "stop retrying".
1225
+ */
1226
+ const FAILURE_WINDOW_MS = 10 * 6e4;
1227
+ /**
1228
+ * Recoverable-error preview bounds (B-line G5, Hermes `_previews` parity):
1229
+ * failed replace/remove/batch calls echo the current entries so the model can
1230
+ * self-recover without re-reading the store. Bounded to five entries of eighty
1231
+ * characters each; package-private because it is an error-message shape, not a
1232
+ * behavior switch.
1233
+ */
1234
+ const ERROR_PREVIEW_ENTRIES = 5;
1235
+ const ERROR_PREVIEW_WIDTH = 80;
1236
+ function previewEntries(entries) {
1237
+ if (entries.length === 0) return "";
1238
+ const shown = entries.slice(0, ERROR_PREVIEW_ENTRIES).map((entry) => {
1239
+ return `- ${entry.length > ERROR_PREVIEW_WIDTH ? `${entry.slice(0, ERROR_PREVIEW_WIDTH)}…` : entry}`;
1240
+ });
1241
+ const more = entries.length > ERROR_PREVIEW_ENTRIES ? `\n (+${entries.length - ERROR_PREVIEW_ENTRIES} more)` : "";
1242
+ return `\n\nCurrent entries (preview):\n${shown.join("\n")}${more}`;
1243
+ }
475
1244
  function memoryRoot(env = process.env) {
476
1245
  return join(env.DSH_HOME ?? join(homedir(), ".dsh"), "memories");
477
1246
  }
@@ -495,6 +1264,7 @@ var MemoryStore = class {
495
1264
  maxFailures;
496
1265
  io;
497
1266
  failureCount = 0;
1267
+ lastFailureAt = 0;
498
1268
  constructor(options = {}) {
499
1269
  this.io = options.io ?? nodeEvolutionIo();
500
1270
  this.memoryLimit = options.memoryCharLimit ?? 2200;
@@ -506,7 +1276,24 @@ var MemoryStore = class {
506
1276
  limitFor(target) {
507
1277
  return target === "memory" ? this.memoryLimit : this.userLimit;
508
1278
  }
1279
+ /**
1280
+ * Read-guard probe: `{ size, limit }` when the on-disk file exceeds
1281
+ * `limit * READ_GUARD_FACTOR` bytes, `null` when it is absent, unknown
1282
+ * (backend without a size probe), under the bound, or the target has no
1283
+ * limit configured.
1284
+ */
1285
+ async oversizedFile(target) {
1286
+ const size = await this.io.size?.(fileFor(this.root, target));
1287
+ if (size === null || size === void 0) return null;
1288
+ const limit = this.limitFor(target);
1289
+ if (limit <= 0) return null;
1290
+ return size > limit * READ_GUARD_FACTOR ? {
1291
+ size,
1292
+ limit
1293
+ } : null;
1294
+ }
509
1295
  async read(target) {
1296
+ if (await this.oversizedFile(target)) return [];
510
1297
  const raw = await this.io.readText(fileFor(this.root, target));
511
1298
  return raw === null ? [] : [...new Set(normalizeEntries(raw))];
512
1299
  }
@@ -517,24 +1304,86 @@ var MemoryStore = class {
517
1304
  this.failureCount = 0;
518
1305
  }
519
1306
  failure(target, message, entries) {
1307
+ if (Date.now() - this.lastFailureAt > FAILURE_WINDOW_MS) this.failureCount = 0;
1308
+ this.lastFailureAt = Date.now();
520
1309
  this.failureCount += 1;
521
1310
  const chars = entries.join(ENTRY_DELIMITER).length;
522
1311
  if (this.failureCount > this.maxFailures) return {
523
1312
  ok: false,
524
- message: `Memory consolidation failed ${this.failureCount} times this turn. Stop retrying memory calls and continue with the user's task.`,
1313
+ message: `Memory consolidation failed ${this.failureCount} times this turn. Stop retrying memory calls and continue with the user's task.${previewEntries(entries)}`,
525
1314
  entries,
526
1315
  chars,
527
1316
  limit: this.limitFor(target)
528
1317
  };
529
1318
  return {
530
1319
  ok: false,
531
- message,
1320
+ message: `${message}${previewEntries(entries)}`,
532
1321
  entries,
533
1322
  chars,
534
1323
  limit: this.limitFor(target)
535
1324
  };
536
1325
  }
1326
+ /**
1327
+ * StorageHint percentage must clamp at 100 like the render header: a drifted
1328
+ * entry can push chars past the limit, and "Storage at 125%" contradicts the
1329
+ * clamped usage indicator.
1330
+ */
1331
+ storageHint(target, chars) {
1332
+ const limit = this.limitFor(target);
1333
+ if (limit <= 0) return "";
1334
+ const percent = Math.min(100, Math.floor(chars * 100 / limit));
1335
+ return percent >= 80 ? ` ⚠️ Storage at ${percent}% (${chars}/${limit} chars).` : "";
1336
+ }
1337
+ /**
1338
+ * Best-effort raw-copy backup of the on-disk file to `<file>.bak.<stamp>`
1339
+ * before a refusal, so an externally modified (or oversized) file stays
1340
+ * recoverable. Copies bytes instead of reading them so a pathologically
1341
+ * large file is never loaded just to back it up. Failure to back up does
1342
+ * not change the refusal semantics.
1343
+ */
1344
+ async backupFile(target) {
1345
+ const path = fileFor(this.root, target);
1346
+ const unique = `${(/* @__PURE__ */ new Date()).toISOString().replace(/[-:T]/g, "").slice(0, 14)}-${Math.random().toString(36).slice(2, 8)}`;
1347
+ try {
1348
+ await this.io.copy(path, `${path}.bak.${unique}`);
1349
+ return `${path}.bak.${unique}`;
1350
+ } catch {
1351
+ return null;
1352
+ }
1353
+ }
1354
+ /**
1355
+ * Read-guard refusal for write paths. Returns the refusal result when the
1356
+ * target file is oversized, `null` otherwise. The file is skipped for
1357
+ * reading (never loaded), backed up by raw copy, and the model is told to
1358
+ * fix it manually — mirroring the drift refusal so corrupted state is never
1359
+ * silently overwritten.
1360
+ */
1361
+ async oversizedRefusal(target) {
1362
+ const oversized = await this.oversizedFile(target);
1363
+ if (!oversized) return null;
1364
+ const backup = await this.backupFile(target);
1365
+ const suffix = backup ? ` A backup was saved to ${basename(backup)}.` : "";
1366
+ return {
1367
+ ok: false,
1368
+ message: `Memory file is ${oversized.size} bytes (limit ${oversized.limit * READ_GUARD_FACTOR}) — skipping read.${suffix} Fix the file manually, then retry.`,
1369
+ entries: [],
1370
+ chars: 0,
1371
+ limit: this.limitFor(target)
1372
+ };
1373
+ }
537
1374
  async add(target, facts) {
1375
+ const refusal = await this.oversizedRefusal(target);
1376
+ if (refusal) return refusal;
1377
+ if (await this.detectDrift(target)) {
1378
+ const backup = await this.backupFile(target);
1379
+ return {
1380
+ ok: false,
1381
+ message: `External drift detected in memory file.${backup ? ` A backup was saved to ${basename(backup)}.` : ""} Resolve the drift before retrying.`,
1382
+ entries: [],
1383
+ chars: 0,
1384
+ limit: this.limitFor(target)
1385
+ };
1386
+ }
538
1387
  const content = facts.trim();
539
1388
  if (!content) return {
540
1389
  ok: false,
@@ -556,7 +1405,7 @@ var MemoryStore = class {
556
1405
  this.resetFailures();
557
1406
  return {
558
1407
  ok: true,
559
- message: "Entry already exists (no duplicate added).",
1408
+ message: `Entry already exists (no duplicate added).${this.storageHint(target, entries.join(ENTRY_DELIMITER).length)}`,
560
1409
  entries,
561
1410
  chars: entries.join(ENTRY_DELIMITER).length,
562
1411
  limit: this.limitFor(target)
@@ -564,101 +1413,38 @@ var MemoryStore = class {
564
1413
  }
565
1414
  const next = [...entries, this.addDatePrefix ? `## ${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}\n${content}` : content];
566
1415
  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);
1416
+ const addLimit = this.limitFor(target);
1417
+ if (addLimit > 0 && total > addLimit) return this.failure(target, `Adding this entry would exceed the ${addLimit} char limit. Consolidate or remove stale entries, then retry.`, entries);
568
1418
  await this.write(target, next);
569
1419
  this.resetFailures();
570
1420
  return {
571
1421
  ok: true,
572
- message: "Entry added.",
1422
+ message: `Entry added.${this.storageHint(target, total)}`,
573
1423
  entries: next,
574
1424
  chars: total,
575
1425
  limit: this.limitFor(target)
576
1426
  };
577
1427
  }
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 {
1428
+ async applyBatch(target, operations) {
1429
+ if (operations.length === 0) return {
595
1430
  ok: false,
596
- message: "facts is required for replace; use remove to delete.",
1431
+ message: "operations list is empty.",
597
1432
  entries: [],
598
1433
  chars: 0,
599
1434
  limit: this.limitFor(target)
600
1435
  };
601
- if (action === "replace") {
602
- const threat = scanMemoryThreats(content);
603
- if (threat) return {
1436
+ const refusal = await this.oversizedRefusal(target);
1437
+ if (refusal) return refusal;
1438
+ if (await this.detectDrift(target)) {
1439
+ const backup = await this.backupFile(target);
1440
+ return {
604
1441
  ok: false,
605
- message: threat,
1442
+ message: `External drift detected in memory file.${backup ? ` A backup was saved to ${basename(backup)}.` : ""} Resolve the drift before retrying.`,
606
1443
  entries: [],
607
1444
  chars: 0,
608
1445
  limit: this.limitFor(target)
609
1446
  };
610
1447
  }
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;
635
- 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);
638
- this.resetFailures();
639
- return {
640
- ok: true,
641
- message: `Entry ${action === "remove" ? "removed" : "replaced"}.`,
642
- entries: next,
643
- chars: total,
644
- limit: this.limitFor(target)
645
- };
646
- }
647
- async applyBatch(target, operations) {
648
- if (operations.length === 0) return {
649
- ok: false,
650
- message: "operations list is empty.",
651
- entries: [],
652
- chars: 0,
653
- limit: this.limitFor(target)
654
- };
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
1448
  const entries = await this.read(target);
663
1449
  const working = [...entries];
664
1450
  for (const [index, op] of operations.entries()) {
@@ -667,7 +1453,7 @@ var MemoryStore = class {
667
1453
  const body = (op.facts ?? "").trim();
668
1454
  if (!body) return {
669
1455
  ok: false,
670
- message: `Operation ${position} (add): facts is required. No operations were applied.`,
1456
+ message: `Operation ${position} (add): facts is required. No operations were applied.${previewEntries(entries)}`,
671
1457
  entries,
672
1458
  chars: entries.join(ENTRY_DELIMITER).length,
673
1459
  limit: this.limitFor(target)
@@ -686,7 +1472,7 @@ var MemoryStore = class {
686
1472
  const needle = (op.old_text ?? "").trim();
687
1473
  if (!needle) return {
688
1474
  ok: false,
689
- message: `Operation ${position} (${op.action}): old_text is required. No operations were applied.`,
1475
+ message: `Operation ${position} (${op.action}): old_text is required. No operations were applied.${previewEntries(entries)}`,
690
1476
  entries,
691
1477
  chars: entries.join(ENTRY_DELIMITER).length,
692
1478
  limit: this.limitFor(target)
@@ -698,7 +1484,7 @@ var MemoryStore = class {
698
1484
  if (matches.length === 0) return this.failure(target, `Operation ${position}: no entry matching "${needle}" found. No operations were applied.`, entries);
699
1485
  if (new Set(matches.map((m) => m.entry)).size > 1) return {
700
1486
  ok: false,
701
- message: `Operation ${position}: "${needle}" matched multiple distinct entries. No operations were applied.`,
1487
+ message: `Operation ${position}: "${needle}" matched multiple distinct entries. No operations were applied.${previewEntries(entries)}`,
702
1488
  entries,
703
1489
  chars: entries.join(ENTRY_DELIMITER).length,
704
1490
  limit: this.limitFor(target)
@@ -709,7 +1495,7 @@ var MemoryStore = class {
709
1495
  const body = (op.facts ?? "").trim();
710
1496
  if (!body) return {
711
1497
  ok: false,
712
- message: `Operation ${position} (replace): facts is required.`,
1498
+ message: `Operation ${position} (replace): facts is required.${previewEntries(entries)}`,
713
1499
  entries,
714
1500
  chars: entries.join(ENTRY_DELIMITER).length,
715
1501
  limit: this.limitFor(target)
@@ -726,12 +1512,13 @@ var MemoryStore = class {
726
1512
  }
727
1513
  }
728
1514
  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);
1515
+ const batchLimit = this.limitFor(target);
1516
+ if (batchLimit > 0 && total > batchLimit) return this.failure(target, `Batch result (${total} chars) exceeds the ${batchLimit} limit. Remove or shorten more entries in the same batch.`, entries);
730
1517
  await this.write(target, working);
731
1518
  this.resetFailures();
732
1519
  return {
733
1520
  ok: true,
734
- message: `Applied ${operations.length} operation(s).`,
1521
+ message: `Applied ${operations.length} operation(s).${this.storageHint(target, total)}`,
735
1522
  entries: working,
736
1523
  chars: total,
737
1524
  limit: this.limitFor(target)
@@ -741,172 +1528,239 @@ var MemoryStore = class {
741
1528
  const memory = await this.read("memory");
742
1529
  const user = await this.read("user");
743
1530
  const parts = [];
744
- for (const [target, entries] of [["Memory", memory], ["User Profile", user]]) {
1531
+ for (const [target, label, entries] of [[
1532
+ "memory",
1533
+ "Memory",
1534
+ memory
1535
+ ], [
1536
+ "user",
1537
+ "User Profile",
1538
+ user
1539
+ ]]) {
1540
+ const oversized = entries.length === 0 ? await this.oversizedFile(target) : null;
1541
+ if (oversized) {
1542
+ parts.push(`## ${label} — file skipped: ${oversized.size} bytes (limit ${oversized.limit * READ_GUARD_FACTOR}); not read`);
1543
+ continue;
1544
+ }
745
1545
  const safe = entries.filter((entry) => !scanMemoryThreats(entry));
746
1546
  if (safe.length > 0) {
747
1547
  const body = safe.join(ENTRY_DELIMITER);
1548
+ const limit = this.limitFor(target);
1549
+ const pct = limit > 0 ? Math.min(100, Math.floor(body.length * 100 / limit)) : 0;
748
1550
  const note = safe.length === entries.length ? "" : ` (${entries.length - safe.length} threat-matched entries filtered)`;
749
- parts.push(`## ${target} (${safe.length} entries)${note}\n${body}`);
1551
+ parts.push(`## ${label} (${safe.length} entries) [${pct}% — ${body.length}/${limit} chars]${note}\n${body}`);
750
1552
  }
751
1553
  }
752
1554
  return parts.join("\n\n");
753
1555
  }
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
- }
1556
+ /**
1557
+ * Detect on-disk drift: true when the file is not in the canonical
1558
+ * `render(normalizeEntries(raw))` form. This catches structural anomalies
1559
+ * the writer would quietly normalize away (empty/`§`-only entries, stray
1560
+ * blank lines, leading/trailing delimiters) that indicate the file was
1561
+ * edited outside MemoryStore. Purely single-canonical content reaches the
1562
+ * same serialization and returns false, so a normal write is never flagged.
1563
+ *
1564
+ * An absent, empty, or whitespace-only file is the "never written" state
1565
+ * (rc.42 audit P1-6): it parses to zero entries, so the canonical form
1566
+ * `'\n'` can never byte-match it and every write path was permanently
1567
+ * refused with "External drift detected" — including the repairs the model
1568
+ * would need to make. Such files are adopted instead of flagged.
1569
+ */
765
1570
  async detectDrift(target) {
1571
+ if (await this.oversizedFile(target)) return true;
766
1572
  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();
1573
+ if (raw === null || raw.trim() === "") return false;
1574
+ const entries = normalizeEntries(raw);
1575
+ const limit = this.limitFor(target);
1576
+ if (limit > 0 && entries.some((entry) => entry.length > limit)) return true;
1577
+ return render(entries) !== raw;
769
1578
  }
770
1579
  };
771
1580
  //#endregion
772
- //#region lib/types/prompts.js
1581
+ //#region lib/types/mutations.js
773
1582
  /**
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.
1583
+ * Curator/author audit trail: `.mutations.json` records every skill mutation
1584
+ * with before/after content hashes so any automated edit is reviewable and
1585
+ * replayable. Best-effort persistence, mirroring the usage sidecar posture.
1586
+ * @module @lmzhen/dsh-evolution-core
782
1587
  */
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;
1588
+ const DEFAULT_MUTATION_CAP = 500;
1589
+ /** Version of the `.mutations.json` file shape; writers always emit the current one. */
1590
+ const MUTATIONS_FILE_VERSION = 1;
1591
+ function mutationsFile(root) {
1592
+ return join(root, ".mutations.json");
1593
+ }
1594
+ function contentHash(content) {
1595
+ return createHash("sha256").update(content).digest("hex");
1596
+ }
1597
+ /**
1598
+ * Parse a raw mutations sidecar; malformed content reads as empty (auditing is
1599
+ * best-effort). Versioned shape ({ version, records }) with legacy
1600
+ * plain-array compat, plus a field-level guard for records without the
1601
+ * required identity/timestamp fields (rc.42 audit P2-3).
1602
+ */
1603
+ function parseMutationRecords(raw) {
1604
+ if (raw === null) return [];
1605
+ try {
1606
+ const parsed = JSON.parse(raw);
1607
+ 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");
1608
+ } catch {
1609
+ return [];
1610
+ }
849
1611
  }
850
- function sha256(text) {
851
- return createHash("sha256").update(text).digest("hex");
1612
+ async function loadMutations(root, io = nodeEvolutionIo()) {
1613
+ return parseMutationRecords(await io.readText(mutationsFile(root)));
852
1614
  }
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)
1615
+ /** Append one record, trim to `cap`, and write atomically (versioned shape). */
1616
+ async function recordMutation(root, io, record, cap = 500) {
1617
+ await transactIo(io, mutationsFile(root), (current) => {
1618
+ const existing = parseMutationRecords(current);
1619
+ existing.push(record);
1620
+ const trimmed = existing.length > cap ? existing.slice(existing.length - cap) : existing;
1621
+ return Promise.resolve(JSON.stringify({
1622
+ version: 1,
1623
+ records: trimmed
1624
+ }, null, 2));
864
1625
  });
865
1626
  }
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);
1627
+ //#endregion
1628
+ //#region lib/types/quality.js
1629
+ /**
1630
+ * Quality scoring and near-duplicate detection for the curated skill library.
1631
+ *
1632
+ * Pure functions over data inputs so the scoring policy is unit-testable and
1633
+ * the same math feeds the usage sidecar, the `skill_manage review` surface and
1634
+ * the learning graph. Weights follow the Hermes/hermes-claw six-factor model;
1635
+ * mutation maturity is a documented DSH approximation (single per-month patch
1636
+ * trend ratio replaces the claw timestamp-trend formula, since DSH usage
1637
+ * records only carry the last patched timestamp).
1638
+ * @module @lmzhen/dsh-evolution-core
1639
+ */
1640
+ const QUALITY_WEIGHTS = {
1641
+ usageFrequency: .25,
1642
+ stability: .2,
1643
+ recency: .2,
1644
+ references: .1,
1645
+ mutationMaturity: .2,
1646
+ richness: .05
1647
+ };
1648
+ /** Score below which a skill is flagged for review. */
1649
+ const LOW_QUALITY_THRESHOLD = .3;
1650
+ function clamp01(value) {
1651
+ return Math.max(0, Math.min(1, value));
1652
+ }
1653
+ function daysBetween(from, now) {
1654
+ return Math.max(0, (now.getTime() - new Date(from).getTime()) / 864e5);
1655
+ }
1656
+ function computeQualityScores(input) {
1657
+ const now = input.now ?? /* @__PURE__ */ new Date();
1658
+ const scores = /* @__PURE__ */ new Map();
1659
+ for (const [name, record] of input.usage) {
1660
+ const ageDays = Math.max(1, daysBetween(record.created_at, now));
1661
+ const idleDays = daysBetween(latestActivityAt(record) ?? record.created_at, now);
1662
+ const patchCount = record.patch_count;
1663
+ const useCount = record.use_count;
1664
+ const usageFrequency = clamp01(useCount / ageDays);
1665
+ const stability = useCount === 0 ? 1 : clamp01(1 - patchCount / useCount);
1666
+ const recency = idleDays < 30 ? 1 : clamp01(1 - (idleDays - 30) / 150);
1667
+ const references = clamp01((input.referenceCounts?.get(name) ?? 0) / 3);
1668
+ const mutationMaturity = patchCount === 0 ? .3 : patchCount === 1 ? .4 : clamp01((patchCount - 1) / Math.max(1, ageDays / 30));
1669
+ const richness = clamp01((input.supportDirs?.get(name) ?? 0) * .175);
1670
+ const factors = {
1671
+ usageFrequency,
1672
+ stability,
1673
+ recency,
1674
+ references,
1675
+ mutationMaturity,
1676
+ richness
1677
+ };
1678
+ 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;
1679
+ scores.set(name, {
1680
+ score,
1681
+ factors,
1682
+ warn: score < LOW_QUALITY_THRESHOLD
1683
+ });
1684
+ }
1685
+ return scores;
1686
+ }
1687
+ function normalize(content) {
1688
+ return content.toLowerCase().replace(/\s+/g, " ").trim();
1689
+ }
1690
+ function contentHash$1(content) {
1691
+ return createHash("sha256").update(normalize(content)).digest("hex");
1692
+ }
1693
+ function tokenize(content) {
1694
+ return new Set(normalize(content).split(/[^a-z0-9\u4e00-\u9fff]+/).filter(Boolean));
1695
+ }
1696
+ function jaccard(a, b) {
1697
+ if (a.size === 0 || b.size === 0) return 0;
1698
+ let intersection = 0;
1699
+ for (const token of a) if (b.has(token)) intersection += 1;
1700
+ return intersection / (a.size + b.size - intersection);
1701
+ }
1702
+ /**
1703
+ * Two-phase near-duplicate clustering: exact normalized-hash groups first,
1704
+ * then token-Jaccard edges at {@link DEDUP_SIMILARITY_THRESHOLD} with a token
1705
+ * ratio guard, union-find across the whole set.
1706
+ */
1707
+ function computeDedupGroups(input) {
1708
+ const threshold = input.threshold ?? .95;
1709
+ const names = [...input.contents.keys()];
1710
+ const hashes = /* @__PURE__ */ new Map();
1711
+ for (const name of names) {
1712
+ const hash = contentHash$1(input.contents.get(name) ?? "");
1713
+ const bucket = hashes.get(hash);
1714
+ if (bucket) bucket.push(name);
1715
+ else hashes.set(hash, [name]);
1716
+ }
1717
+ const parent = /* @__PURE__ */ new Map();
1718
+ const find = (x) => {
1719
+ const root = parent.get(x) ?? x;
1720
+ if (root !== x) parent.set(x, find(root));
1721
+ return parent.get(x) ?? x;
1722
+ };
1723
+ const union = (a, b) => {
1724
+ const [ra, rb] = [find(a), find(b)];
1725
+ if (ra !== rb) parent.set(rb, ra);
1726
+ };
1727
+ for (const [hash, bucketNames] of hashes) {
1728
+ const first = bucketNames[0];
1729
+ if (first === void 0 || bucketNames.length === 1) continue;
1730
+ for (let index = 1; index < bucketNames.length; index += 1) {
1731
+ const peer = bucketNames[index];
1732
+ if (peer) union(first, peer);
1733
+ }
1734
+ }
1735
+ const tokens = /* @__PURE__ */ new Map();
1736
+ const tokenSet = (name) => {
1737
+ let set = tokens.get(name);
1738
+ if (!set) {
1739
+ set = tokenize(input.contents.get(name) ?? "");
1740
+ tokens.set(name, set);
1741
+ }
1742
+ return set;
1743
+ };
1744
+ for (let index = 0; index < names.length; index += 1) {
1745
+ const a = names[index];
1746
+ if (a === void 0) continue;
1747
+ for (let other = index + 1; other < names.length; other += 1) {
1748
+ const b = names[other];
1749
+ if (b === void 0) continue;
1750
+ const [ta, tb] = [tokenSet(a), tokenSet(b)];
1751
+ if (Math.max(ta.size, tb.size) / Math.max(1, Math.min(ta.size, tb.size)) > 5) continue;
1752
+ if (jaccard(ta, tb) >= threshold) union(a, b);
1753
+ }
1754
+ }
1755
+ const groups = /* @__PURE__ */ new Map();
1756
+ for (const name of names) {
1757
+ const root = find(name);
1758
+ const group = groups.get(root);
1759
+ if (group) group.push(name);
1760
+ else groups.set(root, [name]);
1761
+ }
1762
+ return [...groups.values()].filter((group) => group.length > 1);
879
1763
  }
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
1764
  //#endregion
911
1765
  //#region lib/types/signals.js
912
1766
  /**
@@ -994,31 +1848,53 @@ function foldTurn(session, fromSeq) {
994
1848
  * it created unless a `.hermes-managed` marker opts a skill in. Archival is a
995
1849
  * move to `.archive/` — never a hard delete.
996
1850
  */
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
1851
  const DEFAULT_SKILL_LIMITS = {
1003
1852
  maxNameLength: 64,
1004
1853
  maxDescriptionLength: MAX_DESCRIPTION_LENGTH,
1005
1854
  maxSkillContentChars: MAX_SKILL_CONTENT_CHARS,
1006
1855
  maxSkillFileBytes: MAX_SKILL_FILE_BYTES
1007
1856
  };
1008
- const SUPPORT_DIRS = [
1009
- "references",
1010
- "templates",
1011
- "scripts",
1012
- "assets"
1013
- ];
1857
+ /** Extra file name carried inside a snapshot's `extras/` directory. */
1858
+ const SNAPSHOT_EXTRA_NAME_RE = /^[a-z0-9][a-z0-9._-]*$/;
1014
1859
  function skillsRoot(env = process.env) {
1015
1860
  return join(env.DSH_HOME ?? join(homedir(), ".dsh"), "skills");
1016
1861
  }
1862
+ /**
1863
+ * Map a requesting session onto the two origin surfaces (rc.44 plan M2-2.3):
1864
+ * the APPROVAL surface treats every delegated subagent as the autonomous
1865
+ * review channel, while the LIBRARY surface keeps the Hermes distinction -
1866
+ * the review fork is 'background_review' (the pinned guard blocks its
1867
+ * writes) and any other subagent is 'subagent' (agent-authored, not
1868
+ * review-channel). `isReview` marks the caller as the background review
1869
+ * pipeline itself. Single source: the two tools and the review executor all
1870
+ * read this table instead of re-deriving it.
1871
+ */
1872
+ function resolveOrigins(headerOrigin, isReview = false) {
1873
+ if (isReview) return {
1874
+ approval: "background_review",
1875
+ library: "background_review"
1876
+ };
1877
+ if (headerOrigin === "subagent") return {
1878
+ approval: "background_review",
1879
+ library: "subagent"
1880
+ };
1881
+ return {
1882
+ approval: "foreground",
1883
+ library: "foreground"
1884
+ };
1885
+ }
1017
1886
  function skillDir(root, name) {
1018
1887
  return join(root, name);
1019
1888
  }
1889
+ /** Dot-prefixed on-disk marker name. SINGLE source: `list()` matches directory
1890
+ * entries against this name, and path builders must never hardcode a marker
1891
+ * literal (N-1: the rc.49 exists()-probe convergence dropped the dot,
1892
+ * poisoning every protectedBy/managed report). */
1893
+ function markerEntryName(marker) {
1894
+ return `.${marker}`;
1895
+ }
1020
1896
  function markerPath(dir, marker) {
1021
- return join(dir, `.${marker}`);
1897
+ return join(dir, markerEntryName(marker));
1022
1898
  }
1023
1899
  function parseFrontmatter(content) {
1024
1900
  if (!content.trimStart().startsWith("---")) return null;
@@ -1040,6 +1916,26 @@ function parseFrontmatter(content) {
1040
1916
  body
1041
1917
  };
1042
1918
  }
1919
+ /**
1920
+ * Skill names referenced by a SKILL.md's `related_skills` frontmatter
1921
+ * (B-line G3, rc.44): the single parsing source for the quality references
1922
+ * factor and the learning-graph edges. The DSH frontmatter parser keeps the
1923
+ * YAML value as a string (`"[a, b]"`), so names are scanned out of it; each
1924
+ * must satisfy the skill-name shape and the referencing skill itself is
1925
+ * excluded. Pure and deduplicated.
1926
+ */
1927
+ function relatedSkillNames(content, exclude) {
1928
+ const parsed = parseFrontmatter(content);
1929
+ if (!parsed) return [];
1930
+ const raw = parsed.frontmatter["related_skills"];
1931
+ if (typeof raw !== "string") return [];
1932
+ const names = /* @__PURE__ */ new Set();
1933
+ for (const match of Array.from(raw.matchAll(/[a-z0-9][a-z0-9-]*/g))) {
1934
+ const target = match[0];
1935
+ if (target && SKILL_NAME_RE.test(target) && target !== exclude) names.add(target);
1936
+ }
1937
+ return [...names];
1938
+ }
1043
1939
  function validateFrontmatter(content, expectedName, limits = DEFAULT_SKILL_LIMITS) {
1044
1940
  const parsed = parseFrontmatter(content);
1045
1941
  if (!parsed) return "SKILL.md must start and end with YAML frontmatter and include a body.";
@@ -1052,6 +1948,31 @@ function validateFrontmatter(content, expectedName, limits = DEFAULT_SKILL_LIMIT
1052
1948
  if (content.length > limits.maxSkillContentChars) return `SKILL.md content exceeds ${limits.maxSkillContentChars} characters.`;
1053
1949
  return null;
1054
1950
  }
1951
+ /** Hermes authoring quality bar for descriptions (the 60-char Rule). The
1952
+ * platform's own index limit stays in `validateFrontmatter`; this bar is the
1953
+ * target the authoring standard names, enforced as ADVISORY feedback. */
1954
+ const AUTHORING_DESCRIPTION_BAR = 60;
1955
+ /**
1956
+ * Advisory authoring feedback (P0): evaluate frontmatter against the
1957
+ * authoring bar WITHOUT changing platform validation semantics. The bar is
1958
+ * the quality target, `validateFrontmatter`'s limits are the compatibility
1959
+ * floor, and this bridge layer tells the model when its text would be
1960
+ * truncated or route-poor instead of silently shipping it.
1961
+ */
1962
+ function authoringFeedback(frontmatter) {
1963
+ const description = frontmatter.description ?? "";
1964
+ const over60 = description.length > 60;
1965
+ const hasColon = description.includes(":");
1966
+ const lines = [];
1967
+ lines.push(over60 ? `Description is ${description.length}/60 characters — exceeds the 60-char authoring bar (Hermes skill-authoring standard).` : `Description ${description.length}/60 characters — within the authoring bar.`);
1968
+ if (hasColon) lines.push("Description contains a colon — wrap the whole value in double quotes.");
1969
+ return {
1970
+ descriptionChars: description.length,
1971
+ over60,
1972
+ hasColon,
1973
+ lines
1974
+ };
1975
+ }
1055
1976
  async function listNames(root, io) {
1056
1977
  const entries = await io.list(root);
1057
1978
  const names = [];
@@ -1069,65 +1990,274 @@ function validateSupportPath(filePath) {
1069
1990
  if (parts.length < 2) return "Provide a file name, not just a directory.";
1070
1991
  return null;
1071
1992
  }
1993
+ /**
1994
+ * Index of `pattern` inside `content`, treating whitespace runs (spaces/tabs)
1995
+ * as flexible and literal escape sequences (`\n`, `\t`, `\r`) as their real
1996
+ * characters: a PATTERN whitespace run matches any content run of any length
1997
+ * (even empty), while extra whitespace that only exists in the content is not
1998
+ * skipped — the flexibility is one-sided on the pattern, and a backslash-
1999
+ * escaped char in the pattern matches the real char in the content
2000
+ * (model-copy drift). Returns the [start, end) range in the ORIGINAL content
2001
+ * so a patch can replace exactly the matched span and keep every other byte
2002
+ * intact. Returns null when no fuzzy match exists.
2003
+ */
2004
+ function fuzzyIndexOf(content, pattern, from = 0) {
2005
+ const isSpace = (char) => char !== void 0 && /[ \t]/.test(char);
2006
+ const escaped = (char) => {
2007
+ if (char === "n") return "\n";
2008
+ if (char === "t") return " ";
2009
+ if (char === "r") return "\r";
2010
+ return null;
2011
+ };
2012
+ for (let start = from; start < content.length; start += 1) {
2013
+ let contentIndex = start;
2014
+ let patternIndex = 0;
2015
+ while (patternIndex < pattern.length && contentIndex < content.length) {
2016
+ const patternChar = pattern[patternIndex];
2017
+ const contentChar = content[contentIndex];
2018
+ if (isSpace(patternChar)) {
2019
+ while (patternIndex < pattern.length && isSpace(pattern[patternIndex])) patternIndex += 1;
2020
+ while (contentIndex < content.length && isSpace(content[contentIndex])) contentIndex += 1;
2021
+ continue;
2022
+ }
2023
+ const escapedChar = patternChar === "\\" ? escaped(pattern[patternIndex + 1]) : null;
2024
+ if (escapedChar !== null && contentChar === escapedChar) {
2025
+ patternIndex += 2;
2026
+ contentIndex += 1;
2027
+ continue;
2028
+ }
2029
+ if (patternChar === contentChar) {
2030
+ contentIndex += 1;
2031
+ patternIndex += 1;
2032
+ continue;
2033
+ }
2034
+ break;
2035
+ }
2036
+ if (patternIndex === pattern.length) return [start, contentIndex];
2037
+ }
2038
+ return null;
2039
+ }
2040
+ /** Trim leading whitespace of the first line and trailing whitespace of the last line. */
2041
+ function trimPatternBoundaries(pattern) {
2042
+ const from = pattern.search(/\S/);
2043
+ const trimmed = from < 0 ? pattern : pattern.slice(from);
2044
+ const trailing = trimmed.search(/\s+$/);
2045
+ return trailing < 0 ? trimmed : trimmed.slice(0, trailing);
2046
+ }
2047
+ /** Replace only the fuzzy-matched span, preserving all surrounding bytes. */
2048
+ function fuzzyReplace(content, oldString, newString, replaceAll) {
2049
+ let current = content;
2050
+ let scanFrom = 0;
2051
+ for (;;) {
2052
+ const match = fuzzyIndexOf(current, oldString, scanFrom);
2053
+ if (match === null) return current;
2054
+ const [start, end] = match;
2055
+ const next = current.slice(0, start) + newString + current.slice(end);
2056
+ if (!replaceAll) return next;
2057
+ current = next;
2058
+ scanFrom = start + newString.length;
2059
+ }
2060
+ }
1072
2061
  function fuzzyPatch(content, oldString, newString, replaceAll = false) {
2062
+ if (oldString === "") return null;
1073
2063
  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);
2064
+ const boundary = trimPatternBoundaries(oldString);
2065
+ if (boundary === "") return null;
2066
+ if (boundary !== oldString) {
2067
+ if (fuzzyIndexOf(content, boundary) !== null) {
2068
+ const patched = fuzzyReplace(content, boundary, newString, replaceAll);
2069
+ return patched === content ? null : patched;
2070
+ }
2071
+ }
2072
+ if (fuzzyIndexOf(content, oldString) !== null) {
2073
+ const patched = fuzzyReplace(content, oldString, newString, replaceAll);
2074
+ return patched === content ? null : patched;
2075
+ }
1078
2076
  return null;
1079
2077
  }
1080
2078
  var SkillLibrary = class {
1081
2079
  root;
1082
2080
  limits;
1083
2081
  io;
1084
- constructor(root = skillsRoot(), io = nodeEvolutionIo(), limits = DEFAULT_SKILL_LIMITS) {
2082
+ onMutation;
2083
+ constructor(root = skillsRoot(), io = nodeEvolutionIo(), limits = DEFAULT_SKILL_LIMITS, onMutation) {
1085
2084
  this.root = root;
1086
2085
  this.io = io;
1087
2086
  this.limits = limits;
2087
+ this.onMutation = onMutation;
2088
+ }
2089
+ /** Notify the mutation observer after a successful write; observers must never fail the mutation. */
2090
+ notifyMutation(event) {
2091
+ try {
2092
+ this.onMutation?.(event);
2093
+ } catch {}
1088
2094
  }
1089
2095
  async list() {
1090
2096
  const summaries = [];
1091
2097
  for (const name of await listNames(this.root, this.io)) {
1092
- const dir = skillDir(this.root, name);
2098
+ const dir = this.dirOf(name);
1093
2099
  const md = await this.io.readText(join(dir, "SKILL.md"));
1094
2100
  if (!md) continue;
1095
2101
  const parsed = parseFrontmatter(md);
1096
- const protectedBy = await this.deleteProtection(name);
1097
- const managed = await this.io.exists(markerPath(dir, "hermes-managed"));
2102
+ let entries = [];
2103
+ try {
2104
+ entries = await this.io.list(dir);
2105
+ } catch {}
2106
+ const has = (marker) => entries.includes(markerEntryName(marker));
2107
+ const protectedBy = has("bundled") ? "bundled" : has("hub-installed") ? "hub-installed" : has("pinned") ? "pinned" : null;
1098
2108
  summaries.push({
1099
2109
  name,
1100
2110
  description: parsed?.frontmatter.description ?? "",
1101
2111
  path: dir,
1102
2112
  protectedBy,
1103
- managed,
2113
+ managed: has("hermes-managed"),
1104
2114
  archived: false
1105
2115
  });
1106
2116
  }
1107
2117
  return summaries;
1108
2118
  }
1109
- async read(name) {
1110
- return this.io.readText(join(skillDir(this.root, name), "SKILL.md"));
2119
+ async read(rawName) {
2120
+ const name = rawName.trim();
2121
+ if (this.badName(name) !== null) return null;
2122
+ return this.io.readText(join(this.dirOf(name), "SKILL.md"));
2123
+ }
2124
+ /**
2125
+
2126
+ * Single path-building choke point (rc.42 audit P2-5): every directory path
2127
+
2128
+ * is built from the TRIMMED name, so a name that passes `badName` (which
2129
+
2130
+ * trims before validating) can never mint a second, whitespace-padded
2131
+
2132
+ * directory next to the real one. Callers keep passing raw user input.
2133
+
2134
+ */
2135
+ dirOf(name) {
2136
+ return skillDir(this.root, name.trim());
2137
+ }
2138
+ /** Name-format guard shared by every path-building mutator/reader. */
2139
+ badName(name) {
2140
+ const normalized = name.trim();
2141
+ 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}).`;
2142
+ return null;
1111
2143
  }
1112
- async writeProtection(name) {
1113
- const dir = skillDir(this.root, name);
2144
+ async writeProtection(rawName, origin = "foreground") {
2145
+ const name = rawName.trim();
2146
+ const dir = this.dirOf(name);
1114
2147
  for (const marker of ["bundled", "hub-installed"]) if (await this.io.exists(markerPath(dir, marker))) return marker;
2148
+ if (origin === "background_review" && await this.io.exists(markerPath(dir, "pinned"))) return "pinned";
1115
2149
  return null;
1116
2150
  }
1117
- async deleteProtection(name) {
1118
- const dir = skillDir(this.root, name);
1119
- for (const marker of [
2151
+ async deleteProtection(rawName, options = {}) {
2152
+ const name = rawName.trim();
2153
+ const dir = this.dirOf(name);
2154
+ const markers = options.allowBundled ? ["hub-installed", "pinned"] : [
1120
2155
  "bundled",
1121
2156
  "hub-installed",
1122
2157
  "pinned"
1123
- ]) if (await this.io.exists(markerPath(dir, marker))) return marker;
2158
+ ];
2159
+ for (const marker of markers) if (await this.io.exists(markerPath(dir, marker))) return marker;
1124
2160
  return null;
1125
2161
  }
1126
- async isManaged(name) {
1127
- const dir = skillDir(this.root, name);
2162
+ async isManaged(rawName) {
2163
+ const name = rawName.trim();
2164
+ const dir = this.dirOf(name);
1128
2165
  return await this.io.exists(markerPath(dir, "hermes-managed"));
1129
2166
  }
1130
- async create(name, content, origin) {
2167
+ /** Whether the skill carries the bundled marker (curator prune-builtins eligibility). */
2168
+ async isBundled(rawName) {
2169
+ const name = rawName.trim();
2170
+ if (this.badName(name) !== null) return false;
2171
+ const dir = this.dirOf(name);
2172
+ return await this.io.exists(markerPath(dir, "bundled"));
2173
+ }
2174
+ /** Whether the skill carries the pinned marker (the marker is the factual source; usage.pinned mirrors it). */
2175
+ async isPinned(rawName) {
2176
+ const name = rawName.trim();
2177
+ if (this.badName(name) !== null) return false;
2178
+ const dir = this.dirOf(name);
2179
+ return await this.io.exists(markerPath(dir, "pinned"));
2180
+ }
2181
+ /** Count non-empty support subdirectories (richness input for quality scoring). */
2182
+ async countSupportDirs(rawName) {
2183
+ const name = rawName.trim();
2184
+ if (this.badName(name) !== null) return 0;
2185
+ const dir = this.dirOf(name);
2186
+ let entries;
2187
+ try {
2188
+ entries = await this.io.list(dir);
2189
+ } catch {
2190
+ return 0;
2191
+ }
2192
+ let count = 0;
2193
+ for (const subdir of SUPPORT_DIRS) {
2194
+ if (!entries.includes(subdir)) continue;
2195
+ try {
2196
+ if ((await this.io.list(join(dir, subdir))).some((file) => file !== ".gitkeep")) count += 1;
2197
+ } catch {}
2198
+ }
2199
+ return count;
2200
+ }
2201
+ /** Best-effort audit trail entry; never blocks the mutation. */
2202
+ async audit(skillName, action, before, after, summary) {
2203
+ try {
2204
+ await recordMutation(this.root, this.io, {
2205
+ skillName,
2206
+ action,
2207
+ ...before === null ? {} : { beforeHash: contentHash(before) },
2208
+ ...after === null ? {} : { afterHash: contentHash(after) },
2209
+ summary,
2210
+ at: (/* @__PURE__ */ new Date()).toISOString()
2211
+ });
2212
+ } catch {}
2213
+ }
2214
+ /** Recent mutation audit records (read-only inspection surface). */
2215
+ async listMutations() {
2216
+ return await loadMutations(this.root, this.io);
2217
+ }
2218
+ /**
2219
+ * Pin or unpin a skill (`.pinned` marker). Pinned skills are protected from
2220
+ * deletion, from background-review writes, and from the lifecycle — a
2221
+ * protective mutation, so the autonomous pipeline may never call it. The
2222
+ * marker write is the only state change; content is untouched.
2223
+ */
2224
+ async setPinned(name, pinned, origin = "foreground") {
2225
+ const normalized = name.trim();
2226
+ if (!SKILL_NAME_RE.test(normalized) || normalized.length > this.limits.maxNameLength) return {
2227
+ ok: false,
2228
+ message: `Invalid skill name "${normalized}". Use lowercase letters, digits, and hyphens (<= ${this.limits.maxNameLength}).`
2229
+ };
2230
+ if (origin === "background_review") return {
2231
+ ok: false,
2232
+ message: "Only the foreground (user or the main agent) may pin or unpin skills."
2233
+ };
2234
+ const dir = this.dirOf(normalized);
2235
+ const marker = markerPath(dir, "pinned");
2236
+ const existing = await this.io.exists(marker);
2237
+ if (pinned && existing) return {
2238
+ ok: true,
2239
+ message: `Skill "${normalized}" is already pinned.`,
2240
+ path: dir
2241
+ };
2242
+ if (!pinned && !existing) return {
2243
+ ok: true,
2244
+ message: `Skill "${normalized}" is not pinned; nothing to do.`,
2245
+ path: dir
2246
+ };
2247
+ if (!await this.io.exists(join(dir, "SKILL.md"))) return {
2248
+ ok: false,
2249
+ message: `Skill "${normalized}" not found.`
2250
+ };
2251
+ if (pinned) await this.io.writeText(marker, "");
2252
+ else await this.io.remove(marker);
2253
+ await this.audit(normalized, pinned ? "pin" : "unpin", null, null, pinned ? "pinned" : "unpinned");
2254
+ return {
2255
+ ok: true,
2256
+ message: pinned ? `Skill "${normalized}" pinned: protected from deletion, background review, and the lifecycle.` : `Skill "${normalized}" unpinned.`,
2257
+ path: dir
2258
+ };
2259
+ }
2260
+ async create(name, content, origin = "foreground") {
1131
2261
  const normalized = name.trim();
1132
2262
  if (!SKILL_NAME_RE.test(normalized) || normalized.length > this.limits.maxNameLength) return {
1133
2263
  ok: false,
@@ -1143,26 +2273,39 @@ var SkillLibrary = class {
1143
2273
  ok: false,
1144
2274
  message: threat
1145
2275
  };
1146
- const dir = skillDir(this.root, normalized);
2276
+ const dir = this.dirOf(normalized);
1147
2277
  if (await this.io.exists(join(dir, "SKILL.md"))) return {
1148
2278
  ok: false,
1149
2279
  message: `Skill "${normalized}" already exists.`
1150
2280
  };
1151
2281
  await this.io.writeText(join(dir, "SKILL.md"), content.trimEnd() + "\n");
1152
- if (origin === "background_review") await this.io.writeText(markerPath(dir, "hermes-managed"), "");
2282
+ if (origin !== "foreground") await this.io.writeText(markerPath(dir, "hermes-managed"), "");
2283
+ await this.audit(normalized, "create", null, content, "created");
2284
+ this.notifyMutation({
2285
+ action: "create",
2286
+ name: normalized,
2287
+ filePath: dir
2288
+ });
1153
2289
  return {
1154
2290
  ok: true,
1155
2291
  message: `Skill "${normalized}" created.`,
1156
2292
  path: dir
1157
2293
  };
1158
2294
  }
1159
- async update(name, content) {
1160
- const dir = skillDir(this.root, name);
1161
- if (!await this.io.readText(join(dir, "SKILL.md"))) return {
2295
+ async update(rawName, content, origin = "foreground") {
2296
+ const name = rawName.trim();
2297
+ const badName = this.badName(name);
2298
+ if (badName) return {
2299
+ ok: false,
2300
+ message: badName
2301
+ };
2302
+ const dir = this.dirOf(name);
2303
+ const md = await this.io.readText(join(dir, "SKILL.md"));
2304
+ if (!md) return {
1162
2305
  ok: false,
1163
2306
  message: `Skill "${name}" not found.`
1164
2307
  };
1165
- const protection = await this.writeProtection(name);
2308
+ const protection = await this.writeProtection(name, origin);
1166
2309
  if (protection) return {
1167
2310
  ok: false,
1168
2311
  message: `Skill "${name}" is protected (${protection}).`
@@ -1178,20 +2321,32 @@ var SkillLibrary = class {
1178
2321
  message: threat
1179
2322
  };
1180
2323
  await this.io.writeText(join(dir, "SKILL.md"), content.trimEnd() + "\n");
2324
+ await this.audit(name, "update", md, content, "updated");
2325
+ this.notifyMutation({
2326
+ action: "update",
2327
+ name,
2328
+ filePath: dir
2329
+ });
1181
2330
  return {
1182
2331
  ok: true,
1183
2332
  message: `Skill "${name}" updated.`,
1184
2333
  path: dir
1185
2334
  };
1186
2335
  }
1187
- async patch(name, oldString, newString, filePath = "", replaceAll = false) {
1188
- const dir = skillDir(this.root, name);
2336
+ async patch(rawName, oldString, newString, filePath = "", replaceAll = false, origin = "foreground") {
2337
+ const name = rawName.trim();
2338
+ const badName = this.badName(name);
2339
+ if (badName) return {
2340
+ ok: false,
2341
+ message: badName
2342
+ };
2343
+ const dir = this.dirOf(name);
1189
2344
  const skillMd = join(dir, "SKILL.md");
1190
2345
  if (!await this.io.exists(skillMd)) return {
1191
2346
  ok: false,
1192
2347
  message: `Skill "${name}" not found.`
1193
2348
  };
1194
- const protection = await this.writeProtection(name);
2349
+ const protection = await this.writeProtection(name, origin);
1195
2350
  if (protection) return {
1196
2351
  ok: false,
1197
2352
  message: `Skill "${name}" is protected (${protection}).`
@@ -1213,7 +2368,7 @@ var SkillLibrary = class {
1213
2368
  message: `File not found: ${patchLabel}`
1214
2369
  };
1215
2370
  const patched = fuzzyPatch(md, oldString, newString, replaceAll);
1216
- if (!patched) return {
2371
+ if (patched === null) return {
1217
2372
  ok: false,
1218
2373
  message: `Could not find old_string in "${name}/${patchLabel}". Use update for a full rewrite.`
1219
2374
  };
@@ -1238,40 +2393,69 @@ var SkillLibrary = class {
1238
2393
  message: threat
1239
2394
  };
1240
2395
  await this.io.writeText(target, patched.trimEnd() + "\n");
2396
+ await this.audit(name, "patch", md, patched, `patched ${patchLabel}`);
2397
+ this.notifyMutation({
2398
+ action: "patch",
2399
+ name,
2400
+ filePath: dir
2401
+ });
1241
2402
  return {
1242
2403
  ok: true,
1243
2404
  message: `Skill "${name}" patched (${patchLabel}).`,
1244
2405
  path: dir
1245
2406
  };
1246
2407
  }
1247
- async archive(name, absorbedInto = "") {
1248
- const dir = skillDir(this.root, name);
1249
- if (!await this.io.readText(join(dir, "SKILL.md"))) return {
2408
+ async archive(rawName, options = {}) {
2409
+ const name = rawName.trim();
2410
+ const badName = this.badName(name);
2411
+ if (badName) return {
2412
+ ok: false,
2413
+ message: badName
2414
+ };
2415
+ const dir = this.dirOf(name);
2416
+ const md = await this.io.readText(join(dir, "SKILL.md"));
2417
+ if (!md) return {
1250
2418
  ok: false,
1251
2419
  message: `Skill "${name}" not found.`
1252
2420
  };
1253
- const protection = await this.deleteProtection(name);
2421
+ const protection = await this.deleteProtection(name, options.allowBundled === void 0 ? {} : { allowBundled: options.allowBundled });
1254
2422
  if (protection) return {
1255
2423
  ok: false,
1256
2424
  message: `Skill "${name}" is protected (${protection}).`
1257
2425
  };
1258
- if (absorbedInto) {
1259
- if (!await this.io.readText(join(skillDir(this.root, absorbedInto), "SKILL.md"))) return {
2426
+ if (options.absorbedInto) {
2427
+ if (!await this.io.readText(join(this.dirOf(options.absorbedInto), "SKILL.md"))) return {
1260
2428
  ok: false,
1261
- message: `absorbed_into="${absorbedInto}" does not exist.`
2429
+ message: `absorbed_into="${options.absorbedInto}" does not exist.`
1262
2430
  };
1263
2431
  }
1264
2432
  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)}`);
2433
+ let dest = join(archiveRoot, name.trim());
2434
+ if (await this.io.exists(dest)) {
2435
+ const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[-:T]/g, "").slice(0, 14);
2436
+ dest = join(archiveRoot, `${name.trim()}-${stamp}`);
2437
+ while (await this.io.exists(dest)) dest = join(archiveRoot, `${name.trim()}-${stamp}-${Math.random().toString(36).slice(2, 8)}`);
2438
+ }
2439
+ if (this.io.isSymlink) {
2440
+ if (await this.io.isSymlink(dir) === true) return {
2441
+ ok: false,
2442
+ message: `Skill "${name}" is a symlink; refusing to archive it.`
2443
+ };
2444
+ }
1267
2445
  try {
1268
2446
  await this.io.rename(dir, dest);
1269
2447
  } catch {
1270
2448
  await this.io.copy(dir, dest);
1271
2449
  await this.io.remove(dir);
1272
2450
  }
1273
- const reason = absorbedInto ? `Consolidated into ${absorbedInto}` : "Archived by self-evolution curator";
2451
+ const reason = options.reason ?? (options.absorbedInto ? `Consolidated into ${options.absorbedInto}` : "Archived by self-evolution curator");
1274
2452
  await this.io.writeText(join(dest, ".archive-reason"), `${(/* @__PURE__ */ new Date()).toISOString()}: ${reason}\n`);
2453
+ await this.audit(name, "archive", md, null, reason);
2454
+ this.notifyMutation({
2455
+ action: "archive",
2456
+ name,
2457
+ archivedPath: dest
2458
+ });
1275
2459
  return {
1276
2460
  ok: true,
1277
2461
  message: `Skill "${name}" archived to .archive.`,
@@ -1283,26 +2467,27 @@ var SkillLibrary = class {
1283
2467
  * an absorbed-into marker. Hermes-style consolidation: overlapping skills
1284
2468
  * collapse into one, and the originals stay recoverable under `.archive/`.
1285
2469
  */
1286
- async consolidate(target, sources) {
1287
- const normalizedSources = [...new Set(sources)].filter((name) => name !== target);
2470
+ async consolidate(target, sources, origin = "foreground") {
2471
+ const targetName = target.trim();
2472
+ const normalizedSources = [...new Set(sources.map((name) => name.trim()))].filter((name) => name !== targetName);
1288
2473
  if (normalizedSources.length === 0) return {
1289
2474
  ok: false,
1290
2475
  message: "Consolidation requires at least one distinct source skill."
1291
2476
  };
1292
- for (const name of [target, ...normalizedSources]) if (!SKILL_NAME_RE.test(name)) return {
2477
+ for (const name of [targetName, ...normalizedSources]) if (!SKILL_NAME_RE.test(name)) return {
1293
2478
  ok: false,
1294
2479
  message: `Invalid skill name "${name}". Use lowercase letters, digits, and hyphens.`
1295
2480
  };
1296
- const targetDir = skillDir(this.root, target);
2481
+ const targetDir = this.dirOf(targetName);
1297
2482
  const targetMd = await this.io.readText(join(targetDir, "SKILL.md"));
1298
2483
  if (!targetMd) return {
1299
2484
  ok: false,
1300
- message: `Skill "${target}" not found.`
2485
+ message: `Skill "${targetName}" not found.`
1301
2486
  };
1302
- const targetProtection = await this.writeProtection(target);
2487
+ const targetProtection = await this.writeProtection(targetName, origin);
1303
2488
  if (targetProtection) return {
1304
2489
  ok: false,
1305
- message: `Skill "${target}" is protected (${targetProtection}).`
2490
+ message: `Skill "${targetName}" is protected (${targetProtection}).`
1306
2491
  };
1307
2492
  const parts = [];
1308
2493
  for (const source of normalizedSources) {
@@ -1311,7 +2496,7 @@ var SkillLibrary = class {
1311
2496
  ok: false,
1312
2497
  message: `Skill "${source}" is protected (${protection}).`
1313
2498
  };
1314
- const sourceMd = await this.io.readText(join(skillDir(this.root, source), "SKILL.md"));
2499
+ const sourceMd = await this.io.readText(join(this.dirOf(source), "SKILL.md"));
1315
2500
  if (!sourceMd) return {
1316
2501
  ok: false,
1317
2502
  message: `Skill "${source}" not found.`
@@ -1324,7 +2509,7 @@ var SkillLibrary = class {
1324
2509
  parts.push(`\n<!-- consolidated from ${source} at ${(/* @__PURE__ */ new Date()).toISOString()} -->\n${parsed.body.trim()}`);
1325
2510
  }
1326
2511
  const merged = targetMd.trimEnd() + parts.join("\n") + "\n";
1327
- const validation = validateFrontmatter(merged, target, this.limits);
2512
+ const validation = validateFrontmatter(merged, targetName, this.limits);
1328
2513
  if (validation) return {
1329
2514
  ok: false,
1330
2515
  message: `Consolidation rejected: ${validation}`
@@ -1334,14 +2519,30 @@ var SkillLibrary = class {
1334
2519
  ok: false,
1335
2520
  message: threat
1336
2521
  };
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;
2522
+ const archived = [];
2523
+ try {
2524
+ for (const source of normalizedSources) {
2525
+ const result = await this.archive(source, { absorbedInto: targetName });
2526
+ if (!result.ok) throw new Error(result.message);
2527
+ archived.push(source);
2528
+ }
2529
+ await this.io.writeText(join(targetDir, "SKILL.md"), merged);
2530
+ } catch (error) {
2531
+ await this.io.writeText(join(targetDir, "SKILL.md"), targetMd).catch(() => {});
2532
+ for (const source of archived.reverse()) await this.restoreFromArchive(source).catch(() => {});
2533
+ return {
2534
+ ok: false,
2535
+ message: `Consolidation failed and was rolled back: ${error instanceof Error ? error.message : String(error)}`
2536
+ };
1341
2537
  }
2538
+ this.notifyMutation({
2539
+ action: "consolidate",
2540
+ name: targetName,
2541
+ filePath: targetDir
2542
+ });
1342
2543
  return {
1343
2544
  ok: true,
1344
- message: `Consolidated ${normalizedSources.join(", ")} into "${target}".`,
2545
+ message: `Consolidated ${normalizedSources.join(", ")} into "${targetName}".`,
1345
2546
  path: targetDir
1346
2547
  };
1347
2548
  }
@@ -1350,12 +2551,13 @@ var SkillLibrary = class {
1350
2551
  * recoverability: archival never deletes, and this is the control-plane
1351
2552
  * path back. The `.archive-reason` marker is dropped on restore.
1352
2553
  */
1353
- async restoreFromArchive(name) {
2554
+ async restoreFromArchive(rawName) {
2555
+ const name = rawName.trim();
1354
2556
  if (!SKILL_NAME_RE.test(name)) return {
1355
2557
  ok: false,
1356
2558
  message: `Invalid skill name "${name}". Use lowercase letters, digits, and hyphens.`
1357
2559
  };
1358
- if (await this.io.exists(join(skillDir(this.root, name), "SKILL.md"))) return {
2560
+ if (await this.io.exists(join(this.dirOf(name), "SKILL.md"))) return {
1359
2561
  ok: false,
1360
2562
  message: `Skill "${name}" already exists in the active root; refusing to overwrite.`
1361
2563
  };
@@ -1375,7 +2577,13 @@ var SkillLibrary = class {
1375
2577
  message: `Skill "${name}" is not in .archive.`
1376
2578
  };
1377
2579
  const source = join(archiveRoot, chosen);
1378
- const dest = skillDir(this.root, name);
2580
+ const dest = this.dirOf(name);
2581
+ if (this.io.isSymlink) {
2582
+ if (await this.io.isSymlink(source) === true) return {
2583
+ ok: false,
2584
+ message: `Archived entry "${chosen}" is a symlink; refusing to restore it.`
2585
+ };
2586
+ }
1379
2587
  try {
1380
2588
  await this.io.rename(source, dest);
1381
2589
  } catch {
@@ -1383,19 +2591,30 @@ var SkillLibrary = class {
1383
2591
  await this.io.remove(source);
1384
2592
  }
1385
2593
  if (await this.io.exists(join(dest, ".archive-reason"))) await this.io.remove(join(dest, ".archive-reason"));
2594
+ this.notifyMutation({
2595
+ action: "restore",
2596
+ name,
2597
+ filePath: dest
2598
+ });
1386
2599
  return {
1387
2600
  ok: true,
1388
2601
  message: `Skill "${name}" restored from .archive.`,
1389
2602
  path: dest
1390
2603
  };
1391
2604
  }
1392
- async writeSupportFile(name, filePath, content) {
1393
- const dir = skillDir(this.root, name);
2605
+ async writeSupportFile(rawName, filePath, content, origin = "foreground") {
2606
+ const name = rawName.trim();
2607
+ const badName = this.badName(name);
2608
+ if (badName) return {
2609
+ ok: false,
2610
+ message: badName
2611
+ };
2612
+ const dir = this.dirOf(name);
1394
2613
  if (!await this.io.exists(join(dir, "SKILL.md"))) return {
1395
2614
  ok: false,
1396
2615
  message: `Skill "${name}" not found.`
1397
2616
  };
1398
- const protection = await this.writeProtection(name);
2617
+ const protection = await this.writeProtection(name, origin);
1399
2618
  if (protection) return {
1400
2619
  ok: false,
1401
2620
  message: `Skill "${name}" is protected (${protection}).`
@@ -1415,20 +2634,33 @@ var SkillLibrary = class {
1415
2634
  message: threat
1416
2635
  };
1417
2636
  const target = join(dir, ...filePath.replace(/\\/g, "/").split("/").filter(Boolean));
2637
+ const existing = await this.io.readText(target).catch(() => null);
1418
2638
  await this.io.writeText(target, content);
2639
+ await this.audit(name, "write_file", existing, content, `wrote ${filePath}`);
2640
+ this.notifyMutation({
2641
+ action: "write_file",
2642
+ name,
2643
+ filePath: target
2644
+ });
1419
2645
  return {
1420
2646
  ok: true,
1421
2647
  message: `Support file "${filePath}" written to "${name}".`,
1422
2648
  path: target
1423
2649
  };
1424
2650
  }
1425
- async removeSupportFile(name, filePath) {
1426
- const dir = skillDir(this.root, name);
2651
+ async removeSupportFile(rawName, filePath, origin = "foreground") {
2652
+ const name = rawName.trim();
2653
+ const badName = this.badName(name);
2654
+ if (badName) return {
2655
+ ok: false,
2656
+ message: badName
2657
+ };
2658
+ const dir = this.dirOf(name);
1427
2659
  if (!await this.io.exists(join(dir, "SKILL.md"))) return {
1428
2660
  ok: false,
1429
2661
  message: `Skill "${name}" not found.`
1430
2662
  };
1431
- const protection = await this.writeProtection(name);
2663
+ const protection = await this.writeProtection(name, origin);
1432
2664
  if (protection) return {
1433
2665
  ok: false,
1434
2666
  message: `Skill "${name}" is protected (${protection}).`
@@ -1443,24 +2675,88 @@ var SkillLibrary = class {
1443
2675
  ok: false,
1444
2676
  message: `File "${filePath}" not found in skill "${name}".`
1445
2677
  };
2678
+ const before = await this.io.readText(target).catch(() => null);
1446
2679
  await this.io.remove(target);
2680
+ await this.audit(name, "remove_file", before, null, `removed ${filePath}`);
2681
+ this.notifyMutation({
2682
+ action: "remove_file",
2683
+ name,
2684
+ filePath: target
2685
+ });
1447
2686
  return {
1448
2687
  ok: true,
1449
2688
  message: `Support file "${filePath}" removed from "${name}".`,
1450
2689
  path: target
1451
2690
  };
1452
2691
  }
1453
- async snapshotAll(reason = "pre-mutation") {
1454
- const dest = join(join(this.root, ".backups"), `skills-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}`);
2692
+ /**
2693
+ * Snapshot the recoverable skills state: active tree, usage/suppression
2694
+ * sidecars, `.archive/` and caller-supplied extras. `extras` are opaque
2695
+ * side files the Snapshot owner cares about (curator state); they are
2696
+ * listed in the manifest and only those names are ever read back.
2697
+ */
2698
+ async snapshotAll(reason = "pre-mutation", extras = []) {
2699
+ const backupRoot = join(this.root, ".backups");
2700
+ const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
2701
+ let dest = join(backupRoot, `skills-${stamp}`);
2702
+ while (await this.io.exists(dest)) dest = join(backupRoot, `skills-${stamp}-${Math.random().toString(36).slice(2, 8)}`);
1455
2703
  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));
2704
+ await Promise.all(names.map(async (name) => {
2705
+ await this.io.copy(this.dirOf(name), join(dest, name));
2706
+ }));
2707
+ const sidecars = [];
2708
+ for (const sidecar of [usageFile(this.root), suppressedFile(this.root)]) if (await this.io.exists(sidecar)) {
2709
+ const name = basename(sidecar);
2710
+ await this.io.copy(sidecar, join(dest, name));
2711
+ sidecars.push(name);
2712
+ }
2713
+ const archiveRoot = join(this.root, ".archive");
2714
+ let hasArchive = false;
2715
+ if (await this.io.exists(archiveRoot)) {
2716
+ await this.io.copy(archiveRoot, join(dest, ".archive"));
2717
+ hasArchive = true;
2718
+ }
2719
+ const validExtras = extras.filter((extra) => SNAPSHOT_EXTRA_NAME_RE.test(extra.name));
2720
+ const extraNames = validExtras.map((extra) => extra.name);
2721
+ await Promise.all(validExtras.map(async (extra) => {
2722
+ await this.io.writeText(join(dest, "extras", extra.name), extra.content);
2723
+ }));
1457
2724
  await this.io.writeText(join(dest, "manifest.json"), JSON.stringify({
1458
2725
  reason,
1459
2726
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1460
- skills: names
2727
+ skills: names,
2728
+ sidecars,
2729
+ hasArchive,
2730
+ extras: extraNames
1461
2731
  }, null, 2));
2732
+ await this.retainSnapshots(5);
1462
2733
  return dest;
1463
2734
  }
2735
+ /** Read and normalize a snapshot manifest; null when the file is missing or unparsable. */
2736
+ async readSnapshotManifest(path) {
2737
+ const raw = await this.io.readText(join(path, "manifest.json"));
2738
+ if (raw === null) return null;
2739
+ try {
2740
+ const manifest = JSON.parse(raw);
2741
+ return {
2742
+ reason: typeof manifest.reason === "string" ? manifest.reason : "",
2743
+ createdAt: typeof manifest.createdAt === "string" ? manifest.createdAt : "",
2744
+ skills: Array.isArray(manifest.skills) ? manifest.skills : [],
2745
+ sidecars: Array.isArray(manifest.sidecars) ? manifest.sidecars : [],
2746
+ ...typeof manifest.hasArchive === "boolean" ? { hasArchive: manifest.hasArchive } : {},
2747
+ extras: Array.isArray(manifest.extras) ? manifest.extras : []
2748
+ };
2749
+ } catch {
2750
+ return null;
2751
+ }
2752
+ }
2753
+ /** Keep only the newest N snapshots (Hermes keep=5 parity); older ones are removed outright. */
2754
+ async retainSnapshots(keep) {
2755
+ const snapshots = await this.listSnapshots();
2756
+ for (const snapshot of snapshots.slice(keep)) try {
2757
+ await this.io.remove(snapshot.path);
2758
+ } catch {}
2759
+ }
1464
2760
  async listSnapshots() {
1465
2761
  const backupRoot = join(this.root, ".backups");
1466
2762
  let entries;
@@ -1472,96 +2768,93 @@ var SkillLibrary = class {
1472
2768
  const out = [];
1473
2769
  for (const name of entries.sort().reverse()) {
1474
2770
  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 {}
2771
+ const manifest = await this.readSnapshotManifest(join(backupRoot, name));
2772
+ if (manifest === null) continue;
2773
+ out.push({
2774
+ path: join(backupRoot, name),
2775
+ createdAt: manifest.createdAt,
2776
+ reason: manifest.reason
2777
+ });
1485
2778
  }
1486
2779
  return out;
1487
2780
  }
1488
- async restoreLatestSnapshot() {
2781
+ /**
2782
+ * Read the extras of a snapshot, restricted to the names declared in the
2783
+ * manifest — an `extras/` directory is never listed directly, so unknown
2784
+ * files cannot leak back as state on the next restore.
2785
+ */
2786
+ async readSnapshotExtras(path) {
2787
+ const manifest = await this.readSnapshotManifest(path);
2788
+ if (manifest === null) return [];
2789
+ const extras = [];
2790
+ for (const name of manifest.extras) {
2791
+ if (!SNAPSHOT_EXTRA_NAME_RE.test(name)) continue;
2792
+ const content = await this.io.readText(join(path, "extras", name));
2793
+ if (content !== null) extras.push({
2794
+ name,
2795
+ content
2796
+ });
2797
+ }
2798
+ return extras;
2799
+ }
2800
+ /**
2801
+ * Manifest-driven restore of the latest snapshot: active tree, sidecars,
2802
+ * `.archive/` and (for full-state snapshots) the extras read back by the
2803
+ * caller. `extras` are additionally written into the pre-rollback safety
2804
+ * snapshot so the rollback itself is undoable with the same state.
2805
+ */
2806
+ async restoreLatestSnapshot(extras = []) {
1489
2807
  const latest = (await this.listSnapshots())[0];
1490
2808
  if (!latest) return {
1491
2809
  ok: false,
1492
2810
  message: "No skill snapshot available."
1493
2811
  };
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;
2812
+ await this.snapshotAll("pre-rollback", extras);
2813
+ let rootEntries;
2814
+ try {
2815
+ rootEntries = await this.io.list(this.root);
2816
+ } catch {
2817
+ rootEntries = [];
2818
+ }
2819
+ for (const entry of rootEntries) {
2820
+ if (entry.startsWith(".")) continue;
2821
+ await this.io.remove(join(this.root, entry));
2822
+ }
2823
+ const manifest = await this.readSnapshotManifest(latest.path);
2824
+ if (manifest === null) for (const entry of await this.io.list(latest.path)) {
2825
+ if (entry === "manifest.json" || entry === "extras") continue;
1499
2826
  await this.io.copy(join(latest.path, entry), join(this.root, entry));
1500
2827
  }
2828
+ else {
2829
+ for (const name of manifest.skills) await this.io.copy(join(latest.path, name), join(this.root, name));
2830
+ for (const sidecar of manifest.sidecars) await this.io.copy(join(latest.path, sidecar), join(this.root, sidecar));
2831
+ const archiveRoot = join(this.root, ".archive");
2832
+ if (manifest.hasArchive === true) {
2833
+ await this.io.remove(archiveRoot);
2834
+ await this.io.copy(join(latest.path, ".archive"), archiveRoot);
2835
+ } else if (manifest.hasArchive === false) await this.io.remove(archiveRoot);
2836
+ }
2837
+ const snapshotExtras = await this.readSnapshotExtras(latest.path);
2838
+ this.notifyMutation({
2839
+ action: "restore",
2840
+ name: "snapshot"
2841
+ });
1501
2842
  return {
1502
2843
  ok: true,
1503
2844
  message: `Restored skill tree from ${latest.path}`,
1504
- path: latest.path
2845
+ path: latest.path,
2846
+ ...snapshotExtras.length === 0 ? {} : { extras: snapshotExtras }
1505
2847
  };
1506
2848
  }
1507
2849
  };
1508
2850
  //#endregion
1509
2851
  //#region lib/types/state-store.js
1510
2852
  /**
1511
- * Small crash-safe JSON state store for plugin-owned sidecar state.
1512
- * Writes are atomic (temp + rename). Reads are synchronous for startup use.
2853
+ * Evolution home path helper: `$DSH_HOME/evolution` for plugin-owned sidecar
2854
+ * state (reports, activity store, feedback file, state-domain data).
1513
2855
  */
1514
2856
  function evolutionHome(env = process.env) {
1515
2857
  return join(env.DSH_HOME ?? join(homedir(), ".dsh"), "evolution");
1516
2858
  }
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
2859
  //#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 };
2860
+ export { AUTHORING_DESCRIPTION_BAR, 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, 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_PROMPT, SNAPSHOT_EXTRA_NAME_RE, SUPPORT_DIRS, SUPPRESSED_FILE_VERSION, SkillLibrary, advanceReview, authoringFeedback, buildCuratorRunReport, buildLearnPrompt, bumpPatch, bumpUse, bumpView, computeDedupGroups, computeLifecycleTransitions, computeQualityScores, computeScopeView, contentHash, createGateSet, emptyRecord, evaluateThreat, evolutionHome, evolutionIoAdapter, foldTurn, getRecord, latestActivityAt, lifecycleCandidate, loadMutations, loadSuppressedNames, loadUsage, markAgentCreated, memoryRoot, mutateUsage, mutationsFile, nodeEvolutionIo, normalizeUsageRecord, observeEvent, parseCuratorNominations, parseFrontmatter, recordMutation, relatedSkillNames, renderCuratorReportMarkdown, resolveOrigins, reviewPrompt, saveSuppressedNames, saveUsage, scanContentThreats, scanMemoryThreats, scanThreats, skillsRoot, suppressedFile, transactIo, updateSuppressedNames, usageFile, validateFrontmatter, verifyPromptBundle };