@lmzhen/dsh-evolution-core 0.48.0 → 0.50.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 (97) hide show
  1. package/lib/authority-plugin.js +2 -1
  2. package/lib/citations-CZKTUGQF.js +198 -0
  3. package/lib/composition/index.js +2 -2
  4. package/lib/{composition-Cqjbho0t.js → composition-DA8XPfMc.js} +1 -1
  5. package/lib/connection-DAJy7Xjm.js +28 -0
  6. package/lib/{ensure-CAjLGd9f.js → ensure-Bx4ksgJk.js} +15 -5
  7. package/lib/errors.js +2 -0
  8. package/lib/extract-plan-Bru3c9ec.js +271 -0
  9. package/lib/extract.js +240 -0
  10. package/lib/http-routes.js +27 -7
  11. package/lib/index.js +41 -822
  12. package/lib/{numeric-D8js3sqC.js → limits-C9jfvxBl.js} +1 -43
  13. package/lib/{mutation-authority-l57R626O.js → mutation-authority-DQfpXs1O.js} +2 -54
  14. package/lib/numeric-Dc53KQoe.js +43 -0
  15. package/lib/platform/index.js +4 -3
  16. package/lib/platform-DyHnHUmQ.js +251 -0
  17. package/lib/policy.js +3 -2
  18. package/lib/quality-WAU6YatF.js +554 -0
  19. package/lib/restrictor.js +1 -1
  20. package/lib/result.js +33 -0
  21. package/lib/runtime/plugin.js +97 -43
  22. package/lib/{session-projection-DSXnUNZG.js → session-projection-ByNxQi9O.js} +2 -198
  23. package/lib/skill-health-Bl-MdXZ4.js +1409 -0
  24. package/lib/skills.js +7 -4
  25. package/lib/state-store-Jpa-iYIZ.js +54 -0
  26. package/lib/subagent/index.js +214 -176
  27. package/lib/{tools-DzcNFex2.js → tools-BrUswg8v.js} +3 -1
  28. package/lib/types/composition/ensure.js +21 -7
  29. package/lib/types/extract-plan.d.ts +2 -0
  30. package/lib/types/extract.d.ts +12 -0
  31. package/lib/types/extract.js +12 -0
  32. package/lib/types/http-routes.js +32 -9
  33. package/lib/types/index.d.ts +0 -3
  34. package/lib/types/index.js +0 -3
  35. package/lib/types/long-runs.d.ts +0 -5
  36. package/lib/types/long-runs.js +0 -7
  37. package/lib/types/opt-in.js +4 -3
  38. package/lib/types/params.js +2 -1
  39. package/lib/types/platform/agents.d.ts +32 -0
  40. package/lib/types/platform/agents.js +26 -0
  41. package/lib/types/platform/commands.d.ts +14 -0
  42. package/lib/types/platform/commands.js +9 -0
  43. package/lib/types/platform/connection.d.ts +26 -0
  44. package/lib/types/platform/connection.js +27 -0
  45. package/lib/types/platform/index.d.ts +26 -0
  46. package/lib/types/platform/index.js +13 -0
  47. package/lib/types/platform/llm.d.ts +3 -1
  48. package/lib/types/platform/llm.js +1 -0
  49. package/lib/types/platform/platformView.d.ts +21 -0
  50. package/lib/types/platform/platformView.js +29 -0
  51. package/lib/types/platform/profileContext.d.ts +16 -0
  52. package/lib/types/platform/profileContext.js +14 -0
  53. package/lib/types/platform/sessionQuery.d.ts +14 -0
  54. package/lib/types/platform/sessionQuery.js +9 -0
  55. package/lib/types/platform/settings.d.ts +22 -0
  56. package/lib/types/platform/settings.js +14 -0
  57. package/lib/types/platform/skills.d.ts +16 -0
  58. package/lib/types/platform/skills.js +9 -0
  59. package/lib/types/platform/storageDomain.d.ts +13 -0
  60. package/lib/types/platform/storageDomain.js +9 -0
  61. package/lib/types/platform/subagents.d.ts +25 -0
  62. package/lib/types/platform/subagents.js +17 -0
  63. package/lib/types/platform/systemPrompt.d.ts +16 -0
  64. package/lib/types/platform/systemPrompt.js +13 -0
  65. package/lib/types/platform/tools.d.ts +4 -0
  66. package/lib/types/platform/tools.js +2 -0
  67. package/lib/types/platform/userQuestions.d.ts +33 -0
  68. package/lib/types/platform/userQuestions.js +9 -0
  69. package/lib/types/platform/workingDirectory.d.ts +14 -0
  70. package/lib/types/platform/workingDirectory.js +9 -0
  71. package/lib/types/platform-line.generated.d.ts +5 -5
  72. package/lib/types/platform-line.generated.js +5 -5
  73. package/lib/types/platform-services.js +3 -0
  74. package/lib/types/result.d.ts +35 -0
  75. package/lib/types/result.js +25 -0
  76. package/lib/types/runtime/llm.d.ts +2 -2
  77. package/lib/types/runtime/llm.js +5 -8
  78. package/lib/types/runtime/platform.d.ts +37 -4
  79. package/lib/types/runtime/platform.js +40 -5
  80. package/lib/types/runtime/projections.d.ts +9 -4
  81. package/lib/types/runtime/projections.js +64 -28
  82. package/lib/types/subagent/channel.d.ts +1 -3
  83. package/lib/types/subagent/channel.js +2 -332
  84. package/lib/types/subagent/index.d.ts +2 -0
  85. package/lib/types/subagent/index.js +2 -0
  86. package/lib/types/subagent/kernel.d.ts +4 -0
  87. package/lib/types/subagent/kernel.js +234 -0
  88. package/lib/types/subagent/readiness.js +5 -7
  89. package/lib/types/subagent/run.d.ts +53 -0
  90. package/lib/types/subagent/run.js +125 -0
  91. package/lib/types/subagent/types.d.ts +2 -2
  92. package/lib/types/write-inventory.d.ts +0 -11
  93. package/lib/types/write-inventory.js +0 -16
  94. package/lib/usage-DdjIBAkm.js +1252 -0
  95. package/package.json +37 -25
  96. package/lib/platform-Cc9cNt5j.js +0 -111
  97. package/lib/skill-health-DP8z9TPf.js +0 -2923
@@ -1,2923 +0,0 @@
1
- import { c as transactIo, o as nodeEvolutionIo } from "./io-GxghO3Ip.js";
2
- import { G as resolveCitations, O as collectReadSkillNames, R as supportFileReadFromPath, k as collectReadSupportFiles, l as sessionReadNames, o as isProjectableSession, v as DEFAULT_SUPPORT_READ_TOOL_NAMES } from "./session-projection-DSXnUNZG.js";
3
- import { K as SKILL_NAME_RE, M as DEFAULT_THREAT_MAX_SCAN_CHARS, Y as UPSTREAM_LIMIT_CHARS_PER_TOKEN, a as DEFAULT_SKILL_LIMITS, d as CONTENT_SPLIT_HINT, t as clampedNumber, u as AUTHORING_SPLIT_LINE_CHARS } from "./numeric-D8js3sqC.js";
4
- import { n as isRecord } from "./guards-3f02mnf2.js";
5
- import { AsyncLocalStorage } from "node:async_hooks";
6
- import { dirname, join } from "node:path";
7
- import { createHash } from "node:crypto";
8
- import { parse } from "yaml";
9
- //#region lib/types/write-authority.js
10
- /** The mode a deployment that configures nothing gets. */
11
- const DEFAULT_WRITE_CONFIRM_MODE = "auto";
12
- /** Seconds a timeout-mode prompt waits before the write is cancelled. */
13
- const DEFAULT_WRITE_CONFIRM_TIMEOUT_SECONDS = 120;
14
- /**
15
- * The batch-one migration aid: every call site becomes ONE of these instead of hand-building the
16
- * object - so the shape cannot drift between callers, and each site still has to say its own
17
- * origin out loud (origin is required here on purpose: the whole point is that no caller inherits
18
- * a default identity).
19
- */
20
- function authorityFrom(input) {
21
- return {
22
- origin: input.origin,
23
- threatExemptLabels: input.threatExemptLabels ?? [],
24
- protectedNames: input.protectedNames,
25
- readNames: input.readNames,
26
- ...input.confirm === void 0 ? {} : { confirm: input.confirm },
27
- ...input.confirmMode === void 0 ? {} : { confirmMode: input.confirmMode },
28
- ...input.confirmTimeoutSeconds === void 0 ? {} : { confirmTimeoutSeconds: input.confirmTimeoutSeconds },
29
- warn: input.warn ?? (() => {})
30
- };
31
- }
32
- //#endregion
33
- //#region lib/types/skill-reads.js
34
- /**
35
- * The skill names ONE session read, or `undefined` when its log is not readable.
36
- *
37
- * Two readers, in this order: the family's `evolutionReads` projection for a platform `Session`
38
- * (0.2.x's live read — the deprecated synchronous log read is gone from production), then the
39
- * STRUCTURAL accessor for a view that is not a `Session` at all. The tool path's exec view may be a
40
- * bare stub, which is what this module exists for; a real Session always takes the first path.
41
- *
42
- * `undefined` is NOT an empty set: a caller that must decide (the tool path's read-before-write
43
- * gate) can then keep its previous behavior instead of refusing every write in a composition whose
44
- * session objects expose no log at all.
45
- * @param ctx - a context of the runtime.
46
- * @param session - the session whose reads are wanted; `undefined` when the call carries none.
47
- * @returns the names read through a non-failed `skill` dispatch, or `undefined` when unreadable.
48
- */
49
- function sessionReadSkillNames(ctx, session) {
50
- if (session === void 0) return void 0;
51
- const projected = sessionReadNames(ctx, session);
52
- if (projected !== void 0) return projected;
53
- const events = session.readEvents?.();
54
- return events === void 0 ? void 0 : collectReadSkillNames(events);
55
- }
56
- /**
57
- * Skill support files ONE session read through a non-failed file tool (P2-27).
58
- *
59
- * platform-declaration anchor: `sessionProjections` is declared by
60
- * `@deepseek-ai/dsh-session-projection` (its registry; capability-probed here).
61
- * Same two readers as {@link sessionReadSkillNames}: the family projection first,
62
- * then the structural log view. `undefined` means "no evidence", not "nothing was
63
- * read" - the write gate then keeps its fail-open posture.
64
- * @param ctx - a context of the runtime.
65
- * @param session - the session whose reads are wanted.
66
- * @param options - the skills root and the configured file-tool names.
67
- * @returns skill -> set of skill-root-relative support paths.
68
- */
69
- function sessionReadSupportFiles(ctx, session, options) {
70
- if (session === void 0) return void 0;
71
- if (isProjectableSession(session)) {
72
- const state = ctx.get("evolutionProjections")?.reads(session);
73
- if (state !== void 0) {
74
- const toolNames = options.toolNames ?? DEFAULT_SUPPORT_READ_TOOL_NAMES;
75
- const reads = /* @__PURE__ */ new Map();
76
- for (const entry of state.reads) {
77
- if (entry.failed || typeof entry.file !== "string") continue;
78
- if (entry.tool !== void 0 && !toolNames.includes(entry.tool)) continue;
79
- const hit = supportFileReadFromPath(entry.file, { root: options.root });
80
- if (hit === null) continue;
81
- const set = reads.get(hit.skill) ?? /* @__PURE__ */ new Set();
82
- set.add(hit.rel);
83
- reads.set(hit.skill, set);
84
- }
85
- return reads;
86
- }
87
- }
88
- const events = session.readEvents?.();
89
- return events === void 0 ? void 0 : collectReadSupportFiles(events, {
90
- toolNames: options.toolNames ?? DEFAULT_SUPPORT_READ_TOOL_NAMES,
91
- root: options.root
92
- });
93
- }
94
- /** Actions whose target must have been read first (create is authorship, so it is exempt). */
95
- const READ_REQUIRED_ACTIONS = Object.freeze([
96
- "edit",
97
- "update",
98
- "patch",
99
- "delete",
100
- "write_file",
101
- "remove_file",
102
- "restructure",
103
- "extract"
104
- ]);
105
- /**
106
- * Does this one op write a skill the caller never read?
107
- *
108
- * V6-26 (0.3.37): the validator normalizes a missing action to `patch`, so a missing action is a
109
- * read-required write, never silently exempt.
110
- * @param op - one skill operation (from a tool call or a review plan).
111
- * @param readNames - names read this session, from {@link collectReadSkillNames}.
112
- * @returns true when the op is a read-required write to an unread target.
113
- */
114
- function isUnreadWrite(op, readNames) {
115
- if (!op.name) return false;
116
- return READ_REQUIRED_ACTIONS.includes(op.action ?? "patch") && !readNames.has(op.name);
117
- }
118
- /**
119
- * Drop mutating ops whose target was not read this session, in place.
120
- *
121
- * Covers the same mutating surface Hermes guards (edit/patch/write_file/remove_file), so a
122
- * background review cannot blind-touch support files or edits of skills it never loaded.
123
- * @param ops - the plan's ops; dropped entries are removed in place.
124
- * @param readNames - names read this session.
125
- * @returns the count of dropped ops, so the plan event can report them as rejected.
126
- */
127
- function filterUnreadSkillOps(ops, readNames) {
128
- let dropped = 0;
129
- for (let index = ops.length - 1; index >= 0; index -= 1) {
130
- const op = ops[index];
131
- if (!op) continue;
132
- if (isUnreadWrite(op, readNames)) {
133
- ops.splice(index, 1);
134
- dropped += 1;
135
- }
136
- }
137
- return dropped;
138
- }
139
- //#endregion
140
- //#region lib/types/reference-rewrite.js
141
- /**
142
- * Reference re-homing plans (0.5.0 V1, design §16.7).
143
- *
144
- * A consolidation moves one skill's body under ANOTHER skill root, where every
145
- * support-dir reference resolves against that other root (design §2.1). This
146
- * module plans what has to happen to the support files and to the body's
147
- * references for the move to leave no dangling link. Pure: the caller owns IO,
148
- * decides the destination names, and decides whether the plan is applied (V2)
149
- * or only reported (V1). Cross-skill rewriting is out of scope by design (§14) —
150
- * a plan covers ONE body.
151
- */
152
- /**
153
- * Provisional re-homing rule. The naming style for re-homed files is still an
154
- * open decision (design §16.3 B5); this rule only fires on a COLLISION, where
155
- * something has to give: a path that the target already occupies gets the source
156
- * name as a prefix (`references/a.md` -> `references/<source>-a.md`). Nested
157
- * destinations are deliberately avoided: the support listing is one level deep,
158
- * so a file moved into a subdirectory would drop out of the listing entirely.
159
- * @param sourceFiles - the moving skill's support files.
160
- * @param targetFiles - the destination skill's support files.
161
- * @param sourceName - the moving skill's name, used as the collision prefix.
162
- * @returns the moves plus the paths that collided (for the report).
163
- */
164
- function planRehoming(sourceFiles, targetFiles, sourceName) {
165
- const taken = new Set(targetFiles);
166
- const collisions = [];
167
- const moves = [];
168
- for (const path of sourceFiles) {
169
- if (!taken.has(path)) {
170
- moves.push({
171
- from: path,
172
- to: path
173
- });
174
- continue;
175
- }
176
- collisions.push(path);
177
- const cut = path.lastIndexOf("/");
178
- const dir = cut < 0 ? "" : path.slice(0, cut + 1);
179
- const name = path.slice(cut + 1);
180
- let candidate = `${dir}${sourceName}-${name}`;
181
- let counter = 2;
182
- while (taken.has(candidate)) {
183
- candidate = `${dir}${sourceName}-${counter}-${name}`;
184
- counter += 1;
185
- }
186
- taken.add(candidate);
187
- moves.push({
188
- from: path,
189
- to: candidate
190
- });
191
- }
192
- return {
193
- moves,
194
- collisions
195
- };
196
- }
197
- /**
198
- * Plan the reference rewrites for one body that is moving into another root.
199
- * @param input - the body, the MOVING skill's file list, the re-homing moves and
200
- * the destination's file list (with the moved paths already included).
201
- * @returns the edits, the cited files without a destination, and any target that
202
- * the destination file list cannot prove (applying such a plan would dangle).
203
- */
204
- function planReferenceRewrite(input) {
205
- const report = resolveCitations({
206
- content: input.content,
207
- file: "SKILL.md",
208
- files: input.files
209
- });
210
- const byFrom = new Map(input.moves.map((move) => [move.from, move.to]));
211
- const available = new Set(input.targetFiles);
212
- const edits = [];
213
- const unresolved = [];
214
- const residual = /* @__PURE__ */ new Set();
215
- const used = /* @__PURE__ */ new Set();
216
- for (const ref of report.refs) {
217
- if (ref.kind !== "citation" || ref.target === null) continue;
218
- const move = byFrom.get(ref.target);
219
- const to = move ?? ref.target;
220
- if (move !== void 0) {
221
- used.add(ref.target);
222
- if (move !== ref.target) edits.push({
223
- line: ref.line,
224
- from: ref.target,
225
- to: move,
226
- raw: ref.raw
227
- });
228
- } else if (!report.dangling.some((entry) => entry.target === ref.target)) unresolved.push(ref.target);
229
- if (!available.has(to)) residual.add(to);
230
- }
231
- return {
232
- edits,
233
- unresolved: [...new Set(unresolved)],
234
- residualDangling: [...residual],
235
- moves: input.moves.filter((move) => used.has(move.from))
236
- };
237
- }
238
- /**
239
- * Apply a plan's edits to the body (V2). Line-wise and literal: line N gets its
240
- * FIRST occurrence of the recorded token replaced, everything else is copied
241
- * byte for byte — no regex, so a token that happens to contain regex
242
- * metacharacters cannot rewrite more than it matched.
243
- * @param content - the body the plan was computed against.
244
- * @param edits - the plan's edits.
245
- * @returns the rewritten body (identical to the input when there is nothing to do).
246
- */
247
- function applyReferenceRewrite(content, edits) {
248
- if (edits.length === 0) return content;
249
- const byLine = /* @__PURE__ */ new Map();
250
- for (const edit of edits) {
251
- const list = byLine.get(edit.line);
252
- if (list === void 0) byLine.set(edit.line, [edit]);
253
- else list.push(edit);
254
- }
255
- const lines = content.split("\n");
256
- for (const [lineNo, lineEdits] of byLine) {
257
- const index = lineNo - 1;
258
- const original = lines[index];
259
- if (original === void 0) continue;
260
- let next = original;
261
- for (const edit of lineEdits) {
262
- const at = next.indexOf(edit.raw);
263
- if (at < 0) continue;
264
- next = next.slice(0, at) + edit.to + next.slice(at + edit.raw.length);
265
- }
266
- lines[index] = next;
267
- }
268
- return lines.join("\n");
269
- }
270
- /**
271
- * One-line, model-facing summary of a plan, for the consolidation refusal and
272
- * for the V2 apply path's audit text.
273
- * @param plan - the plan to describe.
274
- * @returns a compact sentence naming counts, the moves and any residual risk.
275
- */
276
- function describeReferenceRewrite(plan) {
277
- const renames = plan.moves.filter((move) => move.from !== move.to);
278
- return `plan: ${[
279
- `re-home ${plan.moves.length} file(s)`,
280
- renames.length === 0 ? "" : `renamed: ${renames.map((move) => `${move.from}->${move.to}`).join(", ")}`,
281
- `rewrite ${plan.edits.length} reference(s)`,
282
- `residual dangling ${plan.residualDangling.length}`,
283
- plan.unresolved.length === 0 ? "" : `no destination: ${plan.unresolved.slice(0, 5).join(", ")}`
284
- ].filter((part) => part.length > 0).join("; ")}`;
285
- }
286
- //#endregion
287
- //#region lib/types/support-refs.js
288
- /**
289
- * Support-directory references in a markdown body (009 kernel): references/…,
290
- * templates/…, scripts/…, assets/… relative links — any extension and nested
291
- * paths. Pure: who checks them and what the verdict is belongs to the caller.
292
- * `..` traversal is a different defect class (path validation owns it) and is
293
- * not a support link.
294
- */
295
- function supportRefs(content) {
296
- const refs = [];
297
- for (const match of content.matchAll(/(?<![A-Za-z0-9._/-])(?:references|templates|scripts|assets)\/[A-Za-z0-9._/-]+/g)) {
298
- const ref = match[0];
299
- if (ref.includes("..")) continue;
300
- refs.push(ref);
301
- }
302
- return refs;
303
- }
304
- /**
305
- * References that leave the skill root: parent traversals or absolute support paths.
306
- * Extract must not silently treat these as relative support files; the caller reports
307
- * them (bounded external copy is a separate, explicit policy).
308
- * @param content - markdown body.
309
- * @returns external-looking support references, de-duplicated in first-seen order.
310
- */
311
- function externalRefs(content) {
312
- const refs = [];
313
- for (const match of content.matchAll(/(?:^|[\s("'`])((?:\.\.\/)+[A-Za-z0-9._/-]+|\/[A-Za-z0-9._/-]+)/g)) {
314
- const ref = match[1]?.replace(/[.,;:]+$/, "");
315
- if (ref === void 0 || ref.length === 0 || refs.includes(ref)) continue;
316
- refs.push(ref);
317
- }
318
- return refs;
319
- }
320
- //#endregion
321
- //#region lib/types/frontmatter.js
322
- /**
323
- * Frontmatter parsing, normalization and validation for skill Markdown files.
324
- *
325
- * Split out of skill-store.ts (S2-1): pure functions over file text, no store
326
- * state. skill-store.ts re-exports the same names it exported before the split,
327
- * so the package export surface is unchanged.
328
- */
329
- /**
330
- * Shared frontmatter block detection (P3-3 single owner): opening line `---`
331
- * and closing line exactly `---`. Used by `parseFrontmatter`,
332
- * `frontmatterCatalogInvalid` and `normalizeFrontmatter` so the three can
333
- * never disagree about where the block ends (the loose `indexOf('\n---')`
334
- * form matched `\n----` and was replaced by this strict line rule).
335
- *
336
- * V27 G2.1: both fence lines are matched EXACTLY, tolerating only a trailing
337
- * `\r` — the same rule the upstream filesystem catalog uses
338
- * (`skill-filesystem.parseFrontmatter`). The former `.trim()` comparison
339
- * accepted ` --- `, so an indented fence loaded in the family while the
340
- * platform ignored the file: family visibility split from platform visibility,
341
- * which is exactly what a strict-YAML frontmatter is supposed to prevent.
342
- */
343
- /**
344
- * S1.1 (v37 P1-4): the frontmatter block is split on LF and every line keeps its
345
- * own `\r`, so the byte-preserving rebuild (`lines.join('\n')`) is exact. Line
346
- * MATCHERS must therefore look at a CR-stripped view: JS `.` does not match `\r`,
347
- * so `(.*)$` never reaches the end of a CRLF line.
348
- * @param line - one block line, possibly CR-terminated.
349
- * @returns the line without its trailing CR.
350
- */
351
- function withoutCr(line) {
352
- return line.endsWith("\r") ? line.slice(0, -1) : line;
353
- }
354
- function frontmatterBlock(content) {
355
- if (!content.trimStart().startsWith("---")) return null;
356
- const firstBreak = content.indexOf("\n");
357
- const nl = firstBreak > 0 && content[firstBreak - 1] === "\r" ? "\r\n" : "\n";
358
- const lines = content.split("\n");
359
- if ((lines[0] ?? "").replace(/\r$/, "") !== "---") return null;
360
- let end = -1;
361
- for (let i = 1; i < lines.length; i++) {
362
- const line = lines[i];
363
- if (line === void 0) continue;
364
- if (line === "---" || line === "---\r") {
365
- end = i;
366
- break;
367
- }
368
- }
369
- if (end < 0) return null;
370
- return {
371
- block: lines.slice(1, end).join("\n"),
372
- lines,
373
- end,
374
- nl
375
- };
376
- }
377
- /**
378
- * Raw-line scan of a frontmatter block: the single owner of "which entries the
379
- * strict catalog cannot load". `frontmatterCatalogInvalid` publishes it and
380
- * `normalizeFrontmatter` decides each rewrite with the same predicate
381
- * (`yamlPlainScalarNeedsQuotes`), so the audit verdict and the write path can
382
- * never disagree. A9 (audit P2-12): the scan is ENDING-AGNOSTIC — lines are
383
- * split on `\n` with the per-line CR stripped, exactly the iteration the
384
- * rewrite path uses. The former split on the block's FIRST-LINE ending turned
385
- * a mixed-ending block (first line CRLF, entries LF) into one unsplit chunk
386
- * whose entries were all skipped, so an unquoted ` #` value read as CLEAN
387
- * while the catalog silently dropped it and the next edit would have quoted
388
- * it. Only single-line `key: value` entries are judged.
389
- */
390
- function unsafeFrontmatterEntries(block) {
391
- const found = [];
392
- for (const rawLine of block.split("\n")) {
393
- const match = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(withoutCr(rawLine));
394
- if (!match) continue;
395
- const key = match[1];
396
- if (key === void 0) continue;
397
- const value = (match[2] ?? "").trim();
398
- if (yamlPlainScalarNeedsQuotes(value)) found.push({
399
- key,
400
- value
401
- });
402
- }
403
- return found;
404
- }
405
- /**
406
- * Frontmatter fields the platform catalog reads as STRINGS (`stringField` /
407
- * `optionalString` in `skill-filesystem`): any other YAML type reads as
408
- * ABSENT there, and an absent `name`/`description` makes the catalog ignore the
409
- * whole file. The family publishes text for these keys anyway (its lenient
410
- * read), which is the one split a write must not create.
411
- */
412
- const PLATFORM_STRING_FIELDS = [
413
- "name",
414
- "description",
415
- "whenToUse"
416
- ];
417
- /**
418
- * Frontmatter values as the STRICT platform catalog reads them — the `yaml`
419
- * package (YAML 1.2 core schema, the same dependency the platform's
420
- * skill-filesystem parses with — see the import note above),
421
- * the parser `normalizeFrontmatter` also verifies rewrites with — or `null`
422
- * when the block is not loadable as a YAML mapping. Also reports the platform
423
- * string fields whose value is not a string ({@link PlatformStringSplit}).
424
- *
425
- * Scalars publish their text (`name`, `description`, `whenToUse` are strings by
426
- * contract; a number/boolean-shaped value keeps the text the family always
427
- * published), a flow or block sequence publishes its inline `[a, b]` form
428
- * (`relatedSkillNames` scans names out of it), and a nested mapping publishes
429
- * nothing — no consumer in this family reads one, and a lossy string could be
430
- * picked up by a routing field. A string value is trimmed: YAML's block-scalar
431
- * chomping appends a newline that the family's single-line routing fields never
432
- * carried.
433
- */
434
- function strictFrontmatterValues(block) {
435
- if (block.trim() === "") return {
436
- values: /* @__PURE__ */ new Map(),
437
- split: []
438
- };
439
- let loaded;
440
- try {
441
- loaded = parse(block);
442
- } catch {
443
- return null;
444
- }
445
- if (loaded === null || loaded === void 0) return {
446
- values: /* @__PURE__ */ new Map(),
447
- split: []
448
- };
449
- if (typeof loaded !== "object" || Array.isArray(loaded)) return null;
450
- const values = /* @__PURE__ */ new Map();
451
- const split = [];
452
- let metadata;
453
- for (const [key, value] of Object.entries(loaded)) {
454
- if (typeof value !== "string" && PLATFORM_STRING_FIELDS.includes(key)) split.push({
455
- key,
456
- kind: value === null || value === void 0 ? "null" : Array.isArray(value) ? "sequence" : typeof value === "object" ? "mapping" : "scalar"
457
- });
458
- if (typeof value === "string") {
459
- values.set(key, value.trim());
460
- continue;
461
- }
462
- if (typeof value === "number" || typeof value === "boolean") {
463
- values.set(key, String(value));
464
- continue;
465
- }
466
- if (Array.isArray(value)) {
467
- values.set(key, `[${value.map((item) => String(item)).join(", ")}]`);
468
- continue;
469
- }
470
- if (key === "metadata" && isRecord(value)) {
471
- metadata = value;
472
- continue;
473
- }
474
- }
475
- return {
476
- values,
477
- split,
478
- metadata
479
- };
480
- }
481
- /**
482
- * Lenient line scan, used only for a block the strict parser rejects: the
483
- * family keeps routing a legacy file the platform refuses, and
484
- * `catalogInvalid` reports the split instead of hiding it. Values are trimmed
485
- * and unquoted exactly as before.
486
- */
487
- function lenientFrontmatterValues(block, nl) {
488
- const values = /* @__PURE__ */ new Map();
489
- const blockLines = block.split(nl);
490
- for (let i = 0; i < blockLines.length; i += 1) {
491
- const line = withoutCr(blockLines[i] ?? "");
492
- const match = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(line);
493
- if (!match) continue;
494
- const [, key, value] = match;
495
- if (key === void 0 || value === void 0) continue;
496
- const header = /^([>|])[+-]?\d*$/.exec(value.trim());
497
- if (header !== null) {
498
- const fold = header[1] === ">";
499
- const parts = [];
500
- let scan = i + 1;
501
- for (; scan < blockLines.length; scan += 1) {
502
- const raw = blockLines[scan] ?? "";
503
- if (raw.trim() === "") {
504
- parts.push("");
505
- continue;
506
- }
507
- if (!/^\s/.test(raw)) break;
508
- parts.push(raw.trim());
509
- }
510
- while (parts.length > 0 && parts[parts.length - 1] === "") parts.pop();
511
- let folded = "";
512
- for (const part of parts) {
513
- if (part === "") {
514
- if (folded !== "" && !folded.endsWith("\n")) folded += "\n";
515
- continue;
516
- }
517
- if (folded === "" || folded.endsWith("\n")) folded += part;
518
- else folded += ` ${part}`;
519
- }
520
- values.set(key, (fold ? folded : parts.join("\n")).trim());
521
- i = scan - 1;
522
- continue;
523
- }
524
- values.set(key, value.trim().replace(/^["']|["']$/g, ""));
525
- }
526
- return values;
527
- }
528
- /**
529
- * The single read of a SKILL.md frontmatter block: values, body and every
530
- * strict-catalog signal, computed once. `null` only when the file has no
531
- * frontmatter block; the body may be empty. {@link parseFrontmatter} and
532
- * {@link frontmatterCatalogInvalid} are its two projections.
533
- *
534
- * @param content - the SKILL.md text.
535
- * @returns the block read, or `null` when there is no block.
536
- */
537
- function readFrontmatterBlock(content) {
538
- const found = frontmatterBlock(content);
539
- if (!found) return null;
540
- const body = found.lines.slice(found.end + 1).join("\n").trim();
541
- const strict = strictFrontmatterValues(found.block);
542
- const values = strict?.values ?? lenientFrontmatterValues(found.block, found.nl);
543
- const frontmatter = {};
544
- for (const [key, value] of values) frontmatter[key] = value;
545
- return {
546
- frontmatter,
547
- body,
548
- unsafeValues: unsafeFrontmatterEntries(found.block),
549
- strictFailed: strict === null,
550
- platformStringSplit: strict?.split ?? [],
551
- metadata: strict?.metadata
552
- };
553
- }
554
- /**
555
- * Parse a SKILL.md: its frontmatter values and body, or `null` when the file
556
- * has no frontmatter block or no body. Every consumer of frontmatter values
557
- * goes through here — the write path's validation, `list()`'s published
558
- * description, `relatedSkillNames` and the audit — so all of them read the same
559
- * bytes the same way.
560
- *
561
- * @param content - the SKILL.md text.
562
- * @returns the read, or `null` when there is no block or no body.
563
- */
564
- function parseFrontmatter(content) {
565
- const read = readFrontmatterBlock(content);
566
- if (!read || !read.body) return null;
567
- return {
568
- frontmatter: read.frontmatter,
569
- body: read.body,
570
- unsafeValues: read.unsafeValues,
571
- metadata: read.metadata,
572
- catalogInvalid: read.strictFailed || read.unsafeValues.length > 0 || read.platformStringSplit.length > 0,
573
- platformStringSplit: read.platformStringSplit
574
- };
575
- }
576
- /**
577
- * Whether this file's frontmatter is valid as written for the strict platform
578
- * catalog (see `FrontmatterRead.catalogInvalid`). Body-independent (a body-less
579
- * file is still judged), and derived from the same read as `parseFrontmatter` —
580
- * so the audit's verdict and the values the family publishes for one file can
581
- * never disagree (V27 G2.1).
582
- *
583
- * @param content - the SKILL.md text.
584
- * @returns `true` when the strict parser rejects the block or an unquoted value would read as something else.
585
- */
586
- function frontmatterCatalogInvalid(content) {
587
- const read = readFrontmatterBlock(content);
588
- if (read !== null) return read.strictFailed || read.unsafeValues.length > 0 || read.platformStringSplit.length > 0;
589
- return frontmatterBlock(content.replace(/^\uFEFF/, "").replace(/\r\n/g, "\n")) !== null;
590
- }
591
- /** YAML plain-scalar hazards that make an UNQUOTED frontmatter value
592
- * unloadable to the platform catalog (strict YAML parser): `: ` (mapping
593
- * separator), ` #` (comment start), a trailing `:` (a mapping marker),
594
- * or a leading YAML indicator. The evolution `parseFrontmatter` is
595
- * deliberately lenient, so violations silently split family-visibility from
596
- * platform-visibility (0.3.11 inkos-harness case: the description carried
597
- * "…: " and the catalog dropped the whole skill). Already-quoted values and
598
- * well-formed flow collections (`[a, b]` / `{a: b}`) are considered safe.
599
- * 0.3.16 (E-47): null/bool/number-shaped plain scalars are flagged too — they
600
- * parse as booleans/numbers on the platform while the family keeps the string
601
- * (a `description: true` split-brain).
602
- * This rule is only the FAST PATH — the write path re-verifies every rewrite
603
- * with the real YAML parser (see normalizeFrontmatter), so an incomplete
604
- * approximation can never corrupt a multiline flow value (P3-4). */
605
- function yamlPlainScalarNeedsQuotes(value) {
606
- if (value.length === 0) return false;
607
- if (value.length >= 2 && (value.startsWith("\"") && value.endsWith("\"") || value.startsWith("'") && value.endsWith("'"))) return false;
608
- if (/^\[.*\]$/.test(value) || /^\{.*\}$/.test(value)) return false;
609
- if (/^[>|][+-]?\d*$/.test(value)) return false;
610
- if (value.includes(": ")) return true;
611
- if (value.includes(" #")) return true;
612
- if (value.endsWith(":")) return true;
613
- if (/^(?:null|true|false|~)$/i.test(value)) return true;
614
- if (/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?$/.test(value)) return true;
615
- if (/^0x[0-9a-f]+$/i.test(value)) return true;
616
- if (/^0o[0-7]+$/.test(value)) return true;
617
- if (/^(?:[-+]?\.inf|\.nan)$/i.test(value)) return true;
618
- if (/^[-?:,[\]{}#&*!|>'"%@`\s]/.test(value)) return true;
619
- return false;
620
- }
621
- /**
622
- * Normalize a SKILL.md frontmatter block into catalog-loadable YAML: values
623
- * that YAML forbids unquoted get quotes — double quotes normally, single
624
- * quotes (with `''` doubling) when the value contains `"` or `\` (both legal
625
- * unescaped inside single-quoted YAML). Idempotent; only single-line
626
- * `key: value` entries are touched; body text is never modified; line-ending
627
- * style is preserved. **Every rewrite is re-verified with the real YAML
628
- * parser** (`yaml` — the package the platform's skill-filesystem catalog parses
629
- * with, YAML 1.2 core schema; PLAN S2.1, 2026-09-16 — the former "js-yaml, the
630
- * same parser" claim was false: js-yaml speaks YAML 1.1 full and diverged on
631
- * dates, timestamps and 1.1 int forms): if the
632
- * rewritten block no longer parses, or a rewritten value's parsed content
633
- * differs from the original, the rewrite is rolled back and reported in
634
- * `issues` (fail-loud, never a silent value corruption — P3-4).
635
- *
636
- * V10-02 (P2-3): the rewrite decision is PER LINE — each entry parses its own
637
- * value, so a duplicated key can never route one entry's unsafe value into a
638
- * different line's rewrite (the old key→Map lookup rewrote the FIRST (safe)
639
- * line with the SECOND line's quoted value, and the last-wins YAML reader
640
- * masked the damage). A duplicated key is itself invalid input and is
641
- * reported in `issues` (the write path refuses) instead of being rewritten.
642
- */
643
- function normalizeFrontmatter(content) {
644
- const block = frontmatterBlock(content);
645
- if (!block) return {
646
- content,
647
- changed: false,
648
- fields: [],
649
- issues: []
650
- };
651
- const { lines, end } = block;
652
- const fields = [];
653
- const issues = [];
654
- const seen = /* @__PURE__ */ new Set();
655
- const originalValues = /* @__PURE__ */ new Map();
656
- let changed = false;
657
- for (let i = 1; i < end; i++) {
658
- const raw = lines[i];
659
- if (raw === void 0) continue;
660
- const match = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(withoutCr(raw));
661
- if (!match) continue;
662
- const key = match[1];
663
- if (key === void 0) continue;
664
- const value = (match[2] ?? "").trim();
665
- if (seen.has(key)) {
666
- issues.push(`${key}: duplicate frontmatter key — remove the repeated entry and retry`);
667
- continue;
668
- }
669
- seen.add(key);
670
- if (!yamlPlainScalarNeedsQuotes(value)) continue;
671
- if (/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/.test(value)) {
672
- issues.push(`${key}: value contains control characters — clean them manually`);
673
- continue;
674
- }
675
- lines[i] = `${key}: ${value.includes("\"") || value.includes("\\") ? `'${value.replace(/'/g, "''")}'` : `"${value}"`}${raw.endsWith("\r") ? "\r" : ""}`;
676
- originalValues.set(key, value);
677
- fields.push(key);
678
- changed = true;
679
- }
680
- if (issues.length > 0) return {
681
- content,
682
- changed: false,
683
- fields: [],
684
- issues
685
- };
686
- if (!changed) return {
687
- content,
688
- changed: false,
689
- fields: [],
690
- issues
691
- };
692
- const rewrittenBlock = lines.slice(1, end).join("\n");
693
- try {
694
- const parsed = parse(rewrittenBlock);
695
- for (const key of fields) if (String(parsed[key]) !== originalValues.get(key)) throw new Error(`rewritten value for ${key} differs from the original`);
696
- return {
697
- content: lines.join("\n"),
698
- changed: true,
699
- fields,
700
- issues
701
- };
702
- } catch (error) {
703
- return {
704
- content,
705
- changed: false,
706
- fields: [],
707
- issues: [`frontmatter rewrite verification failed (${error instanceof Error ? error.message : String(error)}) — quoting skipped; wrap this value manually`]
708
- };
709
- }
710
- }
711
- /**
712
- * Skill names referenced by a SKILL.md's `related_skills` frontmatter
713
- * (B-line G3, rc.44): the single parsing source for the quality references
714
- * factor and the learning-graph edges. The DSH frontmatter parser keeps the
715
- * YAML value as a string (`"[a, b]"`), so names are scanned out of it; each
716
- * must satisfy the skill-name shape and the referencing skill itself is
717
- * excluded. Pure and deduplicated.
718
- */
719
- function relatedSkillNames(content, exclude) {
720
- const parsed = parseFrontmatter(content);
721
- if (!parsed) return [];
722
- const nestedHost = parsed.metadata?.["hermes"];
723
- const nestedRaw = isRecord(nestedHost) ? nestedHost["related_skills"] : void 0;
724
- const flat = parsed.frontmatter["related_skills"];
725
- const raw = typeof flat === "string" ? flat : Array.isArray(nestedRaw) ? `[${nestedRaw.map((item) => String(item)).join(", ")}]` : void 0;
726
- if (typeof raw !== "string") return [];
727
- const names = /* @__PURE__ */ new Set();
728
- for (const match of Array.from(raw.matchAll(/(?<![A-Za-z0-9_-])[a-z0-9][a-z0-9-]*(?![A-Za-z0-9_-])/g))) {
729
- const target = match[0];
730
- if (target && SKILL_NAME_RE.test(target) && target !== exclude) names.add(target);
731
- }
732
- return [...names];
733
- }
734
- /** S1.2 (v37 P2-1): the content limit applies to the bytes that LAND ON DISK.
735
- * Every write normalizes with `trimEnd() + '\n'`, so judging the raw argument let
736
- * a 100_000-character body with no trailing newline land as 100_001 bytes — and
737
- * every later patch/update of that skill was then refused, which made it
738
- * unmaintainable through `skill_manage` with no repair path at all. */
739
- /** The bytes that land on disk for a SKILL.md write — the ONE accounting basis
740
- * shared by the content limit and the cost estimate (design §5.2). */
741
- function skillMdOnDisk(content) {
742
- return content.trimEnd() + "\n";
743
- }
744
- /** Whether `content` would exceed `limit` once written. */
745
- function exceedsContentLimit(content, limit) {
746
- return skillMdOnDisk(content).length > limit;
747
- }
748
- /** S1.2: the repair path — a write that makes an already-over-limit file smaller.
749
- * Only a NET SHRINK is exempt; an equal or larger write stays refused. */
750
- function shrinksOverLimit(next, current, limit) {
751
- if (current === null || current === void 0 || !exceedsContentLimit(current, limit)) return false;
752
- return skillMdOnDisk(next).length < skillMdOnDisk(current).length;
753
- }
754
- /**
755
- * Synthesize a missing SKILL.md header at the write boundary.
756
- *
757
- * A model-authored create/update whose body starts with `# Title` is valid Markdown but the
758
- * skill writer rejects it before any content check. Repair only the truly headerless shape: an
759
- * existing fence is passed through byte-identical, even when it is malformed, so this helper
760
- * cannot mask a header error that the validator should report. The caller owns the audit notice.
761
- * @param content - the model-authored SKILL.md text.
762
- * @param name - the validated skill name used for the `name:` field.
763
- * @param description - optional description; otherwise derived from the first heading/prose.
764
- * @returns the write text and whether a header was synthesized.
765
- */
766
- function ensureSkillFrontmatter(content, name, description) {
767
- if (frontmatterBlock(content) !== null || content.trimStart().startsWith("---")) return {
768
- content,
769
- repaired: false
770
- };
771
- const body = content.replace(/^\uFEFF/, "").replace(/^(?:[ \t]*\r?\n)+/, "");
772
- const heading = /^#{1,6}\s+(.+?)\s*$/m.exec(body)?.[1];
773
- const firstLine = body.split(/\r?\n/).map((line) => line.trim()).find((line) => line !== "" && !line.startsWith("#")) ?? "";
774
- const source = (description?.trim() || heading || firstLine || name).replace(/\s+/g, " ").trim();
775
- const clipped = source.length > 58 ? source.slice(0, 57) + "…" : source;
776
- const summary = /[.。!?!?]$/.test(clipped) ? clipped : clipped + ".";
777
- const encoded = yamlPlainScalarNeedsQuotes(summary) ? JSON.stringify(summary) : summary;
778
- return {
779
- content: [
780
- "---",
781
- `name: ${name}`,
782
- `description: ${encoded}`,
783
- "version: 0.1.0",
784
- "author: Hermes",
785
- "---",
786
- ""
787
- ].join("\n") + "\n" + body,
788
- repaired: true
789
- };
790
- }
791
- function validateFrontmatter(content, expectedName, limits = DEFAULT_SKILL_LIMITS, current) {
792
- const parsed = parseFrontmatter(content);
793
- if (!parsed) return "SKILL.md 必须以 `---` 行开头,用另一个完全相同的 `---` 行结束 frontmatter(只容忍结尾的 `\\r`),并在其下包含正文。";
794
- const unreadable = parsed.platformStringSplit.filter((entry) => entry.kind === "sequence" || entry.kind === "mapping");
795
- if (unreadable.length > 0) return `Frontmatter 字段 ${unreadable.map((entry) => `"${entry.key}" (a YAML ${entry.kind})`).join(", ")} 必须是字符串:平台技能目录会把这种字段当作缺失,并忽略整个文件。请写成纯文本,或用双引号包住取值以保持字面内容。`;
796
- if (!parsed.frontmatter.name) return "Frontmatter 必须包含 name 字段。";
797
- if (!SKILL_NAME_RE.test(parsed.frontmatter.name)) return `技能名「${parsed.frontmatter.name}」不合法:请只用小写字母、数字和连字符。`;
798
- if (parsed.frontmatter.name.length > limits.maxNameLength) return `技能名超过 ${limits.maxNameLength} 个字符。`;
799
- if (expectedName && parsed.frontmatter.name !== expectedName) return `Frontmatter 里的 name「${parsed.frontmatter.name}」与目标技能「${expectedName}」不一致。`;
800
- if (!parsed.frontmatter.description) return "Frontmatter 必须包含 description 字段。";
801
- if (parsed.frontmatter.description.length > limits.maxDescriptionLength) return `description 超过 ${limits.maxDescriptionLength} 个字符。`;
802
- if (exceedsContentLimit(content, limits.maxSkillContentChars) && !shrinksOverLimit(content, current, limits.maxSkillContentChars)) return `SKILL.md 内容超过 ${limits.maxSkillContentChars} 个字符。${CONTENT_SPLIT_HINT}`;
803
- return null;
804
- }
805
- /**
806
- * Advisory authoring feedback (P0): evaluate frontmatter against the
807
- * authoring bar WITHOUT changing platform validation semantics. The bar is
808
- * the quality target, `validateFrontmatter`'s limits are the compatibility
809
- * floor, and this bridge layer tells the model when its text would be
810
- * truncated or route-poor instead of silently shipping it.
811
- */
812
- function authoringFeedback(frontmatter) {
813
- const description = frontmatter.description ?? "";
814
- const over60 = description.length > 60;
815
- const hasColon = description.includes(":");
816
- const lines = [];
817
- lines.push(over60 ? `描述为 ${description.length}/60 个字符 —— 超过 60 字符的作者规范上限(Hermes 标准;技能目录会按平台配置的上限截断)。` : `描述为 ${description.length}/60 个字符 —— 在作者规范上限之内。`);
818
- if (hasColon) lines.push("描述里含冒号 —— 请用双引号把整个取值包起来。");
819
- return {
820
- descriptionChars: description.length,
821
- over60,
822
- hasColon,
823
- lines
824
- };
825
- }
826
- /** A1-15 (v18) / P2-2 (v19): the io layer marks an error `committed: true` when
827
- * the rename landed and only the directory fsync failed. Every single-file
828
- * writer must treat that as "written, durability unconfirmed" — never as a
829
- * plain failure (which a caller would retry, or a two-phase caller roll back).
830
- * v28 G2.1 (EVO-IO-05): this is a delegation to the seam's own
831
- * `isCommittedWarning` — the marker predicate has exactly one definition. */
832
- //#endregion
833
- //#region lib/types/document-body.js
834
- /**
835
- * What the panel shows when it renders one version as a document.
836
- *
837
- * Two decisions, both made here so the preview and the rendered diff cannot drift apart:
838
- *
839
- * - FRONTMATTER IS NOT DOCUMENT TEXT. A SKILL.md opens with a YAML block; the renderer read its
840
- * closing `---` as a setext underline, so the metadata line became the document's biggest heading
841
- * and the real title sat below it (measured on the installed panel 2026-09-28). The block is
842
- * stripped for DISPLAY only: the raw view and the body route still carry every byte, and the
843
- * panel already shows the name and description on the row and in the left column.
844
- * - STRIPPING FAILS OPEN. Only a block that the family's own reader accepts is removed. A document
845
- * whose text merely starts with a thematic break, a block with no closing line, or a frontmatter
846
- * whose body is empty is returned UNCHANGED — showing a document's first line is always better
847
- * than showing nothing.
848
- *
849
- * `readingStats` exists for the other half of the reader's honesty: a preview that stops early has
850
- * to be able to say HOW much it is not showing.
851
- * @module @lmzhen/dsh-evolution-core/document-body
852
- */
853
- /**
854
- * The document a reader sees: the body without its leading frontmatter block.
855
- * @param content - the stored bytes of one version.
856
- * @returns the text to render; unchanged when there is no frontmatter the reader accepts.
857
- */
858
- function displayBodyOf(content) {
859
- const block = frontmatterBlock(content);
860
- if (block === null) return content;
861
- if (parseFrontmatter(content) === null) return content;
862
- return block.lines.slice(block.end + 1).join("\n").replace(/^\s*\n/, "");
863
- }
864
- /**
865
- * How much of a version the panel is showing.
866
- * @param full - the whole stored text.
867
- * @param shown - the part the route handed over.
868
- * @returns the counts, so the panel can say what it is not showing.
869
- */
870
- function readingStats(full, shown) {
871
- return {
872
- totalChars: full.length,
873
- shownChars: shown.length,
874
- truncated: shown.length < full.length
875
- };
876
- }
877
- /**
878
- * The H2 sections of a body, in document order — the ONE scan (G3).
879
- *
880
- * Both the restructure candidate list and the store anchor validation call this function, so a
881
- * candidate can only name a heading that exists EXACTLY ONCE and has content: the two rejections a
882
- * hand-written anchor used to hit ("no such heading", "ambiguous anchor") stop being reachable.
883
- * H2 is the section boundary (a section spans to the next H2 or EOF), matching the store.
884
- * @param body - the markdown after the frontmatter block.
885
- * @returns one row per H2 heading, with `count` filled in a second pass.
886
- */
887
- function h2Sections(body) {
888
- const lines = body.split(String.fromCharCode(10));
889
- const rows = [];
890
- for (let i = 0; i < lines.length; i += 1) {
891
- const match = /^#{2}\s+(.+?)\s*$/.exec(lines[i] ?? "");
892
- if (match === null) continue;
893
- const title = (match[1] ?? "").trim();
894
- let end = lines.length;
895
- for (let j = i + 1; j < lines.length; j += 1) if (/^#{2}\s/.test(lines[j] ?? "")) {
896
- end = j;
897
- break;
898
- }
899
- rows.push({
900
- title,
901
- start: i,
902
- end,
903
- count: 0
904
- });
905
- }
906
- for (const row of rows) row.count = rows.filter((other) => other.title === row.title).length;
907
- return rows;
908
- }
909
- //#endregion
910
- //#region lib/types/section-selection.js
911
- const LF$1 = String.fromCharCode(10);
912
- /**
913
- * Select whole H2 sections or exact content sub-blocks from one body.
914
- *
915
- * The H2 scan is document-body's h2Sections, so restructure and extract share
916
- * one boundary rule. A start/end pair selects an inclusive, contiguous run of
917
- * exact lines inside that heading; it cannot select the heading itself, overlap
918
- * another request, or leave a selected range empty.
919
- * @param body - markdown after frontmatter.
920
- * @param requests - exact heading plus optional start/end line pairs.
921
- * @returns selected ranges in request order, or the first refusal.
922
- */
923
- function selectSections(body, requests) {
924
- const lines = body.split(LF$1);
925
- const sections = h2Sections(body);
926
- const selected = [];
927
- for (let requestIndex = 0; requestIndex < requests.length; requestIndex += 1) {
928
- const request = requests[requestIndex];
929
- if (request === void 0) continue;
930
- const wanted = request.heading.trim();
931
- const matching = sections.filter((section) => section.title === wanted);
932
- if (matching.length === 0) return {
933
- ok: false,
934
- code: "heading-missing",
935
- message: "no \"## " + wanted + "\" heading in the body"
936
- };
937
- if (matching.length > 1) return {
938
- ok: false,
939
- code: "heading-ambiguous",
940
- message: "heading \"## " + wanted + "\" appears " + matching.length + " times (ambiguous anchor)"
941
- };
942
- const section = matching[0];
943
- if (section === void 0) return {
944
- ok: false,
945
- code: "heading-missing",
946
- message: "no \"## " + wanted + "\" heading in the body"
947
- };
948
- if (selected.some((entry) => entry.start === section.start)) return {
949
- ok: false,
950
- code: "heading-duplicate",
951
- message: "heading \"## " + wanted + "\" is moved twice"
952
- };
953
- if (!(request.start !== void 0 || request.end !== void 0)) {
954
- if (section.end === section.start + 1) return {
955
- ok: false,
956
- code: "heading-empty",
957
- message: "heading \"## " + wanted + "\" has an empty section"
958
- };
959
- selected.push({
960
- heading: wanted,
961
- start: section.start,
962
- end: section.end,
963
- text: lines.slice(section.start, section.end).join(LF$1),
964
- requestIndex
965
- });
966
- continue;
967
- }
968
- if (request.start === void 0 || request.end === void 0) return {
969
- ok: false,
970
- code: "part-anchor-incomplete",
971
- message: "heading \"## " + wanted + "\" needs both start and end anchors"
972
- };
973
- const startMatches = [];
974
- const endMatches = [];
975
- for (let index = 0; index < lines.length; index += 1) {
976
- if (index <= section.start || index >= section.end) continue;
977
- if (lines[index] === request.start) startMatches.push(index);
978
- if (lines[index] === request.end) endMatches.push(index);
979
- }
980
- if (startMatches.length !== 1) return {
981
- ok: false,
982
- code: "part-anchor-not-found",
983
- message: "heading \"## " + wanted + "\" start anchor must match exactly one content line"
984
- };
985
- if (endMatches.length !== 1) return {
986
- ok: false,
987
- code: "part-anchor-not-found",
988
- message: "heading \"## " + wanted + "\" end anchor must match exactly one content line"
989
- };
990
- const start = startMatches[0];
991
- const end = endMatches[0];
992
- if (start === void 0 || end === void 0 || start > end) return {
993
- ok: false,
994
- code: "part-anchor-order",
995
- message: "heading \"## " + wanted + "\" start anchor is after end anchor"
996
- };
997
- if (selected.some((entry) => start < entry.end && end + 1 > entry.start)) return {
998
- ok: false,
999
- code: "part-anchor-overlaps",
1000
- message: "heading \"## " + wanted + "\" selection overlaps another selected block"
1001
- };
1002
- selected.push({
1003
- heading: wanted,
1004
- start,
1005
- end: end + 1,
1006
- text: lines.slice(start, end + 1).join(LF$1),
1007
- requestIndex,
1008
- anchorStart: request.start,
1009
- anchorEnd: request.end
1010
- });
1011
- }
1012
- return {
1013
- ok: true,
1014
- sections: selected
1015
- };
1016
- }
1017
- //#endregion
1018
- //#region lib/types/extract-plan.js
1019
- const LF = String.fromCharCode(10);
1020
- function sha256(text) {
1021
- return createHash("sha256").update(text).digest("hex");
1022
- }
1023
- function unique(values) {
1024
- return [...new Set(values)];
1025
- }
1026
- function computeSupport(parts, residual, sourceName, sourceFiles, targetFiles, externalFiles) {
1027
- const selectedText = parts.map((part) => part.sourceText).join("\n\n");
1028
- const selectedRefs = unique(supportRefs(selectedText));
1029
- const residualRefs = new Set(supportRefs(residual));
1030
- const unresolved = selectedRefs.filter((ref) => !sourceFiles.includes(ref));
1031
- if (unresolved.length > 0) return { error: "support-unresolved: " + unresolved.join(", ") };
1032
- const candidates = selectedRefs.filter((ref) => sourceFiles.includes(ref));
1033
- const moves = planRehoming(candidates, targetFiles, sourceName).moves;
1034
- const byFrom = new Map(moves.map((move) => [move.from, move.to]));
1035
- const exclusive = [];
1036
- const shared = [];
1037
- for (const from of candidates) {
1038
- const to = byFrom.get(from);
1039
- if (to === void 0) continue;
1040
- if (residualRefs.has(from)) shared.push({
1041
- from,
1042
- to,
1043
- provenance: sourceName + ":" + from
1044
- });
1045
- else exclusive.push({
1046
- from,
1047
- to
1048
- });
1049
- }
1050
- const targetFilesWithMoves = unique([...targetFiles, ...moves.map((move) => move.to)]);
1051
- const external = unique(externalRefs(selectedText));
1052
- const suppliedRefs = new Set(externalFiles.map((file) => file.ref));
1053
- const missingExternal = external.filter((ref) => !suppliedRefs.has(ref));
1054
- const warnings = [];
1055
- if (missingExternal.length > 0) warnings.push("external-support-not-copied: " + missingExternal.join(", "));
1056
- const externalClosure = [];
1057
- for (const file of externalFiles) {
1058
- if (!external.includes(file.ref)) return { error: "external-ref-not-selected: " + file.ref };
1059
- if (file.targetPath.startsWith("/") || file.targetPath.includes("..") || !/^(?:references|templates|scripts|assets)\//.test(file.targetPath)) return { error: "external-target-unsafe: " + file.targetPath };
1060
- if (targetFilesWithMoves.includes(file.targetPath)) return { error: "external-collision: " + file.targetPath };
1061
- externalClosure.push({
1062
- from: file.ref,
1063
- to: file.targetPath,
1064
- provenance: file.provenance,
1065
- originalPath: file.originalPath,
1066
- content: file.content,
1067
- sha256: file.sha256
1068
- });
1069
- }
1070
- const rewritten = /* @__PURE__ */ new Map();
1071
- for (const part of parts) {
1072
- const partRefs = supportRefs(part.sourceText);
1073
- const rewrite = planReferenceRewrite({
1074
- content: part.sourceText,
1075
- files: sourceFiles,
1076
- moves: moves.filter((move) => partRefs.includes(move.from)),
1077
- targetFiles: targetFilesWithMoves
1078
- });
1079
- rewritten.set(part.heading, applyReferenceRewrite(part.sourceText, rewrite.edits));
1080
- warnings.push(...rewrite.unresolved.map((ref) => "support-unresolved: " + ref));
1081
- warnings.push(...rewrite.residualDangling.map((ref) => "support-dangling: " + ref));
1082
- }
1083
- for (const part of parts) {
1084
- let text = rewritten.get(part.heading) ?? part.sourceText;
1085
- for (const file of externalClosure) text = text.split(file.from).join(file.to);
1086
- part.movedText = text;
1087
- }
1088
- const exclusiveSet = new Set(exclusive.map((entry) => entry.from));
1089
- const parentExclusive = supportRefs(residual).filter((ref) => exclusiveSet.has(ref));
1090
- if (parentExclusive.length > 0) return { error: "support-exclusive-referenced-by-parent: " + parentExclusive.join(", ") };
1091
- const dangling = unique(warnings.filter((item) => item.startsWith("support-dangling: ")).map((item) => item.slice(18)));
1092
- return {
1093
- support: {
1094
- exclusive,
1095
- shared,
1096
- external: externalClosure,
1097
- unresolved: warnings.filter((item) => item.startsWith("support-unresolved: ")),
1098
- dangling
1099
- },
1100
- warnings
1101
- };
1102
- }
1103
- /**
1104
- * Build a pure extract plan. No IO, no writes: selection, residual, support
1105
- * closure and the moved text are computed from the supplied bodies/file lists.
1106
- * @param input - source body, target identity, owner decision and support lists.
1107
- * @returns a plan, or a refusal with a stable code.
1108
- */
1109
- function planExtract(input) {
1110
- if (input.outcome === "owner-gap") {
1111
- if (input.owner.mode !== "owner-gap") return {
1112
- ok: false,
1113
- code: "owner-gap-mismatch",
1114
- message: "outcome owner-gap requires an owner-gap decision"
1115
- };
1116
- if (input.owner.neededOwner === void 0 || input.owner.neededOwner.trim() === "") return {
1117
- ok: false,
1118
- code: "owner-gap-needed-owner",
1119
- message: "owner-gap requires neededOwner"
1120
- };
1121
- } else {
1122
- if (input.owner.mode !== "covered" || !input.owner.triggerCovers || !input.owner.outcomeCovers) return {
1123
- ok: false,
1124
- code: "owner-not-covered",
1125
- message: "extract/mixed requires a covering owner"
1126
- };
1127
- if (!input.targetExists) return {
1128
- ok: false,
1129
- code: "target-missing",
1130
- message: "covered owner target does not exist"
1131
- };
1132
- }
1133
- const selection = selectSections(input.body, input.requests);
1134
- if (!selection.ok) return {
1135
- ok: false,
1136
- code: selection.code,
1137
- message: selection.message
1138
- };
1139
- if (selection.sections.length === 0) return {
1140
- ok: false,
1141
- code: "part-empty",
1142
- message: "at least one part is required"
1143
- };
1144
- const externalRewrites = new Map((input.external ?? []).map((file) => [file.ref, file.targetPath]));
1145
- const parts = selection.sections.map((section) => {
1146
- let movedText = section.text;
1147
- for (const [from, to] of externalRewrites) movedText = movedText.split(from).join(to);
1148
- return {
1149
- heading: section.heading,
1150
- anchor: {
1151
- heading: section.heading,
1152
- ...section.anchorStart === void 0 ? {} : { start: section.anchorStart },
1153
- ...section.anchorEnd === void 0 ? {} : { end: section.anchorEnd }
1154
- },
1155
- sourceText: section.text,
1156
- movedText,
1157
- bytes: Buffer.byteLength(movedText, "utf8"),
1158
- sha256: sha256(movedText)
1159
- };
1160
- });
1161
- 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.";
1162
- const ordered = [...selection.sections].sort((a, b) => a.start - b.start);
1163
- const first = ordered[0];
1164
- if (first === void 0) return {
1165
- ok: false,
1166
- code: "part-empty",
1167
- message: "at least one part is required"
1168
- };
1169
- const byStart = new Map(ordered.map((section) => [section.start, section]));
1170
- const lines = input.body.split(LF);
1171
- const rebuilt = [];
1172
- for (let index = 0; index < lines.length; index += 1) {
1173
- const section = byStart.get(index);
1174
- if (section !== void 0) {
1175
- if (index === first.start) rebuilt.push(pointer);
1176
- index = section.end - 1;
1177
- } else rebuilt.push(lines[index] ?? "");
1178
- }
1179
- const residual = rebuilt.join(LF);
1180
- if (residual.trim().length === 0) return {
1181
- ok: false,
1182
- code: "parent-empty",
1183
- message: "parent residual is empty"
1184
- };
1185
- if (residual.split(LF).filter((line) => line.trim() !== "" && line !== pointer && !line.trimStart().startsWith("#")).length === 0) return {
1186
- ok: false,
1187
- code: "parent-hollow-heading",
1188
- message: "parent residual has no substantive content"
1189
- };
1190
- if (input.outcome === "owner-gap") return {
1191
- ok: true,
1192
- plan: {
1193
- source: input.sourceName,
1194
- target: {
1195
- name: input.targetName,
1196
- exists: input.targetExists
1197
- },
1198
- outcome: input.outcome,
1199
- parts,
1200
- residual,
1201
- pointer,
1202
- owner: input.owner,
1203
- support: {
1204
- exclusive: [],
1205
- shared: [],
1206
- external: [],
1207
- unresolved: [],
1208
- dangling: []
1209
- },
1210
- warnings: [],
1211
- ...input.anchors === void 0 ? {} : { anchors: input.anchors }
1212
- }
1213
- };
1214
- const supportResult = computeSupport(parts, residual, input.sourceName, input.sourceFiles, input.targetFiles, input.external ?? []);
1215
- if ("error" in supportResult) return {
1216
- ok: false,
1217
- code: supportResult.error.split(":")[0] ?? "support-invalid",
1218
- message: supportResult.error
1219
- };
1220
- if (supportResult.support.dangling.length > 0) return {
1221
- ok: false,
1222
- code: "support-dangling",
1223
- message: "support-dangling: " + supportResult.support.dangling.join(", ")
1224
- };
1225
- return {
1226
- ok: true,
1227
- plan: {
1228
- source: input.sourceName,
1229
- target: {
1230
- name: input.targetName,
1231
- exists: input.targetExists
1232
- },
1233
- outcome: input.outcome,
1234
- parts,
1235
- residual,
1236
- pointer,
1237
- owner: input.owner,
1238
- support: supportResult.support,
1239
- warnings: unique(supportResult.warnings),
1240
- ...input.anchors === void 0 ? {} : { anchors: input.anchors }
1241
- }
1242
- };
1243
- }
1244
- /**
1245
- * Project one plan onto the current source/target SKILL.md bytes.
1246
- *
1247
- * This is the one place that composes frontmatter + residual + target additions;
1248
- * preview and the write adapter both call it so they cannot advertise different
1249
- * bytes. Pure: no IO.
1250
- * @param plan - plan from planExtract.
1251
- * @param sourceMd - current source SKILL.md.
1252
- * @param targetMd - current target SKILL.md.
1253
- * @returns both next documents, or the refusal that makes projection impossible.
1254
- */
1255
- function projectExtractBodies(plan, sourceMd, targetMd) {
1256
- const sourceBlock = frontmatterBlock(sourceMd);
1257
- const targetBlock = frontmatterBlock(targetMd);
1258
- if (!sourceBlock) return {
1259
- ok: false,
1260
- message: "source 没有有效 frontmatter"
1261
- };
1262
- if (!targetBlock) return {
1263
- ok: false,
1264
- message: "target 没有有效 frontmatter"
1265
- };
1266
- const sourceHeader = sourceBlock.lines.slice(0, sourceBlock.end + 1).join(LF);
1267
- const targetNormalized = targetMd.replace(/\r\n/g, LF);
1268
- const targetLines = targetNormalized.split(LF);
1269
- for (const part of plan.parts) if (targetLines.some((line) => line.trim() === "## " + part.heading)) return {
1270
- ok: false,
1271
- message: "target 已有同名 heading「" + part.heading + "」。"
1272
- };
1273
- const additions = plan.parts.map((part) => part.movedText).join("\n\n");
1274
- const targetRaw = targetNormalized.trimEnd() + "\n\n" + additions + LF;
1275
- const targetAfter = targetBlock.nl === "\r\n" ? targetRaw.replace(/\n/g, "\r\n") : targetRaw;
1276
- const sourceRaw = (sourceHeader + plan.residual).replace(/\r\n/g, LF);
1277
- return {
1278
- ok: true,
1279
- projection: {
1280
- sourceAfter: sourceBlock.nl === "\r\n" ? sourceRaw.replace(/\n/g, "\r\n") : sourceRaw,
1281
- targetAfter
1282
- }
1283
- };
1284
- }
1285
- //#endregion
1286
- //#region lib/types/usage.js
1287
- /**
1288
- * Skill usage telemetry sidecar: `$DSH_HOME/skills/.usage.json`.
1289
- * Format-compatible with Hermes Agent / hermes-claw core fields.
1290
- */
1291
- function usageFile(root) {
1292
- return join(root, ".usage.json");
1293
- }
1294
- function emptyRecord() {
1295
- return {
1296
- created_by: null,
1297
- use_count: 0,
1298
- view_count: 0,
1299
- patch_count: 0,
1300
- last_used_at: null,
1301
- last_viewed_at: null,
1302
- last_patched_at: null,
1303
- created_at: (/* @__PURE__ */ new Date()).toISOString(),
1304
- state: "active",
1305
- pinned: false,
1306
- archived_at: null
1307
- };
1308
- }
1309
- /** A timestamp passes only when `Date.parse` yields a finite epoch (N-3): a bare
1310
- * string check let garbage like "not-a-date" propagate as Invalid Date → NaN
1311
- * into quality math and lifecycle comparisons. */
1312
- const validTimestamp = (value) => typeof value === "string" && Number.isFinite(Date.parse(value));
1313
- const nullableTimestamp = (value) => value === null || validTimestamp(value);
1314
- /**
1315
- * Field-level normalization for one sidecar record (rc.42 audit P2-3): the
1316
- * spread used to copy any junk through verbatim, so a corrupted file could
1317
- * carry `use_count: "3"` into the quality math and lifecycle comparisons as
1318
- * NaN. Every field falls back to its `emptyRecord()` baseline unless it has
1319
- * exactly the declared type; an invalid `created_at` anchors the age clock at
1320
- * now (first-sight defer semantics for a record whose age is unknowable).
1321
- * Timestamps additionally require a parseable date (N-3): `"not-a-date"`
1322
- * would otherwise survive the type check as Invalid Date.
1323
- * Pure — exported for unit tests; `loadUsage` is the production caller.
1324
- */
1325
- function normalizeUsageRecord(record) {
1326
- const base = emptyRecord();
1327
- if (!record || typeof record !== "object" || Array.isArray(record)) return base;
1328
- const raw = record;
1329
- const num = (value, fallback) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : fallback;
1330
- const bool = (value, fallback) => typeof value === "boolean" ? value : fallback;
1331
- return {
1332
- ...raw,
1333
- created_by: typeof raw.created_by === "string" ? raw.created_by : null,
1334
- use_count: num(raw.use_count, base.use_count),
1335
- view_count: num(raw.view_count, base.view_count),
1336
- patch_count: num(raw.patch_count, base.patch_count),
1337
- last_used_at: nullableTimestamp(raw.last_used_at) ? raw.last_used_at : base.last_used_at,
1338
- last_viewed_at: nullableTimestamp(raw.last_viewed_at) ? raw.last_viewed_at : base.last_viewed_at,
1339
- last_patched_at: nullableTimestamp(raw.last_patched_at) ? raw.last_patched_at : base.last_patched_at,
1340
- created_at: validTimestamp(raw.created_at) ? raw.created_at : base.created_at,
1341
- state: raw.state === "stale" || raw.state === "archived" ? raw.state : "active",
1342
- pinned: bool(raw.pinned, base.pinned),
1343
- archived_at: nullableTimestamp(raw.archived_at) ? raw.archived_at : base.archived_at,
1344
- quality_score: typeof raw.quality_score === "number" && Number.isFinite(raw.quality_score) ? raw.quality_score : void 0,
1345
- quality_warn: typeof raw.quality_warn === "boolean" ? raw.quality_warn : void 0,
1346
- feedback_score: typeof raw.feedback_score === "number" && Number.isFinite(raw.feedback_score) ? raw.feedback_score : void 0,
1347
- feedback_warn: typeof raw.feedback_warn === "boolean" ? raw.feedback_warn : void 0,
1348
- support_reads: normalizeSupportReads(raw.support_reads)
1349
- };
1350
- }
1351
- /** Sidecar bound: a pathological path set must not grow the usage file forever. */
1352
- const MAX_SUPPORT_READ_PATHS = 200;
1353
- /** Sanitize the per-support-file read counts: non-negative finite numbers under
1354
- * non-empty, bounded, non-traversal path keys. An unusable value drops the whole
1355
- * map (absence over a poisoned count). */
1356
- function normalizeSupportReads(value) {
1357
- if (value === null || typeof value !== "object" || Array.isArray(value)) return void 0;
1358
- const out = {};
1359
- let kept = 0;
1360
- for (const [key, count] of Object.entries(value)) {
1361
- if (kept >= 200) break;
1362
- if (key === "" || key.length > 200 || key.split("/").includes("..")) continue;
1363
- if (typeof count !== "number" || !Number.isFinite(count) || count < 0) continue;
1364
- out[key] = count;
1365
- kept += 1;
1366
- }
1367
- return kept === 0 ? void 0 : out;
1368
- }
1369
- /** Parse a raw usage sidecar; malformed content reads as empty (best-effort telemetry). */
1370
- function parseUsage(raw) {
1371
- const map = /* @__PURE__ */ new Map();
1372
- if (raw === null) return map;
1373
- try {
1374
- const parsed = JSON.parse(raw);
1375
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return map;
1376
- for (const [name, record] of Object.entries(parsed)) map.set(name, normalizeUsageRecord(record));
1377
- } catch {}
1378
- return map;
1379
- }
1380
- async function loadUsage(root, io = nodeEvolutionIo()) {
1381
- return parseUsage(await io.readText(usageFile(root)));
1382
- }
1383
- async function mutateUsage(root, io, task, options = {}) {
1384
- const run = async () => {
1385
- await transactIo(io, usageFile(root), async (current) => {
1386
- let shapePreserved = false;
1387
- let recovered = null;
1388
- const quarantineCopy = async () => {
1389
- const corruptPath = `${usageFile(root)}.corrupt`;
1390
- return io.writeText(corruptPath, current).then(() => true, () => false);
1391
- };
1392
- if (current !== null) {
1393
- let parsed = null;
1394
- try {
1395
- const probe = JSON.parse(current);
1396
- if (isRecord(probe)) parsed = probe;
1397
- } catch {
1398
- parsed = null;
1399
- }
1400
- if (parsed === null) {
1401
- if (!await quarantineCopy()) {
1402
- 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)`);
1403
- return current;
1404
- }
1405
- 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`);
1406
- } else {
1407
- const record = parsed;
1408
- const isMalformed = (value) => value === null || typeof value !== "object" || Array.isArray(value);
1409
- if (typeof record.version === "number" && record.version > 1) {
1410
- 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`;
1411
- if (options.onQuarantine !== void 0) options.onQuarantine(message);
1412
- else console.warn(message);
1413
- shapePreserved = true;
1414
- } else if (Object.values(record).some(isMalformed)) {
1415
- const bad = Object.keys(record).filter((key) => isMalformed(record[key]));
1416
- if (!await quarantineCopy()) {
1417
- 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`);
1418
- return current;
1419
- }
1420
- recovered = JSON.stringify(Object.fromEntries(Object.entries(record).filter(([, value]) => !isMalformed(value))));
1421
- 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`);
1422
- }
1423
- }
1424
- }
1425
- if (shapePreserved) return current;
1426
- const map = parseUsage(recovered ?? current);
1427
- await task(map);
1428
- return JSON.stringify(Object.fromEntries(map.entries()), null, 2);
1429
- });
1430
- };
1431
- if (options.fence !== void 0) await options.fence.run(run);
1432
- else await run();
1433
- }
1434
- /** Curator-owned usage fields (rc.67 K-2): the curator writes ONLY this set —
1435
- * lifecycle state, archive stamp, the six-factor quality pair, and the
1436
- * marker-mirrored pin flag; counters and activity stamps belong to the
1437
- * tool-telemetry side and are never copied by a fold. P2-12 (v39): the
1438
- * combined `applyCuratorFields` wrapper had no production caller (folds go
1439
- * through {@link foldCuratorFields}), so the two field copies below are the
1440
- * whole contract. */
1441
- /** Copy only the lifecycle pair (state/archived_at) — see the ownership split
1442
- * rationale above. */
1443
- function applyCuratorLifecycleFields(disk, curated) {
1444
- disk.state = curated.state;
1445
- disk.archived_at = curated.archived_at;
1446
- }
1447
- /**
1448
- * Copy the recomputed meta pair (quality_score/quality_warn + the
1449
- * marker-mirrored pin flag) — refreshed tree-wide each run by design, so a
1450
- * concurrent curator run's lifecycle changes are never reverted by them.
1451
- * P1-1 (v15): the feedback pair (`feedback_score`/`feedback_warn`) is
1452
- * deliberately NOT copied — it is feedback-owned (see the field-ownership
1453
- * contract on {@link UsageRecord}) and must survive curator runs untouched.
1454
- */
1455
- function applyCuratorMetaFields(disk, curated) {
1456
- disk.quality_score = curated.quality_score;
1457
- disk.quality_warn = curated.quality_warn;
1458
- disk.pinned = curated.pinned;
1459
- }
1460
- /**
1461
- * Fold a curator run-start snapshot onto the current on-disk map (rc.67 K-2):
1462
- * each curated record is projected onto its disk peer by copying only the
1463
- * curator-owned fields, so a concurrent tool-side bump between snapshot and
1464
- * save survives. Records absent from the snapshot are left untouched; a
1465
- * curated record with no disk peer is seeded from the snapshot. `stateOwned`
1466
- * (rc.72 H-1) restricts the lifecycle pair to the names this run ACTUALLY
1467
- * transitioned — a concurrent curator run's archive/restore is never reverted
1468
- * by a stale snapshot; without it both pairs apply everywhere.
1469
- */
1470
- function foldCuratorFields(disk, curated, stateOwned, runStartStates) {
1471
- const skipped = [];
1472
- for (const [name, record] of curated) {
1473
- const diskRecord = disk.get(name);
1474
- if (!diskRecord) {
1475
- disk.set(name, { ...record });
1476
- continue;
1477
- }
1478
- applyCuratorMetaFields(diskRecord, record);
1479
- if (stateOwned === void 0 || stateOwned.has(name)) {
1480
- const expected = runStartStates?.get(name);
1481
- if (expected !== void 0 && diskRecord.state !== expected) {
1482
- skipped.push(name);
1483
- continue;
1484
- }
1485
- applyCuratorLifecycleFields(diskRecord, record);
1486
- }
1487
- }
1488
- return skipped;
1489
- }
1490
- /** Whole-file usage write (V6-37, 0.3.37): this is the ONE path that bypasses
1491
- * the malformed-defense and the transact lock — prefer `mutateUsage` for any
1492
- * read-modify-write so a concurrent writer cannot lose its update and a
1493
- * malformed sidecar stays recoverable. Kept for fixture/test seeding.
1494
- * @internal P3-16 (v14): no production caller (verified by grep); exported for
1495
- * the family's tests only. Do not use it to write the sidecar in new code. */
1496
- async function saveUsage(root, map, io = nodeEvolutionIo()) {
1497
- const obj = Object.fromEntries(map.entries());
1498
- await io.writeText(usageFile(root), JSON.stringify(obj, null, 2));
1499
- }
1500
- function getRecord(map, name) {
1501
- let record = map.get(name);
1502
- if (!record) {
1503
- record = emptyRecord();
1504
- map.set(name, record);
1505
- }
1506
- return record;
1507
- }
1508
- function bumpView(map, name, when = /* @__PURE__ */ new Date()) {
1509
- const record = getRecord(map, name);
1510
- record.view_count += 1;
1511
- record.last_viewed_at = when.toISOString();
1512
- }
1513
- function bumpUse(map, name, when = /* @__PURE__ */ new Date()) {
1514
- const record = getRecord(map, name);
1515
- record.use_count += 1;
1516
- record.last_used_at = when.toISOString();
1517
- }
1518
- function bumpPatch(map, name, when = /* @__PURE__ */ new Date()) {
1519
- const record = getRecord(map, name);
1520
- record.patch_count += 1;
1521
- record.last_patched_at = when.toISOString();
1522
- }
1523
- /** Count one observed support-file read (design §5.5). The map is created on
1524
- * first evidence only — a skill with no support reads keeps the field absent. */
1525
- function bumpSupportRead(map, name, rel, when = /* @__PURE__ */ new Date()) {
1526
- const record = getRecord(map, name);
1527
- const counts = record.support_reads ?? {};
1528
- counts[rel] = (counts[rel] ?? 0) + 1;
1529
- record.support_reads = counts;
1530
- record.last_viewed_at = when.toISOString();
1531
- }
1532
- function markAgentCreated(map, name) {
1533
- getRecord(map, name).created_by = "agent";
1534
- }
1535
- function latestActivityAt(record) {
1536
- const values = [
1537
- record.last_used_at,
1538
- record.last_viewed_at,
1539
- record.last_patched_at
1540
- ].filter((value) => typeof value === "string" && Number.isFinite(Date.parse(value)));
1541
- if (values.length === 0) return null;
1542
- return values.reduce((latest, value) => Date.parse(value) > Date.parse(latest) ? value : latest);
1543
- }
1544
- /** Days between an ISO timestamp (falling back to `created`) and `now`. An
1545
- * unparseable date counts as 0 days: NaN silently froze every age comparison
1546
- * (A2-9). */
1547
- function daysSinceIso(iso, created, nowMs) {
1548
- const t = Date.parse(iso ?? created);
1549
- if (!Number.isFinite(t)) return 0;
1550
- return (nowMs - t) / 864e5;
1551
- }
1552
- /** Idle days of one skill since its lifecycle age anchor (`last activity ??
1553
- * created_at`) — the SAME anchor the curator's transitions use, so the
1554
- * maintenance view and the lifecycle can never disagree about staleness. */
1555
- function idleDays(record, now = /* @__PURE__ */ new Date()) {
1556
- return daysSinceIso(latestActivityAt(record), record.created_at, now.getTime());
1557
- }
1558
- /**
1559
- * Whether the library has ANY observed read evidence (C observation window):
1560
- * reads were invisible to the usage sidecar before A2, so `view_count` zero
1561
- * means "never read" ONLY after the first observed read exists anywhere in
1562
- * the map. Before that, churn-based signals (write-ghost) are untrustworthy
1563
- * and callers must suppress them. Pure and derived — never persisted.
1564
- */
1565
- function usageObserved(usage) {
1566
- for (const record of usage.values()) if (record.view_count > 0) return true;
1567
- return false;
1568
- }
1569
- /**
1570
- * Curator suppression sidecar: built-in skills the curator has archived stay
1571
- * suppressed across re-seeds, so the lifecycle never fights a re-created
1572
- * bundled skill. Best-effort load/save, mirroring the usage sidecar posture.
1573
- * Versioned shape ({ version, names }) with legacy plain-array compat.
1574
- */
1575
- const SUPPRESSED_FILE_VERSION = 1;
1576
- function suppressedFile(root) {
1577
- return join(root, ".curator-suppressed.json");
1578
- }
1579
- async function loadSuppressedNames(root, io = nodeEvolutionIo()) {
1580
- return parseSuppressed(await io.readText(suppressedFile(root)));
1581
- }
1582
- function parseSuppressed(raw) {
1583
- if (raw === null) return /* @__PURE__ */ new Set();
1584
- try {
1585
- const parsed = JSON.parse(raw);
1586
- const names = Array.isArray(parsed) ? parsed : typeof parsed === "object" && parsed !== null && Array.isArray(parsed.names) ? parsed.names : [];
1587
- return new Set(names.filter((entry) => typeof entry === "string"));
1588
- } catch {
1589
- return /* @__PURE__ */ new Set();
1590
- }
1591
- }
1592
- /**
1593
- * Plain wholesale write of the suppression sidecar (tests and fixture seeding).
1594
- * @internal S2.4 (PLAN 2026-09-16, audit P2-31): NO production consumer
1595
- * (verified by grep; production suppressions go through
1596
- * {@link updateSuppressedNames}) — exported for the family's tests only. Do
1597
- * not use it to write the sidecar in new code.
1598
- *
1599
- * The write rides the {@link transactIo} channel (the same lock the RMW
1600
- * writer uses), not the former naked read → `io.writeText`: that form was an
1601
- * unserialized read-modify-write — the last `saveSuppressedNames` in this file
1602
- * with no lock, while its sibling `saveUsage` already carried the `@internal`
1603
- * test-only note. Version discipline is unchanged (V24-09 / S2-14): a read
1604
- * failure surfaces (an unreadable sidecar is never written over), a newer
1605
- * on-disk schema is warned about and preserved byte-for-byte (the
1606
- * byte-identical result short-circuits the write), and a malformed sidecar is
1607
- * still overwritten with the v1 shape (the historical plain-writer posture).
1608
- */
1609
- async function saveSuppressedNames(root, names, io = nodeEvolutionIo()) {
1610
- await transactIo(io, suppressedFile(root), (current) => {
1611
- if (current !== null) try {
1612
- const parsed = JSON.parse(current);
1613
- if (parsed !== null && typeof parsed.version === "number" && parsed.version > 1) {
1614
- console.warn(`suppression sidecar ${suppressedFile(root)} declares version ${String(parsed.version)} (newer than 1); not overwritten`);
1615
- return current;
1616
- }
1617
- } catch {}
1618
- return JSON.stringify({
1619
- version: 1,
1620
- names: [...names].sort()
1621
- }, null, 2);
1622
- });
1623
- }
1624
- /**
1625
- * Atomic read-modify-write on the suppression sidecar (rc.50 P2-2): `task`
1626
- * receives the set parsed from the current on-disk state and may mutate it;
1627
- * the result is persisted inside the same transact so a second process
1628
- * sharing DSH_HOME cannot interleave its RMW. Best-effort posture unchanged.
1629
- */
1630
- async function updateSuppressedNames(root, io, task) {
1631
- await transactIo(io, suppressedFile(root), async (current) => {
1632
- if (current !== null) {
1633
- let parsed = null;
1634
- try {
1635
- parsed = JSON.parse(current);
1636
- } catch {
1637
- return current;
1638
- }
1639
- if (parsed !== null && typeof parsed.version === "number" && parsed.version > 1) {
1640
- console.warn(`suppression sidecar ${suppressedFile(root)} declares version ${String(parsed.version)} (newer than 1); not overwritten`);
1641
- return current;
1642
- }
1643
- }
1644
- const names = parseSuppressed(current);
1645
- await task(names);
1646
- return JSON.stringify({
1647
- version: 1,
1648
- names: [...names].sort()
1649
- }, null, 2);
1650
- });
1651
- }
1652
- //#endregion
1653
- //#region lib/types/cost.js
1654
- /**
1655
- * Context-cost accounting for skill bodies (design §5.2).
1656
- *
1657
- * A raw character count is a poor budget: the same 100k characters cost very
1658
- * different amounts of context in Chinese-heavy prose and in English. The
1659
- * weighted unit makes the two comparable, and the token range exists only to
1660
- * make the load cost visible next to the character count — it is an ESTIMATE,
1661
- * never a measurement.
1662
- *
1663
- * Accounting basis: the ON-DISK form (`skillMdOnDisk()`, the same view the
1664
- * write limit uses), so a body that is exactly at the limit cannot read as
1665
- * over-limit here and pass there (the v37 P2-1 deadlock class).
1666
- */
1667
- /** Token weight of one CJK / kana / full-width code unit on the LIMIT basis —
1668
- * upstream's model-independent conversion is 2.75 chars/token for prose, and CJK
1669
- * prose is ~1 token per character (the conservative end of the 0.6–1.0 range the
1670
- * estimate side reports). Thresholds are compared on THIS basis so a borrowed
1671
- * character line keeps its meaning; the estimate range below reports the spread. */
1672
- const TOKEN_CJK_WEIGHT = 1;
1673
- /** Token weight of one non-CJK code unit on the LIMIT basis (1 / 2.75 ≈ 0.364). */
1674
- const TOKEN_ASCII_WEIGHT = 1 / UPSTREAM_LIMIT_CHARS_PER_TOKEN;
1675
- /** Token-per-unit bounds of the estimate range (CJK: 0.6–1.0, non-CJK: 1/4–1/3).
1676
- * The range is the 4-chars/token estimate family, so on ASCII-heavy bodies the
1677
- * LIMIT-basis `tokens` point can sit above `tokensHigh` (1/2.75 > 1/3): the two
1678
- * answer different questions and are never nested by construction. */
1679
- const COST_CJK_TOKEN_LOW = .6;
1680
- const COST_CJK_TOKEN_HIGH = 1;
1681
- const COST_ASCII_TOKEN_LOW = .25;
1682
- const COST_ASCII_TOKEN_HIGH = 1 / 3;
1683
- /** The token line a borrowed CHARACTER threshold draws for ONE body: 20k characters
1684
- * of THIS composition, expressed in the same tokens `bodyCost` counts. Comparing
1685
- * `tokens` against this line is deliberately equivalent to "chars >= line" — that
1686
- * equivalence is what keeps a borrowed line's textual effect identical — while the
1687
- * judgment itself, and every number reported, stays on the token scale.
1688
- * @param lineChars - the borrowed character line (whole-body characters).
1689
- * @param cost - the body's own cost breakdown.
1690
- * @returns the equivalent token line (0 when the body is empty). */
1691
- function tokenLineFor(lineChars, cost) {
1692
- if (cost.chars === 0) return 0;
1693
- return Math.round(lineChars * cost.tokens / cost.chars);
1694
- }
1695
- /** CJK ideographs, kana, full-width forms and CJK punctuation. */
1696
- const CJK_RE = /[\u3000-\u303f\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff00-\uffef]/g;
1697
- /**
1698
- * Cost of one skill body.
1699
- * @param content - the body text as written (trailing whitespace is normalized
1700
- * away by the on-disk accounting, so callers need not pre-trim).
1701
- * @returns the cost breakdown; an empty body answers all-zero.
1702
- */
1703
- function bodyCost(content) {
1704
- const onDisk = skillMdOnDisk(content);
1705
- const cjk = [...onDisk.matchAll(CJK_RE)].length;
1706
- const chars = onDisk.length;
1707
- const ascii = chars - cjk;
1708
- return {
1709
- chars,
1710
- cjk,
1711
- ascii,
1712
- tokens: Math.round(cjk * 1 + ascii * TOKEN_ASCII_WEIGHT),
1713
- tokensLow: Math.round(cjk * COST_CJK_TOKEN_LOW + ascii * COST_ASCII_TOKEN_LOW),
1714
- tokensHigh: Math.round(cjk * 1 + ascii * COST_ASCII_TOKEN_HIGH)
1715
- };
1716
- }
1717
- //#endregion
1718
- //#region lib/types/skill-lint.js
1719
- const msg = (parts) => parts.map((p) => typeof p === "string" ? p : String(p)).join("");
1720
- /** One rule yields AT MOST one finding (contract §3). `body-oversize-2x` is the only rule whose
1721
- * severity can escalate a verdict to needs-restructure. */
1722
- const RULES = [
1723
- {
1724
- id: "unreadable-skill",
1725
- severity: "error",
1726
- run: (facts) => facts.readable && facts.dims.bodyChars !== null ? null : {
1727
- severity: "error",
1728
- rule: "unreadable-skill",
1729
- message: msg([facts.skillName, ": SKILL.md could not be read — no health claim is possible"]),
1730
- count: 1
1731
- }
1732
- },
1733
- {
1734
- id: "body-oversize-2x",
1735
- severity: "error",
1736
- run: (facts) => facts.overTwiceSoftLine ? {
1737
- severity: "error",
1738
- rule: "body-oversize-2x",
1739
- message: msg([
1740
- facts.skillName,
1741
- ": body is at or past twice the soft line (",
1742
- facts.softLineChars,
1743
- " chars); keeping the current skill is valid"
1744
- ]),
1745
- count: 1
1746
- } : null
1747
- },
1748
- {
1749
- id: "body-oversize",
1750
- severity: "warn",
1751
- run: (facts) => !facts.overTwiceSoftLine && facts.overSoftLine ? {
1752
- severity: "warn",
1753
- rule: "body-oversize",
1754
- message: msg([
1755
- facts.skillName,
1756
- ": body is at or above the soft line (",
1757
- facts.softLineChars,
1758
- " chars); keep is valid — size alone does not require a split"
1759
- ]),
1760
- count: 1
1761
- } : null
1762
- },
1763
- {
1764
- id: "stamp-density",
1765
- severity: "warn",
1766
- run: (facts) => {
1767
- const density = facts.dims.stampDensityPerKb;
1768
- const hits = facts.dims.stampHits;
1769
- if (density === null || hits === null || density < facts.stampLimitPerKb) return null;
1770
- return {
1771
- severity: "warn",
1772
- rule: "stamp-density",
1773
- message: msg([
1774
- facts.skillName,
1775
- ": stamp density ",
1776
- density.toFixed(1),
1777
- "/KB (rc/sha/date lines — log-like content)"
1778
- ]),
1779
- count: hits
1780
- };
1781
- }
1782
- },
1783
- {
1784
- id: "body-without-support",
1785
- severity: "warn",
1786
- run: (facts) => facts.dims.supportGroups === 0 && facts.dims.bodyChars !== null && facts.dims.bodyChars >= facts.softLineChars / 2 ? {
1787
- severity: "warn",
1788
- rule: "body-without-support",
1789
- message: msg([
1790
- facts.skillName,
1791
- ": large body (",
1792
- facts.dims.bodyChars,
1793
- " chars) with NO support files"
1794
- ]),
1795
- count: 1
1796
- } : null
1797
- },
1798
- {
1799
- id: "references-sprawl",
1800
- severity: "warn",
1801
- run: (facts) => {
1802
- const files = facts.dims.supportFiles;
1803
- if (files === null || files < 60) return null;
1804
- return {
1805
- severity: "warn",
1806
- rule: "references-sprawl",
1807
- message: msg([
1808
- facts.skillName,
1809
- ": ",
1810
- files,
1811
- " support files"
1812
- ]),
1813
- count: files
1814
- };
1815
- }
1816
- },
1817
- {
1818
- id: "scope-overloaded",
1819
- severity: "warn",
1820
- run: (facts) => {
1821
- const hits = facts.dims.hardCapHits;
1822
- const files = facts.dims.supportFiles;
1823
- if (hits === null || files === null || hits < facts.hardCapMinHits || files < 3) return null;
1824
- return {
1825
- severity: "warn",
1826
- rule: "scope-overloaded",
1827
- message: msg([
1828
- facts.skillName,
1829
- ": ",
1830
- hits,
1831
- " hard-cap hit(s) with ",
1832
- files,
1833
- " support files — remaining growth may be scope"
1834
- ]),
1835
- count: hits
1836
- };
1837
- }
1838
- },
1839
- {
1840
- id: "write-ghost",
1841
- severity: "warn",
1842
- run: (facts) => {
1843
- const patches = facts.dims.churnPatches;
1844
- const reads = facts.dims.churnReads;
1845
- if (patches === null || reads === null || patches < facts.churnMinPatches || reads > 0) return null;
1846
- return {
1847
- severity: "warn",
1848
- rule: "write-ghost",
1849
- message: msg([
1850
- facts.skillName,
1851
- ": ",
1852
- patches,
1853
- " patch(es), never read"
1854
- ]),
1855
- count: patches
1856
- };
1857
- }
1858
- }
1859
- ];
1860
- function lintSkill(facts) {
1861
- const out = [];
1862
- for (const rule of RULES) {
1863
- const hit = rule.run(facts);
1864
- if (hit !== null) out.push(hit);
1865
- }
1866
- return out;
1867
- }
1868
- /** What a write introduced, what got worse, what got fixed. A rule whose count grew (one site to
1869
- * nine) counts as worsened — comparing by rule name alone reported nothing. */
1870
- function diffFindings(before, after) {
1871
- const beforeByRule = new Map(before.map((f) => [f.rule, f]));
1872
- const afterByRule = new Map(after.map((f) => [f.rule, f]));
1873
- return {
1874
- introduced: after.filter((f) => !beforeByRule.has(f.rule)),
1875
- worsened: after.filter((f) => {
1876
- const old = beforeByRule.get(f.rule);
1877
- return old !== void 0 && f.count > old.count;
1878
- }),
1879
- resolved: before.filter((f) => !afterByRule.has(f.rule)).map((f) => f.rule)
1880
- };
1881
- }
1882
- //#endregion
1883
- //#region lib/types/evolution-events.js
1884
- /**
1885
- * Self-evolution event log (rc.68): an append-only sidecar under
1886
- * `$DSH_HOME/evolution/events.json` that is the single source of truth for
1887
- * the self-improvement loop. Feedback increments and learn actions share one
1888
- * ordered timeline (`seq` is the ordering key), so "feedback before/after a
1889
- * learn on target X" is answerable. The aggregate `feedback.json` is a
1890
- * rebuildable boot cache, never the truth.
1891
- *
1892
- * Usage events (C semantics, rc.73+): `type:'usage'` records are the
1893
- * OBSERVATION WINDOW ANCHOR — written once, when the library's first observed
1894
- * read (`view_count` 0 -> 1) happens. The anchor is the durable timeline record
1895
- * of that moment: the churn-suppression gate itself (`usageObserved()`) reads
1896
- * the usage SIDECAR's own first-view evidence, since reads were invisible to it
1897
- * pre-A2 and no sidecar record can reach `view_count > 0` without the same
1898
- * 0 -> 1 transition. `counts` on the event is a cumulative library-wide
1899
- * snapshot (skills/views/use/patches) at that moment, and `window.opened` pins
1900
- * the window start for the timeline. (V27 G3.3: `verify-event-pairing` requires
1901
- * every persisted type to have a production reader or a declared external
1902
- * contract — this one is the latter.)
1903
- *
1904
- * Rotation (rc.71, 007 design): when the active log reaches
1905
- * `EVENT_LOG_ROTATE_AT` the older half is split into an archive
1906
- * (`events-<lastArchivedSeq>.json`); the boot timeline merges active +
1907
- * archives and dedupes by seq (active copy wins), so the rotation crash window
1908
- * yields the identical timeline. Archival naming is STRICTLY numeric
1909
- * (`/^events-\d+\.json$/`) — user files under the same directory are never
1910
- * read as archives and never pruned (rc.72 G-2).
1911
- */
1912
- const EVENT_LOG_VERSION = 1;
1913
- /** Active-log split point (rc.71): when the active log reaches this many events
1914
- * the older half is rotated into an archive; the active stays bounded so a
1915
- * single append stays O(active) instead of O(total-history). Tunable default —
1916
- * callers may override per append (the tests use small values). */
1917
- const EVENT_LOG_ROTATE_AT = 4e3;
1918
- /** Number of archives retained (rc.71): older archives are pruned at rotation,
1919
- * mirroring retainReports. The horizon covers the loop-analysis window. */
1920
- const EVENT_LOG_RETAIN_ARCHIVES = 10;
1921
- /** Archive file prefix: `events-<lastArchivedSeq>.json`. The active file is
1922
- * `events.json` and never matches this glob. */
1923
- const EVENT_ARCHIVE_PREFIX = "events-";
1924
- /** Archive naming is strictly numeric: a user file such as `events-backup.json`
1925
- * under the same directory is neither read into the timeline nor pruned. */
1926
- const EVENT_ARCHIVE_RE = /^events-(\d+)\.json$/;
1927
- function eventsFile(home) {
1928
- return join(home, "evolution", "events.json");
1929
- }
1930
- /** I-5 (v18): one lightweight description of the durable event payload
1931
- * contract. The log is a FILE boundary (a host, a script or an older version
1932
- * can write it), so `appendEvolutionEvent` refuses a record no consumer can
1933
- * fold instead of persisting it and failing silently later. The process event
1934
- * bus stays unvalidated — that is a typed same-process boundary.
1935
- * @param event - the candidate event record.
1936
- * @returns a human-readable issue, or null when the record is well-formed.
1937
- */
1938
- function evolutionEventPayloadIssue(event) {
1939
- const type = event.type;
1940
- if (typeof type !== "string") return `unknown event type "${String(type)}"`;
1941
- switch (type) {
1942
- case "feedback":
1943
- if (event.kind !== "skill" && event.kind !== "session") return "feedback event requires kind skill|session";
1944
- if (event.rating !== "positive" && event.rating !== "negative") return "feedback event requires rating positive|negative";
1945
- if (typeof event.target !== "string" || event.target.trim() === "") return "feedback event requires a non-empty target";
1946
- return null;
1947
- case "maintain": return typeof event.runId === "string" ? null : "maintain event requires runId";
1948
- case "learn":
1949
- case "usage": return null;
1950
- case "hard-cap":
1951
- if (typeof event.target !== "string" || event.target.trim() === "") return "hard-cap event requires a non-empty target";
1952
- if (typeof event.bodyChars !== "number" || !Number.isFinite(event.bodyChars)) return "hard-cap event requires a finite bodyChars";
1953
- return null;
1954
- default: return `unknown event type "${type}"`;
1955
- }
1956
- }
1957
- function isEventRecord(event) {
1958
- const seq = event?.seq;
1959
- return typeof event === "object" && event !== null && typeof seq === "number" && Number.isFinite(seq);
1960
- }
1961
- /**
1962
- * Parse an event log body. A missing file, a whitespace-only file (rc.69:
1963
- * rebuildable, NOT malformed) or a corrupt one reads as empty; corrupt content
1964
- * is still refused on append, never overwritten.
1965
- *
1966
- * This reader is **v1-only** (F-338): a body carrying a `version` other than
1967
- * `EVENT_LOG_VERSION` is a future-format log this reader cannot interpret, so
1968
- * it reads as an EMPTY timeline rather than being mis-parsed as v1. The read
1969
- * side never overwrites it on its own — `appendEvolutionEvent` rejects a
1970
- * version mismatch up front and preserves the original bytes, so a newer log
1971
- * is never silently downgraded here.
1972
- *
1973
- * Per-entry normalization (rc.70 F-1): entries without a numeric `seq` are
1974
- * skipped here and dropped at the next append — valid entries survive, the
1975
- * damaged record is the only loss (self-heal semantics, matching the usage
1976
- * sidecar's per-field normalization on read).
1977
- */
1978
- /**
1979
- * Post-parse v1 gate shared by parseEvolutionEvents and appendEvolutionEvent
1980
- * (C-06, v10 audit: the append used to JSON.parse the same body a second time
1981
- * through parseEvolutionEvents — double parse cost per append). A null parse
1982
- * (missing/whitespace/unparsable body) reads as an empty timeline.
1983
- */
1984
- function v1EventRecords(parsed) {
1985
- if (parsed === null) return [];
1986
- if (parsed.version !== void 0 && parsed.version !== 1) return [];
1987
- if (!Array.isArray(parsed.events)) return [];
1988
- return parsed.events.filter(isEventRecord);
1989
- }
1990
- function parseEvolutionEvents(raw) {
1991
- if (raw === null || raw.trim() === "") return [];
1992
- try {
1993
- return v1EventRecords(JSON.parse(raw));
1994
- } catch {
1995
- return [];
1996
- }
1997
- }
1998
- /**
1999
- * List the numeric archives under the log's directory, sorted ascending by
2000
- * their last-archived seq. Single glob predicate for the timeline, the
2001
- * retention pass and the feedback migration check (rc.72 H-3).
2002
- */
2003
- async function listEventArchives(io, path) {
2004
- const dir = dirname(path);
2005
- return (await io.list(dir)).filter((name) => EVENT_ARCHIVE_RE.test(name)).sort((a, b) => {
2006
- return Number.parseInt(a.slice(7, a.length - 5), 10) - Number.parseInt(b.slice(7, b.length - 5), 10);
2007
- });
2008
- }
2009
- /**
2010
- * Append one event under the write lock (rc.68): `seq` = current max + 1
2011
- * computed inside the transact, so two processes appending concurrently never
2012
- * collide. A malformed log is refused (bytes preserved) and the append fails.
2013
- * Returns the assigned seq.
2014
- *
2015
- * Rotation (rc.71, 007 design): when the active log reaches `rotateAt`, the
2016
- * older half is copied into an archive inside the SAME transact (the archive
2017
- * path has its own lock, so no recursion) and the active is replaced with the
2018
- * newer half + the new event. seqs stay globally monotonic; a crash between
2019
- * archive write and active write leaves both copies, which the timeline merge
2020
- * dedupes by seq. An archive-write failure aborts the append (active keeps the
2021
- * full old content — no loss) and the caller's best-effort handling applies.
2022
- *
2023
- * rc.72 G-1: when the ACTIVE is missing/whitespace but archives exist (a
2024
- * deleted active, or B-2 self-heal), seq derivation consults the archive names
2025
- * — the active restarts AFTER the highest archived seq, never at 1, so a new
2026
- * event can never shadow an archived one in the seq-deduped timeline.
2027
- */
2028
- async function appendEvolutionEvent(io, path, event, rotateAt = EVENT_LOG_ROTATE_AT, fence) {
2029
- const issue = evolutionEventPayloadIssue(event);
2030
- if (issue !== null) throw new Error(`evolution event refused: ${issue}`);
2031
- let assigned = 0;
2032
- let refuseMessage = "";
2033
- let parsedBody = null;
2034
- const write = async () => {
2035
- await transactIo(io, path, async (current) => {
2036
- parsedBody = null;
2037
- refuseMessage = "";
2038
- assigned = 0;
2039
- if (current !== null && current.trim() !== "") {
2040
- let shape;
2041
- try {
2042
- shape = JSON.parse(current);
2043
- } catch {
2044
- return current;
2045
- }
2046
- parsedBody = shape;
2047
- if (shape.version !== void 0 && shape.version !== 1) {
2048
- const found = typeof shape.version === "number" || typeof shape.version === "string" ? String(shape.version) : "unknown";
2049
- const kind = typeof shape.version === "number" || typeof shape.version === "string" ? typeof shape.version : "unknown";
2050
- refuseMessage = `evolution event log version mismatch (expected version 1, got ${kind === "string" ? `"${found}"` : found} (${kind})) and was not touched`;
2051
- return current;
2052
- }
2053
- }
2054
- const rotated = await rotateIfDue(io, path, v1EventRecords(parsedBody), rotateAt);
2055
- if (!rotated.ok) {
2056
- refuseMessage = rotated.reason;
2057
- return current;
2058
- }
2059
- const events = rotated.events;
2060
- let maxSeq = events.reduce((max, entry) => Math.max(max, entry.seq), 0);
2061
- for (const name of await listEventArchives(io, path)) maxSeq = Math.max(maxSeq, Number.parseInt(name.slice(7, name.length - 5), 10));
2062
- const record = {
2063
- ...event,
2064
- seq: maxSeq + 1,
2065
- at: (/* @__PURE__ */ new Date()).toISOString()
2066
- };
2067
- assigned = record.seq;
2068
- return JSON.stringify({
2069
- version: 1,
2070
- events: [...events, record]
2071
- }, null, 2);
2072
- });
2073
- };
2074
- if (fence !== void 0) await fence.run(write);
2075
- else await write();
2076
- if (assigned === 0) throw new Error(`${refuseMessage || "evolution event log is malformed and was not touched"}: ${path}`);
2077
- return assigned;
2078
- }
2079
- /** The collision archive is mergeable only when this v1 writer can read it
2080
- * (P2-11): a foreign `version` (F-338) or a body without an `events` array is
2081
- * refused, so a merge can never downgrade it or empty it out.
2082
- * @param parsed - the parsed collision archive body.
2083
- * @returns the usable events, or null when the archive must not be rewritten. */
2084
- function mergeableCollisionEvents(parsed) {
2085
- if (parsed.version !== void 0 && parsed.version !== 1) return null;
2086
- if (!Array.isArray(parsed.events)) return null;
2087
- return parsed.events.filter(isEventRecord);
2088
- }
2089
- /**
2090
- * Split the active log at its midpoint when due: the older half is written to
2091
- * `events-<lastArchivedSeq>.json` (await — a failed archive write aborts the
2092
- * append so the active is never truncated without its copy), old archives are
2093
- * pruned, and the newer half is returned as the next active body. No-op when
2094
- * under the threshold; `rotateAt < 2` is a guarded no-op (rc.72 G-1: a
2095
- * one-event rotate would archive everything and restart seqs at 1).
2096
- */
2097
- async function rotateIfDue(io, path, events, rotateAt) {
2098
- if (!Number.isFinite(rotateAt) || rotateAt < 2 || events.length < rotateAt) return {
2099
- ok: true,
2100
- events
2101
- };
2102
- const mid = Math.ceil(events.length / 2);
2103
- const head = events.slice(0, mid);
2104
- const tail = events.slice(mid);
2105
- if (tail.length === 0) return {
2106
- ok: true,
2107
- events
2108
- };
2109
- const anchor = tail[0]?.seq ?? 0;
2110
- const archivePath = join(dirname(path), `${EVENT_ARCHIVE_PREFIX}${anchor - 1}.json`);
2111
- let archived = head;
2112
- let existing;
2113
- try {
2114
- existing = await io.readText(archivePath);
2115
- } catch (error) {
2116
- return {
2117
- ok: false,
2118
- reason: `evolution event archive collision at ${archivePath} could not be read (${error instanceof Error ? error.message : String(error)}) and was not touched`
2119
- };
2120
- }
2121
- if (existing !== null) {
2122
- let parsed = null;
2123
- try {
2124
- parsed = JSON.parse(existing);
2125
- } catch {
2126
- parsed = null;
2127
- }
2128
- if (parsed === null) {
2129
- const shiftPath = `${archivePath}.${Date.now()}.collide`;
2130
- await io.writeText(shiftPath, JSON.stringify({
2131
- version: 1,
2132
- events: head
2133
- }, null, 2));
2134
- 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`);
2135
- await retainEventArchives(io, path);
2136
- await pruneCollideArchives(io, path);
2137
- return {
2138
- ok: true,
2139
- events: tail
2140
- };
2141
- }
2142
- const prior = mergeableCollisionEvents(parsed);
2143
- if (prior === null) return {
2144
- ok: false,
2145
- reason: `evolution event archive collision at ${archivePath} is not a readable version-1 archive (future version, or no "events" array) and was not touched`
2146
- };
2147
- const bySeq = new Map(prior.map((event) => [event.seq, event]));
2148
- for (const event of head) bySeq.set(event.seq, event);
2149
- archived = [...bySeq.values()].sort((a, b) => a.seq - b.seq);
2150
- }
2151
- await io.writeText(archivePath, JSON.stringify({
2152
- version: 1,
2153
- events: archived
2154
- }, null, 2));
2155
- await retainEventArchives(io, path);
2156
- return {
2157
- ok: true,
2158
- events: tail
2159
- };
2160
- }
2161
- /**
2162
- * Prune old event archives (rc.71): keep the newest `EVENT_LOG_RETAIN_ARCHIVES`.
2163
- * The name's numeric part is the last archived seq, so ordering is NUMERIC —
2164
- * lexicographic would rank `events-10` before `events-2`. Only strictly
2165
- * numeric names participate (rc.72 G-2: user files are never deleted).
2166
- * Best-effort per removal; exported for the retention test.
2167
- */
2168
- async function retainEventArchives(io, path) {
2169
- const dir = dirname(path);
2170
- const names = await listEventArchives(io, path);
2171
- const excess = names.slice(0, Math.max(0, names.length - 10));
2172
- for (const name of excess) await io.remove(join(dir, name)).catch(() => {});
2173
- }
2174
- /** v31 EVENTS-02: prune shift-aside collision files (`events-*.json.<ts>.collide`)
2175
- * after the same 7-day window the `.corrupt` sweep uses. They are write-once
2176
- * recovery artifacts no reader accepts; without a sweep they accumulated
2177
- * without bound across rollback episodes. No mtime probe → keep (fail-safe). */
2178
- const COLLIDE_AGE_MS = 10080 * 60 * 1e3;
2179
- async function pruneCollideArchives(io, path) {
2180
- const dir = dirname(path);
2181
- let names;
2182
- try {
2183
- names = await io.list(dir);
2184
- } catch {
2185
- return;
2186
- }
2187
- const now = Date.now();
2188
- for (const name of names) {
2189
- if (!name.endsWith(".collide") || !name.startsWith("events-")) continue;
2190
- const full = join(dir, name);
2191
- const stamp = name.match(/\.(\d{13})\.collide$/);
2192
- if (stamp && now - Number(stamp[1]) < COLLIDE_AGE_MS) continue;
2193
- if (!stamp) try {
2194
- const mtime = await io.mtime?.(full);
2195
- if (typeof mtime !== "number" || now - mtime < COLLIDE_AGE_MS) continue;
2196
- } catch {
2197
- continue;
2198
- }
2199
- await io.remove(full).catch(() => {});
2200
- }
2201
- }
2202
- /** Read the event log; a missing/whitespace-only file reads as empty, corrupt
2203
- * content is flagged (and refused on append). A well-formed future-version body
2204
- * is v1-incompatible: it reads as EMPTY and is now flagged malformed as well
2205
- * (C-events-dispatch-1, v43). F-338's own guarantees are untouched — the reader
2206
- * never mis-shapes a newer format and the append path refuses it up front, so
2207
- * the original bytes survive — while the flag reports what the old reader hid:
2208
- * every record that body holds is dropped from this read. */
2209
- async function readEvolutionEvents(io, path) {
2210
- let raw;
2211
- try {
2212
- raw = await io.readText(path);
2213
- } catch {
2214
- return {
2215
- events: [],
2216
- malformed: true
2217
- };
2218
- }
2219
- if (raw === null || raw.trim() === "") return {
2220
- events: [],
2221
- malformed: false
2222
- };
2223
- try {
2224
- const parsed = JSON.parse(raw);
2225
- if (parsed.version !== void 0 && parsed.version !== 1) return {
2226
- events: [],
2227
- malformed: true
2228
- };
2229
- if (!Array.isArray(parsed.events)) return {
2230
- events: [],
2231
- malformed: false
2232
- };
2233
- return {
2234
- events: parsed.events.filter(isEventRecord),
2235
- malformed: false
2236
- };
2237
- } catch {
2238
- return {
2239
- events: [],
2240
- malformed: true
2241
- };
2242
- }
2243
- }
2244
- /**
2245
- * Read the full timeline (rc.71): active log + all archives, merged by seq
2246
- * (active copy wins, duplicates only arise from the rotation crash window),
2247
- * sorted ascending. Per-file malformed flag as in `readEvolutionEvents`; a
2248
- * flagged ARCHIVE (unreadable, damaged, or a future-version body this reader
2249
- * cannot interpret) is SKIPPED — it never bricks the boot, the returned events
2250
- * simply LACK that seq band, and `malformed` is the only signal that they do
2251
- * (C-events-dispatch-1, v43: the flag is the consumer's contract; a truncated
2252
- * timeline must never be folded back as if it were complete).
2253
- */
2254
- async function readEvolutionTimeline(io, path, archives) {
2255
- const dir = dirname(path);
2256
- let malformed = false;
2257
- const bySeq = /* @__PURE__ */ new Map();
2258
- for (const name of archives ?? await listEventArchives(io, path)) {
2259
- const read = await readEvolutionEvents(io, join(dir, name));
2260
- if (read.malformed) malformed = true;
2261
- for (const event of read.events) bySeq.set(event.seq, event);
2262
- }
2263
- const active = await readEvolutionEvents(io, path);
2264
- if (active.malformed) malformed = true;
2265
- for (const event of active.events) bySeq.set(event.seq, event);
2266
- return {
2267
- events: [...bySeq.values()].sort((a, b) => a.seq - b.seq),
2268
- malformed
2269
- };
2270
- }
2271
- //#endregion
2272
- //#region lib/types/fuzzy-match.js
2273
- /**
2274
- * Fuzzy string matching and replacement for patch/restructure edits of skill files.
2275
- *
2276
- * Split out of skill-store.ts (S2-1): pure text functions with no store state.
2277
- * The store imports the scan, the budgets and the replace entry points directly;
2278
- * none of them is re-exported, so the package export surface is unchanged.
2279
- */
2280
- function fuzzyIndexOf(content, pattern, from = 0) {
2281
- const isSpace = (char) => char !== void 0 && /[ \t]/.test(char);
2282
- const escaped = (char) => {
2283
- if (char === "n") return "\n";
2284
- if (char === "t") return " ";
2285
- if (char === "r") return "\r";
2286
- return null;
2287
- };
2288
- for (let start = from; start < content.length; start += 1) {
2289
- let contentIndex = start;
2290
- let patternIndex = 0;
2291
- while (patternIndex < pattern.length && contentIndex < content.length) {
2292
- const patternChar = pattern[patternIndex];
2293
- const contentChar = content[contentIndex];
2294
- if (isSpace(patternChar)) {
2295
- while (patternIndex < pattern.length && isSpace(pattern[patternIndex])) patternIndex += 1;
2296
- while (contentIndex < content.length && isSpace(content[contentIndex])) contentIndex += 1;
2297
- continue;
2298
- }
2299
- const escapedChar = patternChar === "\\" ? escaped(pattern[patternIndex + 1]) : null;
2300
- if (escapedChar !== null && contentChar === escapedChar) {
2301
- patternIndex += 2;
2302
- contentIndex += 1;
2303
- continue;
2304
- }
2305
- if (patternChar === contentChar) {
2306
- contentIndex += 1;
2307
- patternIndex += 1;
2308
- continue;
2309
- }
2310
- break;
2311
- }
2312
- if (patternIndex === pattern.length) return [start, contentIndex];
2313
- }
2314
- return null;
2315
- }
2316
- /** V6-17 (0.3.37): the fuzzy-patch scan is O(n·m) with no input bound; a
2317
- * non-exact anchor past these budgets would block the event loop (measured
2318
- * ~6s at 20k×20k). Exact matches go through the fast `includes` path and stay
2319
- * allowed regardless of size. */
2320
- const FUZZY_MAX_PATTERN_CHARS = 4096;
2321
- const FUZZY_MAX_WORK = 8e6;
2322
- /** Trim leading whitespace of the first line and trailing whitespace of the last line. */
2323
- function trimPatternBoundaries(pattern) {
2324
- const from = pattern.search(/\S/);
2325
- const trimmed = from < 0 ? pattern : pattern.slice(from);
2326
- const trailing = trimmed.search(/\s+$/);
2327
- return trailing < 0 ? trimmed : trimmed.slice(0, trailing);
2328
- }
2329
- /** Replace only the fuzzy-matched span, preserving all surrounding bytes.
2330
- * V7-11 (0.3.44): the replaceAll loop accumulates the per-scan cost — the
2331
- * single-scan budget at the caller only bounded ONE fuzzyIndexOf, while an
2332
- * unbounded number of matches × O(n·m) each could still stall the loop.
2333
- * When the accumulated cost exceeds the budget the whole replace fails
2334
- * (null) instead of partially applying an arbitrary prefix. */
2335
- function fuzzyReplace(content, oldString, newString, replaceAll) {
2336
- let current = content;
2337
- let scanFrom = 0;
2338
- let totalWork = 0;
2339
- for (;;) {
2340
- totalWork += current.length * oldString.length;
2341
- if (totalWork > 8e6) return null;
2342
- const match = fuzzyIndexOf(current, oldString, scanFrom);
2343
- if (match === null) return current;
2344
- const [start, end] = match;
2345
- const next = current.slice(0, start) + newString + current.slice(end);
2346
- if (!replaceAll) return next;
2347
- current = next;
2348
- scanFrom = start + newString.length;
2349
- }
2350
- }
2351
- function fuzzyPatch(content, oldString, newString, replaceAll = false) {
2352
- if (oldString === "") return null;
2353
- if (content.includes(oldString)) return replaceAll ? content.split(oldString).join(newString) : content.replace(oldString, () => newString);
2354
- const boundary = trimPatternBoundaries(oldString);
2355
- if (boundary === "") return null;
2356
- if (boundary !== oldString) {
2357
- if (fuzzyIndexOf(content, boundary) !== null) return fuzzyReplace(content, boundary, newString, replaceAll);
2358
- }
2359
- if (fuzzyIndexOf(content, oldString) !== null) return fuzzyReplace(content, oldString, newString, replaceAll);
2360
- return null;
2361
- }
2362
- /** Deterministic section-extraction plan facts; the caller owns the IO and the append semantics. */
2363
- //#endregion
2364
- //#region lib/types/serial.js
2365
- /**
2366
- * A process-local serial task queue: each task starts only after the previous
2367
- * one settles (success or failure), so read-modify-write sequences that share
2368
- * one file never interleave inside this process. When the IO backend provides
2369
- * a cross-process transact lock, that is the first layer; the node backend does
2370
- * not, so this chain is its only serialization. (0.3.17 S2.8, T-1: the shape was
2371
- * duplicated in state-json and
2372
- * memory-files — one factory now).
2373
- */
2374
- function makeSerialQueue() {
2375
- let chain = Promise.resolve();
2376
- return (task) => {
2377
- const run = chain.then(task, task);
2378
- chain = run.then(() => void 0, () => void 0);
2379
- return run;
2380
- };
2381
- }
2382
- //#endregion
2383
- //#region lib/types/threats.js
2384
- /**
2385
- * Threat scanning for agent-authored memory and skill content.
2386
- *
2387
- * Ported as a small, dependency-free subset of Hermes Agent's
2388
- * `tools/threat_patterns.py` + hermes-claw `threats.ts`.
2389
- *
2390
- * Policy (P1-1, v19): a finding either BLOCKS the write or only REPORTS.
2391
- * Blocking is reserved for shapes with no legitimate use in stored knowledge
2392
- * (prompt-injection phrasing, credential exfiltration, the invisible-character
2393
- * smuggling core). Typography and presentation characters that are legitimate
2394
- * in ordinary prose — variation selectors (❤️), zero-width non-joiner, soft
2395
- * hyphen from PDF paste, Arabic letter mark, Mongolian vowel separator — are
2396
- * REPORT findings: they stay visible to operators and tests but never reject a
2397
- * write. Blocking them turned every emoji into a security event.
2398
- */
2399
- const FILLER = String.raw`(?:\w+\s+){0,8}`;
2400
- const PATTERNS = [
2401
- {
2402
- label: "prompt_injection_ignore",
2403
- category: "prompt_injection",
2404
- scope: "all",
2405
- regex: new RegExp(String.raw`ignore\s+${FILLER}(?:previous|above|prior|all)\s+${FILLER}instructions`, "i")
2406
- },
2407
- {
2408
- label: "disregard_rules",
2409
- category: "prompt_injection",
2410
- scope: "all",
2411
- regex: new RegExp(String.raw`disregard\s+${FILLER}(?:your|all|any)\s+${FILLER}(?:instructions|rules|guidelines)`, "i")
2412
- },
2413
- {
2414
- label: "system_prompt_override",
2415
- category: "prompt_injection",
2416
- scope: "all",
2417
- regex: /system\s+prompt\s+override/i
2418
- },
2419
- {
2420
- label: "bypass_restrictions",
2421
- category: "prompt_injection",
2422
- scope: "all",
2423
- regex: /act\s+as\s+(?:if|though)\s+(?:you\s+)?(?:have\s+no|don'?t\s+have)\s+(?:restrictions?|limits?|rules)/i
2424
- },
2425
- {
2426
- label: "new_system_prompt",
2427
- category: "prompt_injection",
2428
- scope: "strict",
2429
- regex: new RegExp(String.raw`new\s+${FILLER}system\s+${FILLER}prompt`, "i")
2430
- },
2431
- {
2432
- label: "forget_everything",
2433
- category: "prompt_injection",
2434
- scope: "strict",
2435
- regex: new RegExp(String.raw`forget\s+${FILLER}(?:everything|all)\s+${FILLER}(?:discussed|you\s+know)`, "i")
2436
- },
2437
- {
2438
- label: "role_hijack",
2439
- category: "role_hijacking",
2440
- scope: "context",
2441
- regex: /you\s+are\s+now\s+(?:a|an|the|acting|playing|pretending)/i
2442
- },
2443
- {
2444
- label: "fake_update",
2445
- category: "role_hijacking",
2446
- scope: "context",
2447
- regex: new RegExp(String.raw`you\s+have\s+been\s+${FILLER}(?:updated|upgraded|patched)\s+to`, "i")
2448
- },
2449
- {
2450
- label: "identity_override",
2451
- category: "role_hijacking",
2452
- scope: "context",
2453
- regex: /\bname\s+yourself\s+\w+/i
2454
- },
2455
- {
2456
- label: "remove_filters",
2457
- category: "role_hijacking",
2458
- scope: "context",
2459
- regex: /(?:respond|answer|reply)\s+without\s+(?:restrictions?|limitations?|filters?|safety)/i
2460
- },
2461
- {
2462
- label: "deception_hide",
2463
- category: "deception",
2464
- scope: "all",
2465
- regex: new RegExp(String.raw`do\s+not\s+${FILLER}tell\s+${FILLER}the\s+user`, "i")
2466
- },
2467
- {
2468
- label: "leak_system_prompt",
2469
- category: "deception",
2470
- scope: "context",
2471
- regex: new RegExp(String.raw`output\s+${FILLER}(?:system|initial)\s+prompt`, "i")
2472
- },
2473
- {
2474
- label: "context_exfil",
2475
- category: "exfiltration",
2476
- scope: "strict",
2477
- regex: /(?:include|output|print|share)\s+(?:the\s+)?(?:conversation|chat\s+history|previous\s+messages|(?:full|entire)\s+context)/i
2478
- },
2479
- {
2480
- label: "send_to_url",
2481
- category: "exfiltration",
2482
- scope: "strict",
2483
- regex: /(?:send|post|upload|transmit)\s+[\s\S]{0,512}?\s+(?:to|at)\s+https?:\/\//i
2484
- },
2485
- {
2486
- label: "exfil_curl",
2487
- category: "exfiltration",
2488
- scope: "all",
2489
- regex: /\bcurl\s+[\s\S]{0,512}?\$\{?\w*(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|API)/i
2490
- },
2491
- {
2492
- label: "exfil_wget",
2493
- category: "exfiltration",
2494
- scope: "all",
2495
- regex: /\bwget\s+[\s\S]{0,512}?\$\{?\w*(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|API)/i
2496
- },
2497
- {
2498
- label: "read_secrets",
2499
- category: "exfiltration",
2500
- scope: "all",
2501
- regex: /\bcat\s+[^\n]{0,512}(?:\.env(?!\w)(?!\.(?:[\w-]+\.)*(?:example|sample)(?=$|[\s"']))|(?:\bcredentials\b)|\.netrc|\.pgpass|\.npmrc|\.pypirc)/i
2502
- },
2503
- {
2504
- label: "ssh_backdoor",
2505
- category: "persistence",
2506
- scope: "strict",
2507
- regex: /\bauthorized_keys\b/i
2508
- },
2509
- {
2510
- label: "agent_config_mod",
2511
- category: "persistence",
2512
- scope: "strict",
2513
- regex: /(?:update|modify|edit|write|change|append|add\s+to)\s+(?:AGENTS\.md|CLAUDE\.md|\.cursorrules|\.clinerules)/i
2514
- },
2515
- {
2516
- label: "hermes_env",
2517
- category: "persistence",
2518
- scope: "strict",
2519
- regex: /\$?HOME\/\.hermes|~\/\.hermes|\.hermes\/\.env|%USERPROFILE%[\\/]\.hermes/i
2520
- },
2521
- {
2522
- label: "c2_node_registration",
2523
- category: "c2_promptware",
2524
- scope: "context",
2525
- regex: /register\s+(?:as\s+)?a?\s*node/i
2526
- },
2527
- {
2528
- label: "c2_heartbeat",
2529
- category: "c2_promptware",
2530
- scope: "context",
2531
- regex: /(?:heartbeats?|beacon|check[\s-]?in)\s+(?:to|with)/i
2532
- },
2533
- {
2534
- label: "c2_task_pull",
2535
- category: "c2_promptware",
2536
- scope: "context",
2537
- regex: /pull\s+(?:new\s+)?tasks?/i
2538
- },
2539
- {
2540
- label: "known_c2_framework",
2541
- category: "c2_promptware",
2542
- scope: "context",
2543
- regex: /\b(?:cobalt\s*strike|sliver|havoc|mythic|metasploit|brainworm)\b/i
2544
- },
2545
- {
2546
- label: "hardcoded_secret",
2547
- category: "hardcoded_secrets",
2548
- scope: "strict",
2549
- regex: /(?:api[_-]?key|token|secret|password)\s*[=:]\s*["'][a-z0-9+/=_-]{20,}["']/i
2550
- },
2551
- {
2552
- label: "jwt_like_secret",
2553
- category: "hardcoded_secrets",
2554
- scope: "strict",
2555
- regex: /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/
2556
- },
2557
- {
2558
- label: "private_key_block",
2559
- category: "hardcoded_secrets",
2560
- scope: "all",
2561
- regex: /-----BEGIN\s+(?:(?:RSA|EC|DSA|OPENSSH|ENCRYPTED|PGP)\s+)?PRIVATE\s+KEY(?:\s+BLOCK)?-----/
2562
- },
2563
- {
2564
- label: "prompt_injection_ignore_zh",
2565
- category: "prompt_injection",
2566
- scope: "all",
2567
- regex: /(?:忽略|无视|抛开)[\s\S]{0,8}(?:之前|以上|上面|先前|以前)?[\s\S]{0,8}(?:所有|全部|任何)?[\s\S]{0,4}(?:指令|规则|设定|约束)/
2568
- },
2569
- {
2570
- label: "deception_hide_zh",
2571
- category: "deception",
2572
- scope: "all",
2573
- regex: /(?:不要|别|勿)(?:告诉|告知|透露)(?:给)?[\s\S]{0,6}(?:用户|任何人|主人|开发者)/
2574
- },
2575
- {
2576
- label: "system_prompt_leak_zh",
2577
- category: "deception",
2578
- scope: "context",
2579
- regex: /(?:泄露|输出|打印|透露|导出)[\s\S]{0,10}系统提示|系统提示[\s\S]{0,10}(?:泄露|透露|发送|导出)/
2580
- },
2581
- {
2582
- label: "context_exfil_zh",
2583
- category: "exfiltration",
2584
- scope: "strict",
2585
- regex: /(?:对话记录|聊天记录|全部上下文|完整上下文)[\s\S]{0,30}(?:发送|上传|传输|外传|泄露)[\s\S]{0,30}(?:到|至|给)/
2586
- },
2587
- {
2588
- label: "secret_exfil_zh",
2589
- category: "exfiltration",
2590
- scope: "strict",
2591
- regex: /(?:密钥|凭据|口令|密码|环境变量)[\s\S]{0,30}(?:发送|上传|传输|外传|泄露)[\s\S]{0,30}(?:到|至)\s*(?:https?:\/\/|[\w.-]+\.(?:com|net|org|io|cn|dev|xyz|ru)\b)/
2592
- }
2593
- ];
2594
- const ZERO_WIDTH_CHARS = new RegExp(`[\\u034f\\u200b\\u2060\\u2061\\u2062\\u2063\\u2064\\u206a-\\u206f\\ufeff\\u{e0000}-\\u{e007f}]`, "u");
2595
- const ZWJ_OUTSIDE_EMOJI = /(?<!\p{Extended_Pictographic})\u200d(?!\p{Extended_Pictographic})/u;
2596
- const TYPOGRAPHY_CHARS = /[\u00ad\u061c\u180e\u200c\ufe00-\ufe0f]/;
2597
- const BIDI_CHARS = /[\u202a-\u202e\u2066-\u2069]/;
2598
- const FORMAT_CONTROL_CLASS = "\\p{Cf}\\p{Zl}\\p{Zp}\\u0000\\u2065\\ufff0-\\ufff8\\u{e0080}-\\u{e00ff}";
2599
- const FORMAT_CONTROL_TEST = new RegExp(`[${FORMAT_CONTROL_CLASS}]`, "u");
2600
- /** S0.4 (v37 P0-3): a format control the three finding sets above do NOT report.
2601
- * S1-E3: the ZWJ exemption compares the real character. It used to read
2602
- * `'\\u200d'` — a 6-character literal that never equals a code point — so the
2603
- * branch was dead and every emoji ZWJ sequence (👨‍👩‍👧) raised the report-level
2604
- * `unicode_format_control` finding the class comment above promises it will not. */
2605
- function hasUnreportedFormatControl(text) {
2606
- for (const character of text) {
2607
- if (!FORMAT_CONTROL_TEST.test(character)) continue;
2608
- if (ZERO_WIDTH_CHARS.test(character) || TYPOGRAPHY_CHARS.test(character) || BIDI_CHARS.test(character)) continue;
2609
- if (character === "‍") continue;
2610
- return true;
2611
- }
2612
- return false;
2613
- }
2614
- const SCOPE_ORDER = {
2615
- all: 1,
2616
- context: 2,
2617
- strict: 3
2618
- };
2619
- const NO_SCAN_OPTIONS = {};
2620
- /** Minimum window size for the full-coverage scan (V6-05, 0.3.35). With the
2621
- * proportional half-window step below, the overlap is `ceil(w/2)` — only a
2622
- * window at or above this floor keeps the overlap above the longest pattern
2623
- * span (~530 chars: `curl [^\n]{0,512} ...`), so a match straddling a window
2624
- * boundary is fully inside at least one window (E-12, 0.3.16). The clamp
2625
- * falls back to the default for a smaller caller value instead of risking a
2626
- * blind zone. */
2627
- const PATTERN_OVERLAP = 4096;
2628
- /**
2629
- * Scan text at `scope`. Patterns are cumulative: `strict` includes all scopes.
2630
- * `options.excludeLabels` removes matching patterns without changing `scope`.
2631
- * `maxScanChars` is the WINDOW SIZE, not a total cap (E-12, 0.3.16): the whole
2632
- * text is always scanned in overlapping windows, so content beyond 65,536
2633
- * characters (skill files may run to 100,000) is no longer a blind zone.
2634
- */
2635
- function scanThreats(text, scope = "strict", maxScanChars = DEFAULT_THREAT_MAX_SCAN_CHARS, options = NO_SCAN_OPTIONS) {
2636
- const windowSize = clampedNumber(maxScanChars, DEFAULT_THREAT_MAX_SCAN_CHARS, { min: 4097 });
2637
- const findings = [];
2638
- const excluded = new Set(options.excludeLabels ?? []);
2639
- if ((ZERO_WIDTH_CHARS.test(text) || ZWJ_OUTSIDE_EMOJI.test(text)) && !excluded.has("unicode_zero_width")) findings.push({
2640
- label: "unicode_zero_width",
2641
- category: "unicode_obfuscation",
2642
- scope: "all"
2643
- });
2644
- if (TYPOGRAPHY_CHARS.test(text) && !excluded.has("unicode_typography")) findings.push({
2645
- label: "unicode_typography",
2646
- category: "unicode_obfuscation",
2647
- scope: "all",
2648
- severity: "report"
2649
- });
2650
- if (BIDI_CHARS.test(text) && !excluded.has("unicode_bidi_override")) findings.push({
2651
- label: "unicode_bidi_override",
2652
- category: "unicode_obfuscation",
2653
- scope: "all"
2654
- });
2655
- if (!excluded.has("unicode_format_control") && hasUnreportedFormatControl(text)) findings.push({
2656
- label: "unicode_format_control",
2657
- category: "unicode_obfuscation",
2658
- scope: "all",
2659
- severity: "report"
2660
- });
2661
- const normalized = text.normalize("NFKC");
2662
- const SPACE_SPLITTERS = /[\u00ad\u061c\u180e\u200c\ufe00-\ufe0f]/gu;
2663
- const OBFUSCATION_SPLITTERS = new RegExp(`[${FORMAT_CONTROL_CLASS}]`, "gu");
2664
- const patternTexts = [normalized.replace(SPACE_SPLITTERS, " ").replace(OBFUSCATION_SPLITTERS, " "), normalized.replace(SPACE_SPLITTERS, "").replace(OBFUSCATION_SPLITTERS, "")];
2665
- const windows = [];
2666
- for (const patternText of patternTexts) if (patternText.length <= windowSize) windows.push(patternText);
2667
- else {
2668
- const step = Math.max(Math.floor(windowSize / 2), 1);
2669
- for (let start = 0; start < patternText.length; start += step) windows.push(patternText.slice(start, start + windowSize));
2670
- }
2671
- const seen = /* @__PURE__ */ new Set();
2672
- for (const window of windows) for (const pattern of PATTERNS) {
2673
- if (SCOPE_ORDER[pattern.scope] > SCOPE_ORDER[scope]) continue;
2674
- if (excluded.has(pattern.label)) continue;
2675
- if (!pattern.regex.test(window)) continue;
2676
- const key = `${pattern.label}|${pattern.scope}`;
2677
- if (seen.has(key)) continue;
2678
- seen.add(key);
2679
- findings.push({
2680
- label: pattern.label,
2681
- category: pattern.category,
2682
- scope: pattern.scope
2683
- });
2684
- }
2685
- return findings;
2686
- }
2687
- /** Blocking policy (P1-1, v19): a finding blocks unless it is explicitly
2688
- * `report`-only. Pattern findings carry no severity and therefore block as
2689
- * before. */
2690
- function evaluateThreat(text, scope = "strict", maxScanChars = DEFAULT_THREAT_MAX_SCAN_CHARS, options = NO_SCAN_OPTIONS) {
2691
- const findings = scanThreats(text, scope, maxScanChars, options);
2692
- return {
2693
- blocked: findings.some((finding) => finding.severity !== "report"),
2694
- findings
2695
- };
2696
- }
2697
- /** User-facing block message for memory writes. */
2698
- function scanMemoryThreats(text, maxScanChars = DEFAULT_THREAT_MAX_SCAN_CHARS, options = NO_SCAN_OPTIONS) {
2699
- const { blocked, findings } = evaluateThreat(text, "strict", maxScanChars, options);
2700
- if (!blocked) return null;
2701
- const pattern = findings.find((f) => f.category !== "unicode_obfuscation");
2702
- if (pattern) return `Blocked by security scan (${pattern.label}). Rephrase without instruction-like language.${THREAT_EXEMPTION_HINT}`;
2703
- return `Blocked by security scan: invisible or potentially malicious Unicode detected.${THREAT_EXEMPTION_HINT}`;
2704
- }
2705
- /** User-facing block message for skill content writes. */
2706
- function scanContentThreats(text, maxScanChars = DEFAULT_THREAT_MAX_SCAN_CHARS, options = NO_SCAN_OPTIONS) {
2707
- const { blocked, findings } = evaluateThreat(text, "strict", maxScanChars, options);
2708
- if (!blocked) return null;
2709
- const pattern = findings.find((f) => f.category !== "unicode_obfuscation");
2710
- if (pattern) return `Blocked by security scan (${pattern.label}). This content appears to contain potentially malicious instructions.${THREAT_EXEMPTION_HINT}`;
2711
- return `Blocked by security scan: invisible or potentially malicious Unicode detected. This content appears to contain potentially malicious instructions.${THREAT_EXEMPTION_HINT}`;
2712
- }
2713
- /**
2714
- * WD2 (0.3.56): the shared tail of every user-facing threat block — names the
2715
- * deployable self-heal path so the model (or operator) can allowlist a
2716
- * known-benign label. v20 (B-2) single source: the scan builders embed this
2717
- * constant verbatim; do NOT re-word it per call site (the three former copies
2718
- * — memory inline, content inline, and the dead `THREAT_EXEMPT_HINT` export,
2719
- * whose docblock still claimed a store-side append that memory-store/skill-store
2720
- * had already removed — had drifted apart). The evolution-threat guard channel
2721
- * returns the scan message verbatim, so the hint rides along there too.
2722
- */
2723
- const THREAT_EXEMPTION_HINT = " A deployment that needs a specific label can exempt it via threatExemptLabels (see the README env/dial reference).";
2724
- //#endregion
2725
- //#region lib/types/review-channel.js
2726
- /**
2727
- * Family-internal mark for the review channel's INJECT delivery (v37 S2.2).
2728
- *
2729
- * With the default `reviewMode: 'inject'` the review prompt runs in the PARENT
2730
- * session, so the parent model's own `skill_manage` calls carry no origin the
2731
- * platform could attribute: `.pinned` and the `.hermes-managed` authorship mark
2732
- * were skipped for exactly the autonomous writes they exist for. The delivery
2733
- * marks the session here and the write path reads the mark.
2734
- *
2735
- * Window: after the review prompt, until the next REAL user message (a
2736
- * `user/message` with `source.kind === 'user'` clears it; plugin-sourced notices
2737
- * never do). Process-wide and keyed by session on purpose — the same
2738
- * "restart is a fresh conversation boundary" discipline as the review plugin's
2739
- * own per-session counters. This module is the ONE owner of the marker.
2740
- * @module @lmzhen/dsh-evolution-core/review-channel
2741
- */
2742
- /** Session ids currently executing a review prompt, oldest delivery first. */
2743
- const MARK_KEY = Symbol.for("dsh.evolution.review-channel.marked");
2744
- const registry$1 = globalThis;
2745
- const markedSessions = registry$1[MARK_KEY] ?? (registry$1[MARK_KEY] = /* @__PURE__ */ new Set());
2746
- /**
2747
- * Mark one session as running the review channel's prompt; idempotent, and
2748
- * keyed by session so a mark can never leak into another session.
2749
- * @param sessionId - the session the review prompt was delivered to.
2750
- */
2751
- function markReviewChannel(sessionId) {
2752
- markedSessions.delete(sessionId);
2753
- markedSessions.add(sessionId);
2754
- }
2755
- /**
2756
- * Clear the mark: the session's next prompt is human input again.
2757
- * @param sessionId - the session whose mark is dropped.
2758
- */
2759
- function clearReviewChannel(sessionId) {
2760
- markedSessions.delete(sessionId);
2761
- }
2762
- /**
2763
- * Whether this session's current prompt came from the review channel. An
2764
- * execution without a session is never the review channel.
2765
- * @param sessionId - the executing session id, when the caller has one.
2766
- * @returns true only for a marked session.
2767
- */
2768
- function isReviewChannelSession(sessionId) {
2769
- return sessionId !== void 0 && markedSessions.has(sessionId);
2770
- }
2771
- /**
2772
- * Drop marks whose session is gone — a dead session cannot execute a write.
2773
- * @param isAlive - liveness probe for one session id.
2774
- * @returns the number of removed marks.
2775
- */
2776
- function sweepReviewChannelSessions(isAlive) {
2777
- let removed = 0;
2778
- for (const sessionId of [...markedSessions]) {
2779
- if (isAlive(sessionId)) continue;
2780
- markedSessions.delete(sessionId);
2781
- removed += 1;
2782
- }
2783
- return removed;
2784
- }
2785
- //#endregion
2786
- //#region lib/types/review-context.js
2787
- /**
2788
- * Plugin-local review execution context.
2789
- *
2790
- * This is deliberately not a platform API: the family review executor wraps one
2791
- * bounded tool loop, and the write tools read the context to attribute writes as
2792
- * background_review without relying on a Session header or a global mark.
2793
- *
2794
- * @module @lmzhen/dsh-evolution-core/review-context
2795
- */
2796
- const STORAGE_KEY = Symbol.for("dsh.evolution.review-context.storage");
2797
- const registry = globalThis;
2798
- const storage = registry[STORAGE_KEY] ?? (registry[STORAGE_KEY] = new AsyncLocalStorage());
2799
- /**
2800
- * Run one review tool loop under the review write context.
2801
- * @param context - review/run identity.
2802
- * @param task - loop body; nested tool executions inherit the context.
2803
- * @returns the task's value.
2804
- */
2805
- function withReviewContext(context, task) {
2806
- return storage.run(Object.freeze({ ...context }), task);
2807
- }
2808
- /**
2809
- * The active review context, when the current async execution belongs to a review loop.
2810
- * @returns the frozen context, or undefined outside a review loop.
2811
- */
2812
- function currentReviewContext() {
2813
- return storage.getStore();
2814
- }
2815
- //#endregion
2816
- //#region lib/types/skill-health.js
2817
- /**
2818
- * Skill structure-health domain (rc.73 A1, 008 design): a SECOND assessment
2819
- * dimension beside the six-factor usage quality — document hygiene, consumed
2820
- * by the curator health view and the `/evolution skills health` command.
2821
- *
2822
- * PURE and DERIVED: nothing is persisted; every assessment is computed from
2823
- * file facts at read time. The judgment split follows the original's
2824
- * boundary/治理 layering — deterministic signals here, refinement proposals
2825
- * stay in the review/curator judgment layer. Never become a 7th factor of
2826
- * `computeQualityScores` (different dimension, different consumers).
2827
- */
2828
- const DEFAULT_HEALTH_THRESHOLDS = {
2829
- softBodyChars: AUTHORING_SPLIT_LINE_CHARS,
2830
- stampDensityPerKb: 2,
2831
- churnMinPatches: 20,
2832
- hardCapMinHits: 3
2833
- };
2834
- /**
2835
- * Stamp regex shared by health assessment and the maintenance probe (single
2836
- * source, 011). Two refinements over the naive form (F-320): the hex branch
2837
- * requires at least one digit so coincidental all-letter English words
2838
- * (`defaced`, `feedback`) are not counted as commit shas; the ISO branch
2839
- * accepts a UTC `Z`, a numeric UTC offset (`+08:00`), or no timezone at all —
2840
- * non-UTC timestamps used to escape detection (log-like content missed).
2841
- *
2842
- * Known boundary, recorded not fixed (C-22, v10 audit): the hex branch also
2843
- * matches 7-40 char PURE-DIGIT strings (order numbers etc.), so stamp density
2844
- * can be over-reported for such content. The misjudgment direction is "extra
2845
- * stamp hits" only — never a miss — and no real incident exists; revisit only
2846
- * if curator decisions are actually distorted (v10 deferral ledger).
2847
- */
2848
- 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");
2849
- /**
2850
- * Bodies below this size skip stamp-density assessment: a few dates or shas
2851
- * in a short body are ordinary documentation, not log-like content. With the
2852
- * 1KB density floor a 3-date sentence in a small skill measured 3.0/KB and
2853
- * warned on a perfectly healthy body (audit 2026-08-31 X1).
2854
- */
2855
- const MIN_STAMP_BODY_CHARS = 2e3;
2856
- /**
2857
- * The findings for ONE body, computed by the engine that owns the judgement (G4).
2858
- *
2859
- * Deliberately a thin call into `assessStructureHealth`: a later consumer (the write receipt) needs
2860
- * findings for a body it is about to store, and re-deriving the facts anywhere else would be a
2861
- * SECOND judgement — the token-scale line, the /1024 stamp density and the soft/2 support threshold
2862
- * all live in one place and must stay there.
2863
- * @param skillName - the skill the body belongs to (used in messages).
2864
- * @param content - the WHOLE SKILL.md text, frontmatter included (the engine's own convention).
2865
- * @param supportGroups - non-empty support dirs; pass the real count, never a guess.
2866
- * @param thresholds - the configured thresholds; defaults to the shipped ones.
2867
- * @returns the findings, in rule order.
2868
- */
2869
- function lintBody(skillName, content, supportGroups, thresholds = DEFAULT_HEALTH_THRESHOLDS) {
2870
- return assessStructureHealth({
2871
- skillName,
2872
- bodyChars: content.length,
2873
- bodyText: content,
2874
- supportGroups
2875
- }, thresholds).findings;
2876
- }
2877
- function assessStructureHealth(snapshot, thresholds = DEFAULT_HEALTH_THRESHOLDS) {
2878
- const dims = {
2879
- bodyChars: snapshot.bodyChars,
2880
- bodyTokens: Math.round(snapshot.bodyChars / UPSTREAM_LIMIT_CHARS_PER_TOKEN),
2881
- stampDensityPerKb: null,
2882
- stampHits: null,
2883
- supportGroups: snapshot.supportGroups,
2884
- supportFiles: snapshot.supportFiles ?? null,
2885
- churnPatches: null,
2886
- churnReads: null,
2887
- hardCapHits: snapshot.hardCapHits ?? null
2888
- };
2889
- const text = snapshot.bodyText;
2890
- const cost = typeof text === "string" && text.length > 0 ? bodyCost(text) : null;
2891
- const lineTokens = cost === null ? null : tokenLineFor(thresholds.softBodyChars, cost);
2892
- dims.bodyTokens = cost === null ? Math.round(snapshot.bodyChars / UPSTREAM_LIMIT_CHARS_PER_TOKEN) : cost.tokens;
2893
- const overLine = cost === null || lineTokens === null ? snapshot.bodyChars >= thresholds.softBodyChars : cost.tokens >= lineTokens;
2894
- const overTwice = cost === null || lineTokens === null ? snapshot.bodyChars >= thresholds.softBodyChars * 2 : cost.tokens >= lineTokens * 2;
2895
- if (snapshot.bodyText && snapshot.bodyChars >= 2e3) {
2896
- const kb = Math.max(1, snapshot.bodyChars / 1024);
2897
- const stamps = (snapshot.bodyText.match(HEALTH_STAMP_RE) ?? []).length;
2898
- dims.stampDensityPerKb = stamps / kb;
2899
- dims.stampHits = stamps;
2900
- }
2901
- if (snapshot.patchCount !== void 0 && snapshot.readCount !== void 0) {
2902
- dims.churnPatches = snapshot.patchCount;
2903
- dims.churnReads = snapshot.readCount;
2904
- }
2905
- const findings = lintSkill({
2906
- skillName: snapshot.skillName,
2907
- dims,
2908
- softLineChars: thresholds.softBodyChars,
2909
- overSoftLine: overLine,
2910
- overTwiceSoftLine: overTwice,
2911
- stampLimitPerKb: thresholds.stampDensityPerKb,
2912
- churnMinPatches: thresholds.churnMinPatches,
2913
- hardCapMinHits: thresholds.hardCapMinHits,
2914
- readable: true
2915
- });
2916
- return {
2917
- verdict: findings.some((f) => f.rule === "body-oversize-2x") ? "needs-restructure" : findings.length > 0 ? "warn" : "healthy",
2918
- dims,
2919
- findings
2920
- };
2921
- }
2922
- //#endregion
2923
- export { bumpView as $, listEventArchives as A, relatedSkillNames as At, COST_CJK_TOKEN_HIGH as B, planRehoming as Bt, EVENT_ARCHIVE_PREFIX as C, authoringFeedback as Ct, appendEvolutionEvent as D, frontmatterCatalogInvalid as Dt, EVENT_LOG_VERSION as E, frontmatterBlock as Et, RULES as F, externalRefs as Ft, tokenLineFor as G, sessionReadSupportFiles as Gt, TOKEN_ASCII_WEIGHT as H, filterUnreadSkillOps as Ht, diffFindings as I, supportRefs as It, applyCuratorLifecycleFields as J, authorityFrom as Jt, MAX_SUPPORT_READ_PATHS as K, DEFAULT_WRITE_CONFIRM_MODE as Kt, lintSkill as L, applyReferenceRewrite as Lt, readEvolutionEvents as M, skillMdOnDisk as Mt, readEvolutionTimeline as N, validateFrontmatter as Nt, eventsFile as O, normalizeFrontmatter as Ot, retainEventArchives as P, yamlPlainScalarNeedsQuotes as Pt, bumpUse as Q, COST_ASCII_TOKEN_HIGH as R, describeReferenceRewrite as Rt, trimPatternBoundaries as S, readingStats as St, EVENT_LOG_ROTATE_AT as T, exceedsContentLimit as Tt, TOKEN_CJK_WEIGHT as U, isUnreadWrite as Ut, COST_CJK_TOKEN_LOW as V, READ_REQUIRED_ACTIONS as Vt, bodyCost as W, sessionReadSkillNames as Wt, bumpPatch as X, applyCuratorMetaFields as Y, bumpSupportRead as Z, scanThreats as _, planExtract as _t, lintBody as a, latestActivityAt as at, FUZZY_MAX_WORK as b, displayBodyOf as bt, clearReviewChannel as c, markAgentCreated as ct, sweepReviewChannelSessions as d, saveSuppressedNames as dt, daysSinceIso as et, PATTERN_OVERLAP as f, saveUsage as ft, scanMemoryThreats as g, usageObserved as gt, scanContentThreats as h, usageFile as ht, assessStructureHealth as i, idleDays as it, parseEvolutionEvents as j, shrinksOverLimit as jt, evolutionEventPayloadIssue as k, parseFrontmatter as kt, isReviewChannelSession as l, mutateUsage as lt, evaluateThreat as m, updateSuppressedNames as mt, HEALTH_STAMP_RE as n, foldCuratorFields as nt, currentReviewContext as o, loadSuppressedNames as ot, THREAT_EXEMPTION_HINT as p, suppressedFile as pt, SUPPRESSED_FILE_VERSION as q, DEFAULT_WRITE_CONFIRM_TIMEOUT_SECONDS as qt, MIN_STAMP_BODY_CHARS as r, getRecord as rt, withReviewContext as s, loadUsage as st, DEFAULT_HEALTH_THRESHOLDS as t, emptyRecord as tt, markReviewChannel as u, normalizeUsageRecord as ut, makeSerialQueue as v, projectExtractBodies as vt, EVENT_LOG_RETAIN_ARCHIVES as w, ensureSkillFrontmatter as wt, fuzzyPatch as x, h2Sections as xt, FUZZY_MAX_PATTERN_CHARS as y, selectSections as yt, COST_ASCII_TOKEN_LOW as z, planReferenceRewrite as zt };