@lmzhen/dsh-evolution-core 0.53.0 → 0.55.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 (53) hide show
  1. package/lib/{extract-plan-D4zO7dmD.js → extract-plan-ihQznLVT.js} +2 -1
  2. package/lib/extract.js +7 -7
  3. package/lib/index.js +795 -546
  4. package/lib/{limits-TD4Pv92Q.js → limits-DBg3UMkw.js} +11 -6
  5. package/lib/{skill-history-CZp8vhyL.js → mutation-storage-adapter-BM7mIJKp.js} +4 -647
  6. package/lib/mutations-1wLISSrY.js +592 -0
  7. package/lib/policy.js +9 -3
  8. package/lib/{quality-BLc6UQQb.js → quality-DNUVRbUm.js} +1 -1
  9. package/lib/{skill-health-BIpiPvw6.js → review-context-CXKwGGd8.js} +124 -183
  10. package/lib/runtime/plugin.js +92 -1
  11. package/lib/{session-projection-ByNxQi9O.js → session-projection-CbIKvDfJ.js} +3 -2
  12. package/lib/skill-history-B-DyIedq.js +646 -0
  13. package/lib/skills.js +12 -8
  14. package/lib/text-metrics-CyJhxWBs.js +132 -0
  15. package/lib/types/constants.d.ts +10 -5
  16. package/lib/types/constants.js +10 -5
  17. package/lib/types/drift-signals.d.ts +1 -4
  18. package/lib/types/drift-signals.js +14 -23
  19. package/lib/types/extract-request.js +3 -2
  20. package/lib/types/frontmatter.js +12 -8
  21. package/lib/types/index.d.ts +2 -1
  22. package/lib/types/index.js +2 -1
  23. package/lib/types/memory-store.d.ts +32 -6
  24. package/lib/types/memory-store.js +86 -30
  25. package/lib/types/mutation-unit.js +2 -1
  26. package/lib/types/params.js +6 -3
  27. package/lib/types/policy.d.ts +5 -0
  28. package/lib/types/policy.js +8 -2
  29. package/lib/types/prompts.d.ts +1 -1
  30. package/lib/types/prompts.js +1 -1
  31. package/lib/types/runtime/coherence.d.ts +27 -0
  32. package/lib/types/runtime/coherence.js +115 -0
  33. package/lib/types/runtime/plugin.js +2 -0
  34. package/lib/types/signals.js +3 -2
  35. package/lib/types/skill-health.d.ts +8 -5
  36. package/lib/types/skill-health.js +27 -28
  37. package/lib/types/skill-history.d.ts +2 -2
  38. package/lib/types/skill-history.js +7 -7
  39. package/lib/types/skill-lint.d.ts +1 -1
  40. package/lib/types/skill-lint.js +4 -4
  41. package/lib/types/skill-stats.d.ts +3 -1
  42. package/lib/types/skill-stats.js +2 -0
  43. package/lib/types/skill-store.js +2 -1
  44. package/lib/types/text-budgets.d.ts +150 -0
  45. package/lib/types/text-budgets.js +65 -0
  46. package/lib/types/text-metrics.d.ts +88 -0
  47. package/lib/types/text-metrics.js +131 -0
  48. package/lib/{usage-B1qveKi9.js → usage-e34VZPmK.js} +2 -515
  49. package/lib/write.js +3 -2
  50. package/package.json +1 -1
  51. package/lib/mutations-DQXddSJd.js +0 -75
  52. package/lib/types/cost.d.ts +0 -63
  53. package/lib/types/cost.js +0 -67
@@ -0,0 +1,592 @@
1
+ import { c as transactIo, o as nodeEvolutionIo } from "./io-GxghO3Ip.js";
2
+ import { J as SKILL_NAME_RE, i as DEFAULT_SKILL_LIMITS, u as CONTENT_SPLIT_HINT } from "./limits-DBg3UMkw.js";
3
+ import { a as measureUnit, o as truncateGraphemes, r as graphemeCount } from "./text-metrics-CyJhxWBs.js";
4
+ import { n as isRecord } from "./guards-3f02mnf2.js";
5
+ import { join } from "node:path";
6
+ import { createHash } from "node:crypto";
7
+ import { parse } from "yaml";
8
+ //#region lib/types/frontmatter.js
9
+ /**
10
+ * Frontmatter parsing, normalization and validation for skill Markdown files.
11
+ *
12
+ * Split out of skill-store.ts (S2-1): pure functions over file text, no store
13
+ * state. skill-store.ts re-exports the same names it exported before the split,
14
+ * so the package export surface is unchanged.
15
+ */
16
+ /**
17
+ * Shared frontmatter block detection (P3-3 single owner): opening line `---`
18
+ * and closing line exactly `---`. Used by `parseFrontmatter`,
19
+ * `frontmatterCatalogInvalid` and `normalizeFrontmatter` so the three can
20
+ * never disagree about where the block ends (the loose `indexOf('\n---')`
21
+ * form matched `\n----` and was replaced by this strict line rule).
22
+ *
23
+ * V27 G2.1: both fence lines are matched EXACTLY, tolerating only a trailing
24
+ * `\r` — the same rule the upstream filesystem catalog uses
25
+ * (`skill-filesystem.parseFrontmatter`). The former `.trim()` comparison
26
+ * accepted ` --- `, so an indented fence loaded in the family while the
27
+ * platform ignored the file: family visibility split from platform visibility,
28
+ * which is exactly what a strict-YAML frontmatter is supposed to prevent.
29
+ */
30
+ /**
31
+ * S1.1 (v37 P1-4): the frontmatter block is split on LF and every line keeps its
32
+ * own `\r`, so the byte-preserving rebuild (`lines.join('\n')`) is exact. Line
33
+ * MATCHERS must therefore look at a CR-stripped view: JS `.` does not match `\r`,
34
+ * so `(.*)$` never reaches the end of a CRLF line.
35
+ * @param line - one block line, possibly CR-terminated.
36
+ * @returns the line without its trailing CR.
37
+ */
38
+ function withoutCr(line) {
39
+ return line.endsWith("\r") ? line.slice(0, -1) : line;
40
+ }
41
+ function frontmatterBlock(content) {
42
+ if (!content.trimStart().startsWith("---")) return null;
43
+ const firstBreak = content.indexOf("\n");
44
+ const nl = firstBreak > 0 && content[firstBreak - 1] === "\r" ? "\r\n" : "\n";
45
+ const lines = content.split("\n");
46
+ if ((lines[0] ?? "").replace(/\r$/, "") !== "---") return null;
47
+ let end = -1;
48
+ for (let i = 1; i < lines.length; i++) {
49
+ const line = lines[i];
50
+ if (line === void 0) continue;
51
+ if (line === "---" || line === "---\r") {
52
+ end = i;
53
+ break;
54
+ }
55
+ }
56
+ if (end < 0) return null;
57
+ return {
58
+ block: lines.slice(1, end).join("\n"),
59
+ lines,
60
+ end,
61
+ nl
62
+ };
63
+ }
64
+ /**
65
+ * Raw-line scan of a frontmatter block: the single owner of "which entries the
66
+ * strict catalog cannot load". `frontmatterCatalogInvalid` publishes it and
67
+ * `normalizeFrontmatter` decides each rewrite with the same predicate
68
+ * (`yamlPlainScalarNeedsQuotes`), so the audit verdict and the write path can
69
+ * never disagree. A9 (audit P2-12): the scan is ENDING-AGNOSTIC — lines are
70
+ * split on `\n` with the per-line CR stripped, exactly the iteration the
71
+ * rewrite path uses. The former split on the block's FIRST-LINE ending turned
72
+ * a mixed-ending block (first line CRLF, entries LF) into one unsplit chunk
73
+ * whose entries were all skipped, so an unquoted ` #` value read as CLEAN
74
+ * while the catalog silently dropped it and the next edit would have quoted
75
+ * it. Only single-line `key: value` entries are judged.
76
+ */
77
+ function unsafeFrontmatterEntries(block) {
78
+ const found = [];
79
+ for (const rawLine of block.split("\n")) {
80
+ const match = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(withoutCr(rawLine));
81
+ if (!match) continue;
82
+ const key = match[1];
83
+ if (key === void 0) continue;
84
+ const value = (match[2] ?? "").trim();
85
+ if (yamlPlainScalarNeedsQuotes(value)) found.push({
86
+ key,
87
+ value
88
+ });
89
+ }
90
+ return found;
91
+ }
92
+ /**
93
+ * Frontmatter fields the platform catalog reads as STRINGS (`stringField` /
94
+ * `optionalString` in `skill-filesystem`): any other YAML type reads as
95
+ * ABSENT there, and an absent `name`/`description` makes the catalog ignore the
96
+ * whole file. The family publishes text for these keys anyway (its lenient
97
+ * read), which is the one split a write must not create.
98
+ */
99
+ const PLATFORM_STRING_FIELDS = [
100
+ "name",
101
+ "description",
102
+ "whenToUse"
103
+ ];
104
+ /**
105
+ * Frontmatter values as the STRICT platform catalog reads them — the `yaml`
106
+ * package (YAML 1.2 core schema, the same dependency the platform's
107
+ * skill-filesystem parses with — see the import note above),
108
+ * the parser `normalizeFrontmatter` also verifies rewrites with — or `null`
109
+ * when the block is not loadable as a YAML mapping. Also reports the platform
110
+ * string fields whose value is not a string ({@link PlatformStringSplit}).
111
+ *
112
+ * Scalars publish their text (`name`, `description`, `whenToUse` are strings by
113
+ * contract; a number/boolean-shaped value keeps the text the family always
114
+ * published), a flow or block sequence publishes its inline `[a, b]` form
115
+ * (`relatedSkillNames` scans names out of it), and a nested mapping publishes
116
+ * nothing — no consumer in this family reads one, and a lossy string could be
117
+ * picked up by a routing field. A string value is trimmed: YAML's block-scalar
118
+ * chomping appends a newline that the family's single-line routing fields never
119
+ * carried.
120
+ */
121
+ function strictFrontmatterValues(block) {
122
+ if (block.trim() === "") return {
123
+ values: /* @__PURE__ */ new Map(),
124
+ split: []
125
+ };
126
+ let loaded;
127
+ try {
128
+ loaded = parse(block);
129
+ } catch {
130
+ return null;
131
+ }
132
+ if (loaded === null || loaded === void 0) return {
133
+ values: /* @__PURE__ */ new Map(),
134
+ split: []
135
+ };
136
+ if (typeof loaded !== "object" || Array.isArray(loaded)) return null;
137
+ const values = /* @__PURE__ */ new Map();
138
+ const split = [];
139
+ let metadata;
140
+ for (const [key, value] of Object.entries(loaded)) {
141
+ if (typeof value !== "string" && PLATFORM_STRING_FIELDS.includes(key)) split.push({
142
+ key,
143
+ kind: value === null || value === void 0 ? "null" : Array.isArray(value) ? "sequence" : typeof value === "object" ? "mapping" : "scalar"
144
+ });
145
+ if (typeof value === "string") {
146
+ values.set(key, value.trim());
147
+ continue;
148
+ }
149
+ if (typeof value === "number" || typeof value === "boolean") {
150
+ values.set(key, String(value));
151
+ continue;
152
+ }
153
+ if (Array.isArray(value)) {
154
+ values.set(key, `[${value.map((item) => String(item)).join(", ")}]`);
155
+ continue;
156
+ }
157
+ if (key === "metadata" && isRecord(value)) {
158
+ metadata = value;
159
+ continue;
160
+ }
161
+ }
162
+ return {
163
+ values,
164
+ split,
165
+ metadata
166
+ };
167
+ }
168
+ /**
169
+ * Lenient line scan, used only for a block the strict parser rejects: the
170
+ * family keeps routing a legacy file the platform refuses, and
171
+ * `catalogInvalid` reports the split instead of hiding it. Values are trimmed
172
+ * and unquoted exactly as before.
173
+ */
174
+ function lenientFrontmatterValues(block, nl) {
175
+ const values = /* @__PURE__ */ new Map();
176
+ const blockLines = block.split(nl);
177
+ for (let i = 0; i < blockLines.length; i += 1) {
178
+ const line = withoutCr(blockLines[i] ?? "");
179
+ const match = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(line);
180
+ if (!match) continue;
181
+ const [, key, value] = match;
182
+ if (key === void 0 || value === void 0) continue;
183
+ const header = /^([>|])[+-]?\d*$/.exec(value.trim());
184
+ if (header !== null) {
185
+ const fold = header[1] === ">";
186
+ const parts = [];
187
+ let scan = i + 1;
188
+ for (; scan < blockLines.length; scan += 1) {
189
+ const raw = blockLines[scan] ?? "";
190
+ if (raw.trim() === "") {
191
+ parts.push("");
192
+ continue;
193
+ }
194
+ if (!/^\s/.test(raw)) break;
195
+ parts.push(raw.trim());
196
+ }
197
+ while (parts.length > 0 && parts[parts.length - 1] === "") parts.pop();
198
+ let folded = "";
199
+ for (const part of parts) {
200
+ if (part === "") {
201
+ if (folded !== "" && !folded.endsWith("\n")) folded += "\n";
202
+ continue;
203
+ }
204
+ if (folded === "" || folded.endsWith("\n")) folded += part;
205
+ else folded += ` ${part}`;
206
+ }
207
+ values.set(key, (fold ? folded : parts.join("\n")).trim());
208
+ i = scan - 1;
209
+ continue;
210
+ }
211
+ values.set(key, value.trim().replace(/^["']|["']$/g, ""));
212
+ }
213
+ return values;
214
+ }
215
+ /**
216
+ * The single read of a SKILL.md frontmatter block: values, body and every
217
+ * strict-catalog signal, computed once. `null` only when the file has no
218
+ * frontmatter block; the body may be empty. {@link parseFrontmatter} and
219
+ * {@link frontmatterCatalogInvalid} are its two projections.
220
+ *
221
+ * @param content - the SKILL.md text.
222
+ * @returns the block read, or `null` when there is no block.
223
+ */
224
+ function readFrontmatterBlock(content) {
225
+ const found = frontmatterBlock(content);
226
+ if (!found) return null;
227
+ const body = found.lines.slice(found.end + 1).join("\n").trim();
228
+ const strict = strictFrontmatterValues(found.block);
229
+ const values = strict?.values ?? lenientFrontmatterValues(found.block, found.nl);
230
+ const frontmatter = {};
231
+ for (const [key, value] of values) frontmatter[key] = value;
232
+ return {
233
+ frontmatter,
234
+ body,
235
+ unsafeValues: unsafeFrontmatterEntries(found.block),
236
+ strictFailed: strict === null,
237
+ platformStringSplit: strict?.split ?? [],
238
+ metadata: strict?.metadata
239
+ };
240
+ }
241
+ /**
242
+ * Parse a SKILL.md: its frontmatter values and body, or `null` when the file
243
+ * has no frontmatter block or no body. Every consumer of frontmatter values
244
+ * goes through here — the write path's validation, `list()`'s published
245
+ * description, `relatedSkillNames` and the audit — so all of them read the same
246
+ * bytes the same way.
247
+ *
248
+ * @param content - the SKILL.md text.
249
+ * @returns the read, or `null` when there is no block or no body.
250
+ */
251
+ function parseFrontmatter(content) {
252
+ const read = readFrontmatterBlock(content);
253
+ if (!read || !read.body) return null;
254
+ return {
255
+ frontmatter: read.frontmatter,
256
+ body: read.body,
257
+ unsafeValues: read.unsafeValues,
258
+ metadata: read.metadata,
259
+ catalogInvalid: read.strictFailed || read.unsafeValues.length > 0 || read.platformStringSplit.length > 0,
260
+ platformStringSplit: read.platformStringSplit
261
+ };
262
+ }
263
+ /**
264
+ * Whether this file's frontmatter is valid as written for the strict platform
265
+ * catalog (see `FrontmatterRead.catalogInvalid`). Body-independent (a body-less
266
+ * file is still judged), and derived from the same read as `parseFrontmatter` —
267
+ * so the audit's verdict and the values the family publishes for one file can
268
+ * never disagree (V27 G2.1).
269
+ *
270
+ * @param content - the SKILL.md text.
271
+ * @returns `true` when the strict parser rejects the block or an unquoted value would read as something else.
272
+ */
273
+ function frontmatterCatalogInvalid(content) {
274
+ const read = readFrontmatterBlock(content);
275
+ if (read !== null) return read.strictFailed || read.unsafeValues.length > 0 || read.platformStringSplit.length > 0;
276
+ return frontmatterBlock(content.replace(/^\uFEFF/, "").replace(/\r\n/g, "\n")) !== null;
277
+ }
278
+ /** YAML plain-scalar hazards that make an UNQUOTED frontmatter value
279
+ * unloadable to the platform catalog (strict YAML parser): `: ` (mapping
280
+ * separator), ` #` (comment start), a trailing `:` (a mapping marker),
281
+ * or a leading YAML indicator. The evolution `parseFrontmatter` is
282
+ * deliberately lenient, so violations silently split family-visibility from
283
+ * platform-visibility (0.3.11 inkos-harness case: the description carried
284
+ * "…: " and the catalog dropped the whole skill). Already-quoted values and
285
+ * well-formed flow collections (`[a, b]` / `{a: b}`) are considered safe.
286
+ * 0.3.16 (E-47): null/bool/number-shaped plain scalars are flagged too — they
287
+ * parse as booleans/numbers on the platform while the family keeps the string
288
+ * (a `description: true` split-brain).
289
+ * This rule is only the FAST PATH — the write path re-verifies every rewrite
290
+ * with the real YAML parser (see normalizeFrontmatter), so an incomplete
291
+ * approximation can never corrupt a multiline flow value (P3-4). */
292
+ function yamlPlainScalarNeedsQuotes(value) {
293
+ if (value.length === 0) return false;
294
+ if (value.length >= 2 && (value.startsWith("\"") && value.endsWith("\"") || value.startsWith("'") && value.endsWith("'"))) return false;
295
+ if (/^\[.*\]$/.test(value) || /^\{.*\}$/.test(value)) return false;
296
+ if (/^[>|][+-]?\d*$/.test(value)) return false;
297
+ if (value.includes(": ")) return true;
298
+ if (value.includes(" #")) return true;
299
+ if (value.endsWith(":")) return true;
300
+ if (/^(?:null|true|false|~)$/i.test(value)) return true;
301
+ if (/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?$/.test(value)) return true;
302
+ if (/^0x[0-9a-f]+$/i.test(value)) return true;
303
+ if (/^0o[0-7]+$/.test(value)) return true;
304
+ if (/^(?:[-+]?\.inf|\.nan)$/i.test(value)) return true;
305
+ if (/^[-?:,[\]{}#&*!|>'"%@`\s]/.test(value)) return true;
306
+ return false;
307
+ }
308
+ /**
309
+ * Normalize a SKILL.md frontmatter block into catalog-loadable YAML: values
310
+ * that YAML forbids unquoted get quotes — double quotes normally, single
311
+ * quotes (with `''` doubling) when the value contains `"` or `\` (both legal
312
+ * unescaped inside single-quoted YAML). Idempotent; only single-line
313
+ * `key: value` entries are touched; body text is never modified; line-ending
314
+ * style is preserved. **Every rewrite is re-verified with the real YAML
315
+ * parser** (`yaml` — the package the platform's skill-filesystem catalog parses
316
+ * with, YAML 1.2 core schema; PLAN S2.1, 2026-09-16 — the former "js-yaml, the
317
+ * same parser" claim was false: js-yaml speaks YAML 1.1 full and diverged on
318
+ * dates, timestamps and 1.1 int forms): if the
319
+ * rewritten block no longer parses, or a rewritten value's parsed content
320
+ * differs from the original, the rewrite is rolled back and reported in
321
+ * `issues` (fail-loud, never a silent value corruption — P3-4).
322
+ *
323
+ * V10-02 (P2-3): the rewrite decision is PER LINE — each entry parses its own
324
+ * value, so a duplicated key can never route one entry's unsafe value into a
325
+ * different line's rewrite (the old key→Map lookup rewrote the FIRST (safe)
326
+ * line with the SECOND line's quoted value, and the last-wins YAML reader
327
+ * masked the damage). A duplicated key is itself invalid input and is
328
+ * reported in `issues` (the write path refuses) instead of being rewritten.
329
+ */
330
+ function normalizeFrontmatter(content) {
331
+ const block = frontmatterBlock(content);
332
+ if (!block) return {
333
+ content,
334
+ changed: false,
335
+ fields: [],
336
+ issues: []
337
+ };
338
+ const { lines, end } = block;
339
+ const fields = [];
340
+ const issues = [];
341
+ const seen = /* @__PURE__ */ new Set();
342
+ const originalValues = /* @__PURE__ */ new Map();
343
+ let changed = false;
344
+ for (let i = 1; i < end; i++) {
345
+ const raw = lines[i];
346
+ if (raw === void 0) continue;
347
+ const match = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(withoutCr(raw));
348
+ if (!match) continue;
349
+ const key = match[1];
350
+ if (key === void 0) continue;
351
+ const value = (match[2] ?? "").trim();
352
+ if (seen.has(key)) {
353
+ issues.push(`${key}: duplicate frontmatter key — remove the repeated entry and retry`);
354
+ continue;
355
+ }
356
+ seen.add(key);
357
+ if (!yamlPlainScalarNeedsQuotes(value)) continue;
358
+ if (/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/.test(value)) {
359
+ issues.push(`${key}: value contains control characters — clean them manually`);
360
+ continue;
361
+ }
362
+ lines[i] = `${key}: ${value.includes("\"") || value.includes("\\") ? `'${value.replace(/'/g, "''")}'` : `"${value}"`}${raw.endsWith("\r") ? "\r" : ""}`;
363
+ originalValues.set(key, value);
364
+ fields.push(key);
365
+ changed = true;
366
+ }
367
+ if (issues.length > 0) return {
368
+ content,
369
+ changed: false,
370
+ fields: [],
371
+ issues
372
+ };
373
+ if (!changed) return {
374
+ content,
375
+ changed: false,
376
+ fields: [],
377
+ issues
378
+ };
379
+ const rewrittenBlock = lines.slice(1, end).join("\n");
380
+ try {
381
+ const parsed = parse(rewrittenBlock);
382
+ for (const key of fields) if (String(parsed[key]) !== originalValues.get(key)) throw new Error(`rewritten value for ${key} differs from the original`);
383
+ return {
384
+ content: lines.join("\n"),
385
+ changed: true,
386
+ fields,
387
+ issues
388
+ };
389
+ } catch (error) {
390
+ return {
391
+ content,
392
+ changed: false,
393
+ fields: [],
394
+ issues: [`frontmatter rewrite verification failed (${error instanceof Error ? error.message : String(error)}) — quoting skipped; wrap this value manually`]
395
+ };
396
+ }
397
+ }
398
+ /**
399
+ * Skill names referenced by a SKILL.md's `related_skills` frontmatter
400
+ * (B-line G3, rc.44): the single parsing source for the quality references
401
+ * factor and the learning-graph edges. The DSH frontmatter parser keeps the
402
+ * YAML value as a string (`"[a, b]"`), so names are scanned out of it; each
403
+ * must satisfy the skill-name shape and the referencing skill itself is
404
+ * excluded. Pure and deduplicated.
405
+ */
406
+ function relatedSkillNames(content, exclude) {
407
+ const parsed = parseFrontmatter(content);
408
+ if (!parsed) return [];
409
+ const nestedHost = parsed.metadata?.["hermes"];
410
+ const nestedRaw = isRecord(nestedHost) ? nestedHost["related_skills"] : void 0;
411
+ const flat = parsed.frontmatter["related_skills"];
412
+ const raw = typeof flat === "string" ? flat : Array.isArray(nestedRaw) ? `[${nestedRaw.map((item) => String(item)).join(", ")}]` : void 0;
413
+ if (typeof raw !== "string") return [];
414
+ const names = /* @__PURE__ */ new Set();
415
+ for (const match of Array.from(raw.matchAll(/(?<![A-Za-z0-9_-])[a-z0-9][a-z0-9-]*(?![A-Za-z0-9_-])/g))) {
416
+ const target = match[0];
417
+ if (target && SKILL_NAME_RE.test(target) && target !== exclude) names.add(target);
418
+ }
419
+ return [...names];
420
+ }
421
+ /** S1.2 (v37 P2-1): the content limit applies to the bytes that LAND ON DISK.
422
+ * Every write normalizes with `trimEnd() + '\n'`, so judging the raw argument let
423
+ * a 100_000-character body with no trailing newline land as 100_001 bytes — and
424
+ * every later patch/update of that skill was then refused, which made it
425
+ * unmaintainable through `skill_manage` with no repair path at all. */
426
+ /** The bytes that land on disk for a SKILL.md write — the ONE accounting basis
427
+ * shared by the content limit and the cost estimate (design §5.2). */
428
+ function skillMdOnDisk(content) {
429
+ return content.trimEnd() + "\n";
430
+ }
431
+ /** Whether `content` would exceed `limit` once written. */
432
+ function exceedsContentLimit(content, limit) {
433
+ return measureUnit(skillMdOnDisk(content), "codePoints") > limit;
434
+ }
435
+ /** S1.2: the repair path — a write that makes an already-over-limit file smaller.
436
+ * Only a NET SHRINK is exempt; an equal or larger write stays refused. */
437
+ function shrinksOverLimit(next, current, limit) {
438
+ if (current === null || current === void 0 || !exceedsContentLimit(current, limit)) return false;
439
+ return measureUnit(skillMdOnDisk(next), "codePoints") < measureUnit(skillMdOnDisk(current), "codePoints");
440
+ }
441
+ /**
442
+ * Synthesize a missing SKILL.md header at the write boundary.
443
+ *
444
+ * A model-authored create/update whose body starts with `# Title` is valid Markdown but the
445
+ * skill writer rejects it before any content check. Repair only the truly headerless shape: an
446
+ * existing fence is passed through byte-identical, even when it is malformed, so this helper
447
+ * cannot mask a header error that the validator should report. The caller owns the audit notice.
448
+ * @param content - the model-authored SKILL.md text.
449
+ * @param name - the validated skill name used for the `name:` field.
450
+ * @param description - optional description; otherwise derived from the first heading/prose.
451
+ * @returns the write text and whether a header was synthesized.
452
+ */
453
+ function ensureSkillFrontmatter(content, name, description) {
454
+ if (frontmatterBlock(content) !== null || content.trimStart().startsWith("---")) return {
455
+ content,
456
+ repaired: false
457
+ };
458
+ const body = content.replace(/^\uFEFF/, "").replace(/^(?:[ \t]*\r?\n)+/, "");
459
+ const heading = /^#{1,6}\s+(.+?)\s*$/m.exec(body)?.[1];
460
+ const firstLine = body.split(/\r?\n/).map((line) => line.trim()).find((line) => line !== "" && !line.startsWith("#")) ?? "";
461
+ const source = (description?.trim() || heading || firstLine || name).replace(/\s+/g, " ").trim();
462
+ const clipped = graphemeCount(source) > 58 ? truncateGraphemes(source, 58) : source;
463
+ const summary = /[.。!?!?]$/.test(clipped) ? clipped : clipped + ".";
464
+ const encoded = yamlPlainScalarNeedsQuotes(summary) ? JSON.stringify(summary) : summary;
465
+ return {
466
+ content: [
467
+ "---",
468
+ `name: ${name}`,
469
+ `description: ${encoded}`,
470
+ "version: 0.1.0",
471
+ "author: Hermes",
472
+ "---",
473
+ ""
474
+ ].join("\n") + "\n" + body,
475
+ repaired: true
476
+ };
477
+ }
478
+ function validateFrontmatter(content, expectedName, limits = DEFAULT_SKILL_LIMITS, current) {
479
+ const parsed = parseFrontmatter(content);
480
+ if (!parsed) return "SKILL.md 必须以 `---` 行开头,用另一个完全相同的 `---` 行结束 frontmatter(只容忍结尾的 `\\r`),并在其下包含正文。";
481
+ const unreadable = parsed.platformStringSplit.filter((entry) => entry.kind === "sequence" || entry.kind === "mapping");
482
+ if (unreadable.length > 0) return `Frontmatter 字段 ${unreadable.map((entry) => `"${entry.key}" (a YAML ${entry.kind})`).join(", ")} 必须是字符串:平台技能目录会把这种字段当作缺失,并忽略整个文件。请写成纯文本,或用双引号包住取值以保持字面内容。`;
483
+ if (!parsed.frontmatter.name) return "Frontmatter 必须包含 name 字段。";
484
+ if (!SKILL_NAME_RE.test(parsed.frontmatter.name)) return `技能名「${parsed.frontmatter.name}」不合法:请只用小写字母、数字和连字符。`;
485
+ if (parsed.frontmatter.name.length > limits.maxNameLength) return `技能名超过 ${limits.maxNameLength} 个字符。`;
486
+ if (expectedName && parsed.frontmatter.name !== expectedName) return `Frontmatter 里的 name「${parsed.frontmatter.name}」与目标技能「${expectedName}」不一致。`;
487
+ if (!parsed.frontmatter.description) return "Frontmatter 必须包含 description 字段。";
488
+ const description = parsed.frontmatter.description;
489
+ if (graphemeCount(description) > limits.maxDescriptionLength) return `description 超过 ${limits.maxDescriptionLength} 个字符。`;
490
+ if (exceedsContentLimit(content, limits.maxSkillContentChars) && !shrinksOverLimit(content, current, limits.maxSkillContentChars)) return `SKILL.md 内容超过 ${limits.maxSkillContentChars} 个字符。${CONTENT_SPLIT_HINT}`;
491
+ return null;
492
+ }
493
+ /**
494
+ * Advisory authoring feedback (P0): evaluate frontmatter against the
495
+ * authoring bar WITHOUT changing platform validation semantics. The bar is
496
+ * the quality target, `validateFrontmatter`'s limits are the compatibility
497
+ * floor, and this bridge layer tells the model when its text would be
498
+ * truncated or route-poor instead of silently shipping it.
499
+ */
500
+ function authoringFeedback(frontmatter) {
501
+ const description = frontmatter.description ?? "";
502
+ const descriptionLength = graphemeCount(description);
503
+ const over60 = descriptionLength > 60;
504
+ const hasColon = description.includes(":");
505
+ const lines = [];
506
+ lines.push(over60 ? `描述为 ${descriptionLength}/60 个字符 —— 超过 60 字符的作者规范上限(Hermes 标准;技能目录会按平台配置的上限截断)。` : `描述为 ${descriptionLength}/60 个字符 —— 在作者规范上限之内。`);
507
+ if (hasColon) lines.push("描述里含冒号 —— 请用双引号把整个取值包起来。");
508
+ return {
509
+ descriptionChars: descriptionLength,
510
+ over60,
511
+ hasColon,
512
+ lines
513
+ };
514
+ }
515
+ /** A1-15 (v18) / P2-2 (v19): the io layer marks an error `committed: true` when
516
+ * the rename landed and only the directory fsync failed. Every single-file
517
+ * writer must treat that as "written, durability unconfirmed" — never as a
518
+ * plain failure (which a caller would retry, or a two-phase caller roll back).
519
+ * v28 G2.1 (EVO-IO-05): this is a delegation to the seam's own
520
+ * `isCommittedWarning` — the marker predicate has exactly one definition. */
521
+ //#endregion
522
+ //#region lib/types/mutations.js
523
+ /**
524
+ * Curator/author audit trail: `.mutations.json` records every skill mutation
525
+ * with before/after content hashes so any automated edit is reviewable and
526
+ * replayable. Best-effort persistence, mirroring the usage sidecar posture.
527
+ * @module @lmzhen/dsh-evolution-core
528
+ */
529
+ const DEFAULT_MUTATION_CAP = 500;
530
+ /** Version of the `.mutations.json` file shape; writers always emit the current one. */
531
+ const MUTATIONS_FILE_VERSION = 1;
532
+ function mutationsFile(root) {
533
+ return join(root, ".mutations.json");
534
+ }
535
+ function contentHash(content) {
536
+ return createHash("sha256").update(content.replaceAll("\r\n", "\n")).digest("hex");
537
+ }
538
+ /**
539
+ * Parse a raw mutations sidecar; malformed content reads as empty (auditing is
540
+ * best-effort). Versioned shape ({ version, records }) with legacy
541
+ * plain-array compat, plus a field-level guard for records without the
542
+ * required identity/timestamp fields (rc.42 audit P2-3).
543
+ */
544
+ function parseMutationRecords(raw) {
545
+ if (raw === null) return [];
546
+ try {
547
+ return recordsFromParsed(JSON.parse(raw));
548
+ } catch {
549
+ return [];
550
+ }
551
+ }
552
+ /** Field-level shape guard shared by the parse and the recordMutation write
553
+ * path (P3/v15: the guard's JSON.parse and this parse used to run twice over
554
+ * the same bytes inside one transact). */
555
+ function recordsFromParsed(parsed) {
556
+ return (Array.isArray(parsed) ? parsed : typeof parsed === "object" && parsed !== null && Array.isArray(parsed.records) ? parsed.records : []).filter((entry) => typeof entry === "object" && entry !== null && typeof entry.skillName === "string" && typeof entry.action === "string" && typeof entry.at === "string");
557
+ }
558
+ async function loadMutations(root, io = nodeEvolutionIo()) {
559
+ return parseMutationRecords(await io.readText(mutationsFile(root)));
560
+ }
561
+ /** Append one record, trim to `cap`, and write atomically (versioned shape). */
562
+ async function recordMutation(root, io, record, cap = 500, fence) {
563
+ const write = async () => {
564
+ await transactIo(io, mutationsFile(root), (current) => {
565
+ let parsed = [];
566
+ if (current !== null) try {
567
+ parsed = JSON.parse(current);
568
+ } catch {
569
+ console.warn(`mutation audit record dropped: ${mutationsFile(root)} is malformed and was not overwritten`);
570
+ return current;
571
+ }
572
+ if (isRecord(parsed)) {
573
+ const version = parsed.version;
574
+ if (typeof version === "number" && version > 1) {
575
+ console.warn(`mutation audit record dropped: ${mutationsFile(root)} declares version ${version} (newer than 1); not overwritten`);
576
+ return current;
577
+ }
578
+ }
579
+ const existing = recordsFromParsed(parsed);
580
+ existing.push(record);
581
+ const trimmed = existing.length > cap ? existing.slice(existing.length - cap) : existing;
582
+ return JSON.stringify({
583
+ version: 1,
584
+ records: trimmed
585
+ }, null, 2);
586
+ });
587
+ };
588
+ if (fence !== void 0) await fence.run(write);
589
+ else await write();
590
+ }
591
+ //#endregion
592
+ export { validateFrontmatter as _, mutationsFile as a, ensureSkillFrontmatter as c, frontmatterCatalogInvalid as d, normalizeFrontmatter as f, skillMdOnDisk as g, shrinksOverLimit as h, loadMutations as i, exceedsContentLimit as l, relatedSkillNames as m, MUTATIONS_FILE_VERSION as n, recordMutation as o, parseFrontmatter as p, contentHash as r, authoringFeedback as s, DEFAULT_MUTATION_CAP as t, frontmatterBlock as u, yamlPlainScalarNeedsQuotes as v };
package/lib/policy.js CHANGED
@@ -1,4 +1,4 @@
1
- import { C as DEFAULT_SKILL_CONTENT_CHARS, F as FORBIDDEN_CONTROL_KEYS, H as PROTECTED_BUILTIN_SKILLS, M as DEFAULT_USER_CHAR_LIMIT, P as EVOLUTION_WRITE_TOOLS, _ as DEFAULT_MEMORY_CHAR_LIMIT, a as DEFAULT_SUPPORT_FILE_CHAR_POLICY, h as DEFAULT_CURATOR_MODEL, n as DEFAULT_CITATION_POLICY, o as POLICY_STAGE_DEFAULTS, r as DEFAULT_REFERENCE_REWRITE_POLICY, t as DEFAULT_ARCHIVE_RETENTION_POLICY } from "./limits-TD4Pv92Q.js";
1
+ import { G as PROTECTED_BUILTIN_SKILLS, L as EVOLUTION_WRITE_TOOLS, P as DEFAULT_USER_CHAR_LIMIT, R as FORBIDDEN_CONTROL_KEYS, _ as DEFAULT_MEMORY_CHAR_LIMIT, a as DEFAULT_SUPPORT_FILE_CHAR_POLICY, h as DEFAULT_CURATOR_MODEL, n as DEFAULT_CITATION_POLICY, o as POLICY_STAGE_DEFAULTS, r as DEFAULT_REFERENCE_REWRITE_POLICY, t as DEFAULT_ARCHIVE_RETENTION_POLICY, w as DEFAULT_SKILL_CONTENT_CHARS } from "./limits-DBg3UMkw.js";
2
2
  import { t as asRecord } from "./guards-3f02mnf2.js";
3
3
  import { t as clampedNumber } from "./numeric-Dc53KQoe.js";
4
4
  import { n as toolsPort } from "./tools-BrUswg8v.js";
@@ -20,6 +20,8 @@ const Config = z.object({
20
20
  curatorModel: z.string().default(DEFAULT_CURATOR_MODEL),
21
21
  memoryChars: z.number().min(1).default(DEFAULT_MEMORY_CHAR_LIMIT),
22
22
  userChars: z.number().min(1).default(DEFAULT_USER_CHAR_LIMIT),
23
+ memoryTokens: z.number().min(1),
24
+ userTokens: z.number().min(1),
23
25
  skillContentChars: z.number().min(1).default(DEFAULT_SKILL_CONTENT_CHARS),
24
26
  curatorIntervalHours: z.number().min(1).default(168),
25
27
  staleAfterDays: z.number().min(1).default(30),
@@ -50,6 +52,8 @@ var EvolutionPolicy = class extends Service {
50
52
  if (value !== void 0 && result !== value) clamped.push(name);
51
53
  return result;
52
54
  };
55
+ const memoryChars = field("memoryChars", config.memoryChars, DEFAULT_MEMORY_CHAR_LIMIT);
56
+ const userChars = field("userChars", config.userChars, DEFAULT_USER_CHAR_LIMIT);
53
57
  this.snapshot = Object.freeze({
54
58
  version: 1,
55
59
  reviewMemoryInterval: field("reviewMemoryInterval", config.reviewMemoryInterval, 10),
@@ -61,8 +65,10 @@ var EvolutionPolicy = class extends Service {
61
65
  return config.reviewMode === "aux" ? "aux" : "inject";
62
66
  })(),
63
67
  curatorModel: config.curatorModel ?? "deepseek-v4-pro",
64
- memoryChars: field("memoryChars", config.memoryChars, DEFAULT_MEMORY_CHAR_LIMIT),
65
- userChars: field("userChars", config.userChars, DEFAULT_USER_CHAR_LIMIT),
68
+ memoryChars,
69
+ userChars,
70
+ ...config.memoryTokens === void 0 ? {} : { memoryTokens: field("memoryTokens", config.memoryTokens, 1) },
71
+ ...config.userTokens === void 0 ? {} : { userTokens: field("userTokens", config.userTokens, 1) },
66
72
  skillContentChars: field("skillContentChars", config.skillContentChars, DEFAULT_SKILL_CONTENT_CHARS),
67
73
  curatorIntervalHours: field("curatorIntervalHours", config.curatorIntervalHours, 168),
68
74
  staleAfterDays: field("staleAfterDays", config.staleAfterDays, 30),
@@ -1,5 +1,5 @@
1
1
  import { b as probeText, g as probeList, m as isUnknown, p as isPresent } from "./io-GxghO3Ip.js";
2
- import { A as h2Sections, W as externalRefs, h as latestActivityAt } from "./usage-B1qveKi9.js";
2
+ import { A as h2Sections, M as externalRefs, h as latestActivityAt } from "./usage-e34VZPmK.js";
3
3
  import { t as evolutionHome } from "./state-store-Jpa-iYIZ.js";
4
4
  import { readFile, realpath, stat } from "node:fs/promises";
5
5
  import { basename, isAbsolute, join, relative, resolve } from "node:path";