@lmzhen/dsh-evolution-core 0.41.0 → 0.42.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 (55) hide show
  1. package/lib/composition/index.js +2 -2
  2. package/lib/{composition-Da8NfRI7.js → composition-CVafrlEw.js} +2 -2
  3. package/lib/guards-3f02mnf2.js +29 -0
  4. package/lib/http-routes.js +205 -1
  5. package/lib/index.js +3587 -15048
  6. package/lib/mutations-jUuOPaCn.js +718 -0
  7. package/lib/platform/index.js +2 -2
  8. package/lib/{platform-CFp373_0.js → platform-B06_h8t-.js} +4 -1
  9. package/lib/runtime/plugin.js +2 -2
  10. package/lib/{session-projection-CXUNPkq9.js → session-projection-EB7mUOlJ.js} +63 -63
  11. package/lib/skill-health-BLGZTIv8.js +3773 -0
  12. package/lib/skill-history-_Cssts5o.js +1912 -0
  13. package/lib/skills.js +4067 -0
  14. package/lib/subagent/index.js +1 -1
  15. package/lib/types/home-fence.d.ts +7 -0
  16. package/lib/types/home-fence.js +58 -3
  17. package/lib/types/index.d.ts +1 -18
  18. package/lib/types/index.js +1 -18
  19. package/lib/types/io.js +1 -1
  20. package/lib/types/mutation-authority.d.ts +14 -37
  21. package/lib/types/mutation-authority.js +16 -103
  22. package/lib/types/mutation-storage-adapter.js +9 -6
  23. package/lib/types/mutation-unit.d.ts +14 -0
  24. package/lib/types/mutation-unit.js +30 -10
  25. package/lib/types/opt-in.js +1 -1
  26. package/lib/types/platform/index.d.ts +8 -1
  27. package/lib/types/platform/index.js +3 -0
  28. package/lib/types/review-channel.js +3 -1
  29. package/lib/types/review-context.js +3 -1
  30. package/lib/types/run-registry.d.ts +2 -24
  31. package/lib/types/scope.js +1 -1
  32. package/lib/types/signals.d.ts +1 -1
  33. package/lib/types/skill-store.d.ts +7 -1
  34. package/lib/types/skill-store.js +43 -80
  35. package/lib/types/skills.d.ts +11 -0
  36. package/lib/types/skills.js +11 -0
  37. package/lib/types/subagent/types.d.ts +3 -3
  38. package/lib/types/tree-lock.js +4 -1
  39. package/lib/types/unit-claim.d.ts +8 -0
  40. package/lib/types/unit-claim.js +3 -0
  41. package/lib/types/unit-journal.d.ts +3 -1
  42. package/lib/types/unit-journal.js +12 -3
  43. package/lib/types/unit-storage.d.ts +1 -0
  44. package/lib/types/write-gates.d.ts +1 -1
  45. package/lib/types/write-gates.js +3 -1
  46. package/lib/types/write.d.ts +11 -0
  47. package/lib/types/write.js +11 -0
  48. package/lib/write.js +357 -0
  49. package/package.json +16 -4
  50. package/lib/http-routes-_anZVlPf.js +0 -233
  51. package/lib/types/unit-backend.d.ts +0 -5
  52. package/lib/types/unit-backend.js +0 -55
  53. package/lib/types/unit-transaction.d.ts +0 -225
  54. package/lib/types/unit-transaction.js +0 -501
  55. package/lib/{ensure-C5Mo1dbB.js → ensure-BjToTMMj.js} +1 -1
@@ -0,0 +1,1912 @@
1
+ import { D as probeText, b as isUnknown, l as isCommittedWarning, p as transactIo, r as contentHash, u as isProcessAlive, y as isPresent } from "./mutations-jUuOPaCn.js";
2
+ import { basename, dirname, isAbsolute, join, relative } from "node:path";
3
+ import { createHash, randomUUID } from "node:crypto";
4
+ //#region lib/types/write-kernel.js
5
+ /**
6
+ * The family's single write primitive: compare the baseline INSIDE the write
7
+ * transaction, never overwrite a concurrent value, and compensate only this
8
+ * unit's own writes. Business state machines stay in their domain owners.
9
+ */
10
+ var WriteKernel = class {
11
+ io;
12
+ transact;
13
+ now;
14
+ constructor(options) {
15
+ this.io = options.io;
16
+ this.transact = options.transact;
17
+ this.now = options.now ?? Date.now;
18
+ }
19
+ /** @returns the current time source; exposed for adapters that stamp evidence. */
20
+ clock() {
21
+ return this.now();
22
+ }
23
+ /**
24
+ * Run a read-modify-write task inside the same transaction seam. Unlike
25
+ * writeOne, task errors keep their type (state files rely on WRITE_GATE_ERROR_NAME)
26
+ * and only committed-only failures become warnings. expected is optional because
27
+ * the state medium passes the task the locked current value itself.
28
+ */
29
+ async run(target, task) {
30
+ let invoked = false;
31
+ let conflict = false;
32
+ const invoke = async (current) => {
33
+ if (target.expected !== void 0 && current !== target.expected) {
34
+ conflict = true;
35
+ throw Object.assign(/* @__PURE__ */ new Error("concurrent modification detected: " + target.path), { noWrite: true });
36
+ }
37
+ invoked = true;
38
+ return await task(current);
39
+ };
40
+ try {
41
+ if (this.transact !== void 0) await this.transact(this.io, target.path, invoke);
42
+ else if (this.io.transact !== void 0) await this.io.transact(target.path, invoke);
43
+ else {
44
+ const current = await this.io.readText(target.path);
45
+ const next = await invoke(current);
46
+ if (next === null && current !== null) await this.io.remove(target.path);
47
+ else if (next !== null && next !== current) await this.io.writeText(target.path, next);
48
+ }
49
+ } catch (error) {
50
+ if (conflict) throw Object.assign(/* @__PURE__ */ new Error("concurrent modification detected: " + target.path), { noWrite: true });
51
+ if (isCommittedWarning(error)) return { warnings: [error instanceof Error ? error.message : String(error)] };
52
+ throw error;
53
+ }
54
+ if (!invoked) throw new Error("internal error: the write transaction for " + target.path + " did not invoke the task; no write was performed");
55
+ return {};
56
+ }
57
+ /**
58
+ * Write one target only if the current bytes still equal the baseline.
59
+ * A conflict performs no write. With guardBaseline:false a stale callback
60
+ * defers (returns the current bytes) so a retrying transact can re-observe;
61
+ * if no retry ever writes, the result is still a conflict.
62
+ */
63
+ async writeOne(target, options = {}) {
64
+ const guard = options.guardBaseline !== false;
65
+ let wrote = false;
66
+ let deferred = false;
67
+ let conflict = false;
68
+ const task = (current) => {
69
+ if (current !== target.expected) {
70
+ if (guard) {
71
+ conflict = true;
72
+ throw Object.assign(/* @__PURE__ */ new Error("concurrent modification detected: " + target.path), { noWrite: true });
73
+ }
74
+ deferred = true;
75
+ return current;
76
+ }
77
+ wrote = true;
78
+ return target.next;
79
+ };
80
+ try {
81
+ if (this.transact !== void 0) await this.transact(this.io, target.path, task);
82
+ else if (this.io.transact !== void 0) await this.io.transact(target.path, task);
83
+ else {
84
+ const current = await this.io.readText(target.path);
85
+ const next = task(current);
86
+ if (next === null && current !== null) await this.io.remove(target.path);
87
+ else if (next !== null && next !== current) await this.io.writeText(target.path, next);
88
+ }
89
+ } catch (error) {
90
+ if (conflict) return {
91
+ ok: false,
92
+ changed: [],
93
+ errors: [{
94
+ code: "cas-conflict",
95
+ message: error instanceof Error ? error.message : String(error),
96
+ target: target.path
97
+ }]
98
+ };
99
+ if (isCommittedWarning(error)) return {
100
+ ok: true,
101
+ changed: [target.path],
102
+ errors: [],
103
+ warnings: [error instanceof Error ? error.message : String(error)]
104
+ };
105
+ return {
106
+ ok: false,
107
+ changed: [],
108
+ errors: [{
109
+ code: "write-failed",
110
+ message: error instanceof Error ? error.message : String(error),
111
+ target: target.path
112
+ }]
113
+ };
114
+ }
115
+ if (conflict || !wrote && deferred) return {
116
+ ok: false,
117
+ changed: [],
118
+ errors: [{
119
+ code: "cas-conflict",
120
+ message: "concurrent modification detected: " + target.path,
121
+ target: target.path
122
+ }]
123
+ };
124
+ if (!wrote) return {
125
+ ok: false,
126
+ changed: [],
127
+ errors: [{
128
+ code: "write-failed",
129
+ message: "transaction did not invoke the write task: " + target.path,
130
+ target: target.path
131
+ }]
132
+ };
133
+ return {
134
+ ok: true,
135
+ changed: [target.path],
136
+ errors: []
137
+ };
138
+ }
139
+ /**
140
+ * Write a plan in order. A preflight drift writes nothing; a later failure
141
+ * compensates only the targets this commit wrote, and only while they still
142
+ * hold this commit's bytes.
143
+ */
144
+ async commit(targets) {
145
+ for (const target of targets) if (await this.io.readText(target.path) !== target.expected) return {
146
+ ok: false,
147
+ changed: [],
148
+ errors: [{
149
+ code: "cas-conflict",
150
+ message: "target changed after plan: " + target.path,
151
+ target: target.path
152
+ }]
153
+ };
154
+ const written = [];
155
+ for (const target of targets) {
156
+ const result = await this.writeOne(target);
157
+ if (!result.ok) {
158
+ const compensation = await this.compensate(written);
159
+ return {
160
+ ok: false,
161
+ changed: written.map((item) => item.path),
162
+ errors: [...result.errors, ...compensation]
163
+ };
164
+ }
165
+ written.push(target);
166
+ }
167
+ return {
168
+ ok: true,
169
+ changed: written.map((item) => item.path),
170
+ errors: []
171
+ };
172
+ }
173
+ /**
174
+ * Restore a target to its before bytes only if it still holds the bytes this
175
+ * unit wrote. A concurrent writer wins and the compensation is reported.
176
+ */
177
+ async restore(target) {
178
+ const result = await this.writeOne({
179
+ path: target.path,
180
+ expected: target.after,
181
+ next: target.before
182
+ });
183
+ if (result.ok) return result;
184
+ if (result.errors.some((error) => error.code === "cas-conflict")) return {
185
+ ok: false,
186
+ changed: [],
187
+ errors: [{
188
+ code: "compensation-blocked",
189
+ message: "compensation refused: target changed after this unit; leave the concurrent bytes in place",
190
+ target: target.path
191
+ }]
192
+ };
193
+ return result;
194
+ }
195
+ async compensate(written) {
196
+ const errors = [];
197
+ for (const target of [...written].reverse()) {
198
+ const result = await this.restore({
199
+ path: target.path,
200
+ before: target.expected,
201
+ after: target.next
202
+ });
203
+ if (!result.ok) errors.push(...result.errors);
204
+ }
205
+ return errors;
206
+ }
207
+ };
208
+ //#endregion
209
+ //#region lib/types/mutation-unit.js
210
+ function underRoot(rootDir, target) {
211
+ if (rootDir === void 0 || rootDir === "") return false;
212
+ const rel = relative(rootDir, target);
213
+ return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);
214
+ }
215
+ /**
216
+ * Pure preflight for one mutation request. It deliberately does no IO: the
217
+ * caller must resolve roots and read bodies before this point; the unit kernel
218
+ * performs CAS/protection/journal after validation.
219
+ */
220
+ function validateMutationRequest(request, limits) {
221
+ const errors = [];
222
+ const roots = [];
223
+ for (const root of request.roots) {
224
+ const name = root.name.trim();
225
+ if (name === "") {
226
+ errors.push({
227
+ code: "root-empty",
228
+ message: "mutation root name is empty"
229
+ });
230
+ continue;
231
+ }
232
+ if (roots.some((entry) => entry.name === name)) {
233
+ errors.push({
234
+ code: "root-duplicate",
235
+ message: "duplicate mutation root " + name
236
+ });
237
+ continue;
238
+ }
239
+ roots.push({
240
+ name,
241
+ protection: root.protection
242
+ });
243
+ }
244
+ const primary = request.name.trim();
245
+ if (request.rootDirs !== void 0) {
246
+ for (const root of roots) if (request.rootDirs[root.name] === void 0) errors.push({
247
+ code: "root-dir-missing",
248
+ message: "no directory for mutation root " + root.name
249
+ });
250
+ }
251
+ if (!roots.some((root) => root.name === primary)) errors.push({
252
+ code: "root-primary-missing",
253
+ message: "primary skill " + primary + " is not in roots"
254
+ });
255
+ if (request.ops.length === 0) errors.push({
256
+ code: "ops-empty",
257
+ message: "mutation has no operations"
258
+ });
259
+ const seen = /* @__PURE__ */ new Set();
260
+ const ops = [];
261
+ for (const op of request.ops) {
262
+ const target = op.target.trim();
263
+ if (target === "") {
264
+ errors.push({
265
+ code: "target-empty",
266
+ message: "operation target is empty"
267
+ });
268
+ continue;
269
+ }
270
+ if (seen.has(target)) {
271
+ errors.push({
272
+ code: "target-duplicate",
273
+ message: "duplicate operation target " + target,
274
+ target
275
+ });
276
+ continue;
277
+ }
278
+ seen.add(target);
279
+ const skill = op.skill?.trim();
280
+ if (skill !== void 0 && !roots.some((root) => root.name === skill)) {
281
+ errors.push({
282
+ code: "op-skill-unknown",
283
+ message: "operation skill " + skill + " is not in roots",
284
+ target
285
+ });
286
+ continue;
287
+ }
288
+ if (request.rootDirs !== void 0) {
289
+ if ((skill === void 0 ? roots.find((root) => underRoot(request.rootDirs?.[root.name], target)) : underRoot(request.rootDirs[skill], target) ? { name: skill } : void 0) === void 0) {
290
+ errors.push({
291
+ code: "target-outside-root",
292
+ message: "operation target is outside its declared root",
293
+ target
294
+ });
295
+ continue;
296
+ }
297
+ }
298
+ if (op.kind === "write") {
299
+ if (Buffer.byteLength(op.content, "utf8") > limits.maxSkillFileBytes) {
300
+ errors.push({
301
+ code: "file-too-large",
302
+ message: "write exceeds " + limits.maxSkillFileBytes + " bytes",
303
+ target
304
+ });
305
+ continue;
306
+ }
307
+ if (basename(target) === "SKILL.md" && op.content.length > limits.maxSkillContentChars) {
308
+ errors.push({
309
+ code: "skill-too-large",
310
+ message: "SKILL.md exceeds " + limits.maxSkillContentChars + " characters",
311
+ target
312
+ });
313
+ continue;
314
+ }
315
+ ops.push({
316
+ ...op,
317
+ target
318
+ });
319
+ } else ops.push({
320
+ ...op,
321
+ target
322
+ });
323
+ }
324
+ return {
325
+ ok: errors.length === 0,
326
+ roots,
327
+ ops,
328
+ errors
329
+ };
330
+ }
331
+ const noLock = { async acquire() {
332
+ return { async release() {} };
333
+ } };
334
+ const identitySerial = async (task) => await task();
335
+ var MutationUnit = class {
336
+ io;
337
+ limits;
338
+ serial;
339
+ lock;
340
+ journal;
341
+ snapshots;
342
+ claim;
343
+ claimRunId;
344
+ hooks;
345
+ context;
346
+ validateWrite;
347
+ kernel;
348
+ transactGuard;
349
+ now;
350
+ journalId;
351
+ constructor(options) {
352
+ this.io = options.io;
353
+ this.limits = options.limits;
354
+ this.serial = options.serial ?? identitySerial;
355
+ if (options.lock === void 0 && options.nested !== true) throw new Error("mutation-unit: a lock (or an explicit nested:true under an outer fence) is required");
356
+ this.lock = options.lock ?? noLock;
357
+ this.journal = options.journal;
358
+ this.snapshots = options.snapshots;
359
+ this.claim = options.claim;
360
+ this.claimRunId = options.claimRunId;
361
+ this.hooks = options.hooks;
362
+ this.context = options.context;
363
+ this.validateWrite = options.validateWrite;
364
+ this.transactGuard = options.transactGuard !== false;
365
+ this.now = options.now ?? Date.now;
366
+ this.journalId = "j-" + String(this.now()) + "-" + Math.random().toString(36).slice(2);
367
+ const transact = options.transact;
368
+ this.kernel = new WriteKernel({
369
+ io: this.io,
370
+ ...transact === void 0 ? {} : { transact },
371
+ now: this.now
372
+ });
373
+ }
374
+ preview(request) {
375
+ const validation = validateMutationRequest(request, this.limits);
376
+ return {
377
+ ok: validation.ok,
378
+ unitId: request.unitId ?? "preview-" + String(this.now()),
379
+ roots: validation.roots,
380
+ ops: validation.ops,
381
+ errors: validation.errors
382
+ };
383
+ }
384
+ async apply(request) {
385
+ const primary = request.name.trim();
386
+ const unitId = request.unitId ?? "u-" + String(this.now()) + "-" + Math.random().toString(36).slice(2);
387
+ const validation = validateMutationRequest(request, this.limits);
388
+ if (!validation.ok) return {
389
+ ok: false,
390
+ unitId,
391
+ dryRun: request.dryRun === true,
392
+ changed: [],
393
+ errors: validation.errors
394
+ };
395
+ if (request.dryRun === true) return {
396
+ ok: true,
397
+ unitId,
398
+ dryRun: true,
399
+ changed: [],
400
+ errors: []
401
+ };
402
+ return await this.serial(async () => {
403
+ let lease;
404
+ try {
405
+ lease = await this.lock.acquire();
406
+ } catch (error) {
407
+ return {
408
+ ok: false,
409
+ unitId,
410
+ dryRun: false,
411
+ changed: [],
412
+ errors: [{
413
+ code: "unit-fence-failed",
414
+ message: error instanceof Error ? error.message : String(error)
415
+ }]
416
+ };
417
+ }
418
+ let claim;
419
+ if (this.claim !== void 0) try {
420
+ claim = await this.claim.acquire(primary, this.claimRunId ?? this.context?.runId ?? "");
421
+ } catch (error) {
422
+ await lease.release();
423
+ return {
424
+ ok: false,
425
+ unitId,
426
+ dryRun: false,
427
+ changed: [],
428
+ errors: [{
429
+ code: "claim-failed",
430
+ message: error instanceof Error ? error.message : String(error)
431
+ }]
432
+ };
433
+ }
434
+ const changed = [];
435
+ const warnings = [];
436
+ const bestEffort = async (task) => {
437
+ try {
438
+ await task();
439
+ } catch (error) {
440
+ if (!isCommittedWarning(error)) throw error;
441
+ warnings.push(error instanceof Error ? error.message : String(error));
442
+ }
443
+ };
444
+ const snapshots = [];
445
+ try {
446
+ for (const op of validation.ops) {
447
+ const current = await this.io.readText(op.target);
448
+ const baseline = op.expected === void 0 ? current : op.expected;
449
+ if (current !== baseline) return {
450
+ ok: false,
451
+ unitId,
452
+ dryRun: false,
453
+ changed,
454
+ errors: [{
455
+ code: "cas-drift",
456
+ message: "target changed after plan",
457
+ target: op.target
458
+ }]
459
+ };
460
+ snapshots.push({
461
+ target: op.target,
462
+ before: current,
463
+ after: op.kind === "write" ? op.content : null,
464
+ baseline
465
+ });
466
+ }
467
+ for (const op of validation.ops) {
468
+ const refusal = this.validateWrite?.(op) ?? null;
469
+ if (refusal !== null) return {
470
+ ok: false,
471
+ unitId,
472
+ dryRun: false,
473
+ changed: [],
474
+ errors: [{
475
+ code: "write-validation",
476
+ message: refusal,
477
+ target: op.target
478
+ }]
479
+ };
480
+ }
481
+ const eventOps = snapshots.map((snapshot) => {
482
+ const op = validation.ops.find((entry) => entry.target === snapshot.target);
483
+ return {
484
+ target: snapshot.target,
485
+ before: snapshot.before,
486
+ after: op?.kind === "write" ? op.content : null,
487
+ ...op?.skill === void 0 ? {} : { skill: op.skill }
488
+ };
489
+ });
490
+ const cleanup = request.cleanupPaths === void 0 ? {} : { cleanup: request.cleanupPaths };
491
+ if (this.snapshots !== void 0) await bestEffort(() => this.snapshots.write({
492
+ unitId,
493
+ journalId: this.journalId,
494
+ state: "prepared",
495
+ ops: eventOps,
496
+ ...cleanup,
497
+ createdAt: this.now(),
498
+ ...this.contextFields()
499
+ }));
500
+ await bestEffort(async () => this.journal?.write({
501
+ unitId,
502
+ journalId: this.journalId,
503
+ ...this.context?.runId === void 0 ? {} : { runId: this.context.runId },
504
+ phase: "prepared",
505
+ changed: [],
506
+ target: validation.roots.find((root) => root.name === primary)?.name ?? primary,
507
+ roots: validation.roots.map((root) => root.name)
508
+ }));
509
+ for (const op of validation.ops) {
510
+ const snapshot = snapshots.find((entry) => entry.target === op.target);
511
+ if (snapshot === void 0) throw new Error("snapshot missing for " + op.target);
512
+ try {
513
+ const opWarnings = await this.applyOp(op, snapshot.baseline);
514
+ warnings.push(...opWarnings);
515
+ changed.push(op.target);
516
+ } catch (error) {
517
+ if (error?.noWrite !== true) changed.push(op.target);
518
+ if (!isCommittedWarning(error)) throw error;
519
+ warnings.push(error instanceof Error ? error.message : String(error));
520
+ }
521
+ }
522
+ await bestEffort(async () => this.journal?.write({
523
+ unitId,
524
+ journalId: this.journalId,
525
+ ...this.context?.runId === void 0 ? {} : { runId: this.context.runId },
526
+ phase: "unit-written",
527
+ changed,
528
+ target: primary,
529
+ roots: validation.roots.map((root) => root.name)
530
+ }));
531
+ if (this.snapshots !== void 0) await bestEffort(() => this.snapshots.write({
532
+ unitId,
533
+ journalId: this.journalId,
534
+ state: "committed",
535
+ ops: eventOps,
536
+ ...cleanup,
537
+ createdAt: this.now(),
538
+ ...this.contextFields()
539
+ }));
540
+ await bestEffort(async () => this.journal?.write({
541
+ unitId,
542
+ journalId: this.journalId,
543
+ ...this.context?.runId === void 0 ? {} : { runId: this.context.runId },
544
+ phase: "committed",
545
+ changed,
546
+ target: primary,
547
+ roots: validation.roots.map((root) => root.name)
548
+ }));
549
+ try {
550
+ await this.hooks?.committed?.({
551
+ unitId,
552
+ changed,
553
+ ops: eventOps,
554
+ roots: validation.roots.map((root) => root.name)
555
+ });
556
+ } catch {}
557
+ return {
558
+ ok: true,
559
+ unitId,
560
+ dryRun: false,
561
+ changed,
562
+ errors: [],
563
+ ...warnings.length === 0 ? {} : { warnings }
564
+ };
565
+ } catch (error) {
566
+ const message = error instanceof Error ? error.message : String(error);
567
+ let rollbackFailure = "";
568
+ try {
569
+ await this.rollback(snapshots.filter((snapshot) => changed.includes(snapshot.target)));
570
+ } catch (rollbackError) {
571
+ rollbackFailure = rollbackError instanceof Error ? rollbackError.message : String(rollbackError);
572
+ }
573
+ const detail = rollbackFailure === "" ? message : message + "; rollback failed: " + rollbackFailure;
574
+ await this.journal?.write({
575
+ unitId,
576
+ journalId: this.journalId,
577
+ ...this.context?.runId === void 0 ? {} : { runId: this.context.runId },
578
+ phase: "failed",
579
+ changed,
580
+ error: detail
581
+ });
582
+ try {
583
+ await this.hooks?.rolledBack?.({
584
+ unitId,
585
+ changed,
586
+ ops: snapshots.map((snapshot) => {
587
+ const op = validation.ops.find((entry) => entry.target === snapshot.target);
588
+ return {
589
+ target: snapshot.target,
590
+ before: snapshot.before,
591
+ after: op?.kind === "write" ? op.content : null,
592
+ ...op?.skill === void 0 ? {} : { skill: op.skill }
593
+ };
594
+ }),
595
+ roots: validation.roots.map((root) => root.name)
596
+ });
597
+ } catch {}
598
+ return {
599
+ ok: false,
600
+ unitId,
601
+ dryRun: false,
602
+ changed,
603
+ errors: [{
604
+ code: "write-failed",
605
+ message: detail
606
+ }]
607
+ };
608
+ } finally {
609
+ await claim?.release().catch(() => {});
610
+ await lease.release();
611
+ }
612
+ });
613
+ }
614
+ /** Recover every prepared snapshot known to the port; safe to call at boot. */
615
+ async recoverPrepared() {
616
+ const prepared = await this.snapshots?.listPrepared?.() ?? [];
617
+ const results = [];
618
+ for (const snapshot of prepared) results.push(await this.recover(snapshot.unitId));
619
+ return results;
620
+ }
621
+ /** Converge a prepared unit left by a crash. Every path must be at its after-bytes; a drift refuses the whole recovery. */
622
+ async recover(unitId) {
623
+ const snapshot = await this.snapshots?.read(unitId);
624
+ if (snapshot === void 0 || snapshot === null) return {
625
+ ok: false,
626
+ unitId,
627
+ dryRun: false,
628
+ changed: [],
629
+ errors: [{
630
+ code: "recover-missing-snapshot",
631
+ message: "no snapshot for " + unitId
632
+ }]
633
+ };
634
+ if (snapshot.state !== "prepared") return {
635
+ ok: false,
636
+ unitId,
637
+ dryRun: false,
638
+ changed: [],
639
+ errors: [{
640
+ code: "recover-not-needed",
641
+ message: "unit is not prepared: " + unitId
642
+ }]
643
+ };
644
+ return await this.serial(async () => {
645
+ let lease;
646
+ try {
647
+ lease = await this.lock.acquire();
648
+ } catch (error) {
649
+ return {
650
+ ok: false,
651
+ unitId,
652
+ dryRun: false,
653
+ changed: [],
654
+ errors: [{
655
+ code: "unit-fence-failed",
656
+ message: error instanceof Error ? error.message : String(error)
657
+ }]
658
+ };
659
+ }
660
+ const reverted = [];
661
+ try {
662
+ for (const op of [...snapshot.ops].reverse()) {
663
+ const current = await this.io.readText(op.target);
664
+ if (current === op.before) continue;
665
+ if (current !== op.after) return {
666
+ ok: false,
667
+ unitId,
668
+ dryRun: false,
669
+ changed: [],
670
+ errors: [{
671
+ code: "recover-drift",
672
+ message: "target is neither before nor after: " + op.target
673
+ }]
674
+ };
675
+ const inverse = op.before === null ? {
676
+ kind: "delete",
677
+ target: op.target,
678
+ ...op.skill === void 0 ? {} : { skill: op.skill }
679
+ } : {
680
+ kind: "write",
681
+ target: op.target,
682
+ content: op.before,
683
+ ...op.skill === void 0 ? {} : { skill: op.skill }
684
+ };
685
+ await this.applyOp(inverse, op.after);
686
+ reverted.push(op.target);
687
+ }
688
+ for (const path of snapshot.cleanup ?? []) await this.io.remove(path).catch(() => {});
689
+ await this.snapshots?.write({
690
+ ...snapshot,
691
+ state: "undone"
692
+ });
693
+ await this.journal?.write({
694
+ unitId,
695
+ journalId: snapshot.journalId ?? this.journalId,
696
+ ...this.context?.runId === void 0 ? {} : { runId: this.context.runId },
697
+ phase: "undone",
698
+ changed: reverted,
699
+ ...snapshot.ops[0]?.target === void 0 ? {} : { target: snapshot.ops[0].target },
700
+ roots: [...new Set(snapshot.ops.map((op) => op.skill).filter((skill) => skill !== void 0))]
701
+ });
702
+ try {
703
+ await this.hooks?.undone?.({
704
+ unitId,
705
+ changed: reverted,
706
+ ops: snapshot.ops,
707
+ roots: [...new Set(snapshot.ops.map((op) => op.skill).filter((skill) => skill !== void 0))]
708
+ });
709
+ } catch {}
710
+ return {
711
+ ok: true,
712
+ unitId,
713
+ dryRun: false,
714
+ changed: reverted,
715
+ errors: []
716
+ };
717
+ } catch (error) {
718
+ return {
719
+ ok: false,
720
+ unitId,
721
+ dryRun: false,
722
+ changed: reverted,
723
+ errors: [{
724
+ code: "recover-failed",
725
+ message: error instanceof Error ? error.message : String(error)
726
+ }]
727
+ };
728
+ } finally {
729
+ await lease.release();
730
+ }
731
+ });
732
+ }
733
+ contextFields() {
734
+ return this.context === void 0 ? {} : {
735
+ owner: this.context.owner,
736
+ runId: this.context.runId,
737
+ leaseId: this.context.leaseId
738
+ };
739
+ }
740
+ async undo(unitId) {
741
+ const snapshot = await this.snapshots?.read(unitId);
742
+ if (snapshot === void 0 || snapshot === null) return {
743
+ ok: false,
744
+ unitId,
745
+ dryRun: false,
746
+ changed: [],
747
+ errors: [{
748
+ code: "undo-missing-snapshot",
749
+ message: "no committed snapshot for " + unitId
750
+ }]
751
+ };
752
+ if (snapshot.state === "prepared") return {
753
+ ok: false,
754
+ unitId,
755
+ dryRun: false,
756
+ changed: [],
757
+ errors: [{
758
+ code: "undo-needs-recovery",
759
+ message: "unit has a prepared snapshot; run recover first: " + unitId
760
+ }]
761
+ };
762
+ if (snapshot.state === "undone") return {
763
+ ok: false,
764
+ unitId,
765
+ dryRun: false,
766
+ changed: [],
767
+ errors: [{
768
+ code: "undo-already",
769
+ message: "unit already undone: " + unitId
770
+ }]
771
+ };
772
+ return await this.serial(async () => {
773
+ let lease;
774
+ try {
775
+ lease = await this.lock.acquire();
776
+ } catch (error) {
777
+ return {
778
+ ok: false,
779
+ unitId,
780
+ dryRun: false,
781
+ changed: [],
782
+ errors: [{
783
+ code: "lock-failed",
784
+ message: error instanceof Error ? error.message : String(error)
785
+ }]
786
+ };
787
+ }
788
+ const undone = [];
789
+ try {
790
+ for (const op of snapshot.ops) if (await this.io.readText(op.target) !== op.after) return {
791
+ ok: false,
792
+ unitId,
793
+ dryRun: false,
794
+ changed: [],
795
+ errors: [{
796
+ code: "undo-preflight",
797
+ message: "target changed after the unit: " + op.target
798
+ }]
799
+ };
800
+ for (const op of [...snapshot.ops].reverse()) {
801
+ const inverse = op.before === null ? {
802
+ kind: "delete",
803
+ target: op.target,
804
+ ...op.skill === void 0 ? {} : { skill: op.skill }
805
+ } : {
806
+ kind: "write",
807
+ target: op.target,
808
+ content: op.before,
809
+ ...op.skill === void 0 ? {} : { skill: op.skill }
810
+ };
811
+ await this.applyOp(inverse, op.after);
812
+ undone.push(op.target);
813
+ }
814
+ for (const path of snapshot.cleanup ?? []) await this.io.remove(path).catch(() => {});
815
+ await this.journal?.write({
816
+ unitId,
817
+ journalId: snapshot.journalId === void 0 ? this.journalId : snapshot.journalId + ":undo",
818
+ ...this.context?.runId === void 0 ? {} : { runId: this.context.runId },
819
+ phase: "undone",
820
+ changed: undone,
821
+ ...snapshot.ops[0]?.target === void 0 ? {} : { target: snapshot.ops[0].target },
822
+ roots: [...new Set(snapshot.ops.map((op) => op.skill).filter((skill) => skill !== void 0))]
823
+ });
824
+ await this.snapshots?.write({
825
+ ...snapshot,
826
+ state: "undone"
827
+ });
828
+ try {
829
+ await this.hooks?.undone?.({
830
+ unitId,
831
+ changed: undone,
832
+ ops: snapshot.ops,
833
+ roots: [...new Set(snapshot.ops.map((op) => op.skill).filter((skill) => skill !== void 0))]
834
+ });
835
+ } catch {}
836
+ return {
837
+ ok: true,
838
+ unitId,
839
+ dryRun: false,
840
+ changed: undone,
841
+ errors: []
842
+ };
843
+ } catch (error) {
844
+ for (const target of undone.reverse()) {
845
+ const op = snapshot.ops.find((entry) => entry.target === target);
846
+ if (op === void 0) continue;
847
+ try {
848
+ if (op.after === null) await this.io.remove(target);
849
+ else await this.io.writeText(target, op.after);
850
+ } catch {}
851
+ }
852
+ return {
853
+ ok: false,
854
+ unitId,
855
+ dryRun: false,
856
+ changed: undone,
857
+ errors: [{
858
+ code: "undo-failed",
859
+ message: error instanceof Error ? error.message : String(error)
860
+ }]
861
+ };
862
+ } finally {
863
+ await lease.release();
864
+ }
865
+ });
866
+ }
867
+ async applyOp(op, baseline) {
868
+ const result = await this.kernel.writeOne({
869
+ path: op.target,
870
+ expected: baseline,
871
+ next: op.kind === "delete" ? null : op.content,
872
+ ...op.skill === void 0 ? {} : { skill: op.skill }
873
+ }, { guardBaseline: this.transactGuard });
874
+ if (!result.ok) throw Object.assign(new Error(result.errors[0]?.message ?? "write failed: " + op.target), { noWrite: true });
875
+ return [...result.warnings ?? []];
876
+ }
877
+ async rollback(snapshots) {
878
+ for (const snapshot of [...snapshots].reverse()) {
879
+ const result = await this.kernel.restore({
880
+ path: snapshot.target,
881
+ before: snapshot.before,
882
+ after: snapshot.after
883
+ });
884
+ if (!result.ok) throw new Error(result.errors[0]?.message ?? "rollback failed: " + snapshot.target);
885
+ }
886
+ }
887
+ };
888
+ function parseFileLock(raw) {
889
+ if (raw === null) return void 0;
890
+ try {
891
+ const value = JSON.parse(raw);
892
+ if (typeof value.token !== "string" || typeof value.pid !== "number" || typeof value.startedAt !== "number") return void 0;
893
+ return {
894
+ token: value.token,
895
+ pid: value.pid,
896
+ startedAt: value.startedAt
897
+ };
898
+ } catch {
899
+ return;
900
+ }
901
+ }
902
+ const defaultSleep = async (ms) => await new Promise((resolve) => setTimeout(resolve, ms));
903
+ /**
904
+ * Cross-process root mutation lock. A live holder is never stolen; a dead pid
905
+ * or corrupt record can be taken over. This is separate from merge's run-level
906
+ * tree lock so an ordinary skill write cannot deadlock a merge run.
907
+ */
908
+ function fileMutationLock(io, root, options = {}) {
909
+ const path = join(dirname(root), "." + basename(root) + ".mutation-lock");
910
+ const waitMs = options.waitMs ?? 5e3;
911
+ const pollMs = options.pollMs ?? 25;
912
+ const now = options.now ?? Date.now;
913
+ const sleep = options.sleep ?? defaultSleep;
914
+ const update = async (task) => {
915
+ if (io.transact !== void 0) {
916
+ let ran = false;
917
+ await io.transact(path, (current) => {
918
+ ran = true;
919
+ return task(current);
920
+ });
921
+ if (!ran) throw new Error("mutation-lock-transact-not-run: " + path);
922
+ return;
923
+ }
924
+ const next = task(await io.readText(path));
925
+ try {
926
+ if (next === null) await io.remove(path);
927
+ else await io.writeText(path, next);
928
+ } catch (error) {
929
+ if (!isCommittedWarning(error)) throw error;
930
+ }
931
+ };
932
+ return { async acquire() {
933
+ const deadline = now() + waitMs;
934
+ for (;;) {
935
+ const token = randomUUID();
936
+ let acquired = false;
937
+ await update((current) => {
938
+ const existing = parseFileLock(current);
939
+ if (existing !== void 0 && isProcessAlive(existing.pid)) return current;
940
+ acquired = true;
941
+ return JSON.stringify({
942
+ token,
943
+ pid: process.pid,
944
+ startedAt: now()
945
+ });
946
+ });
947
+ if (acquired) {
948
+ let released = false;
949
+ return { async release() {
950
+ if (released) return;
951
+ released = true;
952
+ await update((current) => {
953
+ return parseFileLock(current)?.token === token ? null : current;
954
+ });
955
+ } };
956
+ }
957
+ if (now() >= deadline) throw new Error("mutation-lock-busy: " + path);
958
+ await sleep(Math.min(pollMs, Math.max(0, deadline - now())));
959
+ }
960
+ } };
961
+ }
962
+ //#endregion
963
+ //#region lib/types/unit-storage.js
964
+ /** G2 unit storage: opaque unitId -> Windows-safe storage key. */
965
+ const UNIT_STORAGE_SCHEMA_VERSION = 1;
966
+ /** Stable, filesystem-safe key; unitId stays opaque (may contain ':' or '/'). */
967
+ function unitStorageKey(unitId) {
968
+ return createHash("sha256").update(unitId).digest("hex");
969
+ }
970
+ function unitSnapshotsDir(home, scope = "merge") {
971
+ return scope === "merge" ? join(home, "merge", "unit-snapshots") : join(home, "units", "skill", "snapshots");
972
+ }
973
+ function unitSnapshotPath(home, unitId, scope = "merge") {
974
+ return join(unitSnapshotsDir(home, scope), unitStorageKey(unitId) + ".json");
975
+ }
976
+ function unitEvidencePath(home, unitId) {
977
+ return join(home, "merge", "units", unitStorageKey(unitId), "evidence.json");
978
+ }
979
+ function unitIndexPath(home) {
980
+ return join(home, "merge", "unit-index.json");
981
+ }
982
+ async function writeUnitSnapshot(io, home, snapshot, scope = "merge") {
983
+ const path = unitSnapshotPath(home, snapshot.unitId, scope);
984
+ const content = JSON.stringify(snapshot, null, 2) + "\n";
985
+ if (io.transact !== void 0) await io.transact(path, () => content);
986
+ else await io.writeText(path, content);
987
+ return path;
988
+ }
989
+ async function readUnitSnapshot(io, home, unitId, scope = "merge") {
990
+ const raw = await io.readText(unitSnapshotPath(home, unitId, scope));
991
+ if (raw === null) return null;
992
+ try {
993
+ return JSON.parse(raw);
994
+ } catch {
995
+ return null;
996
+ }
997
+ }
998
+ async function writeUnitEvidence(io, home, evidence) {
999
+ const path = unitEvidencePath(home, evidence.unitId);
1000
+ const content = JSON.stringify(evidence, null, 2) + "\n";
1001
+ if (io.transact !== void 0) await io.transact(path, () => content);
1002
+ else await io.writeText(path, content);
1003
+ await upsertUnitIndex(io, home, {
1004
+ unitId: evidence.unitId,
1005
+ storageKey: unitStorageKey(evidence.unitId),
1006
+ runId: evidence.runId,
1007
+ planDigest: evidence.planDigest,
1008
+ state: evidence.state,
1009
+ updatedAt: evidence.at
1010
+ });
1011
+ return path;
1012
+ }
1013
+ async function readUnitEvidence(io, home, unitId) {
1014
+ const raw = await io.readText(unitEvidencePath(home, unitId));
1015
+ if (raw === null) return null;
1016
+ try {
1017
+ return JSON.parse(raw);
1018
+ } catch {
1019
+ return null;
1020
+ }
1021
+ }
1022
+ async function readUnitIndex(io, home) {
1023
+ const raw = await io.readText(unitIndexPath(home));
1024
+ if (raw === null) return [];
1025
+ try {
1026
+ const parsed = JSON.parse(raw);
1027
+ return Array.isArray(parsed.entries) ? parsed.entries : [];
1028
+ } catch {
1029
+ return [];
1030
+ }
1031
+ }
1032
+ async function upsertUnitIndex(io, home, entry) {
1033
+ const path = unitIndexPath(home);
1034
+ const content = (current) => {
1035
+ let entries = [];
1036
+ if (current !== null) try {
1037
+ entries = JSON.parse(current).entries ?? [];
1038
+ } catch {
1039
+ entries = [];
1040
+ }
1041
+ const next = entries.filter((item) => item.unitId !== entry.unitId).concat(entry);
1042
+ return JSON.stringify({
1043
+ schemaVersion: 1,
1044
+ entries: next
1045
+ }, null, 2) + "\n";
1046
+ };
1047
+ if (io.transact !== void 0) await io.transact(path, content);
1048
+ else await io.writeText(path, content(await io.readText(path)));
1049
+ }
1050
+ function unitReceiptPath(home, unitId) {
1051
+ return join(home, "merge", "unit-receipts", unitStorageKey(unitId) + ".json");
1052
+ }
1053
+ async function writeUnitReceipt(io, home, receipt) {
1054
+ const path = unitReceiptPath(home, receipt.unitId);
1055
+ const text = JSON.stringify(receipt, null, 2) + "\n";
1056
+ if (io.transact !== void 0) await io.transact(path, () => text);
1057
+ else await io.writeText(path, text);
1058
+ return path;
1059
+ }
1060
+ async function readUnitReceipt(io, home, unitId) {
1061
+ const raw = await io.readText(unitReceiptPath(home, unitId));
1062
+ if (raw === null) return null;
1063
+ try {
1064
+ return JSON.parse(raw);
1065
+ } catch {
1066
+ return null;
1067
+ }
1068
+ }
1069
+ //#endregion
1070
+ //#region lib/types/unit-journal.js
1071
+ /** G2 unit journal: intent/phase/checkpoint only, never evidence bodies. */
1072
+ const UNIT_JOURNAL_SCHEMA_VERSION = 1;
1073
+ const UNIT_JOURNAL_PHASES = [
1074
+ "prepared",
1075
+ "target-pending",
1076
+ "target-written",
1077
+ "source-archiving",
1078
+ "support-pending",
1079
+ "sources-archived",
1080
+ "unit-written",
1081
+ "committed",
1082
+ "failed",
1083
+ "rolled-back"
1084
+ ];
1085
+ function unitJournalPath(home, unitId, scope = "merge") {
1086
+ return join(scope === "merge" ? join(home, "merge", "unit-journals") : join(home, "units", "skill", "journals"), createHash("sha256").update(unitId).digest("hex") + ".json");
1087
+ }
1088
+ function unitJournalPhaseRank(phase) {
1089
+ return UNIT_JOURNAL_PHASES.indexOf(phase);
1090
+ }
1091
+ function assertUnitJournalTransition(from, to) {
1092
+ if (from === to) return;
1093
+ if (from === "committed") throw new Error("unit-journal-terminal:" + from);
1094
+ if (to === "failed" || to === "rolled-back") return;
1095
+ if (from === "failed" || from === "rolled-back") throw new Error("unit-journal-terminal:" + from);
1096
+ if (unitJournalPhaseRank(to) <= unitJournalPhaseRank(from)) throw new Error("unit-journal-nonmonotonic:" + from + "->" + to);
1097
+ }
1098
+ async function writeUnitJournal(io, home, journal, scope = "merge") {
1099
+ const key = journal.journalId ?? journal.unitId;
1100
+ const path = unitJournalPath(home, key, scope);
1101
+ const existing = await readUnitJournal(io, home, key, scope);
1102
+ if (existing !== null) assertUnitJournalTransition(existing.phase, journal.phase);
1103
+ const content = JSON.stringify(journal, null, 2) + "\n";
1104
+ if (io.transact !== void 0) await io.transact(path, () => content);
1105
+ else await io.writeText(path, content);
1106
+ return path;
1107
+ }
1108
+ async function readUnitJournal(io, home, unitId, scope = "merge") {
1109
+ const raw = await io.readText(unitJournalPath(home, unitId, scope));
1110
+ if (raw === null) return null;
1111
+ try {
1112
+ return JSON.parse(raw);
1113
+ } catch {
1114
+ return null;
1115
+ }
1116
+ }
1117
+ //#endregion
1118
+ //#region lib/types/mutation-storage-adapter.js
1119
+ /**
1120
+ * Production adapter onto the existing unit snapshot store. A tree-change
1121
+ * snapshot is encoded as a UnitSnapshot with kind='tree-change'; merge
1122
+ * snapshots do not carry that kind and are ignored by the reader.
1123
+ */
1124
+ function unitSnapshotPort(io, home) {
1125
+ return {
1126
+ async write(snapshot) {
1127
+ const first = snapshot.ops[0];
1128
+ await writeUnitSnapshot(io, home, {
1129
+ schemaVersion: 1,
1130
+ unitId: snapshot.unitId,
1131
+ ...snapshot.journalId === void 0 ? {} : { journalId: snapshot.journalId },
1132
+ planDigest: contentHash(JSON.stringify(snapshot.ops)),
1133
+ runId: snapshot.runId ?? snapshot.unitId,
1134
+ target: first?.target ?? "",
1135
+ targetExists: true,
1136
+ targetBefore: first?.before ?? null,
1137
+ ...first?.after === null || first?.after === void 0 ? {} : { targetAfter: first.after },
1138
+ supportBefore: [],
1139
+ supportAfter: [],
1140
+ sourceBefore: [],
1141
+ origin: snapshot.owner ?? "foreground",
1142
+ ...snapshot.leaseId === void 0 ? {} : { leaseId: snapshot.leaseId },
1143
+ summary: "tree-change " + snapshot.unitId,
1144
+ createdAt: snapshot.createdAt,
1145
+ kind: "tree-change",
1146
+ mutationState: snapshot.state,
1147
+ ...snapshot.cleanup === void 0 ? {} : { cleanup: snapshot.cleanup },
1148
+ ops: snapshot.ops.map((op) => ({
1149
+ target: op.target,
1150
+ before: op.before,
1151
+ after: op.after,
1152
+ ...op.skill === void 0 ? {} : { skill: op.skill }
1153
+ }))
1154
+ }, "skill");
1155
+ },
1156
+ async read(unitId) {
1157
+ const snapshot = await readUnitSnapshot(io, home, unitId, "skill") ?? await readUnitSnapshot(io, home, unitId);
1158
+ if (snapshot === null || snapshot.kind !== "tree-change" || snapshot.ops === void 0) return null;
1159
+ return {
1160
+ unitId,
1161
+ ...snapshot.journalId === void 0 ? {} : { journalId: snapshot.journalId },
1162
+ state: snapshot.mutationState ?? "committed",
1163
+ ops: snapshot.ops,
1164
+ ...snapshot.cleanup === void 0 ? {} : { cleanup: snapshot.cleanup },
1165
+ createdAt: snapshot.createdAt,
1166
+ ...snapshot.origin === "foreground" || snapshot.origin === "background_review" ? { owner: snapshot.origin } : {},
1167
+ runId: snapshot.runId,
1168
+ ...snapshot.leaseId === void 0 ? {} : { leaseId: snapshot.leaseId }
1169
+ };
1170
+ },
1171
+ async listPrepared() {
1172
+ const out = [];
1173
+ const seen = /* @__PURE__ */ new Set();
1174
+ for (const dir of [unitSnapshotsDir(home, "skill"), unitSnapshotsDir(home)]) {
1175
+ const names = await io.list(dir);
1176
+ for (const name of names) {
1177
+ if (!name.endsWith(".json")) continue;
1178
+ const raw = await io.readText(join(dir, name));
1179
+ if (raw === null) continue;
1180
+ let snapshot;
1181
+ try {
1182
+ snapshot = JSON.parse(raw);
1183
+ } catch {
1184
+ continue;
1185
+ }
1186
+ if (snapshot.kind !== "tree-change" || snapshot.mutationState !== "prepared" || snapshot.ops === void 0) continue;
1187
+ if (seen.has(snapshot.unitId)) continue;
1188
+ seen.add(snapshot.unitId);
1189
+ out.push({
1190
+ unitId: snapshot.unitId,
1191
+ ...snapshot.journalId === void 0 ? {} : { journalId: snapshot.journalId },
1192
+ state: "prepared",
1193
+ ops: snapshot.ops,
1194
+ ...snapshot.cleanup === void 0 ? {} : { cleanup: snapshot.cleanup },
1195
+ createdAt: snapshot.createdAt,
1196
+ ...snapshot.origin === "foreground" || snapshot.origin === "background_review" ? { owner: snapshot.origin } : {},
1197
+ runId: snapshot.runId,
1198
+ ...snapshot.leaseId === void 0 ? {} : { leaseId: snapshot.leaseId }
1199
+ });
1200
+ }
1201
+ }
1202
+ return out;
1203
+ }
1204
+ };
1205
+ }
1206
+ /** Keep a bounded number of terminal tree-change snapshots; prepared units are never pruned. */
1207
+ async function pruneTreeChangeUnits(io, home, keep = 500) {
1208
+ if (!Number.isInteger(keep) || keep < 1) return 0;
1209
+ const dir = unitSnapshotsDir(home, "skill");
1210
+ const names = await io.list(dir);
1211
+ const terminal = [];
1212
+ for (const name of names) {
1213
+ if (!name.endsWith(".json")) continue;
1214
+ try {
1215
+ const snapshot = JSON.parse(await io.readText(join(dir, name)) ?? "");
1216
+ if (snapshot.kind !== "tree-change" || snapshot.mutationState === "prepared") continue;
1217
+ terminal.push({
1218
+ name,
1219
+ unitId: snapshot.unitId,
1220
+ ...snapshot.journalId === void 0 ? {} : { journalId: snapshot.journalId },
1221
+ createdAt: snapshot.createdAt
1222
+ });
1223
+ } catch {}
1224
+ }
1225
+ terminal.sort((a, b) => b.createdAt - a.createdAt);
1226
+ let removed = 0;
1227
+ for (const entry of terminal.slice(keep)) {
1228
+ await io.remove(join(dir, entry.name));
1229
+ await io.remove(unitJournalPath(home, entry.journalId ?? entry.unitId, "skill")).catch(() => {});
1230
+ removed += 1;
1231
+ }
1232
+ return removed;
1233
+ }
1234
+ const PHASE = {
1235
+ prepared: "prepared",
1236
+ "unit-written": "unit-written",
1237
+ committed: "committed",
1238
+ failed: "failed",
1239
+ undone: "rolled-back"
1240
+ };
1241
+ /**
1242
+ * Production adapter onto the skill-owned journal directory. Merge recovery
1243
+ * reads merge/unit-journals only; legacy tree-change journals carry kind and
1244
+ * are skipped by the recovery coordinator.
1245
+ */
1246
+ function unitJournalPort(io, home) {
1247
+ return { async write(record) {
1248
+ await writeUnitJournal(io, home, {
1249
+ schemaVersion: 1,
1250
+ unitId: record.unitId,
1251
+ ...record.journalId === void 0 ? {} : { journalId: record.journalId },
1252
+ runId: record.runId ?? record.unitId,
1253
+ planDigest: contentHash(JSON.stringify({
1254
+ unitId: record.unitId,
1255
+ target: record.target ?? record.changed[0] ?? "",
1256
+ roots: record.roots ?? [],
1257
+ changed: record.changed
1258
+ })),
1259
+ target: record.target ?? record.changed[0] ?? "",
1260
+ sources: record.roots ?? [],
1261
+ phase: PHASE[record.phase],
1262
+ storageKey: unitStorageKey(record.unitId),
1263
+ snapshotSha256: contentHash(JSON.stringify({
1264
+ unitId: record.unitId,
1265
+ target: record.target ?? record.changed[0] ?? "",
1266
+ roots: record.roots ?? []
1267
+ })),
1268
+ kind: "tree-change",
1269
+ updatedAt: Date.now()
1270
+ }, "skill");
1271
+ } };
1272
+ }
1273
+ //#endregion
1274
+ //#region lib/types/skill-history.js
1275
+ /**
1276
+ * Skill content history: content-addressed blobs plus a per-skill version index.
1277
+ *
1278
+ * Why it exists: `.mutations.json` records before/after HASHES and calls every automated edit
1279
+ * "reviewable and replayable" — but a hash cannot be replayed. With no content store, the only way
1280
+ * back was a whole-tree snapshot (`.backups`, keep=5) or `.archive` (removed skills only), so
1281
+ * reverting one skill cost the collateral of every other change in that window. This module keeps
1282
+ * the content, keyed by skill and version.
1283
+ *
1284
+ * Invariants (design `dsh-evolution-skill-history-design.md` §1):
1285
+ * - HISTORY IS HISTORY: the skill tree stays the single truth for "current content"; nothing here
1286
+ * feeds a judgment — callers read back content and version NUMBERS only.
1287
+ * - BEST-EFFORT, like the mutation audit: a failed history write warns and never fails the write
1288
+ * that already landed.
1289
+ * - Blobs are content-addressed, so identical bodies are stored once (across skills too).
1290
+ * - Versions are numbered by `v` (max+1), NOT by the clock: a moved system clock must not reorder
1291
+ * history (KiroCrew's `v<N>` choice, independently arrived at). Numbering and the index read-modify-write run
1292
+ * under the INDEX's own io lock, so two writers of one skill cannot mint the same number.
1293
+ * - The array's ORDER is append order, and the index is appended after the content lock is released, so two
1294
+ * writers of ONE skill can interleave their appends. Each entry therefore carries `beforeHash` — the content
1295
+ * it replaced, read under that writer's lock — and that link, not the position, is what `undo` follows
1296
+ * ({@link orderVersions} rebuilds the content order for display when the chain is complete).
1297
+ *
1298
+ * NOT here: blob garbage collection. Trimming drops INDEX entries; orphan blobs stay until a
1299
+ * sweeper collects them, because a reference count would have to span every skill's index and that
1300
+ * belongs to the curator's whole-library pass, not to the write path.
1301
+ * @module @lmzhen/dsh-evolution-core/skill-history
1302
+ */
1303
+ /** Root-level history directory. Dot-prefixed so skill discovery skips it. */
1304
+ const HISTORY_DIR = ".history";
1305
+ /** Versioned index shape, so a future field can migrate without guessing. */
1306
+ const HISTORY_INDEX_VERSION = 1;
1307
+ /** The action label for a predecessor the index had never seen (content found on disk before this
1308
+ * feature existed, or a hand-edited tree): it says "this is what was there", not what wrote it. */
1309
+ const BASELINE_ACTION = "baseline";
1310
+ /** The root-level history directory. */
1311
+ function historyRoot(root) {
1312
+ return join(root, HISTORY_DIR);
1313
+ }
1314
+ /** Content-addressed blob path: identical bodies share one file, across skills too. */
1315
+ function blobPath(root, hash) {
1316
+ return join(historyRoot(root), "blobs", hash);
1317
+ }
1318
+ /** One skill's index file. */
1319
+ function historyIndexFile(root, name) {
1320
+ return join(historyRoot(root), "skills", name, "index.json");
1321
+ }
1322
+ /**
1323
+ * The versions in CONTENT order (oldest first), rebuilt from the chain links, for display.
1324
+ *
1325
+ * The stored array is append order, which interleaves when two writers of one skill audit out of
1326
+ * order; the links say what actually replaced what. The rebuild runs only when it can account for
1327
+ * EVERY entry (exactly one start and a forward link for each step) — otherwise the stored order is
1328
+ * returned unchanged, because a partial reconstruction would be a worse answer than the honest one.
1329
+ * @param versions - the stored index, oldest first as recorded.
1330
+ * @returns the same entries, in content order when the chain is complete.
1331
+ */
1332
+ function orderVersions(versions) {
1333
+ if (versions.length < 2) return [...versions];
1334
+ const replaced = /* @__PURE__ */ new Set();
1335
+ for (const entry of versions) if (entry.beforeHash !== void 0) replaced.add(entry.beforeHash);
1336
+ const ends = versions.filter((entry) => !replaced.has(entry.hash));
1337
+ if (ends.length !== 1) return [...versions];
1338
+ const used = /* @__PURE__ */ new Set();
1339
+ const backward = [];
1340
+ let cursor = ends[0];
1341
+ while (cursor !== void 0 && !used.has(cursor)) {
1342
+ used.add(cursor);
1343
+ backward.push(cursor);
1344
+ const before = cursor.beforeHash;
1345
+ cursor = before === void 0 ? void 0 : [...versions].reverse().find((entry) => !used.has(entry) && entry.hash === before);
1346
+ }
1347
+ return backward.length === versions.length ? backward.reverse() : [...versions];
1348
+ }
1349
+ /** The actions that record a SUPPORT FILE's bytes (they share the skill's version index). */
1350
+ const SUPPORT_ACTIONS = ["write_file", "remove_file"];
1351
+ /** The actions that record the skill's own SKILL.md body. */
1352
+ const CONTENT_ACTIONS = [
1353
+ "create",
1354
+ "update",
1355
+ "patch",
1356
+ "consolidate",
1357
+ "restructure",
1358
+ "extract",
1359
+ "restore",
1360
+ "merge"
1361
+ ];
1362
+ /**
1363
+ * Which artifact one recorded version holds, from the action that produced it.
1364
+ * @param action - the entry's action label.
1365
+ * @returns the artifact class; `other` when the label does not say.
1366
+ */
1367
+ function versionTarget(action) {
1368
+ if (SUPPORT_ACTIONS.includes(action)) return "support";
1369
+ if (CONTENT_ACTIONS.includes(action)) return "content";
1370
+ return "other";
1371
+ }
1372
+ /**
1373
+ * Which artifact one INDEX ENTRY holds.
1374
+ *
1375
+ * {@link versionTarget} reads the ACTION, which is enough for the entries a write mints under its own
1376
+ * label and is NOT enough for a {@link BASELINE_ACTION}: a baseline minted for a support write holds
1377
+ * that FILE's previous bytes while its action says only "this is what was there". Two facts recover
1378
+ * the artifact:
1379
+ *
1380
+ * - `path` is written exactly when the bytes come from a support file, on BOTH entries one support
1381
+ * write can mint, so it decides on its own;
1382
+ * - an entry recorded before `path` existed has none, and the link is the evidence left: a support
1383
+ * write names the content it replaced through `beforeHash`, so a baseline that a support write
1384
+ * names as its predecessor holds that file's bytes.
1385
+ *
1386
+ * The inference runs only for a baseline. Every other entry keeps the action's verdict, which is also
1387
+ * the fail-closed one for an action this module does not know.
1388
+ * @param entry - one entry of a skill's index.
1389
+ * @param index - the index the entry came from: the legacy link is only readable across the whole
1390
+ * index. Omitting it answers from `path` and the action alone.
1391
+ * @returns the artifact class; `other` when nothing attributes the bytes.
1392
+ */
1393
+ function entryTarget(entry, index = []) {
1394
+ if (entry.path !== void 0) return "support";
1395
+ if (entry.action !== "baseline") return versionTarget(entry.action);
1396
+ return index.some((candidate) => SUPPORT_ACTIONS.includes(candidate.action) && candidate.beforeHash === entry.hash) ? "support" : "other";
1397
+ }
1398
+ /**
1399
+ * Split one index into the skill body's chain and the support files' versions.
1400
+ *
1401
+ * Both share ONE index, so a skill that ever wrote a support file has two chains and
1402
+ * {@link orderVersions} cannot account for every entry (it falls back to the stored order). Splitting
1403
+ * first lets each group rebuild its own order, and keeps the body's chain intact by leaving every
1404
+ * entry whose artifact nothing attributes in it — a `baseline` predecessor is usually the body's
1405
+ * first link, and only the support-file baselines {@link entryTarget} recovers leave it.
1406
+ * @param versions - the stored index, oldest first as recorded.
1407
+ * @returns the two groups, each in content order when its chain is complete.
1408
+ */
1409
+ function partitionVersions(versions) {
1410
+ const content = [];
1411
+ const support = [];
1412
+ for (const entry of versions) if (entryTarget(entry, versions) === "support") support.push(entry);
1413
+ else content.push(entry);
1414
+ return {
1415
+ content: orderVersions(content),
1416
+ support: orderVersions(support)
1417
+ };
1418
+ }
1419
+ /**
1420
+ * When this skill's content last changed: the newest `at` across BOTH chains, or null when the index
1421
+ * holds nothing.
1422
+ *
1423
+ * The stored array is APPEND order and two writers of one skill can interleave, so the answer is the
1424
+ * maximum timestamp rather than the tail. Every `at` this family writes is the same ISO-8601 UTC
1425
+ * form, so comparing the strings is comparing the instants.
1426
+ * @param versions - every entry the index holds, in any order.
1427
+ * @returns the newest timestamp, or null when there is none to report.
1428
+ */
1429
+ function latestVersionAt(versions) {
1430
+ let newest = null;
1431
+ for (const entry of versions) if (newest === null || entry.at > newest) newest = entry.at;
1432
+ return newest;
1433
+ }
1434
+ /** Keep nothing less than one version, whatever the deployment asks for. */
1435
+ function clampKeep(keep) {
1436
+ return Number.isFinite(keep) ? Math.max(1, Math.floor(keep)) : 1;
1437
+ }
1438
+ /** The next version number: max+1, never a timestamp. */
1439
+ function nextVersion(versions) {
1440
+ let max = 0;
1441
+ for (const entry of versions) if (entry.v > max) max = entry.v;
1442
+ return max + 1;
1443
+ }
1444
+ /** The last entry carrying this hash, or undefined (a hash may repeat after an undo). */
1445
+ function lastVersionOf(versions, hash) {
1446
+ for (let index = versions.length - 1; index >= 0; index -= 1) {
1447
+ const entry = versions[index];
1448
+ if (entry !== void 0 && entry.hash === hash) return entry.v;
1449
+ }
1450
+ }
1451
+ /** One entry as this reader accepts it, or null when the entry cannot be understood. */
1452
+ function readVersionEntry(entry) {
1453
+ if (typeof entry !== "object" || entry === null) return null;
1454
+ const candidate = entry;
1455
+ if (typeof candidate.v !== "number" || !Number.isInteger(candidate.v) || candidate.v <= 0) return null;
1456
+ if (typeof candidate.hash !== "string" || candidate.hash === "") return null;
1457
+ if (typeof candidate.at !== "string") return null;
1458
+ if (typeof candidate.action !== "string") return null;
1459
+ if (typeof candidate.chars !== "number") return null;
1460
+ const summary = typeof candidate.summary === "string" && candidate.summary !== "" ? candidate.summary : void 0;
1461
+ const path = typeof candidate.path === "string" && candidate.path !== "" ? candidate.path : void 0;
1462
+ const unitId = typeof candidate.unitId === "string" && candidate.unitId !== "" ? candidate.unitId : void 0;
1463
+ const removed = candidate.removed === true ? true : void 0;
1464
+ const unitHead = candidate.unitHead;
1465
+ const base = {
1466
+ v: candidate.v,
1467
+ at: candidate.at,
1468
+ action: candidate.action,
1469
+ hash: candidate.hash,
1470
+ chars: candidate.chars,
1471
+ ...summary === void 0 ? {} : { summary },
1472
+ ...path === void 0 ? {} : { path },
1473
+ ...unitId === void 0 ? {} : { unitId },
1474
+ ...removed === void 0 ? {} : { removed },
1475
+ ...unitHead === void 0 ? {} : { unitHead }
1476
+ };
1477
+ return typeof candidate.beforeHash === "string" && candidate.beforeHash !== "" ? {
1478
+ ...base,
1479
+ beforeHash: candidate.beforeHash
1480
+ } : base;
1481
+ }
1482
+ /**
1483
+ * Read one index body for a RECORDER: "understood", "no file", or "cannot be understood".
1484
+ * A file whose shape is right but which carries an entry this reader would have to drop counts as
1485
+ * unreadable — dropping it silently would be the overwrite the audit posture forbids.
1486
+ * @param raw - the index file's bytes, or null when absent.
1487
+ * @returns the three-state answer.
1488
+ */
1489
+ function readHistoryIndex(raw) {
1490
+ if (raw === null) return { kind: "absent" };
1491
+ if (raw.trim() === "") return { kind: "unreadable" };
1492
+ let parsed;
1493
+ try {
1494
+ parsed = JSON.parse(raw);
1495
+ } catch {
1496
+ return { kind: "unreadable" };
1497
+ }
1498
+ if (typeof parsed !== "object" || parsed === null) return { kind: "unreadable" };
1499
+ const holder = parsed;
1500
+ if (typeof holder.version === "number" && holder.version > 1) return { kind: "unreadable" };
1501
+ if (!Array.isArray(holder.versions)) return { kind: "unreadable" };
1502
+ const versions = [];
1503
+ for (const entry of holder.versions) {
1504
+ const version = readVersionEntry(entry);
1505
+ if (version === null) return { kind: "unreadable" };
1506
+ versions.push(version);
1507
+ }
1508
+ return {
1509
+ kind: "ok",
1510
+ versions
1511
+ };
1512
+ }
1513
+ /**
1514
+ * Parse one index body for a READER. Malformed content, a foreign shape, or a version NEWER than this
1515
+ * reader all read as empty — the audit posture: never guess. A recorder must use
1516
+ * {@link readHistoryIndex} instead, because it has to PRESERVE bytes it cannot understand.
1517
+ * @param raw - the index file's bytes, or null when absent.
1518
+ * @returns the versions, oldest first.
1519
+ */
1520
+ function parseHistoryIndex(raw) {
1521
+ const state = readHistoryIndex(raw);
1522
+ return state.kind === "ok" ? state.versions : [];
1523
+ }
1524
+ /**
1525
+ * The index after this write, and the version numbers it produced. Pure, so the versioning rules
1526
+ * are testable without io.
1527
+ *
1528
+ * Two rules matter here: a predecessor the index has never seen gets a BASELINE entry (so the state
1529
+ * before this mutation is recoverable even for a skill that predates the feature), and re-writing
1530
+ * identical content mints NO new version (the library's no-op updates must not grow history).
1531
+ * @param versions - the current index, oldest first.
1532
+ * @param input - the write being recorded.
1533
+ * @param keep - how many versions to retain per skill.
1534
+ * @returns the trimmed index and the recorded numbers.
1535
+ */
1536
+ function nextHistoryIndex(versions, input, keep) {
1537
+ const beforeHash = input.before === null ? null : contentHash(input.before);
1538
+ const afterHash = input.after === null ? null : contentHash(input.after);
1539
+ const grown = [...versions];
1540
+ const pathField = input.path === void 0 ? {} : { path: input.path };
1541
+ if (beforeHash !== null && !grown.some((entry) => entry.hash === beforeHash)) grown.push({
1542
+ v: nextVersion(grown),
1543
+ at: input.at,
1544
+ action: BASELINE_ACTION,
1545
+ hash: beforeHash,
1546
+ chars: input.before?.length ?? 0,
1547
+ ...pathField,
1548
+ ...input.unitId === void 0 ? {} : { unitId: input.unitId }
1549
+ });
1550
+ const removalHash = afterHash === null ? beforeHash : null;
1551
+ if (afterHash !== null) {
1552
+ if (grown[grown.length - 1]?.hash !== afterHash) grown.push({
1553
+ ...input.unitId === void 0 ? {} : { unitId: input.unitId },
1554
+ ...input.unitHead === void 0 ? {} : { unitHead: input.unitHead },
1555
+ v: nextVersion(grown),
1556
+ at: input.at,
1557
+ action: input.action,
1558
+ hash: afterHash,
1559
+ chars: input.after?.length ?? 0,
1560
+ ...pathField,
1561
+ ...input.summary === void 0 ? {} : { summary: input.summary },
1562
+ ...beforeHash === null ? {} : { beforeHash }
1563
+ });
1564
+ }
1565
+ if (removalHash !== null) {
1566
+ const tail = grown[grown.length - 1];
1567
+ if (tail?.hash !== removalHash || tail.action !== input.action) grown.push({
1568
+ v: nextVersion(grown),
1569
+ at: input.at,
1570
+ action: input.action,
1571
+ hash: removalHash,
1572
+ chars: input.before?.length ?? 0,
1573
+ removed: true,
1574
+ ...pathField,
1575
+ ...input.unitId === void 0 ? {} : { unitId: input.unitId },
1576
+ ...input.unitHead === void 0 ? {} : { unitHead: input.unitHead },
1577
+ ...input.summary === void 0 ? {} : { summary: input.summary }
1578
+ });
1579
+ }
1580
+ const budget = clampKeep(keep);
1581
+ const groups = [];
1582
+ const byUnit = /* @__PURE__ */ new Map();
1583
+ for (const entry of grown) {
1584
+ const unit = entry.unitId;
1585
+ if (unit === void 0) {
1586
+ groups.push([entry]);
1587
+ continue;
1588
+ }
1589
+ const found = byUnit.get(unit);
1590
+ if (found !== void 0) {
1591
+ found.push(entry);
1592
+ continue;
1593
+ }
1594
+ const made = [entry];
1595
+ byUnit.set(unit, made);
1596
+ groups.push(made);
1597
+ }
1598
+ const keptIndexes = /* @__PURE__ */ new Set();
1599
+ let keptCount = 0;
1600
+ for (let i = groups.length - 1; i >= 0; i -= 1) {
1601
+ const group = groups[i];
1602
+ if (group === void 0) continue;
1603
+ if (keptCount > 0 && keptCount + group.length > budget) break;
1604
+ for (const entry of group) keptIndexes.add(grown.indexOf(entry));
1605
+ keptCount += group.length;
1606
+ }
1607
+ const trimmed = grown.filter((_, index) => keptIndexes.has(index));
1608
+ const recorded = {};
1609
+ if (beforeHash !== null) {
1610
+ const v = lastVersionOf(trimmed, beforeHash);
1611
+ if (v !== void 0) recorded.beforeVersion = v;
1612
+ }
1613
+ if (afterHash !== null) {
1614
+ const v = lastVersionOf(trimmed, afterHash);
1615
+ if (v !== void 0) recorded.afterVersion = v;
1616
+ }
1617
+ return {
1618
+ versions: trimmed,
1619
+ recorded
1620
+ };
1621
+ }
1622
+ /** Shrink level at which the retention line speaks: a body that keeps less than this share of the
1623
+ * previous one is a rewrite, not an edit. */
1624
+ const RETENTION_FEEDBACK_KEEP_RATIO = .5;
1625
+ /** Floor on the REPLACED body: below this a ratio is noise (a 40-character skill cut in half is not
1626
+ * news), so the line stays off for small skills. */
1627
+ const RETENTION_FEEDBACK_MIN_CHARS = 200;
1628
+ /**
1629
+ * The anti-overwrite feedback line (design §4, item 3): says how much of the previous body a
1630
+ * replacement kept, so a destructive rewrite is visible in the same message that reports the write.
1631
+ *
1632
+ * Computed where the replaced bytes are still in hand — the write path's own in-lock read — instead of
1633
+ * re-reading the file from a caller (that second read would race the writers this library serializes).
1634
+ * It is FEEDBACK, never a gate: no ratio refuses a write, and the function owns no configuration
1635
+ * (a toggle nobody reads would be configuration that does nothing).
1636
+ *
1637
+ * @param input - the write being described.
1638
+ * @returns the line, or null when the write is not a significant whole-body replacement.
1639
+ */
1640
+ function contentRetentionFeedback(input) {
1641
+ if (input.action !== "update") return null;
1642
+ const before = input.before;
1643
+ const after = input.after;
1644
+ if (before === null || after === null) return null;
1645
+ if (before.length < 200) return null;
1646
+ if (after.length >= before.length * .5) return null;
1647
+ return `新内容保留了上一版正文的 ${Math.round(after.length / before.length * 100)}%(${after.length}/${before.length} 字符);被替换的版本已保留在该技能的历史里。`;
1648
+ }
1649
+ /**
1650
+ * Read one skill's versions, oldest first.
1651
+ * @param root - the skills root.
1652
+ * @param io - the io seam.
1653
+ * @param name - the skill name.
1654
+ * @returns the versions; an absent or unreadable index reads as empty (never a throw).
1655
+ */
1656
+ async function loadVersions(root, io, name) {
1657
+ const file = historyIndexFile(root, name);
1658
+ const probe = await probeText(io, file);
1659
+ if (isUnknown(probe)) {
1660
+ console.warn(`skill-store: ${file} could not be read (${probe.reason}); reporting no versions for "${name}" — the bytes are untouched`);
1661
+ return [];
1662
+ }
1663
+ return parseHistoryIndex(isPresent(probe) ? probe.value : null);
1664
+ }
1665
+ /**
1666
+ * One version's content.
1667
+ * @param root - the skills root.
1668
+ * @param io - the io seam.
1669
+ * @param name - the skill name.
1670
+ * @param v - the version number.
1671
+ * @returns the content, or null when the version or its blob cannot be read (never '').
1672
+ */
1673
+ async function loadVersionContent(root, io, name, v) {
1674
+ const entry = (await loadVersions(root, io, name)).find((candidate) => candidate.v === v);
1675
+ if (entry === void 0) return null;
1676
+ const probe = await probeText(io, blobPath(root, entry.hash));
1677
+ if (isUnknown(probe)) {
1678
+ console.warn(`skill-store: version ${v} of "${name}" could not be read (${probe.reason}); reporting no content`);
1679
+ return null;
1680
+ }
1681
+ return isPresent(probe) ? probe.value : null;
1682
+ }
1683
+ async function recordVersions(root, io, input, keep, fence) {
1684
+ if (input.before === null && input.after === null) return null;
1685
+ for (const side of [input.before, input.after]) {
1686
+ if (side === null) continue;
1687
+ const path = blobPath(root, contentHash(side));
1688
+ let blobPresent;
1689
+ try {
1690
+ blobPresent = await io.exists(path);
1691
+ } catch (error) {
1692
+ blobPresent = false;
1693
+ 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`);
1694
+ }
1695
+ if (!blobPresent) await io.writeText(path, side);
1696
+ }
1697
+ const file = historyIndexFile(root, input.skillName);
1698
+ const fileProbe = await probeText(io, file);
1699
+ if (isUnknown(fileProbe)) {
1700
+ const quarantine = `${file}.corrupt`;
1701
+ try {
1702
+ await io.copy(file, quarantine);
1703
+ } catch {}
1704
+ 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`);
1705
+ return null;
1706
+ }
1707
+ const probe = readHistoryIndex(isPresent(fileProbe) ? fileProbe.value : null);
1708
+ if (probe.kind === "unreadable") {
1709
+ const quarantine = `${file}.corrupt`;
1710
+ await io.copy(file, quarantine);
1711
+ 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`);
1712
+ }
1713
+ const recorded = {};
1714
+ let raceRefused = false;
1715
+ const write = async () => {
1716
+ await transactIo(io, file, (current) => {
1717
+ const state = readHistoryIndex(current);
1718
+ if (state.kind === "unreadable" && probe.kind !== "unreadable") {
1719
+ raceRefused = true;
1720
+ return current;
1721
+ }
1722
+ const { versions, recorded: numbers } = nextHistoryIndex(state.kind === "ok" ? state.versions : [], input, keep);
1723
+ recorded.beforeVersion = numbers.beforeVersion;
1724
+ recorded.afterVersion = numbers.afterVersion;
1725
+ return JSON.stringify({
1726
+ version: 1,
1727
+ versions
1728
+ }, null, 2);
1729
+ });
1730
+ };
1731
+ if (fence !== void 0) await fence.run(write);
1732
+ else await write();
1733
+ if (raceRefused) {
1734
+ const quarantine = `${file}.corrupt`;
1735
+ try {
1736
+ await io.copy(file, quarantine);
1737
+ } catch {}
1738
+ 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`);
1739
+ return null;
1740
+ }
1741
+ return recorded;
1742
+ }
1743
+ /**
1744
+ * Classify one version action for display. Fail-closed like {@link versionTarget}: an action this
1745
+ * module does not know reads as `other` rather than being guessed, and `tests/skill-history.spec.ts`
1746
+ * pins every action the library can write, so a new one cannot land unclassified.
1747
+ * @param action - the entry’s action label.
1748
+ * @returns the kind the faces switch on.
1749
+ */
1750
+ function versionActionKind(action) {
1751
+ switch (action) {
1752
+ case BASELINE_ACTION: return "baseline";
1753
+ case "create": return "create";
1754
+ case "patch":
1755
+ case "edit": return "patch";
1756
+ case "update": return "update";
1757
+ case "restore": return "restore";
1758
+ case "delete": return "delete";
1759
+ case "archive": return "archive";
1760
+ case "consolidate": return "consolidate";
1761
+ case "restructure": return "restructure";
1762
+ case "extract": return "extract";
1763
+ case "merge": return "merge";
1764
+ case "write_file": return "support-write";
1765
+ case "remove_file": return "support-remove";
1766
+ default: return "other";
1767
+ }
1768
+ }
1769
+ /** Lines one changed region may carry before it is windowed and flagged. */
1770
+ const TEXT_DIFF_MAX_LINES = 40;
1771
+ /** Characters one windowed side may carry, so a single enormous line cannot travel whole. */
1772
+ const TEXT_DIFF_MAX_CHARS = 4e3;
1773
+ /**
1774
+ * The facts of one whole-body replacement: how many lines the changed region gained and lost, and
1775
+ * that region itself as one hunk.
1776
+ *
1777
+ * The algorithm is the honest one for "what did this edit touch": common leading and trailing lines
1778
+ * are trimmed away and what remains is ONE contiguous region. It is not a minimal edit script — a
1779
+ * body edited in two distant places reports their span as one region — and that limitation is the
1780
+ * reason the faces show the region as context rather than as a line-by-line proof.
1781
+ * @param before - the body the write replaced.
1782
+ * @param after - the body the write stored.
1783
+ * @param path - the path the hunk names (the platform’s diff card requires one).
1784
+ * @param maxLines - the window a region’s text is capped to.
1785
+ * @returns the counts, the windowed hunk, and whether the window cut anything.
1786
+ */
1787
+ function textDiffFacts(before, after, path, maxLines = 40) {
1788
+ const oldLines = before === "" ? [] : before.split("\n");
1789
+ const newLines = after === "" ? [] : after.split("\n");
1790
+ let head = 0;
1791
+ while (head < oldLines.length && head < newLines.length && oldLines[head] === newLines[head]) head += 1;
1792
+ let tail = 0;
1793
+ while (tail < oldLines.length - head && tail < newLines.length - head && oldLines[oldLines.length - 1 - tail] === newLines[newLines.length - 1 - tail]) tail += 1;
1794
+ const oldRegion = oldLines.slice(head, oldLines.length - tail);
1795
+ const newRegion = newLines.slice(head, newLines.length - tail);
1796
+ if (oldRegion.length === 0 && newRegion.length === 0) return {
1797
+ linesAdded: 0,
1798
+ linesRemoved: 0,
1799
+ hunks: [],
1800
+ truncated: false
1801
+ };
1802
+ const window = (lines) => {
1803
+ const joined = lines.slice(0, maxLines).join("\n");
1804
+ if (joined.length <= 4e3) return {
1805
+ text: joined,
1806
+ cut: lines.length > maxLines
1807
+ };
1808
+ return {
1809
+ text: joined.slice(0, TEXT_DIFF_MAX_CHARS),
1810
+ cut: true
1811
+ };
1812
+ };
1813
+ const oldWindow = window(oldRegion);
1814
+ const newWindow = window(newRegion);
1815
+ return {
1816
+ linesAdded: newRegion.length,
1817
+ linesRemoved: oldRegion.length,
1818
+ hunks: [{
1819
+ path,
1820
+ oldText: oldWindow.text,
1821
+ newText: newWindow.text
1822
+ }],
1823
+ truncated: oldWindow.cut || newWindow.cut
1824
+ };
1825
+ }
1826
+ /** Characters one generated summary may carry. */
1827
+ const VERSION_SUMMARY_MAX_CHARS = 80;
1828
+ /**
1829
+ * The fixed prompt the optional per-write summarizer runs (registry `skillVersionSummary`).
1830
+ *
1831
+ * Model-visible, so it is written from the model’s perspective and pinned: the tests assert that it
1832
+ * carries the skill name, the character cap and both bodies, because a silent change to a prompt is a
1833
+ * silent change to what every recorded version says.
1834
+ * @param input - the skill, the action, and the two bodies (null when absent).
1835
+ * @returns the prompt text.
1836
+ */
1837
+ function versionSummaryPrompt(input) {
1838
+ return [
1839
+ "You are writing ONE line that tells a reader what this single edit to the agent skill",
1840
+ "\"" + input.name + "\" changed. The edit action was \"" + input.action + "\".",
1841
+ "Rules: at most " + String(80) + " characters; the same language as the body;",
1842
+ "name the decision, number or section that moved (for example \"keeps 30 days instead of 90 days\");",
1843
+ "never say merely that something changed; no preamble, quotes, markdown or trailing period.",
1844
+ "",
1845
+ "Body BEFORE the edit:",
1846
+ input.before ?? "(the skill did not exist before this edit)",
1847
+ "",
1848
+ "Body AFTER the edit:",
1849
+ input.after ?? "(the skill does not exist after this edit)"
1850
+ ].join("\n");
1851
+ }
1852
+ /**
1853
+ * Reduce a model answer to the one line the index stores.
1854
+ * @param raw - the model’s answer, whatever shape it came in.
1855
+ * @param maxChars - the character cap.
1856
+ * @returns the one line, or undefined when there is nothing usable (callers store no summary).
1857
+ */
1858
+ function normalizeVersionSummary(raw, maxChars = 80) {
1859
+ const firstLine = raw.split("\n").map((line) => line.trim()).find((line) => line !== "");
1860
+ if (firstLine === void 0) return void 0;
1861
+ const stripped = firstLine.replace(/^["'`*•s]+/u, "").replace(/["'`*s]+$/u, "").replace(/[。.]$/u, "").trim();
1862
+ if (stripped === "") return void 0;
1863
+ return stripped.length > maxChars ? stripped.slice(0, maxChars - 1) + "…" : stripped;
1864
+ }
1865
+ /**
1866
+ * How long ago an ISO timestamp was, as a bucket plus a count — never as a sentence.
1867
+ *
1868
+ * The shape deliberately mirrors the platform’s `relativeTime` (`ui-primitives`), so a face that later
1869
+ * may import the platform helper swaps one call and keeps its dictionary; the WORDS live in the
1870
+ * faces (the panel’s locale dictionary, the command surface’s English), which is why this module
1871
+ * returns numbers.
1872
+ * @param at - an ISO timestamp, or any string `Date.parse` understands.
1873
+ * @param nowMs - the reference instant.
1874
+ * @returns the bucket and its count; an unparsable timestamp reads as `now` with 0.
1875
+ */
1876
+ function elapsedSince(at, nowMs) {
1877
+ const then = Date.parse(at);
1878
+ if (Number.isNaN(then)) return {
1879
+ unit: "now",
1880
+ n: 0
1881
+ };
1882
+ const minutes = Math.floor(Math.max(0, nowMs - then) / 6e4);
1883
+ if (minutes < 1) return {
1884
+ unit: "now",
1885
+ n: 0
1886
+ };
1887
+ if (minutes < 60) return {
1888
+ unit: "minutes",
1889
+ n: minutes
1890
+ };
1891
+ const hours = Math.floor(minutes / 60);
1892
+ if (hours < 24) return {
1893
+ unit: "hours",
1894
+ n: hours
1895
+ };
1896
+ const days = Math.floor(hours / 24);
1897
+ if (days < 30) return {
1898
+ unit: "days",
1899
+ n: days
1900
+ };
1901
+ const months = Math.floor(days / 30);
1902
+ if (months < 12) return {
1903
+ unit: "months",
1904
+ n: months
1905
+ };
1906
+ return {
1907
+ unit: "years",
1908
+ n: Math.max(1, Math.floor(days / 365))
1909
+ };
1910
+ }
1911
+ //#endregion
1912
+ export { writeUnitSnapshot as $, unitJournalPort as A, readUnitEvidence as B, readHistoryIndex as C, versionSummaryPrompt as D, versionActionKind as E, readUnitJournal as F, unitIndexPath as G, readUnitReceipt as H, unitJournalPath as I, unitSnapshotsDir as J, unitReceiptPath as K, unitJournalPhaseRank as L, UNIT_JOURNAL_PHASES as M, UNIT_JOURNAL_SCHEMA_VERSION as N, versionTarget as O, assertUnitJournalTransition as P, writeUnitReceipt as Q, writeUnitJournal as R, partitionVersions as S, textDiffFacts as T, readUnitSnapshot as U, readUnitIndex as V, unitEvidencePath as W, upsertUnitIndex as X, unitStorageKey as Y, writeUnitEvidence as Z, loadVersions as _, RETENTION_FEEDBACK_MIN_CHARS as a, orderVersions as b, VERSION_SUMMARY_MAX_CHARS as c, elapsedSince as d, MutationUnit as et, entryTarget as f, loadVersionContent as g, latestVersionAt as h, RETENTION_FEEDBACK_KEEP_RATIO as i, unitSnapshotPort as j, pruneTreeChangeUnits as k, blobPath as l, historyRoot as m, HISTORY_DIR as n, validateMutationRequest as nt, TEXT_DIFF_MAX_CHARS as o, historyIndexFile as p, unitSnapshotPath as q, HISTORY_INDEX_VERSION as r, WriteKernel as rt, TEXT_DIFF_MAX_LINES as s, BASELINE_ACTION as t, fileMutationLock as tt, contentRetentionFeedback as u, nextHistoryIndex as v, recordVersions as w, parseHistoryIndex as x, normalizeVersionSummary as y, UNIT_STORAGE_SCHEMA_VERSION as z };