@lmzhen/dsh-evolution-core 0.54.0 → 0.55.1

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-BxDhKSki.js} +2 -1
  2. package/lib/extract.js +7 -7
  3. package/lib/index.js +830 -546
  4. package/lib/{limits-TD4Pv92Q.js → limits-CO4JGSJL.js} +20 -6
  5. package/lib/{skill-history-CZp8vhyL.js → mutation-storage-adapter-7R3ra0wj.js} +4 -647
  6. package/lib/mutations-mvTnWkua.js +592 -0
  7. package/lib/policy.js +9 -3
  8. package/lib/{quality-BLc6UQQb.js → quality-CREp6s1G.js} +1 -1
  9. package/lib/{skill-health-BIpiPvw6.js → review-context-70XYS11J.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-YX84wO20.js +647 -0
  13. package/lib/skills.js +16 -11
  14. package/lib/text-metrics-CyJhxWBs.js +132 -0
  15. package/lib/types/constants.d.ts +19 -5
  16. package/lib/types/constants.js +19 -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 +9 -8
  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 +7 -3
  40. package/lib/types/skill-store.js +2 -1
  41. package/lib/types/text-budgets.d.ts +185 -0
  42. package/lib/types/text-budgets.js +70 -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-DrczLTP4.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,647 @@
1
+ import { b as probeText, c as transactIo, m as isUnknown, p as isPresent } from "./io-GxghO3Ip.js";
2
+ import { et as TEXT_DIFF_MAX_GRAPHEMES } from "./limits-CO4JGSJL.js";
3
+ import { o as truncateGraphemes, r as graphemeCount } from "./text-metrics-CyJhxWBs.js";
4
+ import { r as contentHash } from "./mutations-mvTnWkua.js";
5
+ import { join } from "node:path";
6
+ //#region lib/types/skill-history.js
7
+ /**
8
+ * Skill content history: content-addressed blobs plus a per-skill version index.
9
+ *
10
+ * Why it exists: `.mutations.json` records before/after HASHES and calls every automated edit
11
+ * "reviewable and replayable" — but a hash cannot be replayed. With no content store, the only way
12
+ * back was a whole-tree snapshot (`.backups`, keep=5) or `.archive` (removed skills only), so
13
+ * reverting one skill cost the collateral of every other change in that window. This module keeps
14
+ * the content, keyed by skill and version.
15
+ *
16
+ * Invariants (design `dsh-evolution-skill-history-design.md` §1):
17
+ * - HISTORY IS HISTORY: the skill tree stays the single truth for "current content"; nothing here
18
+ * feeds a judgment — callers read back content and version NUMBERS only.
19
+ * - BEST-EFFORT, like the mutation audit: a failed history write warns and never fails the write
20
+ * that already landed.
21
+ * - Blobs are content-addressed, so identical bodies are stored once (across skills too).
22
+ * - Versions are numbered by `v` (max+1), NOT by the clock: a moved system clock must not reorder
23
+ * history (KiroCrew's `v<N>` choice, independently arrived at). Numbering and the index read-modify-write run
24
+ * under the INDEX's own io lock, so two writers of one skill cannot mint the same number.
25
+ * - The array's ORDER is append order, and the index is appended after the content lock is released, so two
26
+ * writers of ONE skill can interleave their appends. Each entry therefore carries `beforeHash` — the content
27
+ * it replaced, read under that writer's lock — and that link, not the position, is what `undo` follows
28
+ * ({@link orderVersions} rebuilds the content order for display when the chain is complete).
29
+ *
30
+ * NOT here: blob garbage collection. Trimming drops INDEX entries; orphan blobs stay until a
31
+ * sweeper collects them, because a reference count would have to span every skill's index and that
32
+ * belongs to the curator's whole-library pass, not to the write path.
33
+ * @module @lmzhen/dsh-evolution-core/skill-history
34
+ */
35
+ /** Root-level history directory. Dot-prefixed so skill discovery skips it. */
36
+ const HISTORY_DIR = ".history";
37
+ /** Versioned index shape, so a future field can migrate without guessing. */
38
+ const HISTORY_INDEX_VERSION = 1;
39
+ /** The action label for a predecessor the index had never seen (content found on disk before this
40
+ * feature existed, or a hand-edited tree): it says "this is what was there", not what wrote it. */
41
+ const BASELINE_ACTION = "baseline";
42
+ /** Default hard cap for a change summary, counted in grapheme clusters. */
43
+ const DEFAULT_SKILL_WRITE_SUMMARY_CHARS = 50;
44
+ /** Count a summary the same way the write gate does (graphemes, not UTF-16 units). */
45
+ function summaryChars(text) {
46
+ return graphemeCount(text);
47
+ }
48
+ /** Normalize a model-supplied summary: single line, trimmed, non-empty, within the hard cap. */
49
+ function normalizeChangeSummary(value, cap = 50) {
50
+ if (typeof value !== "string") return {
51
+ ok: false,
52
+ reason: "missing",
53
+ length: 0
54
+ };
55
+ const text = value.replace(/\s+/g, " ").trim();
56
+ if (text === "") return {
57
+ ok: false,
58
+ reason: "missing",
59
+ length: 0
60
+ };
61
+ if (value.includes("\n") || value.includes("\r")) return {
62
+ ok: false,
63
+ reason: "multiline",
64
+ length: summaryChars(text)
65
+ };
66
+ const length = summaryChars(text);
67
+ return length <= cap ? {
68
+ ok: true,
69
+ text
70
+ } : {
71
+ ok: false,
72
+ reason: "length",
73
+ length
74
+ };
75
+ }
76
+ /** Clip a host-generated summary to the same hard cap; host facts are not rejected. */
77
+ function clipChangeSummary(text, cap = 50) {
78
+ return truncateGraphemes(text.replace(/\s+/g, " ").trim(), cap);
79
+ }
80
+ /** The root-level history directory. */
81
+ function historyRoot(root) {
82
+ return join(root, HISTORY_DIR);
83
+ }
84
+ /** Content-addressed blob path: identical bodies share one file, across skills too. */
85
+ function blobPath(root, hash) {
86
+ return join(historyRoot(root), "blobs", hash);
87
+ }
88
+ /** One skill's index file. */
89
+ function historyIndexFile(root, name) {
90
+ return join(historyRoot(root), "skills", name, "index.json");
91
+ }
92
+ /**
93
+ * The versions in CONTENT order (oldest first), rebuilt from the chain links, for display.
94
+ *
95
+ * The stored array is append order, which interleaves when two writers of one skill audit out of
96
+ * order; the links say what actually replaced what. The rebuild runs only when it can account for
97
+ * EVERY entry (exactly one start and a forward link for each step) — otherwise the stored order is
98
+ * returned unchanged, because a partial reconstruction would be a worse answer than the honest one.
99
+ * @param versions - the stored index, oldest first as recorded.
100
+ * @returns the same entries, in content order when the chain is complete.
101
+ */
102
+ function orderVersions(versions) {
103
+ if (versions.length < 2) return [...versions];
104
+ const replaced = /* @__PURE__ */ new Set();
105
+ for (const entry of versions) if (entry.beforeHash !== void 0) replaced.add(entry.beforeHash);
106
+ const ends = versions.filter((entry) => !replaced.has(entry.hash));
107
+ if (ends.length !== 1) return [...versions];
108
+ const used = /* @__PURE__ */ new Set();
109
+ const backward = [];
110
+ let cursor = ends[0];
111
+ while (cursor !== void 0 && !used.has(cursor)) {
112
+ used.add(cursor);
113
+ backward.push(cursor);
114
+ const before = cursor.beforeHash;
115
+ cursor = before === void 0 ? void 0 : [...versions].reverse().find((entry) => !used.has(entry) && entry.hash === before);
116
+ }
117
+ return backward.length === versions.length ? backward.reverse() : [...versions];
118
+ }
119
+ /** The actions that record a SUPPORT FILE's bytes (they share the skill's version index). */
120
+ const SUPPORT_ACTIONS = ["write_file", "remove_file"];
121
+ /** The actions that record the skill's own SKILL.md body. */
122
+ const CONTENT_ACTIONS = [
123
+ "create",
124
+ "update",
125
+ "patch",
126
+ "consolidate",
127
+ "restructure",
128
+ "extract",
129
+ "restore",
130
+ "merge"
131
+ ];
132
+ /**
133
+ * Which artifact one recorded version holds, from the action that produced it.
134
+ * @param action - the entry's action label.
135
+ * @returns the artifact class; `other` when the label does not say.
136
+ */
137
+ function versionTarget(action) {
138
+ if (SUPPORT_ACTIONS.includes(action)) return "support";
139
+ if (CONTENT_ACTIONS.includes(action)) return "content";
140
+ return "other";
141
+ }
142
+ /**
143
+ * Which artifact one INDEX ENTRY holds.
144
+ *
145
+ * {@link versionTarget} reads the ACTION, which is enough for the entries a write mints under its own
146
+ * label and is NOT enough for a {@link BASELINE_ACTION}: a baseline minted for a support write holds
147
+ * that FILE's previous bytes while its action says only "this is what was there". Two facts recover
148
+ * the artifact:
149
+ *
150
+ * - `path` is written exactly when the bytes come from a support file, on BOTH entries one support
151
+ * write can mint, so it decides on its own;
152
+ * - an entry recorded before `path` existed has none, and the link is the evidence left: a support
153
+ * write names the content it replaced through `beforeHash`, so a baseline that a support write
154
+ * names as its predecessor holds that file's bytes.
155
+ *
156
+ * The inference runs only for a baseline. Every other entry keeps the action's verdict, which is also
157
+ * the fail-closed one for an action this module does not know.
158
+ * @param entry - one entry of a skill's index.
159
+ * @param index - the index the entry came from: the legacy link is only readable across the whole
160
+ * index. Omitting it answers from `path` and the action alone.
161
+ * @returns the artifact class; `other` when nothing attributes the bytes.
162
+ */
163
+ function entryTarget(entry, index = []) {
164
+ if (entry.path !== void 0) return "support";
165
+ if (entry.action !== "baseline") return versionTarget(entry.action);
166
+ return index.some((candidate) => SUPPORT_ACTIONS.includes(candidate.action) && candidate.beforeHash === entry.hash) ? "support" : "other";
167
+ }
168
+ /**
169
+ * Split one index into the skill body's chain and the support files' versions.
170
+ *
171
+ * Both share ONE index, so a skill that ever wrote a support file has two chains and
172
+ * {@link orderVersions} cannot account for every entry (it falls back to the stored order). Splitting
173
+ * first lets each group rebuild its own order, and keeps the body's chain intact by leaving every
174
+ * entry whose artifact nothing attributes in it — a `baseline` predecessor is usually the body's
175
+ * first link, and only the support-file baselines {@link entryTarget} recovers leave it.
176
+ * @param versions - the stored index, oldest first as recorded.
177
+ * @returns the two groups, each in content order when its chain is complete.
178
+ */
179
+ function partitionVersions(versions) {
180
+ const content = [];
181
+ const support = [];
182
+ for (const entry of versions) if (entryTarget(entry, versions) === "support") support.push(entry);
183
+ else content.push(entry);
184
+ return {
185
+ content: orderVersions(content),
186
+ support: orderVersions(support)
187
+ };
188
+ }
189
+ /**
190
+ * When this skill's content last changed: the newest `at` across BOTH chains, or null when the index
191
+ * holds nothing.
192
+ *
193
+ * The stored array is APPEND order and two writers of one skill can interleave, so the answer is the
194
+ * maximum timestamp rather than the tail. Every `at` this family writes is the same ISO-8601 UTC
195
+ * form, so comparing the strings is comparing the instants.
196
+ * @param versions - every entry the index holds, in any order.
197
+ * @returns the newest timestamp, or null when there is none to report.
198
+ */
199
+ function latestVersionAt(versions) {
200
+ let newest = null;
201
+ for (const entry of versions) if (newest === null || entry.at > newest) newest = entry.at;
202
+ return newest;
203
+ }
204
+ /** Keep nothing less than one version, whatever the deployment asks for. */
205
+ function clampKeep(keep) {
206
+ return Number.isFinite(keep) ? Math.max(1, Math.floor(keep)) : 1;
207
+ }
208
+ /** The next version number: max+1, never a timestamp. */
209
+ function nextVersion(versions) {
210
+ let max = 0;
211
+ for (const entry of versions) if (entry.v > max) max = entry.v;
212
+ return max + 1;
213
+ }
214
+ /** The last entry carrying this hash, or undefined (a hash may repeat after an undo). */
215
+ function lastVersionOf(versions, hash) {
216
+ for (let index = versions.length - 1; index >= 0; index -= 1) {
217
+ const entry = versions[index];
218
+ if (entry !== void 0 && entry.hash === hash) return entry.v;
219
+ }
220
+ }
221
+ /** One entry as this reader accepts it, or null when the entry cannot be understood. */
222
+ function readVersionEntry(entry) {
223
+ if (typeof entry !== "object" || entry === null) return null;
224
+ const candidate = entry;
225
+ if (typeof candidate.v !== "number" || !Number.isInteger(candidate.v) || candidate.v <= 0) return null;
226
+ if (typeof candidate.hash !== "string" || candidate.hash === "") return null;
227
+ if (typeof candidate.at !== "string") return null;
228
+ if (typeof candidate.action !== "string") return null;
229
+ if (typeof candidate.chars !== "number") return null;
230
+ const summary = typeof candidate.summary === "string" && candidate.summary !== "" ? candidate.summary : void 0;
231
+ const summarySource = candidate.summarySource === "model" || candidate.summarySource === "host" || candidate.summarySource === "fallback" ? candidate.summarySource : void 0;
232
+ const path = typeof candidate.path === "string" && candidate.path !== "" ? candidate.path : void 0;
233
+ const unitId = typeof candidate.unitId === "string" && candidate.unitId !== "" ? candidate.unitId : void 0;
234
+ const removed = candidate.removed === true ? true : void 0;
235
+ const unitHead = candidate.unitHead;
236
+ const base = {
237
+ v: candidate.v,
238
+ at: candidate.at,
239
+ action: candidate.action,
240
+ hash: candidate.hash,
241
+ chars: candidate.chars,
242
+ ...summary === void 0 ? {} : { summary },
243
+ ...summarySource === void 0 ? {} : { summarySource },
244
+ ...path === void 0 ? {} : { path },
245
+ ...unitId === void 0 ? {} : { unitId },
246
+ ...removed === void 0 ? {} : { removed },
247
+ ...unitHead === void 0 ? {} : { unitHead }
248
+ };
249
+ return typeof candidate.beforeHash === "string" && candidate.beforeHash !== "" ? {
250
+ ...base,
251
+ beforeHash: candidate.beforeHash
252
+ } : base;
253
+ }
254
+ /**
255
+ * Read one index body for a RECORDER: "understood", "no file", or "cannot be understood".
256
+ * A file whose shape is right but which carries an entry this reader would have to drop counts as
257
+ * unreadable — dropping it silently would be the overwrite the audit posture forbids.
258
+ * @param raw - the index file's bytes, or null when absent.
259
+ * @returns the three-state answer.
260
+ */
261
+ function readHistoryIndex(raw) {
262
+ if (raw === null) return { kind: "absent" };
263
+ if (raw.trim() === "") return { kind: "unreadable" };
264
+ let parsed;
265
+ try {
266
+ parsed = JSON.parse(raw);
267
+ } catch {
268
+ return { kind: "unreadable" };
269
+ }
270
+ if (typeof parsed !== "object" || parsed === null) return { kind: "unreadable" };
271
+ const holder = parsed;
272
+ if (typeof holder.version === "number" && holder.version > 1) return { kind: "unreadable" };
273
+ if (!Array.isArray(holder.versions)) return { kind: "unreadable" };
274
+ const versions = [];
275
+ for (const entry of holder.versions) {
276
+ const version = readVersionEntry(entry);
277
+ if (version === null) return { kind: "unreadable" };
278
+ versions.push(version);
279
+ }
280
+ return {
281
+ kind: "ok",
282
+ versions
283
+ };
284
+ }
285
+ /**
286
+ * Parse one index body for a READER. Malformed content, a foreign shape, or a version NEWER than this
287
+ * reader all read as empty — the audit posture: never guess. A recorder must use
288
+ * {@link readHistoryIndex} instead, because it has to PRESERVE bytes it cannot understand.
289
+ * @param raw - the index file's bytes, or null when absent.
290
+ * @returns the versions, oldest first.
291
+ */
292
+ function parseHistoryIndex(raw) {
293
+ const state = readHistoryIndex(raw);
294
+ return state.kind === "ok" ? state.versions : [];
295
+ }
296
+ /**
297
+ * The index after this write, and the version numbers it produced. Pure, so the versioning rules
298
+ * are testable without io.
299
+ *
300
+ * Two rules matter here: a predecessor the index has never seen gets a BASELINE entry (so the state
301
+ * before this mutation is recoverable even for a skill that predates the feature), and re-writing
302
+ * identical content mints NO new version (the library's no-op updates must not grow history).
303
+ * @param versions - the current index, oldest first.
304
+ * @param input - the write being recorded.
305
+ * @param keep - how many versions to retain per skill.
306
+ * @returns the trimmed index and the recorded numbers.
307
+ */
308
+ function nextHistoryIndex(versions, input, keep) {
309
+ const beforeHash = input.before === null ? null : contentHash(input.before);
310
+ const afterHash = input.after === null ? null : contentHash(input.after);
311
+ const grown = [...versions];
312
+ const pathField = input.path === void 0 ? {} : { path: input.path };
313
+ if (beforeHash !== null && !grown.some((entry) => entry.hash === beforeHash)) grown.push({
314
+ v: nextVersion(grown),
315
+ at: input.at,
316
+ action: BASELINE_ACTION,
317
+ hash: beforeHash,
318
+ chars: input.before?.length ?? 0,
319
+ ...pathField,
320
+ ...input.unitId === void 0 ? {} : { unitId: input.unitId }
321
+ });
322
+ const removalHash = afterHash === null ? beforeHash : null;
323
+ if (afterHash !== null) {
324
+ if (grown[grown.length - 1]?.hash !== afterHash) grown.push({
325
+ ...input.unitId === void 0 ? {} : { unitId: input.unitId },
326
+ ...input.unitHead === void 0 ? {} : { unitHead: input.unitHead },
327
+ v: nextVersion(grown),
328
+ at: input.at,
329
+ action: input.action,
330
+ hash: afterHash,
331
+ chars: input.after?.length ?? 0,
332
+ ...pathField,
333
+ ...input.summary === void 0 ? {} : { summary: input.summary },
334
+ ...input.summarySource === void 0 ? {} : { summarySource: input.summarySource },
335
+ ...beforeHash === null ? {} : { beforeHash }
336
+ });
337
+ }
338
+ if (removalHash !== null) {
339
+ const tail = grown[grown.length - 1];
340
+ if (tail?.hash !== removalHash || tail.action !== input.action) grown.push({
341
+ v: nextVersion(grown),
342
+ at: input.at,
343
+ action: input.action,
344
+ hash: removalHash,
345
+ chars: input.before?.length ?? 0,
346
+ removed: true,
347
+ ...pathField,
348
+ ...input.unitId === void 0 ? {} : { unitId: input.unitId },
349
+ ...input.unitHead === void 0 ? {} : { unitHead: input.unitHead },
350
+ ...input.summary === void 0 ? {} : { summary: input.summary },
351
+ ...input.summarySource === void 0 ? {} : { summarySource: input.summarySource }
352
+ });
353
+ }
354
+ const budget = clampKeep(keep);
355
+ const groups = [];
356
+ const byUnit = /* @__PURE__ */ new Map();
357
+ for (const entry of grown) {
358
+ const unit = entry.unitId;
359
+ if (unit === void 0) {
360
+ groups.push([entry]);
361
+ continue;
362
+ }
363
+ const found = byUnit.get(unit);
364
+ if (found !== void 0) {
365
+ found.push(entry);
366
+ continue;
367
+ }
368
+ const made = [entry];
369
+ byUnit.set(unit, made);
370
+ groups.push(made);
371
+ }
372
+ const keptIndexes = /* @__PURE__ */ new Set();
373
+ let keptCount = 0;
374
+ for (let i = groups.length - 1; i >= 0; i -= 1) {
375
+ const group = groups[i];
376
+ if (group === void 0) continue;
377
+ if (keptCount > 0 && keptCount + group.length > budget) break;
378
+ for (const entry of group) keptIndexes.add(grown.indexOf(entry));
379
+ keptCount += group.length;
380
+ }
381
+ const trimmed = grown.filter((_, index) => keptIndexes.has(index));
382
+ const recorded = {};
383
+ if (beforeHash !== null) {
384
+ const v = lastVersionOf(trimmed, beforeHash);
385
+ if (v !== void 0) recorded.beforeVersion = v;
386
+ }
387
+ if (afterHash !== null) {
388
+ const v = lastVersionOf(trimmed, afterHash);
389
+ if (v !== void 0) recorded.afterVersion = v;
390
+ }
391
+ return {
392
+ versions: trimmed,
393
+ recorded
394
+ };
395
+ }
396
+ /** Shrink level at which the retention line speaks: a body that keeps less than this share of the
397
+ * previous one is a rewrite, not an edit. */
398
+ const RETENTION_FEEDBACK_KEEP_RATIO = .5;
399
+ /** Floor on the REPLACED body: below this a ratio is noise (a 40-character skill cut in half is not
400
+ * news), so the line stays off for small skills. */
401
+ const RETENTION_FEEDBACK_MIN_CHARS = 200;
402
+ /**
403
+ * The anti-overwrite feedback line (design §4, item 3): says how much of the previous body a
404
+ * replacement kept, so a destructive rewrite is visible in the same message that reports the write.
405
+ *
406
+ * Computed where the replaced bytes are still in hand — the write path's own in-lock read — instead of
407
+ * re-reading the file from a caller (that second read would race the writers this library serializes).
408
+ * It is FEEDBACK, never a gate: no ratio refuses a write, and the function owns no configuration
409
+ * (a toggle nobody reads would be configuration that does nothing).
410
+ *
411
+ * @param input - the write being described.
412
+ * @returns the line, or null when the write is not a significant whole-body replacement.
413
+ */
414
+ function contentRetentionFeedback(input) {
415
+ if (input.action !== "update") return null;
416
+ const before = input.before;
417
+ const after = input.after;
418
+ if (before === null || after === null) return null;
419
+ if (before.length < 200) return null;
420
+ if (after.length >= before.length * .5) return null;
421
+ return `新内容保留了上一版正文的 ${Math.round(after.length / before.length * 100)}%(${after.length}/${before.length} 字符);被替换的版本已保留在该技能的历史里。`;
422
+ }
423
+ /**
424
+ * Read one skill's versions, oldest first.
425
+ * @param root - the skills root.
426
+ * @param io - the io seam.
427
+ * @param name - the skill name.
428
+ * @returns the versions; an absent or unreadable index reads as empty (never a throw).
429
+ */
430
+ async function loadVersions(root, io, name) {
431
+ const file = historyIndexFile(root, name);
432
+ const probe = await probeText(io, file);
433
+ if (isUnknown(probe)) {
434
+ console.warn(`skill-store: ${file} could not be read (${probe.reason}); reporting no versions for "${name}" — the bytes are untouched`);
435
+ return [];
436
+ }
437
+ return parseHistoryIndex(isPresent(probe) ? probe.value : null);
438
+ }
439
+ /**
440
+ * One version's content.
441
+ * @param root - the skills root.
442
+ * @param io - the io seam.
443
+ * @param name - the skill name.
444
+ * @param v - the version number.
445
+ * @returns the content, or null when the version or its blob cannot be read (never '').
446
+ */
447
+ async function loadVersionContent(root, io, name, v) {
448
+ const entry = (await loadVersions(root, io, name)).find((candidate) => candidate.v === v);
449
+ if (entry === void 0) return null;
450
+ const probe = await probeText(io, blobPath(root, entry.hash));
451
+ if (isUnknown(probe)) {
452
+ console.warn(`skill-store: version ${v} of "${name}" could not be read (${probe.reason}); reporting no content`);
453
+ return null;
454
+ }
455
+ return isPresent(probe) ? probe.value : null;
456
+ }
457
+ async function recordVersions(root, io, input, keep, fence) {
458
+ if (input.before === null && input.after === null) return null;
459
+ for (const side of [input.before, input.after]) {
460
+ if (side === null) continue;
461
+ const path = blobPath(root, contentHash(side));
462
+ let blobPresent;
463
+ try {
464
+ blobPresent = await io.exists(path);
465
+ } catch (error) {
466
+ blobPresent = false;
467
+ console.warn(`skill-store: could not check whether the history blob ${path} exists (${error instanceof Error ? error.message : String(error)}); writing it — content-addressed bytes are the same file`);
468
+ }
469
+ if (!blobPresent) await io.writeText(path, side);
470
+ }
471
+ const file = historyIndexFile(root, input.skillName);
472
+ const fileProbe = await probeText(io, file);
473
+ if (isUnknown(fileProbe)) {
474
+ const quarantine = `${file}.corrupt`;
475
+ try {
476
+ await io.copy(file, quarantine);
477
+ } catch {}
478
+ console.warn(`skill-store: ${file} could not be read (${fileProbe.reason}); its bytes were copied to ${quarantine} where possible and the version record for this write was abandoned — the mutation stands and the file is untouched`);
479
+ return null;
480
+ }
481
+ const probe = readHistoryIndex(isPresent(fileProbe) ? fileProbe.value : null);
482
+ if (probe.kind === "unreadable") {
483
+ const quarantine = `${file}.corrupt`;
484
+ await io.copy(file, quarantine);
485
+ console.warn(`skill-store: ${file} could not be understood (malformed, foreign, or written by a newer reader); its bytes were copied to ${quarantine} and a fresh index starts from this write`);
486
+ }
487
+ const recorded = {};
488
+ let raceRefused = false;
489
+ const write = async () => {
490
+ await transactIo(io, file, (current) => {
491
+ const state = readHistoryIndex(current);
492
+ if (state.kind === "unreadable" && probe.kind !== "unreadable") {
493
+ raceRefused = true;
494
+ return current;
495
+ }
496
+ const { versions, recorded: numbers } = nextHistoryIndex(state.kind === "ok" ? state.versions : [], input, keep);
497
+ recorded.beforeVersion = numbers.beforeVersion;
498
+ recorded.afterVersion = numbers.afterVersion;
499
+ return JSON.stringify({
500
+ version: 1,
501
+ versions
502
+ }, null, 2);
503
+ });
504
+ };
505
+ if (fence !== void 0) await fence.run(write);
506
+ else await write();
507
+ if (raceRefused) {
508
+ const quarantine = `${file}.corrupt`;
509
+ try {
510
+ await io.copy(file, quarantine);
511
+ } catch {}
512
+ console.warn(`skill-store: ${file} became unreadable between the probe and the locked read; its bytes were copied to ${quarantine} where possible and the version record for this write was abandoned — nothing was overwritten`);
513
+ return null;
514
+ }
515
+ return recorded;
516
+ }
517
+ /**
518
+ * Classify one version action for display. Fail-closed like {@link versionTarget}: an action this
519
+ * module does not know reads as `other` rather than being guessed, and `tests/skill-history.spec.ts`
520
+ * pins every action the library can write, so a new one cannot land unclassified.
521
+ * @param action - the entry’s action label.
522
+ * @returns the kind the faces switch on.
523
+ */
524
+ function versionActionKind(action) {
525
+ switch (action) {
526
+ case BASELINE_ACTION: return "baseline";
527
+ case "create": return "create";
528
+ case "patch":
529
+ case "edit": return "patch";
530
+ case "update": return "update";
531
+ case "restore": return "restore";
532
+ case "delete": return "delete";
533
+ case "archive": return "archive";
534
+ case "consolidate": return "consolidate";
535
+ case "restructure": return "restructure";
536
+ case "extract": return "extract";
537
+ case "merge": return "merge";
538
+ case "write_file": return "support-write";
539
+ case "remove_file": return "support-remove";
540
+ default: return "other";
541
+ }
542
+ }
543
+ /** Lines one changed region may carry before it is windowed and flagged. */
544
+ const TEXT_DIFF_MAX_LINES = 40;
545
+ /** Characters one windowed side may carry, so a single enormous line cannot travel whole. */
546
+ const TEXT_DIFF_MAX_CHARS = TEXT_DIFF_MAX_GRAPHEMES;
547
+ /**
548
+ * The facts of one whole-body replacement: how many lines the changed region gained and lost, and
549
+ * that region itself as one hunk.
550
+ *
551
+ * The algorithm is the honest one for "what did this edit touch": common leading and trailing lines
552
+ * are trimmed away and what remains is ONE contiguous region. It is not a minimal edit script — a
553
+ * body edited in two distant places reports their span as one region — and that limitation is the
554
+ * reason the faces show the region as context rather than as a line-by-line proof.
555
+ * @param before - the body the write replaced.
556
+ * @param after - the body the write stored.
557
+ * @param path - the path the hunk names (the platform’s diff card requires one).
558
+ * @param maxLines - the window a region’s text is capped to.
559
+ * @returns the counts, the windowed hunk, and whether the window cut anything.
560
+ */
561
+ function textDiffFacts(before, after, path, maxLines = 40) {
562
+ const oldLines = before === "" ? [] : before.split("\n");
563
+ const newLines = after === "" ? [] : after.split("\n");
564
+ let head = 0;
565
+ while (head < oldLines.length && head < newLines.length && oldLines[head] === newLines[head]) head += 1;
566
+ let tail = 0;
567
+ while (tail < oldLines.length - head && tail < newLines.length - head && oldLines[oldLines.length - 1 - tail] === newLines[newLines.length - 1 - tail]) tail += 1;
568
+ const oldRegion = oldLines.slice(head, oldLines.length - tail);
569
+ const newRegion = newLines.slice(head, newLines.length - tail);
570
+ if (oldRegion.length === 0 && newRegion.length === 0) return {
571
+ linesAdded: 0,
572
+ linesRemoved: 0,
573
+ hunks: [],
574
+ truncated: false
575
+ };
576
+ const window = (lines) => {
577
+ const joined = lines.slice(0, maxLines).join("\n");
578
+ if (graphemeCount(joined) <= TEXT_DIFF_MAX_CHARS) return {
579
+ text: joined,
580
+ cut: lines.length > maxLines
581
+ };
582
+ return {
583
+ text: truncateGraphemes(joined, TEXT_DIFF_MAX_CHARS, ""),
584
+ cut: true
585
+ };
586
+ };
587
+ const oldWindow = window(oldRegion);
588
+ const newWindow = window(newRegion);
589
+ return {
590
+ linesAdded: newRegion.length,
591
+ linesRemoved: oldRegion.length,
592
+ hunks: [{
593
+ path,
594
+ oldText: oldWindow.text,
595
+ newText: newWindow.text
596
+ }],
597
+ truncated: oldWindow.cut || newWindow.cut
598
+ };
599
+ }
600
+ /**
601
+ * How long ago an ISO timestamp was, as a bucket plus a count — never as a sentence.
602
+ *
603
+ * The shape deliberately mirrors the platform’s `relativeTime` (`ui-primitives`), so a face that later
604
+ * may import the platform helper swaps one call and keeps its dictionary; the WORDS live in the
605
+ * faces (the panel’s locale dictionary, the command surface’s English), which is why this module
606
+ * returns numbers.
607
+ * @param at - an ISO timestamp, or any string `Date.parse` understands.
608
+ * @param nowMs - the reference instant.
609
+ * @returns the bucket and its count; an unparsable timestamp reads as `now` with 0.
610
+ */
611
+ function elapsedSince(at, nowMs) {
612
+ const then = Date.parse(at);
613
+ if (Number.isNaN(then)) return {
614
+ unit: "now",
615
+ n: 0
616
+ };
617
+ const minutes = Math.floor(Math.max(0, nowMs - then) / 6e4);
618
+ if (minutes < 1) return {
619
+ unit: "now",
620
+ n: 0
621
+ };
622
+ if (minutes < 60) return {
623
+ unit: "minutes",
624
+ n: minutes
625
+ };
626
+ const hours = Math.floor(minutes / 60);
627
+ if (hours < 24) return {
628
+ unit: "hours",
629
+ n: hours
630
+ };
631
+ const days = Math.floor(hours / 24);
632
+ if (days < 30) return {
633
+ unit: "days",
634
+ n: days
635
+ };
636
+ const months = Math.floor(days / 30);
637
+ if (months < 12) return {
638
+ unit: "months",
639
+ n: months
640
+ };
641
+ return {
642
+ unit: "years",
643
+ n: Math.max(1, Math.floor(days / 365))
644
+ };
645
+ }
646
+ //#endregion
647
+ export { partitionVersions as C, textDiffFacts as D, summaryChars as E, versionActionKind as O, parseHistoryIndex as S, recordVersions as T, loadVersionContent as _, RETENTION_FEEDBACK_KEEP_RATIO as a, normalizeChangeSummary as b, TEXT_DIFF_MAX_LINES as c, contentRetentionFeedback as d, elapsedSince as f, latestVersionAt as g, historyRoot as h, HISTORY_INDEX_VERSION as i, versionTarget as k, blobPath as l, historyIndexFile as m, DEFAULT_SKILL_WRITE_SUMMARY_CHARS as n, RETENTION_FEEDBACK_MIN_CHARS as o, entryTarget as p, HISTORY_DIR as r, TEXT_DIFF_MAX_CHARS as s, BASELINE_ACTION as t, clipChangeSummary as u, loadVersions as v, readHistoryIndex as w, orderVersions as x, nextHistoryIndex as y };