@lmzhen/dsh-evolution-core 0.54.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 (50) 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 +1 -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/signals.js +3 -2
  32. package/lib/types/skill-health.d.ts +8 -5
  33. package/lib/types/skill-health.js +27 -28
  34. package/lib/types/skill-history.d.ts +2 -2
  35. package/lib/types/skill-history.js +7 -7
  36. package/lib/types/skill-lint.d.ts +1 -1
  37. package/lib/types/skill-lint.js +4 -4
  38. package/lib/types/skill-stats.d.ts +3 -1
  39. package/lib/types/skill-stats.js +2 -0
  40. package/lib/types/skill-store.js +2 -1
  41. package/lib/types/text-budgets.d.ts +150 -0
  42. package/lib/types/text-budgets.js +65 -0
  43. package/lib/types/text-metrics.d.ts +88 -0
  44. package/lib/types/text-metrics.js +131 -0
  45. package/lib/{usage-B1qveKi9.js → usage-e34VZPmK.js} +2 -515
  46. package/lib/write.js +3 -2
  47. package/package.json +1 -1
  48. package/lib/mutations-DQXddSJd.js +0 -75
  49. package/lib/types/cost.d.ts +0 -63
  50. package/lib/types/cost.js +0 -67
@@ -0,0 +1,131 @@
1
+ /**
2
+ * One text-metrics source for every character-based budget in the family.
3
+ *
4
+ * A budget is not a language: the same text needs different units for storage,
5
+ * display, context cost and quality heuristics. This module measures ONE string
6
+ * once and exposes the four units; callers choose a unit through a named budget
7
+ * instead of reaching for `String.length`, `[...text].length` or `slice()`.
8
+ *
9
+ * The token figure is deliberately an ESTIMATE. With no model tokenizer it uses
10
+ * a script-neutral conservative upper bound (`utf8Bytes / 3`, floored by
11
+ * `codePoints / 4`); a caller may inject a provider/model estimator later
12
+ * without changing any budget.
13
+ *
14
+ * @module @lmzhen/dsh-evolution-core
15
+ */
16
+ const segmenterCtor = Intl.Segmenter;
17
+ const segmenter = segmenterCtor === undefined
18
+ ? undefined
19
+ : new segmenterCtor(undefined, { granularity: 'grapheme' });
20
+ /** UTF-8 byte length; TextEncoder is available on every Node/browser target this package runs on. */
21
+ export function utf8ByteLength(text) {
22
+ return new TextEncoder().encode(text).length;
23
+ }
24
+ /** Unicode scalar-value count. */
25
+ export function codePointCount(text) {
26
+ let count = 0;
27
+ for (const _codePoint of text)
28
+ count += 1;
29
+ return count;
30
+ }
31
+ /**
32
+ * User-perceived character count.
33
+ * @param text - the string to measure.
34
+ * @returns grapheme clusters, or code points when the runtime has no Segmenter.
35
+ */
36
+ export function graphemeCount(text) {
37
+ if (segmenter === undefined)
38
+ return codePointCount(text);
39
+ let count = 0;
40
+ for (const _grapheme of segmenter.segment(text))
41
+ count += 1;
42
+ return count;
43
+ }
44
+ /** Split a string without ever cutting through a grapheme cluster. */
45
+ function graphemeParts(text) {
46
+ if (segmenter === undefined)
47
+ return [...text];
48
+ const parts = [];
49
+ for (const part of segmenter.segment(text)) {
50
+ const value = part.segment;
51
+ if (typeof value === 'string')
52
+ parts.push(value);
53
+ }
54
+ return parts;
55
+ }
56
+ /** The pure estimate from already-counted bytes/code points. */
57
+ function estimateFromCounts(bytes, codePoints) {
58
+ if (bytes === 0)
59
+ return { value: 0, low: 0, high: 0, source: 'unicode-heuristic' };
60
+ const low = Math.ceil(codePoints / 4);
61
+ const high = Math.ceil(bytes / 3);
62
+ return { value: Math.max(low, high), low, high, source: 'unicode-heuristic' };
63
+ }
64
+ /**
65
+ * Conservative, model-agnostic token estimate.
66
+ *
67
+ * English prose is about 4 characters/token; CJK prose is about 1 token/char.
68
+ * UTF-8 bytes encode that difference naturally (3 bytes for CJK, 1 for ASCII),
69
+ * so the upper bound is `bytes / 3` while `codePoints / 4` keeps the lower end
70
+ * anchored to the common English heuristic. The point estimate is the upper
71
+ * bound: early warnings are recoverable, silent over-budget is not.
72
+ * @param text - the string to estimate.
73
+ * @returns the estimate and its range; never an exact tokenizer count.
74
+ */
75
+ export function conservativeTokenEstimator(text) {
76
+ return estimateFromCounts(utf8ByteLength(text), codePointCount(text));
77
+ }
78
+ /**
79
+ * Measure every unit for one string in one pass over the text.
80
+ * @param text - the raw string; body callers should pass the on-disk form.
81
+ * @param estimator - optional exact/estimated token source; defaults to the conservative fallback.
82
+ * @returns all units and the token range.
83
+ */
84
+ export function measureText(text, estimator) {
85
+ const bytes = utf8ByteLength(text);
86
+ const codePoints = codePointCount(text);
87
+ return {
88
+ utf8Bytes: bytes,
89
+ codePoints,
90
+ graphemes: graphemeCount(text),
91
+ tokens: estimator === undefined ? estimateFromCounts(bytes, codePoints) : estimator(text),
92
+ degraded: segmenter === undefined,
93
+ };
94
+ }
95
+ /**
96
+ * Read one unit from a fresh measurement.
97
+ * @param text - the string to measure.
98
+ * @param unit - the budget unit to read.
99
+ * @param estimator - optional token source; ignored for non-token units.
100
+ * @returns the numeric value in that unit.
101
+ */
102
+ export function measureUnit(text, unit, estimator) {
103
+ const metrics = measureText(text, estimator);
104
+ switch (unit) {
105
+ case 'utf8Bytes': return metrics.utf8Bytes;
106
+ case 'codePoints': return metrics.codePoints;
107
+ case 'graphemes': return metrics.graphemes;
108
+ case 'tokens': return metrics.tokens.value;
109
+ }
110
+ }
111
+ /**
112
+ * Truncate to a grapheme budget without splitting emoji or combining sequences.
113
+ * The ellipsis counts inside `max`, matching how UI budgets are described.
114
+ * @param text - the string to shorten.
115
+ * @param max - maximum output graphemes, ellipsis included.
116
+ * @param ellipsis - marker appended when shortened; may itself be multi-grapheme.
117
+ * @returns the original text or a grapheme-safe prefix plus marker.
118
+ */
119
+ export function truncateGraphemes(text, max, ellipsis = '…') {
120
+ if (!Number.isFinite(max) || max <= 0)
121
+ return '';
122
+ const limit = Math.floor(max);
123
+ const parts = graphemeParts(text);
124
+ if (parts.length <= limit)
125
+ return text;
126
+ const marker = graphemeParts(ellipsis);
127
+ if (marker.length >= limit)
128
+ return marker.slice(0, limit).join('');
129
+ return parts.slice(0, limit - marker.length).join('') + ellipsis;
130
+ }
131
+ //# sourceMappingURL=text-metrics.js.map
@@ -1,9 +1,8 @@
1
1
  import { c as transactIo, o as nodeEvolutionIo } from "./io-GxghO3Ip.js";
2
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-TD4Pv92Q.js";
4
3
  import { n as isRecord } from "./guards-3f02mnf2.js";
4
+ import { p as parseFrontmatter, u as frontmatterBlock } from "./mutations-1wLISSrY.js";
5
5
  import { join } from "node:path";
6
- import { parse } from "yaml";
7
6
  //#region lib/types/reference-rewrite.js
8
7
  /**
9
8
  * Reference re-homing plans (0.5.0 V1, design §16.7).
@@ -185,518 +184,6 @@ function externalRefs(content) {
185
184
  return refs;
186
185
  }
187
186
  //#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
187
  //#region lib/types/document-body.js
701
188
  /**
702
189
  * What the panel shows when it renders one version as a document.
@@ -1302,4 +789,4 @@ async function updateSuppressedNames(root, io, task) {
1302
789
  });
1303
790
  }
1304
791
  //#endregion
1305
- export { h2Sections as A, shrinksOverLimit as B, saveUsage as C, usageObserved as D, usageFile as E, frontmatterBlock as F, supportRefs as G, validateFrontmatter as H, frontmatterCatalogInvalid as I, planReferenceRewrite as J, applyReferenceRewrite as K, normalizeFrontmatter as L, authoringFeedback as M, ensureSkillFrontmatter as N, selectSections as O, exceedsContentLimit as P, parseFrontmatter as R, saveSuppressedNames as S, updateSuppressedNames as T, yamlPlainScalarNeedsQuotes as U, skillMdOnDisk as V, externalRefs as W, planRehoming as Y, loadUsage as _, applyCuratorMetaFields as a, normalizeUsageRecord as b, bumpUse as c, emptyRecord as d, foldCuratorFields as f, loadSuppressedNames as g, latestActivityAt as h, applyCuratorLifecycleFields as i, readingStats as j, displayBodyOf as k, bumpView as l, idleDays as m, SUPPRESSED_FILE_VERSION as n, bumpPatch as o, getRecord as p, describeReferenceRewrite as q, VIEW_WINDOW_DAYS as r, bumpSupportRead as s, MAX_SUPPORT_READ_PATHS as t, daysSinceIso as u, markAgentCreated as v, suppressedFile as w, recentViewCount as x, mutateUsage as y, relatedSkillNames as z };
792
+ export { h2Sections as A, saveUsage as C, usageObserved as D, usageFile as E, describeReferenceRewrite as F, planReferenceRewrite as I, planRehoming as L, externalRefs as M, supportRefs as N, selectSections as O, applyReferenceRewrite as P, saveSuppressedNames as S, updateSuppressedNames as T, loadUsage as _, applyCuratorMetaFields as a, normalizeUsageRecord as b, bumpUse as c, emptyRecord as d, foldCuratorFields as f, loadSuppressedNames as g, latestActivityAt as h, applyCuratorLifecycleFields as i, readingStats as j, displayBodyOf as k, bumpView as l, idleDays as m, SUPPRESSED_FILE_VERSION as n, bumpPatch as o, getRecord as p, VIEW_WINDOW_DAYS as r, bumpSupportRead as s, MAX_SUPPORT_READ_PATHS as t, daysSinceIso as u, markAgentCreated as v, suppressedFile as w, recentViewCount as x, mutateUsage as y };
package/lib/write.js CHANGED
@@ -1,5 +1,6 @@
1
- import { r as contentHash } from "./mutations-DQXddSJd.js";
2
- import { $ as writeUnitReceipt, A as pruneTreeChangeUnits, B as UNIT_STORAGE_SCHEMA_VERSION, F as assertUnitJournalTransition, G as unitEvidencePath, H as readUnitIndex, I as readUnitJournal, J as unitSnapshotPath, K as unitIndexPath, L as unitJournalPath, M as unitSnapshotPort, N as UNIT_JOURNAL_PHASES, P as UNIT_JOURNAL_SCHEMA_VERSION, Q as writeUnitEvidence, R as unitJournalPhaseRank, U as readUnitReceipt, V as readUnitEvidence, W as readUnitSnapshot, X as unitStorageKey, Y as unitSnapshotsDir, Z as upsertUnitIndex, et as writeUnitSnapshot, it as WriteKernel, j as unitJournalPort, nt as fileMutationLock, p as entryTarget, q as unitReceiptPath, rt as validateMutationRequest, tt as MutationUnit, z as writeUnitJournal } from "./skill-history-CZp8vhyL.js";
1
+ import { r as contentHash } from "./mutations-1wLISSrY.js";
2
+ import { p as entryTarget } from "./skill-history-B-DyIedq.js";
3
+ import { C as writeUnitEvidence, D as fileMutationLock, E as MutationUnit, O as validateMutationRequest, S as upsertUnitIndex, T as writeUnitSnapshot, _ as unitIndexPath, a as UNIT_JOURNAL_SCHEMA_VERSION, b as unitSnapshotsDir, c as unitJournalPath, d as UNIT_STORAGE_SCHEMA_VERSION, f as readUnitEvidence, g as unitEvidencePath, h as readUnitSnapshot, i as UNIT_JOURNAL_PHASES, k as WriteKernel, l as unitJournalPhaseRank, m as readUnitReceipt, n as unitJournalPort, o as assertUnitJournalTransition, p as readUnitIndex, r as unitSnapshotPort, s as readUnitJournal, t as pruneTreeChangeUnits, u as writeUnitJournal, v as unitReceiptPath, w as writeUnitReceipt, x as unitStorageKey, y as unitSnapshotPath } from "./mutation-storage-adapter-BM7mIJKp.js";
3
4
  //#region lib/types/unit-undo.js
4
5
  /**
5
6
  * Cross-skill unit undo executor.