@lmzhen/dsh-evolution-core 0.1.0-rc.9 → 0.2.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,16 +1,28 @@
1
- import { dirname, join } from "node:path";
2
- import { cp, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
1
+ import { basename, dirname, join } from "node:path";
2
+ import { cp, lstat, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
3
3
  import { createHash, randomBytes } from "node:crypto";
4
4
  import { homedir } from "node:os";
5
- import { readFileSync } from "node:fs";
6
5
  //#region lib/types/io.js
7
6
  /**
8
- * Structural IO seam for the legacy facade stores.
7
+ * Structural IO seam for the evolution plugin family.
9
8
  *
10
- * The facade accepts any object exposing this small async file-tree surface.
11
- * Native DSH packages pass `ctx.evolutionIo.provider()`; standalone consumers
12
- * (and the facade's own tests) can use `nodeEvolutionIo`.
9
+ * Every evolution package passes `ctx.evolutionIo.provider()`; standalone
10
+ * consumers (and the core's own tests) can use `nodeEvolutionIo`.
13
11
  */
12
+ /**
13
+ * Run `task` inside `io.transact` when the backend provides it; otherwise fall
14
+ * back to a plain read → task → write/remove sequence (no cross-process lock —
15
+ * callers keep their single-process serialize chain as the second layer).
16
+ */
17
+ async function transactIo(io, path, task) {
18
+ if (io.transact) {
19
+ await io.transact(path, task);
20
+ return;
21
+ }
22
+ const next = await task(await io.readText(path));
23
+ if (next === null) await io.remove(path);
24
+ else await io.writeText(path, next);
25
+ }
14
26
  /** Lazy adapter over an IO provider registry, shared by every evolution consumer. */
15
27
  function evolutionIoAdapter(provider) {
16
28
  return {
@@ -20,23 +32,112 @@ function evolutionIoAdapter(provider) {
20
32
  list: (path) => provider().list(path),
21
33
  exists: (path) => provider().exists(path),
22
34
  rename: (path, destination) => provider().rename(path, destination),
23
- copy: (path, destination) => provider().copy(path, destination)
35
+ copy: (path, destination) => provider().copy(path, destination),
36
+ size: (path) => {
37
+ const io = provider();
38
+ return io.size ? io.size(path) : Promise.resolve(null);
39
+ },
40
+ transact: (path, task) => {
41
+ const io = provider();
42
+ return io.transact ? io.transact(path, task) : transactIo(io, path, task);
43
+ },
44
+ isSymlink: (path) => {
45
+ const io = provider();
46
+ return io.isSymlink ? io.isSymlink(path) : Promise.resolve(null);
47
+ }
24
48
  };
25
49
  }
26
50
  function nodeEvolutionIo() {
51
+ const isMissing = (error) => {
52
+ const code = error?.code;
53
+ return code === "ENOENT" || code === "ENOTDIR";
54
+ };
55
+ /** True when the pid is alive (EPERM = alive but unowned; ESRCH = gone). */
56
+ const isAlive = (pid) => {
57
+ try {
58
+ process.kill(pid, 0);
59
+ return true;
60
+ } catch (error) {
61
+ return error?.code === "EPERM";
62
+ }
63
+ };
64
+ /**
65
+ * Cross-process write lock (claw `withFileLock` parity): an O_EXCL lock file
66
+ * guards the atomic write. A >5s-old lock is taken over ONLY after probing
67
+ * the holder pid it carries (rc.66): a LIVE holder is never stolen, so a
68
+ * slow writer no longer loses its lock to a peer at the 5s mark (the
69
+ * takeover is the only best-effort surface; the retry budget fails loud —
70
+ * rc.65 — instead of ever proceeding unlocked). Budget = 40 * 50ms (~2s,
71
+ * rc.69): 8-writer contention bursts on a loaded CI runner exceed 10
72
+ * attempts (500ms), and a fail-loud throw was observed instead of a clean
73
+ * serialization.
74
+ */
75
+ const withWriteLock = async (path, task) => {
76
+ const lock = `${path}.lock`;
77
+ for (let attempt = 0; attempt < 40; attempt += 1) try {
78
+ await writeFile(lock, String(process.pid), { flag: "wx" });
79
+ try {
80
+ return await task();
81
+ } finally {
82
+ await rm(lock, { force: true }).catch(() => {});
83
+ }
84
+ } catch (error) {
85
+ const code = error?.code;
86
+ if (code !== "EEXIST" && code !== "EPERM") throw error;
87
+ try {
88
+ const st = await stat(lock);
89
+ if (Date.now() - st.mtimeMs > 5e3) {
90
+ const holder = Number(await readFile(lock, "utf8").catch(() => ""));
91
+ if (!(Number.isInteger(holder) && holder > 0 && isAlive(holder))) {
92
+ try {
93
+ await rm(lock, { force: true });
94
+ } catch {}
95
+ continue;
96
+ }
97
+ }
98
+ } catch {
99
+ continue;
100
+ }
101
+ await new Promise((resolve) => setTimeout(resolve, 50));
102
+ }
103
+ throw new Error(`could not acquire write lock for ${path} after 40 attempts`);
104
+ };
27
105
  return {
28
106
  async readText(path) {
29
107
  try {
30
108
  return await readFile(path, "utf8");
31
- } catch {
32
- return null;
109
+ } catch (error) {
110
+ if (isMissing(error)) return null;
111
+ throw error;
33
112
  }
34
113
  },
35
114
  async writeText(path, content) {
36
115
  await mkdir(dirname(path), { recursive: true });
37
- const tmp = `${path}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
38
- await writeFile(tmp, content, "utf8");
39
- await rename(tmp, path);
116
+ await withWriteLock(path, async () => {
117
+ const tmp = `${path}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
118
+ await writeFile(tmp, content, "utf8");
119
+ await rename(tmp, path);
120
+ });
121
+ },
122
+ async transact(path, task) {
123
+ await mkdir(dirname(path), { recursive: true });
124
+ await withWriteLock(path, async () => {
125
+ let current;
126
+ try {
127
+ current = await readFile(path, "utf8");
128
+ } catch (error) {
129
+ if (isMissing(error)) current = null;
130
+ else throw error;
131
+ }
132
+ const next = await task(current);
133
+ if (next === null) {
134
+ await rm(path, { force: true });
135
+ return;
136
+ }
137
+ const tmp = `${path}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
138
+ await writeFile(tmp, next, "utf8");
139
+ await rename(tmp, path);
140
+ });
40
141
  },
41
142
  async remove(path) {
42
143
  await rm(path, {
@@ -47,16 +148,18 @@ function nodeEvolutionIo() {
47
148
  async list(path) {
48
149
  try {
49
150
  return await readdir(path);
50
- } catch {
51
- return [];
151
+ } catch (error) {
152
+ if (isMissing(error)) return [];
153
+ throw error;
52
154
  }
53
155
  },
54
156
  async exists(path) {
55
157
  try {
56
158
  await stat(path);
57
159
  return true;
58
- } catch {
59
- return false;
160
+ } catch (error) {
161
+ if (isMissing(error)) return false;
162
+ throw error;
60
163
  }
61
164
  },
62
165
  async rename(path, destination) {
@@ -69,6 +172,21 @@ function nodeEvolutionIo() {
69
172
  recursive: true,
70
173
  force: true
71
174
  });
175
+ },
176
+ async size(path) {
177
+ try {
178
+ return (await stat(path)).size;
179
+ } catch (error) {
180
+ if (isMissing(error)) return null;
181
+ throw error;
182
+ }
183
+ },
184
+ async isSymlink(path) {
185
+ try {
186
+ return (await lstat(path)).isSymbolicLink();
187
+ } catch {
188
+ return null;
189
+ }
72
190
  }
73
191
  };
74
192
  }
@@ -96,22 +214,126 @@ function emptyRecord() {
96
214
  archived_at: null
97
215
  };
98
216
  }
99
- async function loadUsage(root, io = nodeEvolutionIo()) {
217
+ /** A timestamp passes only when `Date.parse` yields a finite epoch (N-3): a bare
218
+ * string check let garbage like "not-a-date" propagate as Invalid Date → NaN
219
+ * into quality math and lifecycle comparisons. */
220
+ const validTimestamp = (value) => typeof value === "string" && Number.isFinite(Date.parse(value));
221
+ const nullableTimestamp = (value) => value === null || validTimestamp(value);
222
+ /**
223
+ * Field-level normalization for one sidecar record (rc.42 audit P2-3): the
224
+ * spread used to copy any junk through verbatim, so a corrupted file could
225
+ * carry `use_count: "3"` into the quality math and lifecycle comparisons as
226
+ * NaN. Every field falls back to its `emptyRecord()` baseline unless it has
227
+ * exactly the declared type; an invalid `created_at` anchors the age clock at
228
+ * now (first-sight defer semantics for a record whose age is unknowable).
229
+ * Timestamps additionally require a parseable date (N-3): `"not-a-date"`
230
+ * would otherwise survive the type check as Invalid Date.
231
+ * Pure — exported for unit tests; `loadUsage` is the production caller.
232
+ */
233
+ function normalizeUsageRecord(record) {
234
+ const base = emptyRecord();
235
+ if (!record || typeof record !== "object" || Array.isArray(record)) return base;
236
+ const raw = record;
237
+ const num = (value, fallback) => typeof value === "number" && Number.isFinite(value) ? value : fallback;
238
+ const bool = (value, fallback) => typeof value === "boolean" ? value : fallback;
239
+ return {
240
+ created_by: typeof raw.created_by === "string" ? raw.created_by : null,
241
+ use_count: num(raw.use_count, base.use_count),
242
+ view_count: num(raw.view_count, base.view_count),
243
+ patch_count: num(raw.patch_count, base.patch_count),
244
+ last_used_at: nullableTimestamp(raw.last_used_at) ? raw.last_used_at : base.last_used_at,
245
+ last_viewed_at: nullableTimestamp(raw.last_viewed_at) ? raw.last_viewed_at : base.last_viewed_at,
246
+ last_patched_at: nullableTimestamp(raw.last_patched_at) ? raw.last_patched_at : base.last_patched_at,
247
+ created_at: validTimestamp(raw.created_at) ? raw.created_at : base.created_at,
248
+ state: raw.state === "stale" || raw.state === "archived" ? raw.state : "active",
249
+ pinned: bool(raw.pinned, base.pinned),
250
+ archived_at: nullableTimestamp(raw.archived_at) ? raw.archived_at : base.archived_at,
251
+ quality_score: typeof raw.quality_score === "number" && Number.isFinite(raw.quality_score) ? raw.quality_score : void 0,
252
+ quality_warn: typeof raw.quality_warn === "boolean" ? raw.quality_warn : void 0
253
+ };
254
+ }
255
+ /** Parse a raw usage sidecar; malformed content reads as empty (best-effort telemetry). */
256
+ function parseUsage(raw) {
100
257
  const map = /* @__PURE__ */ new Map();
101
- const raw = await io.readText(usageFile(root));
102
- if (raw !== null) try {
258
+ if (raw === null) return map;
259
+ try {
103
260
  const parsed = JSON.parse(raw);
104
- for (const [name, record] of Object.entries(parsed)) {
105
- const base = emptyRecord();
106
- map.set(name, {
107
- ...base,
108
- ...record,
109
- state: record.state === "stale" || record.state === "archived" ? record.state : "active"
110
- });
111
- }
261
+ for (const [name, record] of Object.entries(parsed)) map.set(name, normalizeUsageRecord(record));
112
262
  } catch {}
113
263
  return map;
114
264
  }
265
+ async function loadUsage(root, io = nodeEvolutionIo()) {
266
+ return parseUsage(await io.readText(usageFile(root)));
267
+ }
268
+ /**
269
+ * Atomic read-modify-write on the usage sidecar (rc.50 P2-2): `task` receives
270
+ * the map parsed from the current on-disk state and may mutate it; the result
271
+ * is persisted inside the same transact so a second process sharing DSH_HOME
272
+ * cannot interleave its RMW and lose a counter update. Callers keep their own
273
+ * single-process serialize chain as the second layer.
274
+ */
275
+ async function mutateUsage(root, io, task) {
276
+ await transactIo(io, usageFile(root), async (current) => {
277
+ if (current !== null) try {
278
+ JSON.parse(current);
279
+ } catch {
280
+ return current;
281
+ }
282
+ const map = parseUsage(current);
283
+ await task(map);
284
+ return JSON.stringify(Object.fromEntries(map.entries()), null, 2);
285
+ });
286
+ }
287
+ /**
288
+ * Curator-owned usage fields (rc.67 K-2): the curator writes ONLY this set —
289
+ * lifecycle state, archive stamp, the six-factor quality pair, and the
290
+ * marker-mirrored pin flag. Counter and activity-stamp fields belong to the
291
+ * tool-telemetry side (skill-usage / tool-skill-manage), which bumps them
292
+ * through its own transact-backed RMW. A whole-record overwrite by either
293
+ * side would clobber the other side's concurrent increment, so cross-side
294
+ * folds copy this set only.
295
+ */
296
+ function applyCuratorFields(disk, curated) {
297
+ applyCuratorMetaFields(disk, curated);
298
+ applyCuratorLifecycleFields(disk, curated);
299
+ }
300
+ /** Copy only the lifecycle pair (state/archived_at) — see the ownership split
301
+ * rationale on {@link applyCuratorMetaFields}. */
302
+ function applyCuratorLifecycleFields(disk, curated) {
303
+ disk.state = curated.state;
304
+ disk.archived_at = curated.archived_at;
305
+ }
306
+ /**
307
+ * Copy the recomputed meta pair (quality_score/quality_warn + the
308
+ * marker-mirrored pin flag) — refreshed tree-wide each run by design, so a
309
+ * concurrent curator run's lifecycle changes are never reverted by them.
310
+ */
311
+ function applyCuratorMetaFields(disk, curated) {
312
+ disk.quality_score = curated.quality_score;
313
+ disk.quality_warn = curated.quality_warn;
314
+ disk.pinned = curated.pinned;
315
+ }
316
+ /**
317
+ * Fold a curator run-start snapshot onto the current on-disk map (rc.67 K-2):
318
+ * each curated record is projected onto its disk peer by copying only the
319
+ * curator-owned fields, so a concurrent tool-side bump between snapshot and
320
+ * save survives. Records absent from the snapshot are left untouched; a
321
+ * curated record with no disk peer is seeded from the snapshot. `stateOwned`
322
+ * (rc.72 H-1) restricts the lifecycle pair to the names this run ACTUALLY
323
+ * transitioned — a concurrent curator run's archive/restore is never reverted
324
+ * by a stale snapshot; without it both pairs apply everywhere.
325
+ */
326
+ function foldCuratorFields(disk, curated, stateOwned) {
327
+ for (const [name, record] of curated) {
328
+ const diskRecord = disk.get(name);
329
+ if (!diskRecord) {
330
+ disk.set(name, { ...record });
331
+ continue;
332
+ }
333
+ applyCuratorMetaFields(diskRecord, record);
334
+ if (stateOwned === void 0 || stateOwned.has(name)) applyCuratorLifecycleFields(diskRecord, record);
335
+ }
336
+ }
115
337
  async function saveUsage(root, map, io = nodeEvolutionIo()) {
116
338
  const obj = Object.fromEntries(map.entries());
117
339
  await io.writeText(usageFile(root), JSON.stringify(obj, null, 2));
@@ -151,15 +373,185 @@ function latestActivityAt(record) {
151
373
  if (values.length === 0) return null;
152
374
  return values.sort().reverse()[0] ?? null;
153
375
  }
376
+ /**
377
+ * Whether the library has ANY observed read evidence (C observation window):
378
+ * reads were invisible to the usage sidecar before A2, so `view_count` zero
379
+ * means "never read" ONLY after the first observed read exists anywhere in
380
+ * the map. Before that, churn-based signals (write-ghost) are untrustworthy
381
+ * and callers must suppress them. Pure and derived — never persisted.
382
+ */
383
+ function usageObserved(usage) {
384
+ for (const record of usage.values()) if (record.view_count > 0) return true;
385
+ return false;
386
+ }
387
+ /**
388
+ * Curator suppression sidecar: built-in skills the curator has archived stay
389
+ * suppressed across re-seeds, so the lifecycle never fights a re-created
390
+ * bundled skill. Best-effort load/save, mirroring the usage sidecar posture.
391
+ * Versioned shape ({ version, names }) with legacy plain-array compat.
392
+ */
393
+ const SUPPRESSED_FILE_VERSION = 1;
394
+ function suppressedFile(root) {
395
+ return join(root, ".curator-suppressed.json");
396
+ }
397
+ async function loadSuppressedNames(root, io = nodeEvolutionIo()) {
398
+ return parseSuppressed(await io.readText(suppressedFile(root)));
399
+ }
400
+ function parseSuppressed(raw) {
401
+ if (raw === null) return /* @__PURE__ */ new Set();
402
+ try {
403
+ const parsed = JSON.parse(raw);
404
+ const names = Array.isArray(parsed) ? parsed : typeof parsed === "object" && parsed !== null && Array.isArray(parsed.names) ? parsed.names : [];
405
+ return new Set(names.filter((entry) => typeof entry === "string"));
406
+ } catch {
407
+ return /* @__PURE__ */ new Set();
408
+ }
409
+ }
410
+ async function saveSuppressedNames(root, names, io = nodeEvolutionIo()) {
411
+ await io.writeText(suppressedFile(root), JSON.stringify({
412
+ version: 1,
413
+ names: [...names].sort()
414
+ }, null, 2));
415
+ }
416
+ /**
417
+ * Atomic read-modify-write on the suppression sidecar (rc.50 P2-2): `task`
418
+ * receives the set parsed from the current on-disk state and may mutate it;
419
+ * the result is persisted inside the same transact so a second process
420
+ * sharing DSH_HOME cannot interleave its RMW. Best-effort posture unchanged.
421
+ */
422
+ async function updateSuppressedNames(root, io, task) {
423
+ await transactIo(io, suppressedFile(root), async (current) => {
424
+ if (current !== null) try {
425
+ JSON.parse(current);
426
+ } catch {
427
+ return current;
428
+ }
429
+ const names = parseSuppressed(current);
430
+ await task(names);
431
+ return JSON.stringify({
432
+ version: 1,
433
+ names: [...names].sort()
434
+ }, null, 2);
435
+ });
436
+ }
437
+ //#endregion
438
+ //#region lib/types/constants.js
439
+ /**
440
+ * Shared constants for the dsh-evolution plugin family.
441
+ *
442
+ * Two classes of value live here, deliberately separated by section so future
443
+ * edits do not blur the semantic boundary:
444
+ *
445
+ * 1. **Fixed protocol/format/security invariants** — changing these breaks an
446
+ * on-disk format, a naming/format contract, a path-security boundary, or a
447
+ * cross-component invariant. They are NOT exposed as deployment config.
448
+ *
449
+ * 2. **Cross-package shared tunable defaults** — the same semantic default is
450
+ * read (with a config override path) by more than one package (e.g.
451
+ * `evolution-policy` and `evolution-curator` both default `staleAfterDays`
452
+ * to 30). Centralizing them here means one authoritative default: a config
453
+ * override still applies per package, but the fallback is single-sourced.
454
+ *
455
+ * Package-private tunables (used by exactly one package) stay in that package,
456
+ * not here — see evolution-replay's `DEFAULT_WEIGHTS` and evolution-feedback's
457
+ * threshold, which are intentionally left where they are used.
458
+ * @module @lmzhen/dsh-evolution-core
459
+ */
460
+ /** Skill frontmatter `name` validated for the file name (lowercase + hyphen). */
461
+ const SKILL_NAME_RE = /^[a-z0-9][a-z0-9-]*$/;
462
+ /** Allowed skill support-file subdirectories (path-traversal boundary). */
463
+ const SUPPORT_DIRS = [
464
+ "references",
465
+ "templates",
466
+ "scripts",
467
+ "assets"
468
+ ];
469
+ /** Delimiter between durable memory entries (on-disk storage format). */
470
+ const ENTRY_DELIMITER = "\n§\n";
471
+ /** Built-in skill names the curator must never lifecycle-manage. */
472
+ const PROTECTED_BUILTIN_SKILLS = new Set(["plan"]);
473
+ const MAX_SKILL_NAME_LENGTH = 64;
474
+ const MAX_DESCRIPTION_LENGTH = 1024;
475
+ const MAX_SKILL_CONTENT_CHARS = 1e5;
476
+ const MAX_SKILL_FILE_BYTES = 1048576;
477
+ const DEFAULT_REVIEW_MEMORY_INTERVAL = 10;
478
+ const DEFAULT_REVIEW_SKILL_INTERVAL = 10;
479
+ /** Skill-review completion channel trigger mode: 'cadence' | 'completion' | 'both'. */
480
+ const DEFAULT_SKILL_REVIEW_TRIGGER = "both";
481
+ /** Cumulative session tool calls before a session counts as "proven long" for the completion channel. */
482
+ const DEFAULT_SKILL_REVIEW_COMPLETION_MIN_TOOL_CALLS = 20;
483
+ const DEFAULT_SUBSTANTIVE_MIN_TOOL_CALLS = 3;
484
+ const DEFAULT_SUBSTANTIVE_MIN_USER_CHARS = 200;
485
+ const DEFAULT_SUBSTANTIVE_MIN_AGENT_CHARS = 500;
486
+ const DEFAULT_MAX_OPS_PER_PLAN = 32;
487
+ const DEFAULT_CURATOR_INTERVAL_HOURS = 168;
488
+ const DEFAULT_MIN_IDLE_HOURS = 2;
489
+ const DEFAULT_STALE_AFTER_DAYS = 30;
490
+ const DEFAULT_ARCHIVE_AFTER_DAYS = 90;
491
+ const DEFAULT_MEMORY_CHAR_LIMIT = 2200;
492
+ const DEFAULT_USER_CHAR_LIMIT = 1375;
493
+ /** Consolidation-failure backoff cap, shared by MemoryStore and memory-files' Config default. */
494
+ const DEFAULT_CONSOLIDATION_FAILURES = 3;
495
+ const DEFAULT_SKILL_CONTENT_CHARS = 1e5;
496
+ //#endregion
497
+ //#region lib/types/gates.js
498
+ /**
499
+ * The control-plane protection sets, held once and queried everywhere
500
+ * (decision B, rc.44 plan M2): the lifecycle engine, the scope view, the LLM
501
+ * nomination gate and the control-plane consolidate all answer "is this name
502
+ * off limits — and why" from the same instance, so the gate sets can never
503
+ * drift apart the way the three pre-rc.46 implementations did.
504
+ *
505
+ * Scope boundary: a GateSet covers NAME-SET protections only. Marker-based
506
+ * protections (pinned / bundled / hub-installed) are file markers resolved by
507
+ * `SkillLibrary.writeProtection` / `deleteProtection` — they depend on the
508
+ * filesystem and the write origin, not on a name list.
509
+ * @module @lmzhen/dsh-evolution-core
510
+ */
511
+ var EvolutionGateSet = class {
512
+ exclude;
513
+ referenced;
514
+ suppressed;
515
+ constructor(inputs = {}) {
516
+ this.exclude = inputs.exclude ?? /* @__PURE__ */ new Set();
517
+ this.referenced = inputs.referenced ?? /* @__PURE__ */ new Set();
518
+ this.suppressed = inputs.suppressed ?? /* @__PURE__ */ new Set();
519
+ }
520
+ /**
521
+ * The first protection blocking this name, or null. Any hit blocks — the
522
+ * order is diagnostic only, so a name in two sets reports the first.
523
+ */
524
+ blockReason(name) {
525
+ if (this.exclude.has(name)) return "excluded";
526
+ if (this.referenced.has(name)) return "referenced";
527
+ if (this.suppressed.has(name)) return "suppressed";
528
+ if (PROTECTED_BUILTIN_SKILLS.has(name)) return "protected-builtin";
529
+ return null;
530
+ }
531
+ isBlocked(name) {
532
+ return this.blockReason(name) !== null;
533
+ }
534
+ };
535
+ /** Build a GateSet from the curator-style config field names. */
536
+ function createGateSet(config) {
537
+ return new EvolutionGateSet({
538
+ exclude: config.excludeSkillNames,
539
+ referenced: config.referencedSkillNames,
540
+ suppressed: config.suppressedNames
541
+ });
542
+ }
154
543
  //#endregion
155
544
  //#region lib/types/curator.js
156
545
  /**
157
546
  * Deterministic skill curator: active → stale → archived transitions.
158
- * Pure function; file moves are performed by SkillLibrary.
547
+ * Pure function with one deliberate side effect: records in the passed
548
+ * `usage` map are MUTATED (state/archived_at) to carry the transition — the
549
+ * caller owns the map and decides whether to clone first (dry-run) or persist
550
+ * after. File moves are performed by SkillLibrary.
159
551
  */
160
- const PROTECTED_BUILTIN_SKILLS = new Set(["plan"]);
161
552
  function buildCuratorRunReport(input) {
162
553
  return {
554
+ schemaVersion: 1,
163
555
  runId: input.runId,
164
556
  startedAt: input.startedAt,
165
557
  finishedAt: input.finishedAt,
@@ -168,25 +560,154 @@ function buildCuratorRunReport(input) {
168
560
  archiveCandidates: [...input.archiveCandidates],
169
561
  archived: [...input.archived],
170
562
  failed: [...input.failed],
171
- ...input.snapshotPath === void 0 ? {} : { snapshotPath: input.snapshotPath }
563
+ ...input.consolidated === void 0 ? {} : { consolidated: [...input.consolidated] },
564
+ ...input.snapshotPath === void 0 ? {} : { snapshotPath: input.snapshotPath },
565
+ ...input.llmReviewEnabled === void 0 ? {} : { llmReviewEnabled: input.llmReviewEnabled }
566
+ };
567
+ }
568
+ /**
569
+ * Render a curator run report as a compact human-readable markdown digest
570
+ * (G6): run metadata first, then the notable sections (archived / failed /
571
+ * stale candidates / LLM nominations).
572
+ */
573
+ function renderCuratorReportMarkdown(report) {
574
+ const lines = [
575
+ `# Curator run ${report.runId}`,
576
+ "",
577
+ `- **Started** ${report.startedAt}`,
578
+ `- **Finished** ${report.finishedAt}`,
579
+ `- **Stale candidates**: ${report.staleCandidates.length}`,
580
+ `- **LLM nominations**: ${report.llmNominations.length}`,
581
+ `- **Archived**: ${report.archived.length}`,
582
+ `- **Failed**: ${report.failed.length}`,
583
+ ...report.snapshotPath === void 0 ? [] : [`- **Snapshot**: ${report.snapshotPath}`],
584
+ ...report.llmReviewEnabled === void 0 ? [] : [`- **llmReview**: ${report.llmReviewEnabled}`]
585
+ ];
586
+ const section = (title, items) => items.length === 0 ? [] : [
587
+ "",
588
+ `## ${title}`,
589
+ "",
590
+ ...items.map((item) => `- ${item}`)
591
+ ];
592
+ return [
593
+ ...lines,
594
+ ...section("Archived", report.archived.map((item) => `${item.name} (${item.reason})`)),
595
+ ...section("Failed", report.failed.map((item) => `${item.name}: ${item.reason}`)),
596
+ ...section("Stale candidates", report.staleCandidates),
597
+ ...section("LLM nominations", report.llmNominations),
598
+ ""
599
+ ].join("\n");
600
+ }
601
+ const NOMINATION_NAME_RE = /^[a-z0-9][a-z0-9-]*$/;
602
+ /**
603
+ * Parse the curator LLM's YAML nomination block (consolidations + prunings).
604
+ * Line-oriented and lenient by design: the LLM output is advisory, every name
605
+ * is re-validated against the tree before any file move happens downstream.
606
+ */
607
+ function parseCuratorNominations(text) {
608
+ const prunings = [];
609
+ const consolidations = [];
610
+ let section = null;
611
+ let currentFrom = "";
612
+ let currentMode;
613
+ for (const line of text.split("\n")) {
614
+ const consolidated = /^\s*-\s*from:\s*([a-z0-9][a-z0-9-]*)\s*$/.exec(line);
615
+ if (consolidated) {
616
+ section = "consolidations";
617
+ currentFrom = consolidated[1] ?? "";
618
+ currentMode = void 0;
619
+ continue;
620
+ }
621
+ const mode = /^\s*mode:\s*(append|reference)\s*$/.exec(line);
622
+ if (mode) {
623
+ if (currentFrom !== "") currentMode = mode[1] === "reference" ? "reference" : "append";
624
+ continue;
625
+ }
626
+ const into = /^\s*into:\s*([a-z0-9][a-z0-9-]*)\s*$/.exec(line);
627
+ if (into) {
628
+ const intoName = into[1] ?? "";
629
+ if (section === "consolidations" && currentFrom !== "" && currentFrom !== intoName) consolidations.push({
630
+ from: currentFrom,
631
+ into: intoName,
632
+ ...currentMode === void 0 ? {} : { mode: currentMode }
633
+ });
634
+ currentFrom = "";
635
+ currentMode = void 0;
636
+ continue;
637
+ }
638
+ const pruned = /^\s*-\s*name:\s*([a-z0-9][a-z0-9-]*)\s*$/.exec(line);
639
+ if (pruned) {
640
+ section = "prunings";
641
+ const name = pruned[1];
642
+ if (name) prunings.push(name);
643
+ }
644
+ }
645
+ const valid = (name) => NOMINATION_NAME_RE.test(name);
646
+ return {
647
+ prunings: prunings.filter(valid),
648
+ consolidations: consolidations.filter((item) => valid(item.from) && valid(item.into))
649
+ };
650
+ }
651
+ /**
652
+ * The lifecycle-candidate gate, shared by the transition engine and the scope
653
+ * view so the two can never disagree: records failing ANY of these gates are
654
+ * outside the managed scope.
655
+ */
656
+ function lifecycleCandidate(name, record, config, bundled, gates = createGateSet(config)) {
657
+ if (record.pinned) return false;
658
+ if (gates.isBlocked(name)) return false;
659
+ if (!(record.created_by === "agent" || config.manageUnmanaged === true) && !(config.pruneBuiltins === true && bundled)) return false;
660
+ if (record.state === "archived") return false;
661
+ return true;
662
+ }
663
+ /**
664
+ * Read-only scope classification, derived from the SAME gate the transition
665
+ * engine uses (`lifecycleCandidate`), so the view always predicts what a
666
+ * curator pass may touch. `protectedNames` carries the marker info the usage
667
+ * records lack (bundled / hub-installed / pinned from `SkillLibrary.list()`).
668
+ */
669
+ function computeScopeView(usage, config, protectedNames, gates) {
670
+ const managed = [];
671
+ const watched = [];
672
+ const qualityWarned = [];
673
+ const exempted = [];
674
+ const protectedSet = /* @__PURE__ */ new Set();
675
+ const gateSet = gates ?? createGateSet(config);
676
+ for (const [name, record] of usage) {
677
+ if (gateSet.exclude.has(name) || gateSet.referenced.has(name)) {
678
+ exempted.push(name);
679
+ continue;
680
+ }
681
+ const bundled = config.bundledNames?.has(name) === true;
682
+ const suppressed = gateSet.suppressed.has(name);
683
+ if (record.pinned || bundled || suppressed || protectedNames?.has(name) === true) protectedSet.add(name);
684
+ if (lifecycleCandidate(name, record, config, bundled, gateSet)) {
685
+ managed.push(name);
686
+ if (record.state === "stale" || record.quality_warn === true) watched.push(name);
687
+ if (record.quality_warn === true) qualityWarned.push(name);
688
+ }
689
+ }
690
+ return {
691
+ managed: managed.sort(),
692
+ watched: watched.sort(),
693
+ qualityWarned: qualityWarned.sort(),
694
+ exempted: exempted.sort(),
695
+ protected: [...protectedSet].sort()
172
696
  };
173
697
  }
174
698
  function daysSince(iso, created, now) {
175
699
  return (now - new Date(iso ?? created).getTime()) / 864e5;
176
700
  }
177
- function computeLifecycleTransitions(usage, config, now = /* @__PURE__ */ new Date()) {
701
+ function computeLifecycleTransitions(usage, config, now = /* @__PURE__ */ new Date(), gates) {
178
702
  const result = {
179
703
  transitions: [],
180
704
  archive: [],
181
705
  reactivate: [],
182
706
  markStale: []
183
707
  };
708
+ const gateSet = gates ?? createGateSet(config);
184
709
  for (const [name, record] of usage) {
185
- if (record.pinned) continue;
186
- if (config.excludeSkillNames?.has(name)) continue;
187
- if (record.created_by !== "agent" && config.manageUnmanaged !== true) continue;
188
- if (PROTECTED_BUILTIN_SKILLS.has(name)) continue;
189
- if (record.state === "archived") continue;
710
+ if (!lifecycleCandidate(name, record, config, config.bundledNames?.has(name) === true, gateSet)) continue;
190
711
  const age = daysSince(null, record.created_at, now.getTime());
191
712
  if (record.use_count === 0 && age < config.staleAfterDays) continue;
192
713
  const idle = daysSince(latestActivityAt(record), record.created_at, now.getTime());
@@ -238,6 +759,550 @@ function computeLifecycleTransitions(usage, config, now = /* @__PURE__ */ new Da
238
759
  return result;
239
760
  }
240
761
  //#endregion
762
+ //#region lib/types/evolution-events.js
763
+ /**
764
+ * Self-evolution event log (rc.68): an append-only sidecar under
765
+ * `$DSH_HOME/evolution/events.json` that is the single source of truth for
766
+ * the self-improvement loop. Feedback increments and learn actions share one
767
+ * ordered timeline (`seq` is the ordering key), so "feedback before/after a
768
+ * learn on target X" is answerable. The aggregate `feedback.json` is a
769
+ * rebuildable boot cache, never the truth.
770
+ *
771
+ * Usage events (C semantics, rc.73+): `type:'usage'` records are the
772
+ * OBSERVATION WINDOW ANCHOR — written once, when the library's first observed
773
+ * read (`view_count` 0 -> 1) happens. Before that anchor the usage sidecar
774
+ * has no read evidence (reads were invisible pre-A2), so churn-based health
775
+ * judgments are NOT trustworthy; the curator suppresses them (its
776
+ * `usageObserved()` gate) until the anchor exists. `counts` on the event is a
777
+ * cumulative library-wide snapshot (skills/views/use/patches) at that moment,
778
+ * and `window.opened` pins the window start for the timeline.
779
+ *
780
+ * Rotation (rc.71, 007 design): when the active log reaches
781
+ * `EVENT_LOG_ROTATE_AT` the older half is split into an archive
782
+ * (`events-<lastArchivedSeq>.json`); the boot timeline merges active +
783
+ * archives and dedupes by seq (active copy wins), so the rotation crash window
784
+ * yields the identical timeline. Archival naming is STRICTLY numeric
785
+ * (`/^events-\d+\.json$/`) — user files under the same directory are never
786
+ * read as archives and never pruned (rc.72 G-2).
787
+ */
788
+ const EVENT_LOG_VERSION = 1;
789
+ /** Active-log split point (rc.71): when the active log reaches this many events
790
+ * the older half is rotated into an archive; the active stays bounded so a
791
+ * single append stays O(active) instead of O(total-history). Tunable default —
792
+ * callers may override per append (the tests use small values). */
793
+ const EVENT_LOG_ROTATE_AT = 4e3;
794
+ /** Number of archives retained (rc.71): older archives are pruned at rotation,
795
+ * mirroring retainReports. The horizon covers the loop-analysis window. */
796
+ const EVENT_LOG_RETAIN_ARCHIVES = 10;
797
+ /** Archive file prefix: `events-<lastArchivedSeq>.json`. The active file is
798
+ * `events.json` and never matches this glob. */
799
+ const EVENT_ARCHIVE_PREFIX = "events-";
800
+ /** Archive naming is strictly numeric: a user file such as `events-backup.json`
801
+ * under the same directory is neither read into the timeline nor pruned. */
802
+ const EVENT_ARCHIVE_RE = /^events-(\d+)\.json$/;
803
+ function eventsFile(home) {
804
+ return join(home, "evolution", "events.json");
805
+ }
806
+ function isEventRecord(event) {
807
+ return typeof event === "object" && event !== null && typeof event.seq === "number";
808
+ }
809
+ /**
810
+ * Parse an event log body. A missing file, a whitespace-only file (rc.69:
811
+ * rebuildable, NOT malformed) or a corrupt one reads as empty; corrupt content
812
+ * is still refused on append, never overwritten.
813
+ *
814
+ * Per-entry normalization (rc.70 F-1): entries without a numeric `seq` are
815
+ * skipped here and dropped at the next append — valid entries survive, the
816
+ * damaged record is the only loss (self-heal semantics, matching the usage
817
+ * sidecar's per-field normalization on read).
818
+ */
819
+ function parseEvolutionEvents(raw) {
820
+ if (raw === null || raw.trim() === "") return [];
821
+ try {
822
+ const parsed = JSON.parse(raw);
823
+ if (!Array.isArray(parsed.events)) return [];
824
+ return parsed.events.filter(isEventRecord);
825
+ } catch {
826
+ return [];
827
+ }
828
+ }
829
+ /**
830
+ * List the numeric archives under the log's directory, sorted ascending by
831
+ * their last-archived seq. Single glob predicate for the timeline, the
832
+ * retention pass and the feedback migration check (rc.72 H-3).
833
+ */
834
+ async function listEventArchives(io, path) {
835
+ const dir = dirname(path);
836
+ return (await io.list(dir)).filter((name) => EVENT_ARCHIVE_RE.test(name)).sort((a, b) => {
837
+ return Number.parseInt(a.slice(7, a.length - 5), 10) - Number.parseInt(b.slice(7, b.length - 5), 10);
838
+ });
839
+ }
840
+ /**
841
+ * Append one event under the write lock (rc.68): `seq` = current max + 1
842
+ * computed inside the transact, so two processes appending concurrently never
843
+ * collide. A malformed log is refused (bytes preserved) and the append fails.
844
+ * Returns the assigned seq.
845
+ *
846
+ * Rotation (rc.71, 007 design): when the active log reaches `rotateAt`, the
847
+ * older half is copied into an archive inside the SAME transact (the archive
848
+ * path has its own lock, so no recursion) and the active is replaced with the
849
+ * newer half + the new event. seqs stay globally monotonic; a crash between
850
+ * archive write and active write leaves both copies, which the timeline merge
851
+ * dedupes by seq. An archive-write failure aborts the append (active keeps the
852
+ * full old content — no loss) and the caller's best-effort handling applies.
853
+ *
854
+ * rc.72 G-1: when the ACTIVE is missing/whitespace but archives exist (a
855
+ * deleted active, or B-2 self-heal), seq derivation consults the archive names
856
+ * — the active restarts AFTER the highest archived seq, never at 1, so a new
857
+ * event can never shadow an archived one in the seq-deduped timeline.
858
+ */
859
+ async function appendEvolutionEvent(io, path, event, rotateAt = EVENT_LOG_ROTATE_AT) {
860
+ let assigned = 0;
861
+ await transactIo(io, path, async (current) => {
862
+ if (current !== null && current.trim() !== "") try {
863
+ JSON.parse(current);
864
+ } catch {
865
+ return current;
866
+ }
867
+ const nextEvents = await rotateIfDue(io, path, parseEvolutionEvents(current), rotateAt);
868
+ let maxSeq = nextEvents.reduce((max, entry) => Math.max(max, entry.seq), 0);
869
+ if (maxSeq === 0) for (const name of await listEventArchives(io, path)) maxSeq = Math.max(maxSeq, Number.parseInt(name.slice(7, name.length - 5), 10));
870
+ const record = {
871
+ ...event,
872
+ seq: maxSeq + 1,
873
+ at: (/* @__PURE__ */ new Date()).toISOString()
874
+ };
875
+ assigned = record.seq;
876
+ return JSON.stringify({
877
+ version: 1,
878
+ events: [...nextEvents, record]
879
+ }, null, 2);
880
+ });
881
+ if (assigned === 0) throw new Error(`evolution event log is malformed and was not touched: ${path}`);
882
+ return assigned;
883
+ }
884
+ /**
885
+ * Split the active log at its midpoint when due: the older half is written to
886
+ * `events-<lastArchivedSeq>.json` (await — a failed archive write aborts the
887
+ * append so the active is never truncated without its copy), old archives are
888
+ * pruned, and the newer half is returned as the next active body. No-op when
889
+ * under the threshold; `rotateAt < 2` is a guarded no-op (rc.72 G-1: a
890
+ * one-event rotate would archive everything and restart seqs at 1).
891
+ */
892
+ async function rotateIfDue(io, path, events, rotateAt) {
893
+ if (rotateAt < 2 || events.length < rotateAt) return events;
894
+ const mid = Math.ceil(events.length / 2);
895
+ const head = events.slice(0, mid);
896
+ const tail = events.slice(mid);
897
+ if (tail.length === 0) return events;
898
+ const anchor = tail[0]?.seq ?? 0;
899
+ const archivePath = join(dirname(path), `${EVENT_ARCHIVE_PREFIX}${anchor - 1}.json`);
900
+ await io.writeText(archivePath, JSON.stringify({
901
+ version: 1,
902
+ events: head
903
+ }, null, 2));
904
+ await retainEventArchives(io, path);
905
+ return tail;
906
+ }
907
+ /**
908
+ * Prune old event archives (rc.71): keep the newest `EVENT_LOG_RETAIN_ARCHIVES`.
909
+ * The name's numeric part is the last archived seq, so ordering is NUMERIC —
910
+ * lexicographic would rank `events-10` before `events-2`. Only strictly
911
+ * numeric names participate (rc.72 G-2: user files are never deleted).
912
+ * Best-effort per removal; exported for the retention test.
913
+ */
914
+ async function retainEventArchives(io, path) {
915
+ const dir = dirname(path);
916
+ const names = await listEventArchives(io, path);
917
+ const excess = names.slice(0, Math.max(0, names.length - 10));
918
+ for (const name of excess) await io.remove(join(dir, name)).catch(() => {});
919
+ }
920
+ /** Read the event log; a missing/whitespace-only file reads as empty,
921
+ * corrupt content is flagged (and refused on append). */
922
+ async function readEvolutionEvents(io, path) {
923
+ let raw;
924
+ try {
925
+ raw = await io.readText(path);
926
+ } catch {
927
+ return {
928
+ events: [],
929
+ malformed: true
930
+ };
931
+ }
932
+ if (raw === null || raw.trim() === "") return {
933
+ events: [],
934
+ malformed: false
935
+ };
936
+ try {
937
+ const parsed = JSON.parse(raw);
938
+ if (!Array.isArray(parsed.events)) return {
939
+ events: [],
940
+ malformed: false
941
+ };
942
+ return {
943
+ events: parsed.events.filter(isEventRecord),
944
+ malformed: false
945
+ };
946
+ } catch {
947
+ return {
948
+ events: [],
949
+ malformed: true
950
+ };
951
+ }
952
+ }
953
+ /**
954
+ * Read the full timeline (rc.71): active log + all archives, merged by seq
955
+ * (active copy wins, duplicates only arise from the rotation crash window),
956
+ * sorted ascending. Per-file malformed flag as in `readEvolutionEvents`; a
957
+ * malformed (or unreadable) ARCHIVE is skipped — it never bricks the boot and
958
+ * it is still flagged.
959
+ */
960
+ async function readEvolutionTimeline(io, path) {
961
+ const dir = dirname(path);
962
+ let malformed = false;
963
+ const bySeq = /* @__PURE__ */ new Map();
964
+ for (const name of await listEventArchives(io, path)) {
965
+ const read = await readEvolutionEvents(io, join(dir, name));
966
+ if (read.malformed) malformed = true;
967
+ for (const event of read.events) bySeq.set(event.seq, event);
968
+ }
969
+ const active = await readEvolutionEvents(io, path);
970
+ if (active.malformed) malformed = true;
971
+ for (const event of active.events) bySeq.set(event.seq, event);
972
+ return {
973
+ events: [...bySeq.values()].sort((a, b) => a.seq - b.seq),
974
+ malformed
975
+ };
976
+ }
977
+ //#endregion
978
+ //#region lib/types/prompts.js
979
+ /**
980
+ * Review and curation prompts adapted from Hermes Agent
981
+ * `agent/background_review.py`, `agent/curator.py`, and
982
+ * `agent/learn_prompt.py`, with tool names translated to the DSH-native
983
+ * catalog (`memory`, `skill_manage`, `skill`, `bash`, `str_replace_editor`).
984
+ *
985
+ * Alignment policy (2026-08-29): the OPERATIONAL steps and instructions the
986
+ * model follows mirror the Hermes originals structurally (signal list,
987
+ * preference order, support-file taxonomy, curator package integrity,
988
+ * consolidated/pruned reporting block). Tool and platform differences are
989
+ * DSH-adapted (native tool names, pinned-within-review semantics, this
990
+ * platform's index cap), and DSH-only additions are marked as such.
991
+ *
992
+ * Every prompt is pinned in a versioned bundle. Review workers verify the
993
+ * bundle digest before spending a model call, so a partially-patched
994
+ * deployment fails closed instead of silently running a truncated prompt.
995
+ */
996
+ /**
997
+ * Prompt bundle identity. Bump both id and version whenever a prompt's text
998
+ * changes semantically: the bundle digest is the fail-closed signal for
999
+ * review workers, so a stale id across deployments must be distinguishable.
1000
+ */
1001
+ const PROMPT_BUNDLE_ID = "dsh-evolution@9";
1002
+ const PROMPT_BUNDLE_VERSION = 9;
1003
+ const MEMORY_REVIEW_PROMPT = `[Auto-review — Memory]
1004
+ Review the conversation above and consider saving to memory if appropriate.
1005
+
1006
+ Focus on:
1007
+ 1. Has the user revealed things about themselves — persona, desires, preferences, or personal details worth remembering?
1008
+ 2. Has the user expressed expectations about how you should behave, their work style, or ways they want you to operate?
1009
+
1010
+ If something stands out, save it using the memory tool.
1011
+ If nothing is worth saving, just say "Nothing to save." and stop.`;
1012
+ const SKILL_REVIEW_PROMPT = `[Auto-review — Skills]
1013
+ 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.
1014
+
1015
+ 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.
1016
+
1017
+ Signals to look for (any one of these warrants action):
1018
+ • 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.
1019
+ • 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.
1020
+ • Non-trivial technique, fix, workaround, debugging path, or tool-usage pattern emerged that a future session would benefit from. Capture it.
1021
+ • A skill that got loaded or consulted this session turned out to be wrong, missing a step, or outdated. Patch it NOW.
1022
+
1023
+ Read-before-write (enforced by this channel): update, patch, delete, or write support files ONLY into skills you loaded or read in THIS session — ops on unread skills are dropped; CREATE of a brand-new umbrella is the only exception.
1024
+
1025
+ Preference order — prefer the earliest action that fits, but do pick one when a signal above fired:
1026
+ 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.
1027
+ 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.
1028
+ 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:
1029
+ • 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.
1030
+ • templates/<name>.<ext> — starter files meant to be copied and modified (boilerplate configs, scaffolding, a known-good example the agent can reproduce with modifications).
1031
+ • 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).
1032
+ 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.
1033
+ 4. RESTRUCTURE a loaded skill whose body grew log-like — rc/sha/date-dense sections, session-detail spirals, or a fat body with no support files. Use skill_manage action=restructure with restructure: [{"heading": "<the exact ## heading text>", "to_file": "references/<topic>.md"}] — the ENTIRE ## section (from that heading to the next heading) moves into the support file and its position becomes a pointer line. The skill's name and directory never change. Only propose headings that exist verbatim in the body; never invent one, and never restructure a healthy small skill.
1034
+ 5. 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).
1035
+
1036
+ 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.
1037
+
1038
+ If you notice two existing skills that overlap, note it in your reply — the background curator handles consolidation at scale.
1039
+
1040
+ Two-tier deposition discipline (DSH addition, same spirit as the umbrella rule): before writing, classify the knowledge:
1041
+ • PATTERN (reusable — symptom → mechanism → fix → verification, still valuable next session) belongs in the SKILL.md body.
1042
+ • 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.
1043
+
1044
+ Protected skills (DO NOT edit these):
1045
+ • Bundled skills (shipped with the platform).
1046
+ • Hub-installed skills (installed from a hub).
1047
+ 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.
1048
+ If the only skills that need updating are protected, say 'Nothing to save.' and stop.
1049
+
1050
+ Do NOT capture (these become persistent self-imposed constraints that bite you later when the environment changes):
1051
+ • 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.
1052
+ • 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.
1053
+ • Session-specific transient errors that resolved before the conversation ended. If retrying worked, the lesson is the retry pattern, not the original failure.
1054
+ • 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.
1055
+
1056
+ 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.
1057
+
1058
+ '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.`;
1059
+ const COMBINED_REVIEW_PROMPT = `[Auto-review]
1060
+ Review the conversation above and update two things:
1061
+
1062
+ **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.
1063
+
1064
+ **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.
1065
+
1066
+ 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.
1067
+
1068
+ Signals that warrant a skill update (any one is enough):
1069
+ • 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.
1070
+ • Non-trivial technique, fix, workaround, or debugging path emerged.
1071
+ • A skill that was loaded or consulted turned out wrong, missing, or outdated — patch it now.
1072
+
1073
+ Read-before-write (enforced by this channel): update, patch, delete, or write support files ONLY into skills you loaded or read in THIS session — ops on unread skills are dropped; CREATE of a brand-new umbrella is the only exception.
1074
+
1075
+ Preference order for skills — pick the earliest that fits:
1076
+ 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.
1077
+ 2. UPDATE AN EXISTING UMBRELLA. Patch it.
1078
+ 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.
1079
+ 4. RESTRUCTURE a loaded skill whose body grew log-like (rc/sha/date-dense sections, session-detail spirals, fat body with no support files) via skill_manage action=restructure with restructure: [{"heading": "<the exact ## heading text>", "to_file": "references/<topic>.md"}] — the ENTIRE ## section moves into the support file and its position becomes a pointer line; the skill's name and directory never change. Only propose headings that exist verbatim in the body.
1080
+ 5. 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).
1081
+
1082
+ 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.
1083
+
1084
+ 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.
1085
+
1086
+ If you notice overlapping existing skills, mention it — the background curator handles consolidation.
1087
+
1088
+ Protected skills (DO NOT edit these):
1089
+ • Bundled skills (shipped with the platform).
1090
+ • Hub-installed skills (installed from a hub).
1091
+ 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.
1092
+ If the only skills that need updating are protected, say 'Nothing to save.' and stop.
1093
+
1094
+ Do NOT capture as skills (these become persistent self-imposed constraints that bite you later when the environment changes):
1095
+ • 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.
1096
+ • 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.
1097
+ • Session-specific transient errors that resolved before the conversation ended. If retrying worked, the lesson is the retry pattern, not the original failure.
1098
+ • 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.
1099
+
1100
+ 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.
1101
+
1102
+ 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.`;
1103
+ const CURATOR_PROMPT = `You are the skill curator. Maintain a healthy, class-level skill library, not a flat pile of narrow one-session skills.
1104
+
1105
+ This is an UMBRELLA-BUILDING consolidation pass, not a passive audit and not a duplicate-finder.
1106
+
1107
+ 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.
1108
+
1109
+ Right target shape: class-level skills with rich SKILL.md + references/, templates/, scripts/ support files for session-specific detail.
1110
+
1111
+ Hard rules:
1112
+ 1. NEVER hard-delete a skill. Archive (moving to .archive/) is the maximum destructive action; archives are recoverable, deletion is not.
1113
+ 2. Do not touch bundled, hub-installed, pinned, or scheduled-task-referenced (referenced) skills. Referenced skills are fully protected — never consolidated, never pruned (there is no scheduled-task reference-rewriting pass; a referenced skill stays in place by design).
1114
+ 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.
1115
+ 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.
1116
+ 5. Judge overlap on CONTENT, not on usage counters.
1117
+ 6. Before archiving a merged skill, ensure its unique content was preserved in the umbrella.
1118
+
1119
+ How to work:
1120
+ 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.
1121
+ 2. For each cluster with 2+ members, ask "what is the UMBRELLA CLASS these skills serve?" and consolidate:
1122
+ a. MERGE INTO AN EXISTING UMBRELLA (patch a labeled section for each sibling's unique insight, then archive the siblings).
1123
+ b. CREATE A NEW UMBRELLA SKILL.md covering the shared workflow with short labeled subsections, then archive the absorbed siblings.
1124
+ c. DEMOTE session-specific detail to references/, templates/, or scripts/ under the umbrella. Use the right directory per kind:
1125
+ • 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.
1126
+ • templates/<name>.<ext> — starter files meant to be copied and modified.
1127
+ • scripts/<name>.<ext> — statically re-runnable actions (verification scripts, fixture generators, probes).
1128
+ 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.
1129
+ 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.
1130
+ 5. Iterate. After one consolidation round, scan the remaining set and look for the NEXT umbrella opportunity. Don't stop after 3 merges.
1131
+
1132
+ You are a NOMINATOR, not an executor: this channel has NO tools. Your single deliverable is the structured YAML block below. Never narrate actions you did not take ("merged", "patched", "archived") — you are proposing, and the deterministic engine executes only names from the candidate pool it gave you. (A future execution view would expose skill_manage; today it does not.)
1133
+
1134
+ '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.
1135
+
1136
+ 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.
1137
+
1138
+ Keep the umbrella body tight and scannable: exact commands, verbatim paths, ~100-200 lines; never invent flags or APIs.
1139
+
1140
+ When done, write a human summary THEN the structured machine-readable block. The block is the contract: every skill you would move to .archive/ MUST appear in exactly one of the two lists. Return ONLY the YAML block after the summary — no post-block prose. Format EXACTLY:
1141
+
1142
+ ## Structured summary (required)
1143
+ \`\`\`yaml
1144
+ consolidations:
1145
+ - from: <old-skill-name>
1146
+ mode: reference # optional — ONLY for a 'demote': source is narrow-but-valuable session detail, write it as references/<source>.md under the umbrella instead of appending to the body. Default is append. Place this line BEFORE into:. NEVER use reference when the source body links its own references/ templates/ scripts/ files.
1147
+ into: <umbrella-skill-name>
1148
+ reason: <one short sentence — why merged, not just 'similar'>
1149
+ prunings:
1150
+ - name: <skill-name>
1151
+ reason: <one short sentence — why archived with no merge target>
1152
+ \`\`\`
1153
+
1154
+ Every skill you would move to .archive/ MUST appear in exactly one of the two lists. If you consolidated X into umbrella Y (patched Y, wrote a references file to Y, or created Y with X's content absorbed), X goes under consolidations with into: Y. If you archived X with no absorption — truly stale, irrelevant, or obsolete — X goes under prunings. Leave a list empty (consolidations: []) if none. Do not omit the block. The block comes AFTER your human-readable summary of clusters processed, patches made, and decisions left alone.`;
1155
+ const CURATOR_DRY_RUN_BANNER = `═══════════════════════════════════════════════════════════════
1156
+ DRY-RUN — REPORT ONLY. DO NOT MUTATE THE SKILL LIBRARY.
1157
+ ═══════════════════════════════════════════════════════════════
1158
+
1159
+ This is a PREVIEW pass. Follow every instruction above EXCEPT:
1160
+ • Do NOT call skill_manage with action=create, update, patch, delete, write_file, or remove_file.
1161
+ • Do NOT move, copy, or rewrite any file under the skills tree.
1162
+
1163
+ 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.
1164
+
1165
+ If you accidentally take a mutating action, say so explicitly in the summary.`;
1166
+ const COMPLETION_SKILL_REVIEW_PROMPT = `[Auto-review — Skills · task complete]
1167
+ Your current task now appears complete. Before wrapping up, review the approach and update the skill library via skill_manage.
1168
+
1169
+ 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.
1170
+
1171
+ Do NOT modify output files or re-run the task. If you are still mid-task, ignore this.`;
1172
+ /**
1173
+ * System-prompt guidance section (Hermes `SKILLS_GUIDANCE`, DSH-adapted).
1174
+ * Registered as a system-prompt section by tool-skill-manage (it mounts
1175
+ * exactly when `skill_manage` is available — the DSH analogue of Hermes'
1176
+ * `if "skill_manage" in agent.valid_tool_names` condition). Instructs the
1177
+ * model to save/repair skills on its own initiative.
1178
+ */
1179
+ const SKILLS_GUIDANCE = `Skills guidance:
1180
+ • 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.
1181
+ • 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.`;
1182
+ const PLAN_CHANNEL_NOTE = `
1183
+
1184
+ CHANNEL (subagent): this review channel mounts only the read-only \`skill\` tool — you have NO \`skill_manage\`, NO \`memory\`. Your deliverable is the structured JSON plan below (outputSchema). Describe the patches/creates you RECOMMEND in the plan; never narrate actions you took.`;
1185
+ /** Subagent-channel variant: same review policy, channel-limited deliverable (M-2). */
1186
+ const SKILL_REVIEW_PLAN_PROMPT = `${SKILL_REVIEW_PROMPT}${PLAN_CHANNEL_NOTE}`;
1187
+ /** Subagent-channel variant of the combined review (M-2). */
1188
+ const COMBINED_REVIEW_PLAN_PROMPT = `${COMBINED_REVIEW_PROMPT}${PLAN_CHANNEL_NOTE}`;
1189
+ function reviewPrompt(kind, channel = "agent") {
1190
+ if (kind === "memory") return MEMORY_REVIEW_PROMPT;
1191
+ if (channel === "plan") return kind === "skill" ? SKILL_REVIEW_PLAN_PROMPT : COMBINED_REVIEW_PLAN_PROMPT;
1192
+ if (kind === "skill") return SKILL_REVIEW_PROMPT;
1193
+ return COMBINED_REVIEW_PROMPT;
1194
+ }
1195
+ function sha256(text) {
1196
+ return createHash("sha256").update(text).digest("hex");
1197
+ }
1198
+ function createPromptBundle(prompts) {
1199
+ const canonical = JSON.stringify({
1200
+ id: PROMPT_BUNDLE_ID,
1201
+ version: 9,
1202
+ prompts: Object.fromEntries(Object.entries(prompts).sort())
1203
+ });
1204
+ return Object.freeze({
1205
+ id: PROMPT_BUNDLE_ID,
1206
+ version: 9,
1207
+ prompts: Object.freeze({ ...prompts }),
1208
+ sha256: sha256(canonical)
1209
+ });
1210
+ }
1211
+ const PROMPT_BUNDLE = createPromptBundle({
1212
+ memory: MEMORY_REVIEW_PROMPT,
1213
+ skill: SKILL_REVIEW_PROMPT,
1214
+ combined: COMBINED_REVIEW_PROMPT,
1215
+ skillPlan: SKILL_REVIEW_PLAN_PROMPT,
1216
+ combinedPlan: COMBINED_REVIEW_PLAN_PROMPT,
1217
+ curator: CURATOR_PROMPT,
1218
+ completion: COMPLETION_SKILL_REVIEW_PROMPT,
1219
+ skillsGuidance: SKILLS_GUIDANCE
1220
+ });
1221
+ function verifyPromptBundle(bundle = PROMPT_BUNDLE) {
1222
+ if (bundle.id !== "dsh-evolution@9" || bundle.version !== 9) return false;
1223
+ const canonical = JSON.stringify({
1224
+ id: PROMPT_BUNDLE_ID,
1225
+ version: 9,
1226
+ prompts: Object.fromEntries(Object.entries(bundle.prompts).sort())
1227
+ });
1228
+ return bundle.sha256 === sha256(canonical);
1229
+ }
1230
+ const DSH_AUTHORING_STANDARDS = `Follow the Hermes skill-authoring standards, translated to DSH tools.
1231
+
1232
+ Frontmatter:
1233
+ - name: lowercase-hyphenated, <=64 chars, no spaces.
1234
+ - 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.
1235
+ - version: 0.1.0
1236
+ - 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.
1237
+ - 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.
1238
+ - metadata.hermes.tags: a few Capitalized, Relevant, Tags.
1239
+ - metadata.hermes.related_skills: [a, b] — name sibling skills this one builds on or is referenced by (optional; feeds the quality references factor).
1240
+
1241
+ Body section order (omit only when empty):
1242
+ 1. "# <Human Title>" then a 2-3 sentence intro: what it does, what it does NOT do, key dependency stance.
1243
+ 2. "## When to Use" — concrete trigger phrases.
1244
+ 3. "## Prerequisites" — exact env vars, install steps, credentials.
1245
+ 4. "## How to Run" — canonical invocation framed through DSH tools.
1246
+ 5. "## Quick Reference" — flat command/endpoint list.
1247
+ 6. "## Procedure" — numbered steps with copy-paste-exact commands.
1248
+ 7. "## Pitfalls" — known limits and rate limits.
1249
+ 8. "## Verification" — one check proving the skill worked.
1250
+
1251
+ DSH-tool framing:
1252
+ - Reference DSH tools by name in backticks: \`bash\`, \`str_replace_editor\`, \`write\`, \`skill\`, \`skill_manage\`, \`memory\`.
1253
+ - Do not name wrapped shell utilities when a DSH tool already covers them.
1254
+ - Larger scripts belong under \`scripts/\` (written with \`skill_manage write_file\`) and are referenced from SKILL.md by relative path.
1255
+
1256
+ Quality bar:
1257
+ - Prefer verbatim flags, paths, and APIs from the source. Never invent them.
1258
+ - Keep it tight: ~100 lines simple, ~200 complex.
1259
+ - No router/index/hub skills that only point at other skills.
1260
+ - References go in \`references/\`, templates in \`templates/\`.
1261
+
1262
+ Learn workflow (when the user asks you to learn a reusable skill, or you decide to turn a source/request into one):
1263
+ 1. Gather every source named (files, URLs, "what we just did", pasted notes) with the tools you already have — and treat prose after a source as authoring requirements, not noise.
1264
+ 2. Apply every requirement and constraint from the request to the SKILL.md you author.
1265
+ 3. Author exactly ONE SKILL.md and save it with \`skill_manage\` (action=create); non-trivial scripts go under \`scripts/\`.
1266
+ 4. When done, tell the user the skill name, its category, and a one-line summary of what it captured.`;
1267
+ //#endregion
1268
+ //#region lib/types/learn-prompt.js
1269
+ /**
1270
+ * Open-ended `/evolution learn` prompt builder.
1271
+ *
1272
+ * `learn` is open-ended: the user can name anything they can describe — a
1273
+ * directory of code, an API doc URL, a workflow they just walked the agent
1274
+ * through, or pasted notes. The prompt instructs the live agent to gather the
1275
+ * named sources with its existing tools, then author a single SKILL.md via
1276
+ * `skill_manage` following `DSH_AUTHORING_STANDARDS`. There is no separate
1277
+ * distillation engine and no model-tool footprint.
1278
+ */
1279
+ /**
1280
+ * Build the agent prompt for an open-ended `/evolution learn` request.
1281
+ *
1282
+ * @param userRequest free-text the user gave after `/evolution learn`; an
1283
+ * empty string falls back to "the workflow we just went through".
1284
+ * @returns a complete instruction the agent runs as a normal turn.
1285
+ */
1286
+ function buildLearnPrompt(userRequest) {
1287
+ return [
1288
+ "[/learn] The user wants you to learn a reusable skill from the request below, and save it.",
1289
+ "",
1290
+ "THE REQUEST:",
1291
+ userRequest.trim() || "the workflow we just went through in this conversation — review the steps taken and distill them into a reusable skill",
1292
+ "",
1293
+ "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.",
1294
+ "",
1295
+ "Do this:",
1296
+ "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.",
1297
+ "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.",
1298
+ "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.",
1299
+ "",
1300
+ DSH_AUTHORING_STANDARDS,
1301
+ "",
1302
+ "When done, tell the user the skill name, its category, and a one-line summary of what it captured."
1303
+ ].join("\n");
1304
+ }
1305
+ //#endregion
241
1306
  //#region lib/types/threats.js
242
1307
  /**
243
1308
  * Threat scanning for agent-authored memory and skill content.
@@ -413,10 +1478,12 @@ const SCOPE_ORDER = {
413
1478
  context: 2,
414
1479
  strict: 3
415
1480
  };
1481
+ const NO_SCAN_OPTIONS = {};
416
1482
  /**
417
1483
  * Scan text at `scope`. Patterns are cumulative: `strict` includes all scopes.
1484
+ * `options.excludeLabels` removes matching patterns without changing `scope`.
418
1485
  */
419
- function scanThreats(text, scope = "strict", maxScanChars = 65536) {
1486
+ function scanThreats(text, scope = "strict", maxScanChars = 65536, options = NO_SCAN_OPTIONS) {
420
1487
  const findings = [];
421
1488
  if (ZERO_WIDTH_CHARS.test(text)) findings.push({
422
1489
  label: "unicode_zero_width",
@@ -429,8 +1496,10 @@ function scanThreats(text, scope = "strict", maxScanChars = 65536) {
429
1496
  scope
430
1497
  });
431
1498
  const normalized = text.normalize("NFKC").slice(0, maxScanChars);
1499
+ const excluded = new Set(options.excludeLabels ?? []);
432
1500
  for (const pattern of PATTERNS) {
433
1501
  if (SCOPE_ORDER[pattern.scope] > SCOPE_ORDER[scope]) continue;
1502
+ if (excluded.has(pattern.label)) continue;
434
1503
  if (pattern.regex.test(normalized)) findings.push({
435
1504
  label: pattern.label,
436
1505
  category: pattern.category,
@@ -440,24 +1509,24 @@ function scanThreats(text, scope = "strict", maxScanChars = 65536) {
440
1509
  return findings;
441
1510
  }
442
1511
  /** Blocking policy: any hit blocks. `severity` is deliberately not a gate. */
443
- function evaluateThreat(text, scope = "strict", maxScanChars = 65536) {
444
- const findings = scanThreats(text, scope, maxScanChars);
1512
+ function evaluateThreat(text, scope = "strict", maxScanChars = 65536, options = NO_SCAN_OPTIONS) {
1513
+ const findings = scanThreats(text, scope, maxScanChars, options);
445
1514
  return {
446
1515
  blocked: findings.length > 0,
447
1516
  findings
448
1517
  };
449
1518
  }
450
1519
  /** User-facing block message for memory writes. */
451
- function scanMemoryThreats(text, maxScanChars = 65536) {
452
- const { blocked, findings } = evaluateThreat(text, "strict", maxScanChars);
1520
+ function scanMemoryThreats(text, maxScanChars = 65536, options = NO_SCAN_OPTIONS) {
1521
+ const { blocked, findings } = evaluateThreat(text, "strict", maxScanChars, options);
453
1522
  if (!blocked) return null;
454
1523
  const pattern = findings.find((f) => f.category !== "unicode_obfuscation");
455
1524
  if (pattern) return `Blocked by security scan (${pattern.label}). Rephrase without instruction-like language.`;
456
1525
  return "Blocked by security scan: invisible or potentially malicious Unicode detected.";
457
1526
  }
458
1527
  /** User-facing block message for skill content writes. */
459
- function scanContentThreats(text, maxScanChars = 65536) {
460
- const { blocked, findings } = evaluateThreat(text, "strict", maxScanChars);
1528
+ function scanContentThreats(text, maxScanChars = 65536, options = NO_SCAN_OPTIONS) {
1529
+ const { blocked, findings } = evaluateThreat(text, "strict", maxScanChars, options);
461
1530
  if (!blocked) return null;
462
1531
  return `Blocked by security scan (${findings[0]?.label ?? "unknown"}). This content appears to contain potentially malicious instructions.`;
463
1532
  }
@@ -467,7 +1536,39 @@ function scanContentThreats(text, maxScanChars = 65536) {
467
1536
  * File-backed durable memory with Hermes-compatible semantics.
468
1537
  * Stores are MEMORY.md and USER.md under $DSH_HOME/memories (~/.dsh/memories).
469
1538
  */
470
- const ENTRY_DELIMITER = "\n§\n";
1539
+ /**
1540
+ * Read-guard factor: a memory file larger than this multiple of its target's
1541
+ * char limit is treated as externally corrupted and skipped instead of being
1542
+ * read whole (aligned with claw `tools/memory.ts` size guard, which uses the
1543
+ * same 10× bound around a file that should never exceed the store limit).
1544
+ */
1545
+ const READ_GUARD_FACTOR = 10;
1546
+ /**
1547
+ * Consolidation-failure backoff window (package-private, rc.42 audit P2-1):
1548
+ * only failures inside the window count toward `maxConsolidationFailures`.
1549
+ * The store cannot observe turn boundaries, so the model-facing "this turn"
1550
+ * phrasing is approximated with ten minutes — generous enough to cover one
1551
+ * turn's retry loop, short enough that a failure yesterday never makes today's
1552
+ * first refusal say "stop retrying".
1553
+ */
1554
+ const FAILURE_WINDOW_MS = 10 * 6e4;
1555
+ /**
1556
+ * Recoverable-error preview bounds (B-line G5, Hermes `_previews` parity):
1557
+ * failed replace/remove/batch calls echo the current entries so the model can
1558
+ * self-recover without re-reading the store. Bounded to five entries of eighty
1559
+ * characters each; package-private because it is an error-message shape, not a
1560
+ * behavior switch.
1561
+ */
1562
+ const ERROR_PREVIEW_ENTRIES = 5;
1563
+ const ERROR_PREVIEW_WIDTH = 80;
1564
+ function previewEntries(entries) {
1565
+ if (entries.length === 0) return "";
1566
+ const shown = entries.slice(0, ERROR_PREVIEW_ENTRIES).map((entry) => {
1567
+ return `- ${entry.length > ERROR_PREVIEW_WIDTH ? `${entry.slice(0, ERROR_PREVIEW_WIDTH)}…` : entry}`;
1568
+ });
1569
+ const more = entries.length > ERROR_PREVIEW_ENTRIES ? `\n (+${entries.length - ERROR_PREVIEW_ENTRIES} more)` : "";
1570
+ return `\n\nCurrent entries (preview):\n${shown.join("\n")}${more}`;
1571
+ }
471
1572
  function memoryRoot(env = process.env) {
472
1573
  return join(env.DSH_HOME ?? join(homedir(), ".dsh"), "memories");
473
1574
  }
@@ -491,6 +1592,7 @@ var MemoryStore = class {
491
1592
  maxFailures;
492
1593
  io;
493
1594
  failureCount = 0;
1595
+ lastFailureAt = 0;
494
1596
  constructor(options = {}) {
495
1597
  this.io = options.io ?? nodeEvolutionIo();
496
1598
  this.memoryLimit = options.memoryCharLimit ?? 2200;
@@ -502,7 +1604,24 @@ var MemoryStore = class {
502
1604
  limitFor(target) {
503
1605
  return target === "memory" ? this.memoryLimit : this.userLimit;
504
1606
  }
1607
+ /**
1608
+ * Read-guard probe: `{ size, limit }` when the on-disk file exceeds
1609
+ * `limit * READ_GUARD_FACTOR` bytes, `null` when it is absent, unknown
1610
+ * (backend without a size probe), under the bound, or the target has no
1611
+ * limit configured.
1612
+ */
1613
+ async oversizedFile(target) {
1614
+ const size = await this.io.size?.(fileFor(this.root, target));
1615
+ if (size === null || size === void 0) return null;
1616
+ const limit = this.limitFor(target);
1617
+ if (limit <= 0) return null;
1618
+ return size > limit * READ_GUARD_FACTOR ? {
1619
+ size,
1620
+ limit
1621
+ } : null;
1622
+ }
505
1623
  async read(target) {
1624
+ if (await this.oversizedFile(target)) return [];
506
1625
  const raw = await this.io.readText(fileFor(this.root, target));
507
1626
  return raw === null ? [] : [...new Set(normalizeEntries(raw))];
508
1627
  }
@@ -513,133 +1632,168 @@ var MemoryStore = class {
513
1632
  this.failureCount = 0;
514
1633
  }
515
1634
  failure(target, message, entries) {
1635
+ if (Date.now() - this.lastFailureAt > FAILURE_WINDOW_MS) this.failureCount = 0;
1636
+ this.lastFailureAt = Date.now();
516
1637
  this.failureCount += 1;
517
1638
  const chars = entries.join(ENTRY_DELIMITER).length;
518
1639
  if (this.failureCount > this.maxFailures) return {
519
1640
  ok: false,
520
- message: `Memory consolidation failed ${this.failureCount} times this turn. Stop retrying memory calls and continue with the user's task.`,
1641
+ message: `Memory consolidation failed ${this.failureCount} times this turn. Stop retrying memory calls and continue with the user's task.${previewEntries(entries)}`,
521
1642
  entries,
522
1643
  chars,
523
1644
  limit: this.limitFor(target)
524
1645
  };
525
1646
  return {
526
1647
  ok: false,
527
- message,
1648
+ message: `${message}${previewEntries(entries)}`,
528
1649
  entries,
529
1650
  chars,
530
1651
  limit: this.limitFor(target)
531
1652
  };
532
1653
  }
533
- async add(target, facts) {
534
- const content = facts.trim();
535
- if (!content) return {
1654
+ /**
1655
+ * StorageHint percentage must clamp at 100 like the render header: a drifted
1656
+ * entry can push chars past the limit, and "Storage at 125%" contradicts the
1657
+ * clamped usage indicator.
1658
+ */
1659
+ storageHint(target, chars) {
1660
+ const limit = this.limitFor(target);
1661
+ if (limit <= 0) return "";
1662
+ const percent = Math.min(100, Math.floor(chars * 100 / limit));
1663
+ return percent >= 80 ? ` ⚠️ Storage at ${percent}% (${chars}/${limit} chars).` : "";
1664
+ }
1665
+ /**
1666
+ * Best-effort raw-copy backup of the on-disk file to `<file>.bak.<stamp>`
1667
+ * before a refusal, so an externally modified (or oversized) file stays
1668
+ * recoverable. Copies bytes instead of reading them so a pathologically
1669
+ * large file is never loaded just to back it up. Failure to back up does
1670
+ * not change the refusal semantics.
1671
+ */
1672
+ async backupFile(target) {
1673
+ const path = fileFor(this.root, target);
1674
+ const unique = `${(/* @__PURE__ */ new Date()).toISOString().replace(/[-:T]/g, "").slice(0, 14)}-${Math.random().toString(36).slice(2, 8)}`;
1675
+ try {
1676
+ await this.io.copy(path, `${path}.bak.${unique}`);
1677
+ return `${path}.bak.${unique}`;
1678
+ } catch {
1679
+ return null;
1680
+ }
1681
+ }
1682
+ /**
1683
+ * Read-guard refusal for write paths. Returns the refusal result when the
1684
+ * target file is oversized, `null` otherwise. The file is skipped for
1685
+ * reading (never loaded), backed up by raw copy, and the model is told to
1686
+ * fix it manually — mirroring the drift refusal so corrupted state is never
1687
+ * silently overwritten.
1688
+ */
1689
+ async oversizedRefusal(target) {
1690
+ const oversized = await this.oversizedFile(target);
1691
+ if (!oversized) return null;
1692
+ const backup = await this.backupFile(target);
1693
+ const suffix = backup ? ` A backup was saved to ${basename(backup)}.` : "";
1694
+ return {
536
1695
  ok: false,
537
- message: "Content cannot be empty.",
1696
+ message: `Memory file is ${oversized.size} bytes (limit ${oversized.limit * READ_GUARD_FACTOR}) — skipping read.${suffix} Fix the file manually, then retry.`,
538
1697
  entries: [],
539
1698
  chars: 0,
540
1699
  limit: this.limitFor(target)
541
1700
  };
542
- const threat = scanMemoryThreats(content);
543
- if (threat) return {
1701
+ }
1702
+ async add(target, facts) {
1703
+ if (!facts.trim()) return {
544
1704
  ok: false,
545
- message: threat,
1705
+ message: "Content cannot be empty.",
546
1706
  entries: [],
547
1707
  chars: 0,
548
1708
  limit: this.limitFor(target)
549
1709
  };
550
- const entries = await this.read(target);
551
- if (entries.some((entry) => stripDatePrefix(entry) === content)) {
552
- this.resetFailures();
1710
+ const path = fileFor(this.root, target);
1711
+ const refusal = await this.oversizedRefusal(target);
1712
+ if (refusal) return refusal;
1713
+ let outcome;
1714
+ await transactIo(this.io, path, async (current) => {
1715
+ const core = await this.addCore(target, facts, current ?? "");
1716
+ outcome = core.result;
1717
+ return core.write ?? current ?? null;
1718
+ });
1719
+ return outcome;
1720
+ }
1721
+ /**
1722
+ * Single-entry add inside the transaction: shared checks (oversized,
1723
+ * drift, threat) and the content computation. `raw` is the locked view
1724
+ * (`current`) — never a second IO read. `write: null` means "no change".
1725
+ */
1726
+ async addCore(target, facts, raw) {
1727
+ const content = facts.trim();
1728
+ if (!content) return {
1729
+ result: this.failure(target, "Content cannot be empty.", []),
1730
+ write: null
1731
+ };
1732
+ if (this.driftFromRaw(target, raw)) {
1733
+ const backup = await this.backupFile(target);
553
1734
  return {
554
- ok: true,
555
- message: "Entry already exists (no duplicate added).",
556
- entries,
557
- chars: entries.join(ENTRY_DELIMITER).length,
558
- limit: this.limitFor(target)
1735
+ result: {
1736
+ ok: false,
1737
+ message: `External drift detected in memory file.${backup ? ` A backup was saved to ${basename(backup)}.` : ""} Resolve the drift before retrying.`,
1738
+ entries: [],
1739
+ chars: 0,
1740
+ limit: this.limitFor(target)
1741
+ },
1742
+ write: null
559
1743
  };
560
1744
  }
561
- const next = [...entries, this.addDatePrefix ? `## ${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}\n${content}` : content];
562
- const total = next.join(ENTRY_DELIMITER).length;
563
- 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);
564
- await this.write(target, next);
565
- this.resetFailures();
566
- return {
567
- ok: true,
568
- message: "Entry added.",
569
- entries: next,
570
- chars: total,
571
- limit: this.limitFor(target)
572
- };
573
- }
574
- async replace(target, oldText, facts) {
575
- return this.mutate(target, oldText, "replace", facts);
576
- }
577
- async remove(target, oldText) {
578
- return this.mutate(target, oldText, "remove", void 0);
579
- }
580
- async mutate(target, oldText, action, facts) {
581
- const needle = oldText.trim();
582
- if (!needle) return {
583
- ok: false,
584
- message: "old_text cannot be empty.",
585
- entries: [],
586
- chars: 0,
587
- limit: this.limitFor(target)
588
- };
589
- const content = action === "replace" ? (facts ?? "").trim() : "";
590
- if (action === "replace" && !content) return {
591
- ok: false,
592
- message: "facts is required for replace; use remove to delete.",
593
- entries: [],
594
- chars: 0,
595
- limit: this.limitFor(target)
596
- };
597
- if (action === "replace") {
598
- const threat = scanMemoryThreats(content);
599
- if (threat) return {
1745
+ const threat = scanMemoryThreats(content);
1746
+ if (threat) return {
1747
+ result: {
600
1748
  ok: false,
601
1749
  message: threat,
602
1750
  entries: [],
603
1751
  chars: 0,
604
1752
  limit: this.limitFor(target)
605
- };
606
- }
607
- if (await this.detectDrift(target)) return {
608
- ok: false,
609
- message: "External drift detected in memory file. Resolve the drift before retrying.",
610
- entries: [],
611
- chars: 0,
612
- limit: this.limitFor(target)
1753
+ },
1754
+ write: null
613
1755
  };
614
- const entries = await this.read(target);
615
- const matches = entries.map((entry, index) => ({
616
- entry,
617
- index
618
- })).filter(({ entry }) => entry.includes(needle));
619
- if (matches.length === 0) return this.failure(target, `No entry matching "${needle}" found.`, entries);
620
- if (new Set(matches.map((m) => m.entry)).size > 1) return {
621
- ok: false,
622
- message: `Multiple distinct entries matched "${needle}". Be more specific.`,
623
- entries,
624
- chars: entries.join(ENTRY_DELIMITER).length,
625
- limit: this.limitFor(target)
626
- };
627
- const index = matches[0]?.index ?? -1;
628
- const next = [...entries];
629
- if (action === "remove") next.splice(index, 1);
630
- else next[index] = content;
1756
+ const entries = [...new Set(normalizeEntries(raw))];
1757
+ if (entries.some((entry) => stripDatePrefix(entry) === content)) {
1758
+ this.resetFailures();
1759
+ return {
1760
+ result: {
1761
+ ok: true,
1762
+ message: `Entry already exists (no duplicate added).${this.storageHint(target, entries.join(ENTRY_DELIMITER).length)}`,
1763
+ entries,
1764
+ chars: entries.join(ENTRY_DELIMITER).length,
1765
+ limit: this.limitFor(target)
1766
+ },
1767
+ write: null
1768
+ };
1769
+ }
1770
+ const next = [...entries, this.addDatePrefix ? `## ${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}\n${content}` : content];
631
1771
  const total = next.join(ENTRY_DELIMITER).length;
632
- if (total > this.limitFor(target)) return this.failure(target, `Resulting memory would exceed the ${this.limitFor(target)} char limit.`, entries);
633
- await this.write(target, next);
1772
+ const addLimit = this.limitFor(target);
1773
+ if (addLimit > 0 && total > addLimit) return {
1774
+ result: this.failure(target, `Adding this entry would exceed the ${addLimit} char limit. Consolidate or remove stale entries, then retry.`, entries),
1775
+ write: null
1776
+ };
634
1777
  this.resetFailures();
635
1778
  return {
636
- ok: true,
637
- message: `Entry ${action === "remove" ? "removed" : "replaced"}.`,
638
- entries: next,
639
- chars: total,
640
- limit: this.limitFor(target)
1779
+ result: {
1780
+ ok: true,
1781
+ message: `Entry added.${this.storageHint(target, total)}`,
1782
+ entries: next,
1783
+ chars: total,
1784
+ limit: this.limitFor(target)
1785
+ },
1786
+ write: render(next)
641
1787
  };
642
1788
  }
1789
+ /** Canonical-form drift check derived from the locked view (same formula as `detectDrift`, no second read). */
1790
+ driftFromRaw(target, raw) {
1791
+ if (raw.trim() === "") return false;
1792
+ const entries = normalizeEntries(raw);
1793
+ const limit = this.limitFor(target);
1794
+ if (limit > 0 && entries.some((entry) => entry.length > limit)) return true;
1795
+ return render(entries) !== raw;
1796
+ }
643
1797
  async applyBatch(target, operations) {
644
1798
  if (operations.length === 0) return {
645
1799
  ok: false,
@@ -648,261 +1802,457 @@ var MemoryStore = class {
648
1802
  chars: 0,
649
1803
  limit: this.limitFor(target)
650
1804
  };
651
- if (await this.detectDrift(target)) return {
652
- ok: false,
653
- message: "External drift detected in memory file. Resolve the drift before retrying.",
654
- entries: [],
655
- chars: 0,
656
- limit: this.limitFor(target)
657
- };
658
- const entries = await this.read(target);
1805
+ const path = fileFor(this.root, target);
1806
+ const refusal = await this.oversizedRefusal(target);
1807
+ if (refusal) return refusal;
1808
+ let outcome;
1809
+ await transactIo(this.io, path, async (current) => {
1810
+ const core = await this.applyBatchCore(target, operations, current ?? "");
1811
+ outcome = core.result;
1812
+ return core.write ?? current ?? null;
1813
+ });
1814
+ return outcome;
1815
+ }
1816
+ /** Batch RMW inside the transaction. `write: null` = failure/no-op, disk untouched. */
1817
+ async applyBatchCore(target, operations, raw) {
1818
+ if (this.driftFromRaw(target, raw)) {
1819
+ const backup = await this.backupFile(target);
1820
+ return {
1821
+ result: {
1822
+ ok: false,
1823
+ message: `External drift detected in memory file.${backup ? ` A backup was saved to ${basename(backup)}.` : ""} Resolve the drift before retrying.`,
1824
+ entries: [],
1825
+ chars: 0,
1826
+ limit: this.limitFor(target)
1827
+ },
1828
+ write: null
1829
+ };
1830
+ }
1831
+ const entries = [...new Set(normalizeEntries(raw))];
659
1832
  const working = [...entries];
660
1833
  for (const [index, op] of operations.entries()) {
661
1834
  const position = index + 1;
662
1835
  if (op.action === "add") {
663
1836
  const body = (op.facts ?? "").trim();
664
1837
  if (!body) return {
665
- ok: false,
666
- message: `Operation ${position} (add): facts is required. No operations were applied.`,
667
- entries,
668
- chars: entries.join(ENTRY_DELIMITER).length,
669
- limit: this.limitFor(target)
1838
+ result: {
1839
+ ok: false,
1840
+ message: `Operation ${position} (add): facts is required. No operations were applied.${previewEntries(entries)}`,
1841
+ entries,
1842
+ chars: entries.join(ENTRY_DELIMITER).length,
1843
+ limit: this.limitFor(target)
1844
+ },
1845
+ write: null
670
1846
  };
671
1847
  const threat = scanMemoryThreats(body);
672
1848
  if (threat) return {
673
- ok: false,
674
- message: `Operation ${position}: ${threat}`,
675
- entries,
676
- chars: entries.join(ENTRY_DELIMITER).length,
677
- limit: this.limitFor(target)
1849
+ result: {
1850
+ ok: false,
1851
+ message: `Operation ${position}: ${threat}`,
1852
+ entries,
1853
+ chars: entries.join(ENTRY_DELIMITER).length,
1854
+ limit: this.limitFor(target)
1855
+ },
1856
+ write: null
678
1857
  };
679
1858
  if (!working.some((entry) => stripDatePrefix(entry) === body)) working.push(this.addDatePrefix ? `## ${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}\n${body}` : body);
680
1859
  continue;
681
1860
  }
682
1861
  const needle = (op.old_text ?? "").trim();
683
1862
  if (!needle) return {
684
- ok: false,
685
- message: `Operation ${position} (${op.action}): old_text is required. No operations were applied.`,
686
- entries,
687
- chars: entries.join(ENTRY_DELIMITER).length,
688
- limit: this.limitFor(target)
1863
+ result: {
1864
+ ok: false,
1865
+ message: `Operation ${position} (${op.action}): old_text is required. No operations were applied.${previewEntries(entries)}`,
1866
+ entries,
1867
+ chars: entries.join(ENTRY_DELIMITER).length,
1868
+ limit: this.limitFor(target)
1869
+ },
1870
+ write: null
689
1871
  };
690
1872
  const matches = working.map((entry, matchIndex) => ({
691
1873
  entry,
692
1874
  matchIndex
693
1875
  })).filter(({ entry }) => entry.includes(needle));
694
- if (matches.length === 0) return this.failure(target, `Operation ${position}: no entry matching "${needle}" found. No operations were applied.`, entries);
1876
+ if (matches.length === 0) return {
1877
+ result: this.failure(target, `Operation ${position}: no entry matching "${needle}" found. No operations were applied.`, entries),
1878
+ write: null
1879
+ };
695
1880
  if (new Set(matches.map((m) => m.entry)).size > 1) return {
696
- ok: false,
697
- message: `Operation ${position}: "${needle}" matched multiple distinct entries. No operations were applied.`,
698
- entries,
699
- chars: entries.join(ENTRY_DELIMITER).length,
700
- limit: this.limitFor(target)
1881
+ result: {
1882
+ ok: false,
1883
+ message: `Operation ${position}: "${needle}" matched multiple distinct entries. No operations were applied.${previewEntries(entries)}`,
1884
+ entries,
1885
+ chars: entries.join(ENTRY_DELIMITER).length,
1886
+ limit: this.limitFor(target)
1887
+ },
1888
+ write: null
701
1889
  };
702
1890
  const matchIndex = matches[0]?.matchIndex ?? -1;
703
1891
  if (op.action === "remove") working.splice(matchIndex, 1);
704
1892
  else {
705
1893
  const body = (op.facts ?? "").trim();
706
1894
  if (!body) return {
707
- ok: false,
708
- message: `Operation ${position} (replace): facts is required.`,
709
- entries,
710
- chars: entries.join(ENTRY_DELIMITER).length,
711
- limit: this.limitFor(target)
1895
+ result: {
1896
+ ok: false,
1897
+ message: `Operation ${position} (replace): facts is required.${previewEntries(entries)}`,
1898
+ entries,
1899
+ chars: entries.join(ENTRY_DELIMITER).length,
1900
+ limit: this.limitFor(target)
1901
+ },
1902
+ write: null
712
1903
  };
713
1904
  const threat = scanMemoryThreats(body);
714
1905
  if (threat) return {
715
- ok: false,
716
- message: `Operation ${position}: ${threat}`,
717
- entries,
718
- chars: entries.join(ENTRY_DELIMITER).length,
719
- limit: this.limitFor(target)
1906
+ result: {
1907
+ ok: false,
1908
+ message: `Operation ${position}: ${threat}`,
1909
+ entries,
1910
+ chars: entries.join(ENTRY_DELIMITER).length,
1911
+ limit: this.limitFor(target)
1912
+ },
1913
+ write: null
720
1914
  };
721
1915
  working[matchIndex] = body;
722
1916
  }
723
1917
  }
724
1918
  const total = working.join(ENTRY_DELIMITER).length;
725
- 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);
726
- await this.write(target, working);
1919
+ const batchLimit = this.limitFor(target);
1920
+ if (batchLimit > 0 && total > batchLimit) return {
1921
+ result: this.failure(target, `Batch result (${total} chars) exceeds the ${batchLimit} limit. Remove or shorten more entries in the same batch.`, entries),
1922
+ write: null
1923
+ };
727
1924
  this.resetFailures();
728
1925
  return {
729
- ok: true,
730
- message: `Applied ${operations.length} operation(s).`,
731
- entries: working,
732
- chars: total,
733
- limit: this.limitFor(target)
1926
+ result: {
1927
+ ok: true,
1928
+ message: `Applied ${operations.length} operation(s).${this.storageHint(target, total)}`,
1929
+ entries: working,
1930
+ chars: total,
1931
+ limit: this.limitFor(target)
1932
+ },
1933
+ write: render(working)
734
1934
  };
735
1935
  }
736
1936
  async renderContext() {
737
1937
  const memory = await this.read("memory");
738
1938
  const user = await this.read("user");
739
1939
  const parts = [];
740
- for (const [target, entries] of [["Memory", memory], ["User Profile", user]]) {
1940
+ for (const [target, label, entries] of [[
1941
+ "memory",
1942
+ "Memory",
1943
+ memory
1944
+ ], [
1945
+ "user",
1946
+ "User Profile",
1947
+ user
1948
+ ]]) {
1949
+ const oversized = entries.length === 0 ? await this.oversizedFile(target) : null;
1950
+ if (oversized) {
1951
+ parts.push(`## ${label} — file skipped: ${oversized.size} bytes (limit ${oversized.limit * READ_GUARD_FACTOR}); not read`);
1952
+ continue;
1953
+ }
741
1954
  const safe = entries.filter((entry) => !scanMemoryThreats(entry));
742
1955
  if (safe.length > 0) {
743
1956
  const body = safe.join(ENTRY_DELIMITER);
1957
+ const limit = this.limitFor(target);
1958
+ const pct = limit > 0 ? Math.min(100, Math.floor(body.length * 100 / limit)) : 0;
744
1959
  const note = safe.length === entries.length ? "" : ` (${entries.length - safe.length} threat-matched entries filtered)`;
745
- parts.push(`## ${target} (${safe.length} entries)${note}\n${body}`);
1960
+ parts.push(`## ${label} (${safe.length} entries) [${pct}% — ${body.length}/${limit} chars]${note}\n${body}`);
746
1961
  }
747
1962
  }
748
1963
  return parts.join("\n\n");
749
1964
  }
750
- async snapshot() {
751
- const [memory, user] = await Promise.all([this.read("memory"), this.read("user")]);
752
- return {
753
- memory,
754
- user
755
- };
756
- }
757
- async restoreSnapshot(snapshot) {
758
- await this.write("memory", snapshot.memory);
759
- await this.write("user", snapshot.user);
760
- }
1965
+ /**
1966
+ * Detect on-disk drift: true when the file is not in the canonical
1967
+ * `render(normalizeEntries(raw))` form. This catches structural anomalies
1968
+ * the writer would quietly normalize away (empty/`§`-only entries, stray
1969
+ * blank lines, leading/trailing delimiters) that indicate the file was
1970
+ * edited outside MemoryStore. Purely single-canonical content reaches the
1971
+ * same serialization and returns false, so a normal write is never flagged.
1972
+ *
1973
+ * An absent, empty, or whitespace-only file is the "never written" state
1974
+ * (rc.42 audit P1-6): it parses to zero entries, so the canonical form
1975
+ * `'\n'` can never byte-match it and every write path was permanently
1976
+ * refused with "External drift detected" — including the repairs the model
1977
+ * would need to make. Such files are adopted instead of flagged.
1978
+ */
761
1979
  async detectDrift(target) {
1980
+ if (await this.oversizedFile(target)) return true;
762
1981
  const raw = await this.io.readText(fileFor(this.root, target));
763
- if (raw === null) return false;
764
- return normalizeEntries(raw).join(ENTRY_DELIMITER) !== raw.trim();
1982
+ if (raw === null || raw.trim() === "") return false;
1983
+ const entries = normalizeEntries(raw);
1984
+ const limit = this.limitFor(target);
1985
+ if (limit > 0 && entries.some((entry) => entry.length > limit)) return true;
1986
+ return render(entries) !== raw;
765
1987
  }
766
1988
  };
767
1989
  //#endregion
768
- //#region lib/types/prompts.js
1990
+ //#region lib/types/mutations.js
769
1991
  /**
770
- * Review and curation prompts adapted from Hermes Agent
771
- * `agent/background_review.py`, `agent/curator.py`, and
772
- * `agent/learn_prompt.py`, with tool names translated to the DSH-native
773
- * catalog (`memory`, `skill_manage`, `skill`, `bash`, `str_replace_editor`).
774
- *
775
- * Every prompt is pinned in a versioned bundle. Review workers verify the
776
- * bundle digest before spending a model call, so a partially-patched
777
- * deployment fails closed instead of silently running a truncated prompt.
1992
+ * Curator/author audit trail: `.mutations.json` records every skill mutation
1993
+ * with before/after content hashes so any automated edit is reviewable and
1994
+ * replayable. Best-effort persistence, mirroring the usage sidecar posture.
1995
+ * @module @lmzhen/dsh-evolution-core
778
1996
  */
779
- const PROMPT_BUNDLE_ID = "dsh-evolution@1";
780
- const MEMORY_REVIEW_PROMPT = `[Auto-review — Memory]
781
- Review the conversation above and consider saving to memory if appropriate.
782
-
783
- Focus on:
784
- 1. Has the user revealed things about themselves — persona, desires, preferences, or personal details worth remembering?
785
- 2. Has the user expressed expectations about how you should behave, their work style, or ways they want you to operate?
786
-
787
- If something stands out, save it using the memory tool.
788
- If nothing is worth saving, just say "Nothing to save." and stop.`;
789
- const SKILL_REVIEW_PROMPT = `[Auto-review — Skills]
790
- Review the conversation above and update the skill library. Be ACTIVE — most sessions produce at least one skill update, even if small.
791
-
792
- 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.
793
-
794
- Signals that warrant action:
795
- - The user corrected your style, tone, format, verbosity, workflow, or approach.
796
- - A non-trivial technique, fix, workaround, or debugging path emerged.
797
- - A loaded skill turned out wrong, missing, or outdated — patch it now.
798
-
799
- Preference order:
800
- 1. Patch a skill that was loaded or read this session.
801
- 2. Patch an existing umbrella skill.
802
- 3. Add references/, templates/, or scripts/ support under an existing skill.
803
- 4. Create a new class-level umbrella skill only when nothing fits.
804
-
805
- Protected skills (bundled/hub-installed) must not be edited. Pinned skills may be patched but not archived.
806
-
807
- Do NOT capture:
808
- - Environment-dependent failures (missing binaries, unconfigured credentials).
809
- - Negative claims about tools ("browser tools do not work").
810
- - Transient errors that resolved during the session.
811
- - One-off task narratives.
812
-
813
- 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.
814
-
815
- "Nothing to save." is a real option but should NOT be the default.`;
816
- const COMBINED_REVIEW_PROMPT = `[Auto-review]
817
- Review the conversation above and update two things.
818
-
819
- **Memory**: who the user is. Save durable user preferences, personal details, and expectations with the memory tool.
820
-
821
- **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.
822
-
823
- 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.`;
824
- const CURATOR_PROMPT = `You are the skill curator. Maintain a healthy, class-level skill library.
825
-
826
- Rules:
827
- 1. NEVER hard-delete a skill. Archive is the maximum destructive action.
828
- 2. Do not touch bundled, hub-installed, or pinned skills.
829
- 3. Do not archive recently-created or never-used skills without strong evidence.
830
- 4. Prefer merging narrow skills into class-level umbrellas.
831
- 5. Before archiving a merged skill, ensure its unique content was preserved.
832
-
833
- Produce a YAML summary:
834
- consolidations:
835
- - from: <old-skill-name>
836
- into: <umbrella-skill-name>
837
- reason: <one short sentence>
838
- prunings:
839
- - name: <skill-name>
840
- reason: <one short sentence>`;
841
- function reviewPrompt(kind) {
842
- if (kind === "memory") return MEMORY_REVIEW_PROMPT;
843
- if (kind === "skill") return SKILL_REVIEW_PROMPT;
844
- return COMBINED_REVIEW_PROMPT;
1997
+ const DEFAULT_MUTATION_CAP = 500;
1998
+ /** Version of the `.mutations.json` file shape; writers always emit the current one. */
1999
+ const MUTATIONS_FILE_VERSION = 1;
2000
+ function mutationsFile(root) {
2001
+ return join(root, ".mutations.json");
845
2002
  }
846
- function sha256(text) {
847
- return createHash("sha256").update(text).digest("hex");
2003
+ function contentHash(content) {
2004
+ return createHash("sha256").update(content).digest("hex");
848
2005
  }
849
- function createPromptBundle(prompts) {
850
- const canonical = JSON.stringify({
851
- id: PROMPT_BUNDLE_ID,
852
- version: 1,
853
- prompts: Object.fromEntries(Object.entries(prompts).sort())
854
- });
855
- return Object.freeze({
856
- id: PROMPT_BUNDLE_ID,
857
- version: 1,
858
- prompts: Object.freeze({ ...prompts }),
859
- sha256: sha256(canonical)
860
- });
2006
+ /**
2007
+ * Parse a raw mutations sidecar; malformed content reads as empty (auditing is
2008
+ * best-effort). Versioned shape ({ version, records }) with legacy
2009
+ * plain-array compat, plus a field-level guard for records without the
2010
+ * required identity/timestamp fields (rc.42 audit P2-3).
2011
+ */
2012
+ function parseMutationRecords(raw) {
2013
+ if (raw === null) return [];
2014
+ try {
2015
+ const parsed = JSON.parse(raw);
2016
+ 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");
2017
+ } catch {
2018
+ return [];
2019
+ }
861
2020
  }
862
- const PROMPT_BUNDLE = createPromptBundle({
863
- memory: MEMORY_REVIEW_PROMPT,
864
- skill: SKILL_REVIEW_PROMPT,
865
- combined: COMBINED_REVIEW_PROMPT,
866
- curator: CURATOR_PROMPT
867
- });
868
- function verifyPromptBundle(bundle = PROMPT_BUNDLE) {
869
- const canonical = JSON.stringify({
870
- id: bundle.id,
871
- version: bundle.version,
872
- prompts: Object.fromEntries(Object.entries(bundle.prompts).sort())
2021
+ async function loadMutations(root, io = nodeEvolutionIo()) {
2022
+ return parseMutationRecords(await io.readText(mutationsFile(root)));
2023
+ }
2024
+ /** Append one record, trim to `cap`, and write atomically (versioned shape). */
2025
+ async function recordMutation(root, io, record, cap = 500) {
2026
+ await transactIo(io, mutationsFile(root), async (current) => {
2027
+ if (current !== null) try {
2028
+ JSON.parse(current);
2029
+ } catch {
2030
+ return current;
2031
+ }
2032
+ const existing = parseMutationRecords(current);
2033
+ existing.push(record);
2034
+ const trimmed = existing.length > cap ? existing.slice(existing.length - cap) : existing;
2035
+ return Promise.resolve(JSON.stringify({
2036
+ version: 1,
2037
+ records: trimmed
2038
+ }, null, 2));
873
2039
  });
874
- return bundle.sha256 === sha256(canonical);
875
2040
  }
876
- const DSH_AUTHORING_STANDARDS = `Follow the Hermes skill-authoring standards, translated to DSH tools.
877
-
878
- Frontmatter:
879
- - name: lowercase-hyphenated, <=64 chars, no spaces.
880
- - 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.
881
- - version: 0.1.0
882
- - author: always the literal value "Hermes". NEVER fill it from the environment, git config, or any identity you can probe.
883
- - platforms: declare [macos], [linux], and/or [windows] only when the skill is genuinely OS-bound; omit for portable skills.
884
- - metadata.hermes.tags: a few Capitalized, Relevant, Tags.
885
-
886
- Body section order (omit only when empty):
887
- 1. "# <Human Title>" then a 2-3 sentence intro: what it does, what it does NOT do, key dependency stance.
888
- 2. "## When to Use" — concrete trigger phrases.
889
- 3. "## Prerequisites" — exact env vars, install steps, credentials.
890
- 4. "## How to Run" — canonical invocation framed through DSH tools.
891
- 5. "## Quick Reference" — flat command/endpoint list.
892
- 6. "## Procedure" — numbered steps with copy-paste-exact commands.
893
- 7. "## Pitfalls" — known limits and rate limits.
894
- 8. "## Verification" — one check proving the skill worked.
895
-
896
- DSH-tool framing:
897
- - Reference DSH tools by name in backticks: \`bash\`, \`str_replace_editor\`, \`write\`, \`skill\`, \`skill_manage\`, \`memory\`.
898
- - Do not name wrapped shell utilities when a DSH tool already covers them.
899
- - Larger scripts belong under \`scripts/\` (written with \`skill_manage write_file\`) and are referenced from SKILL.md by relative path.
900
-
901
- Quality bar:
902
- - Prefer verbatim flags, paths, and APIs from the source. Never invent them.
903
- - Keep it tight: ~100 lines simple, ~200 complex.
904
- - No router/index/hub skills that only point at other skills.
905
- - References go in \`references/\`, templates in \`templates/\`.`;
2041
+ //#endregion
2042
+ //#region lib/types/quality.js
2043
+ /**
2044
+ * Quality scoring and near-duplicate detection for the curated skill library.
2045
+ *
2046
+ * Pure functions over data inputs so the scoring policy is unit-testable and
2047
+ * the same math feeds the usage sidecar, the `skill_manage review` surface and
2048
+ * the learning graph. Weights follow the Hermes/hermes-claw six-factor model;
2049
+ * mutation maturity is a documented DSH approximation (single per-month patch
2050
+ * trend ratio replaces the claw timestamp-trend formula, since DSH usage
2051
+ * records only carry the last patched timestamp).
2052
+ * @module @lmzhen/dsh-evolution-core
2053
+ */
2054
+ const QUALITY_WEIGHTS = {
2055
+ usageFrequency: .25,
2056
+ stability: .2,
2057
+ recency: .2,
2058
+ references: .1,
2059
+ mutationMaturity: .2,
2060
+ richness: .05
2061
+ };
2062
+ /** Score below which a skill is flagged for review. */
2063
+ const LOW_QUALITY_THRESHOLD = .3;
2064
+ function clamp01(value) {
2065
+ return Math.max(0, Math.min(1, value));
2066
+ }
2067
+ function daysBetween(from, now) {
2068
+ return Math.max(0, (now.getTime() - new Date(from).getTime()) / 864e5);
2069
+ }
2070
+ function computeQualityScores(input) {
2071
+ const now = input.now ?? /* @__PURE__ */ new Date();
2072
+ const scores = /* @__PURE__ */ new Map();
2073
+ for (const [name, record] of input.usage) {
2074
+ const ageDays = Math.max(1, daysBetween(record.created_at, now));
2075
+ const idleDays = daysBetween(latestActivityAt(record) ?? record.created_at, now);
2076
+ const patchCount = record.patch_count;
2077
+ const useCount = record.use_count;
2078
+ const usageFrequency = clamp01(useCount / ageDays);
2079
+ const stability = useCount === 0 ? 1 : clamp01(1 - patchCount / useCount);
2080
+ const recency = idleDays < 30 ? 1 : clamp01(1 - (idleDays - 30) / 150);
2081
+ const references = clamp01((input.referenceCounts?.get(name) ?? 0) / 3);
2082
+ const mutationMaturity = patchCount === 0 ? .3 : patchCount === 1 ? .4 : clamp01((patchCount - 1) / Math.max(1, ageDays / 30));
2083
+ const richness = clamp01((input.supportDirs?.get(name) ?? 0) * .175);
2084
+ const factors = {
2085
+ usageFrequency,
2086
+ stability,
2087
+ recency,
2088
+ references,
2089
+ mutationMaturity,
2090
+ richness
2091
+ };
2092
+ 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;
2093
+ scores.set(name, {
2094
+ score,
2095
+ factors,
2096
+ warn: score < LOW_QUALITY_THRESHOLD
2097
+ });
2098
+ }
2099
+ return scores;
2100
+ }
2101
+ function normalize(content) {
2102
+ return content.toLowerCase().replace(/\s+/g, " ").trim();
2103
+ }
2104
+ function contentHash$1(content) {
2105
+ return createHash("sha256").update(normalize(content)).digest("hex");
2106
+ }
2107
+ function tokenize(content) {
2108
+ return new Set(normalize(content).split(/[^a-z0-9\u4e00-\u9fff]+/).filter(Boolean));
2109
+ }
2110
+ function jaccard(a, b) {
2111
+ if (a.size === 0 || b.size === 0) return 0;
2112
+ let intersection = 0;
2113
+ for (const token of a) if (b.has(token)) intersection += 1;
2114
+ return intersection / (a.size + b.size - intersection);
2115
+ }
2116
+ /**
2117
+ * Two-phase near-duplicate clustering: exact normalized-hash groups first,
2118
+ * then token-Jaccard edges at {@link DEDUP_SIMILARITY_THRESHOLD} with a token
2119
+ * ratio guard, union-find across the whole set.
2120
+ */
2121
+ function computeDedupGroups(input) {
2122
+ const threshold = input.threshold ?? .95;
2123
+ const names = [...input.contents.keys()];
2124
+ const hashes = /* @__PURE__ */ new Map();
2125
+ for (const name of names) {
2126
+ const hash = contentHash$1(input.contents.get(name) ?? "");
2127
+ const bucket = hashes.get(hash);
2128
+ if (bucket) bucket.push(name);
2129
+ else hashes.set(hash, [name]);
2130
+ }
2131
+ const parent = /* @__PURE__ */ new Map();
2132
+ const find = (x) => {
2133
+ const root = parent.get(x) ?? x;
2134
+ if (root !== x) parent.set(x, find(root));
2135
+ return parent.get(x) ?? x;
2136
+ };
2137
+ const union = (a, b) => {
2138
+ const [ra, rb] = [find(a), find(b)];
2139
+ if (ra !== rb) parent.set(rb, ra);
2140
+ };
2141
+ for (const [hash, bucketNames] of hashes) {
2142
+ const first = bucketNames[0];
2143
+ if (first === void 0 || bucketNames.length === 1) continue;
2144
+ for (let index = 1; index < bucketNames.length; index += 1) {
2145
+ const peer = bucketNames[index];
2146
+ if (peer) union(first, peer);
2147
+ }
2148
+ }
2149
+ const tokens = /* @__PURE__ */ new Map();
2150
+ const tokenSet = (name) => {
2151
+ let set = tokens.get(name);
2152
+ if (!set) {
2153
+ set = tokenize(input.contents.get(name) ?? "");
2154
+ tokens.set(name, set);
2155
+ }
2156
+ return set;
2157
+ };
2158
+ for (let index = 0; index < names.length; index += 1) {
2159
+ const a = names[index];
2160
+ if (a === void 0) continue;
2161
+ for (let other = index + 1; other < names.length; other += 1) {
2162
+ const b = names[other];
2163
+ if (b === void 0) continue;
2164
+ const [ta, tb] = [tokenSet(a), tokenSet(b)];
2165
+ if (Math.max(ta.size, tb.size) / Math.max(1, Math.min(ta.size, tb.size)) > 5) continue;
2166
+ if (jaccard(ta, tb) >= threshold) union(a, b);
2167
+ }
2168
+ }
2169
+ const groups = /* @__PURE__ */ new Map();
2170
+ for (const name of names) {
2171
+ const root = find(name);
2172
+ const group = groups.get(root);
2173
+ if (group) group.push(name);
2174
+ else groups.set(root, [name]);
2175
+ }
2176
+ return [...groups.values()].filter((group) => group.length > 1);
2177
+ }
2178
+ /**
2179
+ * Prefix-cluster index over a name set (rc.67 merge heuristic, input side):
2180
+ * the curator prompt asks the model to identify "prefix clusters — skills
2181
+ * sharing a first word or domain keyword"; the deterministic index supplies
2182
+ * stable ground truth instead of letting the model infer clusters from the
2183
+ * raw list. Key = first alphanumeric run of the lowercased name; groups with
2184
+ * at least two members, largest first then alphabetical. Orientation-only:
2185
+ * nomination authority stays with the LLM and the candidate-pool gates.
2186
+ */
2187
+ function computePrefixClusters(names) {
2188
+ const groups = /* @__PURE__ */ new Map();
2189
+ for (const name of names) {
2190
+ const key = name.toLowerCase().split(/[^a-z0-9]+/)[0];
2191
+ if (!key) continue;
2192
+ const bucket = groups.get(key);
2193
+ if (bucket) bucket.push(name);
2194
+ else groups.set(key, [name]);
2195
+ }
2196
+ return [...groups.entries()].filter(([, members]) => members.length >= 2).map(([key, members]) => ({
2197
+ key,
2198
+ members
2199
+ })).sort((a, b) => b.members.length - a.members.length || a.key.localeCompare(b.key));
2200
+ }
2201
+ //#endregion
2202
+ //#region lib/types/skill-health.js
2203
+ /**
2204
+ * Skill structure-health domain (rc.73 A1, 008 design): a SECOND assessment
2205
+ * dimension beside the six-factor usage quality — document hygiene, consumed
2206
+ * by the curator health view and the `/evolution skills health` command.
2207
+ *
2208
+ * PURE and DERIVED: nothing is persisted; every assessment is computed from
2209
+ * file facts at read time. The judgment split follows the original's
2210
+ * boundary/治理 layering — deterministic signals here, refinement proposals
2211
+ * stay in the review/curator judgment layer. Never become a 7th factor of
2212
+ * `computeQualityScores` (different dimension, different consumers).
2213
+ */
2214
+ const DEFAULT_HEALTH_THRESHOLDS = {
2215
+ softBodyChars: 4e4,
2216
+ stampDensityPerKb: 2,
2217
+ churnMinPatches: 20
2218
+ };
2219
+ const HEALTH_STAMP_RE = /\brc\.\d+\b|\b[0-9a-f]{7,40}\b|\b\d{4}-\d{2}-\d{2}(?:T[0-9:.]+Z)?\b/g;
2220
+ /**
2221
+ * Bodies below this size skip stamp-density assessment: a few dates or shas
2222
+ * in a short body are ordinary documentation, not log-like content. With the
2223
+ * 1KB density floor a 3-date sentence in a small skill measured 3.0/KB and
2224
+ * warned on a perfectly healthy body (audit 2026-09-01 X1).
2225
+ */
2226
+ const MIN_STAMP_BODY_CHARS = 2e3;
2227
+ function assessStructureHealth(snapshot, thresholds = DEFAULT_HEALTH_THRESHOLDS) {
2228
+ const reasons = [];
2229
+ const dims = {
2230
+ bodyChars: snapshot.bodyChars,
2231
+ stampDensityPerKb: null,
2232
+ supportGroups: snapshot.supportGroups,
2233
+ churnPatches: null,
2234
+ churnReads: null
2235
+ };
2236
+ const needs = snapshot.bodyChars >= thresholds.softBodyChars * 2;
2237
+ if (needs) reasons.push(`body ${snapshot.bodyChars} chars is >= 2x the soft limit (${thresholds.softBodyChars}) — consider splitting or offloading`);
2238
+ else if (snapshot.bodyChars >= thresholds.softBodyChars) reasons.push(`body ${snapshot.bodyChars} chars above the soft limit (${thresholds.softBodyChars})`);
2239
+ if (snapshot.bodyText && snapshot.bodyChars >= MIN_STAMP_BODY_CHARS) {
2240
+ const kb = Math.max(1, snapshot.bodyChars / 1024);
2241
+ dims.stampDensityPerKb = (snapshot.bodyText.match(HEALTH_STAMP_RE) ?? []).length / kb;
2242
+ if (dims.stampDensityPerKb >= thresholds.stampDensityPerKb) reasons.push(`stamp density ${dims.stampDensityPerKb.toFixed(1)}/KB (rc/sha/date lines — log-like content in the body)`);
2243
+ }
2244
+ if (snapshot.supportGroups === 0 && snapshot.bodyChars >= thresholds.softBodyChars / 2) reasons.push(`large body (${snapshot.bodyChars} chars) with NO support files — session detail may belong in references/`);
2245
+ if (snapshot.patchCount !== void 0 && snapshot.readCount !== void 0) {
2246
+ dims.churnPatches = snapshot.patchCount;
2247
+ dims.churnReads = snapshot.readCount;
2248
+ if (snapshot.patchCount >= thresholds.churnMinPatches && snapshot.readCount === 0) reasons.push(`patched ${snapshot.patchCount} times but never read (write-ghost — content may be dead)`);
2249
+ }
2250
+ return {
2251
+ verdict: needs ? "needs-restructure" : reasons.length > 0 ? "warn" : "healthy",
2252
+ dims,
2253
+ reasons
2254
+ };
2255
+ }
906
2256
  //#endregion
907
2257
  //#region lib/types/signals.js
908
2258
  /**
@@ -990,31 +2340,57 @@ function foldTurn(session, fromSeq) {
990
2340
  * it created unless a `.hermes-managed` marker opts a skill in. Archival is a
991
2341
  * move to `.archive/` — never a hard delete.
992
2342
  */
993
- const SKILL_NAME_RE = /^[a-z0-9][a-z0-9-]*$/;
994
- const MAX_SKILL_NAME_LENGTH = 64;
995
- const MAX_DESCRIPTION_LENGTH = 1024;
996
- const MAX_SKILL_CONTENT_CHARS = 1e5;
997
- const MAX_SKILL_FILE_BYTES = 1048576;
998
2343
  const DEFAULT_SKILL_LIMITS = {
999
2344
  maxNameLength: 64,
1000
2345
  maxDescriptionLength: MAX_DESCRIPTION_LENGTH,
1001
2346
  maxSkillContentChars: MAX_SKILL_CONTENT_CHARS,
1002
2347
  maxSkillFileBytes: MAX_SKILL_FILE_BYTES
1003
2348
  };
1004
- const SUPPORT_DIRS = [
1005
- "references",
1006
- "templates",
1007
- "scripts",
1008
- "assets"
1009
- ];
2349
+ /** Upper bound of moves per restructure proposal (validator and core agree). */
2350
+ const MAX_RESTRUCTURE_MOVES = 5;
2351
+ /** Restructure targets are plain markdown files under references/ — no subdirectories, no other support kind. */
2352
+ const RESTRUCTURE_TARGET_RE = /^references\/[a-z0-9][a-z0-9._-]*\.md$/;
2353
+ /** Extra file name carried inside a snapshot's `extras/` directory. */
2354
+ const SNAPSHOT_EXTRA_NAME_RE = /^[a-z0-9][a-z0-9._-]*$/;
1010
2355
  function skillsRoot(env = process.env) {
1011
2356
  return join(env.DSH_HOME ?? join(homedir(), ".dsh"), "skills");
1012
2357
  }
2358
+ /**
2359
+ * Map a requesting session onto the two origin surfaces (rc.44 plan M2-2.3):
2360
+ * the APPROVAL surface treats every delegated subagent as the autonomous
2361
+ * review channel, while the LIBRARY surface keeps the Hermes distinction -
2362
+ * the review fork is 'background_review' (the pinned guard blocks its
2363
+ * writes) and any other subagent is 'subagent' (agent-authored, not
2364
+ * review-channel). `isReview` marks the caller as the background review
2365
+ * pipeline itself. Single source: the two tools and the review executor all
2366
+ * read this table instead of re-deriving it.
2367
+ */
2368
+ function resolveOrigins(headerOrigin, isReview = false) {
2369
+ if (isReview) return {
2370
+ approval: "background_review",
2371
+ library: "background_review"
2372
+ };
2373
+ if (headerOrigin === "subagent") return {
2374
+ approval: "background_review",
2375
+ library: "subagent"
2376
+ };
2377
+ return {
2378
+ approval: "foreground",
2379
+ library: "foreground"
2380
+ };
2381
+ }
1013
2382
  function skillDir(root, name) {
1014
2383
  return join(root, name);
1015
2384
  }
2385
+ /** Dot-prefixed on-disk marker name. SINGLE source: `list()` matches directory
2386
+ * entries against this name, and path builders must never hardcode a marker
2387
+ * literal (N-1: the rc.49 exists()-probe convergence dropped the dot,
2388
+ * poisoning every protectedBy/managed report). */
2389
+ function markerEntryName(marker) {
2390
+ return `.${marker}`;
2391
+ }
1016
2392
  function markerPath(dir, marker) {
1017
- return join(dir, `.${marker}`);
2393
+ return join(dir, markerEntryName(marker));
1018
2394
  }
1019
2395
  function parseFrontmatter(content) {
1020
2396
  if (!content.trimStart().startsWith("---")) return null;
@@ -1036,6 +2412,26 @@ function parseFrontmatter(content) {
1036
2412
  body
1037
2413
  };
1038
2414
  }
2415
+ /**
2416
+ * Skill names referenced by a SKILL.md's `related_skills` frontmatter
2417
+ * (B-line G3, rc.44): the single parsing source for the quality references
2418
+ * factor and the learning-graph edges. The DSH frontmatter parser keeps the
2419
+ * YAML value as a string (`"[a, b]"`), so names are scanned out of it; each
2420
+ * must satisfy the skill-name shape and the referencing skill itself is
2421
+ * excluded. Pure and deduplicated.
2422
+ */
2423
+ function relatedSkillNames(content, exclude) {
2424
+ const parsed = parseFrontmatter(content);
2425
+ if (!parsed) return [];
2426
+ const raw = parsed.frontmatter["related_skills"];
2427
+ if (typeof raw !== "string") return [];
2428
+ const names = /* @__PURE__ */ new Set();
2429
+ for (const match of Array.from(raw.matchAll(/[a-z0-9][a-z0-9-]*/g))) {
2430
+ const target = match[0];
2431
+ if (target && SKILL_NAME_RE.test(target) && target !== exclude) names.add(target);
2432
+ }
2433
+ return [...names];
2434
+ }
1039
2435
  function validateFrontmatter(content, expectedName, limits = DEFAULT_SKILL_LIMITS) {
1040
2436
  const parsed = parseFrontmatter(content);
1041
2437
  if (!parsed) return "SKILL.md must start and end with YAML frontmatter and include a body.";
@@ -1045,9 +2441,34 @@ function validateFrontmatter(content, expectedName, limits = DEFAULT_SKILL_LIMIT
1045
2441
  if (expectedName && parsed.frontmatter.name !== expectedName) return `Frontmatter name "${parsed.frontmatter.name}" does not match target skill "${expectedName}".`;
1046
2442
  if (!parsed.frontmatter.description) return "Frontmatter must include a description field.";
1047
2443
  if (parsed.frontmatter.description.length > limits.maxDescriptionLength) return `Description exceeds ${limits.maxDescriptionLength} characters.`;
1048
- if (content.length > limits.maxSkillContentChars) return `SKILL.md content exceeds ${limits.maxSkillContentChars} characters.`;
2444
+ if (content.length > limits.maxSkillContentChars) return `SKILL.md content exceeds ${limits.maxSkillContentChars} characters. Consider splitting into a smaller SKILL.md with supporting files.`;
1049
2445
  return null;
1050
2446
  }
2447
+ /** Hermes authoring quality bar for descriptions (the 60-char Rule). The
2448
+ * platform's own index limit stays in `validateFrontmatter`; this bar is the
2449
+ * target the authoring standard names, enforced as ADVISORY feedback. */
2450
+ const AUTHORING_DESCRIPTION_BAR = 60;
2451
+ /**
2452
+ * Advisory authoring feedback (P0): evaluate frontmatter against the
2453
+ * authoring bar WITHOUT changing platform validation semantics. The bar is
2454
+ * the quality target, `validateFrontmatter`'s limits are the compatibility
2455
+ * floor, and this bridge layer tells the model when its text would be
2456
+ * truncated or route-poor instead of silently shipping it.
2457
+ */
2458
+ function authoringFeedback(frontmatter) {
2459
+ const description = frontmatter.description ?? "";
2460
+ const over60 = description.length > 60;
2461
+ const hasColon = description.includes(":");
2462
+ const lines = [];
2463
+ lines.push(over60 ? `Description is ${description.length}/60 characters — exceeds the 60-char authoring bar (Hermes standard; the catalog truncates at the configured platform cap).` : `Description ${description.length}/60 characters — within the authoring bar.`);
2464
+ if (hasColon) lines.push("Description contains a colon — wrap the whole value in double quotes.");
2465
+ return {
2466
+ descriptionChars: description.length,
2467
+ over60,
2468
+ hasColon,
2469
+ lines
2470
+ };
2471
+ }
1051
2472
  async function listNames(root, io) {
1052
2473
  const entries = await io.list(root);
1053
2474
  const names = [];
@@ -1055,75 +2476,359 @@ async function listNames(root, io) {
1055
2476
  if (entry.startsWith(".")) continue;
1056
2477
  if (await io.exists(join(root, entry, "SKILL.md"))) names.push(entry);
1057
2478
  }
1058
- return names.sort();
1059
- }
1060
- function validateSupportPath(filePath) {
1061
- const normalized = filePath.replace(/\\/g, "/");
1062
- if (normalized.includes("..")) return "Path traversal is not allowed.";
1063
- const parts = normalized.split("/").filter(Boolean);
1064
- if (parts.length === 0 || !SUPPORT_DIRS.includes(parts[0])) return `file_path must be under one of: ${SUPPORT_DIRS.join(", ")}.`;
1065
- if (parts.length < 2) return "Provide a file name, not just a directory.";
2479
+ return names.sort();
2480
+ }
2481
+ function validateSupportPath(filePath) {
2482
+ const normalized = filePath.replace(/\\/g, "/");
2483
+ if (normalized.includes("..")) return "Path traversal is not allowed.";
2484
+ const parts = normalized.split("/").filter(Boolean);
2485
+ if (parts.length === 0 || !SUPPORT_DIRS.includes(parts[0])) return `file_path must be under one of: ${SUPPORT_DIRS.join(", ")}.`;
2486
+ if (parts.length < 2) return "Provide a file name, not just a directory.";
2487
+ return null;
2488
+ }
2489
+ /**
2490
+ * Index of `pattern` inside `content`, treating whitespace runs (spaces/tabs)
2491
+ * as flexible and literal escape sequences (`\n`, `\t`, `\r`) as their real
2492
+ * characters: a PATTERN whitespace run matches any content run of any length
2493
+ * (even empty), while extra whitespace that only exists in the content is not
2494
+ * skipped — the flexibility is one-sided on the pattern, and a backslash-
2495
+ * escaped char in the pattern matches the real char in the content
2496
+ * (model-copy drift). Returns the [start, end) range in the ORIGINAL content
2497
+ * so a patch can replace exactly the matched span and keep every other byte
2498
+ * intact. Returns null when no fuzzy match exists.
2499
+ */
2500
+ function fuzzyIndexOf(content, pattern, from = 0) {
2501
+ const isSpace = (char) => char !== void 0 && /[ \t]/.test(char);
2502
+ const escaped = (char) => {
2503
+ if (char === "n") return "\n";
2504
+ if (char === "t") return " ";
2505
+ if (char === "r") return "\r";
2506
+ return null;
2507
+ };
2508
+ for (let start = from; start < content.length; start += 1) {
2509
+ let contentIndex = start;
2510
+ let patternIndex = 0;
2511
+ while (patternIndex < pattern.length && contentIndex < content.length) {
2512
+ const patternChar = pattern[patternIndex];
2513
+ const contentChar = content[contentIndex];
2514
+ if (isSpace(patternChar)) {
2515
+ while (patternIndex < pattern.length && isSpace(pattern[patternIndex])) patternIndex += 1;
2516
+ while (contentIndex < content.length && isSpace(content[contentIndex])) contentIndex += 1;
2517
+ continue;
2518
+ }
2519
+ const escapedChar = patternChar === "\\" ? escaped(pattern[patternIndex + 1]) : null;
2520
+ if (escapedChar !== null && contentChar === escapedChar) {
2521
+ patternIndex += 2;
2522
+ contentIndex += 1;
2523
+ continue;
2524
+ }
2525
+ if (patternChar === contentChar) {
2526
+ contentIndex += 1;
2527
+ patternIndex += 1;
2528
+ continue;
2529
+ }
2530
+ break;
2531
+ }
2532
+ if (patternIndex === pattern.length) return [start, contentIndex];
2533
+ }
1066
2534
  return null;
1067
2535
  }
2536
+ /** Trim leading whitespace of the first line and trailing whitespace of the last line. */
2537
+ function trimPatternBoundaries(pattern) {
2538
+ const from = pattern.search(/\S/);
2539
+ const trimmed = from < 0 ? pattern : pattern.slice(from);
2540
+ const trailing = trimmed.search(/\s+$/);
2541
+ return trailing < 0 ? trimmed : trimmed.slice(0, trailing);
2542
+ }
2543
+ /** Replace only the fuzzy-matched span, preserving all surrounding bytes. */
2544
+ function fuzzyReplace(content, oldString, newString, replaceAll) {
2545
+ let current = content;
2546
+ let scanFrom = 0;
2547
+ for (;;) {
2548
+ const match = fuzzyIndexOf(current, oldString, scanFrom);
2549
+ if (match === null) return current;
2550
+ const [start, end] = match;
2551
+ const next = current.slice(0, start) + newString + current.slice(end);
2552
+ if (!replaceAll) return next;
2553
+ current = next;
2554
+ scanFrom = start + newString.length;
2555
+ }
2556
+ }
1068
2557
  function fuzzyPatch(content, oldString, newString, replaceAll = false) {
2558
+ if (oldString === "") return null;
1069
2559
  if (content.includes(oldString)) return replaceAll ? content.split(oldString).join(newString) : content.replace(oldString, newString);
1070
- const trimmed = content.replaceAll(/[ ]+$/gm, "");
1071
- if (trimmed.includes(oldString)) return trimmed.replace(oldString, newString);
1072
- const whitespace = content.replaceAll(/[ ]+/g, " ");
1073
- if (whitespace.includes(oldString)) return whitespace.replace(oldString, newString);
2560
+ const boundary = trimPatternBoundaries(oldString);
2561
+ if (boundary === "") return null;
2562
+ if (boundary !== oldString) {
2563
+ if (fuzzyIndexOf(content, boundary) !== null) {
2564
+ const patched = fuzzyReplace(content, boundary, newString, replaceAll);
2565
+ return patched === content ? null : patched;
2566
+ }
2567
+ }
2568
+ if (fuzzyIndexOf(content, oldString) !== null) {
2569
+ const patched = fuzzyReplace(content, oldString, newString, replaceAll);
2570
+ return patched === content ? null : patched;
2571
+ }
1074
2572
  return null;
1075
2573
  }
2574
+ /**
2575
+ * Support-directory references in a markdown body (009 kernel): `references/…`,
2576
+ * `templates/…`, `scripts/…`, `assets/…` relative links. Pure — who checks
2577
+ * them and what the verdict is belongs to the caller's context (a moved/
2578
+ * appended body whose references travel with an archived source is a dangling
2579
+ * link; a restructure pointer is a fresh link to a file written in the same
2580
+ * plan).
2581
+ */
2582
+ function supportRefs(content) {
2583
+ const refs = [];
2584
+ for (const match of content.matchAll(/\b(?:references|templates|scripts|assets)\/[A-Za-z0-9._-]+\.md/g)) refs.push(match[0]);
2585
+ return refs;
2586
+ }
2587
+ function planRestructureSections(body, moves) {
2588
+ const lines = body.split("\n");
2589
+ const spans = [];
2590
+ for (const move of moves) {
2591
+ const wanted = move.heading.trim();
2592
+ const starts = [];
2593
+ for (let i = 0; i < lines.length; i += 1) if ((/^#{2}\s+(.+?)\s*$/.exec(lines[i] ?? "")?.[1]?.trim() ?? "") === wanted) starts.push(i);
2594
+ const [start] = starts;
2595
+ if (start === void 0) return { error: `no "## ${wanted}" heading in the body` };
2596
+ if (starts.length > 1) return { error: `heading "## ${wanted}" appears ${starts.length} times (ambiguous anchor)` };
2597
+ let end = lines.length;
2598
+ for (let i = start + 1; i < lines.length; i += 1) if (/^#{2}\s/.test(lines[i] ?? "")) {
2599
+ end = i;
2600
+ break;
2601
+ }
2602
+ if (end === start + 1) return { error: `heading "## ${wanted}" has an empty section` };
2603
+ if (spans.some((span) => start === span.start)) return { error: `heading "## ${wanted}" is moved twice` };
2604
+ spans.push({
2605
+ start,
2606
+ end,
2607
+ rel: move.toFile,
2608
+ heading: wanted,
2609
+ text: lines.slice(start, end).join("\n")
2610
+ });
2611
+ }
2612
+ const byStart = new Map(spans.map((span) => [span.start, span]));
2613
+ const rebuilt = [];
2614
+ for (let i = 0; i < lines.length; i += 1) {
2615
+ const span = byStart.get(i);
2616
+ if (span) {
2617
+ rebuilt.push(`> 详见 references/${span.rel.split("/").at(-1)}`);
2618
+ i = span.end - 1;
2619
+ } else rebuilt.push(lines[i] ?? "");
2620
+ }
2621
+ return {
2622
+ body: rebuilt.join("\n"),
2623
+ sections: spans.map(({ rel, heading, text }) => ({
2624
+ rel,
2625
+ heading,
2626
+ text
2627
+ }))
2628
+ };
2629
+ }
1076
2630
  var SkillLibrary = class {
1077
2631
  root;
1078
2632
  limits;
1079
2633
  io;
1080
- constructor(root = skillsRoot(), io = nodeEvolutionIo(), limits = DEFAULT_SKILL_LIMITS) {
2634
+ onMutation;
2635
+ constructor(root = skillsRoot(), io = nodeEvolutionIo(), limits = DEFAULT_SKILL_LIMITS, onMutation) {
1081
2636
  this.root = root;
1082
2637
  this.io = io;
1083
2638
  this.limits = limits;
2639
+ this.onMutation = onMutation;
2640
+ }
2641
+ /** Notify the mutation observer after a successful write; observers must never fail the mutation. */
2642
+ notifyMutation(event) {
2643
+ try {
2644
+ this.onMutation?.(event);
2645
+ } catch {}
1084
2646
  }
1085
2647
  async list() {
1086
2648
  const summaries = [];
1087
2649
  for (const name of await listNames(this.root, this.io)) {
1088
- const dir = skillDir(this.root, name);
2650
+ const dir = this.dirOf(name);
1089
2651
  const md = await this.io.readText(join(dir, "SKILL.md"));
1090
2652
  if (!md) continue;
1091
2653
  const parsed = parseFrontmatter(md);
1092
- const protectedBy = await this.deleteProtection(name);
1093
- const managed = await this.io.exists(markerPath(dir, "hermes-managed"));
2654
+ let entries = [];
2655
+ try {
2656
+ entries = await this.io.list(dir);
2657
+ } catch {}
2658
+ const has = (marker) => entries.includes(markerEntryName(marker));
2659
+ const protectedBy = has("bundled") ? "bundled" : has("hub-installed") ? "hub-installed" : has("pinned") ? "pinned" : null;
1094
2660
  summaries.push({
1095
2661
  name,
1096
2662
  description: parsed?.frontmatter.description ?? "",
1097
2663
  path: dir,
1098
2664
  protectedBy,
1099
- managed,
2665
+ managed: has("hermes-managed"),
1100
2666
  archived: false
1101
2667
  });
1102
2668
  }
1103
2669
  return summaries;
1104
2670
  }
1105
- async read(name) {
1106
- return this.io.readText(join(skillDir(this.root, name), "SKILL.md"));
2671
+ async read(rawName) {
2672
+ const name = rawName.trim();
2673
+ if (this.badName(name) !== null) return null;
2674
+ return this.io.readText(join(this.dirOf(name), "SKILL.md"));
2675
+ }
2676
+ /**
2677
+
2678
+ * Single path-building choke point (rc.42 audit P2-5): every directory path
2679
+
2680
+ * is built from the TRIMMED name, so a name that passes `badName` (which
2681
+
2682
+ * trims before validating) can never mint a second, whitespace-padded
2683
+
2684
+ * directory next to the real one. Callers keep passing raw user input.
2685
+
2686
+ */
2687
+ dirOf(name) {
2688
+ return skillDir(this.root, name.trim());
2689
+ }
2690
+ /** Name-format guard shared by every path-building mutator/reader. */
2691
+ badName(name) {
2692
+ const normalized = name.trim();
2693
+ 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}).`;
2694
+ return null;
1107
2695
  }
1108
- async writeProtection(name) {
1109
- const dir = skillDir(this.root, name);
2696
+ async writeProtection(rawName, origin = "foreground") {
2697
+ const name = rawName.trim();
2698
+ const dir = this.dirOf(name);
1110
2699
  for (const marker of ["bundled", "hub-installed"]) if (await this.io.exists(markerPath(dir, marker))) return marker;
2700
+ if (origin === "background_review" && await this.io.exists(markerPath(dir, "pinned"))) return "pinned";
1111
2701
  return null;
1112
2702
  }
1113
- async deleteProtection(name) {
1114
- const dir = skillDir(this.root, name);
1115
- for (const marker of [
2703
+ async deleteProtection(rawName, options = {}) {
2704
+ const name = rawName.trim();
2705
+ const dir = this.dirOf(name);
2706
+ const markers = options.allowBundled ? ["hub-installed", "pinned"] : [
1116
2707
  "bundled",
1117
2708
  "hub-installed",
1118
2709
  "pinned"
1119
- ]) if (await this.io.exists(markerPath(dir, marker))) return marker;
2710
+ ];
2711
+ for (const marker of markers) if (await this.io.exists(markerPath(dir, marker))) return marker;
1120
2712
  return null;
1121
2713
  }
1122
- async isManaged(name) {
1123
- const dir = skillDir(this.root, name);
2714
+ async isManaged(rawName) {
2715
+ const name = rawName.trim();
2716
+ const dir = this.dirOf(name);
1124
2717
  return await this.io.exists(markerPath(dir, "hermes-managed"));
1125
2718
  }
1126
- async create(name, content, origin) {
2719
+ /** Whether the skill carries the bundled marker (curator prune-builtins eligibility). */
2720
+ async isBundled(rawName) {
2721
+ const name = rawName.trim();
2722
+ if (this.badName(name) !== null) return false;
2723
+ const dir = this.dirOf(name);
2724
+ return await this.io.exists(markerPath(dir, "bundled"));
2725
+ }
2726
+ /** Whether the skill carries the pinned marker (the marker is the factual source; usage.pinned mirrors it). */
2727
+ async isPinned(rawName) {
2728
+ const name = rawName.trim();
2729
+ if (this.badName(name) !== null) return false;
2730
+ const dir = this.dirOf(name);
2731
+ return await this.io.exists(markerPath(dir, "pinned"));
2732
+ }
2733
+ /** Count non-empty support subdirectories (richness input for quality scoring). */
2734
+ async countSupportDirs(rawName) {
2735
+ const name = rawName.trim();
2736
+ if (this.badName(name) !== null) return 0;
2737
+ const dir = this.dirOf(name);
2738
+ let entries;
2739
+ try {
2740
+ entries = await this.io.list(dir);
2741
+ } catch {
2742
+ return 0;
2743
+ }
2744
+ let count = 0;
2745
+ for (const subdir of SUPPORT_DIRS) {
2746
+ if (!entries.includes(subdir)) continue;
2747
+ try {
2748
+ if ((await this.io.list(join(dir, subdir))).some((file) => file !== ".gitkeep")) count += 1;
2749
+ } catch {}
2750
+ }
2751
+ return count;
2752
+ }
2753
+ /**
2754
+ * Structure-health facts for one skill (rc.73 A1, 008 design): body
2755
+ * chars/density from SKILL.md, support groups from countSupportDirs, plus
2756
+ * optional usage counts (A2 churn dimension) when the caller has them.
2757
+ * Derived, never persisted; null when the skill is unreadable.
2758
+ */
2759
+ async assessHealth(rawName, thresholds = DEFAULT_HEALTH_THRESHOLDS, counts) {
2760
+ const name = rawName.trim();
2761
+ const content = await this.read(name);
2762
+ if (content === null) return null;
2763
+ return assessStructureHealth({
2764
+ skillName: name,
2765
+ bodyChars: content.length,
2766
+ bodyText: content,
2767
+ supportGroups: await this.countSupportDirs(name),
2768
+ patchCount: counts?.patchCount,
2769
+ readCount: counts?.readCount
2770
+ }, thresholds);
2771
+ }
2772
+ /** Best-effort audit trail entry; never blocks the mutation. */
2773
+ async audit(skillName, action, before, after, summary) {
2774
+ try {
2775
+ await recordMutation(this.root, this.io, {
2776
+ skillName,
2777
+ action,
2778
+ ...before === null ? {} : { beforeHash: contentHash(before) },
2779
+ ...after === null ? {} : { afterHash: contentHash(after) },
2780
+ summary,
2781
+ at: (/* @__PURE__ */ new Date()).toISOString()
2782
+ });
2783
+ } catch {}
2784
+ }
2785
+ /** Recent mutation audit records (read-only inspection surface). */
2786
+ async listMutations() {
2787
+ return await loadMutations(this.root, this.io);
2788
+ }
2789
+ /**
2790
+ * Pin or unpin a skill (`.pinned` marker). Pinned skills are protected from
2791
+ * deletion, from background-review writes, and from the lifecycle — a
2792
+ * protective mutation, so the autonomous pipeline may never call it. The
2793
+ * marker write is the only state change; content is untouched.
2794
+ */
2795
+ async setPinned(name, pinned, origin = "foreground") {
2796
+ const normalized = name.trim();
2797
+ if (!SKILL_NAME_RE.test(normalized) || normalized.length > this.limits.maxNameLength) return {
2798
+ ok: false,
2799
+ message: `Invalid skill name "${normalized}". Use lowercase letters, digits, and hyphens (<= ${this.limits.maxNameLength}).`
2800
+ };
2801
+ if (origin === "background_review") return {
2802
+ ok: false,
2803
+ message: "Only the foreground (user or the main agent) may pin or unpin skills."
2804
+ };
2805
+ const dir = this.dirOf(normalized);
2806
+ const marker = markerPath(dir, "pinned");
2807
+ const existing = await this.io.exists(marker);
2808
+ if (pinned && existing) return {
2809
+ ok: true,
2810
+ message: `Skill "${normalized}" is already pinned.`,
2811
+ path: dir
2812
+ };
2813
+ if (!pinned && !existing) return {
2814
+ ok: true,
2815
+ message: `Skill "${normalized}" is not pinned; nothing to do.`,
2816
+ path: dir
2817
+ };
2818
+ if (!await this.io.exists(join(dir, "SKILL.md"))) return {
2819
+ ok: false,
2820
+ message: `Skill "${normalized}" not found.`
2821
+ };
2822
+ if (pinned) await this.io.writeText(marker, "");
2823
+ else await this.io.remove(marker);
2824
+ await this.audit(normalized, pinned ? "pin" : "unpin", null, null, pinned ? "pinned" : "unpinned");
2825
+ return {
2826
+ ok: true,
2827
+ message: pinned ? `Skill "${normalized}" pinned: protected from deletion, background review, and the lifecycle.` : `Skill "${normalized}" unpinned.`,
2828
+ path: dir
2829
+ };
2830
+ }
2831
+ async create(name, content, origin = "foreground") {
1127
2832
  const normalized = name.trim();
1128
2833
  if (!SKILL_NAME_RE.test(normalized) || normalized.length > this.limits.maxNameLength) return {
1129
2834
  ok: false,
@@ -1139,26 +2844,39 @@ var SkillLibrary = class {
1139
2844
  ok: false,
1140
2845
  message: threat
1141
2846
  };
1142
- const dir = skillDir(this.root, normalized);
2847
+ const dir = this.dirOf(normalized);
1143
2848
  if (await this.io.exists(join(dir, "SKILL.md"))) return {
1144
2849
  ok: false,
1145
2850
  message: `Skill "${normalized}" already exists.`
1146
2851
  };
1147
2852
  await this.io.writeText(join(dir, "SKILL.md"), content.trimEnd() + "\n");
1148
- if (origin === "background_review") await this.io.writeText(markerPath(dir, "hermes-managed"), "");
2853
+ if (origin !== "foreground") await this.io.writeText(markerPath(dir, "hermes-managed"), "");
2854
+ await this.audit(normalized, "create", null, content, "created");
2855
+ this.notifyMutation({
2856
+ action: "create",
2857
+ name: normalized,
2858
+ filePath: dir
2859
+ });
1149
2860
  return {
1150
2861
  ok: true,
1151
2862
  message: `Skill "${normalized}" created.`,
1152
2863
  path: dir
1153
2864
  };
1154
2865
  }
1155
- async update(name, content) {
1156
- const dir = skillDir(this.root, name);
1157
- if (!await this.io.readText(join(dir, "SKILL.md"))) return {
2866
+ async update(rawName, content, origin = "foreground") {
2867
+ const name = rawName.trim();
2868
+ const badName = this.badName(name);
2869
+ if (badName) return {
2870
+ ok: false,
2871
+ message: badName
2872
+ };
2873
+ const dir = this.dirOf(name);
2874
+ const md = await this.io.readText(join(dir, "SKILL.md"));
2875
+ if (!md) return {
1158
2876
  ok: false,
1159
2877
  message: `Skill "${name}" not found.`
1160
2878
  };
1161
- const protection = await this.writeProtection(name);
2879
+ const protection = await this.writeProtection(name, origin);
1162
2880
  if (protection) return {
1163
2881
  ok: false,
1164
2882
  message: `Skill "${name}" is protected (${protection}).`
@@ -1174,20 +2892,32 @@ var SkillLibrary = class {
1174
2892
  message: threat
1175
2893
  };
1176
2894
  await this.io.writeText(join(dir, "SKILL.md"), content.trimEnd() + "\n");
2895
+ await this.audit(name, "update", md, content, "updated");
2896
+ this.notifyMutation({
2897
+ action: "update",
2898
+ name,
2899
+ filePath: dir
2900
+ });
1177
2901
  return {
1178
2902
  ok: true,
1179
2903
  message: `Skill "${name}" updated.`,
1180
2904
  path: dir
1181
2905
  };
1182
2906
  }
1183
- async patch(name, oldString, newString, filePath = "", replaceAll = false) {
1184
- const dir = skillDir(this.root, name);
2907
+ async patch(rawName, oldString, newString, filePath = "", replaceAll = false, origin = "foreground") {
2908
+ const name = rawName.trim();
2909
+ const badName = this.badName(name);
2910
+ if (badName) return {
2911
+ ok: false,
2912
+ message: badName
2913
+ };
2914
+ const dir = this.dirOf(name);
1185
2915
  const skillMd = join(dir, "SKILL.md");
1186
2916
  if (!await this.io.exists(skillMd)) return {
1187
2917
  ok: false,
1188
2918
  message: `Skill "${name}" not found.`
1189
2919
  };
1190
- const protection = await this.writeProtection(name);
2920
+ const protection = await this.writeProtection(name, origin);
1191
2921
  if (protection) return {
1192
2922
  ok: false,
1193
2923
  message: `Skill "${name}" is protected (${protection}).`
@@ -1209,7 +2939,7 @@ var SkillLibrary = class {
1209
2939
  message: `File not found: ${patchLabel}`
1210
2940
  };
1211
2941
  const patched = fuzzyPatch(md, oldString, newString, replaceAll);
1212
- if (!patched) return {
2942
+ if (patched === null) return {
1213
2943
  ok: false,
1214
2944
  message: `Could not find old_string in "${name}/${patchLabel}". Use update for a full rewrite.`
1215
2945
  };
@@ -1226,7 +2956,7 @@ var SkillLibrary = class {
1226
2956
  };
1227
2957
  if (patched.length > this.limits.maxSkillContentChars && target === skillMd) return {
1228
2958
  ok: false,
1229
- message: `Patched content exceeds ${this.limits.maxSkillContentChars} characters.`
2959
+ message: `Patched content exceeds ${this.limits.maxSkillContentChars} characters. Consider splitting into a smaller SKILL.md with supporting files.`
1230
2960
  };
1231
2961
  const threat = scanContentThreats(patched);
1232
2962
  if (threat) return {
@@ -1234,40 +2964,69 @@ var SkillLibrary = class {
1234
2964
  message: threat
1235
2965
  };
1236
2966
  await this.io.writeText(target, patched.trimEnd() + "\n");
2967
+ await this.audit(name, "patch", md, patched, `patched ${patchLabel}`);
2968
+ this.notifyMutation({
2969
+ action: "patch",
2970
+ name,
2971
+ filePath: dir
2972
+ });
1237
2973
  return {
1238
2974
  ok: true,
1239
2975
  message: `Skill "${name}" patched (${patchLabel}).`,
1240
2976
  path: dir
1241
2977
  };
1242
2978
  }
1243
- async archive(name, absorbedInto = "") {
1244
- const dir = skillDir(this.root, name);
1245
- if (!await this.io.readText(join(dir, "SKILL.md"))) return {
2979
+ async archive(rawName, options = {}) {
2980
+ const name = rawName.trim();
2981
+ const badName = this.badName(name);
2982
+ if (badName) return {
2983
+ ok: false,
2984
+ message: badName
2985
+ };
2986
+ const dir = this.dirOf(name);
2987
+ const md = await this.io.readText(join(dir, "SKILL.md"));
2988
+ if (!md) return {
1246
2989
  ok: false,
1247
2990
  message: `Skill "${name}" not found.`
1248
2991
  };
1249
- const protection = await this.deleteProtection(name);
2992
+ const protection = await this.deleteProtection(name, options.allowBundled === void 0 ? {} : { allowBundled: options.allowBundled });
1250
2993
  if (protection) return {
1251
2994
  ok: false,
1252
2995
  message: `Skill "${name}" is protected (${protection}).`
1253
2996
  };
1254
- if (absorbedInto) {
1255
- if (!await this.io.readText(join(skillDir(this.root, absorbedInto), "SKILL.md"))) return {
2997
+ if (options.absorbedInto) {
2998
+ if (!await this.io.readText(join(this.dirOf(options.absorbedInto), "SKILL.md"))) return {
1256
2999
  ok: false,
1257
- message: `absorbed_into="${absorbedInto}" does not exist.`
3000
+ message: `absorbed_into="${options.absorbedInto}" does not exist.`
1258
3001
  };
1259
3002
  }
1260
3003
  const archiveRoot = join(this.root, ".archive");
1261
- let dest = join(archiveRoot, name);
1262
- if (await this.io.exists(dest)) dest = join(archiveRoot, `${name}-${(/* @__PURE__ */ new Date()).toISOString().replace(/[-:T]/g, "").slice(0, 14)}`);
3004
+ let dest = join(archiveRoot, name.trim());
3005
+ if (await this.io.exists(dest)) {
3006
+ const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[-:T]/g, "").slice(0, 14);
3007
+ dest = join(archiveRoot, `${name.trim()}-${stamp}`);
3008
+ while (await this.io.exists(dest)) dest = join(archiveRoot, `${name.trim()}-${stamp}-${Math.random().toString(36).slice(2, 8)}`);
3009
+ }
3010
+ if (this.io.isSymlink) {
3011
+ if (await this.io.isSymlink(dir) === true) return {
3012
+ ok: false,
3013
+ message: `Skill "${name}" is a symlink; refusing to archive it.`
3014
+ };
3015
+ }
1263
3016
  try {
1264
3017
  await this.io.rename(dir, dest);
1265
3018
  } catch {
1266
3019
  await this.io.copy(dir, dest);
1267
3020
  await this.io.remove(dir);
1268
3021
  }
1269
- const reason = absorbedInto ? `Consolidated into ${absorbedInto}` : "Archived by self-evolution curator";
3022
+ const reason = options.reason ?? (options.absorbedInto ? `Consolidated into ${options.absorbedInto}` : "Archived by self-evolution curator");
1270
3023
  await this.io.writeText(join(dest, ".archive-reason"), `${(/* @__PURE__ */ new Date()).toISOString()}: ${reason}\n`);
3024
+ await this.audit(name, "archive", md, null, reason);
3025
+ this.notifyMutation({
3026
+ action: "archive",
3027
+ name,
3028
+ archivedPath: dest
3029
+ });
1271
3030
  return {
1272
3031
  ok: true,
1273
3032
  message: `Skill "${name}" archived to .archive.`,
@@ -1278,67 +3037,342 @@ var SkillLibrary = class {
1278
3037
  * Merge the bodies of `sources` into `target` and archive the sources with
1279
3038
  * an absorbed-into marker. Hermes-style consolidation: overlapping skills
1280
3039
  * collapse into one, and the originals stay recoverable under `.archive/`.
3040
+ *
3041
+ * `mode:'append'` (default) appends each source body to the target. The
3042
+ * target write goes through the tree-change kernel (009) — byte-level
3043
+ * rollback, audit and the mutation event are kernel-owned. Package-integrity
3044
+ * (009-I): append-mode consolidation REFUSES a source whose directory has
3045
+ * support files or whose body carries support-directory links — an append
3046
+ * would leave those references pointing at an archived package (dangling);
3047
+ * the refusal message directs to the reference mode / whole-package archive.
3048
+ *
3049
+ * `mode:'reference'` writes each source's body (frontmatter stripped) into
3050
+ * `target/references/<source>.md` and archives the source — the demote path
3051
+ * (009-II). A source body with support-directory links is refused there too
3052
+ * (the references file would carry links whose files were archived).
1281
3053
  */
1282
- async consolidate(target, sources) {
1283
- const normalizedSources = [...new Set(sources)].filter((name) => name !== target);
3054
+ async consolidate(target, sources, origin = "foreground", options = {}) {
3055
+ const targetName = target.trim();
3056
+ const normalizedSources = [...new Set(sources.map((name) => name.trim()))].filter((name) => name !== targetName);
3057
+ const mode = options.mode ?? "append";
1284
3058
  if (normalizedSources.length === 0) return {
1285
3059
  ok: false,
1286
3060
  message: "Consolidation requires at least one distinct source skill."
1287
3061
  };
1288
- for (const name of [target, ...normalizedSources]) if (!SKILL_NAME_RE.test(name)) return {
3062
+ for (const name of [targetName, ...normalizedSources]) if (!SKILL_NAME_RE.test(name)) return {
1289
3063
  ok: false,
1290
3064
  message: `Invalid skill name "${name}". Use lowercase letters, digits, and hyphens.`
1291
3065
  };
1292
- const targetDir = skillDir(this.root, target);
3066
+ const targetDir = this.dirOf(targetName);
1293
3067
  const targetMd = await this.io.readText(join(targetDir, "SKILL.md"));
1294
3068
  if (!targetMd) return {
1295
3069
  ok: false,
1296
- message: `Skill "${target}" not found.`
3070
+ message: `Skill "${targetName}" not found.`
1297
3071
  };
1298
- const targetProtection = await this.writeProtection(target);
3072
+ const targetProtection = await this.writeProtection(targetName, origin);
1299
3073
  if (targetProtection) return {
1300
3074
  ok: false,
1301
- message: `Skill "${target}" is protected (${targetProtection}).`
3075
+ message: `Skill "${targetName}" is protected (${targetProtection}).`
1302
3076
  };
1303
- const parts = [];
1304
- for (const source of normalizedSources) {
1305
- const protection = await this.deleteProtection(source);
1306
- if (protection) return {
3077
+ const writes = [];
3078
+ if (mode === "append") {
3079
+ const parts = [];
3080
+ for (const source of normalizedSources) {
3081
+ const protection = await this.deleteProtection(source);
3082
+ if (protection) return {
3083
+ ok: false,
3084
+ message: `Skill "${source}" is protected (${protection}).`
3085
+ };
3086
+ const sourceMd = await this.io.readText(join(this.dirOf(source), "SKILL.md"));
3087
+ if (!sourceMd) return {
3088
+ ok: false,
3089
+ message: `Skill "${source}" not found.`
3090
+ };
3091
+ const parsed = parseFrontmatter(sourceMd);
3092
+ if (!parsed) return {
3093
+ ok: false,
3094
+ message: `Skill "${source}" has no valid frontmatter; refusing to merge.`
3095
+ };
3096
+ if (await this.countSupportDirs(source) > 0) return {
3097
+ ok: false,
3098
+ message: `Consolidation rejected: source "${source}" carries support files — use mode:'reference' or archive the whole package instead.`
3099
+ };
3100
+ const refs = supportRefs(parsed.body);
3101
+ if (refs.length > 0) return {
3102
+ ok: false,
3103
+ message: `Consolidation rejected: source "${source}" body references support files (${refs.join(", ")}) that would be left behind — use mode:'reference' or archive the whole package instead.`
3104
+ };
3105
+ parts.push(`\n<!-- consolidated from ${source} at ${(/* @__PURE__ */ new Date()).toISOString()} -->\n${parsed.body.trim()}`);
3106
+ }
3107
+ const merged = targetMd.trimEnd() + parts.join("\n") + "\n";
3108
+ const validation = validateFrontmatter(merged, targetName, this.limits);
3109
+ if (validation) return {
1307
3110
  ok: false,
1308
- message: `Skill "${source}" is protected (${protection}).`
3111
+ message: `Consolidation rejected: ${validation}`
1309
3112
  };
1310
- const sourceMd = await this.io.readText(join(skillDir(this.root, source), "SKILL.md"));
1311
- if (!sourceMd) return {
3113
+ writes.push({
3114
+ target: join(targetDir, "SKILL.md"),
3115
+ content: merged
3116
+ });
3117
+ } else {
3118
+ for (const source of normalizedSources) {
3119
+ const protection = await this.deleteProtection(source);
3120
+ if (protection) return {
3121
+ ok: false,
3122
+ message: `Skill "${source}" is protected (${protection}).`
3123
+ };
3124
+ const sourceMd = await this.io.readText(join(this.dirOf(source), "SKILL.md"));
3125
+ if (!sourceMd) return {
3126
+ ok: false,
3127
+ message: `Skill "${source}" not found.`
3128
+ };
3129
+ const parsed = parseFrontmatter(sourceMd);
3130
+ if (!parsed) return {
3131
+ ok: false,
3132
+ message: `Skill "${source}" has no valid frontmatter; refusing to demote.`
3133
+ };
3134
+ const refs = supportRefs(parsed.body);
3135
+ if (refs.length > 0) return {
3136
+ ok: false,
3137
+ message: `Consolidation rejected: source "${source}" body references support files (${refs.join(", ")}) that would be left behind — archive the whole package instead.`
3138
+ };
3139
+ const target = join(targetDir, "references", `${source}.md`);
3140
+ writes.push({
3141
+ target,
3142
+ content: `<!-- demoted from ${source} at ${(/* @__PURE__ */ new Date()).toISOString()} -->\n${parsed.body.trim()}\n`
3143
+ });
3144
+ }
3145
+ const pointerLines = normalizedSources.map((source) => `\n> 详见 references/${source}.md`).join("");
3146
+ const extended = targetMd.trimEnd() + pointerLines + "\n";
3147
+ const validation = validateFrontmatter(extended, targetName, this.limits);
3148
+ if (validation) return {
1312
3149
  ok: false,
1313
- message: `Skill "${source}" not found.`
3150
+ message: `Consolidation rejected: ${validation}`
1314
3151
  };
1315
- const parsed = parseFrontmatter(sourceMd);
1316
- if (!parsed) return {
3152
+ writes.push({
3153
+ target: join(targetDir, "SKILL.md"),
3154
+ content: extended
3155
+ });
3156
+ }
3157
+ const archived = [];
3158
+ try {
3159
+ for (const source of normalizedSources) {
3160
+ const result = await this.archive(source, { absorbedInto: targetName });
3161
+ if (!result.ok) throw new Error(result.message);
3162
+ archived.push(source);
3163
+ }
3164
+ const result = await this.applyTreeChange({
3165
+ name: targetName,
3166
+ origin,
3167
+ protection: "write",
3168
+ writes,
3169
+ auditAction: "consolidate",
3170
+ auditSummary: `consolidated ${normalizedSources.join(", ")} (${mode}) into ${targetName}`,
3171
+ eventAction: "consolidate"
3172
+ });
3173
+ if (!result.ok) throw new Error(result.message);
3174
+ } catch (error) {
3175
+ for (const source of archived.reverse()) await this.restoreFromArchive(source).catch(() => {});
3176
+ return {
1317
3177
  ok: false,
1318
- message: `Skill "${source}" has no valid frontmatter; refusing to merge.`
3178
+ message: `Consolidation failed and was rolled back: ${error instanceof Error ? error.message : String(error)}`
1319
3179
  };
1320
- parts.push(`\n<!-- consolidated from ${source} at ${(/* @__PURE__ */ new Date()).toISOString()} -->\n${parsed.body.trim()}`);
1321
3180
  }
1322
- const merged = targetMd.trimEnd() + parts.join("\n") + "\n";
1323
- const validation = validateFrontmatter(merged, target, this.limits);
1324
- if (validation) return {
3181
+ return {
3182
+ ok: true,
3183
+ message: `Consolidated ${normalizedSources.join(", ")} into "${targetName}".`,
3184
+ path: targetDir
3185
+ };
3186
+ }
3187
+ /**
3188
+ * Content-distribution repair (008 batch B, 009-R kernel): move body
3189
+ * sections — anchored by their exact `## heading` lines — into references/
3190
+ * support files and replace each span with a pointer line. The skill
3191
+ * name/dir never change (routing stays; only content location shifts, so a
3192
+ * fat body sheds its log-like detail). Deterministic, never automatic:
3193
+ * candidates come from an approved review plan. The write batch goes
3194
+ * through the tree-change kernel — one commit point, byte-level rollback.
3195
+ * Package integrity (009-R): a moved section whose text carries
3196
+ * support-directory links is refused (those links' files stay behind in the
3197
+ * same package; the moved text belongs in references/ beside them).
3198
+ */
3199
+ async restructure(rawName, moves, origin = "foreground") {
3200
+ const name = rawName.trim();
3201
+ const badName = this.badName(name);
3202
+ if (badName) return {
1325
3203
  ok: false,
1326
- message: `Consolidation rejected: ${validation}`
3204
+ message: badName
1327
3205
  };
1328
- const threat = scanContentThreats(merged);
1329
- if (threat) return {
3206
+ if (moves.length === 0) return {
1330
3207
  ok: false,
1331
- message: threat
3208
+ message: "Restructure requires at least one section move."
3209
+ };
3210
+ if (moves.length > 5) return {
3211
+ ok: false,
3212
+ message: `Restructure exceeds 5 moves.`
3213
+ };
3214
+ for (const move of moves) {
3215
+ if (typeof move.heading !== "string" || !move.heading.trim()) return {
3216
+ ok: false,
3217
+ message: "Every restructure move needs a non-empty heading."
3218
+ };
3219
+ if (!RESTRUCTURE_TARGET_RE.test(move.toFile)) return {
3220
+ ok: false,
3221
+ message: `toFile must be references/<topic>.md (got "${move.toFile}").`
3222
+ };
3223
+ }
3224
+ const dir = this.dirOf(name);
3225
+ const md = await this.io.readText(join(dir, "SKILL.md"));
3226
+ if (!md) return {
3227
+ ok: false,
3228
+ message: `Skill "${name}" not found.`
3229
+ };
3230
+ const normalized = md.replace(/\r\n/g, "\n");
3231
+ const plan = planRestructureSections(normalized, moves);
3232
+ if ("error" in plan) return {
3233
+ ok: false,
3234
+ message: `Restructure rejected: ${plan.error}`
3235
+ };
3236
+ const frontmatterEnd = normalized.indexOf("\n---", 3);
3237
+ if (frontmatterEnd < 0) return {
3238
+ ok: false,
3239
+ message: "SKILL.md has no valid frontmatter; refusing to restructure."
3240
+ };
3241
+ const newMd = normalized.slice(0, frontmatterEnd + 4) + plan.body;
3242
+ const newMdCheck = validateFrontmatter(newMd, name, this.limits);
3243
+ if (newMdCheck) return {
3244
+ ok: false,
3245
+ message: `Restructure rejected: ${newMdCheck}`
1332
3246
  };
1333
- await this.io.writeText(join(targetDir, "SKILL.md"), merged);
1334
- for (const source of normalizedSources) {
1335
- const archived = await this.archive(source, target);
1336
- if (!archived.ok) return archived;
3247
+ for (const section of plan.sections) {
3248
+ const refs = supportRefs(section.text);
3249
+ if (refs.length > 0) return {
3250
+ ok: false,
3251
+ message: `Restructure rejected: section "## ${section.heading}" references support files (${refs.join(", ")}) that stay behind — split the section or move it with its files.`
3252
+ };
3253
+ }
3254
+ const byRel = /* @__PURE__ */ new Map();
3255
+ for (const section of plan.sections) {
3256
+ const entry = byRel.get(section.rel) ?? {
3257
+ rel: section.rel,
3258
+ texts: []
3259
+ };
3260
+ entry.texts.push(section.text);
3261
+ byRel.set(section.rel, entry);
3262
+ }
3263
+ const writes = [];
3264
+ for (const entry of byRel.values()) {
3265
+ const target = join(dir, ...entry.rel.split("/"));
3266
+ const base = (await this.io.readText(target).catch(() => null))?.trimEnd() ?? "";
3267
+ writes.push({
3268
+ target,
3269
+ content: base === "" ? entry.texts.join("\n\n") : `${base}\n\n${entry.texts.join("\n\n")}`
3270
+ });
1337
3271
  }
3272
+ writes.push({
3273
+ target: join(dir, "SKILL.md"),
3274
+ content: newMd
3275
+ });
3276
+ const result = await this.applyTreeChange({
3277
+ name,
3278
+ origin,
3279
+ protection: "write",
3280
+ writes,
3281
+ auditAction: "restructure",
3282
+ auditSummary: `moved ${plan.sections.length} section(s): ${[...byRel.keys()].join(", ")}`,
3283
+ eventAction: "restructure"
3284
+ });
3285
+ if (!result.ok) return result;
1338
3286
  return {
1339
3287
  ok: true,
1340
- message: `Consolidated ${normalizedSources.join(", ")} into "${target}".`,
1341
- path: targetDir
3288
+ message: `Restructured "${name}": moved ${plan.sections.length} section(s) to references/.`,
3289
+ path: dir
3290
+ };
3291
+ }
3292
+ /**
3293
+ * Unified tree-change commit point (009 kernel): owns validation order,
3294
+ * pre-read rollback bytes, two-phase write with byte-level rollback, audit
3295
+ * and the mutation event. Mutators compose `TreeChangePlan`s — consolidate,
3296
+ * restructure (and future reference-mode consolidations) never implement
3297
+ * two-phase commit themselves.
3298
+ */
3299
+ async applyTreeChange(plan) {
3300
+ const name = plan.name.trim();
3301
+ const badName = this.badName(name);
3302
+ if (badName) return {
3303
+ ok: false,
3304
+ message: badName
3305
+ };
3306
+ const dir = this.dirOf(name);
3307
+ const md = await this.io.readText(join(dir, "SKILL.md"));
3308
+ if (!md) return {
3309
+ ok: false,
3310
+ message: `Skill "${name}" not found.`
3311
+ };
3312
+ const protection = plan.protection === "write" ? await this.writeProtection(name, plan.origin) : plan.protection === "delete" ? await this.deleteProtection(name) : null;
3313
+ if (protection) return {
3314
+ ok: false,
3315
+ message: `Skill "${name}" is protected (${protection}).`
3316
+ };
3317
+ for (const precondition of plan.preconditions ?? []) {
3318
+ const issue = await precondition({ dir });
3319
+ if (issue) return {
3320
+ ok: false,
3321
+ message: issue
3322
+ };
3323
+ }
3324
+ const landing = [];
3325
+ for (const write of plan.writes) {
3326
+ const previous = await this.io.readText(write.target).catch(() => null);
3327
+ if (Buffer.byteLength(write.content, "utf8") > this.limits.maxSkillFileBytes) return {
3328
+ ok: false,
3329
+ message: `Write exceeds ${this.limits.maxSkillFileBytes} bytes: ${write.target}`
3330
+ };
3331
+ const threat = scanContentThreats(write.content);
3332
+ if (threat) return {
3333
+ ok: false,
3334
+ message: threat
3335
+ };
3336
+ landing.push({
3337
+ target: write.target,
3338
+ content: write.content,
3339
+ previous
3340
+ });
3341
+ }
3342
+ const semantic = plan.validate?.({
3343
+ dir,
3344
+ currentMd: md
3345
+ }) ?? null;
3346
+ if (semantic) return {
3347
+ ok: false,
3348
+ message: semantic
3349
+ };
3350
+ const written = [];
3351
+ try {
3352
+ for (const entry of landing) {
3353
+ await this.io.writeText(entry.target, entry.content);
3354
+ written.push({
3355
+ target: entry.target,
3356
+ previous: entry.previous
3357
+ });
3358
+ }
3359
+ } catch (error) {
3360
+ for (const entry of written.reverse()) await (entry.previous === null ? this.io.remove(entry.target) : this.io.writeText(entry.target, entry.previous)).catch(() => {});
3361
+ return {
3362
+ ok: false,
3363
+ message: `Tree change failed and was rolled back: ${error instanceof Error ? error.message : String(error)}`
3364
+ };
3365
+ }
3366
+ await this.audit(name, plan.auditAction, md, landing.find((entry) => entry.target.endsWith("SKILL.md"))?.content ?? md, plan.auditSummary);
3367
+ this.notifyMutation({
3368
+ action: plan.eventAction,
3369
+ name,
3370
+ filePath: dir
3371
+ });
3372
+ return {
3373
+ ok: true,
3374
+ message: `${plan.eventAction} "${name}" succeeded.`,
3375
+ path: dir
1342
3376
  };
1343
3377
  }
1344
3378
  /**
@@ -1346,12 +3380,13 @@ var SkillLibrary = class {
1346
3380
  * recoverability: archival never deletes, and this is the control-plane
1347
3381
  * path back. The `.archive-reason` marker is dropped on restore.
1348
3382
  */
1349
- async restoreFromArchive(name) {
3383
+ async restoreFromArchive(rawName) {
3384
+ const name = rawName.trim();
1350
3385
  if (!SKILL_NAME_RE.test(name)) return {
1351
3386
  ok: false,
1352
3387
  message: `Invalid skill name "${name}". Use lowercase letters, digits, and hyphens.`
1353
3388
  };
1354
- if (await this.io.exists(join(skillDir(this.root, name), "SKILL.md"))) return {
3389
+ if (await this.io.exists(join(this.dirOf(name), "SKILL.md"))) return {
1355
3390
  ok: false,
1356
3391
  message: `Skill "${name}" already exists in the active root; refusing to overwrite.`
1357
3392
  };
@@ -1371,7 +3406,13 @@ var SkillLibrary = class {
1371
3406
  message: `Skill "${name}" is not in .archive.`
1372
3407
  };
1373
3408
  const source = join(archiveRoot, chosen);
1374
- const dest = skillDir(this.root, name);
3409
+ const dest = this.dirOf(name);
3410
+ if (this.io.isSymlink) {
3411
+ if (await this.io.isSymlink(source) === true) return {
3412
+ ok: false,
3413
+ message: `Archived entry "${chosen}" is a symlink; refusing to restore it.`
3414
+ };
3415
+ }
1375
3416
  try {
1376
3417
  await this.io.rename(source, dest);
1377
3418
  } catch {
@@ -1379,19 +3420,30 @@ var SkillLibrary = class {
1379
3420
  await this.io.remove(source);
1380
3421
  }
1381
3422
  if (await this.io.exists(join(dest, ".archive-reason"))) await this.io.remove(join(dest, ".archive-reason"));
3423
+ this.notifyMutation({
3424
+ action: "restore",
3425
+ name,
3426
+ filePath: dest
3427
+ });
1382
3428
  return {
1383
3429
  ok: true,
1384
3430
  message: `Skill "${name}" restored from .archive.`,
1385
3431
  path: dest
1386
3432
  };
1387
3433
  }
1388
- async writeSupportFile(name, filePath, content) {
1389
- const dir = skillDir(this.root, name);
3434
+ async writeSupportFile(rawName, filePath, content, origin = "foreground") {
3435
+ const name = rawName.trim();
3436
+ const badName = this.badName(name);
3437
+ if (badName) return {
3438
+ ok: false,
3439
+ message: badName
3440
+ };
3441
+ const dir = this.dirOf(name);
1390
3442
  if (!await this.io.exists(join(dir, "SKILL.md"))) return {
1391
3443
  ok: false,
1392
3444
  message: `Skill "${name}" not found.`
1393
3445
  };
1394
- const protection = await this.writeProtection(name);
3446
+ const protection = await this.writeProtection(name, origin);
1395
3447
  if (protection) return {
1396
3448
  ok: false,
1397
3449
  message: `Skill "${name}" is protected (${protection}).`
@@ -1411,20 +3463,33 @@ var SkillLibrary = class {
1411
3463
  message: threat
1412
3464
  };
1413
3465
  const target = join(dir, ...filePath.replace(/\\/g, "/").split("/").filter(Boolean));
3466
+ const existing = await this.io.readText(target).catch(() => null);
1414
3467
  await this.io.writeText(target, content);
3468
+ await this.audit(name, "write_file", existing, content, `wrote ${filePath}`);
3469
+ this.notifyMutation({
3470
+ action: "write_file",
3471
+ name,
3472
+ filePath: target
3473
+ });
1415
3474
  return {
1416
3475
  ok: true,
1417
3476
  message: `Support file "${filePath}" written to "${name}".`,
1418
3477
  path: target
1419
3478
  };
1420
3479
  }
1421
- async removeSupportFile(name, filePath) {
1422
- const dir = skillDir(this.root, name);
3480
+ async removeSupportFile(rawName, filePath, origin = "foreground") {
3481
+ const name = rawName.trim();
3482
+ const badName = this.badName(name);
3483
+ if (badName) return {
3484
+ ok: false,
3485
+ message: badName
3486
+ };
3487
+ const dir = this.dirOf(name);
1423
3488
  if (!await this.io.exists(join(dir, "SKILL.md"))) return {
1424
3489
  ok: false,
1425
3490
  message: `Skill "${name}" not found.`
1426
3491
  };
1427
- const protection = await this.writeProtection(name);
3492
+ const protection = await this.writeProtection(name, origin);
1428
3493
  if (protection) return {
1429
3494
  ok: false,
1430
3495
  message: `Skill "${name}" is protected (${protection}).`
@@ -1439,24 +3504,88 @@ var SkillLibrary = class {
1439
3504
  ok: false,
1440
3505
  message: `File "${filePath}" not found in skill "${name}".`
1441
3506
  };
3507
+ const before = await this.io.readText(target).catch(() => null);
1442
3508
  await this.io.remove(target);
3509
+ await this.audit(name, "remove_file", before, null, `removed ${filePath}`);
3510
+ this.notifyMutation({
3511
+ action: "remove_file",
3512
+ name,
3513
+ filePath: target
3514
+ });
1443
3515
  return {
1444
3516
  ok: true,
1445
3517
  message: `Support file "${filePath}" removed from "${name}".`,
1446
3518
  path: target
1447
3519
  };
1448
3520
  }
1449
- async snapshotAll(reason = "pre-mutation") {
1450
- const dest = join(join(this.root, ".backups"), `skills-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}`);
3521
+ /**
3522
+ * Snapshot the recoverable skills state: active tree, usage/suppression
3523
+ * sidecars, `.archive/` and caller-supplied extras. `extras` are opaque
3524
+ * side files the Snapshot owner cares about (curator state); they are
3525
+ * listed in the manifest and only those names are ever read back.
3526
+ */
3527
+ async snapshotAll(reason = "pre-mutation", extras = []) {
3528
+ const backupRoot = join(this.root, ".backups");
3529
+ const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
3530
+ let dest = join(backupRoot, `skills-${stamp}`);
3531
+ while (await this.io.exists(dest)) dest = join(backupRoot, `skills-${stamp}-${Math.random().toString(36).slice(2, 8)}`);
1451
3532
  const names = await listNames(this.root, this.io);
1452
- for (const name of names) await this.io.copy(skillDir(this.root, name), join(dest, name));
3533
+ await Promise.all(names.map(async (name) => {
3534
+ await this.io.copy(this.dirOf(name), join(dest, name));
3535
+ }));
3536
+ const sidecars = [];
3537
+ for (const sidecar of [usageFile(this.root), suppressedFile(this.root)]) if (await this.io.exists(sidecar)) {
3538
+ const name = basename(sidecar);
3539
+ await this.io.copy(sidecar, join(dest, name));
3540
+ sidecars.push(name);
3541
+ }
3542
+ const archiveRoot = join(this.root, ".archive");
3543
+ let hasArchive = false;
3544
+ if (await this.io.exists(archiveRoot)) {
3545
+ await this.io.copy(archiveRoot, join(dest, ".archive"));
3546
+ hasArchive = true;
3547
+ }
3548
+ const validExtras = extras.filter((extra) => SNAPSHOT_EXTRA_NAME_RE.test(extra.name));
3549
+ const extraNames = validExtras.map((extra) => extra.name);
3550
+ await Promise.all(validExtras.map(async (extra) => {
3551
+ await this.io.writeText(join(dest, "extras", extra.name), extra.content);
3552
+ }));
1453
3553
  await this.io.writeText(join(dest, "manifest.json"), JSON.stringify({
1454
3554
  reason,
1455
3555
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1456
- skills: names
3556
+ skills: names,
3557
+ sidecars,
3558
+ hasArchive,
3559
+ extras: extraNames
1457
3560
  }, null, 2));
3561
+ await this.retainSnapshots(5);
1458
3562
  return dest;
1459
3563
  }
3564
+ /** Read and normalize a snapshot manifest; null when the file is missing or unparsable. */
3565
+ async readSnapshotManifest(path) {
3566
+ const raw = await this.io.readText(join(path, "manifest.json"));
3567
+ if (raw === null) return null;
3568
+ try {
3569
+ const manifest = JSON.parse(raw);
3570
+ return {
3571
+ reason: typeof manifest.reason === "string" ? manifest.reason : "",
3572
+ createdAt: typeof manifest.createdAt === "string" ? manifest.createdAt : "",
3573
+ skills: Array.isArray(manifest.skills) ? manifest.skills : [],
3574
+ sidecars: Array.isArray(manifest.sidecars) ? manifest.sidecars : [],
3575
+ ...typeof manifest.hasArchive === "boolean" ? { hasArchive: manifest.hasArchive } : {},
3576
+ extras: Array.isArray(manifest.extras) ? manifest.extras : []
3577
+ };
3578
+ } catch {
3579
+ return null;
3580
+ }
3581
+ }
3582
+ /** Keep only the newest N snapshots (Hermes keep=5 parity); older ones are removed outright. */
3583
+ async retainSnapshots(keep) {
3584
+ const snapshots = await this.listSnapshots();
3585
+ for (const snapshot of snapshots.slice(keep)) try {
3586
+ await this.io.remove(snapshot.path);
3587
+ } catch {}
3588
+ }
1460
3589
  async listSnapshots() {
1461
3590
  const backupRoot = join(this.root, ".backups");
1462
3591
  let entries;
@@ -1468,96 +3597,93 @@ var SkillLibrary = class {
1468
3597
  const out = [];
1469
3598
  for (const name of entries.sort().reverse()) {
1470
3599
  if (!name.startsWith("skills-")) continue;
1471
- try {
1472
- const raw = await this.io.readText(join(backupRoot, name, "manifest.json"));
1473
- if (raw === null) continue;
1474
- const manifest = JSON.parse(raw);
1475
- out.push({
1476
- path: join(backupRoot, name),
1477
- createdAt: manifest.createdAt ?? "",
1478
- reason: manifest.reason ?? ""
1479
- });
1480
- } catch {}
3600
+ const manifest = await this.readSnapshotManifest(join(backupRoot, name));
3601
+ if (manifest === null) continue;
3602
+ out.push({
3603
+ path: join(backupRoot, name),
3604
+ createdAt: manifest.createdAt,
3605
+ reason: manifest.reason
3606
+ });
1481
3607
  }
1482
3608
  return out;
1483
3609
  }
1484
- async restoreLatestSnapshot() {
3610
+ /**
3611
+ * Read the extras of a snapshot, restricted to the names declared in the
3612
+ * manifest — an `extras/` directory is never listed directly, so unknown
3613
+ * files cannot leak back as state on the next restore.
3614
+ */
3615
+ async readSnapshotExtras(path) {
3616
+ const manifest = await this.readSnapshotManifest(path);
3617
+ if (manifest === null) return [];
3618
+ const extras = [];
3619
+ for (const name of manifest.extras) {
3620
+ if (!SNAPSHOT_EXTRA_NAME_RE.test(name)) continue;
3621
+ const content = await this.io.readText(join(path, "extras", name));
3622
+ if (content !== null) extras.push({
3623
+ name,
3624
+ content
3625
+ });
3626
+ }
3627
+ return extras;
3628
+ }
3629
+ /**
3630
+ * Manifest-driven restore of the latest snapshot: active tree, sidecars,
3631
+ * `.archive/` and (for full-state snapshots) the extras read back by the
3632
+ * caller. `extras` are additionally written into the pre-rollback safety
3633
+ * snapshot so the rollback itself is undoable with the same state.
3634
+ */
3635
+ async restoreLatestSnapshot(extras = []) {
1485
3636
  const latest = (await this.listSnapshots())[0];
1486
3637
  if (!latest) return {
1487
3638
  ok: false,
1488
3639
  message: "No skill snapshot available."
1489
3640
  };
1490
- await this.snapshotAll("pre-rollback");
1491
- for (const name of await listNames(this.root, this.io)) await this.io.remove(skillDir(this.root, name));
1492
- const entries = await this.io.list(latest.path);
1493
- for (const entry of entries) {
1494
- if (entry === "manifest.json") continue;
3641
+ await this.snapshotAll("pre-rollback", extras);
3642
+ let rootEntries;
3643
+ try {
3644
+ rootEntries = await this.io.list(this.root);
3645
+ } catch {
3646
+ rootEntries = [];
3647
+ }
3648
+ for (const entry of rootEntries) {
3649
+ if (entry.startsWith(".")) continue;
3650
+ await this.io.remove(join(this.root, entry));
3651
+ }
3652
+ const manifest = await this.readSnapshotManifest(latest.path);
3653
+ if (manifest === null) for (const entry of await this.io.list(latest.path)) {
3654
+ if (entry === "manifest.json" || entry === "extras") continue;
1495
3655
  await this.io.copy(join(latest.path, entry), join(this.root, entry));
1496
3656
  }
3657
+ else {
3658
+ for (const name of manifest.skills) await this.io.copy(join(latest.path, name), join(this.root, name));
3659
+ for (const sidecar of manifest.sidecars) await this.io.copy(join(latest.path, sidecar), join(this.root, sidecar));
3660
+ const archiveRoot = join(this.root, ".archive");
3661
+ if (manifest.hasArchive === true) {
3662
+ await this.io.remove(archiveRoot);
3663
+ await this.io.copy(join(latest.path, ".archive"), archiveRoot);
3664
+ } else if (manifest.hasArchive === false) await this.io.remove(archiveRoot);
3665
+ }
3666
+ const snapshotExtras = await this.readSnapshotExtras(latest.path);
3667
+ this.notifyMutation({
3668
+ action: "restore",
3669
+ name: "snapshot"
3670
+ });
1497
3671
  return {
1498
3672
  ok: true,
1499
3673
  message: `Restored skill tree from ${latest.path}`,
1500
- path: latest.path
3674
+ path: latest.path,
3675
+ ...snapshotExtras.length === 0 ? {} : { extras: snapshotExtras }
1501
3676
  };
1502
3677
  }
1503
3678
  };
1504
3679
  //#endregion
1505
3680
  //#region lib/types/state-store.js
1506
3681
  /**
1507
- * Small crash-safe JSON state store for plugin-owned sidecar state.
1508
- * Writes are atomic (temp + rename). Reads are synchronous for startup use.
3682
+ * Evolution home path helper: `$DSH_HOME/evolution` for plugin-owned sidecar
3683
+ * state (reports, activity store, feedback file, state-domain data).
1509
3684
  */
1510
3685
  function evolutionHome(env = process.env) {
1511
3686
  return join(env.DSH_HOME ?? join(homedir(), ".dsh"), "evolution");
1512
3687
  }
1513
- var JsonState = class {
1514
- initial;
1515
- path;
1516
- value;
1517
- constructor(name, initial, env = process.env) {
1518
- this.initial = initial;
1519
- this.path = join(evolutionHome(env), name);
1520
- this.value = this.loadSync();
1521
- }
1522
- loadSync() {
1523
- try {
1524
- const raw = readFileSync(this.path, "utf8");
1525
- const parsed = JSON.parse(raw);
1526
- return {
1527
- ...this.initial,
1528
- ...parsed
1529
- };
1530
- } catch {
1531
- return { ...this.initial };
1532
- }
1533
- }
1534
- get() {
1535
- return this.value;
1536
- }
1537
- set(value) {
1538
- this.value = value;
1539
- }
1540
- update(mutator) {
1541
- mutator(this.value);
1542
- }
1543
- async flush() {
1544
- await mkdir(dirname(this.path), { recursive: true });
1545
- const tmp = `${this.path}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
1546
- await writeFile(tmp, JSON.stringify(this.value, null, 2), "utf8");
1547
- await rename(tmp, this.path);
1548
- }
1549
- /** Merge-on-load helper for persisted maps/records. */
1550
- async reload() {
1551
- try {
1552
- const raw = await readFile(this.path, "utf8");
1553
- this.value = {
1554
- ...this.initial,
1555
- ...JSON.parse(raw)
1556
- };
1557
- } catch {
1558
- this.value = { ...this.initial };
1559
- }
1560
- }
1561
- };
1562
3688
  //#endregion
1563
- 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, computeLifecycleTransitions, emptyRecord, evaluateThreat, evolutionHome, evolutionIoAdapter, foldTurn, getRecord, latestActivityAt, loadUsage, markAgentCreated, memoryRoot, nodeEvolutionIo, observeEvent, parseFrontmatter, reviewPrompt, saveUsage, scanContentThreats, scanMemoryThreats, scanThreats, skillsRoot, usageFile, validateFrontmatter, verifyPromptBundle };
3689
+ export { AUTHORING_DESCRIPTION_BAR, COMBINED_REVIEW_PLAN_PROMPT, COMBINED_REVIEW_PROMPT, COMPLETION_SKILL_REVIEW_PROMPT, CURATOR_DRY_RUN_BANNER, CURATOR_PROMPT, DEFAULT_ARCHIVE_AFTER_DAYS, DEFAULT_CONSOLIDATION_FAILURES, DEFAULT_CURATOR_INTERVAL_HOURS, DEFAULT_HEALTH_THRESHOLDS, DEFAULT_MAX_OPS_PER_PLAN, DEFAULT_MEMORY_CHAR_LIMIT, DEFAULT_MIN_IDLE_HOURS, DEFAULT_MUTATION_CAP, DEFAULT_REVIEW_MEMORY_INTERVAL, DEFAULT_REVIEW_SKILL_INTERVAL, DEFAULT_SKILL_CONTENT_CHARS, DEFAULT_SKILL_LIMITS, DEFAULT_SKILL_REVIEW_COMPLETION_MIN_TOOL_CALLS, DEFAULT_SKILL_REVIEW_TRIGGER, DEFAULT_STALE_AFTER_DAYS, DEFAULT_SUBSTANTIVE_MIN_AGENT_CHARS, DEFAULT_SUBSTANTIVE_MIN_TOOL_CALLS, DEFAULT_SUBSTANTIVE_MIN_USER_CHARS, DEFAULT_USER_CHAR_LIMIT, DSH_AUTHORING_STANDARDS, ENTRY_DELIMITER, EVENT_ARCHIVE_PREFIX, EVENT_LOG_RETAIN_ARCHIVES, EVENT_LOG_ROTATE_AT, EVENT_LOG_VERSION, EvolutionGateSet, LOW_QUALITY_THRESHOLD, MAX_DESCRIPTION_LENGTH, MAX_RESTRUCTURE_MOVES, 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, RESTRUCTURE_TARGET_RE, SKILLS_GUIDANCE, SKILL_NAME_RE, SKILL_REVIEW_PLAN_PROMPT, SKILL_REVIEW_PROMPT, SNAPSHOT_EXTRA_NAME_RE, SUPPORT_DIRS, SUPPRESSED_FILE_VERSION, SkillLibrary, advanceReview, appendEvolutionEvent, applyCuratorFields, applyCuratorLifecycleFields, applyCuratorMetaFields, assessStructureHealth, authoringFeedback, buildCuratorRunReport, buildLearnPrompt, bumpPatch, bumpUse, bumpView, computeDedupGroups, computeLifecycleTransitions, computePrefixClusters, computeQualityScores, computeScopeView, contentHash, createGateSet, emptyRecord, evaluateThreat, eventsFile, evolutionHome, evolutionIoAdapter, foldCuratorFields, foldTurn, getRecord, latestActivityAt, lifecycleCandidate, listEventArchives, loadMutations, loadSuppressedNames, loadUsage, markAgentCreated, memoryRoot, mutateUsage, mutationsFile, nodeEvolutionIo, normalizeUsageRecord, observeEvent, parseCuratorNominations, parseEvolutionEvents, parseFrontmatter, readEvolutionEvents, readEvolutionTimeline, recordMutation, relatedSkillNames, renderCuratorReportMarkdown, resolveOrigins, retainEventArchives, reviewPrompt, saveSuppressedNames, saveUsage, scanContentThreats, scanMemoryThreats, scanThreats, skillsRoot, suppressedFile, transactIo, updateSuppressedNames, usageFile, usageObserved, validateFrontmatter, verifyPromptBundle };