@lmzhen/dsh-evolution-core 0.41.0 → 0.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/lib/composition/index.js +2 -2
  2. package/lib/{composition-Da8NfRI7.js → composition-CVafrlEw.js} +2 -2
  3. package/lib/guards-3f02mnf2.js +29 -0
  4. package/lib/http-routes.js +205 -1
  5. package/lib/index.js +3584 -15050
  6. package/lib/mutations-jUuOPaCn.js +718 -0
  7. package/lib/platform/index.js +2 -2
  8. package/lib/{platform-CFp373_0.js → platform-B06_h8t-.js} +4 -1
  9. package/lib/runtime/plugin.js +2 -2
  10. package/lib/{session-projection-CXUNPkq9.js → session-projection-EB7mUOlJ.js} +63 -63
  11. package/lib/skill-health-BLGZTIv8.js +3773 -0
  12. package/lib/skill-history-_Cssts5o.js +1912 -0
  13. package/lib/skills.js +4067 -0
  14. package/lib/subagent/index.js +1 -1
  15. package/lib/types/home-fence.d.ts +7 -0
  16. package/lib/types/home-fence.js +58 -3
  17. package/lib/types/index.d.ts +1 -18
  18. package/lib/types/index.js +1 -18
  19. package/lib/types/io.js +1 -1
  20. package/lib/types/mutation-authority.d.ts +14 -37
  21. package/lib/types/mutation-authority.js +16 -103
  22. package/lib/types/mutation-storage-adapter.js +9 -6
  23. package/lib/types/mutation-unit.d.ts +14 -0
  24. package/lib/types/mutation-unit.js +30 -10
  25. package/lib/types/opt-in.js +1 -1
  26. package/lib/types/params.js +1 -1
  27. package/lib/types/platform/index.d.ts +8 -1
  28. package/lib/types/platform/index.js +3 -0
  29. package/lib/types/platform-services.js +0 -1
  30. package/lib/types/review-channel.js +3 -1
  31. package/lib/types/review-context.js +3 -1
  32. package/lib/types/run-registry.d.ts +2 -24
  33. package/lib/types/scope.js +1 -1
  34. package/lib/types/signals.d.ts +1 -1
  35. package/lib/types/skill-store.d.ts +7 -1
  36. package/lib/types/skill-store.js +43 -80
  37. package/lib/types/skills.d.ts +11 -0
  38. package/lib/types/skills.js +11 -0
  39. package/lib/types/subagent/types.d.ts +3 -3
  40. package/lib/types/tree-lock.js +4 -1
  41. package/lib/types/unit-claim.d.ts +8 -0
  42. package/lib/types/unit-claim.js +3 -0
  43. package/lib/types/unit-journal.d.ts +3 -1
  44. package/lib/types/unit-journal.js +12 -3
  45. package/lib/types/unit-storage.d.ts +1 -0
  46. package/lib/types/write-gates.d.ts +1 -1
  47. package/lib/types/write-gates.js +3 -1
  48. package/lib/types/write.d.ts +11 -0
  49. package/lib/types/write.js +11 -0
  50. package/lib/write.js +357 -0
  51. package/package.json +16 -4
  52. package/lib/http-routes-_anZVlPf.js +0 -233
  53. package/lib/types/unit-backend.d.ts +0 -5
  54. package/lib/types/unit-backend.js +0 -55
  55. package/lib/types/unit-transaction.d.ts +0 -225
  56. package/lib/types/unit-transaction.js +0 -501
  57. package/lib/{ensure-C5Mo1dbB.js → ensure-BjToTMMj.js} +1 -1
@@ -0,0 +1,3773 @@
1
+ import { B as supportFileReadFromPath, O as collectReadSkillNames, k as collectReadSupportFiles, l as sessionReadNames, o as isProjectableSession, q as resolveCitations, v as DEFAULT_SUPPORT_READ_TOOL_NAMES } from "./session-projection-EB7mUOlJ.js";
2
+ import { n as isRecord } from "./guards-3f02mnf2.js";
3
+ import { d as nodeEvolutionIo, p as transactIo, u as isProcessAlive } from "./mutations-jUuOPaCn.js";
4
+ import { dirname, join, resolve } from "node:path";
5
+ import { parse } from "yaml";
6
+ import { createHash, randomUUID } from "node:crypto";
7
+ import { homedir } from "node:os";
8
+ import { AsyncLocalStorage } from "node:async_hooks";
9
+ //#region lib/types/constants.js
10
+ /**
11
+ * Shared constants for the dsh-evolution plugin family.
12
+ *
13
+ * Two classes of value live here, deliberately separated by section so future
14
+ * edits do not blur the semantic boundary:
15
+ *
16
+ * 1. **Fixed protocol/format/security invariants** — changing these breaks an
17
+ * on-disk format, a naming/format contract, a path-security boundary, or a
18
+ * cross-component invariant. They are NOT exposed as deployment config.
19
+ *
20
+ * 2. **Cross-package shared tunable defaults** — the same semantic default is
21
+ * read (with a config override path) by more than one package (e.g.
22
+ * `evolution-policy` and `evolution-curator` both default `staleAfterDays`
23
+ * to 30). Centralizing them here means one authoritative default: a config
24
+ * override still applies per package, but the fallback is single-sourced.
25
+ *
26
+ * Package-private tunables (used by exactly one package) stay in that package,
27
+ * not here — see evolution-replay's `DEFAULT_WEIGHTS` and evolution-feedback's
28
+ * threshold, which are intentionally left where they are used.
29
+ * @module @lmzhen/dsh-evolution-core
30
+ */
31
+ /**
32
+ * Required argument names per `skill_manage` action — the SINGLE SOURCE read
33
+ * by the tool's argument gate (tool-skill-manage write-gates.ts) and the plan
34
+ * validator (evolution-plan-validator), so the two can never drift.
35
+ * OPT-05 (2026-09): the plan validator used to accept a `write_file`/
36
+ * `remove_file` op without `file_path` while the executor required it — the
37
+ * staged write then failed at EVERY approve until rejected.
38
+ * Rows here are the op-level requirements only: `delete` additionally
39
+ * requires `absorbed_into` at the PLAN layer (review passes may only delete
40
+ * into an umbrella) and `pin`/`unpin` are tool-only actions — each consumer
41
+ * adds its own extras on top of this table. An empty-string argument is NOT
42
+ * caught here (the tool's gate deliberately lets it reach the library for a
43
+ * more specific remedy message); the validator adds its own `.trim()`
44
+ * emptiness checks for payload fields.
45
+ */
46
+ const SKILL_ACTION_REQUIRED_FIELDS = {
47
+ create: ["name", "content"],
48
+ edit: ["name", "content"],
49
+ update: ["name", "content"],
50
+ patch: [
51
+ "name",
52
+ "old_string",
53
+ "new_string"
54
+ ],
55
+ delete: ["name"],
56
+ write_file: [
57
+ "name",
58
+ "file_path",
59
+ "file_content"
60
+ ],
61
+ remove_file: ["name", "file_path"],
62
+ restructure: ["name"],
63
+ pin: ["name"],
64
+ unpin: ["name"]
65
+ };
66
+ /** Skill frontmatter `name` validated for the file name (lowercase + hyphen).
67
+ * 计划 B-4 (v18): tightened to the UPSTREAM `SKILL_NAME` shape
68
+ * (`/^[a-z0-9]+(?:-[a-z0-9]+)*$/`, packages/skill/skill/src/index.ts:21). The
69
+ * old form admitted trailing/consecutive hyphens, which upstream
70
+ * `validateCandidate` throws on — and that throw aborts the WHOLE `ctx.skills`
71
+ * collection. The catalog provider still filters such legacy tree entries so
72
+ * an existing tree cannot break a session. */
73
+ const SKILL_NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
74
+ /** Allowed skill support-file subdirectories (path-traversal boundary). */
75
+ const SUPPORT_DIRS = [
76
+ "references",
77
+ "templates",
78
+ "scripts",
79
+ "assets"
80
+ ];
81
+ /** Delimiter between durable memory entries (on-disk storage format). */
82
+ const ENTRY_DELIMITER = "\n§\n";
83
+ /** Built-in skill names the curator must never lifecycle-manage. */
84
+ const PROTECTED_BUILTIN_SKILLS = new Set(["plan"]);
85
+ const MAX_SKILL_NAME_LENGTH = 64;
86
+ const MAX_DESCRIPTION_LENGTH = 1024;
87
+ const MAX_SKILL_CONTENT_CHARS = 1e5;
88
+ /** How many content versions to retain per skill (skill-history.ts). 20 mirrors the count
89
+ * KiroCrew settled on for the same job (its `MAX_SKILL_VERSIONS`), and is an E2 deployment
90
+ * parameter — the value is a retention policy, not a protocol constant. */
91
+ const DEFAULT_SKILL_VERSION_KEEP = 20;
92
+ /** The authoring DISCIPLINE band, taken from the upstream standard (archive §5):
93
+ * peer skills sit at 8-14k characters and a body pushing past 20k belongs in
94
+ * `references/*.md`. Deliberately separate from `MAX_SKILL_CONTENT_CHARS`: the
95
+ * hard ceiling is a deployment-tunable limit, this band is the authoring
96
+ * standard — deriving the band from the ceiling is exactly what let a 40k
97
+ * ceiling hide a 99k body without a single signal saying "split me" (V3). */
98
+ const AUTHORING_SPLIT_LINE_CHARS = 2e4;
99
+ /** Upstream's conversion basis for CHARACTER LIMITS: 2.75 chars/token, labelled
100
+ * model-independent in the config template (\`cli-config.yaml.example:538\`), and the
101
+ * basis behind every quoted token figure there — memory 2200 chars ≈ 800 tokens,
102
+ * user 1375 ≈ 500, SKILL.md 100_000 ≈ 36k (\`tools/skill_manager_tool.py:455\`).
103
+ * Limits are deliberately conservative, so this is the basis a BORROWED LIMIT must
104
+ * be converted with. */
105
+ const UPSTREAM_LIMIT_CHARS_PER_TOKEN = 2.75;
106
+ /** The platform's own estimate basis: \`CHARS_PER_TOKEN = 4\` in
107
+ * \`@deepseek-ai/dsh-token-meter/estimate.ts\` (its comment reads "used until exact
108
+ * tokenization is needed"), matching upstream's ESTIMATE-side heuristic — "~4
109
+ * chars/token is the usual English heuristic" (\`agent/prompt_builder.py:1179\`).
110
+ * Estimates use this; limits use the constant above. */
111
+ const PLATFORM_ESTIMATE_CHARS_PER_TOKEN = 4;
112
+ const MAX_SKILL_FILE_BYTES = 1048576;
113
+ const DEFAULT_REVIEW_MEMORY_INTERVAL = 10;
114
+ const DEFAULT_REVIEW_SKILL_INTERVAL = 10;
115
+ /** Skill-review completion channel trigger mode: 'cadence' | 'completion' | 'both'.
116
+ * 0.3.39 (V6-53 follow-up): default is 'cadence' — since 0.3.38 the cadence
117
+ * channel's review is executed at conversation END (deferred), so 'both' would
118
+ * inject a second (task-complete) prompt at the same boundary; the cadence
119
+ * deferral alone IS the end-of-conversation summary. */
120
+ const DEFAULT_SKILL_REVIEW_TRIGGER = "cadence";
121
+ /** Cumulative session tool calls before a session counts as "proven long" for the completion channel. */
122
+ const DEFAULT_SKILL_REVIEW_COMPLETION_MIN_TOOL_CALLS = 20;
123
+ const DEFAULT_SUBSTANTIVE_MIN_TOOL_CALLS = 3;
124
+ const DEFAULT_SUBSTANTIVE_MIN_USER_CHARS = 200;
125
+ const DEFAULT_SUBSTANTIVE_MIN_AGENT_CHARS = 500;
126
+ const DEFAULT_CURATOR_INTERVAL_HOURS = 168;
127
+ const DEFAULT_MIN_IDLE_HOURS = 2;
128
+ const DEFAULT_STALE_AFTER_DAYS = 30;
129
+ const DEFAULT_ARCHIVE_AFTER_DAYS = 90;
130
+ /**
131
+ * Support-file count above which `references-sprawl` warns. **NOT CALIBRATED YET** — 60 is a
132
+ * placeholder: the platform corpus is empty (no platform skills available here), so the admission
133
+ * band cannot be checked. Until `gen-health-baseline` reports both corpora, the rule is
134
+ * REPORT-ONLY: its count must not be shown as a number on any surface (plan G4 ③).
135
+ */
136
+ const SUPPORT_SPRAWL_FILES = 60;
137
+ const DEFAULT_MEMORY_CHAR_LIMIT = 2200;
138
+ const DEFAULT_USER_CHAR_LIMIT = 1375;
139
+ /** Consolidation-failure backoff cap, shared by MemoryStore and memory-files' Config default. */
140
+ const DEFAULT_CONSOLIDATION_FAILURES = 3;
141
+ /** F-20 (v18): the authored-body budget and the hard ceiling are the same
142
+ * number today. Derive it so a future divergence is one edit, not two names
143
+ * that silently disagree. */
144
+ const DEFAULT_SKILL_CONTENT_CHARS = MAX_SKILL_CONTENT_CHARS;
145
+ /** P3-19 (v14): defaults that were written twice (schema `.default()` AND the
146
+ * clamp fallback literal) now have one home per value. */
147
+ const DEFAULT_REVIEW_TIMEOUT_MS = 12e4;
148
+ const DEFAULT_REVIEW_CONTEXT_MESSAGES = 60;
149
+ const DEFAULT_REVIEW_MESSAGE_CHARS = 2e3;
150
+ const DEFAULT_CURATOR_BOOT_GRACE_SECONDS = 10;
151
+ const DEFAULT_CURATOR_REVIEW_MAX_TOKENS = 2048;
152
+ /** Threat-scan WINDOW SIZE (not a total cap — E-12: the whole text is scanned in
153
+ * overlapping windows, so content beyond this stays in scope). The coverage
154
+ * floor is `PATTERN_OVERLAP + 1` (V6-05). Single home for the core scanners'
155
+ * default parameter and clamp fallback, plus evolution-threat's Config default
156
+ * — the two packages previously wrote 65_536 independently (G0/S0.1). */
157
+ const DEFAULT_THREAT_MAX_SCAN_CHARS = 65536;
158
+ /** 0.3.17 (S3.10, T-1): control-plane fields a model-facing write call may
159
+ * never carry — single source for plan-validator, evolution-policy and the
160
+ * threat scanner (they used to each hardcode the list).
161
+ * P2-13 (v37): staged_from_sha256 joins the list — it is the replay's own
162
+ * staleness anchor, and the tool-arguments root is an OPEN object, so a model
163
+ * could otherwise choose the anchor that decides the write's outcome. */
164
+ const FORBIDDEN_CONTROL_KEYS = [
165
+ "policy",
166
+ "threshold",
167
+ "prompt_hash",
168
+ "model_route",
169
+ "evolution_config",
170
+ "staged_from_sha256"
171
+ ];
172
+ /** 0.3.17 (S3.10): the model-facing write tools the policy guard and threat
173
+ * scanner cover. */
174
+ const EVOLUTION_WRITE_TOOLS = ["memory", "skill_manage"];
175
+ /** Hermes authoring quality bar for descriptions (the 60-char Rule). The
176
+ * platform's own index limit stays in validateFrontmatter; this bar is the
177
+ * target the authoring standard names, enforced as ADVISORY feedback.
178
+ * 0.3.16 (T-4): moved here from skill-store.ts so drift-signals (pure, no IO)
179
+ * can reference it without importing the skill-store module. */
180
+ const AUTHORING_DESCRIPTION_BAR = 60;
181
+ /** The PLATFORM's default cap on the description a skill catalog shows —
182
+ * `catalogDescriptionMaxLength` on the platform's `tool-skill` row (default 500).
183
+ *
184
+ * Recorded here because it is the third number in the description-length relationship, and the one
185
+ * that is easiest to misread as a family rule: the family's own host/all rows SET that field to
186
+ * `AUTHORING_DESCRIPTION_BAR` (60), so what a family deployment truncates at is the ROW's value —
187
+ * this default only governs compositions that do not override it. It is NOT a refusal threshold:
188
+ * the only refusal is `MAX_DESCRIPTION_LENGTH` / the row's `maxDescriptionLength`, and the catalog
189
+ * cut is a view, not a validation. See tool-skill-manage/README.md for the three-number table. */
190
+ const PLATFORM_CATALOG_DESCRIPTION_DEFAULT = 500;
191
+ /** The split hint both size refusals share (0.5.0 V1). The same sentence used to
192
+ * be copied into validateFrontmatter AND the patch path, and neither copy named
193
+ * where the content should go — the upstream cap message names the destination
194
+ * directories, and that is the part a model actually acts on. */
195
+ const CONTENT_SPLIT_HINT = "建议拆成更小的 SKILL.md,把支撑文件放进 references/ 或 templates/。";
196
+ /** V27 G2.4: the largest millisecond delay a timer accepts. `AbortSignal.timeout`
197
+ * (and `setTimeout`) coerce anything larger to 1ms after a Node warning, so a
198
+ * timeout configured above this ceiling silently collapses to "immediately
199
+ * aborted". The curator's review timeout and the review timeout each carried
200
+ * their own copy of the literal; the bound is one protocol constant.
201
+ * (v19 P2-10 corrected the value from 2^32-1 to Node's real 2^31-1 ceiling.) */
202
+ const MAX_TIMER_DELAY_MS = 2147483647;
203
+ /**
204
+ * Model-facing budget of one `maintenance_probe` call (ms) — a HANG GUARD, not a
205
+ * performance knob.
206
+ *
207
+ * Measured (2026-10-10): one probe costs 188/220/225 ms on the deployed library
208
+ * (28 skills / 418 KB) and scales linearly at ~5.5 ms per skill (100 skills
209
+ * 0.4-0.6 s, 400 skills 1.9-2.5 s), so this default is ~50x the worst measured
210
+ * case and ~600x the deployed one — it will not fire in normal use, and the
211
+ * ~305 s desktop interaction wall is ~5e4 skills away.
212
+ *
213
+ * It exists for the state the probe cannot report itself: a provider that never
214
+ * answers. The platform's tool-timeout guard reads this budget off the tool
215
+ * definition and turns the hang into a diagnosable `tool call timed out after
216
+ * <ms>ms` error result, instead of a request that ends with nothing to read.
217
+ * Reopen the default when the library approaches ~1e4 skills, when the
218
+ * `evolutionIo` provider stops being local, or when a model leg enters a tool's
219
+ * execute (the same conditions the probe's own note lists).
220
+ */
221
+ const DEFAULT_PROBE_TIMEOUT_MS = 12e4;
222
+ /** V27 G2.4: the model each review/curation leg defaults to. The policy schema,
223
+ * the policy resolver and the curator's LLM nomination pass each carried their
224
+ * own copy of these strings — a deployment that changed the policy default used
225
+ * to leave the curator passing a different model than the reviews. */
226
+ const DEFAULT_CURATOR_MODEL = "deepseek-v4-pro";
227
+ /** Order of the `evolution:memory-guidance` section (before the skills one). */
228
+ const MEMORY_GUIDANCE_SECTION_ORDER = 11e3;
229
+ /** Order of the `evolution-skills-guidance` section (last of the two). */
230
+ const SKILLS_GUIDANCE_SECTION_ORDER = 11100;
231
+ //#endregion
232
+ //#region lib/types/limits.js
233
+ /**
234
+ * Skill content limits: the byte/char budgets every write path validates against.
235
+ *
236
+ * Split out of skill-store.ts (S2-1) so the frontmatter validators and the
237
+ * store share one declaration site. Re-exported by skill-store.ts: the package
238
+ * export surface is unchanged.
239
+ */
240
+ /** `verify` checks that every cited target exists and otherwise allows the move;
241
+ * `refuse` restores the pre-0.5 behaviour of refusing ANY citation-carrying
242
+ * section. Resolved at the call site, so every existing limits object keeps
243
+ * working (unknown policy never silently changes a write path). */
244
+ const DEFAULT_CITATION_POLICY = "verify";
245
+ /** Default: report the plan on refusal, never write (behaviour unchanged). */
246
+ const DEFAULT_REFERENCE_REWRITE_POLICY = "plan";
247
+ /** Default: report-only, because upstream's hard invariant is never to delete. */
248
+ const DEFAULT_ARCHIVE_RETENTION_POLICY = "report";
249
+ /** Default: report, so the cap cannot brick an existing oversize file on upgrade
250
+ * (the live library carries a 189k-character release log today). */
251
+ const DEFAULT_SUPPORT_FILE_CHAR_POLICY = "report";
252
+ /** The four stage defaults in ONE object, so the policy schema's `z.default(...)`
253
+ * calls and the store's fallbacks cannot drift apart. */
254
+ const POLICY_STAGE_DEFAULTS = Object.freeze({
255
+ citationPolicy: DEFAULT_CITATION_POLICY,
256
+ referenceRewrite: DEFAULT_REFERENCE_REWRITE_POLICY,
257
+ archiveRetention: DEFAULT_ARCHIVE_RETENTION_POLICY,
258
+ supportFileCharPolicy: DEFAULT_SUPPORT_FILE_CHAR_POLICY
259
+ });
260
+ /**
261
+ * The ONE conversion from the deployment policy snapshot to library limits
262
+ * (design §16.7): every plugin that owns a writable SkillLibrary spreads this into
263
+ * its limits, so a stage selected in cordis.yml reaches every write path. A
264
+ * per-plugin copy would be the third home for the same threshold.
265
+ *
266
+ * Only PRESENT fields are copied: an absent policy field must fall through to the
267
+ * library default rather than pinning `undefined` onto an optional limit (which
268
+ * `exactOptionalPropertyTypes` forbids and which would defeat the `?? DEFAULT`
269
+ * resolution inside the store).
270
+ * @param snapshot - the evolutionPolicy snapshot, or undefined when unmounted.
271
+ * @returns the stage fields the snapshot actually carries.
272
+ */
273
+ function policyStageLimits(snapshot) {
274
+ if (snapshot === void 0) return {};
275
+ const stages = {};
276
+ if (snapshot.citationPolicy !== void 0) stages.citationPolicy = snapshot.citationPolicy;
277
+ if (snapshot.referenceRewrite !== void 0) stages.referenceRewrite = snapshot.referenceRewrite;
278
+ if (snapshot.archiveRetention !== void 0) stages.archiveRetention = snapshot.archiveRetention;
279
+ if (snapshot.supportFileCharPolicy !== void 0) stages.supportFileCharPolicy = snapshot.supportFileCharPolicy;
280
+ return stages;
281
+ }
282
+ const DEFAULT_SKILL_LIMITS = {
283
+ maxNameLength: 64,
284
+ maxDescriptionLength: MAX_DESCRIPTION_LENGTH,
285
+ maxSkillContentChars: MAX_SKILL_CONTENT_CHARS,
286
+ maxSkillFileBytes: MAX_SKILL_FILE_BYTES,
287
+ versionKeep: 20
288
+ };
289
+ //#endregion
290
+ //#region lib/types/write-authority.js
291
+ /** The mode a deployment that configures nothing gets. */
292
+ const DEFAULT_WRITE_CONFIRM_MODE = "auto";
293
+ /** Seconds a timeout-mode prompt waits before the write is cancelled. */
294
+ const DEFAULT_WRITE_CONFIRM_TIMEOUT_SECONDS = 120;
295
+ /**
296
+ * The batch-one migration aid: every call site becomes ONE of these instead of hand-building the
297
+ * object - so the shape cannot drift between callers, and each site still has to say its own
298
+ * origin out loud (origin is required here on purpose: the whole point is that no caller inherits
299
+ * a default identity).
300
+ */
301
+ function authorityFrom(input) {
302
+ return {
303
+ origin: input.origin,
304
+ threatExemptLabels: input.threatExemptLabels ?? [],
305
+ protectedNames: input.protectedNames,
306
+ readNames: input.readNames,
307
+ ...input.confirm === void 0 ? {} : { confirm: input.confirm },
308
+ ...input.confirmMode === void 0 ? {} : { confirmMode: input.confirmMode },
309
+ ...input.confirmTimeoutSeconds === void 0 ? {} : { confirmTimeoutSeconds: input.confirmTimeoutSeconds },
310
+ warn: input.warn ?? (() => {})
311
+ };
312
+ }
313
+ //#endregion
314
+ //#region lib/types/skill-reads.js
315
+ /**
316
+ * The skill names ONE session read, or `undefined` when its log is not readable.
317
+ *
318
+ * Two readers, in this order: the family's `evolutionReads` projection for a platform `Session`
319
+ * (0.2.x's live read — the deprecated synchronous log read is gone from production), then the
320
+ * STRUCTURAL accessor for a view that is not a `Session` at all. The tool path's exec view may be a
321
+ * bare stub, which is what this module exists for; a real Session always takes the first path.
322
+ *
323
+ * `undefined` is NOT an empty set: a caller that must decide (the tool path's read-before-write
324
+ * gate) can then keep its previous behavior instead of refusing every write in a composition whose
325
+ * session objects expose no log at all.
326
+ * @param ctx - a context of the runtime.
327
+ * @param session - the session whose reads are wanted; `undefined` when the call carries none.
328
+ * @returns the names read through a non-failed `skill` dispatch, or `undefined` when unreadable.
329
+ */
330
+ function sessionReadSkillNames(ctx, session) {
331
+ if (session === void 0) return void 0;
332
+ const projected = sessionReadNames(ctx, session);
333
+ if (projected !== void 0) return projected;
334
+ const events = session.readEvents?.();
335
+ return events === void 0 ? void 0 : collectReadSkillNames(events);
336
+ }
337
+ /**
338
+ * Skill support files ONE session read through a non-failed file tool (P2-27).
339
+ *
340
+ * platform-declaration anchor: `sessionProjections` is declared by
341
+ * `@deepseek-ai/dsh-session-projection` (its registry; capability-probed here).
342
+ * Same two readers as {@link sessionReadSkillNames}: the family projection first,
343
+ * then the structural log view. `undefined` means "no evidence", not "nothing was
344
+ * read" - the write gate then keeps its fail-open posture.
345
+ * @param ctx - a context of the runtime.
346
+ * @param session - the session whose reads are wanted.
347
+ * @param options - the skills root and the configured file-tool names.
348
+ * @returns skill -> set of skill-root-relative support paths.
349
+ */
350
+ function sessionReadSupportFiles(ctx, session, options) {
351
+ if (session === void 0) return void 0;
352
+ if (isProjectableSession(session)) {
353
+ const state = ctx.get("evolutionProjections")?.reads(session);
354
+ if (state !== void 0) {
355
+ const toolNames = options.toolNames ?? DEFAULT_SUPPORT_READ_TOOL_NAMES;
356
+ const reads = /* @__PURE__ */ new Map();
357
+ for (const entry of state.reads) {
358
+ if (entry.failed || typeof entry.file !== "string") continue;
359
+ if (entry.tool !== void 0 && !toolNames.includes(entry.tool)) continue;
360
+ const hit = supportFileReadFromPath(entry.file, { root: options.root });
361
+ if (hit === null) continue;
362
+ const set = reads.get(hit.skill) ?? /* @__PURE__ */ new Set();
363
+ set.add(hit.rel);
364
+ reads.set(hit.skill, set);
365
+ }
366
+ return reads;
367
+ }
368
+ }
369
+ const events = session.readEvents?.();
370
+ return events === void 0 ? void 0 : collectReadSupportFiles(events, {
371
+ toolNames: options.toolNames ?? DEFAULT_SUPPORT_READ_TOOL_NAMES,
372
+ root: options.root
373
+ });
374
+ }
375
+ /** Actions whose target must have been read first (create is authorship, so it is exempt). */
376
+ const READ_REQUIRED_ACTIONS = Object.freeze([
377
+ "edit",
378
+ "update",
379
+ "patch",
380
+ "delete",
381
+ "write_file",
382
+ "remove_file",
383
+ "restructure",
384
+ "extract"
385
+ ]);
386
+ /**
387
+ * Does this one op write a skill the caller never read?
388
+ *
389
+ * V6-26 (0.3.37): the validator normalizes a missing action to `patch`, so a missing action is a
390
+ * read-required write, never silently exempt.
391
+ * @param op - one skill operation (from a tool call or a review plan).
392
+ * @param readNames - names read this session, from {@link collectReadSkillNames}.
393
+ * @returns true when the op is a read-required write to an unread target.
394
+ */
395
+ function isUnreadWrite(op, readNames) {
396
+ if (!op.name) return false;
397
+ return READ_REQUIRED_ACTIONS.includes(op.action ?? "patch") && !readNames.has(op.name);
398
+ }
399
+ /**
400
+ * Drop mutating ops whose target was not read this session, in place.
401
+ *
402
+ * Covers the same mutating surface Hermes guards (edit/patch/write_file/remove_file), so a
403
+ * background review cannot blind-touch support files or edits of skills it never loaded.
404
+ * @param ops - the plan's ops; dropped entries are removed in place.
405
+ * @param readNames - names read this session.
406
+ * @returns the count of dropped ops, so the plan event can report them as rejected.
407
+ */
408
+ function filterUnreadSkillOps(ops, readNames) {
409
+ let dropped = 0;
410
+ for (let index = ops.length - 1; index >= 0; index -= 1) {
411
+ const op = ops[index];
412
+ if (!op) continue;
413
+ if (isUnreadWrite(op, readNames)) {
414
+ ops.splice(index, 1);
415
+ dropped += 1;
416
+ }
417
+ }
418
+ return dropped;
419
+ }
420
+ //#endregion
421
+ //#region lib/types/reference-rewrite.js
422
+ /**
423
+ * Reference re-homing plans (0.5.0 V1, design §16.7).
424
+ *
425
+ * A consolidation moves one skill's body under ANOTHER skill root, where every
426
+ * support-dir reference resolves against that other root (design §2.1). This
427
+ * module plans what has to happen to the support files and to the body's
428
+ * references for the move to leave no dangling link. Pure: the caller owns IO,
429
+ * decides the destination names, and decides whether the plan is applied (V2)
430
+ * or only reported (V1). Cross-skill rewriting is out of scope by design (§14) —
431
+ * a plan covers ONE body.
432
+ */
433
+ /**
434
+ * Provisional re-homing rule. The naming style for re-homed files is still an
435
+ * open decision (design §16.3 B5); this rule only fires on a COLLISION, where
436
+ * something has to give: a path that the target already occupies gets the source
437
+ * name as a prefix (`references/a.md` -> `references/<source>-a.md`). Nested
438
+ * destinations are deliberately avoided: the support listing is one level deep,
439
+ * so a file moved into a subdirectory would drop out of the listing entirely.
440
+ * @param sourceFiles - the moving skill's support files.
441
+ * @param targetFiles - the destination skill's support files.
442
+ * @param sourceName - the moving skill's name, used as the collision prefix.
443
+ * @returns the moves plus the paths that collided (for the report).
444
+ */
445
+ function planRehoming(sourceFiles, targetFiles, sourceName) {
446
+ const taken = new Set(targetFiles);
447
+ const collisions = [];
448
+ const moves = [];
449
+ for (const path of sourceFiles) {
450
+ if (!taken.has(path)) {
451
+ moves.push({
452
+ from: path,
453
+ to: path
454
+ });
455
+ continue;
456
+ }
457
+ collisions.push(path);
458
+ const cut = path.lastIndexOf("/");
459
+ const dir = cut < 0 ? "" : path.slice(0, cut + 1);
460
+ const name = path.slice(cut + 1);
461
+ let candidate = `${dir}${sourceName}-${name}`;
462
+ let counter = 2;
463
+ while (taken.has(candidate)) {
464
+ candidate = `${dir}${sourceName}-${counter}-${name}`;
465
+ counter += 1;
466
+ }
467
+ taken.add(candidate);
468
+ moves.push({
469
+ from: path,
470
+ to: candidate
471
+ });
472
+ }
473
+ return {
474
+ moves,
475
+ collisions
476
+ };
477
+ }
478
+ /**
479
+ * Plan the reference rewrites for one body that is moving into another root.
480
+ * @param input - the body, the MOVING skill's file list, the re-homing moves and
481
+ * the destination's file list (with the moved paths already included).
482
+ * @returns the edits, the cited files without a destination, and any target that
483
+ * the destination file list cannot prove (applying such a plan would dangle).
484
+ */
485
+ function planReferenceRewrite(input) {
486
+ const report = resolveCitations({
487
+ content: input.content,
488
+ file: "SKILL.md",
489
+ files: input.files
490
+ });
491
+ const byFrom = new Map(input.moves.map((move) => [move.from, move.to]));
492
+ const available = new Set(input.targetFiles);
493
+ const edits = [];
494
+ const unresolved = [];
495
+ const residual = /* @__PURE__ */ new Set();
496
+ const used = /* @__PURE__ */ new Set();
497
+ for (const ref of report.refs) {
498
+ if (ref.kind !== "citation" || ref.target === null) continue;
499
+ const move = byFrom.get(ref.target);
500
+ const to = move ?? ref.target;
501
+ if (move !== void 0) {
502
+ used.add(ref.target);
503
+ if (move !== ref.target) edits.push({
504
+ line: ref.line,
505
+ from: ref.target,
506
+ to: move,
507
+ raw: ref.raw
508
+ });
509
+ } else if (!report.dangling.some((entry) => entry.target === ref.target)) unresolved.push(ref.target);
510
+ if (!available.has(to)) residual.add(to);
511
+ }
512
+ return {
513
+ edits,
514
+ unresolved: [...new Set(unresolved)],
515
+ residualDangling: [...residual],
516
+ moves: input.moves.filter((move) => used.has(move.from))
517
+ };
518
+ }
519
+ /**
520
+ * Apply a plan's edits to the body (V2). Line-wise and literal: line N gets its
521
+ * FIRST occurrence of the recorded token replaced, everything else is copied
522
+ * byte for byte — no regex, so a token that happens to contain regex
523
+ * metacharacters cannot rewrite more than it matched.
524
+ * @param content - the body the plan was computed against.
525
+ * @param edits - the plan's edits.
526
+ * @returns the rewritten body (identical to the input when there is nothing to do).
527
+ */
528
+ function applyReferenceRewrite(content, edits) {
529
+ if (edits.length === 0) return content;
530
+ const byLine = /* @__PURE__ */ new Map();
531
+ for (const edit of edits) {
532
+ const list = byLine.get(edit.line);
533
+ if (list === void 0) byLine.set(edit.line, [edit]);
534
+ else list.push(edit);
535
+ }
536
+ const lines = content.split("\n");
537
+ for (const [lineNo, lineEdits] of byLine) {
538
+ const index = lineNo - 1;
539
+ const original = lines[index];
540
+ if (original === void 0) continue;
541
+ let next = original;
542
+ for (const edit of lineEdits) {
543
+ const at = next.indexOf(edit.raw);
544
+ if (at < 0) continue;
545
+ next = next.slice(0, at) + edit.to + next.slice(at + edit.raw.length);
546
+ }
547
+ lines[index] = next;
548
+ }
549
+ return lines.join("\n");
550
+ }
551
+ /**
552
+ * One-line, model-facing summary of a plan, for the consolidation refusal and
553
+ * for the V2 apply path's audit text.
554
+ * @param plan - the plan to describe.
555
+ * @returns a compact sentence naming counts, the moves and any residual risk.
556
+ */
557
+ function describeReferenceRewrite(plan) {
558
+ const renames = plan.moves.filter((move) => move.from !== move.to);
559
+ return `plan: ${[
560
+ `re-home ${plan.moves.length} file(s)`,
561
+ renames.length === 0 ? "" : `renamed: ${renames.map((move) => `${move.from}->${move.to}`).join(", ")}`,
562
+ `rewrite ${plan.edits.length} reference(s)`,
563
+ `residual dangling ${plan.residualDangling.length}`,
564
+ plan.unresolved.length === 0 ? "" : `no destination: ${plan.unresolved.slice(0, 5).join(", ")}`
565
+ ].filter((part) => part.length > 0).join("; ")}`;
566
+ }
567
+ //#endregion
568
+ //#region lib/types/support-refs.js
569
+ /**
570
+ * Support-directory references in a markdown body (009 kernel): references/…,
571
+ * templates/…, scripts/…, assets/… relative links — any extension and nested
572
+ * paths. Pure: who checks them and what the verdict is belongs to the caller.
573
+ * `..` traversal is a different defect class (path validation owns it) and is
574
+ * not a support link.
575
+ */
576
+ function supportRefs(content) {
577
+ const refs = [];
578
+ for (const match of content.matchAll(/(?<![A-Za-z0-9._/-])(?:references|templates|scripts|assets)\/[A-Za-z0-9._/-]+/g)) {
579
+ const ref = match[0];
580
+ if (ref.includes("..")) continue;
581
+ refs.push(ref);
582
+ }
583
+ return refs;
584
+ }
585
+ /**
586
+ * References that leave the skill root: parent traversals or absolute support paths.
587
+ * Extract must not silently treat these as relative support files; the caller reports
588
+ * them (bounded external copy is a separate, explicit policy).
589
+ * @param content - markdown body.
590
+ * @returns external-looking support references, de-duplicated in first-seen order.
591
+ */
592
+ function externalRefs(content) {
593
+ const refs = [];
594
+ for (const match of content.matchAll(/(?:^|[\s("'`])((?:\.\.\/)+[A-Za-z0-9._/-]+|\/[A-Za-z0-9._/-]+)/g)) {
595
+ const ref = match[1]?.replace(/[.,;:]+$/, "");
596
+ if (ref === void 0 || ref.length === 0 || refs.includes(ref)) continue;
597
+ refs.push(ref);
598
+ }
599
+ return refs;
600
+ }
601
+ //#endregion
602
+ //#region lib/types/frontmatter.js
603
+ /**
604
+ * Frontmatter parsing, normalization and validation for skill Markdown files.
605
+ *
606
+ * Split out of skill-store.ts (S2-1): pure functions over file text, no store
607
+ * state. skill-store.ts re-exports the same names it exported before the split,
608
+ * so the package export surface is unchanged.
609
+ */
610
+ /**
611
+ * Shared frontmatter block detection (P3-3 single owner): opening line `---`
612
+ * and closing line exactly `---`. Used by `parseFrontmatter`,
613
+ * `frontmatterCatalogInvalid` and `normalizeFrontmatter` so the three can
614
+ * never disagree about where the block ends (the loose `indexOf('\n---')`
615
+ * form matched `\n----` and was replaced by this strict line rule).
616
+ *
617
+ * V27 G2.1: both fence lines are matched EXACTLY, tolerating only a trailing
618
+ * `\r` — the same rule the upstream filesystem catalog uses
619
+ * (`skill-filesystem.parseFrontmatter`). The former `.trim()` comparison
620
+ * accepted ` --- `, so an indented fence loaded in the family while the
621
+ * platform ignored the file: family visibility split from platform visibility,
622
+ * which is exactly what a strict-YAML frontmatter is supposed to prevent.
623
+ */
624
+ /**
625
+ * S1.1 (v37 P1-4): the frontmatter block is split on LF and every line keeps its
626
+ * own `\r`, so the byte-preserving rebuild (`lines.join('\n')`) is exact. Line
627
+ * MATCHERS must therefore look at a CR-stripped view: JS `.` does not match `\r`,
628
+ * so `(.*)$` never reaches the end of a CRLF line.
629
+ * @param line - one block line, possibly CR-terminated.
630
+ * @returns the line without its trailing CR.
631
+ */
632
+ function withoutCr(line) {
633
+ return line.endsWith("\r") ? line.slice(0, -1) : line;
634
+ }
635
+ function frontmatterBlock(content) {
636
+ if (!content.trimStart().startsWith("---")) return null;
637
+ const firstBreak = content.indexOf("\n");
638
+ const nl = firstBreak > 0 && content[firstBreak - 1] === "\r" ? "\r\n" : "\n";
639
+ const lines = content.split("\n");
640
+ if ((lines[0] ?? "").replace(/\r$/, "") !== "---") return null;
641
+ let end = -1;
642
+ for (let i = 1; i < lines.length; i++) {
643
+ const line = lines[i];
644
+ if (line === void 0) continue;
645
+ if (line === "---" || line === "---\r") {
646
+ end = i;
647
+ break;
648
+ }
649
+ }
650
+ if (end < 0) return null;
651
+ return {
652
+ block: lines.slice(1, end).join("\n"),
653
+ lines,
654
+ end,
655
+ nl
656
+ };
657
+ }
658
+ /**
659
+ * Raw-line scan of a frontmatter block: the single owner of "which entries the
660
+ * strict catalog cannot load". `frontmatterCatalogInvalid` publishes it and
661
+ * `normalizeFrontmatter` decides each rewrite with the same predicate
662
+ * (`yamlPlainScalarNeedsQuotes`), so the audit verdict and the write path can
663
+ * never disagree. A9 (audit P2-12): the scan is ENDING-AGNOSTIC — lines are
664
+ * split on `\n` with the per-line CR stripped, exactly the iteration the
665
+ * rewrite path uses. The former split on the block's FIRST-LINE ending turned
666
+ * a mixed-ending block (first line CRLF, entries LF) into one unsplit chunk
667
+ * whose entries were all skipped, so an unquoted ` #` value read as CLEAN
668
+ * while the catalog silently dropped it and the next edit would have quoted
669
+ * it. Only single-line `key: value` entries are judged.
670
+ */
671
+ function unsafeFrontmatterEntries(block) {
672
+ const found = [];
673
+ for (const rawLine of block.split("\n")) {
674
+ const match = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(withoutCr(rawLine));
675
+ if (!match) continue;
676
+ const key = match[1];
677
+ if (key === void 0) continue;
678
+ const value = (match[2] ?? "").trim();
679
+ if (yamlPlainScalarNeedsQuotes(value)) found.push({
680
+ key,
681
+ value
682
+ });
683
+ }
684
+ return found;
685
+ }
686
+ /**
687
+ * Frontmatter fields the platform catalog reads as STRINGS (`stringField` /
688
+ * `optionalString` in `skill-filesystem`): any other YAML type reads as
689
+ * ABSENT there, and an absent `name`/`description` makes the catalog ignore the
690
+ * whole file. The family publishes text for these keys anyway (its lenient
691
+ * read), which is the one split a write must not create.
692
+ */
693
+ const PLATFORM_STRING_FIELDS = [
694
+ "name",
695
+ "description",
696
+ "whenToUse"
697
+ ];
698
+ /**
699
+ * Frontmatter values as the STRICT platform catalog reads them — the `yaml`
700
+ * package (YAML 1.2 core schema, the same dependency the platform's
701
+ * skill-filesystem parses with — see the import note above),
702
+ * the parser `normalizeFrontmatter` also verifies rewrites with — or `null`
703
+ * when the block is not loadable as a YAML mapping. Also reports the platform
704
+ * string fields whose value is not a string ({@link PlatformStringSplit}).
705
+ *
706
+ * Scalars publish their text (`name`, `description`, `whenToUse` are strings by
707
+ * contract; a number/boolean-shaped value keeps the text the family always
708
+ * published), a flow or block sequence publishes its inline `[a, b]` form
709
+ * (`relatedSkillNames` scans names out of it), and a nested mapping publishes
710
+ * nothing — no consumer in this family reads one, and a lossy string could be
711
+ * picked up by a routing field. A string value is trimmed: YAML's block-scalar
712
+ * chomping appends a newline that the family's single-line routing fields never
713
+ * carried.
714
+ */
715
+ function strictFrontmatterValues(block) {
716
+ if (block.trim() === "") return {
717
+ values: /* @__PURE__ */ new Map(),
718
+ split: []
719
+ };
720
+ let loaded;
721
+ try {
722
+ loaded = parse(block);
723
+ } catch {
724
+ return null;
725
+ }
726
+ if (loaded === null || loaded === void 0) return {
727
+ values: /* @__PURE__ */ new Map(),
728
+ split: []
729
+ };
730
+ if (typeof loaded !== "object" || Array.isArray(loaded)) return null;
731
+ const values = /* @__PURE__ */ new Map();
732
+ const split = [];
733
+ let metadata;
734
+ for (const [key, value] of Object.entries(loaded)) {
735
+ if (typeof value !== "string" && PLATFORM_STRING_FIELDS.includes(key)) split.push({
736
+ key,
737
+ kind: value === null || value === void 0 ? "null" : Array.isArray(value) ? "sequence" : typeof value === "object" ? "mapping" : "scalar"
738
+ });
739
+ if (typeof value === "string") {
740
+ values.set(key, value.trim());
741
+ continue;
742
+ }
743
+ if (typeof value === "number" || typeof value === "boolean") {
744
+ values.set(key, String(value));
745
+ continue;
746
+ }
747
+ if (Array.isArray(value)) {
748
+ values.set(key, `[${value.map((item) => String(item)).join(", ")}]`);
749
+ continue;
750
+ }
751
+ if (key === "metadata" && isRecord(value)) {
752
+ metadata = value;
753
+ continue;
754
+ }
755
+ }
756
+ return {
757
+ values,
758
+ split,
759
+ metadata
760
+ };
761
+ }
762
+ /**
763
+ * Lenient line scan, used only for a block the strict parser rejects: the
764
+ * family keeps routing a legacy file the platform refuses, and
765
+ * `catalogInvalid` reports the split instead of hiding it. Values are trimmed
766
+ * and unquoted exactly as before.
767
+ */
768
+ function lenientFrontmatterValues(block, nl) {
769
+ const values = /* @__PURE__ */ new Map();
770
+ const blockLines = block.split(nl);
771
+ for (let i = 0; i < blockLines.length; i += 1) {
772
+ const line = withoutCr(blockLines[i] ?? "");
773
+ const match = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(line);
774
+ if (!match) continue;
775
+ const [, key, value] = match;
776
+ if (key === void 0 || value === void 0) continue;
777
+ const header = /^([>|])[+-]?\d*$/.exec(value.trim());
778
+ if (header !== null) {
779
+ const fold = header[1] === ">";
780
+ const parts = [];
781
+ let scan = i + 1;
782
+ for (; scan < blockLines.length; scan += 1) {
783
+ const raw = blockLines[scan] ?? "";
784
+ if (raw.trim() === "") {
785
+ parts.push("");
786
+ continue;
787
+ }
788
+ if (!/^\s/.test(raw)) break;
789
+ parts.push(raw.trim());
790
+ }
791
+ while (parts.length > 0 && parts[parts.length - 1] === "") parts.pop();
792
+ let folded = "";
793
+ for (const part of parts) {
794
+ if (part === "") {
795
+ if (folded !== "" && !folded.endsWith("\n")) folded += "\n";
796
+ continue;
797
+ }
798
+ if (folded === "" || folded.endsWith("\n")) folded += part;
799
+ else folded += ` ${part}`;
800
+ }
801
+ values.set(key, (fold ? folded : parts.join("\n")).trim());
802
+ i = scan - 1;
803
+ continue;
804
+ }
805
+ values.set(key, value.trim().replace(/^["']|["']$/g, ""));
806
+ }
807
+ return values;
808
+ }
809
+ /**
810
+ * The single read of a SKILL.md frontmatter block: values, body and every
811
+ * strict-catalog signal, computed once. `null` only when the file has no
812
+ * frontmatter block; the body may be empty. {@link parseFrontmatter} and
813
+ * {@link frontmatterCatalogInvalid} are its two projections.
814
+ *
815
+ * @param content - the SKILL.md text.
816
+ * @returns the block read, or `null` when there is no block.
817
+ */
818
+ function readFrontmatterBlock(content) {
819
+ const found = frontmatterBlock(content);
820
+ if (!found) return null;
821
+ const body = found.lines.slice(found.end + 1).join("\n").trim();
822
+ const strict = strictFrontmatterValues(found.block);
823
+ const values = strict?.values ?? lenientFrontmatterValues(found.block, found.nl);
824
+ const frontmatter = {};
825
+ for (const [key, value] of values) frontmatter[key] = value;
826
+ return {
827
+ frontmatter,
828
+ body,
829
+ unsafeValues: unsafeFrontmatterEntries(found.block),
830
+ strictFailed: strict === null,
831
+ platformStringSplit: strict?.split ?? [],
832
+ metadata: strict?.metadata
833
+ };
834
+ }
835
+ /**
836
+ * Parse a SKILL.md: its frontmatter values and body, or `null` when the file
837
+ * has no frontmatter block or no body. Every consumer of frontmatter values
838
+ * goes through here — the write path's validation, `list()`'s published
839
+ * description, `relatedSkillNames` and the audit — so all of them read the same
840
+ * bytes the same way.
841
+ *
842
+ * @param content - the SKILL.md text.
843
+ * @returns the read, or `null` when there is no block or no body.
844
+ */
845
+ function parseFrontmatter(content) {
846
+ const read = readFrontmatterBlock(content);
847
+ if (!read || !read.body) return null;
848
+ return {
849
+ frontmatter: read.frontmatter,
850
+ body: read.body,
851
+ unsafeValues: read.unsafeValues,
852
+ metadata: read.metadata,
853
+ catalogInvalid: read.strictFailed || read.unsafeValues.length > 0 || read.platformStringSplit.length > 0,
854
+ platformStringSplit: read.platformStringSplit
855
+ };
856
+ }
857
+ /**
858
+ * Whether this file's frontmatter is valid as written for the strict platform
859
+ * catalog (see `FrontmatterRead.catalogInvalid`). Body-independent (a body-less
860
+ * file is still judged), and derived from the same read as `parseFrontmatter` —
861
+ * so the audit's verdict and the values the family publishes for one file can
862
+ * never disagree (V27 G2.1).
863
+ *
864
+ * @param content - the SKILL.md text.
865
+ * @returns `true` when the strict parser rejects the block or an unquoted value would read as something else.
866
+ */
867
+ function frontmatterCatalogInvalid(content) {
868
+ const read = readFrontmatterBlock(content);
869
+ if (read !== null) return read.strictFailed || read.unsafeValues.length > 0 || read.platformStringSplit.length > 0;
870
+ return frontmatterBlock(content.replace(/^\uFEFF/, "").replace(/\r\n/g, "\n")) !== null;
871
+ }
872
+ /** YAML plain-scalar hazards that make an UNQUOTED frontmatter value
873
+ * unloadable to the platform catalog (strict YAML parser): `: ` (mapping
874
+ * separator), ` #` (comment start), a trailing `:` (a mapping marker),
875
+ * or a leading YAML indicator. The evolution `parseFrontmatter` is
876
+ * deliberately lenient, so violations silently split family-visibility from
877
+ * platform-visibility (0.3.11 inkos-harness case: the description carried
878
+ * "…: " and the catalog dropped the whole skill). Already-quoted values and
879
+ * well-formed flow collections (`[a, b]` / `{a: b}`) are considered safe.
880
+ * 0.3.16 (E-47): null/bool/number-shaped plain scalars are flagged too — they
881
+ * parse as booleans/numbers on the platform while the family keeps the string
882
+ * (a `description: true` split-brain).
883
+ * This rule is only the FAST PATH — the write path re-verifies every rewrite
884
+ * with the real YAML parser (see normalizeFrontmatter), so an incomplete
885
+ * approximation can never corrupt a multiline flow value (P3-4). */
886
+ function yamlPlainScalarNeedsQuotes(value) {
887
+ if (value.length === 0) return false;
888
+ if (value.length >= 2 && (value.startsWith("\"") && value.endsWith("\"") || value.startsWith("'") && value.endsWith("'"))) return false;
889
+ if (/^\[.*\]$/.test(value) || /^\{.*\}$/.test(value)) return false;
890
+ if (/^[>|][+-]?\d*$/.test(value)) return false;
891
+ if (value.includes(": ")) return true;
892
+ if (value.includes(" #")) return true;
893
+ if (value.endsWith(":")) return true;
894
+ if (/^(?:null|true|false|~)$/i.test(value)) return true;
895
+ if (/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?$/.test(value)) return true;
896
+ if (/^0x[0-9a-f]+$/i.test(value)) return true;
897
+ if (/^0o[0-7]+$/.test(value)) return true;
898
+ if (/^(?:[-+]?\.inf|\.nan)$/i.test(value)) return true;
899
+ if (/^[-?:,[\]{}#&*!|>'"%@`\s]/.test(value)) return true;
900
+ return false;
901
+ }
902
+ /**
903
+ * Normalize a SKILL.md frontmatter block into catalog-loadable YAML: values
904
+ * that YAML forbids unquoted get quotes — double quotes normally, single
905
+ * quotes (with `''` doubling) when the value contains `"` or `\` (both legal
906
+ * unescaped inside single-quoted YAML). Idempotent; only single-line
907
+ * `key: value` entries are touched; body text is never modified; line-ending
908
+ * style is preserved. **Every rewrite is re-verified with the real YAML
909
+ * parser** (`yaml` — the package the platform's skill-filesystem catalog parses
910
+ * with, YAML 1.2 core schema; PLAN S2.1, 2026-09-16 — the former "js-yaml, the
911
+ * same parser" claim was false: js-yaml speaks YAML 1.1 full and diverged on
912
+ * dates, timestamps and 1.1 int forms): if the
913
+ * rewritten block no longer parses, or a rewritten value's parsed content
914
+ * differs from the original, the rewrite is rolled back and reported in
915
+ * `issues` (fail-loud, never a silent value corruption — P3-4).
916
+ *
917
+ * V10-02 (P2-3): the rewrite decision is PER LINE — each entry parses its own
918
+ * value, so a duplicated key can never route one entry's unsafe value into a
919
+ * different line's rewrite (the old key→Map lookup rewrote the FIRST (safe)
920
+ * line with the SECOND line's quoted value, and the last-wins YAML reader
921
+ * masked the damage). A duplicated key is itself invalid input and is
922
+ * reported in `issues` (the write path refuses) instead of being rewritten.
923
+ */
924
+ function normalizeFrontmatter(content) {
925
+ const block = frontmatterBlock(content);
926
+ if (!block) return {
927
+ content,
928
+ changed: false,
929
+ fields: [],
930
+ issues: []
931
+ };
932
+ const { lines, end } = block;
933
+ const fields = [];
934
+ const issues = [];
935
+ const seen = /* @__PURE__ */ new Set();
936
+ const originalValues = /* @__PURE__ */ new Map();
937
+ let changed = false;
938
+ for (let i = 1; i < end; i++) {
939
+ const raw = lines[i];
940
+ if (raw === void 0) continue;
941
+ const match = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(withoutCr(raw));
942
+ if (!match) continue;
943
+ const key = match[1];
944
+ if (key === void 0) continue;
945
+ const value = (match[2] ?? "").trim();
946
+ if (seen.has(key)) {
947
+ issues.push(`${key}: duplicate frontmatter key — remove the repeated entry and retry`);
948
+ continue;
949
+ }
950
+ seen.add(key);
951
+ if (!yamlPlainScalarNeedsQuotes(value)) continue;
952
+ if (/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/.test(value)) {
953
+ issues.push(`${key}: value contains control characters — clean them manually`);
954
+ continue;
955
+ }
956
+ lines[i] = `${key}: ${value.includes("\"") || value.includes("\\") ? `'${value.replace(/'/g, "''")}'` : `"${value}"`}${raw.endsWith("\r") ? "\r" : ""}`;
957
+ originalValues.set(key, value);
958
+ fields.push(key);
959
+ changed = true;
960
+ }
961
+ if (issues.length > 0) return {
962
+ content,
963
+ changed: false,
964
+ fields: [],
965
+ issues
966
+ };
967
+ if (!changed) return {
968
+ content,
969
+ changed: false,
970
+ fields: [],
971
+ issues
972
+ };
973
+ const rewrittenBlock = lines.slice(1, end).join("\n");
974
+ try {
975
+ const parsed = parse(rewrittenBlock);
976
+ for (const key of fields) if (String(parsed[key]) !== originalValues.get(key)) throw new Error(`rewritten value for ${key} differs from the original`);
977
+ return {
978
+ content: lines.join("\n"),
979
+ changed: true,
980
+ fields,
981
+ issues
982
+ };
983
+ } catch (error) {
984
+ return {
985
+ content,
986
+ changed: false,
987
+ fields: [],
988
+ issues: [`frontmatter rewrite verification failed (${error instanceof Error ? error.message : String(error)}) — quoting skipped; wrap this value manually`]
989
+ };
990
+ }
991
+ }
992
+ /**
993
+ * Skill names referenced by a SKILL.md's `related_skills` frontmatter
994
+ * (B-line G3, rc.44): the single parsing source for the quality references
995
+ * factor and the learning-graph edges. The DSH frontmatter parser keeps the
996
+ * YAML value as a string (`"[a, b]"`), so names are scanned out of it; each
997
+ * must satisfy the skill-name shape and the referencing skill itself is
998
+ * excluded. Pure and deduplicated.
999
+ */
1000
+ function relatedSkillNames(content, exclude) {
1001
+ const parsed = parseFrontmatter(content);
1002
+ if (!parsed) return [];
1003
+ const nestedHost = parsed.metadata?.["hermes"];
1004
+ const nestedRaw = isRecord(nestedHost) ? nestedHost["related_skills"] : void 0;
1005
+ const flat = parsed.frontmatter["related_skills"];
1006
+ const raw = typeof flat === "string" ? flat : Array.isArray(nestedRaw) ? `[${nestedRaw.map((item) => String(item)).join(", ")}]` : void 0;
1007
+ if (typeof raw !== "string") return [];
1008
+ const names = /* @__PURE__ */ new Set();
1009
+ for (const match of Array.from(raw.matchAll(/(?<![A-Za-z0-9_-])[a-z0-9][a-z0-9-]*(?![A-Za-z0-9_-])/g))) {
1010
+ const target = match[0];
1011
+ if (target && SKILL_NAME_RE.test(target) && target !== exclude) names.add(target);
1012
+ }
1013
+ return [...names];
1014
+ }
1015
+ /** S1.2 (v37 P2-1): the content limit applies to the bytes that LAND ON DISK.
1016
+ * Every write normalizes with `trimEnd() + '\n'`, so judging the raw argument let
1017
+ * a 100_000-character body with no trailing newline land as 100_001 bytes — and
1018
+ * every later patch/update of that skill was then refused, which made it
1019
+ * unmaintainable through `skill_manage` with no repair path at all. */
1020
+ /** The bytes that land on disk for a SKILL.md write — the ONE accounting basis
1021
+ * shared by the content limit and the cost estimate (design §5.2). */
1022
+ function skillMdOnDisk(content) {
1023
+ return content.trimEnd() + "\n";
1024
+ }
1025
+ /** Whether `content` would exceed `limit` once written. */
1026
+ function exceedsContentLimit(content, limit) {
1027
+ return skillMdOnDisk(content).length > limit;
1028
+ }
1029
+ /** S1.2: the repair path — a write that makes an already-over-limit file smaller.
1030
+ * Only a NET SHRINK is exempt; an equal or larger write stays refused. */
1031
+ function shrinksOverLimit(next, current, limit) {
1032
+ if (current === null || current === void 0 || !exceedsContentLimit(current, limit)) return false;
1033
+ return skillMdOnDisk(next).length < skillMdOnDisk(current).length;
1034
+ }
1035
+ /**
1036
+ * Synthesize a missing SKILL.md header at the write boundary.
1037
+ *
1038
+ * A model-authored create/update whose body starts with `# Title` is valid Markdown but the
1039
+ * skill writer rejects it before any content check. Repair only the truly headerless shape: an
1040
+ * existing fence is passed through byte-identical, even when it is malformed, so this helper
1041
+ * cannot mask a header error that the validator should report. The caller owns the audit notice.
1042
+ * @param content - the model-authored SKILL.md text.
1043
+ * @param name - the validated skill name used for the `name:` field.
1044
+ * @param description - optional description; otherwise derived from the first heading/prose.
1045
+ * @returns the write text and whether a header was synthesized.
1046
+ */
1047
+ function ensureSkillFrontmatter(content, name, description) {
1048
+ if (frontmatterBlock(content) !== null || content.trimStart().startsWith("---")) return {
1049
+ content,
1050
+ repaired: false
1051
+ };
1052
+ const body = content.replace(/^\uFEFF/, "").replace(/^(?:[ \t]*\r?\n)+/, "");
1053
+ const heading = /^#{1,6}\s+(.+?)\s*$/m.exec(body)?.[1];
1054
+ const firstLine = body.split(/\r?\n/).map((line) => line.trim()).find((line) => line !== "" && !line.startsWith("#")) ?? "";
1055
+ const source = (description?.trim() || heading || firstLine || name).replace(/\s+/g, " ").trim();
1056
+ const clipped = source.length > 58 ? source.slice(0, 57) + "…" : source;
1057
+ const summary = /[.。!?!?]$/.test(clipped) ? clipped : clipped + ".";
1058
+ const encoded = yamlPlainScalarNeedsQuotes(summary) ? JSON.stringify(summary) : summary;
1059
+ return {
1060
+ content: [
1061
+ "---",
1062
+ `name: ${name}`,
1063
+ `description: ${encoded}`,
1064
+ "version: 0.1.0",
1065
+ "author: Hermes",
1066
+ "---",
1067
+ ""
1068
+ ].join("\n") + "\n" + body,
1069
+ repaired: true
1070
+ };
1071
+ }
1072
+ function validateFrontmatter(content, expectedName, limits = DEFAULT_SKILL_LIMITS, current) {
1073
+ const parsed = parseFrontmatter(content);
1074
+ if (!parsed) return "SKILL.md 必须以 `---` 行开头,用另一个完全相同的 `---` 行结束 frontmatter(只容忍结尾的 `\\r`),并在其下包含正文。";
1075
+ const unreadable = parsed.platformStringSplit.filter((entry) => entry.kind === "sequence" || entry.kind === "mapping");
1076
+ if (unreadable.length > 0) return `Frontmatter 字段 ${unreadable.map((entry) => `"${entry.key}" (a YAML ${entry.kind})`).join(", ")} 必须是字符串:平台技能目录会把这种字段当作缺失,并忽略整个文件。请写成纯文本,或用双引号包住取值以保持字面内容。`;
1077
+ if (!parsed.frontmatter.name) return "Frontmatter 必须包含 name 字段。";
1078
+ if (!SKILL_NAME_RE.test(parsed.frontmatter.name)) return `技能名「${parsed.frontmatter.name}」不合法:请只用小写字母、数字和连字符。`;
1079
+ if (parsed.frontmatter.name.length > limits.maxNameLength) return `技能名超过 ${limits.maxNameLength} 个字符。`;
1080
+ if (expectedName && parsed.frontmatter.name !== expectedName) return `Frontmatter 里的 name「${parsed.frontmatter.name}」与目标技能「${expectedName}」不一致。`;
1081
+ if (!parsed.frontmatter.description) return "Frontmatter 必须包含 description 字段。";
1082
+ if (parsed.frontmatter.description.length > limits.maxDescriptionLength) return `description 超过 ${limits.maxDescriptionLength} 个字符。`;
1083
+ if (exceedsContentLimit(content, limits.maxSkillContentChars) && !shrinksOverLimit(content, current, limits.maxSkillContentChars)) return `SKILL.md 内容超过 ${limits.maxSkillContentChars} 个字符。${CONTENT_SPLIT_HINT}`;
1084
+ return null;
1085
+ }
1086
+ /**
1087
+ * Advisory authoring feedback (P0): evaluate frontmatter against the
1088
+ * authoring bar WITHOUT changing platform validation semantics. The bar is
1089
+ * the quality target, `validateFrontmatter`'s limits are the compatibility
1090
+ * floor, and this bridge layer tells the model when its text would be
1091
+ * truncated or route-poor instead of silently shipping it.
1092
+ */
1093
+ function authoringFeedback(frontmatter) {
1094
+ const description = frontmatter.description ?? "";
1095
+ const over60 = description.length > 60;
1096
+ const hasColon = description.includes(":");
1097
+ const lines = [];
1098
+ lines.push(over60 ? `描述为 ${description.length}/60 个字符 —— 超过 60 字符的作者规范上限(Hermes 标准;技能目录会按平台配置的上限截断)。` : `描述为 ${description.length}/60 个字符 —— 在作者规范上限之内。`);
1099
+ if (hasColon) lines.push("描述里含冒号 —— 请用双引号把整个取值包起来。");
1100
+ return {
1101
+ descriptionChars: description.length,
1102
+ over60,
1103
+ hasColon,
1104
+ lines
1105
+ };
1106
+ }
1107
+ /** A1-15 (v18) / P2-2 (v19): the io layer marks an error `committed: true` when
1108
+ * the rename landed and only the directory fsync failed. Every single-file
1109
+ * writer must treat that as "written, durability unconfirmed" — never as a
1110
+ * plain failure (which a caller would retry, or a two-phase caller roll back).
1111
+ * v28 G2.1 (EVO-IO-05): this is a delegation to the seam's own
1112
+ * `isCommittedWarning` — the marker predicate has exactly one definition. */
1113
+ //#endregion
1114
+ //#region lib/types/document-body.js
1115
+ /**
1116
+ * What the panel shows when it renders one version as a document.
1117
+ *
1118
+ * Two decisions, both made here so the preview and the rendered diff cannot drift apart:
1119
+ *
1120
+ * - FRONTMATTER IS NOT DOCUMENT TEXT. A SKILL.md opens with a YAML block; the renderer read its
1121
+ * closing `---` as a setext underline, so the metadata line became the document's biggest heading
1122
+ * and the real title sat below it (measured on the installed panel 2026-09-28). The block is
1123
+ * stripped for DISPLAY only: the raw view and the body route still carry every byte, and the
1124
+ * panel already shows the name and description on the row and in the left column.
1125
+ * - STRIPPING FAILS OPEN. Only a block that the family's own reader accepts is removed. A document
1126
+ * whose text merely starts with a thematic break, a block with no closing line, or a frontmatter
1127
+ * whose body is empty is returned UNCHANGED — showing a document's first line is always better
1128
+ * than showing nothing.
1129
+ *
1130
+ * `readingStats` exists for the other half of the reader's honesty: a preview that stops early has
1131
+ * to be able to say HOW much it is not showing.
1132
+ * @module @lmzhen/dsh-evolution-core/document-body
1133
+ */
1134
+ /**
1135
+ * The document a reader sees: the body without its leading frontmatter block.
1136
+ * @param content - the stored bytes of one version.
1137
+ * @returns the text to render; unchanged when there is no frontmatter the reader accepts.
1138
+ */
1139
+ function displayBodyOf(content) {
1140
+ const block = frontmatterBlock(content);
1141
+ if (block === null) return content;
1142
+ if (parseFrontmatter(content) === null) return content;
1143
+ return block.lines.slice(block.end + 1).join("\n").replace(/^\s*\n/, "");
1144
+ }
1145
+ /**
1146
+ * How much of a version the panel is showing.
1147
+ * @param full - the whole stored text.
1148
+ * @param shown - the part the route handed over.
1149
+ * @returns the counts, so the panel can say what it is not showing.
1150
+ */
1151
+ function readingStats(full, shown) {
1152
+ return {
1153
+ totalChars: full.length,
1154
+ shownChars: shown.length,
1155
+ truncated: shown.length < full.length
1156
+ };
1157
+ }
1158
+ /**
1159
+ * The H2 sections of a body, in document order — the ONE scan (G3).
1160
+ *
1161
+ * Both the restructure candidate list and the store anchor validation call this function, so a
1162
+ * candidate can only name a heading that exists EXACTLY ONCE and has content: the two rejections a
1163
+ * hand-written anchor used to hit ("no such heading", "ambiguous anchor") stop being reachable.
1164
+ * H2 is the section boundary (a section spans to the next H2 or EOF), matching the store.
1165
+ * @param body - the markdown after the frontmatter block.
1166
+ * @returns one row per H2 heading, with `count` filled in a second pass.
1167
+ */
1168
+ function h2Sections(body) {
1169
+ const lines = body.split(String.fromCharCode(10));
1170
+ const rows = [];
1171
+ for (let i = 0; i < lines.length; i += 1) {
1172
+ const match = /^#{2}\s+(.+?)\s*$/.exec(lines[i] ?? "");
1173
+ if (match === null) continue;
1174
+ const title = (match[1] ?? "").trim();
1175
+ let end = lines.length;
1176
+ for (let j = i + 1; j < lines.length; j += 1) if (/^#{2}\s/.test(lines[j] ?? "")) {
1177
+ end = j;
1178
+ break;
1179
+ }
1180
+ rows.push({
1181
+ title,
1182
+ start: i,
1183
+ end,
1184
+ count: 0
1185
+ });
1186
+ }
1187
+ for (const row of rows) row.count = rows.filter((other) => other.title === row.title).length;
1188
+ return rows;
1189
+ }
1190
+ /**
1191
+ * The sections a restructure proposal may name: heading unique, section non-empty. Derived from
1192
+ * `h2Sections`, i.e. from the SAME scan the store validates against.
1193
+ * @param body - the markdown after the frontmatter block.
1194
+ * @returns move-ready pairs in document order; empty when nothing qualifies.
1195
+ */
1196
+ function restructureCandidates(body) {
1197
+ return h2Sections(body).filter((section) => section.count === 1 && section.end > section.start + 1).map((section) => ({
1198
+ heading: section.title,
1199
+ toFile: "references/" + section.title.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fa5]+/g, "-").replace(/^-+|-+$/g, "") + ".md"
1200
+ }));
1201
+ }
1202
+ //#endregion
1203
+ //#region lib/types/section-selection.js
1204
+ const LF$1 = String.fromCharCode(10);
1205
+ /**
1206
+ * Select whole H2 sections or exact content sub-blocks from one body.
1207
+ *
1208
+ * The H2 scan is document-body's h2Sections, so restructure and extract share
1209
+ * one boundary rule. A start/end pair selects an inclusive, contiguous run of
1210
+ * exact lines inside that heading; it cannot select the heading itself, overlap
1211
+ * another request, or leave a selected range empty.
1212
+ * @param body - markdown after frontmatter.
1213
+ * @param requests - exact heading plus optional start/end line pairs.
1214
+ * @returns selected ranges in request order, or the first refusal.
1215
+ */
1216
+ function selectSections(body, requests) {
1217
+ const lines = body.split(LF$1);
1218
+ const sections = h2Sections(body);
1219
+ const selected = [];
1220
+ for (let requestIndex = 0; requestIndex < requests.length; requestIndex += 1) {
1221
+ const request = requests[requestIndex];
1222
+ if (request === void 0) continue;
1223
+ const wanted = request.heading.trim();
1224
+ const matching = sections.filter((section) => section.title === wanted);
1225
+ if (matching.length === 0) return {
1226
+ ok: false,
1227
+ code: "heading-missing",
1228
+ message: "no \"## " + wanted + "\" heading in the body"
1229
+ };
1230
+ if (matching.length > 1) return {
1231
+ ok: false,
1232
+ code: "heading-ambiguous",
1233
+ message: "heading \"## " + wanted + "\" appears " + matching.length + " times (ambiguous anchor)"
1234
+ };
1235
+ const section = matching[0];
1236
+ if (section === void 0) return {
1237
+ ok: false,
1238
+ code: "heading-missing",
1239
+ message: "no \"## " + wanted + "\" heading in the body"
1240
+ };
1241
+ if (selected.some((entry) => entry.start === section.start)) return {
1242
+ ok: false,
1243
+ code: "heading-duplicate",
1244
+ message: "heading \"## " + wanted + "\" is moved twice"
1245
+ };
1246
+ if (!(request.start !== void 0 || request.end !== void 0)) {
1247
+ if (section.end === section.start + 1) return {
1248
+ ok: false,
1249
+ code: "heading-empty",
1250
+ message: "heading \"## " + wanted + "\" has an empty section"
1251
+ };
1252
+ selected.push({
1253
+ heading: wanted,
1254
+ start: section.start,
1255
+ end: section.end,
1256
+ text: lines.slice(section.start, section.end).join(LF$1),
1257
+ requestIndex
1258
+ });
1259
+ continue;
1260
+ }
1261
+ if (request.start === void 0 || request.end === void 0) return {
1262
+ ok: false,
1263
+ code: "part-anchor-incomplete",
1264
+ message: "heading \"## " + wanted + "\" needs both start and end anchors"
1265
+ };
1266
+ const startMatches = [];
1267
+ const endMatches = [];
1268
+ for (let index = 0; index < lines.length; index += 1) {
1269
+ if (index <= section.start || index >= section.end) continue;
1270
+ if (lines[index] === request.start) startMatches.push(index);
1271
+ if (lines[index] === request.end) endMatches.push(index);
1272
+ }
1273
+ if (startMatches.length !== 1) return {
1274
+ ok: false,
1275
+ code: "part-anchor-not-found",
1276
+ message: "heading \"## " + wanted + "\" start anchor must match exactly one content line"
1277
+ };
1278
+ if (endMatches.length !== 1) return {
1279
+ ok: false,
1280
+ code: "part-anchor-not-found",
1281
+ message: "heading \"## " + wanted + "\" end anchor must match exactly one content line"
1282
+ };
1283
+ const start = startMatches[0];
1284
+ const end = endMatches[0];
1285
+ if (start === void 0 || end === void 0 || start > end) return {
1286
+ ok: false,
1287
+ code: "part-anchor-order",
1288
+ message: "heading \"## " + wanted + "\" start anchor is after end anchor"
1289
+ };
1290
+ if (selected.some((entry) => start < entry.end && end + 1 > entry.start)) return {
1291
+ ok: false,
1292
+ code: "part-anchor-overlaps",
1293
+ message: "heading \"## " + wanted + "\" selection overlaps another selected block"
1294
+ };
1295
+ selected.push({
1296
+ heading: wanted,
1297
+ start,
1298
+ end: end + 1,
1299
+ text: lines.slice(start, end + 1).join(LF$1),
1300
+ requestIndex,
1301
+ anchorStart: request.start,
1302
+ anchorEnd: request.end
1303
+ });
1304
+ }
1305
+ return {
1306
+ ok: true,
1307
+ sections: selected
1308
+ };
1309
+ }
1310
+ //#endregion
1311
+ //#region lib/types/extract-plan.js
1312
+ const LF = String.fromCharCode(10);
1313
+ function sha256(text) {
1314
+ return createHash("sha256").update(text).digest("hex");
1315
+ }
1316
+ function unique(values) {
1317
+ return [...new Set(values)];
1318
+ }
1319
+ function computeSupport(parts, residual, sourceName, sourceFiles, targetFiles, externalFiles) {
1320
+ const selectedText = parts.map((part) => part.sourceText).join("\n\n");
1321
+ const selectedRefs = unique(supportRefs(selectedText));
1322
+ const residualRefs = new Set(supportRefs(residual));
1323
+ const unresolved = selectedRefs.filter((ref) => !sourceFiles.includes(ref));
1324
+ if (unresolved.length > 0) return { error: "support-unresolved: " + unresolved.join(", ") };
1325
+ const candidates = selectedRefs.filter((ref) => sourceFiles.includes(ref));
1326
+ const moves = planRehoming(candidates, targetFiles, sourceName).moves;
1327
+ const byFrom = new Map(moves.map((move) => [move.from, move.to]));
1328
+ const exclusive = [];
1329
+ const shared = [];
1330
+ for (const from of candidates) {
1331
+ const to = byFrom.get(from);
1332
+ if (to === void 0) continue;
1333
+ if (residualRefs.has(from)) shared.push({
1334
+ from,
1335
+ to,
1336
+ provenance: sourceName + ":" + from
1337
+ });
1338
+ else exclusive.push({
1339
+ from,
1340
+ to
1341
+ });
1342
+ }
1343
+ const targetFilesWithMoves = unique([...targetFiles, ...moves.map((move) => move.to)]);
1344
+ const external = unique(externalRefs(selectedText));
1345
+ const suppliedRefs = new Set(externalFiles.map((file) => file.ref));
1346
+ const missingExternal = external.filter((ref) => !suppliedRefs.has(ref));
1347
+ const warnings = [];
1348
+ if (missingExternal.length > 0) warnings.push("external-support-not-copied: " + missingExternal.join(", "));
1349
+ const externalClosure = [];
1350
+ for (const file of externalFiles) {
1351
+ if (!external.includes(file.ref)) return { error: "external-ref-not-selected: " + file.ref };
1352
+ if (file.targetPath.startsWith("/") || file.targetPath.includes("..") || !/^(?:references|templates|scripts|assets)\//.test(file.targetPath)) return { error: "external-target-unsafe: " + file.targetPath };
1353
+ if (targetFilesWithMoves.includes(file.targetPath)) return { error: "external-collision: " + file.targetPath };
1354
+ externalClosure.push({
1355
+ from: file.ref,
1356
+ to: file.targetPath,
1357
+ provenance: file.provenance,
1358
+ originalPath: file.originalPath,
1359
+ content: file.content,
1360
+ sha256: file.sha256
1361
+ });
1362
+ }
1363
+ const rewritten = /* @__PURE__ */ new Map();
1364
+ for (const part of parts) {
1365
+ const partRefs = supportRefs(part.sourceText);
1366
+ const rewrite = planReferenceRewrite({
1367
+ content: part.sourceText,
1368
+ files: sourceFiles,
1369
+ moves: moves.filter((move) => partRefs.includes(move.from)),
1370
+ targetFiles: targetFilesWithMoves
1371
+ });
1372
+ rewritten.set(part.heading, applyReferenceRewrite(part.sourceText, rewrite.edits));
1373
+ warnings.push(...rewrite.unresolved.map((ref) => "support-unresolved: " + ref));
1374
+ warnings.push(...rewrite.residualDangling.map((ref) => "support-dangling: " + ref));
1375
+ }
1376
+ for (const part of parts) {
1377
+ let text = rewritten.get(part.heading) ?? part.sourceText;
1378
+ for (const file of externalClosure) text = text.split(file.from).join(file.to);
1379
+ part.movedText = text;
1380
+ }
1381
+ const exclusiveSet = new Set(exclusive.map((entry) => entry.from));
1382
+ const parentExclusive = supportRefs(residual).filter((ref) => exclusiveSet.has(ref));
1383
+ if (parentExclusive.length > 0) return { error: "support-exclusive-referenced-by-parent: " + parentExclusive.join(", ") };
1384
+ const dangling = unique(warnings.filter((item) => item.startsWith("support-dangling: ")).map((item) => item.slice(18)));
1385
+ return {
1386
+ support: {
1387
+ exclusive,
1388
+ shared,
1389
+ external: externalClosure,
1390
+ unresolved: warnings.filter((item) => item.startsWith("support-unresolved: ")),
1391
+ dangling
1392
+ },
1393
+ warnings
1394
+ };
1395
+ }
1396
+ /**
1397
+ * Build a pure extract plan. No IO, no writes: selection, residual, support
1398
+ * closure and the moved text are computed from the supplied bodies/file lists.
1399
+ * @param input - source body, target identity, owner decision and support lists.
1400
+ * @returns a plan, or a refusal with a stable code.
1401
+ */
1402
+ function planExtract(input) {
1403
+ if (input.outcome === "owner-gap") {
1404
+ if (input.owner.mode !== "owner-gap") return {
1405
+ ok: false,
1406
+ code: "owner-gap-mismatch",
1407
+ message: "outcome owner-gap requires an owner-gap decision"
1408
+ };
1409
+ if (input.owner.neededOwner === void 0 || input.owner.neededOwner.trim() === "") return {
1410
+ ok: false,
1411
+ code: "owner-gap-needed-owner",
1412
+ message: "owner-gap requires neededOwner"
1413
+ };
1414
+ } else {
1415
+ if (input.owner.mode !== "covered" || !input.owner.triggerCovers || !input.owner.outcomeCovers) return {
1416
+ ok: false,
1417
+ code: "owner-not-covered",
1418
+ message: "extract/mixed requires a covering owner"
1419
+ };
1420
+ if (!input.targetExists) return {
1421
+ ok: false,
1422
+ code: "target-missing",
1423
+ message: "covered owner target does not exist"
1424
+ };
1425
+ }
1426
+ const selection = selectSections(input.body, input.requests);
1427
+ if (!selection.ok) return {
1428
+ ok: false,
1429
+ code: selection.code,
1430
+ message: selection.message
1431
+ };
1432
+ if (selection.sections.length === 0) return {
1433
+ ok: false,
1434
+ code: "part-empty",
1435
+ message: "at least one part is required"
1436
+ };
1437
+ const externalRewrites = new Map((input.external ?? []).map((file) => [file.ref, file.targetPath]));
1438
+ const parts = selection.sections.map((section) => {
1439
+ let movedText = section.text;
1440
+ for (const [from, to] of externalRewrites) movedText = movedText.split(from).join(to);
1441
+ return {
1442
+ heading: section.heading,
1443
+ anchor: {
1444
+ heading: section.heading,
1445
+ ...section.anchorStart === void 0 ? {} : { start: section.anchorStart },
1446
+ ...section.anchorEnd === void 0 ? {} : { end: section.anchorEnd }
1447
+ },
1448
+ sourceText: section.text,
1449
+ movedText,
1450
+ bytes: Buffer.byteLength(movedText, "utf8"),
1451
+ sha256: sha256(movedText)
1452
+ };
1453
+ });
1454
+ const pointer = "This capability now lives in " + (input.owner.mode === "covered" ? input.owner.name ?? input.targetName : input.owner.neededOwner ?? input.targetName) + "; project-specific facts stay here.";
1455
+ const ordered = [...selection.sections].sort((a, b) => a.start - b.start);
1456
+ const first = ordered[0];
1457
+ if (first === void 0) return {
1458
+ ok: false,
1459
+ code: "part-empty",
1460
+ message: "at least one part is required"
1461
+ };
1462
+ const byStart = new Map(ordered.map((section) => [section.start, section]));
1463
+ const lines = input.body.split(LF);
1464
+ const rebuilt = [];
1465
+ for (let index = 0; index < lines.length; index += 1) {
1466
+ const section = byStart.get(index);
1467
+ if (section !== void 0) {
1468
+ if (index === first.start) rebuilt.push(pointer);
1469
+ index = section.end - 1;
1470
+ } else rebuilt.push(lines[index] ?? "");
1471
+ }
1472
+ const residual = rebuilt.join(LF);
1473
+ if (residual.trim().length === 0) return {
1474
+ ok: false,
1475
+ code: "parent-empty",
1476
+ message: "parent residual is empty"
1477
+ };
1478
+ if (residual.split(LF).filter((line) => line.trim() !== "" && line !== pointer && !line.trimStart().startsWith("#")).length === 0) return {
1479
+ ok: false,
1480
+ code: "parent-hollow-heading",
1481
+ message: "parent residual has no substantive content"
1482
+ };
1483
+ if (input.outcome === "owner-gap") return {
1484
+ ok: true,
1485
+ plan: {
1486
+ source: input.sourceName,
1487
+ target: {
1488
+ name: input.targetName,
1489
+ exists: input.targetExists
1490
+ },
1491
+ outcome: input.outcome,
1492
+ parts,
1493
+ residual,
1494
+ pointer,
1495
+ owner: input.owner,
1496
+ support: {
1497
+ exclusive: [],
1498
+ shared: [],
1499
+ external: [],
1500
+ unresolved: [],
1501
+ dangling: []
1502
+ },
1503
+ warnings: [],
1504
+ ...input.anchors === void 0 ? {} : { anchors: input.anchors }
1505
+ }
1506
+ };
1507
+ const supportResult = computeSupport(parts, residual, input.sourceName, input.sourceFiles, input.targetFiles, input.external ?? []);
1508
+ if ("error" in supportResult) return {
1509
+ ok: false,
1510
+ code: supportResult.error.split(":")[0] ?? "support-invalid",
1511
+ message: supportResult.error
1512
+ };
1513
+ if (supportResult.support.dangling.length > 0) return {
1514
+ ok: false,
1515
+ code: "support-dangling",
1516
+ message: "support-dangling: " + supportResult.support.dangling.join(", ")
1517
+ };
1518
+ return {
1519
+ ok: true,
1520
+ plan: {
1521
+ source: input.sourceName,
1522
+ target: {
1523
+ name: input.targetName,
1524
+ exists: input.targetExists
1525
+ },
1526
+ outcome: input.outcome,
1527
+ parts,
1528
+ residual,
1529
+ pointer,
1530
+ owner: input.owner,
1531
+ support: supportResult.support,
1532
+ warnings: unique(supportResult.warnings),
1533
+ ...input.anchors === void 0 ? {} : { anchors: input.anchors }
1534
+ }
1535
+ };
1536
+ }
1537
+ /**
1538
+ * Project one plan onto the current source/target SKILL.md bytes.
1539
+ *
1540
+ * This is the one place that composes frontmatter + residual + target additions;
1541
+ * preview and the write adapter both call it so they cannot advertise different
1542
+ * bytes. Pure: no IO.
1543
+ * @param plan - plan from planExtract.
1544
+ * @param sourceMd - current source SKILL.md.
1545
+ * @param targetMd - current target SKILL.md.
1546
+ * @returns both next documents, or the refusal that makes projection impossible.
1547
+ */
1548
+ function projectExtractBodies(plan, sourceMd, targetMd) {
1549
+ const sourceBlock = frontmatterBlock(sourceMd);
1550
+ const targetBlock = frontmatterBlock(targetMd);
1551
+ if (!sourceBlock) return {
1552
+ ok: false,
1553
+ message: "source 没有有效 frontmatter"
1554
+ };
1555
+ if (!targetBlock) return {
1556
+ ok: false,
1557
+ message: "target 没有有效 frontmatter"
1558
+ };
1559
+ const sourceHeader = sourceBlock.lines.slice(0, sourceBlock.end + 1).join(LF);
1560
+ const targetNormalized = targetMd.replace(/\r\n/g, LF);
1561
+ const targetLines = targetNormalized.split(LF);
1562
+ for (const part of plan.parts) if (targetLines.some((line) => line.trim() === "## " + part.heading)) return {
1563
+ ok: false,
1564
+ message: "target 已有同名 heading「" + part.heading + "」。"
1565
+ };
1566
+ const additions = plan.parts.map((part) => part.movedText).join("\n\n");
1567
+ const targetRaw = targetNormalized.trimEnd() + "\n\n" + additions + LF;
1568
+ const targetAfter = targetBlock.nl === "\r\n" ? targetRaw.replace(/\n/g, "\r\n") : targetRaw;
1569
+ const sourceRaw = (sourceHeader + plan.residual).replace(/\r\n/g, LF);
1570
+ return {
1571
+ ok: true,
1572
+ projection: {
1573
+ sourceAfter: sourceBlock.nl === "\r\n" ? sourceRaw.replace(/\n/g, "\r\n") : sourceRaw,
1574
+ targetAfter
1575
+ }
1576
+ };
1577
+ }
1578
+ //#endregion
1579
+ //#region lib/types/usage.js
1580
+ /**
1581
+ * Skill usage telemetry sidecar: `$DSH_HOME/skills/.usage.json`.
1582
+ * Format-compatible with Hermes Agent / hermes-claw core fields.
1583
+ */
1584
+ function usageFile(root) {
1585
+ return join(root, ".usage.json");
1586
+ }
1587
+ function emptyRecord() {
1588
+ return {
1589
+ created_by: null,
1590
+ use_count: 0,
1591
+ view_count: 0,
1592
+ patch_count: 0,
1593
+ last_used_at: null,
1594
+ last_viewed_at: null,
1595
+ last_patched_at: null,
1596
+ created_at: (/* @__PURE__ */ new Date()).toISOString(),
1597
+ state: "active",
1598
+ pinned: false,
1599
+ archived_at: null
1600
+ };
1601
+ }
1602
+ /** A timestamp passes only when `Date.parse` yields a finite epoch (N-3): a bare
1603
+ * string check let garbage like "not-a-date" propagate as Invalid Date → NaN
1604
+ * into quality math and lifecycle comparisons. */
1605
+ const validTimestamp = (value) => typeof value === "string" && Number.isFinite(Date.parse(value));
1606
+ const nullableTimestamp = (value) => value === null || validTimestamp(value);
1607
+ /**
1608
+ * Field-level normalization for one sidecar record (rc.42 audit P2-3): the
1609
+ * spread used to copy any junk through verbatim, so a corrupted file could
1610
+ * carry `use_count: "3"` into the quality math and lifecycle comparisons as
1611
+ * NaN. Every field falls back to its `emptyRecord()` baseline unless it has
1612
+ * exactly the declared type; an invalid `created_at` anchors the age clock at
1613
+ * now (first-sight defer semantics for a record whose age is unknowable).
1614
+ * Timestamps additionally require a parseable date (N-3): `"not-a-date"`
1615
+ * would otherwise survive the type check as Invalid Date.
1616
+ * Pure — exported for unit tests; `loadUsage` is the production caller.
1617
+ */
1618
+ function normalizeUsageRecord(record) {
1619
+ const base = emptyRecord();
1620
+ if (!record || typeof record !== "object" || Array.isArray(record)) return base;
1621
+ const raw = record;
1622
+ const num = (value, fallback) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : fallback;
1623
+ const bool = (value, fallback) => typeof value === "boolean" ? value : fallback;
1624
+ return {
1625
+ ...raw,
1626
+ created_by: typeof raw.created_by === "string" ? raw.created_by : null,
1627
+ use_count: num(raw.use_count, base.use_count),
1628
+ view_count: num(raw.view_count, base.view_count),
1629
+ patch_count: num(raw.patch_count, base.patch_count),
1630
+ last_used_at: nullableTimestamp(raw.last_used_at) ? raw.last_used_at : base.last_used_at,
1631
+ last_viewed_at: nullableTimestamp(raw.last_viewed_at) ? raw.last_viewed_at : base.last_viewed_at,
1632
+ last_patched_at: nullableTimestamp(raw.last_patched_at) ? raw.last_patched_at : base.last_patched_at,
1633
+ created_at: validTimestamp(raw.created_at) ? raw.created_at : base.created_at,
1634
+ state: raw.state === "stale" || raw.state === "archived" ? raw.state : "active",
1635
+ pinned: bool(raw.pinned, base.pinned),
1636
+ archived_at: nullableTimestamp(raw.archived_at) ? raw.archived_at : base.archived_at,
1637
+ quality_score: typeof raw.quality_score === "number" && Number.isFinite(raw.quality_score) ? raw.quality_score : void 0,
1638
+ quality_warn: typeof raw.quality_warn === "boolean" ? raw.quality_warn : void 0,
1639
+ feedback_score: typeof raw.feedback_score === "number" && Number.isFinite(raw.feedback_score) ? raw.feedback_score : void 0,
1640
+ feedback_warn: typeof raw.feedback_warn === "boolean" ? raw.feedback_warn : void 0,
1641
+ support_reads: normalizeSupportReads(raw.support_reads)
1642
+ };
1643
+ }
1644
+ /** Sidecar bound: a pathological path set must not grow the usage file forever. */
1645
+ const MAX_SUPPORT_READ_PATHS = 200;
1646
+ /** Sanitize the per-support-file read counts: non-negative finite numbers under
1647
+ * non-empty, bounded, non-traversal path keys. An unusable value drops the whole
1648
+ * map (absence over a poisoned count). */
1649
+ function normalizeSupportReads(value) {
1650
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return void 0;
1651
+ const out = {};
1652
+ let kept = 0;
1653
+ for (const [key, count] of Object.entries(value)) {
1654
+ if (kept >= 200) break;
1655
+ if (key === "" || key.length > 200 || key.split("/").includes("..")) continue;
1656
+ if (typeof count !== "number" || !Number.isFinite(count) || count < 0) continue;
1657
+ out[key] = count;
1658
+ kept += 1;
1659
+ }
1660
+ return kept === 0 ? void 0 : out;
1661
+ }
1662
+ /** Parse a raw usage sidecar; malformed content reads as empty (best-effort telemetry). */
1663
+ function parseUsage(raw) {
1664
+ const map = /* @__PURE__ */ new Map();
1665
+ if (raw === null) return map;
1666
+ try {
1667
+ const parsed = JSON.parse(raw);
1668
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return map;
1669
+ for (const [name, record] of Object.entries(parsed)) map.set(name, normalizeUsageRecord(record));
1670
+ } catch {}
1671
+ return map;
1672
+ }
1673
+ async function loadUsage(root, io = nodeEvolutionIo()) {
1674
+ return parseUsage(await io.readText(usageFile(root)));
1675
+ }
1676
+ async function mutateUsage(root, io, task, options = {}) {
1677
+ const run = async () => {
1678
+ await transactIo(io, usageFile(root), async (current) => {
1679
+ let shapePreserved = false;
1680
+ let recovered = null;
1681
+ const quarantineCopy = async () => {
1682
+ const corruptPath = `${usageFile(root)}.corrupt`;
1683
+ return io.writeText(corruptPath, current).then(() => true, () => false);
1684
+ };
1685
+ if (current !== null) {
1686
+ let parsed = null;
1687
+ try {
1688
+ const probe = JSON.parse(current);
1689
+ if (isRecord(probe)) parsed = probe;
1690
+ } catch {
1691
+ parsed = null;
1692
+ }
1693
+ if (parsed === null) {
1694
+ if (!await quarantineCopy()) {
1695
+ options.onQuarantine?.(`usage sidecar ${usageFile(root)} is unreadable; the .corrupt copy could not be written — refusing this write so the original bytes stay recoverable (telemetry is frozen until the file is recovered manually)`);
1696
+ return current;
1697
+ }
1698
+ options.onQuarantine?.(`usage sidecar ${usageFile(root)} is unreadable (unparsable JSON or wrong top-level shape); the original bytes were copied to ${usageFile(root)}.corrupt and the sidecar restarts empty`);
1699
+ } else {
1700
+ const record = parsed;
1701
+ const isMalformed = (value) => value === null || typeof value !== "object" || Array.isArray(value);
1702
+ if (typeof record.version === "number" && record.version > 1) {
1703
+ const message = `usage sidecar ${usageFile(root)} carries schema version ${String(record.version)} (> this runtime) — writes stay frozen and the bytes preserved until the runtime is upgraded`;
1704
+ if (options.onQuarantine !== void 0) options.onQuarantine(message);
1705
+ else console.warn(message);
1706
+ shapePreserved = true;
1707
+ } else if (Object.values(record).some(isMalformed)) {
1708
+ const bad = Object.keys(record).filter((key) => isMalformed(record[key]));
1709
+ if (!await quarantineCopy()) {
1710
+ options.onQuarantine?.(`usage sidecar ${usageFile(root)} carried ${bad.length} malformed entr${bad.length === 1 ? "y" : "ies"} (${bad.slice(0, 5).join(", ")}); the .corrupt copy could not be written — refusing this write so the original bytes stay recoverable`);
1711
+ return current;
1712
+ }
1713
+ recovered = JSON.stringify(Object.fromEntries(Object.entries(record).filter(([, value]) => !isMalformed(value))));
1714
+ options.onQuarantine?.(`usage sidecar ${usageFile(root)} carried ${bad.length} malformed entr${bad.length === 1 ? "y" : "ies"} (${bad.slice(0, 5).join(", ")}); the original bytes were copied to ${usageFile(root)}.corrupt and the remaining entries continue to be served`);
1715
+ }
1716
+ }
1717
+ }
1718
+ if (shapePreserved) return current;
1719
+ const map = parseUsage(recovered ?? current);
1720
+ await task(map);
1721
+ return JSON.stringify(Object.fromEntries(map.entries()), null, 2);
1722
+ });
1723
+ };
1724
+ if (options.fence !== void 0) await options.fence.run(run);
1725
+ else await run();
1726
+ }
1727
+ /** Curator-owned usage fields (rc.67 K-2): the curator writes ONLY this set —
1728
+ * lifecycle state, archive stamp, the six-factor quality pair, and the
1729
+ * marker-mirrored pin flag; counters and activity stamps belong to the
1730
+ * tool-telemetry side and are never copied by a fold. P2-12 (v39): the
1731
+ * combined `applyCuratorFields` wrapper had no production caller (folds go
1732
+ * through {@link foldCuratorFields}), so the two field copies below are the
1733
+ * whole contract. */
1734
+ /** Copy only the lifecycle pair (state/archived_at) — see the ownership split
1735
+ * rationale above. */
1736
+ function applyCuratorLifecycleFields(disk, curated) {
1737
+ disk.state = curated.state;
1738
+ disk.archived_at = curated.archived_at;
1739
+ }
1740
+ /**
1741
+ * Copy the recomputed meta pair (quality_score/quality_warn + the
1742
+ * marker-mirrored pin flag) — refreshed tree-wide each run by design, so a
1743
+ * concurrent curator run's lifecycle changes are never reverted by them.
1744
+ * P1-1 (v15): the feedback pair (`feedback_score`/`feedback_warn`) is
1745
+ * deliberately NOT copied — it is feedback-owned (see the field-ownership
1746
+ * contract on {@link UsageRecord}) and must survive curator runs untouched.
1747
+ */
1748
+ function applyCuratorMetaFields(disk, curated) {
1749
+ disk.quality_score = curated.quality_score;
1750
+ disk.quality_warn = curated.quality_warn;
1751
+ disk.pinned = curated.pinned;
1752
+ }
1753
+ /**
1754
+ * Fold a curator run-start snapshot onto the current on-disk map (rc.67 K-2):
1755
+ * each curated record is projected onto its disk peer by copying only the
1756
+ * curator-owned fields, so a concurrent tool-side bump between snapshot and
1757
+ * save survives. Records absent from the snapshot are left untouched; a
1758
+ * curated record with no disk peer is seeded from the snapshot. `stateOwned`
1759
+ * (rc.72 H-1) restricts the lifecycle pair to the names this run ACTUALLY
1760
+ * transitioned — a concurrent curator run's archive/restore is never reverted
1761
+ * by a stale snapshot; without it both pairs apply everywhere.
1762
+ */
1763
+ function foldCuratorFields(disk, curated, stateOwned, runStartStates) {
1764
+ const skipped = [];
1765
+ for (const [name, record] of curated) {
1766
+ const diskRecord = disk.get(name);
1767
+ if (!diskRecord) {
1768
+ disk.set(name, { ...record });
1769
+ continue;
1770
+ }
1771
+ applyCuratorMetaFields(diskRecord, record);
1772
+ if (stateOwned === void 0 || stateOwned.has(name)) {
1773
+ const expected = runStartStates?.get(name);
1774
+ if (expected !== void 0 && diskRecord.state !== expected) {
1775
+ skipped.push(name);
1776
+ continue;
1777
+ }
1778
+ applyCuratorLifecycleFields(diskRecord, record);
1779
+ }
1780
+ }
1781
+ return skipped;
1782
+ }
1783
+ /** Whole-file usage write (V6-37, 0.3.37): this is the ONE path that bypasses
1784
+ * the malformed-defense and the transact lock — prefer `mutateUsage` for any
1785
+ * read-modify-write so a concurrent writer cannot lose its update and a
1786
+ * malformed sidecar stays recoverable. Kept for fixture/test seeding.
1787
+ * @internal P3-16 (v14): no production caller (verified by grep); exported for
1788
+ * the family's tests only. Do not use it to write the sidecar in new code. */
1789
+ async function saveUsage(root, map, io = nodeEvolutionIo()) {
1790
+ const obj = Object.fromEntries(map.entries());
1791
+ await io.writeText(usageFile(root), JSON.stringify(obj, null, 2));
1792
+ }
1793
+ function getRecord(map, name) {
1794
+ let record = map.get(name);
1795
+ if (!record) {
1796
+ record = emptyRecord();
1797
+ map.set(name, record);
1798
+ }
1799
+ return record;
1800
+ }
1801
+ function bumpView(map, name, when = /* @__PURE__ */ new Date()) {
1802
+ const record = getRecord(map, name);
1803
+ record.view_count += 1;
1804
+ record.last_viewed_at = when.toISOString();
1805
+ }
1806
+ function bumpUse(map, name, when = /* @__PURE__ */ new Date()) {
1807
+ const record = getRecord(map, name);
1808
+ record.use_count += 1;
1809
+ record.last_used_at = when.toISOString();
1810
+ }
1811
+ function bumpPatch(map, name, when = /* @__PURE__ */ new Date()) {
1812
+ const record = getRecord(map, name);
1813
+ record.patch_count += 1;
1814
+ record.last_patched_at = when.toISOString();
1815
+ }
1816
+ /** Count one observed support-file read (design §5.5). The map is created on
1817
+ * first evidence only — a skill with no support reads keeps the field absent. */
1818
+ function bumpSupportRead(map, name, rel, when = /* @__PURE__ */ new Date()) {
1819
+ const record = getRecord(map, name);
1820
+ const counts = record.support_reads ?? {};
1821
+ counts[rel] = (counts[rel] ?? 0) + 1;
1822
+ record.support_reads = counts;
1823
+ record.last_viewed_at = when.toISOString();
1824
+ }
1825
+ function markAgentCreated(map, name) {
1826
+ getRecord(map, name).created_by = "agent";
1827
+ }
1828
+ function latestActivityAt(record) {
1829
+ const values = [
1830
+ record.last_used_at,
1831
+ record.last_viewed_at,
1832
+ record.last_patched_at
1833
+ ].filter((value) => typeof value === "string" && Number.isFinite(Date.parse(value)));
1834
+ if (values.length === 0) return null;
1835
+ return values.reduce((latest, value) => Date.parse(value) > Date.parse(latest) ? value : latest);
1836
+ }
1837
+ /** Days between an ISO timestamp (falling back to `created`) and `now`. An
1838
+ * unparseable date counts as 0 days: NaN silently froze every age comparison
1839
+ * (A2-9). */
1840
+ function daysSinceIso(iso, created, nowMs) {
1841
+ const t = Date.parse(iso ?? created);
1842
+ if (!Number.isFinite(t)) return 0;
1843
+ return (nowMs - t) / 864e5;
1844
+ }
1845
+ /** Idle days of one skill since its lifecycle age anchor (`last activity ??
1846
+ * created_at`) — the SAME anchor the curator's transitions use, so the
1847
+ * maintenance view and the lifecycle can never disagree about staleness. */
1848
+ function idleDays(record, now = /* @__PURE__ */ new Date()) {
1849
+ return daysSinceIso(latestActivityAt(record), record.created_at, now.getTime());
1850
+ }
1851
+ /**
1852
+ * Whether the library has ANY observed read evidence (C observation window):
1853
+ * reads were invisible to the usage sidecar before A2, so `view_count` zero
1854
+ * means "never read" ONLY after the first observed read exists anywhere in
1855
+ * the map. Before that, churn-based signals (write-ghost) are untrustworthy
1856
+ * and callers must suppress them. Pure and derived — never persisted.
1857
+ */
1858
+ function usageObserved(usage) {
1859
+ for (const record of usage.values()) if (record.view_count > 0) return true;
1860
+ return false;
1861
+ }
1862
+ /**
1863
+ * Curator suppression sidecar: built-in skills the curator has archived stay
1864
+ * suppressed across re-seeds, so the lifecycle never fights a re-created
1865
+ * bundled skill. Best-effort load/save, mirroring the usage sidecar posture.
1866
+ * Versioned shape ({ version, names }) with legacy plain-array compat.
1867
+ */
1868
+ const SUPPRESSED_FILE_VERSION = 1;
1869
+ function suppressedFile(root) {
1870
+ return join(root, ".curator-suppressed.json");
1871
+ }
1872
+ async function loadSuppressedNames(root, io = nodeEvolutionIo()) {
1873
+ return parseSuppressed(await io.readText(suppressedFile(root)));
1874
+ }
1875
+ function parseSuppressed(raw) {
1876
+ if (raw === null) return /* @__PURE__ */ new Set();
1877
+ try {
1878
+ const parsed = JSON.parse(raw);
1879
+ const names = Array.isArray(parsed) ? parsed : typeof parsed === "object" && parsed !== null && Array.isArray(parsed.names) ? parsed.names : [];
1880
+ return new Set(names.filter((entry) => typeof entry === "string"));
1881
+ } catch {
1882
+ return /* @__PURE__ */ new Set();
1883
+ }
1884
+ }
1885
+ /**
1886
+ * Plain wholesale write of the suppression sidecar (tests and fixture seeding).
1887
+ * @internal S2.4 (PLAN 2026-09-16, audit P2-31): NO production consumer
1888
+ * (verified by grep; production suppressions go through
1889
+ * {@link updateSuppressedNames}) — exported for the family's tests only. Do
1890
+ * not use it to write the sidecar in new code.
1891
+ *
1892
+ * The write rides the {@link transactIo} channel (the same lock the RMW
1893
+ * writer uses), not the former naked read → `io.writeText`: that form was an
1894
+ * unserialized read-modify-write — the last `saveSuppressedNames` in this file
1895
+ * with no lock, while its sibling `saveUsage` already carried the `@internal`
1896
+ * test-only note. Version discipline is unchanged (V24-09 / S2-14): a read
1897
+ * failure surfaces (an unreadable sidecar is never written over), a newer
1898
+ * on-disk schema is warned about and preserved byte-for-byte (the
1899
+ * byte-identical result short-circuits the write), and a malformed sidecar is
1900
+ * still overwritten with the v1 shape (the historical plain-writer posture).
1901
+ */
1902
+ async function saveSuppressedNames(root, names, io = nodeEvolutionIo()) {
1903
+ await transactIo(io, suppressedFile(root), (current) => {
1904
+ if (current !== null) try {
1905
+ const parsed = JSON.parse(current);
1906
+ if (parsed !== null && typeof parsed.version === "number" && parsed.version > 1) {
1907
+ console.warn(`suppression sidecar ${suppressedFile(root)} declares version ${String(parsed.version)} (newer than 1); not overwritten`);
1908
+ return current;
1909
+ }
1910
+ } catch {}
1911
+ return JSON.stringify({
1912
+ version: 1,
1913
+ names: [...names].sort()
1914
+ }, null, 2);
1915
+ });
1916
+ }
1917
+ /**
1918
+ * Atomic read-modify-write on the suppression sidecar (rc.50 P2-2): `task`
1919
+ * receives the set parsed from the current on-disk state and may mutate it;
1920
+ * the result is persisted inside the same transact so a second process
1921
+ * sharing DSH_HOME cannot interleave its RMW. Best-effort posture unchanged.
1922
+ */
1923
+ async function updateSuppressedNames(root, io, task) {
1924
+ await transactIo(io, suppressedFile(root), async (current) => {
1925
+ if (current !== null) {
1926
+ let parsed = null;
1927
+ try {
1928
+ parsed = JSON.parse(current);
1929
+ } catch {
1930
+ return current;
1931
+ }
1932
+ if (parsed !== null && typeof parsed.version === "number" && parsed.version > 1) {
1933
+ console.warn(`suppression sidecar ${suppressedFile(root)} declares version ${String(parsed.version)} (newer than 1); not overwritten`);
1934
+ return current;
1935
+ }
1936
+ }
1937
+ const names = parseSuppressed(current);
1938
+ await task(names);
1939
+ return JSON.stringify({
1940
+ version: 1,
1941
+ names: [...names].sort()
1942
+ }, null, 2);
1943
+ });
1944
+ }
1945
+ //#endregion
1946
+ //#region lib/types/state-store.js
1947
+ /**
1948
+ * Evolution home path helpers: the DSH root and `$DSH_HOME/evolution` for
1949
+ * plugin-owned sidecar state (reports, activity store, feedback file,
1950
+ * state-domain data).
1951
+ *
1952
+ * C-10: PATH HELPERS ONLY — despite the file name there is no store
1953
+ * here. Durable evolution state lives in the state stack (evolution-state over
1954
+ * evolution-state-json / -domain); skills and memories live in skill-store.ts
1955
+ * / memory-store.ts. The file name is kept deliberately: renaming it would
1956
+ * touch every family import for zero behavior change, and the audit records
1957
+ * the mismatch as known naming debt.
1958
+ */
1959
+ /**
1960
+ * DSH home root: `$DSH_HOME` or `~/.dsh`. Single source of the empty-string
1961
+ * fallback — an EMPTY or WHITESPACE-ONLY DSH_HOME resolves to the default
1962
+ * home, never to a CWD-relative path (0.3.19 W1.3, 0.3.22 F-207);
1963
+ * V8-06 (0.3.47) extends the guard to whitespace.
1964
+ * C-11 correction (S2.2, PLAN 2026-09-16): upstream `resolveDshHome`
1965
+ * (util/home-paths) uses `trim()` ONLY as the ADOPTION test and then uses the
1966
+ * RAW env value — the earlier "same trimmed source" form returned the trimmed
1967
+ * text, so `DSH_HOME=" /x "` produced `/x` where upstream produced the literal
1968
+ * padded path. The value semantics now match upstream line for line:
1969
+ * `const selected = configured ?? (fromEnv !== undefined &&
1970
+ * fromEnv.trim().length > 0 ? fromEnv : defaultDshHome())`.
1971
+ * OPT-27 (2026-09, plan D5 — accepted): the v10-era "no `~` expansion, no
1972
+ * resolve" divergence from upstream `resolveDshHome` is RETIRED. It became
1973
+ * load-bearing when the skill-catalog shadow made "same tree as the upstream
1974
+ * `USER_DSH_RANK` provider" a hard contract: upstream watches the EXPANDED
1975
+ * absolute `<home>/skills` while this value fed a literal `~/x` (a directory
1976
+ * named `~` under the host CWD) or a CWD-relative path — split-brain skill
1977
+ * trees, preset installs the platform never reads, doctor probes of a
1978
+ * directory nothing serves.
1979
+ * S2.2 (PLAN 2026-09-16), final correction: the result is ALWAYS
1980
+ * `resolve(expandHomePath(selected))` — the earlier form returned an
1981
+ * already-absolute value VERBATIM, so a trailing slash or `..` segment
1982
+ * landed unnormalized while upstream normalizes every value. Relative
1983
+ * `DSH_HOME` values change landing spot; a CLEAN absolute home stays
1984
+ * byte-identical (resolve is a no-op on it).
1985
+ */
1986
+ function evolutionRoot(env = process.env) {
1987
+ const fromEnv = env.DSH_HOME;
1988
+ const selected = fromEnv !== void 0 && fromEnv.trim().length > 0 ? fromEnv : join(homedir(), ".dsh");
1989
+ return resolve(selected === "~" ? homedir() : selected.startsWith("~/") || selected.startsWith("~\\") ? join(homedir(), selected.slice(2)) : selected);
1990
+ }
1991
+ /** Evolution home path helper: `$DSH_HOME/evolution` for plugin-owned sidecar
1992
+ * state (reports, activity store, feedback file, state-domain data). */
1993
+ function evolutionHome(env = process.env) {
1994
+ return join(evolutionRoot(env), "evolution");
1995
+ }
1996
+ //#endregion
1997
+ //#region lib/types/cost.js
1998
+ /**
1999
+ * Context-cost accounting for skill bodies (design §5.2).
2000
+ *
2001
+ * A raw character count is a poor budget: the same 100k characters cost very
2002
+ * different amounts of context in Chinese-heavy prose and in English. The
2003
+ * weighted unit makes the two comparable, and the token range exists only to
2004
+ * make the load cost visible next to the character count — it is an ESTIMATE,
2005
+ * never a measurement.
2006
+ *
2007
+ * Accounting basis: the ON-DISK form (`skillMdOnDisk()`, the same view the
2008
+ * write limit uses), so a body that is exactly at the limit cannot read as
2009
+ * over-limit here and pass there (the v37 P2-1 deadlock class).
2010
+ */
2011
+ /** Token weight of one CJK / kana / full-width code unit on the LIMIT basis —
2012
+ * upstream's model-independent conversion is 2.75 chars/token for prose, and CJK
2013
+ * prose is ~1 token per character (the conservative end of the 0.6–1.0 range the
2014
+ * estimate side reports). Thresholds are compared on THIS basis so a borrowed
2015
+ * character line keeps its meaning; the estimate range below reports the spread. */
2016
+ const TOKEN_CJK_WEIGHT = 1;
2017
+ /** Token weight of one non-CJK code unit on the LIMIT basis (1 / 2.75 ≈ 0.364). */
2018
+ const TOKEN_ASCII_WEIGHT = 1 / UPSTREAM_LIMIT_CHARS_PER_TOKEN;
2019
+ /** Token-per-unit bounds of the estimate range (CJK: 0.6–1.0, non-CJK: 1/4–1/3).
2020
+ * The range is the 4-chars/token estimate family, so on ASCII-heavy bodies the
2021
+ * LIMIT-basis `tokens` point can sit above `tokensHigh` (1/2.75 > 1/3): the two
2022
+ * answer different questions and are never nested by construction. */
2023
+ const COST_CJK_TOKEN_LOW = .6;
2024
+ const COST_CJK_TOKEN_HIGH = 1;
2025
+ const COST_ASCII_TOKEN_LOW = .25;
2026
+ const COST_ASCII_TOKEN_HIGH = 1 / 3;
2027
+ /** The token line a borrowed CHARACTER threshold draws for ONE body: 20k characters
2028
+ * of THIS composition, expressed in the same tokens `bodyCost` counts. Comparing
2029
+ * `tokens` against this line is deliberately equivalent to "chars >= line" — that
2030
+ * equivalence is what keeps a borrowed line's textual effect identical — while the
2031
+ * judgment itself, and every number reported, stays on the token scale.
2032
+ * @param lineChars - the borrowed character line (whole-body characters).
2033
+ * @param cost - the body's own cost breakdown.
2034
+ * @returns the equivalent token line (0 when the body is empty). */
2035
+ function tokenLineFor(lineChars, cost) {
2036
+ if (cost.chars === 0) return 0;
2037
+ return Math.round(lineChars * cost.tokens / cost.chars);
2038
+ }
2039
+ /** CJK ideographs, kana, full-width forms and CJK punctuation. */
2040
+ const CJK_RE = /[\u3000-\u303f\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff00-\uffef]/g;
2041
+ /**
2042
+ * Cost of one skill body.
2043
+ * @param content - the body text as written (trailing whitespace is normalized
2044
+ * away by the on-disk accounting, so callers need not pre-trim).
2045
+ * @returns the cost breakdown; an empty body answers all-zero.
2046
+ */
2047
+ function bodyCost(content) {
2048
+ const onDisk = skillMdOnDisk(content);
2049
+ const cjk = [...onDisk.matchAll(CJK_RE)].length;
2050
+ const chars = onDisk.length;
2051
+ const ascii = chars - cjk;
2052
+ return {
2053
+ chars,
2054
+ cjk,
2055
+ ascii,
2056
+ tokens: Math.round(cjk * 1 + ascii * TOKEN_ASCII_WEIGHT),
2057
+ tokensLow: Math.round(cjk * COST_CJK_TOKEN_LOW + ascii * COST_ASCII_TOKEN_LOW),
2058
+ tokensHigh: Math.round(cjk * 1 + ascii * COST_ASCII_TOKEN_HIGH)
2059
+ };
2060
+ }
2061
+ //#endregion
2062
+ //#region lib/types/skill-lint.js
2063
+ const msg = (parts) => parts.map((p) => typeof p === "string" ? p : String(p)).join("");
2064
+ /** One rule yields AT MOST one finding (contract §3). `body-oversize-2x` is the only rule whose
2065
+ * severity can escalate a verdict to needs-restructure. */
2066
+ const RULES = [
2067
+ {
2068
+ id: "unreadable-skill",
2069
+ severity: "error",
2070
+ run: (facts) => facts.readable && facts.dims.bodyChars !== null ? null : {
2071
+ severity: "error",
2072
+ rule: "unreadable-skill",
2073
+ message: msg([facts.skillName, ": SKILL.md could not be read — no health claim is possible"]),
2074
+ count: 1
2075
+ }
2076
+ },
2077
+ {
2078
+ id: "body-oversize-2x",
2079
+ severity: "error",
2080
+ run: (facts) => facts.overTwiceSoftLine ? {
2081
+ severity: "error",
2082
+ rule: "body-oversize-2x",
2083
+ message: msg([
2084
+ facts.skillName,
2085
+ ": body is at or past twice the soft line (",
2086
+ facts.softLineChars,
2087
+ " chars); keeping the current skill is valid"
2088
+ ]),
2089
+ count: 1
2090
+ } : null
2091
+ },
2092
+ {
2093
+ id: "body-oversize",
2094
+ severity: "warn",
2095
+ run: (facts) => !facts.overTwiceSoftLine && facts.overSoftLine ? {
2096
+ severity: "warn",
2097
+ rule: "body-oversize",
2098
+ message: msg([
2099
+ facts.skillName,
2100
+ ": body is at or above the soft line (",
2101
+ facts.softLineChars,
2102
+ " chars); keep is valid — size alone does not require a split"
2103
+ ]),
2104
+ count: 1
2105
+ } : null
2106
+ },
2107
+ {
2108
+ id: "stamp-density",
2109
+ severity: "warn",
2110
+ run: (facts) => {
2111
+ const density = facts.dims.stampDensityPerKb;
2112
+ const hits = facts.dims.stampHits;
2113
+ if (density === null || hits === null || density < facts.stampLimitPerKb) return null;
2114
+ return {
2115
+ severity: "warn",
2116
+ rule: "stamp-density",
2117
+ message: msg([
2118
+ facts.skillName,
2119
+ ": stamp density ",
2120
+ density.toFixed(1),
2121
+ "/KB (rc/sha/date lines — log-like content)"
2122
+ ]),
2123
+ count: hits
2124
+ };
2125
+ }
2126
+ },
2127
+ {
2128
+ id: "body-without-support",
2129
+ severity: "warn",
2130
+ run: (facts) => facts.dims.supportGroups === 0 && facts.dims.bodyChars !== null && facts.dims.bodyChars >= facts.softLineChars / 2 ? {
2131
+ severity: "warn",
2132
+ rule: "body-without-support",
2133
+ message: msg([
2134
+ facts.skillName,
2135
+ ": large body (",
2136
+ facts.dims.bodyChars,
2137
+ " chars) with NO support files"
2138
+ ]),
2139
+ count: 1
2140
+ } : null
2141
+ },
2142
+ {
2143
+ id: "references-sprawl",
2144
+ severity: "warn",
2145
+ run: (facts) => {
2146
+ const files = facts.dims.supportFiles;
2147
+ if (files === null || files < 60) return null;
2148
+ return {
2149
+ severity: "warn",
2150
+ rule: "references-sprawl",
2151
+ message: msg([
2152
+ facts.skillName,
2153
+ ": ",
2154
+ files,
2155
+ " support files"
2156
+ ]),
2157
+ count: files
2158
+ };
2159
+ }
2160
+ },
2161
+ {
2162
+ id: "scope-overloaded",
2163
+ severity: "warn",
2164
+ run: (facts) => {
2165
+ const hits = facts.dims.hardCapHits;
2166
+ const files = facts.dims.supportFiles;
2167
+ if (hits === null || files === null || hits < facts.hardCapMinHits || files < 3) return null;
2168
+ return {
2169
+ severity: "warn",
2170
+ rule: "scope-overloaded",
2171
+ message: msg([
2172
+ facts.skillName,
2173
+ ": ",
2174
+ hits,
2175
+ " hard-cap hit(s) with ",
2176
+ files,
2177
+ " support files — remaining growth may be scope"
2178
+ ]),
2179
+ count: hits
2180
+ };
2181
+ }
2182
+ },
2183
+ {
2184
+ id: "write-ghost",
2185
+ severity: "warn",
2186
+ run: (facts) => {
2187
+ const patches = facts.dims.churnPatches;
2188
+ const reads = facts.dims.churnReads;
2189
+ if (patches === null || reads === null || patches < facts.churnMinPatches || reads > 0) return null;
2190
+ return {
2191
+ severity: "warn",
2192
+ rule: "write-ghost",
2193
+ message: msg([
2194
+ facts.skillName,
2195
+ ": ",
2196
+ patches,
2197
+ " patch(es), never read"
2198
+ ]),
2199
+ count: patches
2200
+ };
2201
+ }
2202
+ }
2203
+ ];
2204
+ function lintSkill(facts) {
2205
+ const out = [];
2206
+ for (const rule of RULES) {
2207
+ const hit = rule.run(facts);
2208
+ if (hit !== null) out.push(hit);
2209
+ }
2210
+ return out;
2211
+ }
2212
+ /** What a write introduced, what got worse, what got fixed. A rule whose count grew (one site to
2213
+ * nine) counts as worsened — comparing by rule name alone reported nothing. */
2214
+ function diffFindings(before, after) {
2215
+ const beforeByRule = new Map(before.map((f) => [f.rule, f]));
2216
+ const afterByRule = new Map(after.map((f) => [f.rule, f]));
2217
+ return {
2218
+ introduced: after.filter((f) => !beforeByRule.has(f.rule)),
2219
+ worsened: after.filter((f) => {
2220
+ const old = beforeByRule.get(f.rule);
2221
+ return old !== void 0 && f.count > old.count;
2222
+ }),
2223
+ resolved: before.filter((f) => !afterByRule.has(f.rule)).map((f) => f.rule)
2224
+ };
2225
+ }
2226
+ /** Support files = markdown files under references/ (contract §4: unit frozen, underscore-prefixed
2227
+ * excluded). Paths are supplied by the caller — this module never touches the filesystem. */
2228
+ function countReferenceFiles(paths) {
2229
+ return paths.filter((p) => {
2230
+ const n = p.replace(/\\/g, "/");
2231
+ if (!(n.includes("/references/") || n.startsWith("references/")) || !n.endsWith(".md")) return false;
2232
+ return !n.slice(n.lastIndexOf("/") + 1).startsWith("_");
2233
+ }).length;
2234
+ }
2235
+ //#endregion
2236
+ //#region lib/types/evolution-events.js
2237
+ /**
2238
+ * Self-evolution event log (rc.68): an append-only sidecar under
2239
+ * `$DSH_HOME/evolution/events.json` that is the single source of truth for
2240
+ * the self-improvement loop. Feedback increments and learn actions share one
2241
+ * ordered timeline (`seq` is the ordering key), so "feedback before/after a
2242
+ * learn on target X" is answerable. The aggregate `feedback.json` is a
2243
+ * rebuildable boot cache, never the truth.
2244
+ *
2245
+ * Usage events (C semantics, rc.73+): `type:'usage'` records are the
2246
+ * OBSERVATION WINDOW ANCHOR — written once, when the library's first observed
2247
+ * read (`view_count` 0 -> 1) happens. The anchor is the durable timeline record
2248
+ * of that moment: the churn-suppression gate itself (`usageObserved()`) reads
2249
+ * the usage SIDECAR's own first-view evidence, since reads were invisible to it
2250
+ * pre-A2 and no sidecar record can reach `view_count > 0` without the same
2251
+ * 0 -> 1 transition. `counts` on the event is a cumulative library-wide
2252
+ * snapshot (skills/views/use/patches) at that moment, and `window.opened` pins
2253
+ * the window start for the timeline. (V27 G3.3: `verify-event-pairing` requires
2254
+ * every persisted type to have a production reader or a declared external
2255
+ * contract — this one is the latter.)
2256
+ *
2257
+ * Rotation (rc.71, 007 design): when the active log reaches
2258
+ * `EVENT_LOG_ROTATE_AT` the older half is split into an archive
2259
+ * (`events-<lastArchivedSeq>.json`); the boot timeline merges active +
2260
+ * archives and dedupes by seq (active copy wins), so the rotation crash window
2261
+ * yields the identical timeline. Archival naming is STRICTLY numeric
2262
+ * (`/^events-\d+\.json$/`) — user files under the same directory are never
2263
+ * read as archives and never pruned (rc.72 G-2).
2264
+ */
2265
+ const EVENT_LOG_VERSION = 1;
2266
+ /** Active-log split point (rc.71): when the active log reaches this many events
2267
+ * the older half is rotated into an archive; the active stays bounded so a
2268
+ * single append stays O(active) instead of O(total-history). Tunable default —
2269
+ * callers may override per append (the tests use small values). */
2270
+ const EVENT_LOG_ROTATE_AT = 4e3;
2271
+ /** Number of archives retained (rc.71): older archives are pruned at rotation,
2272
+ * mirroring retainReports. The horizon covers the loop-analysis window. */
2273
+ const EVENT_LOG_RETAIN_ARCHIVES = 10;
2274
+ /** Archive file prefix: `events-<lastArchivedSeq>.json`. The active file is
2275
+ * `events.json` and never matches this glob. */
2276
+ const EVENT_ARCHIVE_PREFIX = "events-";
2277
+ /** Archive naming is strictly numeric: a user file such as `events-backup.json`
2278
+ * under the same directory is neither read into the timeline nor pruned. */
2279
+ const EVENT_ARCHIVE_RE = /^events-(\d+)\.json$/;
2280
+ function eventsFile(home) {
2281
+ return join(home, "evolution", "events.json");
2282
+ }
2283
+ /** I-5 (v18): one lightweight description of the durable event payload
2284
+ * contract. The log is a FILE boundary (a host, a script or an older version
2285
+ * can write it), so `appendEvolutionEvent` refuses a record no consumer can
2286
+ * fold instead of persisting it and failing silently later. The process event
2287
+ * bus stays unvalidated — that is a typed same-process boundary.
2288
+ * @param event - the candidate event record.
2289
+ * @returns a human-readable issue, or null when the record is well-formed.
2290
+ */
2291
+ function evolutionEventPayloadIssue(event) {
2292
+ const type = event.type;
2293
+ if (typeof type !== "string") return `unknown event type "${String(type)}"`;
2294
+ switch (type) {
2295
+ case "feedback":
2296
+ if (event.kind !== "skill" && event.kind !== "session") return "feedback event requires kind skill|session";
2297
+ if (event.rating !== "positive" && event.rating !== "negative") return "feedback event requires rating positive|negative";
2298
+ if (typeof event.target !== "string" || event.target.trim() === "") return "feedback event requires a non-empty target";
2299
+ return null;
2300
+ case "maintain": return typeof event.runId === "string" ? null : "maintain event requires runId";
2301
+ case "learn":
2302
+ case "usage": return null;
2303
+ case "hard-cap":
2304
+ if (typeof event.target !== "string" || event.target.trim() === "") return "hard-cap event requires a non-empty target";
2305
+ if (typeof event.bodyChars !== "number" || !Number.isFinite(event.bodyChars)) return "hard-cap event requires a finite bodyChars";
2306
+ return null;
2307
+ default: return `unknown event type "${type}"`;
2308
+ }
2309
+ }
2310
+ function isEventRecord(event) {
2311
+ const seq = event?.seq;
2312
+ return typeof event === "object" && event !== null && typeof seq === "number" && Number.isFinite(seq);
2313
+ }
2314
+ /**
2315
+ * Parse an event log body. A missing file, a whitespace-only file (rc.69:
2316
+ * rebuildable, NOT malformed) or a corrupt one reads as empty; corrupt content
2317
+ * is still refused on append, never overwritten.
2318
+ *
2319
+ * This reader is **v1-only** (F-338): a body carrying a `version` other than
2320
+ * `EVENT_LOG_VERSION` is a future-format log this reader cannot interpret, so
2321
+ * it reads as an EMPTY timeline rather than being mis-parsed as v1. The read
2322
+ * side never overwrites it on its own — `appendEvolutionEvent` rejects a
2323
+ * version mismatch up front and preserves the original bytes, so a newer log
2324
+ * is never silently downgraded here.
2325
+ *
2326
+ * Per-entry normalization (rc.70 F-1): entries without a numeric `seq` are
2327
+ * skipped here and dropped at the next append — valid entries survive, the
2328
+ * damaged record is the only loss (self-heal semantics, matching the usage
2329
+ * sidecar's per-field normalization on read).
2330
+ */
2331
+ /**
2332
+ * Post-parse v1 gate shared by parseEvolutionEvents and appendEvolutionEvent
2333
+ * (C-06, v10 audit: the append used to JSON.parse the same body a second time
2334
+ * through parseEvolutionEvents — double parse cost per append). A null parse
2335
+ * (missing/whitespace/unparsable body) reads as an empty timeline.
2336
+ */
2337
+ function v1EventRecords(parsed) {
2338
+ if (parsed === null) return [];
2339
+ if (parsed.version !== void 0 && parsed.version !== 1) return [];
2340
+ if (!Array.isArray(parsed.events)) return [];
2341
+ return parsed.events.filter(isEventRecord);
2342
+ }
2343
+ function parseEvolutionEvents(raw) {
2344
+ if (raw === null || raw.trim() === "") return [];
2345
+ try {
2346
+ return v1EventRecords(JSON.parse(raw));
2347
+ } catch {
2348
+ return [];
2349
+ }
2350
+ }
2351
+ /**
2352
+ * List the numeric archives under the log's directory, sorted ascending by
2353
+ * their last-archived seq. Single glob predicate for the timeline, the
2354
+ * retention pass and the feedback migration check (rc.72 H-3).
2355
+ */
2356
+ async function listEventArchives(io, path) {
2357
+ const dir = dirname(path);
2358
+ return (await io.list(dir)).filter((name) => EVENT_ARCHIVE_RE.test(name)).sort((a, b) => {
2359
+ return Number.parseInt(a.slice(7, a.length - 5), 10) - Number.parseInt(b.slice(7, b.length - 5), 10);
2360
+ });
2361
+ }
2362
+ /**
2363
+ * Append one event under the write lock (rc.68): `seq` = current max + 1
2364
+ * computed inside the transact, so two processes appending concurrently never
2365
+ * collide. A malformed log is refused (bytes preserved) and the append fails.
2366
+ * Returns the assigned seq.
2367
+ *
2368
+ * Rotation (rc.71, 007 design): when the active log reaches `rotateAt`, the
2369
+ * older half is copied into an archive inside the SAME transact (the archive
2370
+ * path has its own lock, so no recursion) and the active is replaced with the
2371
+ * newer half + the new event. seqs stay globally monotonic; a crash between
2372
+ * archive write and active write leaves both copies, which the timeline merge
2373
+ * dedupes by seq. An archive-write failure aborts the append (active keeps the
2374
+ * full old content — no loss) and the caller's best-effort handling applies.
2375
+ *
2376
+ * rc.72 G-1: when the ACTIVE is missing/whitespace but archives exist (a
2377
+ * deleted active, or B-2 self-heal), seq derivation consults the archive names
2378
+ * — the active restarts AFTER the highest archived seq, never at 1, so a new
2379
+ * event can never shadow an archived one in the seq-deduped timeline.
2380
+ */
2381
+ async function appendEvolutionEvent(io, path, event, rotateAt = EVENT_LOG_ROTATE_AT, fence) {
2382
+ const issue = evolutionEventPayloadIssue(event);
2383
+ if (issue !== null) throw new Error(`evolution event refused: ${issue}`);
2384
+ let assigned = 0;
2385
+ let refuseMessage = "";
2386
+ let parsedBody = null;
2387
+ const write = async () => {
2388
+ await transactIo(io, path, async (current) => {
2389
+ parsedBody = null;
2390
+ refuseMessage = "";
2391
+ assigned = 0;
2392
+ if (current !== null && current.trim() !== "") {
2393
+ let shape;
2394
+ try {
2395
+ shape = JSON.parse(current);
2396
+ } catch {
2397
+ return current;
2398
+ }
2399
+ parsedBody = shape;
2400
+ if (shape.version !== void 0 && shape.version !== 1) {
2401
+ const found = typeof shape.version === "number" || typeof shape.version === "string" ? String(shape.version) : "unknown";
2402
+ const kind = typeof shape.version === "number" || typeof shape.version === "string" ? typeof shape.version : "unknown";
2403
+ refuseMessage = `evolution event log version mismatch (expected version 1, got ${kind === "string" ? `"${found}"` : found} (${kind})) and was not touched`;
2404
+ return current;
2405
+ }
2406
+ }
2407
+ const rotated = await rotateIfDue(io, path, v1EventRecords(parsedBody), rotateAt);
2408
+ if (!rotated.ok) {
2409
+ refuseMessage = rotated.reason;
2410
+ return current;
2411
+ }
2412
+ const events = rotated.events;
2413
+ let maxSeq = events.reduce((max, entry) => Math.max(max, entry.seq), 0);
2414
+ for (const name of await listEventArchives(io, path)) maxSeq = Math.max(maxSeq, Number.parseInt(name.slice(7, name.length - 5), 10));
2415
+ const record = {
2416
+ ...event,
2417
+ seq: maxSeq + 1,
2418
+ at: (/* @__PURE__ */ new Date()).toISOString()
2419
+ };
2420
+ assigned = record.seq;
2421
+ return JSON.stringify({
2422
+ version: 1,
2423
+ events: [...events, record]
2424
+ }, null, 2);
2425
+ });
2426
+ };
2427
+ if (fence !== void 0) await fence.run(write);
2428
+ else await write();
2429
+ if (assigned === 0) throw new Error(`${refuseMessage || "evolution event log is malformed and was not touched"}: ${path}`);
2430
+ return assigned;
2431
+ }
2432
+ /** The collision archive is mergeable only when this v1 writer can read it
2433
+ * (P2-11): a foreign `version` (F-338) or a body without an `events` array is
2434
+ * refused, so a merge can never downgrade it or empty it out.
2435
+ * @param parsed - the parsed collision archive body.
2436
+ * @returns the usable events, or null when the archive must not be rewritten. */
2437
+ function mergeableCollisionEvents(parsed) {
2438
+ if (parsed.version !== void 0 && parsed.version !== 1) return null;
2439
+ if (!Array.isArray(parsed.events)) return null;
2440
+ return parsed.events.filter(isEventRecord);
2441
+ }
2442
+ /**
2443
+ * Split the active log at its midpoint when due: the older half is written to
2444
+ * `events-<lastArchivedSeq>.json` (await — a failed archive write aborts the
2445
+ * append so the active is never truncated without its copy), old archives are
2446
+ * pruned, and the newer half is returned as the next active body. No-op when
2447
+ * under the threshold; `rotateAt < 2` is a guarded no-op (rc.72 G-1: a
2448
+ * one-event rotate would archive everything and restart seqs at 1).
2449
+ */
2450
+ async function rotateIfDue(io, path, events, rotateAt) {
2451
+ if (!Number.isFinite(rotateAt) || rotateAt < 2 || events.length < rotateAt) return {
2452
+ ok: true,
2453
+ events
2454
+ };
2455
+ const mid = Math.ceil(events.length / 2);
2456
+ const head = events.slice(0, mid);
2457
+ const tail = events.slice(mid);
2458
+ if (tail.length === 0) return {
2459
+ ok: true,
2460
+ events
2461
+ };
2462
+ const anchor = tail[0]?.seq ?? 0;
2463
+ const archivePath = join(dirname(path), `${EVENT_ARCHIVE_PREFIX}${anchor - 1}.json`);
2464
+ let archived = head;
2465
+ let existing;
2466
+ try {
2467
+ existing = await io.readText(archivePath);
2468
+ } catch (error) {
2469
+ return {
2470
+ ok: false,
2471
+ reason: `evolution event archive collision at ${archivePath} could not be read (${error instanceof Error ? error.message : String(error)}) and was not touched`
2472
+ };
2473
+ }
2474
+ if (existing !== null) {
2475
+ let parsed = null;
2476
+ try {
2477
+ parsed = JSON.parse(existing);
2478
+ } catch {
2479
+ parsed = null;
2480
+ }
2481
+ if (parsed === null) {
2482
+ const shiftPath = `${archivePath}.${Date.now()}.collide`;
2483
+ await io.writeText(shiftPath, JSON.stringify({
2484
+ version: 1,
2485
+ events: head
2486
+ }, null, 2));
2487
+ console.warn(`evolution-events: rotation hit an unparsable archive collision — the rotated head band was preserved at ${shiftPath} but is OUTSIDE the logical timeline; inspect and merge it manually`);
2488
+ await retainEventArchives(io, path);
2489
+ await pruneCollideArchives(io, path);
2490
+ return {
2491
+ ok: true,
2492
+ events: tail
2493
+ };
2494
+ }
2495
+ const prior = mergeableCollisionEvents(parsed);
2496
+ if (prior === null) return {
2497
+ ok: false,
2498
+ reason: `evolution event archive collision at ${archivePath} is not a readable version-1 archive (future version, or no "events" array) and was not touched`
2499
+ };
2500
+ const bySeq = new Map(prior.map((event) => [event.seq, event]));
2501
+ for (const event of head) bySeq.set(event.seq, event);
2502
+ archived = [...bySeq.values()].sort((a, b) => a.seq - b.seq);
2503
+ }
2504
+ await io.writeText(archivePath, JSON.stringify({
2505
+ version: 1,
2506
+ events: archived
2507
+ }, null, 2));
2508
+ await retainEventArchives(io, path);
2509
+ return {
2510
+ ok: true,
2511
+ events: tail
2512
+ };
2513
+ }
2514
+ /**
2515
+ * Prune old event archives (rc.71): keep the newest `EVENT_LOG_RETAIN_ARCHIVES`.
2516
+ * The name's numeric part is the last archived seq, so ordering is NUMERIC —
2517
+ * lexicographic would rank `events-10` before `events-2`. Only strictly
2518
+ * numeric names participate (rc.72 G-2: user files are never deleted).
2519
+ * Best-effort per removal; exported for the retention test.
2520
+ */
2521
+ async function retainEventArchives(io, path) {
2522
+ const dir = dirname(path);
2523
+ const names = await listEventArchives(io, path);
2524
+ const excess = names.slice(0, Math.max(0, names.length - 10));
2525
+ for (const name of excess) await io.remove(join(dir, name)).catch(() => {});
2526
+ }
2527
+ /** v31 EVENTS-02: prune shift-aside collision files (`events-*.json.<ts>.collide`)
2528
+ * after the same 7-day window the `.corrupt` sweep uses. They are write-once
2529
+ * recovery artifacts no reader accepts; without a sweep they accumulated
2530
+ * without bound across rollback episodes. No mtime probe → keep (fail-safe). */
2531
+ const COLLIDE_AGE_MS = 10080 * 60 * 1e3;
2532
+ async function pruneCollideArchives(io, path) {
2533
+ const dir = dirname(path);
2534
+ let names;
2535
+ try {
2536
+ names = await io.list(dir);
2537
+ } catch {
2538
+ return;
2539
+ }
2540
+ const now = Date.now();
2541
+ for (const name of names) {
2542
+ if (!name.endsWith(".collide") || !name.startsWith("events-")) continue;
2543
+ const full = join(dir, name);
2544
+ const stamp = name.match(/\.(\d{13})\.collide$/);
2545
+ if (stamp && now - Number(stamp[1]) < COLLIDE_AGE_MS) continue;
2546
+ if (!stamp) try {
2547
+ const mtime = await io.mtime?.(full);
2548
+ if (typeof mtime !== "number" || now - mtime < COLLIDE_AGE_MS) continue;
2549
+ } catch {
2550
+ continue;
2551
+ }
2552
+ await io.remove(full).catch(() => {});
2553
+ }
2554
+ }
2555
+ /** Read the event log; a missing/whitespace-only file reads as empty, corrupt
2556
+ * content is flagged (and refused on append). A well-formed future-version body
2557
+ * is v1-incompatible: it reads as EMPTY and is now flagged malformed as well
2558
+ * (C-events-dispatch-1, v43). F-338's own guarantees are untouched — the reader
2559
+ * never mis-shapes a newer format and the append path refuses it up front, so
2560
+ * the original bytes survive — while the flag reports what the old reader hid:
2561
+ * every record that body holds is dropped from this read. */
2562
+ async function readEvolutionEvents(io, path) {
2563
+ let raw;
2564
+ try {
2565
+ raw = await io.readText(path);
2566
+ } catch {
2567
+ return {
2568
+ events: [],
2569
+ malformed: true
2570
+ };
2571
+ }
2572
+ if (raw === null || raw.trim() === "") return {
2573
+ events: [],
2574
+ malformed: false
2575
+ };
2576
+ try {
2577
+ const parsed = JSON.parse(raw);
2578
+ if (parsed.version !== void 0 && parsed.version !== 1) return {
2579
+ events: [],
2580
+ malformed: true
2581
+ };
2582
+ if (!Array.isArray(parsed.events)) return {
2583
+ events: [],
2584
+ malformed: false
2585
+ };
2586
+ return {
2587
+ events: parsed.events.filter(isEventRecord),
2588
+ malformed: false
2589
+ };
2590
+ } catch {
2591
+ return {
2592
+ events: [],
2593
+ malformed: true
2594
+ };
2595
+ }
2596
+ }
2597
+ /**
2598
+ * Read the full timeline (rc.71): active log + all archives, merged by seq
2599
+ * (active copy wins, duplicates only arise from the rotation crash window),
2600
+ * sorted ascending. Per-file malformed flag as in `readEvolutionEvents`; a
2601
+ * flagged ARCHIVE (unreadable, damaged, or a future-version body this reader
2602
+ * cannot interpret) is SKIPPED — it never bricks the boot, the returned events
2603
+ * simply LACK that seq band, and `malformed` is the only signal that they do
2604
+ * (C-events-dispatch-1, v43: the flag is the consumer's contract; a truncated
2605
+ * timeline must never be folded back as if it were complete).
2606
+ */
2607
+ async function readEvolutionTimeline(io, path, archives) {
2608
+ const dir = dirname(path);
2609
+ let malformed = false;
2610
+ const bySeq = /* @__PURE__ */ new Map();
2611
+ for (const name of archives ?? await listEventArchives(io, path)) {
2612
+ const read = await readEvolutionEvents(io, join(dir, name));
2613
+ if (read.malformed) malformed = true;
2614
+ for (const event of read.events) bySeq.set(event.seq, event);
2615
+ }
2616
+ const active = await readEvolutionEvents(io, path);
2617
+ if (active.malformed) malformed = true;
2618
+ for (const event of active.events) bySeq.set(event.seq, event);
2619
+ return {
2620
+ events: [...bySeq.values()].sort((a, b) => a.seq - b.seq),
2621
+ malformed
2622
+ };
2623
+ }
2624
+ //#endregion
2625
+ //#region lib/types/fuzzy-match.js
2626
+ /**
2627
+ * Fuzzy string matching and replacement for patch/restructure edits of skill files.
2628
+ *
2629
+ * Split out of skill-store.ts (S2-1): pure text functions with no store state.
2630
+ * The store imports the scan, the budgets and the replace entry points directly;
2631
+ * none of them is re-exported, so the package export surface is unchanged.
2632
+ */
2633
+ function fuzzyIndexOf(content, pattern, from = 0) {
2634
+ const isSpace = (char) => char !== void 0 && /[ \t]/.test(char);
2635
+ const escaped = (char) => {
2636
+ if (char === "n") return "\n";
2637
+ if (char === "t") return " ";
2638
+ if (char === "r") return "\r";
2639
+ return null;
2640
+ };
2641
+ for (let start = from; start < content.length; start += 1) {
2642
+ let contentIndex = start;
2643
+ let patternIndex = 0;
2644
+ while (patternIndex < pattern.length && contentIndex < content.length) {
2645
+ const patternChar = pattern[patternIndex];
2646
+ const contentChar = content[contentIndex];
2647
+ if (isSpace(patternChar)) {
2648
+ while (patternIndex < pattern.length && isSpace(pattern[patternIndex])) patternIndex += 1;
2649
+ while (contentIndex < content.length && isSpace(content[contentIndex])) contentIndex += 1;
2650
+ continue;
2651
+ }
2652
+ const escapedChar = patternChar === "\\" ? escaped(pattern[patternIndex + 1]) : null;
2653
+ if (escapedChar !== null && contentChar === escapedChar) {
2654
+ patternIndex += 2;
2655
+ contentIndex += 1;
2656
+ continue;
2657
+ }
2658
+ if (patternChar === contentChar) {
2659
+ contentIndex += 1;
2660
+ patternIndex += 1;
2661
+ continue;
2662
+ }
2663
+ break;
2664
+ }
2665
+ if (patternIndex === pattern.length) return [start, contentIndex];
2666
+ }
2667
+ return null;
2668
+ }
2669
+ /** V6-17 (0.3.37): the fuzzy-patch scan is O(n·m) with no input bound; a
2670
+ * non-exact anchor past these budgets would block the event loop (measured
2671
+ * ~6s at 20k×20k). Exact matches go through the fast `includes` path and stay
2672
+ * allowed regardless of size. */
2673
+ const FUZZY_MAX_PATTERN_CHARS = 4096;
2674
+ const FUZZY_MAX_WORK = 8e6;
2675
+ /** Trim leading whitespace of the first line and trailing whitespace of the last line. */
2676
+ function trimPatternBoundaries(pattern) {
2677
+ const from = pattern.search(/\S/);
2678
+ const trimmed = from < 0 ? pattern : pattern.slice(from);
2679
+ const trailing = trimmed.search(/\s+$/);
2680
+ return trailing < 0 ? trimmed : trimmed.slice(0, trailing);
2681
+ }
2682
+ /** Replace only the fuzzy-matched span, preserving all surrounding bytes.
2683
+ * V7-11 (0.3.44): the replaceAll loop accumulates the per-scan cost — the
2684
+ * single-scan budget at the caller only bounded ONE fuzzyIndexOf, while an
2685
+ * unbounded number of matches × O(n·m) each could still stall the loop.
2686
+ * When the accumulated cost exceeds the budget the whole replace fails
2687
+ * (null) instead of partially applying an arbitrary prefix. */
2688
+ function fuzzyReplace(content, oldString, newString, replaceAll) {
2689
+ let current = content;
2690
+ let scanFrom = 0;
2691
+ let totalWork = 0;
2692
+ for (;;) {
2693
+ totalWork += current.length * oldString.length;
2694
+ if (totalWork > 8e6) return null;
2695
+ const match = fuzzyIndexOf(current, oldString, scanFrom);
2696
+ if (match === null) return current;
2697
+ const [start, end] = match;
2698
+ const next = current.slice(0, start) + newString + current.slice(end);
2699
+ if (!replaceAll) return next;
2700
+ current = next;
2701
+ scanFrom = start + newString.length;
2702
+ }
2703
+ }
2704
+ function fuzzyPatch(content, oldString, newString, replaceAll = false) {
2705
+ if (oldString === "") return null;
2706
+ if (content.includes(oldString)) return replaceAll ? content.split(oldString).join(newString) : content.replace(oldString, () => newString);
2707
+ const boundary = trimPatternBoundaries(oldString);
2708
+ if (boundary === "") return null;
2709
+ if (boundary !== oldString) {
2710
+ if (fuzzyIndexOf(content, boundary) !== null) return fuzzyReplace(content, boundary, newString, replaceAll);
2711
+ }
2712
+ if (fuzzyIndexOf(content, oldString) !== null) return fuzzyReplace(content, oldString, newString, replaceAll);
2713
+ return null;
2714
+ }
2715
+ /** Deterministic section-extraction plan facts; the caller owns the IO and the append semantics. */
2716
+ //#endregion
2717
+ //#region lib/types/serial.js
2718
+ /**
2719
+ * A process-local serial task queue: each task starts only after the previous
2720
+ * one settles (success or failure), so read-modify-write sequences that share
2721
+ * one file never interleave inside this process. When the IO backend provides
2722
+ * a cross-process transact lock, that is the first layer; the node backend does
2723
+ * not, so this chain is its only serialization. (0.3.17 S2.8, T-1: the shape was
2724
+ * duplicated in state-json and
2725
+ * memory-files — one factory now).
2726
+ */
2727
+ function makeSerialQueue() {
2728
+ let chain = Promise.resolve();
2729
+ return (task) => {
2730
+ const run = chain.then(task, task);
2731
+ chain = run.then(() => void 0, () => void 0);
2732
+ return run;
2733
+ };
2734
+ }
2735
+ //#endregion
2736
+ //#region lib/types/numeric.js
2737
+ /**
2738
+ * Numeric config clamping for the dsh-evolution plugin family.
2739
+ *
2740
+ * G3.1 (0.3.23): numeric configuration values are normalised through a single
2741
+ * helper so 0 / negative / NaN / ±Infinity / out-of-range all fall back to the
2742
+ * package default instead of silently becoming a "disabled" special value or
2743
+ * folding as NaN into a computation. A non-finite value (NaN, ±Infinity) is
2744
+ * never a legitimate config, so it always falls back. The schema layer (a
2745
+ * `.min(1)` clamp on the number schema) is a first-line guard where it can
2746
+ * reject invalid values; this helper is the mandatory assembly-time clamp that
2747
+ * also catches what schemastery lets through (NaN and +Infinity both pass a
2748
+ * bare number schema).
2749
+ *
2750
+ * The scope here is pure numeric conversion only (no schemastery import), so
2751
+ * evolution-core stays free of a schemastery dependency. Per-package Config
2752
+ * schemas keep their own `.min()`/`.default()` call sites.
2753
+ * @module @lmzhen/dsh-evolution-core
2754
+ */
2755
+ /**
2756
+ * Clamp a numeric config to the `[min, max]` range.
2757
+ *
2758
+ * A non-finite value (NaN, ±Infinity), a non-number, or a value outside the
2759
+ * inclusive range falls back to `fallback`. When `opts.min >= 1`, 0 and
2760
+ * negative values also fall back to `fallback` — a 0 is never treated as a
2761
+ * special "disabled" meaning (G3.1 decision). Callers that legitimately allow
2762
+ * 0 (e.g. a threshold or a zero-cost weight) pass `{ min: 0 }` or omit the
2763
+ * range.
2764
+ *
2765
+ * @param value - the raw numeric config, possibly `undefined` (absent).
2766
+ * @param fallback - the default value to return when the value is invalid.
2767
+ * @param opts - optional inclusive lower/upper bound.
2768
+ * @returns `value` when it is a finite number within range, else `fallback`.
2769
+ */
2770
+ function clampedNumber(value, fallback, opts) {
2771
+ if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
2772
+ const { min, max } = opts ?? {};
2773
+ if (min !== void 0 && value < min) return fallback;
2774
+ if (max !== void 0 && value > max) return fallback;
2775
+ return value;
2776
+ }
2777
+ //#endregion
2778
+ //#region lib/types/threats.js
2779
+ /**
2780
+ * Threat scanning for agent-authored memory and skill content.
2781
+ *
2782
+ * Ported as a small, dependency-free subset of Hermes Agent's
2783
+ * `tools/threat_patterns.py` + hermes-claw `threats.ts`.
2784
+ *
2785
+ * Policy (P1-1, v19): a finding either BLOCKS the write or only REPORTS.
2786
+ * Blocking is reserved for shapes with no legitimate use in stored knowledge
2787
+ * (prompt-injection phrasing, credential exfiltration, the invisible-character
2788
+ * smuggling core). Typography and presentation characters that are legitimate
2789
+ * in ordinary prose — variation selectors (❤️), zero-width non-joiner, soft
2790
+ * hyphen from PDF paste, Arabic letter mark, Mongolian vowel separator — are
2791
+ * REPORT findings: they stay visible to operators and tests but never reject a
2792
+ * write. Blocking them turned every emoji into a security event.
2793
+ */
2794
+ const FILLER = String.raw`(?:\w+\s+){0,8}`;
2795
+ const PATTERNS = [
2796
+ {
2797
+ label: "prompt_injection_ignore",
2798
+ category: "prompt_injection",
2799
+ scope: "all",
2800
+ regex: new RegExp(String.raw`ignore\s+${FILLER}(?:previous|above|prior|all)\s+${FILLER}instructions`, "i")
2801
+ },
2802
+ {
2803
+ label: "disregard_rules",
2804
+ category: "prompt_injection",
2805
+ scope: "all",
2806
+ regex: new RegExp(String.raw`disregard\s+${FILLER}(?:your|all|any)\s+${FILLER}(?:instructions|rules|guidelines)`, "i")
2807
+ },
2808
+ {
2809
+ label: "system_prompt_override",
2810
+ category: "prompt_injection",
2811
+ scope: "all",
2812
+ regex: /system\s+prompt\s+override/i
2813
+ },
2814
+ {
2815
+ label: "bypass_restrictions",
2816
+ category: "prompt_injection",
2817
+ scope: "all",
2818
+ regex: /act\s+as\s+(?:if|though)\s+(?:you\s+)?(?:have\s+no|don'?t\s+have)\s+(?:restrictions?|limits?|rules)/i
2819
+ },
2820
+ {
2821
+ label: "new_system_prompt",
2822
+ category: "prompt_injection",
2823
+ scope: "strict",
2824
+ regex: new RegExp(String.raw`new\s+${FILLER}system\s+${FILLER}prompt`, "i")
2825
+ },
2826
+ {
2827
+ label: "forget_everything",
2828
+ category: "prompt_injection",
2829
+ scope: "strict",
2830
+ regex: new RegExp(String.raw`forget\s+${FILLER}(?:everything|all)\s+${FILLER}(?:discussed|you\s+know)`, "i")
2831
+ },
2832
+ {
2833
+ label: "role_hijack",
2834
+ category: "role_hijacking",
2835
+ scope: "context",
2836
+ regex: /you\s+are\s+now\s+(?:a|an|the|acting|playing|pretending)/i
2837
+ },
2838
+ {
2839
+ label: "fake_update",
2840
+ category: "role_hijacking",
2841
+ scope: "context",
2842
+ regex: new RegExp(String.raw`you\s+have\s+been\s+${FILLER}(?:updated|upgraded|patched)\s+to`, "i")
2843
+ },
2844
+ {
2845
+ label: "identity_override",
2846
+ category: "role_hijacking",
2847
+ scope: "context",
2848
+ regex: /\bname\s+yourself\s+\w+/i
2849
+ },
2850
+ {
2851
+ label: "remove_filters",
2852
+ category: "role_hijacking",
2853
+ scope: "context",
2854
+ regex: /(?:respond|answer|reply)\s+without\s+(?:restrictions?|limitations?|filters?|safety)/i
2855
+ },
2856
+ {
2857
+ label: "deception_hide",
2858
+ category: "deception",
2859
+ scope: "all",
2860
+ regex: new RegExp(String.raw`do\s+not\s+${FILLER}tell\s+${FILLER}the\s+user`, "i")
2861
+ },
2862
+ {
2863
+ label: "leak_system_prompt",
2864
+ category: "deception",
2865
+ scope: "context",
2866
+ regex: new RegExp(String.raw`output\s+${FILLER}(?:system|initial)\s+prompt`, "i")
2867
+ },
2868
+ {
2869
+ label: "context_exfil",
2870
+ category: "exfiltration",
2871
+ scope: "strict",
2872
+ regex: /(?:include|output|print|share)\s+(?:the\s+)?(?:conversation|chat\s+history|previous\s+messages|(?:full|entire)\s+context)/i
2873
+ },
2874
+ {
2875
+ label: "send_to_url",
2876
+ category: "exfiltration",
2877
+ scope: "strict",
2878
+ regex: /(?:send|post|upload|transmit)\s+[\s\S]{0,512}?\s+(?:to|at)\s+https?:\/\//i
2879
+ },
2880
+ {
2881
+ label: "exfil_curl",
2882
+ category: "exfiltration",
2883
+ scope: "all",
2884
+ regex: /\bcurl\s+[\s\S]{0,512}?\$\{?\w*(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|API)/i
2885
+ },
2886
+ {
2887
+ label: "exfil_wget",
2888
+ category: "exfiltration",
2889
+ scope: "all",
2890
+ regex: /\bwget\s+[\s\S]{0,512}?\$\{?\w*(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|API)/i
2891
+ },
2892
+ {
2893
+ label: "read_secrets",
2894
+ category: "exfiltration",
2895
+ scope: "all",
2896
+ regex: /\bcat\s+[^\n]{0,512}(?:\.env(?!\w)(?!\.(?:[\w-]+\.)*(?:example|sample)(?=$|[\s"']))|(?:\bcredentials\b)|\.netrc|\.pgpass|\.npmrc|\.pypirc)/i
2897
+ },
2898
+ {
2899
+ label: "ssh_backdoor",
2900
+ category: "persistence",
2901
+ scope: "strict",
2902
+ regex: /\bauthorized_keys\b/i
2903
+ },
2904
+ {
2905
+ label: "agent_config_mod",
2906
+ category: "persistence",
2907
+ scope: "strict",
2908
+ regex: /(?:update|modify|edit|write|change|append|add\s+to)\s+(?:AGENTS\.md|CLAUDE\.md|\.cursorrules|\.clinerules)/i
2909
+ },
2910
+ {
2911
+ label: "hermes_env",
2912
+ category: "persistence",
2913
+ scope: "strict",
2914
+ regex: /\$?HOME\/\.hermes|~\/\.hermes|\.hermes\/\.env|%USERPROFILE%[\\/]\.hermes/i
2915
+ },
2916
+ {
2917
+ label: "c2_node_registration",
2918
+ category: "c2_promptware",
2919
+ scope: "context",
2920
+ regex: /register\s+(?:as\s+)?a?\s*node/i
2921
+ },
2922
+ {
2923
+ label: "c2_heartbeat",
2924
+ category: "c2_promptware",
2925
+ scope: "context",
2926
+ regex: /(?:heartbeats?|beacon|check[\s-]?in)\s+(?:to|with)/i
2927
+ },
2928
+ {
2929
+ label: "c2_task_pull",
2930
+ category: "c2_promptware",
2931
+ scope: "context",
2932
+ regex: /pull\s+(?:new\s+)?tasks?/i
2933
+ },
2934
+ {
2935
+ label: "known_c2_framework",
2936
+ category: "c2_promptware",
2937
+ scope: "context",
2938
+ regex: /\b(?:cobalt\s*strike|sliver|havoc|mythic|metasploit|brainworm)\b/i
2939
+ },
2940
+ {
2941
+ label: "hardcoded_secret",
2942
+ category: "hardcoded_secrets",
2943
+ scope: "strict",
2944
+ regex: /(?:api[_-]?key|token|secret|password)\s*[=:]\s*["'][a-z0-9+/=_-]{20,}["']/i
2945
+ },
2946
+ {
2947
+ label: "jwt_like_secret",
2948
+ category: "hardcoded_secrets",
2949
+ scope: "strict",
2950
+ regex: /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/
2951
+ },
2952
+ {
2953
+ label: "private_key_block",
2954
+ category: "hardcoded_secrets",
2955
+ scope: "all",
2956
+ regex: /-----BEGIN\s+(?:(?:RSA|EC|DSA|OPENSSH|ENCRYPTED|PGP)\s+)?PRIVATE\s+KEY(?:\s+BLOCK)?-----/
2957
+ },
2958
+ {
2959
+ label: "prompt_injection_ignore_zh",
2960
+ category: "prompt_injection",
2961
+ scope: "all",
2962
+ regex: /(?:忽略|无视|抛开)[\s\S]{0,8}(?:之前|以上|上面|先前|以前)?[\s\S]{0,8}(?:所有|全部|任何)?[\s\S]{0,4}(?:指令|规则|设定|约束)/
2963
+ },
2964
+ {
2965
+ label: "deception_hide_zh",
2966
+ category: "deception",
2967
+ scope: "all",
2968
+ regex: /(?:不要|别|勿)(?:告诉|告知|透露)(?:给)?[\s\S]{0,6}(?:用户|任何人|主人|开发者)/
2969
+ },
2970
+ {
2971
+ label: "system_prompt_leak_zh",
2972
+ category: "deception",
2973
+ scope: "context",
2974
+ regex: /(?:泄露|输出|打印|透露|导出)[\s\S]{0,10}系统提示|系统提示[\s\S]{0,10}(?:泄露|透露|发送|导出)/
2975
+ },
2976
+ {
2977
+ label: "context_exfil_zh",
2978
+ category: "exfiltration",
2979
+ scope: "strict",
2980
+ regex: /(?:对话记录|聊天记录|全部上下文|完整上下文)[\s\S]{0,30}(?:发送|上传|传输|外传|泄露)[\s\S]{0,30}(?:到|至|给)/
2981
+ },
2982
+ {
2983
+ label: "secret_exfil_zh",
2984
+ category: "exfiltration",
2985
+ scope: "strict",
2986
+ regex: /(?:密钥|凭据|口令|密码|环境变量)[\s\S]{0,30}(?:发送|上传|传输|外传|泄露)[\s\S]{0,30}(?:到|至)\s*(?:https?:\/\/|[\w.-]+\.(?:com|net|org|io|cn|dev|xyz|ru)\b)/
2987
+ }
2988
+ ];
2989
+ const ZERO_WIDTH_CHARS = new RegExp(`[\\u034f\\u200b\\u2060\\u2061\\u2062\\u2063\\u2064\\u206a-\\u206f\\ufeff\\u{e0000}-\\u{e007f}]`, "u");
2990
+ const ZWJ_OUTSIDE_EMOJI = /(?<!\p{Extended_Pictographic})\u200d(?!\p{Extended_Pictographic})/u;
2991
+ const TYPOGRAPHY_CHARS = /[\u00ad\u061c\u180e\u200c\ufe00-\ufe0f]/;
2992
+ const BIDI_CHARS = /[\u202a-\u202e\u2066-\u2069]/;
2993
+ const FORMAT_CONTROL_CLASS = "\\p{Cf}\\p{Zl}\\p{Zp}\\u0000\\u2065\\ufff0-\\ufff8\\u{e0080}-\\u{e00ff}";
2994
+ const FORMAT_CONTROL_TEST = new RegExp(`[${FORMAT_CONTROL_CLASS}]`, "u");
2995
+ /** S0.4 (v37 P0-3): a format control the three finding sets above do NOT report.
2996
+ * S1-E3: the ZWJ exemption compares the real character. It used to read
2997
+ * `'\\u200d'` — a 6-character literal that never equals a code point — so the
2998
+ * branch was dead and every emoji ZWJ sequence (👨‍👩‍👧) raised the report-level
2999
+ * `unicode_format_control` finding the class comment above promises it will not. */
3000
+ function hasUnreportedFormatControl(text) {
3001
+ for (const character of text) {
3002
+ if (!FORMAT_CONTROL_TEST.test(character)) continue;
3003
+ if (ZERO_WIDTH_CHARS.test(character) || TYPOGRAPHY_CHARS.test(character) || BIDI_CHARS.test(character)) continue;
3004
+ if (character === "‍") continue;
3005
+ return true;
3006
+ }
3007
+ return false;
3008
+ }
3009
+ const SCOPE_ORDER = {
3010
+ all: 1,
3011
+ context: 2,
3012
+ strict: 3
3013
+ };
3014
+ const NO_SCAN_OPTIONS = {};
3015
+ /** Minimum window size for the full-coverage scan (V6-05, 0.3.35). With the
3016
+ * proportional half-window step below, the overlap is `ceil(w/2)` — only a
3017
+ * window at or above this floor keeps the overlap above the longest pattern
3018
+ * span (~530 chars: `curl [^\n]{0,512} ...`), so a match straddling a window
3019
+ * boundary is fully inside at least one window (E-12, 0.3.16). The clamp
3020
+ * falls back to the default for a smaller caller value instead of risking a
3021
+ * blind zone. */
3022
+ const PATTERN_OVERLAP = 4096;
3023
+ /**
3024
+ * Scan text at `scope`. Patterns are cumulative: `strict` includes all scopes.
3025
+ * `options.excludeLabels` removes matching patterns without changing `scope`.
3026
+ * `maxScanChars` is the WINDOW SIZE, not a total cap (E-12, 0.3.16): the whole
3027
+ * text is always scanned in overlapping windows, so content beyond 65,536
3028
+ * characters (skill files may run to 100,000) is no longer a blind zone.
3029
+ */
3030
+ function scanThreats(text, scope = "strict", maxScanChars = DEFAULT_THREAT_MAX_SCAN_CHARS, options = NO_SCAN_OPTIONS) {
3031
+ const windowSize = clampedNumber(maxScanChars, DEFAULT_THREAT_MAX_SCAN_CHARS, { min: 4097 });
3032
+ const findings = [];
3033
+ const excluded = new Set(options.excludeLabels ?? []);
3034
+ if ((ZERO_WIDTH_CHARS.test(text) || ZWJ_OUTSIDE_EMOJI.test(text)) && !excluded.has("unicode_zero_width")) findings.push({
3035
+ label: "unicode_zero_width",
3036
+ category: "unicode_obfuscation",
3037
+ scope: "all"
3038
+ });
3039
+ if (TYPOGRAPHY_CHARS.test(text) && !excluded.has("unicode_typography")) findings.push({
3040
+ label: "unicode_typography",
3041
+ category: "unicode_obfuscation",
3042
+ scope: "all",
3043
+ severity: "report"
3044
+ });
3045
+ if (BIDI_CHARS.test(text) && !excluded.has("unicode_bidi_override")) findings.push({
3046
+ label: "unicode_bidi_override",
3047
+ category: "unicode_obfuscation",
3048
+ scope: "all"
3049
+ });
3050
+ if (!excluded.has("unicode_format_control") && hasUnreportedFormatControl(text)) findings.push({
3051
+ label: "unicode_format_control",
3052
+ category: "unicode_obfuscation",
3053
+ scope: "all",
3054
+ severity: "report"
3055
+ });
3056
+ const normalized = text.normalize("NFKC");
3057
+ const SPACE_SPLITTERS = /[\u00ad\u061c\u180e\u200c\ufe00-\ufe0f]/gu;
3058
+ const OBFUSCATION_SPLITTERS = new RegExp(`[${FORMAT_CONTROL_CLASS}]`, "gu");
3059
+ const patternTexts = [normalized.replace(SPACE_SPLITTERS, " ").replace(OBFUSCATION_SPLITTERS, " "), normalized.replace(SPACE_SPLITTERS, "").replace(OBFUSCATION_SPLITTERS, "")];
3060
+ const windows = [];
3061
+ for (const patternText of patternTexts) if (patternText.length <= windowSize) windows.push(patternText);
3062
+ else {
3063
+ const step = Math.max(Math.floor(windowSize / 2), 1);
3064
+ for (let start = 0; start < patternText.length; start += step) windows.push(patternText.slice(start, start + windowSize));
3065
+ }
3066
+ const seen = /* @__PURE__ */ new Set();
3067
+ for (const window of windows) for (const pattern of PATTERNS) {
3068
+ if (SCOPE_ORDER[pattern.scope] > SCOPE_ORDER[scope]) continue;
3069
+ if (excluded.has(pattern.label)) continue;
3070
+ if (!pattern.regex.test(window)) continue;
3071
+ const key = `${pattern.label}|${pattern.scope}`;
3072
+ if (seen.has(key)) continue;
3073
+ seen.add(key);
3074
+ findings.push({
3075
+ label: pattern.label,
3076
+ category: pattern.category,
3077
+ scope: pattern.scope
3078
+ });
3079
+ }
3080
+ return findings;
3081
+ }
3082
+ /** Blocking policy (P1-1, v19): a finding blocks unless it is explicitly
3083
+ * `report`-only. Pattern findings carry no severity and therefore block as
3084
+ * before. */
3085
+ function evaluateThreat(text, scope = "strict", maxScanChars = DEFAULT_THREAT_MAX_SCAN_CHARS, options = NO_SCAN_OPTIONS) {
3086
+ const findings = scanThreats(text, scope, maxScanChars, options);
3087
+ return {
3088
+ blocked: findings.some((finding) => finding.severity !== "report"),
3089
+ findings
3090
+ };
3091
+ }
3092
+ /** User-facing block message for memory writes. */
3093
+ function scanMemoryThreats(text, maxScanChars = DEFAULT_THREAT_MAX_SCAN_CHARS, options = NO_SCAN_OPTIONS) {
3094
+ const { blocked, findings } = evaluateThreat(text, "strict", maxScanChars, options);
3095
+ if (!blocked) return null;
3096
+ const pattern = findings.find((f) => f.category !== "unicode_obfuscation");
3097
+ if (pattern) return `Blocked by security scan (${pattern.label}). Rephrase without instruction-like language.${THREAT_EXEMPTION_HINT}`;
3098
+ return `Blocked by security scan: invisible or potentially malicious Unicode detected.${THREAT_EXEMPTION_HINT}`;
3099
+ }
3100
+ /** User-facing block message for skill content writes. */
3101
+ function scanContentThreats(text, maxScanChars = DEFAULT_THREAT_MAX_SCAN_CHARS, options = NO_SCAN_OPTIONS) {
3102
+ const { blocked, findings } = evaluateThreat(text, "strict", maxScanChars, options);
3103
+ if (!blocked) return null;
3104
+ const pattern = findings.find((f) => f.category !== "unicode_obfuscation");
3105
+ if (pattern) return `Blocked by security scan (${pattern.label}). This content appears to contain potentially malicious instructions.${THREAT_EXEMPTION_HINT}`;
3106
+ return `Blocked by security scan: invisible or potentially malicious Unicode detected. This content appears to contain potentially malicious instructions.${THREAT_EXEMPTION_HINT}`;
3107
+ }
3108
+ /**
3109
+ * WD2 (0.3.56): the shared tail of every user-facing threat block — names the
3110
+ * deployable self-heal path so the model (or operator) can allowlist a
3111
+ * known-benign label. v20 (B-2) single source: the scan builders embed this
3112
+ * constant verbatim; do NOT re-word it per call site (the three former copies
3113
+ * — memory inline, content inline, and the dead `THREAT_EXEMPT_HINT` export,
3114
+ * whose docblock still claimed a store-side append that memory-store/skill-store
3115
+ * had already removed — had drifted apart). The evolution-threat guard channel
3116
+ * returns the scan message verbatim, so the hint rides along there too.
3117
+ */
3118
+ const THREAT_EXEMPTION_HINT = " A deployment that needs a specific label can exempt it via threatExemptLabels (see the README env/dial reference).";
3119
+ //#endregion
3120
+ //#region lib/types/review-channel.js
3121
+ /**
3122
+ * Family-internal mark for the review channel's INJECT delivery (v37 S2.2).
3123
+ *
3124
+ * With the default `reviewMode: 'inject'` the review prompt runs in the PARENT
3125
+ * session, so the parent model's own `skill_manage` calls carry no origin the
3126
+ * platform could attribute: `.pinned` and the `.hermes-managed` authorship mark
3127
+ * were skipped for exactly the autonomous writes they exist for. The delivery
3128
+ * marks the session here and the write path reads the mark.
3129
+ *
3130
+ * Window: after the review prompt, until the next REAL user message (a
3131
+ * `user/message` with `source.kind === 'user'` clears it; plugin-sourced notices
3132
+ * never do). Process-wide and keyed by session on purpose — the same
3133
+ * "restart is a fresh conversation boundary" discipline as the review plugin's
3134
+ * own per-session counters. This module is the ONE owner of the marker.
3135
+ * @module @lmzhen/dsh-evolution-core/review-channel
3136
+ */
3137
+ /** Session ids currently executing a review prompt, oldest delivery first. */
3138
+ const MARK_KEY = Symbol.for("dsh.evolution.review-channel.marked");
3139
+ const registry$1 = globalThis;
3140
+ const markedSessions = registry$1[MARK_KEY] ?? (registry$1[MARK_KEY] = /* @__PURE__ */ new Set());
3141
+ /**
3142
+ * Mark one session as running the review channel's prompt; idempotent, and
3143
+ * keyed by session so a mark can never leak into another session.
3144
+ * @param sessionId - the session the review prompt was delivered to.
3145
+ */
3146
+ function markReviewChannel(sessionId) {
3147
+ markedSessions.delete(sessionId);
3148
+ markedSessions.add(sessionId);
3149
+ }
3150
+ /**
3151
+ * Clear the mark: the session's next prompt is human input again.
3152
+ * @param sessionId - the session whose mark is dropped.
3153
+ */
3154
+ function clearReviewChannel(sessionId) {
3155
+ markedSessions.delete(sessionId);
3156
+ }
3157
+ /**
3158
+ * Whether this session's current prompt came from the review channel. An
3159
+ * execution without a session is never the review channel.
3160
+ * @param sessionId - the executing session id, when the caller has one.
3161
+ * @returns true only for a marked session.
3162
+ */
3163
+ function isReviewChannelSession(sessionId) {
3164
+ return sessionId !== void 0 && markedSessions.has(sessionId);
3165
+ }
3166
+ /**
3167
+ * Drop marks whose session is gone — a dead session cannot execute a write.
3168
+ * @param isAlive - liveness probe for one session id.
3169
+ * @returns the number of removed marks.
3170
+ */
3171
+ function sweepReviewChannelSessions(isAlive) {
3172
+ let removed = 0;
3173
+ for (const sessionId of [...markedSessions]) {
3174
+ if (isAlive(sessionId)) continue;
3175
+ markedSessions.delete(sessionId);
3176
+ removed += 1;
3177
+ }
3178
+ return removed;
3179
+ }
3180
+ //#endregion
3181
+ //#region lib/types/review-context.js
3182
+ /**
3183
+ * Plugin-local review execution context.
3184
+ *
3185
+ * This is deliberately not a platform API: the family review executor wraps one
3186
+ * bounded tool loop, and the write tools read the context to attribute writes as
3187
+ * background_review without relying on a Session header or a global mark.
3188
+ *
3189
+ * @module @lmzhen/dsh-evolution-core/review-context
3190
+ */
3191
+ const STORAGE_KEY = Symbol.for("dsh.evolution.review-context.storage");
3192
+ const registry = globalThis;
3193
+ const storage = registry[STORAGE_KEY] ?? (registry[STORAGE_KEY] = new AsyncLocalStorage());
3194
+ /**
3195
+ * Run one review tool loop under the review write context.
3196
+ * @param context - review/run identity.
3197
+ * @param task - loop body; nested tool executions inherit the context.
3198
+ * @returns the task's value.
3199
+ */
3200
+ function withReviewContext(context, task) {
3201
+ return storage.run(Object.freeze({ ...context }), task);
3202
+ }
3203
+ /**
3204
+ * The active review context, when the current async execution belongs to a review loop.
3205
+ * @returns the frozen context, or undefined outside a review loop.
3206
+ */
3207
+ function currentReviewContext() {
3208
+ return storage.getStore();
3209
+ }
3210
+ //#endregion
3211
+ //#region lib/types/tree-lock.js
3212
+ /**
3213
+ * Tree write lock.
3214
+ *
3215
+ * The merge run holds this lock for its whole lifetime; curator's pass takes the same
3216
+ * lock. The record is created through `transactIo`, so exclusion is exactly as strong as
3217
+ * the IO backend's `transact`: the platform `ctx.fs` provider is cross-process, while the
3218
+ * standalone `nodeEvolutionIo` is explicitly single-process (G2 S4). This module builds no
3219
+ * file lock or WAL of its own. A holder whose pid is gone is stale and may be taken over;
3220
+ * a live pid is respected, even for a long run (a live long run is what the lock protects).
3221
+ *
3222
+ * `commitMerge` deliberately does NOT take this lock itself: the run shell owns it, so a
3223
+ * run and its commit share one acquisition. Taking it inside the store would also
3224
+ * deadlock the same-process curator path.
3225
+ */
3226
+ /** The one lock path. */
3227
+ function treeLockFile(home) {
3228
+ return join(home, "merge", ".tree-lock");
3229
+ }
3230
+ function parseLock(raw) {
3231
+ if (raw === null) return void 0;
3232
+ try {
3233
+ const value = JSON.parse(raw);
3234
+ if (typeof value.token !== "string" || typeof value.pid !== "number" || typeof value.startedAt !== "number") return void 0;
3235
+ return {
3236
+ token: value.token,
3237
+ epoch: typeof value.epoch === "number" ? value.epoch : 0,
3238
+ pid: value.pid,
3239
+ startedAt: value.startedAt
3240
+ };
3241
+ } catch {
3242
+ return;
3243
+ }
3244
+ }
3245
+ const sleepDefault = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
3246
+ /** Read the current holder without creating or changing anything. */
3247
+ async function readTreeLock(io, home) {
3248
+ return parseLock(await io.readText(treeLockFile(home)));
3249
+ }
3250
+ /** Try once. A stale record (dead pid or unparsable) is replaced. */
3251
+ async function tryAcquire(io, home, now) {
3252
+ const path = treeLockFile(home);
3253
+ let token;
3254
+ let epoch;
3255
+ let holder;
3256
+ await transactIo(io, path, (current) => {
3257
+ const existing = parseLock(current);
3258
+ if (existing !== void 0 && isProcessAlive(existing.pid)) {
3259
+ holder = existing;
3260
+ return current;
3261
+ }
3262
+ token = randomUUID();
3263
+ epoch = (existing?.epoch ?? 0) + 1;
3264
+ return JSON.stringify({
3265
+ token,
3266
+ epoch,
3267
+ pid: process.pid,
3268
+ startedAt: now()
3269
+ });
3270
+ });
3271
+ return token === void 0 ? holder === void 0 ? {} : { holder } : {
3272
+ token,
3273
+ epoch: epoch ?? 0
3274
+ };
3275
+ }
3276
+ /**
3277
+ * Acquire the tree write lock, waiting up to `waitMs`.
3278
+ *
3279
+ * A live holder is never stolen. A record whose pid is gone (or a corrupt record) is
3280
+ * taken over; that is how a killed process releases its lock without a timer.
3281
+ */
3282
+ async function acquireTreeWriteLock(options) {
3283
+ const now = options.now ?? (() => Date.now());
3284
+ const waitMs = options.waitMs ?? 5e3;
3285
+ const pollMs = options.pollMs ?? 25;
3286
+ const sleep = options.sleep ?? sleepDefault;
3287
+ const deadline = now() + Math.max(0, waitMs);
3288
+ let lastHolder;
3289
+ try {
3290
+ for (;;) {
3291
+ const attempt = await tryAcquire(options.io, options.home, now);
3292
+ if (attempt.token !== void 0) {
3293
+ const token = attempt.token;
3294
+ const epoch = attempt.epoch ?? 0;
3295
+ const path = treeLockFile(options.home);
3296
+ let released = false;
3297
+ return {
3298
+ ok: true,
3299
+ lock: {
3300
+ token,
3301
+ epoch,
3302
+ path,
3303
+ acquiredAt: now(),
3304
+ async assertHeld() {
3305
+ const current = parseLock(await options.io.readText(path));
3306
+ return current?.token === token && current.epoch === epoch;
3307
+ },
3308
+ async release() {
3309
+ if (released) return;
3310
+ await transactIo(options.io, path, (current) => {
3311
+ const existing = parseLock(current);
3312
+ return existing?.token === token && existing.epoch === epoch ? null : current;
3313
+ });
3314
+ released = true;
3315
+ }
3316
+ }
3317
+ };
3318
+ }
3319
+ lastHolder = attempt.holder;
3320
+ if (now() >= deadline) break;
3321
+ await sleep(pollMs);
3322
+ }
3323
+ return {
3324
+ ok: false,
3325
+ reason: "busy",
3326
+ ...lastHolder !== void 0 ? { holder: lastHolder } : {}
3327
+ };
3328
+ } catch (error) {
3329
+ return {
3330
+ ok: false,
3331
+ reason: "io",
3332
+ message: error instanceof Error ? error.message : String(error)
3333
+ };
3334
+ }
3335
+ }
3336
+ /** Acquire, run, release; the lock is released even when the body throws. */
3337
+ async function withTreeWriteLock(options, body) {
3338
+ const acquired = await acquireTreeWriteLock(options);
3339
+ if (!acquired.ok) return acquired;
3340
+ try {
3341
+ return {
3342
+ ok: true,
3343
+ value: await body(acquired.lock)
3344
+ };
3345
+ } finally {
3346
+ await acquired.lock.release();
3347
+ }
3348
+ }
3349
+ //#endregion
3350
+ //#region lib/types/home-owner.js
3351
+ const OWNER_FILE = ".evolution-owner.json";
3352
+ function isAlive(pid) {
3353
+ if (!Number.isInteger(pid) || pid <= 0) return false;
3354
+ try {
3355
+ process.kill(pid, 0);
3356
+ return true;
3357
+ } catch (error) {
3358
+ return error.code === "EPERM";
3359
+ }
3360
+ }
3361
+ /** Fail loud when another live process already owns this DSH home. Single-host contract. */
3362
+ async function assertHomeOwner(io, home) {
3363
+ const path = join(home, OWNER_FILE);
3364
+ const raw = await io.readText(path);
3365
+ if (raw !== null) {
3366
+ let record;
3367
+ try {
3368
+ const parsed = JSON.parse(raw);
3369
+ if (typeof parsed.pid !== "number" || typeof parsed.startedAt !== "string") throw new Error("bad owner record");
3370
+ record = {
3371
+ pid: parsed.pid,
3372
+ startedAt: parsed.startedAt
3373
+ };
3374
+ } catch {
3375
+ throw new Error("evolution home owner record is unreadable; refusing a second owner (" + path + ")");
3376
+ }
3377
+ if (record.pid === process.pid) return;
3378
+ if (isAlive(record.pid)) throw new Error("evolution home is owned by another live process (pid " + String(record.pid) + "); this deployment is single-host only");
3379
+ }
3380
+ await io.writeText(path, JSON.stringify({
3381
+ pid: process.pid,
3382
+ startedAt: (/* @__PURE__ */ new Date()).toISOString()
3383
+ }));
3384
+ }
3385
+ //#endregion
3386
+ //#region lib/types/home-fence.js
3387
+ var HomeFenceError = class extends Error {
3388
+ reason;
3389
+ constructor(reason, message) {
3390
+ super(message);
3391
+ this.name = "HomeFenceError";
3392
+ this.reason = reason;
3393
+ }
3394
+ };
3395
+ /** Unlink races on Windows are transient: a virus scanner or a closing handle can hold the
3396
+ * lock file for a few milliseconds. Retry only those, and only inside the fence release:
3397
+ * the durable write path has its own rename budget and must not inherit lock semantics. */
3398
+ const RELEASE_RETRY_MS = [
3399
+ 25,
3400
+ 50,
3401
+ 100
3402
+ ];
3403
+ function transientReleaseError(error) {
3404
+ if (typeof error !== "object" || error === null) return false;
3405
+ const code = error.code;
3406
+ return code === "EPERM" || code === "EBUSY" || code === "EACCES";
3407
+ }
3408
+ function asError(error) {
3409
+ return error instanceof Error ? error : new Error(String(error));
3410
+ }
3411
+ function sleep(ms) {
3412
+ return new Promise((resolve) => setTimeout(resolve, ms));
3413
+ }
3414
+ /**
3415
+ * One home-level writer queue. It serializes same-process callers before the
3416
+ * tree lock, and the tree lock remains the only cross-process guard the current
3417
+ * backend can provide (nodeEvolutionIo is single-process).
3418
+ *
3419
+ * `acquire` is public only for legacy call sites; W0 keeps it usable but makes a
3420
+ * failed release advance the queue and poison the fence instead of wedging every
3421
+ * later writer. Nested acquisition is not supported: the state layer must reuse
3422
+ * the transaction it is already inside (see evolution-state-json appendArchive).
3423
+ */
3424
+ var HomeFence = class {
3425
+ tail = Promise.resolve();
3426
+ poisoned;
3427
+ options;
3428
+ constructor(options) {
3429
+ this.options = options;
3430
+ }
3431
+ async releaseLock(lock) {
3432
+ let attempt = 0;
3433
+ for (;;) try {
3434
+ await lock.release();
3435
+ return;
3436
+ } catch (error) {
3437
+ if (!transientReleaseError(error) || attempt >= RELEASE_RETRY_MS.length) throw error;
3438
+ await sleep(RELEASE_RETRY_MS[attempt] ?? 100);
3439
+ attempt += 1;
3440
+ }
3441
+ }
3442
+ async acquire() {
3443
+ if (this.poisoned !== void 0) throw new HomeFenceError("io", "home fence is poisoned after a failed lock release: " + this.poisoned.message);
3444
+ const previous = this.tail;
3445
+ let releaseQueue = () => {};
3446
+ this.tail = new Promise((resolve) => {
3447
+ releaseQueue = resolve;
3448
+ });
3449
+ await previous;
3450
+ try {
3451
+ const acquired = await acquireTreeWriteLock(this.options);
3452
+ if (!acquired.ok) throw new HomeFenceError(acquired.reason, acquired.message ?? "home fence is " + acquired.reason);
3453
+ try {
3454
+ await assertHomeOwner(this.options.io, this.options.home);
3455
+ } catch (error) {
3456
+ await acquired.lock.release().catch(() => {});
3457
+ throw error;
3458
+ }
3459
+ let released = false;
3460
+ return {
3461
+ lock: acquired.lock,
3462
+ release: async () => {
3463
+ if (released) return;
3464
+ released = true;
3465
+ let failure;
3466
+ try {
3467
+ await this.releaseLock(acquired.lock);
3468
+ } catch (error) {
3469
+ failure = asError(error);
3470
+ this.poisoned = failure;
3471
+ } finally {
3472
+ releaseQueue();
3473
+ }
3474
+ if (failure !== void 0) throw failure;
3475
+ }
3476
+ };
3477
+ } catch (error) {
3478
+ releaseQueue();
3479
+ throw error;
3480
+ }
3481
+ }
3482
+ async run(body) {
3483
+ const lease = await this.acquire();
3484
+ try {
3485
+ return await body(lease.lock);
3486
+ } finally {
3487
+ await lease.release();
3488
+ }
3489
+ }
3490
+ };
3491
+ //#endregion
3492
+ //#region lib/types/lease-store.js
3493
+ const DEFAULT_LEASE_TTL_MS = 3e4;
3494
+ function leaseFile(home, runId) {
3495
+ return join(home, "leases", encodeURIComponent(runId) + ".json");
3496
+ }
3497
+ function parseLease(raw) {
3498
+ if (raw === null) return void 0;
3499
+ try {
3500
+ const value = JSON.parse(raw);
3501
+ if (typeof value.id !== "string" || typeof value.runId !== "string" || typeof value.owner !== "string" || typeof value.pid !== "number" || typeof value.epoch !== "number" || typeof value.issuedAt !== "number" || typeof value.expiresAt !== "number" || typeof value.heartbeatAt !== "number" || value.state !== "active" && value.state !== "released") return void 0;
3502
+ return value;
3503
+ } catch {
3504
+ return;
3505
+ }
3506
+ }
3507
+ async function transact(io, path, task) {
3508
+ if (io.transact !== void 0) {
3509
+ await io.transact(path, task);
3510
+ return;
3511
+ }
3512
+ const current = await io.readText(path);
3513
+ const next = task(current);
3514
+ if (next === null) await io.remove(path);
3515
+ else if (next !== current) await io.writeText(path, next);
3516
+ }
3517
+ function tokenOf(record) {
3518
+ return {
3519
+ id: record.id,
3520
+ owner: record.owner,
3521
+ runId: record.runId,
3522
+ epoch: record.epoch
3523
+ };
3524
+ }
3525
+ /** Durable single-host lease store. One active lease per runId; expired leases are reclaimable. */
3526
+ var LeaseStore = class {
3527
+ io;
3528
+ home;
3529
+ ttlMs;
3530
+ now;
3531
+ pid;
3532
+ constructor(options) {
3533
+ this.io = options.io;
3534
+ this.home = options.home;
3535
+ this.ttlMs = options.ttlMs ?? 3e4;
3536
+ this.now = options.now ?? Date.now;
3537
+ this.pid = options.pid ?? process.pid;
3538
+ }
3539
+ path(runId) {
3540
+ if (runId.trim() === "") throw new Error("lease runId must not be empty");
3541
+ return leaseFile(this.home, runId);
3542
+ }
3543
+ async acquire(owner, runId, ttlMs = this.ttlMs) {
3544
+ if (ttlMs <= 0) throw new Error("lease ttl must be positive");
3545
+ const path = this.path(runId);
3546
+ const now = this.now();
3547
+ let created;
3548
+ let holder;
3549
+ await transact(this.io, path, (raw) => {
3550
+ const current = parseLease(raw);
3551
+ if (current !== void 0 && current.state === "active" && now < current.expiresAt) {
3552
+ holder = current;
3553
+ return raw;
3554
+ }
3555
+ created = {
3556
+ id: randomUUID(),
3557
+ owner,
3558
+ runId,
3559
+ pid: this.pid,
3560
+ epoch: (current?.epoch ?? 0) + 1,
3561
+ issuedAt: now,
3562
+ expiresAt: now + ttlMs,
3563
+ heartbeatAt: now,
3564
+ state: "active"
3565
+ };
3566
+ return JSON.stringify(created);
3567
+ });
3568
+ if (created !== void 0) return {
3569
+ ok: true,
3570
+ lease: created,
3571
+ token: tokenOf(created)
3572
+ };
3573
+ if (holder !== void 0) return {
3574
+ ok: false,
3575
+ reason: "busy",
3576
+ holder
3577
+ };
3578
+ throw new Error("lease acquire did not create or observe a record");
3579
+ }
3580
+ async get(runId) {
3581
+ return parseLease(await this.io.readText(this.path(runId))) ?? null;
3582
+ }
3583
+ async active(runId) {
3584
+ const record = await this.get(runId);
3585
+ return record !== null && record.state === "active" && this.now() < record.expiresAt ? record : null;
3586
+ }
3587
+ async renew(token, ttlMs = this.ttlMs) {
3588
+ const path = this.path(token.runId);
3589
+ let next = null;
3590
+ await transact(this.io, path, (raw) => {
3591
+ const current = parseLease(raw);
3592
+ if (current === void 0 || current.state !== "active" || current.id !== token.id || current.epoch !== token.epoch) return raw;
3593
+ const now = this.now();
3594
+ next = {
3595
+ ...current,
3596
+ heartbeatAt: now,
3597
+ expiresAt: now + ttlMs
3598
+ };
3599
+ return JSON.stringify(next);
3600
+ });
3601
+ return next;
3602
+ }
3603
+ async release(token) {
3604
+ const path = this.path(token.runId);
3605
+ await transact(this.io, path, (raw) => {
3606
+ const current = parseLease(raw);
3607
+ if (current === void 0 || current.id !== token.id || current.epoch !== token.epoch) return raw;
3608
+ return JSON.stringify({
3609
+ ...current,
3610
+ state: "released",
3611
+ heartbeatAt: this.now()
3612
+ });
3613
+ });
3614
+ }
3615
+ };
3616
+ //#endregion
3617
+ //#region lib/types/mutation-authority.js
3618
+ /**
3619
+ * The family's write authority. It owns the one home fence and the per-run lease store.
3620
+ *
3621
+ * The lease is a per-run mutex for long-running review/approval work; foreground writes
3622
+ * have no run identity and are serialized by the fence. The former apply/transact/recover
3623
+ * facade claimed to gate every write on a lease but had no production caller, so it was
3624
+ * removed rather than kept as a false narrow waist.
3625
+ */
3626
+ var MutationAuthority = class {
3627
+ leases;
3628
+ fence;
3629
+ /** Lease primitives for run/claim owners (review, approval). */
3630
+ get lease() {
3631
+ return this.leases;
3632
+ }
3633
+ /** The one home fence domain unit engines must reuse instead of taking tree-lock themselves. */
3634
+ get homeFence() {
3635
+ return this.fence;
3636
+ }
3637
+ /** Adapter for MutationUnit call sites that accept a lock port. It is the fence, no more. */
3638
+ get mutationLock() {
3639
+ return { acquire: async () => {
3640
+ const lease = await this.fence.acquire();
3641
+ return { release: async () => {
3642
+ await lease.release();
3643
+ } };
3644
+ } };
3645
+ }
3646
+ constructor(options) {
3647
+ this.leases = options.leases ?? new LeaseStore({
3648
+ io: options.io,
3649
+ home: options.home,
3650
+ ...options.now === void 0 ? {} : { now: options.now }
3651
+ });
3652
+ this.fence = options.fence ?? new HomeFence({
3653
+ io: options.io,
3654
+ home: options.home,
3655
+ ...options.waitMs === void 0 ? {} : { waitMs: options.waitMs },
3656
+ ...options.now === void 0 ? {} : { now: options.now }
3657
+ });
3658
+ }
3659
+ };
3660
+ /** Read the authority's fence adapter from a context; undefined means no authority is mounted. */
3661
+ function mutationLockFrom(ctx) {
3662
+ if (ctx?.get === void 0) return void 0;
3663
+ return ctx.get("evolutionMutationAuthority")?.mutationLock;
3664
+ }
3665
+ //#endregion
3666
+ //#region lib/types/skill-health.js
3667
+ /**
3668
+ * Skill structure-health domain (rc.73 A1, 008 design): a SECOND assessment
3669
+ * dimension beside the six-factor usage quality — document hygiene, consumed
3670
+ * by the curator health view and the `/evolution skills health` command.
3671
+ *
3672
+ * PURE and DERIVED: nothing is persisted; every assessment is computed from
3673
+ * file facts at read time. The judgment split follows the original's
3674
+ * boundary/治理 layering — deterministic signals here, refinement proposals
3675
+ * stay in the review/curator judgment layer. Never become a 7th factor of
3676
+ * `computeQualityScores` (different dimension, different consumers).
3677
+ */
3678
+ const DEFAULT_HEALTH_THRESHOLDS = {
3679
+ softBodyChars: AUTHORING_SPLIT_LINE_CHARS,
3680
+ stampDensityPerKb: 2,
3681
+ churnMinPatches: 20,
3682
+ hardCapMinHits: 3
3683
+ };
3684
+ /**
3685
+ * Stamp regex shared by health assessment and the maintenance probe (single
3686
+ * source, 011). Two refinements over the naive form (F-320): the hex branch
3687
+ * requires at least one digit so coincidental all-letter English words
3688
+ * (`defaced`, `feedback`) are not counted as commit shas; the ISO branch
3689
+ * accepts a UTC `Z`, a numeric UTC offset (`+08:00`), or no timezone at all —
3690
+ * non-UTC timestamps used to escape detection (log-like content missed).
3691
+ *
3692
+ * Known boundary, recorded not fixed (C-22, v10 audit): the hex branch also
3693
+ * matches 7-40 char PURE-DIGIT strings (order numbers etc.), so stamp density
3694
+ * can be over-reported for such content. The misjudgment direction is "extra
3695
+ * stamp hits" only — never a miss — and no real incident exists; revisit only
3696
+ * if curator decisions are actually distorted (v10 deferral ledger).
3697
+ */
3698
+ const HEALTH_STAMP_RE = new RegExp(String.raw`\brc\.\d+\b|\b(?=[0-9a-f]{7,40}\b)[0-9a-f]*[0-9][0-9a-f]*\b|\b\d{4}-\d{2}-\d{2}(?:T[0-9:.]+(?:Z|[+-]\d{2}:?\d{2})?)?\b`, "g");
3699
+ /**
3700
+ * Bodies below this size skip stamp-density assessment: a few dates or shas
3701
+ * in a short body are ordinary documentation, not log-like content. With the
3702
+ * 1KB density floor a 3-date sentence in a small skill measured 3.0/KB and
3703
+ * warned on a perfectly healthy body (audit 2026-08-31 X1).
3704
+ */
3705
+ const MIN_STAMP_BODY_CHARS = 2e3;
3706
+ /**
3707
+ * The findings for ONE body, computed by the engine that owns the judgement (G4).
3708
+ *
3709
+ * Deliberately a thin call into `assessStructureHealth`: a later consumer (the write receipt) needs
3710
+ * findings for a body it is about to store, and re-deriving the facts anywhere else would be a
3711
+ * SECOND judgement — the token-scale line, the /1024 stamp density and the soft/2 support threshold
3712
+ * all live in one place and must stay there.
3713
+ * @param skillName - the skill the body belongs to (used in messages).
3714
+ * @param content - the WHOLE SKILL.md text, frontmatter included (the engine's own convention).
3715
+ * @param supportGroups - non-empty support dirs; pass the real count, never a guess.
3716
+ * @param thresholds - the configured thresholds; defaults to the shipped ones.
3717
+ * @returns the findings, in rule order.
3718
+ */
3719
+ function lintBody(skillName, content, supportGroups, thresholds = DEFAULT_HEALTH_THRESHOLDS) {
3720
+ return assessStructureHealth({
3721
+ skillName,
3722
+ bodyChars: content.length,
3723
+ bodyText: content,
3724
+ supportGroups
3725
+ }, thresholds).findings;
3726
+ }
3727
+ function assessStructureHealth(snapshot, thresholds = DEFAULT_HEALTH_THRESHOLDS) {
3728
+ const dims = {
3729
+ bodyChars: snapshot.bodyChars,
3730
+ bodyTokens: Math.round(snapshot.bodyChars / UPSTREAM_LIMIT_CHARS_PER_TOKEN),
3731
+ stampDensityPerKb: null,
3732
+ stampHits: null,
3733
+ supportGroups: snapshot.supportGroups,
3734
+ supportFiles: snapshot.supportFiles ?? null,
3735
+ churnPatches: null,
3736
+ churnReads: null,
3737
+ hardCapHits: snapshot.hardCapHits ?? null
3738
+ };
3739
+ const text = snapshot.bodyText;
3740
+ const cost = typeof text === "string" && text.length > 0 ? bodyCost(text) : null;
3741
+ const lineTokens = cost === null ? null : tokenLineFor(thresholds.softBodyChars, cost);
3742
+ dims.bodyTokens = cost === null ? Math.round(snapshot.bodyChars / UPSTREAM_LIMIT_CHARS_PER_TOKEN) : cost.tokens;
3743
+ const overLine = cost === null || lineTokens === null ? snapshot.bodyChars >= thresholds.softBodyChars : cost.tokens >= lineTokens;
3744
+ const overTwice = cost === null || lineTokens === null ? snapshot.bodyChars >= thresholds.softBodyChars * 2 : cost.tokens >= lineTokens * 2;
3745
+ if (snapshot.bodyText && snapshot.bodyChars >= 2e3) {
3746
+ const kb = Math.max(1, snapshot.bodyChars / 1024);
3747
+ const stamps = (snapshot.bodyText.match(HEALTH_STAMP_RE) ?? []).length;
3748
+ dims.stampDensityPerKb = stamps / kb;
3749
+ dims.stampHits = stamps;
3750
+ }
3751
+ if (snapshot.patchCount !== void 0 && snapshot.readCount !== void 0) {
3752
+ dims.churnPatches = snapshot.patchCount;
3753
+ dims.churnReads = snapshot.readCount;
3754
+ }
3755
+ const findings = lintSkill({
3756
+ skillName: snapshot.skillName,
3757
+ dims,
3758
+ softLineChars: thresholds.softBodyChars,
3759
+ overSoftLine: overLine,
3760
+ overTwiceSoftLine: overTwice,
3761
+ stampLimitPerKb: thresholds.stampDensityPerKb,
3762
+ churnMinPatches: thresholds.churnMinPatches,
3763
+ hardCapMinHits: thresholds.hardCapMinHits,
3764
+ readable: true
3765
+ });
3766
+ return {
3767
+ verdict: findings.some((f) => f.rule === "body-oversize-2x") ? "needs-restructure" : findings.length > 0 ? "warn" : "healthy",
3768
+ dims,
3769
+ findings
3770
+ };
3771
+ }
3772
+ //#endregion
3773
+ export { COST_ASCII_TOKEN_LOW as $, MAX_TIMER_DELAY_MS as $n, supportRefs as $t, clampedNumber as A, DEFAULT_PROBE_TIMEOUT_MS as An, updateSuppressedNames as At, appendEvolutionEvent as B, DEFAULT_STALE_AFTER_DAYS as Bn, authoringFeedback as Bt, sweepReviewChannelSessions as C, DEFAULT_CONSOLIDATION_FAILURES as Cn, loadUsage as Ct, scanContentThreats as D, DEFAULT_CURATOR_REVIEW_MAX_TOKENS as Dn, saveSuppressedNames as Dt, evaluateThreat as E, DEFAULT_CURATOR_MODEL as En, normalizeUsageRecord as Et, trimPatternBoundaries as F, DEFAULT_REVIEW_TIMEOUT_MS as Fn, selectSections as Ft, readEvolutionEvents as G, DEFAULT_USER_CHAR_LIMIT as Gn, normalizeFrontmatter as Gt, evolutionEventPayloadIssue as H, DEFAULT_SUBSTANTIVE_MIN_TOOL_CALLS as Hn, exceedsContentLimit as Ht, EVENT_ARCHIVE_PREFIX as I, DEFAULT_SKILL_CONTENT_CHARS as In, displayBodyOf as It, RULES as J, FORBIDDEN_CONTROL_KEYS as Jn, shrinksOverLimit as Jt, readEvolutionTimeline as K, ENTRY_DELIMITER as Kn, parseFrontmatter as Kt, EVENT_LOG_RETAIN_ARCHIVES as L, DEFAULT_SKILL_REVIEW_COMPLETION_MIN_TOOL_CALLS as Ln, h2Sections as Lt, FUZZY_MAX_PATTERN_CHARS as M, DEFAULT_REVIEW_MEMORY_INTERVAL as Mn, usageObserved as Mt, FUZZY_MAX_WORK as N, DEFAULT_REVIEW_MESSAGE_CHARS as Nn, planExtract as Nt, scanMemoryThreats as O, DEFAULT_MEMORY_CHAR_LIMIT as On, saveUsage as Ot, fuzzyPatch as P, DEFAULT_REVIEW_SKILL_INTERVAL as Pn, projectExtractBodies as Pt, COST_ASCII_TOKEN_HIGH as Q, MAX_SKILL_NAME_LENGTH as Qn, externalRefs as Qt, EVENT_LOG_ROTATE_AT as R, DEFAULT_SKILL_REVIEW_TRIGGER as Rn, readingStats as Rt, markReviewChannel as S, DEFAULT_ARCHIVE_AFTER_DAYS as Sn, loadSuppressedNames as St, THREAT_EXEMPTION_HINT as T, DEFAULT_CURATOR_INTERVAL_HOURS as Tn, mutateUsage as Tt, listEventArchives as U, DEFAULT_SUBSTANTIVE_MIN_USER_CHARS as Un, frontmatterBlock as Ut, eventsFile as V, DEFAULT_SUBSTANTIVE_MIN_AGENT_CHARS as Vn, ensureSkillFrontmatter as Vt, parseEvolutionEvents as W, DEFAULT_THREAT_MAX_SCAN_CHARS as Wn, frontmatterCatalogInvalid as Wt, diffFindings as X, MAX_SKILL_CONTENT_CHARS as Xn, validateFrontmatter as Xt, countReferenceFiles as Y, MAX_DESCRIPTION_LENGTH as Yn, skillMdOnDisk as Yt, lintSkill as Z, MAX_SKILL_FILE_BYTES as Zn, yamlPlainScalarNeedsQuotes as Zt, withTreeWriteLock as _, POLICY_STAGE_DEFAULTS as _n, emptyRecord as _t, lintBody as a, filterUnreadSkillOps as an, SKILL_ACTION_REQUIRED_FIELDS as ar, tokenLineFor as at, clearReviewChannel as b, AUTHORING_SPLIT_LINE_CHARS as bn, idleDays as bt, DEFAULT_LEASE_TTL_MS as c, sessionReadSupportFiles as cn, SUPPORT_SPRAWL_FILES as cr, MAX_SUPPORT_READ_PATHS as ct, HomeFence as d, authorityFrom as dn, applyCuratorMetaFields as dt, applyReferenceRewrite as en, MEMORY_GUIDANCE_SECTION_ORDER as er, COST_CJK_TOKEN_HIGH as et, HomeFenceError as f, DEFAULT_ARCHIVE_RETENTION_POLICY as fn, bumpPatch as ft, treeLockFile as g, DEFAULT_SUPPORT_FILE_CHAR_POLICY as gn, daysSinceIso as gt, readTreeLock as h, DEFAULT_SKILL_LIMITS as hn, bumpView as ht, assessStructureHealth as i, READ_REQUIRED_ACTIONS as in, SKILLS_GUIDANCE_SECTION_ORDER as ir, bodyCost as it, makeSerialQueue as j, DEFAULT_REVIEW_CONTEXT_MESSAGES as jn, usageFile as jt, scanThreats as k, DEFAULT_MIN_IDLE_HOURS as kn, suppressedFile as kt, LeaseStore as l, DEFAULT_WRITE_CONFIRM_MODE as ln, UPSTREAM_LIMIT_CHARS_PER_TOKEN as lr, SUPPRESSED_FILE_VERSION as lt, acquireTreeWriteLock as m, DEFAULT_REFERENCE_REWRITE_POLICY as mn, bumpUse as mt, HEALTH_STAMP_RE as n, planReferenceRewrite as nn, PLATFORM_ESTIMATE_CHARS_PER_TOKEN as nr, TOKEN_ASCII_WEIGHT as nt, MutationAuthority as o, isUnreadWrite as on, SKILL_NAME_RE as or, evolutionHome as ot, assertHomeOwner as p, DEFAULT_CITATION_POLICY as pn, bumpSupportRead as pt, retainEventArchives as q, EVOLUTION_WRITE_TOOLS as qn, relatedSkillNames as qt, MIN_STAMP_BODY_CHARS as r, planRehoming as rn, PROTECTED_BUILTIN_SKILLS as rr, TOKEN_CJK_WEIGHT as rt, mutationLockFrom as s, sessionReadSkillNames as sn, SUPPORT_DIRS as sr, evolutionRoot as st, DEFAULT_HEALTH_THRESHOLDS as t, describeReferenceRewrite as tn, PLATFORM_CATALOG_DESCRIPTION_DEFAULT as tr, COST_CJK_TOKEN_LOW as tt, leaseFile as u, DEFAULT_WRITE_CONFIRM_TIMEOUT_SECONDS as un, applyCuratorLifecycleFields as ut, currentReviewContext as v, policyStageLimits as vn, foldCuratorFields as vt, PATTERN_OVERLAP as w, DEFAULT_CURATOR_BOOT_GRACE_SECONDS as wn, markAgentCreated as wt, isReviewChannelSession as x, CONTENT_SPLIT_HINT as xn, latestActivityAt as xt, withReviewContext as y, AUTHORING_DESCRIPTION_BAR as yn, getRecord as yt, EVENT_LOG_VERSION as z, DEFAULT_SKILL_VERSION_KEEP as zn, restructureCandidates as zt };