@lmzhen/dsh-evolution-core 0.49.0 → 0.51.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 (110) hide show
  1. package/lib/authority-plugin.js +2 -1
  2. package/lib/citations-CZKTUGQF.js +198 -0
  3. package/lib/composition/index.js +3 -3
  4. package/lib/{composition-Cqjbho0t.js → composition-CtNbVHq3.js} +1 -1
  5. package/lib/connection-DAJy7Xjm.js +28 -0
  6. package/lib/{ensure-CAjLGd9f.js → ensure-BLmEW0Ju.js} +25 -7
  7. package/lib/errors.js +2 -0
  8. package/lib/extract-plan-D6o__2Kf.js +271 -0
  9. package/lib/extract.js +240 -0
  10. package/lib/http-routes.js +27 -7
  11. package/lib/index.js +100 -811
  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-DpAS0rd9.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-BQCM4N8z.js +1419 -0
  24. package/lib/{skill-history-CxrDE3Rb.js → skill-history-CZp8vhyL.js} +46 -2
  25. package/lib/skills.js +140 -20
  26. package/lib/state-store-Jpa-iYIZ.js +54 -0
  27. package/lib/subagent/index.js +214 -176
  28. package/lib/{tools-DzcNFex2.js → tools-BrUswg8v.js} +3 -1
  29. package/lib/types/composition/ensure.js +21 -7
  30. package/lib/types/composition/preset-ids.d.ts +2 -1
  31. package/lib/types/composition/preset-ids.js +7 -1
  32. package/lib/types/events.d.ts +3 -0
  33. package/lib/types/extract-plan.d.ts +2 -0
  34. package/lib/types/extract.d.ts +12 -0
  35. package/lib/types/extract.js +12 -0
  36. package/lib/types/http-routes.js +32 -9
  37. package/lib/types/index.d.ts +0 -3
  38. package/lib/types/index.js +0 -3
  39. package/lib/types/opt-in.js +4 -3
  40. package/lib/types/params.js +2 -1
  41. package/lib/types/platform/agents.d.ts +32 -0
  42. package/lib/types/platform/agents.js +26 -0
  43. package/lib/types/platform/commands.d.ts +14 -0
  44. package/lib/types/platform/commands.js +9 -0
  45. package/lib/types/platform/connection.d.ts +26 -0
  46. package/lib/types/platform/connection.js +27 -0
  47. package/lib/types/platform/index.d.ts +26 -0
  48. package/lib/types/platform/index.js +13 -0
  49. package/lib/types/platform/llm.d.ts +3 -1
  50. package/lib/types/platform/llm.js +1 -0
  51. package/lib/types/platform/platformView.d.ts +21 -0
  52. package/lib/types/platform/platformView.js +29 -0
  53. package/lib/types/platform/profileContext.d.ts +16 -0
  54. package/lib/types/platform/profileContext.js +14 -0
  55. package/lib/types/platform/sessionQuery.d.ts +14 -0
  56. package/lib/types/platform/sessionQuery.js +9 -0
  57. package/lib/types/platform/settings.d.ts +22 -0
  58. package/lib/types/platform/settings.js +14 -0
  59. package/lib/types/platform/skills.d.ts +16 -0
  60. package/lib/types/platform/skills.js +9 -0
  61. package/lib/types/platform/storageDomain.d.ts +13 -0
  62. package/lib/types/platform/storageDomain.js +9 -0
  63. package/lib/types/platform/subagents.d.ts +25 -0
  64. package/lib/types/platform/subagents.js +17 -0
  65. package/lib/types/platform/systemPrompt.d.ts +16 -0
  66. package/lib/types/platform/systemPrompt.js +13 -0
  67. package/lib/types/platform/tools.d.ts +4 -0
  68. package/lib/types/platform/tools.js +2 -0
  69. package/lib/types/platform/userQuestions.d.ts +33 -0
  70. package/lib/types/platform/userQuestions.js +9 -0
  71. package/lib/types/platform/workingDirectory.d.ts +14 -0
  72. package/lib/types/platform/workingDirectory.js +9 -0
  73. package/lib/types/platform-line.generated.d.ts +5 -5
  74. package/lib/types/platform-line.generated.js +5 -5
  75. package/lib/types/platform-services.js +4 -0
  76. package/lib/types/prompts.d.ts +9 -8
  77. package/lib/types/prompts.js +20 -1
  78. package/lib/types/result.d.ts +35 -0
  79. package/lib/types/result.js +25 -0
  80. package/lib/types/review-context.d.ts +8 -0
  81. package/lib/types/review-context.js +11 -0
  82. package/lib/types/run-registry.d.ts +2 -1
  83. package/lib/types/run-registry.js +37 -7
  84. package/lib/types/runtime/llm.d.ts +2 -2
  85. package/lib/types/runtime/llm.js +5 -8
  86. package/lib/types/runtime/platform.d.ts +37 -4
  87. package/lib/types/runtime/platform.js +40 -5
  88. package/lib/types/runtime/projections.d.ts +9 -4
  89. package/lib/types/runtime/projections.js +64 -28
  90. package/lib/types/section-selection.js +5 -0
  91. package/lib/types/skill-history.d.ts +29 -3
  92. package/lib/types/skill-history.js +30 -0
  93. package/lib/types/skill-store.d.ts +32 -4
  94. package/lib/types/skill-store.js +109 -15
  95. package/lib/types/subagent/channel.d.ts +1 -3
  96. package/lib/types/subagent/channel.js +2 -332
  97. package/lib/types/subagent/index.d.ts +2 -0
  98. package/lib/types/subagent/index.js +2 -0
  99. package/lib/types/subagent/kernel.d.ts +4 -0
  100. package/lib/types/subagent/kernel.js +234 -0
  101. package/lib/types/subagent/readiness.js +5 -7
  102. package/lib/types/subagent/run.d.ts +53 -0
  103. package/lib/types/subagent/run.js +125 -0
  104. package/lib/types/subagent/types.d.ts +3 -3
  105. package/lib/types/write-gates.js +11 -1
  106. package/lib/usage-B5a90TKv.js +1257 -0
  107. package/lib/write.js +1 -1
  108. package/package.json +37 -25
  109. package/lib/platform-Cc9cNt5j.js +0 -111
  110. package/lib/skill-health-DP8z9TPf.js +0 -2923
@@ -0,0 +1,1257 @@
1
+ import { c as transactIo, o as nodeEvolutionIo } from "./io-GxghO3Ip.js";
2
+ import { o as resolveCitations } from "./citations-CZKTUGQF.js";
3
+ import { G as SKILL_NAME_RE, i as DEFAULT_SKILL_LIMITS, u as CONTENT_SPLIT_HINT } from "./limits-C9jfvxBl.js";
4
+ import { n as isRecord } from "./guards-3f02mnf2.js";
5
+ import { join } from "node:path";
6
+ import { parse } from "yaml";
7
+ //#region lib/types/reference-rewrite.js
8
+ /**
9
+ * Reference re-homing plans (0.5.0 V1, design §16.7).
10
+ *
11
+ * A consolidation moves one skill's body under ANOTHER skill root, where every
12
+ * support-dir reference resolves against that other root (design §2.1). This
13
+ * module plans what has to happen to the support files and to the body's
14
+ * references for the move to leave no dangling link. Pure: the caller owns IO,
15
+ * decides the destination names, and decides whether the plan is applied (V2)
16
+ * or only reported (V1). Cross-skill rewriting is out of scope by design (§14) —
17
+ * a plan covers ONE body.
18
+ */
19
+ /**
20
+ * Provisional re-homing rule. The naming style for re-homed files is still an
21
+ * open decision (design §16.3 B5); this rule only fires on a COLLISION, where
22
+ * something has to give: a path that the target already occupies gets the source
23
+ * name as a prefix (`references/a.md` -> `references/<source>-a.md`). Nested
24
+ * destinations are deliberately avoided: the support listing is one level deep,
25
+ * so a file moved into a subdirectory would drop out of the listing entirely.
26
+ * @param sourceFiles - the moving skill's support files.
27
+ * @param targetFiles - the destination skill's support files.
28
+ * @param sourceName - the moving skill's name, used as the collision prefix.
29
+ * @returns the moves plus the paths that collided (for the report).
30
+ */
31
+ function planRehoming(sourceFiles, targetFiles, sourceName) {
32
+ const taken = new Set(targetFiles);
33
+ const collisions = [];
34
+ const moves = [];
35
+ for (const path of sourceFiles) {
36
+ if (!taken.has(path)) {
37
+ moves.push({
38
+ from: path,
39
+ to: path
40
+ });
41
+ continue;
42
+ }
43
+ collisions.push(path);
44
+ const cut = path.lastIndexOf("/");
45
+ const dir = cut < 0 ? "" : path.slice(0, cut + 1);
46
+ const name = path.slice(cut + 1);
47
+ let candidate = `${dir}${sourceName}-${name}`;
48
+ let counter = 2;
49
+ while (taken.has(candidate)) {
50
+ candidate = `${dir}${sourceName}-${counter}-${name}`;
51
+ counter += 1;
52
+ }
53
+ taken.add(candidate);
54
+ moves.push({
55
+ from: path,
56
+ to: candidate
57
+ });
58
+ }
59
+ return {
60
+ moves,
61
+ collisions
62
+ };
63
+ }
64
+ /**
65
+ * Plan the reference rewrites for one body that is moving into another root.
66
+ * @param input - the body, the MOVING skill's file list, the re-homing moves and
67
+ * the destination's file list (with the moved paths already included).
68
+ * @returns the edits, the cited files without a destination, and any target that
69
+ * the destination file list cannot prove (applying such a plan would dangle).
70
+ */
71
+ function planReferenceRewrite(input) {
72
+ const report = resolveCitations({
73
+ content: input.content,
74
+ file: "SKILL.md",
75
+ files: input.files
76
+ });
77
+ const byFrom = new Map(input.moves.map((move) => [move.from, move.to]));
78
+ const available = new Set(input.targetFiles);
79
+ const edits = [];
80
+ const unresolved = [];
81
+ const residual = /* @__PURE__ */ new Set();
82
+ const used = /* @__PURE__ */ new Set();
83
+ for (const ref of report.refs) {
84
+ if (ref.kind !== "citation" || ref.target === null) continue;
85
+ const move = byFrom.get(ref.target);
86
+ const to = move ?? ref.target;
87
+ if (move !== void 0) {
88
+ used.add(ref.target);
89
+ if (move !== ref.target) edits.push({
90
+ line: ref.line,
91
+ from: ref.target,
92
+ to: move,
93
+ raw: ref.raw
94
+ });
95
+ } else if (!report.dangling.some((entry) => entry.target === ref.target)) unresolved.push(ref.target);
96
+ if (!available.has(to)) residual.add(to);
97
+ }
98
+ return {
99
+ edits,
100
+ unresolved: [...new Set(unresolved)],
101
+ residualDangling: [...residual],
102
+ moves: input.moves.filter((move) => used.has(move.from))
103
+ };
104
+ }
105
+ /**
106
+ * Apply a plan's edits to the body (V2). Line-wise and literal: line N gets its
107
+ * FIRST occurrence of the recorded token replaced, everything else is copied
108
+ * byte for byte — no regex, so a token that happens to contain regex
109
+ * metacharacters cannot rewrite more than it matched.
110
+ * @param content - the body the plan was computed against.
111
+ * @param edits - the plan's edits.
112
+ * @returns the rewritten body (identical to the input when there is nothing to do).
113
+ */
114
+ function applyReferenceRewrite(content, edits) {
115
+ if (edits.length === 0) return content;
116
+ const byLine = /* @__PURE__ */ new Map();
117
+ for (const edit of edits) {
118
+ const list = byLine.get(edit.line);
119
+ if (list === void 0) byLine.set(edit.line, [edit]);
120
+ else list.push(edit);
121
+ }
122
+ const lines = content.split("\n");
123
+ for (const [lineNo, lineEdits] of byLine) {
124
+ const index = lineNo - 1;
125
+ const original = lines[index];
126
+ if (original === void 0) continue;
127
+ let next = original;
128
+ for (const edit of lineEdits) {
129
+ const at = next.indexOf(edit.raw);
130
+ if (at < 0) continue;
131
+ next = next.slice(0, at) + edit.to + next.slice(at + edit.raw.length);
132
+ }
133
+ lines[index] = next;
134
+ }
135
+ return lines.join("\n");
136
+ }
137
+ /**
138
+ * One-line, model-facing summary of a plan, for the consolidation refusal and
139
+ * for the V2 apply path's audit text.
140
+ * @param plan - the plan to describe.
141
+ * @returns a compact sentence naming counts, the moves and any residual risk.
142
+ */
143
+ function describeReferenceRewrite(plan) {
144
+ const renames = plan.moves.filter((move) => move.from !== move.to);
145
+ return `plan: ${[
146
+ `re-home ${plan.moves.length} file(s)`,
147
+ renames.length === 0 ? "" : `renamed: ${renames.map((move) => `${move.from}->${move.to}`).join(", ")}`,
148
+ `rewrite ${plan.edits.length} reference(s)`,
149
+ `residual dangling ${plan.residualDangling.length}`,
150
+ plan.unresolved.length === 0 ? "" : `no destination: ${plan.unresolved.slice(0, 5).join(", ")}`
151
+ ].filter((part) => part.length > 0).join("; ")}`;
152
+ }
153
+ //#endregion
154
+ //#region lib/types/support-refs.js
155
+ /**
156
+ * Support-directory references in a markdown body (009 kernel): references/…,
157
+ * templates/…, scripts/…, assets/… relative links — any extension and nested
158
+ * paths. Pure: who checks them and what the verdict is belongs to the caller.
159
+ * `..` traversal is a different defect class (path validation owns it) and is
160
+ * not a support link.
161
+ */
162
+ function supportRefs(content) {
163
+ const refs = [];
164
+ for (const match of content.matchAll(/(?<![A-Za-z0-9._/-])(?:references|templates|scripts|assets)\/[A-Za-z0-9._/-]+/g)) {
165
+ const ref = match[0];
166
+ if (ref.includes("..")) continue;
167
+ refs.push(ref);
168
+ }
169
+ return refs;
170
+ }
171
+ /**
172
+ * References that leave the skill root: parent traversals or absolute support paths.
173
+ * Extract must not silently treat these as relative support files; the caller reports
174
+ * them (bounded external copy is a separate, explicit policy).
175
+ * @param content - markdown body.
176
+ * @returns external-looking support references, de-duplicated in first-seen order.
177
+ */
178
+ function externalRefs(content) {
179
+ const refs = [];
180
+ for (const match of content.matchAll(/(?:^|[\s("'`])((?:\.\.\/)+[A-Za-z0-9._/-]+|\/[A-Za-z0-9._/-]+)/g)) {
181
+ const ref = match[1]?.replace(/[.,;:]+$/, "");
182
+ if (ref === void 0 || ref.length === 0 || refs.includes(ref)) continue;
183
+ refs.push(ref);
184
+ }
185
+ return refs;
186
+ }
187
+ //#endregion
188
+ //#region lib/types/frontmatter.js
189
+ /**
190
+ * Frontmatter parsing, normalization and validation for skill Markdown files.
191
+ *
192
+ * Split out of skill-store.ts (S2-1): pure functions over file text, no store
193
+ * state. skill-store.ts re-exports the same names it exported before the split,
194
+ * so the package export surface is unchanged.
195
+ */
196
+ /**
197
+ * Shared frontmatter block detection (P3-3 single owner): opening line `---`
198
+ * and closing line exactly `---`. Used by `parseFrontmatter`,
199
+ * `frontmatterCatalogInvalid` and `normalizeFrontmatter` so the three can
200
+ * never disagree about where the block ends (the loose `indexOf('\n---')`
201
+ * form matched `\n----` and was replaced by this strict line rule).
202
+ *
203
+ * V27 G2.1: both fence lines are matched EXACTLY, tolerating only a trailing
204
+ * `\r` — the same rule the upstream filesystem catalog uses
205
+ * (`skill-filesystem.parseFrontmatter`). The former `.trim()` comparison
206
+ * accepted ` --- `, so an indented fence loaded in the family while the
207
+ * platform ignored the file: family visibility split from platform visibility,
208
+ * which is exactly what a strict-YAML frontmatter is supposed to prevent.
209
+ */
210
+ /**
211
+ * S1.1 (v37 P1-4): the frontmatter block is split on LF and every line keeps its
212
+ * own `\r`, so the byte-preserving rebuild (`lines.join('\n')`) is exact. Line
213
+ * MATCHERS must therefore look at a CR-stripped view: JS `.` does not match `\r`,
214
+ * so `(.*)$` never reaches the end of a CRLF line.
215
+ * @param line - one block line, possibly CR-terminated.
216
+ * @returns the line without its trailing CR.
217
+ */
218
+ function withoutCr(line) {
219
+ return line.endsWith("\r") ? line.slice(0, -1) : line;
220
+ }
221
+ function frontmatterBlock(content) {
222
+ if (!content.trimStart().startsWith("---")) return null;
223
+ const firstBreak = content.indexOf("\n");
224
+ const nl = firstBreak > 0 && content[firstBreak - 1] === "\r" ? "\r\n" : "\n";
225
+ const lines = content.split("\n");
226
+ if ((lines[0] ?? "").replace(/\r$/, "") !== "---") return null;
227
+ let end = -1;
228
+ for (let i = 1; i < lines.length; i++) {
229
+ const line = lines[i];
230
+ if (line === void 0) continue;
231
+ if (line === "---" || line === "---\r") {
232
+ end = i;
233
+ break;
234
+ }
235
+ }
236
+ if (end < 0) return null;
237
+ return {
238
+ block: lines.slice(1, end).join("\n"),
239
+ lines,
240
+ end,
241
+ nl
242
+ };
243
+ }
244
+ /**
245
+ * Raw-line scan of a frontmatter block: the single owner of "which entries the
246
+ * strict catalog cannot load". `frontmatterCatalogInvalid` publishes it and
247
+ * `normalizeFrontmatter` decides each rewrite with the same predicate
248
+ * (`yamlPlainScalarNeedsQuotes`), so the audit verdict and the write path can
249
+ * never disagree. A9 (audit P2-12): the scan is ENDING-AGNOSTIC — lines are
250
+ * split on `\n` with the per-line CR stripped, exactly the iteration the
251
+ * rewrite path uses. The former split on the block's FIRST-LINE ending turned
252
+ * a mixed-ending block (first line CRLF, entries LF) into one unsplit chunk
253
+ * whose entries were all skipped, so an unquoted ` #` value read as CLEAN
254
+ * while the catalog silently dropped it and the next edit would have quoted
255
+ * it. Only single-line `key: value` entries are judged.
256
+ */
257
+ function unsafeFrontmatterEntries(block) {
258
+ const found = [];
259
+ for (const rawLine of block.split("\n")) {
260
+ const match = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(withoutCr(rawLine));
261
+ if (!match) continue;
262
+ const key = match[1];
263
+ if (key === void 0) continue;
264
+ const value = (match[2] ?? "").trim();
265
+ if (yamlPlainScalarNeedsQuotes(value)) found.push({
266
+ key,
267
+ value
268
+ });
269
+ }
270
+ return found;
271
+ }
272
+ /**
273
+ * Frontmatter fields the platform catalog reads as STRINGS (`stringField` /
274
+ * `optionalString` in `skill-filesystem`): any other YAML type reads as
275
+ * ABSENT there, and an absent `name`/`description` makes the catalog ignore the
276
+ * whole file. The family publishes text for these keys anyway (its lenient
277
+ * read), which is the one split a write must not create.
278
+ */
279
+ const PLATFORM_STRING_FIELDS = [
280
+ "name",
281
+ "description",
282
+ "whenToUse"
283
+ ];
284
+ /**
285
+ * Frontmatter values as the STRICT platform catalog reads them — the `yaml`
286
+ * package (YAML 1.2 core schema, the same dependency the platform's
287
+ * skill-filesystem parses with — see the import note above),
288
+ * the parser `normalizeFrontmatter` also verifies rewrites with — or `null`
289
+ * when the block is not loadable as a YAML mapping. Also reports the platform
290
+ * string fields whose value is not a string ({@link PlatformStringSplit}).
291
+ *
292
+ * Scalars publish their text (`name`, `description`, `whenToUse` are strings by
293
+ * contract; a number/boolean-shaped value keeps the text the family always
294
+ * published), a flow or block sequence publishes its inline `[a, b]` form
295
+ * (`relatedSkillNames` scans names out of it), and a nested mapping publishes
296
+ * nothing — no consumer in this family reads one, and a lossy string could be
297
+ * picked up by a routing field. A string value is trimmed: YAML's block-scalar
298
+ * chomping appends a newline that the family's single-line routing fields never
299
+ * carried.
300
+ */
301
+ function strictFrontmatterValues(block) {
302
+ if (block.trim() === "") return {
303
+ values: /* @__PURE__ */ new Map(),
304
+ split: []
305
+ };
306
+ let loaded;
307
+ try {
308
+ loaded = parse(block);
309
+ } catch {
310
+ return null;
311
+ }
312
+ if (loaded === null || loaded === void 0) return {
313
+ values: /* @__PURE__ */ new Map(),
314
+ split: []
315
+ };
316
+ if (typeof loaded !== "object" || Array.isArray(loaded)) return null;
317
+ const values = /* @__PURE__ */ new Map();
318
+ const split = [];
319
+ let metadata;
320
+ for (const [key, value] of Object.entries(loaded)) {
321
+ if (typeof value !== "string" && PLATFORM_STRING_FIELDS.includes(key)) split.push({
322
+ key,
323
+ kind: value === null || value === void 0 ? "null" : Array.isArray(value) ? "sequence" : typeof value === "object" ? "mapping" : "scalar"
324
+ });
325
+ if (typeof value === "string") {
326
+ values.set(key, value.trim());
327
+ continue;
328
+ }
329
+ if (typeof value === "number" || typeof value === "boolean") {
330
+ values.set(key, String(value));
331
+ continue;
332
+ }
333
+ if (Array.isArray(value)) {
334
+ values.set(key, `[${value.map((item) => String(item)).join(", ")}]`);
335
+ continue;
336
+ }
337
+ if (key === "metadata" && isRecord(value)) {
338
+ metadata = value;
339
+ continue;
340
+ }
341
+ }
342
+ return {
343
+ values,
344
+ split,
345
+ metadata
346
+ };
347
+ }
348
+ /**
349
+ * Lenient line scan, used only for a block the strict parser rejects: the
350
+ * family keeps routing a legacy file the platform refuses, and
351
+ * `catalogInvalid` reports the split instead of hiding it. Values are trimmed
352
+ * and unquoted exactly as before.
353
+ */
354
+ function lenientFrontmatterValues(block, nl) {
355
+ const values = /* @__PURE__ */ new Map();
356
+ const blockLines = block.split(nl);
357
+ for (let i = 0; i < blockLines.length; i += 1) {
358
+ const line = withoutCr(blockLines[i] ?? "");
359
+ const match = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(line);
360
+ if (!match) continue;
361
+ const [, key, value] = match;
362
+ if (key === void 0 || value === void 0) continue;
363
+ const header = /^([>|])[+-]?\d*$/.exec(value.trim());
364
+ if (header !== null) {
365
+ const fold = header[1] === ">";
366
+ const parts = [];
367
+ let scan = i + 1;
368
+ for (; scan < blockLines.length; scan += 1) {
369
+ const raw = blockLines[scan] ?? "";
370
+ if (raw.trim() === "") {
371
+ parts.push("");
372
+ continue;
373
+ }
374
+ if (!/^\s/.test(raw)) break;
375
+ parts.push(raw.trim());
376
+ }
377
+ while (parts.length > 0 && parts[parts.length - 1] === "") parts.pop();
378
+ let folded = "";
379
+ for (const part of parts) {
380
+ if (part === "") {
381
+ if (folded !== "" && !folded.endsWith("\n")) folded += "\n";
382
+ continue;
383
+ }
384
+ if (folded === "" || folded.endsWith("\n")) folded += part;
385
+ else folded += ` ${part}`;
386
+ }
387
+ values.set(key, (fold ? folded : parts.join("\n")).trim());
388
+ i = scan - 1;
389
+ continue;
390
+ }
391
+ values.set(key, value.trim().replace(/^["']|["']$/g, ""));
392
+ }
393
+ return values;
394
+ }
395
+ /**
396
+ * The single read of a SKILL.md frontmatter block: values, body and every
397
+ * strict-catalog signal, computed once. `null` only when the file has no
398
+ * frontmatter block; the body may be empty. {@link parseFrontmatter} and
399
+ * {@link frontmatterCatalogInvalid} are its two projections.
400
+ *
401
+ * @param content - the SKILL.md text.
402
+ * @returns the block read, or `null` when there is no block.
403
+ */
404
+ function readFrontmatterBlock(content) {
405
+ const found = frontmatterBlock(content);
406
+ if (!found) return null;
407
+ const body = found.lines.slice(found.end + 1).join("\n").trim();
408
+ const strict = strictFrontmatterValues(found.block);
409
+ const values = strict?.values ?? lenientFrontmatterValues(found.block, found.nl);
410
+ const frontmatter = {};
411
+ for (const [key, value] of values) frontmatter[key] = value;
412
+ return {
413
+ frontmatter,
414
+ body,
415
+ unsafeValues: unsafeFrontmatterEntries(found.block),
416
+ strictFailed: strict === null,
417
+ platformStringSplit: strict?.split ?? [],
418
+ metadata: strict?.metadata
419
+ };
420
+ }
421
+ /**
422
+ * Parse a SKILL.md: its frontmatter values and body, or `null` when the file
423
+ * has no frontmatter block or no body. Every consumer of frontmatter values
424
+ * goes through here — the write path's validation, `list()`'s published
425
+ * description, `relatedSkillNames` and the audit — so all of them read the same
426
+ * bytes the same way.
427
+ *
428
+ * @param content - the SKILL.md text.
429
+ * @returns the read, or `null` when there is no block or no body.
430
+ */
431
+ function parseFrontmatter(content) {
432
+ const read = readFrontmatterBlock(content);
433
+ if (!read || !read.body) return null;
434
+ return {
435
+ frontmatter: read.frontmatter,
436
+ body: read.body,
437
+ unsafeValues: read.unsafeValues,
438
+ metadata: read.metadata,
439
+ catalogInvalid: read.strictFailed || read.unsafeValues.length > 0 || read.platformStringSplit.length > 0,
440
+ platformStringSplit: read.platformStringSplit
441
+ };
442
+ }
443
+ /**
444
+ * Whether this file's frontmatter is valid as written for the strict platform
445
+ * catalog (see `FrontmatterRead.catalogInvalid`). Body-independent (a body-less
446
+ * file is still judged), and derived from the same read as `parseFrontmatter` —
447
+ * so the audit's verdict and the values the family publishes for one file can
448
+ * never disagree (V27 G2.1).
449
+ *
450
+ * @param content - the SKILL.md text.
451
+ * @returns `true` when the strict parser rejects the block or an unquoted value would read as something else.
452
+ */
453
+ function frontmatterCatalogInvalid(content) {
454
+ const read = readFrontmatterBlock(content);
455
+ if (read !== null) return read.strictFailed || read.unsafeValues.length > 0 || read.platformStringSplit.length > 0;
456
+ return frontmatterBlock(content.replace(/^\uFEFF/, "").replace(/\r\n/g, "\n")) !== null;
457
+ }
458
+ /** YAML plain-scalar hazards that make an UNQUOTED frontmatter value
459
+ * unloadable to the platform catalog (strict YAML parser): `: ` (mapping
460
+ * separator), ` #` (comment start), a trailing `:` (a mapping marker),
461
+ * or a leading YAML indicator. The evolution `parseFrontmatter` is
462
+ * deliberately lenient, so violations silently split family-visibility from
463
+ * platform-visibility (0.3.11 inkos-harness case: the description carried
464
+ * "…: " and the catalog dropped the whole skill). Already-quoted values and
465
+ * well-formed flow collections (`[a, b]` / `{a: b}`) are considered safe.
466
+ * 0.3.16 (E-47): null/bool/number-shaped plain scalars are flagged too — they
467
+ * parse as booleans/numbers on the platform while the family keeps the string
468
+ * (a `description: true` split-brain).
469
+ * This rule is only the FAST PATH — the write path re-verifies every rewrite
470
+ * with the real YAML parser (see normalizeFrontmatter), so an incomplete
471
+ * approximation can never corrupt a multiline flow value (P3-4). */
472
+ function yamlPlainScalarNeedsQuotes(value) {
473
+ if (value.length === 0) return false;
474
+ if (value.length >= 2 && (value.startsWith("\"") && value.endsWith("\"") || value.startsWith("'") && value.endsWith("'"))) return false;
475
+ if (/^\[.*\]$/.test(value) || /^\{.*\}$/.test(value)) return false;
476
+ if (/^[>|][+-]?\d*$/.test(value)) return false;
477
+ if (value.includes(": ")) return true;
478
+ if (value.includes(" #")) return true;
479
+ if (value.endsWith(":")) return true;
480
+ if (/^(?:null|true|false|~)$/i.test(value)) return true;
481
+ if (/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?$/.test(value)) return true;
482
+ if (/^0x[0-9a-f]+$/i.test(value)) return true;
483
+ if (/^0o[0-7]+$/.test(value)) return true;
484
+ if (/^(?:[-+]?\.inf|\.nan)$/i.test(value)) return true;
485
+ if (/^[-?:,[\]{}#&*!|>'"%@`\s]/.test(value)) return true;
486
+ return false;
487
+ }
488
+ /**
489
+ * Normalize a SKILL.md frontmatter block into catalog-loadable YAML: values
490
+ * that YAML forbids unquoted get quotes — double quotes normally, single
491
+ * quotes (with `''` doubling) when the value contains `"` or `\` (both legal
492
+ * unescaped inside single-quoted YAML). Idempotent; only single-line
493
+ * `key: value` entries are touched; body text is never modified; line-ending
494
+ * style is preserved. **Every rewrite is re-verified with the real YAML
495
+ * parser** (`yaml` — the package the platform's skill-filesystem catalog parses
496
+ * with, YAML 1.2 core schema; PLAN S2.1, 2026-09-16 — the former "js-yaml, the
497
+ * same parser" claim was false: js-yaml speaks YAML 1.1 full and diverged on
498
+ * dates, timestamps and 1.1 int forms): if the
499
+ * rewritten block no longer parses, or a rewritten value's parsed content
500
+ * differs from the original, the rewrite is rolled back and reported in
501
+ * `issues` (fail-loud, never a silent value corruption — P3-4).
502
+ *
503
+ * V10-02 (P2-3): the rewrite decision is PER LINE — each entry parses its own
504
+ * value, so a duplicated key can never route one entry's unsafe value into a
505
+ * different line's rewrite (the old key→Map lookup rewrote the FIRST (safe)
506
+ * line with the SECOND line's quoted value, and the last-wins YAML reader
507
+ * masked the damage). A duplicated key is itself invalid input and is
508
+ * reported in `issues` (the write path refuses) instead of being rewritten.
509
+ */
510
+ function normalizeFrontmatter(content) {
511
+ const block = frontmatterBlock(content);
512
+ if (!block) return {
513
+ content,
514
+ changed: false,
515
+ fields: [],
516
+ issues: []
517
+ };
518
+ const { lines, end } = block;
519
+ const fields = [];
520
+ const issues = [];
521
+ const seen = /* @__PURE__ */ new Set();
522
+ const originalValues = /* @__PURE__ */ new Map();
523
+ let changed = false;
524
+ for (let i = 1; i < end; i++) {
525
+ const raw = lines[i];
526
+ if (raw === void 0) continue;
527
+ const match = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(withoutCr(raw));
528
+ if (!match) continue;
529
+ const key = match[1];
530
+ if (key === void 0) continue;
531
+ const value = (match[2] ?? "").trim();
532
+ if (seen.has(key)) {
533
+ issues.push(`${key}: duplicate frontmatter key — remove the repeated entry and retry`);
534
+ continue;
535
+ }
536
+ seen.add(key);
537
+ if (!yamlPlainScalarNeedsQuotes(value)) continue;
538
+ if (/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/.test(value)) {
539
+ issues.push(`${key}: value contains control characters — clean them manually`);
540
+ continue;
541
+ }
542
+ lines[i] = `${key}: ${value.includes("\"") || value.includes("\\") ? `'${value.replace(/'/g, "''")}'` : `"${value}"`}${raw.endsWith("\r") ? "\r" : ""}`;
543
+ originalValues.set(key, value);
544
+ fields.push(key);
545
+ changed = true;
546
+ }
547
+ if (issues.length > 0) return {
548
+ content,
549
+ changed: false,
550
+ fields: [],
551
+ issues
552
+ };
553
+ if (!changed) return {
554
+ content,
555
+ changed: false,
556
+ fields: [],
557
+ issues
558
+ };
559
+ const rewrittenBlock = lines.slice(1, end).join("\n");
560
+ try {
561
+ const parsed = parse(rewrittenBlock);
562
+ for (const key of fields) if (String(parsed[key]) !== originalValues.get(key)) throw new Error(`rewritten value for ${key} differs from the original`);
563
+ return {
564
+ content: lines.join("\n"),
565
+ changed: true,
566
+ fields,
567
+ issues
568
+ };
569
+ } catch (error) {
570
+ return {
571
+ content,
572
+ changed: false,
573
+ fields: [],
574
+ issues: [`frontmatter rewrite verification failed (${error instanceof Error ? error.message : String(error)}) — quoting skipped; wrap this value manually`]
575
+ };
576
+ }
577
+ }
578
+ /**
579
+ * Skill names referenced by a SKILL.md's `related_skills` frontmatter
580
+ * (B-line G3, rc.44): the single parsing source for the quality references
581
+ * factor and the learning-graph edges. The DSH frontmatter parser keeps the
582
+ * YAML value as a string (`"[a, b]"`), so names are scanned out of it; each
583
+ * must satisfy the skill-name shape and the referencing skill itself is
584
+ * excluded. Pure and deduplicated.
585
+ */
586
+ function relatedSkillNames(content, exclude) {
587
+ const parsed = parseFrontmatter(content);
588
+ if (!parsed) return [];
589
+ const nestedHost = parsed.metadata?.["hermes"];
590
+ const nestedRaw = isRecord(nestedHost) ? nestedHost["related_skills"] : void 0;
591
+ const flat = parsed.frontmatter["related_skills"];
592
+ const raw = typeof flat === "string" ? flat : Array.isArray(nestedRaw) ? `[${nestedRaw.map((item) => String(item)).join(", ")}]` : void 0;
593
+ if (typeof raw !== "string") return [];
594
+ const names = /* @__PURE__ */ new Set();
595
+ for (const match of Array.from(raw.matchAll(/(?<![A-Za-z0-9_-])[a-z0-9][a-z0-9-]*(?![A-Za-z0-9_-])/g))) {
596
+ const target = match[0];
597
+ if (target && SKILL_NAME_RE.test(target) && target !== exclude) names.add(target);
598
+ }
599
+ return [...names];
600
+ }
601
+ /** S1.2 (v37 P2-1): the content limit applies to the bytes that LAND ON DISK.
602
+ * Every write normalizes with `trimEnd() + '\n'`, so judging the raw argument let
603
+ * a 100_000-character body with no trailing newline land as 100_001 bytes — and
604
+ * every later patch/update of that skill was then refused, which made it
605
+ * unmaintainable through `skill_manage` with no repair path at all. */
606
+ /** The bytes that land on disk for a SKILL.md write — the ONE accounting basis
607
+ * shared by the content limit and the cost estimate (design §5.2). */
608
+ function skillMdOnDisk(content) {
609
+ return content.trimEnd() + "\n";
610
+ }
611
+ /** Whether `content` would exceed `limit` once written. */
612
+ function exceedsContentLimit(content, limit) {
613
+ return skillMdOnDisk(content).length > limit;
614
+ }
615
+ /** S1.2: the repair path — a write that makes an already-over-limit file smaller.
616
+ * Only a NET SHRINK is exempt; an equal or larger write stays refused. */
617
+ function shrinksOverLimit(next, current, limit) {
618
+ if (current === null || current === void 0 || !exceedsContentLimit(current, limit)) return false;
619
+ return skillMdOnDisk(next).length < skillMdOnDisk(current).length;
620
+ }
621
+ /**
622
+ * Synthesize a missing SKILL.md header at the write boundary.
623
+ *
624
+ * A model-authored create/update whose body starts with `# Title` is valid Markdown but the
625
+ * skill writer rejects it before any content check. Repair only the truly headerless shape: an
626
+ * existing fence is passed through byte-identical, even when it is malformed, so this helper
627
+ * cannot mask a header error that the validator should report. The caller owns the audit notice.
628
+ * @param content - the model-authored SKILL.md text.
629
+ * @param name - the validated skill name used for the `name:` field.
630
+ * @param description - optional description; otherwise derived from the first heading/prose.
631
+ * @returns the write text and whether a header was synthesized.
632
+ */
633
+ function ensureSkillFrontmatter(content, name, description) {
634
+ if (frontmatterBlock(content) !== null || content.trimStart().startsWith("---")) return {
635
+ content,
636
+ repaired: false
637
+ };
638
+ const body = content.replace(/^\uFEFF/, "").replace(/^(?:[ \t]*\r?\n)+/, "");
639
+ const heading = /^#{1,6}\s+(.+?)\s*$/m.exec(body)?.[1];
640
+ const firstLine = body.split(/\r?\n/).map((line) => line.trim()).find((line) => line !== "" && !line.startsWith("#")) ?? "";
641
+ const source = (description?.trim() || heading || firstLine || name).replace(/\s+/g, " ").trim();
642
+ const clipped = source.length > 58 ? source.slice(0, 57) + "…" : source;
643
+ const summary = /[.。!?!?]$/.test(clipped) ? clipped : clipped + ".";
644
+ const encoded = yamlPlainScalarNeedsQuotes(summary) ? JSON.stringify(summary) : summary;
645
+ return {
646
+ content: [
647
+ "---",
648
+ `name: ${name}`,
649
+ `description: ${encoded}`,
650
+ "version: 0.1.0",
651
+ "author: Hermes",
652
+ "---",
653
+ ""
654
+ ].join("\n") + "\n" + body,
655
+ repaired: true
656
+ };
657
+ }
658
+ function validateFrontmatter(content, expectedName, limits = DEFAULT_SKILL_LIMITS, current) {
659
+ const parsed = parseFrontmatter(content);
660
+ if (!parsed) return "SKILL.md 必须以 `---` 行开头,用另一个完全相同的 `---` 行结束 frontmatter(只容忍结尾的 `\\r`),并在其下包含正文。";
661
+ const unreadable = parsed.platformStringSplit.filter((entry) => entry.kind === "sequence" || entry.kind === "mapping");
662
+ if (unreadable.length > 0) return `Frontmatter 字段 ${unreadable.map((entry) => `"${entry.key}" (a YAML ${entry.kind})`).join(", ")} 必须是字符串:平台技能目录会把这种字段当作缺失,并忽略整个文件。请写成纯文本,或用双引号包住取值以保持字面内容。`;
663
+ if (!parsed.frontmatter.name) return "Frontmatter 必须包含 name 字段。";
664
+ if (!SKILL_NAME_RE.test(parsed.frontmatter.name)) return `技能名「${parsed.frontmatter.name}」不合法:请只用小写字母、数字和连字符。`;
665
+ if (parsed.frontmatter.name.length > limits.maxNameLength) return `技能名超过 ${limits.maxNameLength} 个字符。`;
666
+ if (expectedName && parsed.frontmatter.name !== expectedName) return `Frontmatter 里的 name「${parsed.frontmatter.name}」与目标技能「${expectedName}」不一致。`;
667
+ if (!parsed.frontmatter.description) return "Frontmatter 必须包含 description 字段。";
668
+ if (parsed.frontmatter.description.length > limits.maxDescriptionLength) return `description 超过 ${limits.maxDescriptionLength} 个字符。`;
669
+ if (exceedsContentLimit(content, limits.maxSkillContentChars) && !shrinksOverLimit(content, current, limits.maxSkillContentChars)) return `SKILL.md 内容超过 ${limits.maxSkillContentChars} 个字符。${CONTENT_SPLIT_HINT}`;
670
+ return null;
671
+ }
672
+ /**
673
+ * Advisory authoring feedback (P0): evaluate frontmatter against the
674
+ * authoring bar WITHOUT changing platform validation semantics. The bar is
675
+ * the quality target, `validateFrontmatter`'s limits are the compatibility
676
+ * floor, and this bridge layer tells the model when its text would be
677
+ * truncated or route-poor instead of silently shipping it.
678
+ */
679
+ function authoringFeedback(frontmatter) {
680
+ const description = frontmatter.description ?? "";
681
+ const over60 = description.length > 60;
682
+ const hasColon = description.includes(":");
683
+ const lines = [];
684
+ lines.push(over60 ? `描述为 ${description.length}/60 个字符 —— 超过 60 字符的作者规范上限(Hermes 标准;技能目录会按平台配置的上限截断)。` : `描述为 ${description.length}/60 个字符 —— 在作者规范上限之内。`);
685
+ if (hasColon) lines.push("描述里含冒号 —— 请用双引号把整个取值包起来。");
686
+ return {
687
+ descriptionChars: description.length,
688
+ over60,
689
+ hasColon,
690
+ lines
691
+ };
692
+ }
693
+ /** A1-15 (v18) / P2-2 (v19): the io layer marks an error `committed: true` when
694
+ * the rename landed and only the directory fsync failed. Every single-file
695
+ * writer must treat that as "written, durability unconfirmed" — never as a
696
+ * plain failure (which a caller would retry, or a two-phase caller roll back).
697
+ * v28 G2.1 (EVO-IO-05): this is a delegation to the seam's own
698
+ * `isCommittedWarning` — the marker predicate has exactly one definition. */
699
+ //#endregion
700
+ //#region lib/types/document-body.js
701
+ /**
702
+ * What the panel shows when it renders one version as a document.
703
+ *
704
+ * Two decisions, both made here so the preview and the rendered diff cannot drift apart:
705
+ *
706
+ * - FRONTMATTER IS NOT DOCUMENT TEXT. A SKILL.md opens with a YAML block; the renderer read its
707
+ * closing `---` as a setext underline, so the metadata line became the document's biggest heading
708
+ * and the real title sat below it (measured on the installed panel 2026-09-28). The block is
709
+ * stripped for DISPLAY only: the raw view and the body route still carry every byte, and the
710
+ * panel already shows the name and description on the row and in the left column.
711
+ * - STRIPPING FAILS OPEN. Only a block that the family's own reader accepts is removed. A document
712
+ * whose text merely starts with a thematic break, a block with no closing line, or a frontmatter
713
+ * whose body is empty is returned UNCHANGED — showing a document's first line is always better
714
+ * than showing nothing.
715
+ *
716
+ * `readingStats` exists for the other half of the reader's honesty: a preview that stops early has
717
+ * to be able to say HOW much it is not showing.
718
+ * @module @lmzhen/dsh-evolution-core/document-body
719
+ */
720
+ /**
721
+ * The document a reader sees: the body without its leading frontmatter block.
722
+ * @param content - the stored bytes of one version.
723
+ * @returns the text to render; unchanged when there is no frontmatter the reader accepts.
724
+ */
725
+ function displayBodyOf(content) {
726
+ const block = frontmatterBlock(content);
727
+ if (block === null) return content;
728
+ if (parseFrontmatter(content) === null) return content;
729
+ return block.lines.slice(block.end + 1).join("\n").replace(/^\s*\n/, "");
730
+ }
731
+ /**
732
+ * How much of a version the panel is showing.
733
+ * @param full - the whole stored text.
734
+ * @param shown - the part the route handed over.
735
+ * @returns the counts, so the panel can say what it is not showing.
736
+ */
737
+ function readingStats(full, shown) {
738
+ return {
739
+ totalChars: full.length,
740
+ shownChars: shown.length,
741
+ truncated: shown.length < full.length
742
+ };
743
+ }
744
+ /**
745
+ * The H2 sections of a body, in document order — the ONE scan (G3).
746
+ *
747
+ * Both the restructure candidate list and the store anchor validation call this function, so a
748
+ * candidate can only name a heading that exists EXACTLY ONCE and has content: the two rejections a
749
+ * hand-written anchor used to hit ("no such heading", "ambiguous anchor") stop being reachable.
750
+ * H2 is the section boundary (a section spans to the next H2 or EOF), matching the store.
751
+ * @param body - the markdown after the frontmatter block.
752
+ * @returns one row per H2 heading, with `count` filled in a second pass.
753
+ */
754
+ function h2Sections(body) {
755
+ const lines = body.split(String.fromCharCode(10));
756
+ const rows = [];
757
+ for (let i = 0; i < lines.length; i += 1) {
758
+ const match = /^#{2}\s+(.+?)\s*$/.exec(lines[i] ?? "");
759
+ if (match === null) continue;
760
+ const title = (match[1] ?? "").trim();
761
+ let end = lines.length;
762
+ for (let j = i + 1; j < lines.length; j += 1) if (/^#{2}\s/.test(lines[j] ?? "")) {
763
+ end = j;
764
+ break;
765
+ }
766
+ rows.push({
767
+ title,
768
+ start: i,
769
+ end,
770
+ count: 0
771
+ });
772
+ }
773
+ for (const row of rows) row.count = rows.filter((other) => other.title === row.title).length;
774
+ return rows;
775
+ }
776
+ //#endregion
777
+ //#region lib/types/section-selection.js
778
+ const LF = String.fromCharCode(10);
779
+ /**
780
+ * Select whole H2 sections or exact content sub-blocks from one body.
781
+ *
782
+ * The H2 scan is document-body's h2Sections, so restructure and extract share
783
+ * one boundary rule. A start/end pair selects an inclusive, contiguous run of
784
+ * exact lines inside that heading; it cannot select the heading itself, overlap
785
+ * another request, or leave a selected range empty.
786
+ * @param body - markdown after frontmatter.
787
+ * @param requests - exact heading plus optional start/end line pairs.
788
+ * @returns selected ranges in request order, or the first refusal.
789
+ */
790
+ function selectSections(body, requests) {
791
+ const lines = body.split(LF);
792
+ const sections = h2Sections(body);
793
+ const selected = [];
794
+ for (let requestIndex = 0; requestIndex < requests.length; requestIndex += 1) {
795
+ const request = requests[requestIndex];
796
+ if (request === void 0) continue;
797
+ const wanted = request.heading.trim();
798
+ const matching = sections.filter((section) => section.title === wanted);
799
+ if (matching.length === 0) return {
800
+ ok: false,
801
+ code: "heading-missing",
802
+ message: "no \"## " + wanted + "\" heading in the body"
803
+ };
804
+ if (matching.length > 1) return {
805
+ ok: false,
806
+ code: "heading-ambiguous",
807
+ message: "heading \"## " + wanted + "\" appears " + matching.length + " times (ambiguous anchor)"
808
+ };
809
+ const section = matching[0];
810
+ if (section === void 0) return {
811
+ ok: false,
812
+ code: "heading-missing",
813
+ message: "no \"## " + wanted + "\" heading in the body"
814
+ };
815
+ if (selected.some((entry) => entry.start === section.start)) return {
816
+ ok: false,
817
+ code: "heading-duplicate",
818
+ message: "heading \"## " + wanted + "\" is moved twice"
819
+ };
820
+ if (!(request.start !== void 0 || request.end !== void 0)) {
821
+ if (section.end === section.start + 1) return {
822
+ ok: false,
823
+ code: "heading-empty",
824
+ message: "heading \"## " + wanted + "\" has an empty section"
825
+ };
826
+ if (selected.some((entry) => section.start < entry.end && section.end > entry.start)) return {
827
+ ok: false,
828
+ code: "part-anchor-overlaps",
829
+ message: "heading \"## " + wanted + "\" selection overlaps another selected block"
830
+ };
831
+ selected.push({
832
+ heading: wanted,
833
+ start: section.start,
834
+ end: section.end,
835
+ text: lines.slice(section.start, section.end).join(LF),
836
+ requestIndex
837
+ });
838
+ continue;
839
+ }
840
+ if (request.start === void 0 || request.end === void 0) return {
841
+ ok: false,
842
+ code: "part-anchor-incomplete",
843
+ message: "heading \"## " + wanted + "\" needs both start and end anchors"
844
+ };
845
+ const startMatches = [];
846
+ const endMatches = [];
847
+ for (let index = 0; index < lines.length; index += 1) {
848
+ if (index <= section.start || index >= section.end) continue;
849
+ if (lines[index] === request.start) startMatches.push(index);
850
+ if (lines[index] === request.end) endMatches.push(index);
851
+ }
852
+ if (startMatches.length !== 1) return {
853
+ ok: false,
854
+ code: "part-anchor-not-found",
855
+ message: "heading \"## " + wanted + "\" start anchor must match exactly one content line"
856
+ };
857
+ if (endMatches.length !== 1) return {
858
+ ok: false,
859
+ code: "part-anchor-not-found",
860
+ message: "heading \"## " + wanted + "\" end anchor must match exactly one content line"
861
+ };
862
+ const start = startMatches[0];
863
+ const end = endMatches[0];
864
+ if (start === void 0 || end === void 0 || start > end) return {
865
+ ok: false,
866
+ code: "part-anchor-order",
867
+ message: "heading \"## " + wanted + "\" start anchor is after end anchor"
868
+ };
869
+ if (selected.some((entry) => start < entry.end && end + 1 > entry.start)) return {
870
+ ok: false,
871
+ code: "part-anchor-overlaps",
872
+ message: "heading \"## " + wanted + "\" selection overlaps another selected block"
873
+ };
874
+ selected.push({
875
+ heading: wanted,
876
+ start,
877
+ end: end + 1,
878
+ text: lines.slice(start, end + 1).join(LF),
879
+ requestIndex,
880
+ anchorStart: request.start,
881
+ anchorEnd: request.end
882
+ });
883
+ }
884
+ return {
885
+ ok: true,
886
+ sections: selected
887
+ };
888
+ }
889
+ //#endregion
890
+ //#region lib/types/usage.js
891
+ /**
892
+ * Skill usage telemetry sidecar: `$DSH_HOME/skills/.usage.json`.
893
+ * Format-compatible with Hermes Agent / hermes-claw core fields.
894
+ */
895
+ function usageFile(root) {
896
+ return join(root, ".usage.json");
897
+ }
898
+ function emptyRecord() {
899
+ return {
900
+ created_by: null,
901
+ use_count: 0,
902
+ view_count: 0,
903
+ patch_count: 0,
904
+ last_used_at: null,
905
+ last_viewed_at: null,
906
+ last_patched_at: null,
907
+ created_at: (/* @__PURE__ */ new Date()).toISOString(),
908
+ state: "active",
909
+ pinned: false,
910
+ archived_at: null
911
+ };
912
+ }
913
+ /** A timestamp passes only when `Date.parse` yields a finite epoch (N-3): a bare
914
+ * string check let garbage like "not-a-date" propagate as Invalid Date → NaN
915
+ * into quality math and lifecycle comparisons. */
916
+ const validTimestamp = (value) => typeof value === "string" && Number.isFinite(Date.parse(value));
917
+ const nullableTimestamp = (value) => value === null || validTimestamp(value);
918
+ /**
919
+ * Field-level normalization for one sidecar record (rc.42 audit P2-3): the
920
+ * spread used to copy any junk through verbatim, so a corrupted file could
921
+ * carry `use_count: "3"` into the quality math and lifecycle comparisons as
922
+ * NaN. Every field falls back to its `emptyRecord()` baseline unless it has
923
+ * exactly the declared type; an invalid `created_at` anchors the age clock at
924
+ * now (first-sight defer semantics for a record whose age is unknowable).
925
+ * Timestamps additionally require a parseable date (N-3): `"not-a-date"`
926
+ * would otherwise survive the type check as Invalid Date.
927
+ * Pure — exported for unit tests; `loadUsage` is the production caller.
928
+ */
929
+ function normalizeUsageRecord(record) {
930
+ const base = emptyRecord();
931
+ if (!record || typeof record !== "object" || Array.isArray(record)) return base;
932
+ const raw = record;
933
+ const num = (value, fallback) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : fallback;
934
+ const bool = (value, fallback) => typeof value === "boolean" ? value : fallback;
935
+ return {
936
+ ...raw,
937
+ created_by: typeof raw.created_by === "string" ? raw.created_by : null,
938
+ use_count: num(raw.use_count, base.use_count),
939
+ view_count: num(raw.view_count, base.view_count),
940
+ patch_count: num(raw.patch_count, base.patch_count),
941
+ last_used_at: nullableTimestamp(raw.last_used_at) ? raw.last_used_at : base.last_used_at,
942
+ last_viewed_at: nullableTimestamp(raw.last_viewed_at) ? raw.last_viewed_at : base.last_viewed_at,
943
+ last_patched_at: nullableTimestamp(raw.last_patched_at) ? raw.last_patched_at : base.last_patched_at,
944
+ created_at: validTimestamp(raw.created_at) ? raw.created_at : base.created_at,
945
+ state: raw.state === "stale" || raw.state === "archived" ? raw.state : "active",
946
+ pinned: bool(raw.pinned, base.pinned),
947
+ archived_at: nullableTimestamp(raw.archived_at) ? raw.archived_at : base.archived_at,
948
+ quality_score: typeof raw.quality_score === "number" && Number.isFinite(raw.quality_score) ? raw.quality_score : void 0,
949
+ quality_warn: typeof raw.quality_warn === "boolean" ? raw.quality_warn : void 0,
950
+ feedback_score: typeof raw.feedback_score === "number" && Number.isFinite(raw.feedback_score) ? raw.feedback_score : void 0,
951
+ feedback_warn: typeof raw.feedback_warn === "boolean" ? raw.feedback_warn : void 0,
952
+ support_reads: normalizeSupportReads(raw.support_reads)
953
+ };
954
+ }
955
+ /** Sidecar bound: a pathological path set must not grow the usage file forever. */
956
+ const MAX_SUPPORT_READ_PATHS = 200;
957
+ /** Sanitize the per-support-file read counts: non-negative finite numbers under
958
+ * non-empty, bounded, non-traversal path keys. An unusable value drops the whole
959
+ * map (absence over a poisoned count). */
960
+ function normalizeSupportReads(value) {
961
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return void 0;
962
+ const out = {};
963
+ let kept = 0;
964
+ for (const [key, count] of Object.entries(value)) {
965
+ if (kept >= 200) break;
966
+ if (key === "" || key.length > 200 || key.split("/").includes("..")) continue;
967
+ if (typeof count !== "number" || !Number.isFinite(count) || count < 0) continue;
968
+ out[key] = count;
969
+ kept += 1;
970
+ }
971
+ return kept === 0 ? void 0 : out;
972
+ }
973
+ /** Parse a raw usage sidecar; malformed content reads as empty (best-effort telemetry). */
974
+ function parseUsage(raw) {
975
+ const map = /* @__PURE__ */ new Map();
976
+ if (raw === null) return map;
977
+ try {
978
+ const parsed = JSON.parse(raw);
979
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return map;
980
+ for (const [name, record] of Object.entries(parsed)) map.set(name, normalizeUsageRecord(record));
981
+ } catch {}
982
+ return map;
983
+ }
984
+ async function loadUsage(root, io = nodeEvolutionIo()) {
985
+ return parseUsage(await io.readText(usageFile(root)));
986
+ }
987
+ async function mutateUsage(root, io, task, options = {}) {
988
+ const run = async () => {
989
+ await transactIo(io, usageFile(root), async (current) => {
990
+ let shapePreserved = false;
991
+ let recovered = null;
992
+ const quarantineCopy = async () => {
993
+ const corruptPath = `${usageFile(root)}.corrupt`;
994
+ return io.writeText(corruptPath, current).then(() => true, () => false);
995
+ };
996
+ if (current !== null) {
997
+ let parsed = null;
998
+ try {
999
+ const probe = JSON.parse(current);
1000
+ if (isRecord(probe)) parsed = probe;
1001
+ } catch {
1002
+ parsed = null;
1003
+ }
1004
+ if (parsed === null) {
1005
+ if (!await quarantineCopy()) {
1006
+ 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)`);
1007
+ return current;
1008
+ }
1009
+ 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`);
1010
+ } else {
1011
+ const record = parsed;
1012
+ const isMalformed = (value) => value === null || typeof value !== "object" || Array.isArray(value);
1013
+ if (typeof record.version === "number" && record.version > 1) {
1014
+ 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`;
1015
+ if (options.onQuarantine !== void 0) options.onQuarantine(message);
1016
+ else console.warn(message);
1017
+ shapePreserved = true;
1018
+ } else if (Object.values(record).some(isMalformed)) {
1019
+ const bad = Object.keys(record).filter((key) => isMalformed(record[key]));
1020
+ if (!await quarantineCopy()) {
1021
+ 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`);
1022
+ return current;
1023
+ }
1024
+ recovered = JSON.stringify(Object.fromEntries(Object.entries(record).filter(([, value]) => !isMalformed(value))));
1025
+ 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`);
1026
+ }
1027
+ }
1028
+ }
1029
+ if (shapePreserved) return current;
1030
+ const map = parseUsage(recovered ?? current);
1031
+ await task(map);
1032
+ return JSON.stringify(Object.fromEntries(map.entries()), null, 2);
1033
+ });
1034
+ };
1035
+ if (options.fence !== void 0) await options.fence.run(run);
1036
+ else await run();
1037
+ }
1038
+ /** Curator-owned usage fields (rc.67 K-2): the curator writes ONLY this set —
1039
+ * lifecycle state, archive stamp, the six-factor quality pair, and the
1040
+ * marker-mirrored pin flag; counters and activity stamps belong to the
1041
+ * tool-telemetry side and are never copied by a fold. P2-12 (v39): the
1042
+ * combined `applyCuratorFields` wrapper had no production caller (folds go
1043
+ * through {@link foldCuratorFields}), so the two field copies below are the
1044
+ * whole contract. */
1045
+ /** Copy only the lifecycle pair (state/archived_at) — see the ownership split
1046
+ * rationale above. */
1047
+ function applyCuratorLifecycleFields(disk, curated) {
1048
+ disk.state = curated.state;
1049
+ disk.archived_at = curated.archived_at;
1050
+ }
1051
+ /**
1052
+ * Copy the recomputed meta pair (quality_score/quality_warn + the
1053
+ * marker-mirrored pin flag) — refreshed tree-wide each run by design, so a
1054
+ * concurrent curator run's lifecycle changes are never reverted by them.
1055
+ * P1-1 (v15): the feedback pair (`feedback_score`/`feedback_warn`) is
1056
+ * deliberately NOT copied — it is feedback-owned (see the field-ownership
1057
+ * contract on {@link UsageRecord}) and must survive curator runs untouched.
1058
+ */
1059
+ function applyCuratorMetaFields(disk, curated) {
1060
+ disk.quality_score = curated.quality_score;
1061
+ disk.quality_warn = curated.quality_warn;
1062
+ disk.pinned = curated.pinned;
1063
+ }
1064
+ /**
1065
+ * Fold a curator run-start snapshot onto the current on-disk map (rc.67 K-2):
1066
+ * each curated record is projected onto its disk peer by copying only the
1067
+ * curator-owned fields, so a concurrent tool-side bump between snapshot and
1068
+ * save survives. Records absent from the snapshot are left untouched; a
1069
+ * curated record with no disk peer is seeded from the snapshot. `stateOwned`
1070
+ * (rc.72 H-1) restricts the lifecycle pair to the names this run ACTUALLY
1071
+ * transitioned — a concurrent curator run's archive/restore is never reverted
1072
+ * by a stale snapshot; without it both pairs apply everywhere.
1073
+ */
1074
+ function foldCuratorFields(disk, curated, stateOwned, runStartStates) {
1075
+ const skipped = [];
1076
+ for (const [name, record] of curated) {
1077
+ const diskRecord = disk.get(name);
1078
+ if (!diskRecord) {
1079
+ disk.set(name, { ...record });
1080
+ continue;
1081
+ }
1082
+ applyCuratorMetaFields(diskRecord, record);
1083
+ if (stateOwned === void 0 || stateOwned.has(name)) {
1084
+ const expected = runStartStates?.get(name);
1085
+ if (expected !== void 0 && diskRecord.state !== expected) {
1086
+ skipped.push(name);
1087
+ continue;
1088
+ }
1089
+ applyCuratorLifecycleFields(diskRecord, record);
1090
+ }
1091
+ }
1092
+ return skipped;
1093
+ }
1094
+ /** Whole-file usage write (V6-37, 0.3.37): this is the ONE path that bypasses
1095
+ * the malformed-defense and the transact lock — prefer `mutateUsage` for any
1096
+ * read-modify-write so a concurrent writer cannot lose its update and a
1097
+ * malformed sidecar stays recoverable. Kept for fixture/test seeding.
1098
+ * @internal P3-16 (v14): no production caller (verified by grep); exported for
1099
+ * the family's tests only. Do not use it to write the sidecar in new code. */
1100
+ async function saveUsage(root, map, io = nodeEvolutionIo()) {
1101
+ const obj = Object.fromEntries(map.entries());
1102
+ await io.writeText(usageFile(root), JSON.stringify(obj, null, 2));
1103
+ }
1104
+ function getRecord(map, name) {
1105
+ let record = map.get(name);
1106
+ if (!record) {
1107
+ record = emptyRecord();
1108
+ map.set(name, record);
1109
+ }
1110
+ return record;
1111
+ }
1112
+ function bumpView(map, name, when = /* @__PURE__ */ new Date()) {
1113
+ const record = getRecord(map, name);
1114
+ record.view_count += 1;
1115
+ record.last_viewed_at = when.toISOString();
1116
+ }
1117
+ function bumpUse(map, name, when = /* @__PURE__ */ new Date()) {
1118
+ const record = getRecord(map, name);
1119
+ record.use_count += 1;
1120
+ record.last_used_at = when.toISOString();
1121
+ }
1122
+ function bumpPatch(map, name, when = /* @__PURE__ */ new Date()) {
1123
+ const record = getRecord(map, name);
1124
+ record.patch_count += 1;
1125
+ record.last_patched_at = when.toISOString();
1126
+ }
1127
+ /** Count one observed support-file read (design §5.5). The map is created on
1128
+ * first evidence only — a skill with no support reads keeps the field absent. */
1129
+ function bumpSupportRead(map, name, rel, when = /* @__PURE__ */ new Date()) {
1130
+ const record = getRecord(map, name);
1131
+ const counts = record.support_reads ?? {};
1132
+ counts[rel] = (counts[rel] ?? 0) + 1;
1133
+ record.support_reads = counts;
1134
+ record.last_viewed_at = when.toISOString();
1135
+ }
1136
+ function markAgentCreated(map, name) {
1137
+ getRecord(map, name).created_by = "agent";
1138
+ }
1139
+ function latestActivityAt(record) {
1140
+ const values = [
1141
+ record.last_used_at,
1142
+ record.last_viewed_at,
1143
+ record.last_patched_at
1144
+ ].filter((value) => typeof value === "string" && Number.isFinite(Date.parse(value)));
1145
+ if (values.length === 0) return null;
1146
+ return values.reduce((latest, value) => Date.parse(value) > Date.parse(latest) ? value : latest);
1147
+ }
1148
+ /** Days between an ISO timestamp (falling back to `created`) and `now`. An
1149
+ * unparseable date counts as 0 days: NaN silently froze every age comparison
1150
+ * (A2-9). */
1151
+ function daysSinceIso(iso, created, nowMs) {
1152
+ const t = Date.parse(iso ?? created);
1153
+ if (!Number.isFinite(t)) return 0;
1154
+ return (nowMs - t) / 864e5;
1155
+ }
1156
+ /** Idle days of one skill since its lifecycle age anchor (`last activity ??
1157
+ * created_at`) — the SAME anchor the curator's transitions use, so the
1158
+ * maintenance view and the lifecycle can never disagree about staleness. */
1159
+ function idleDays(record, now = /* @__PURE__ */ new Date()) {
1160
+ return daysSinceIso(latestActivityAt(record), record.created_at, now.getTime());
1161
+ }
1162
+ /**
1163
+ * Whether the library has ANY observed read evidence (C observation window):
1164
+ * reads were invisible to the usage sidecar before A2, so `view_count` zero
1165
+ * means "never read" ONLY after the first observed read exists anywhere in
1166
+ * the map. Before that, churn-based signals (write-ghost) are untrustworthy
1167
+ * and callers must suppress them. Pure and derived — never persisted.
1168
+ */
1169
+ function usageObserved(usage) {
1170
+ for (const record of usage.values()) if (record.view_count > 0) return true;
1171
+ return false;
1172
+ }
1173
+ /**
1174
+ * Curator suppression sidecar: built-in skills the curator has archived stay
1175
+ * suppressed across re-seeds, so the lifecycle never fights a re-created
1176
+ * bundled skill. Best-effort load/save, mirroring the usage sidecar posture.
1177
+ * Versioned shape ({ version, names }) with legacy plain-array compat.
1178
+ */
1179
+ const SUPPRESSED_FILE_VERSION = 1;
1180
+ function suppressedFile(root) {
1181
+ return join(root, ".curator-suppressed.json");
1182
+ }
1183
+ async function loadSuppressedNames(root, io = nodeEvolutionIo()) {
1184
+ return parseSuppressed(await io.readText(suppressedFile(root)));
1185
+ }
1186
+ function parseSuppressed(raw) {
1187
+ if (raw === null) return /* @__PURE__ */ new Set();
1188
+ try {
1189
+ const parsed = JSON.parse(raw);
1190
+ const names = Array.isArray(parsed) ? parsed : typeof parsed === "object" && parsed !== null && Array.isArray(parsed.names) ? parsed.names : [];
1191
+ return new Set(names.filter((entry) => typeof entry === "string"));
1192
+ } catch {
1193
+ return /* @__PURE__ */ new Set();
1194
+ }
1195
+ }
1196
+ /**
1197
+ * Plain wholesale write of the suppression sidecar (tests and fixture seeding).
1198
+ * @internal S2.4 (PLAN 2026-09-16, audit P2-31): NO production consumer
1199
+ * (verified by grep; production suppressions go through
1200
+ * {@link updateSuppressedNames}) — exported for the family's tests only. Do
1201
+ * not use it to write the sidecar in new code.
1202
+ *
1203
+ * The write rides the {@link transactIo} channel (the same lock the RMW
1204
+ * writer uses), not the former naked read → `io.writeText`: that form was an
1205
+ * unserialized read-modify-write — the last `saveSuppressedNames` in this file
1206
+ * with no lock, while its sibling `saveUsage` already carried the `@internal`
1207
+ * test-only note. Version discipline is unchanged (V24-09 / S2-14): a read
1208
+ * failure surfaces (an unreadable sidecar is never written over), a newer
1209
+ * on-disk schema is warned about and preserved byte-for-byte (the
1210
+ * byte-identical result short-circuits the write), and a malformed sidecar is
1211
+ * still overwritten with the v1 shape (the historical plain-writer posture).
1212
+ */
1213
+ async function saveSuppressedNames(root, names, io = nodeEvolutionIo()) {
1214
+ await transactIo(io, suppressedFile(root), (current) => {
1215
+ if (current !== null) try {
1216
+ const parsed = JSON.parse(current);
1217
+ if (parsed !== null && typeof parsed.version === "number" && parsed.version > 1) {
1218
+ console.warn(`suppression sidecar ${suppressedFile(root)} declares version ${String(parsed.version)} (newer than 1); not overwritten`);
1219
+ return current;
1220
+ }
1221
+ } catch {}
1222
+ return JSON.stringify({
1223
+ version: 1,
1224
+ names: [...names].sort()
1225
+ }, null, 2);
1226
+ });
1227
+ }
1228
+ /**
1229
+ * Atomic read-modify-write on the suppression sidecar (rc.50 P2-2): `task`
1230
+ * receives the set parsed from the current on-disk state and may mutate it;
1231
+ * the result is persisted inside the same transact so a second process
1232
+ * sharing DSH_HOME cannot interleave its RMW. Best-effort posture unchanged.
1233
+ */
1234
+ async function updateSuppressedNames(root, io, task) {
1235
+ await transactIo(io, suppressedFile(root), async (current) => {
1236
+ if (current !== null) {
1237
+ let parsed = null;
1238
+ try {
1239
+ parsed = JSON.parse(current);
1240
+ } catch {
1241
+ return current;
1242
+ }
1243
+ if (parsed !== null && typeof parsed.version === "number" && parsed.version > 1) {
1244
+ console.warn(`suppression sidecar ${suppressedFile(root)} declares version ${String(parsed.version)} (newer than 1); not overwritten`);
1245
+ return current;
1246
+ }
1247
+ }
1248
+ const names = parseSuppressed(current);
1249
+ await task(names);
1250
+ return JSON.stringify({
1251
+ version: 1,
1252
+ names: [...names].sort()
1253
+ }, null, 2);
1254
+ });
1255
+ }
1256
+ //#endregion
1257
+ export { authoringFeedback as A, validateFrontmatter as B, updateSuppressedNames as C, displayBodyOf as D, selectSections as E, normalizeFrontmatter as F, describeReferenceRewrite as G, externalRefs as H, parseFrontmatter as I, planReferenceRewrite as K, relatedSkillNames as L, exceedsContentLimit as M, frontmatterBlock as N, h2Sections as O, frontmatterCatalogInvalid as P, shrinksOverLimit as R, suppressedFile as S, usageObserved as T, supportRefs as U, yamlPlainScalarNeedsQuotes as V, applyReferenceRewrite as W, markAgentCreated as _, bumpPatch as a, saveSuppressedNames as b, bumpView as c, foldCuratorFields as d, getRecord as f, loadUsage as g, loadSuppressedNames as h, applyCuratorMetaFields as i, ensureSkillFrontmatter as j, readingStats as k, daysSinceIso as l, latestActivityAt as m, SUPPRESSED_FILE_VERSION as n, bumpSupportRead as o, idleDays as p, planRehoming as q, applyCuratorLifecycleFields as r, bumpUse as s, MAX_SUPPORT_READ_PATHS as t, emptyRecord as u, mutateUsage as v, usageFile as w, saveUsage as x, normalizeUsageRecord as y, skillMdOnDisk as z };