@lmzhen/dsh-evolution-core 0.59.5 → 0.60.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 (111) hide show
  1. package/README.md +3 -1
  2. package/lib/authority-plugin.js +3 -2
  3. package/lib/composition/index.js +2 -2
  4. package/lib/{composition-B_F4TYOD.js → composition-BSqh70z_.js} +1 -1
  5. package/lib/{ensure-BpVDuDnA.js → ensure-DTCuxAxR.js} +1 -1
  6. package/lib/{extract-plan-D3ALlAmN.js → extract-plan-CP__XlEs.js} +2 -2
  7. package/lib/extract.js +4 -4
  8. package/lib/http-routes.js +3 -2
  9. package/lib/index.js +15 -15
  10. package/lib/{io-Cpa8wuvj.js → io-DT4-MXLr.js} +25 -1
  11. package/lib/io-node.js +1 -1
  12. package/lib/io-platform.js +163 -0
  13. package/lib/io-registry.js +10 -0
  14. package/lib/{mutation-authority-CZpc9F20.js → mutation-authority-C3RYyiaT.js} +66 -41
  15. package/lib/{mutation-storage-adapter-z1_hyrQn.js → mutation-storage-adapter-CSVn34dK.js} +334 -212
  16. package/lib/{mutations-Y-wKod7W.js → mutations-JKFlfhSO.js} +1 -1
  17. package/lib/policy.js +1 -1
  18. package/lib/{quality-NPGr3VzA.js → quality-C0ri2SgY.js} +2 -2
  19. package/lib/restrictor.js +1 -1
  20. package/lib/result.js +1 -1
  21. package/lib/{review-context-yNiZadPw.js → review-context-D2LIOEi-.js} +2 -2
  22. package/lib/runtime/plugin.js +2 -2
  23. package/lib/{session-projection-DM15fsRp.js → session-projection-Dnmm5bzt.js} +1 -1
  24. package/lib/{skill-history-BvLWFoOo.js → skill-history-BOZ4HCDB.js} +2 -2
  25. package/lib/skills.js +739 -129
  26. package/lib/state/domain/index.js +433 -0
  27. package/lib/state/index.js +136 -0
  28. package/lib/state/migrate.js +90 -0
  29. package/lib/state/storage.js +605 -0
  30. package/lib/state/store-plugin.js +23 -0
  31. package/lib/state/store.js +268 -0
  32. package/lib/subagent/index.js +1 -1
  33. package/lib/types/authority-plugin.d.ts +1 -1
  34. package/lib/types/authority-plugin.js +2 -1
  35. package/lib/types/authority.d.ts +1 -1
  36. package/lib/types/authority.js +75 -48
  37. package/lib/types/composition/ensure.js +1 -1
  38. package/lib/types/contract.d.ts +8 -0
  39. package/lib/types/http-routes.d.ts +1 -0
  40. package/lib/types/http-routes.js +2 -1
  41. package/lib/types/io-platform.d.ts +74 -0
  42. package/lib/types/io-platform.js +178 -0
  43. package/lib/types/io-registry.d.ts +4 -0
  44. package/lib/types/io-registry.js +10 -0
  45. package/lib/types/io.d.ts +7 -0
  46. package/lib/types/io.js +25 -1
  47. package/lib/types/mutation-authority.d.ts +1 -1
  48. package/lib/types/mutation-storage-adapter.d.ts +1 -1
  49. package/lib/types/opt-in.js +2 -2
  50. package/lib/types/params.js +2 -2
  51. package/lib/types/policy.js +1 -1
  52. package/lib/types/restrictor.js +2 -2
  53. package/lib/types/result.d.ts +1 -1
  54. package/lib/types/result.js +1 -1
  55. package/lib/types/runtime/coherence.js +1 -1
  56. package/lib/types/runtime/llm.d.ts +1 -1
  57. package/lib/types/runtime/llm.js +1 -1
  58. package/lib/types/runtime/platform.d.ts +3 -3
  59. package/lib/types/runtime/platform.js +2 -2
  60. package/lib/types/runtime/projections.d.ts +1 -1
  61. package/lib/types/scope.js +1 -1
  62. package/lib/types/session-projection.d.ts +1 -1
  63. package/lib/types/signals.d.ts +1 -1
  64. package/lib/types/skill-observation.d.ts +4 -5
  65. package/lib/types/skill-observation.js +18 -2
  66. package/lib/types/skill-store.d.ts +73 -4
  67. package/lib/types/skill-store.js +376 -29
  68. package/lib/types/skill-write-plan.d.ts +80 -0
  69. package/lib/types/skill-write-plan.js +2 -0
  70. package/lib/types/skill-write-service.d.ts +84 -2
  71. package/lib/types/skill-write-service.js +214 -35
  72. package/lib/types/skills.d.ts +2 -0
  73. package/lib/types/skills.js +2 -0
  74. package/lib/types/state/conformance.d.ts +47 -0
  75. package/lib/types/state/conformance.js +246 -0
  76. package/lib/types/state/constants.d.ts +52 -0
  77. package/lib/types/state/constants.js +52 -0
  78. package/lib/types/state/domain/compatibility.d.ts +40 -0
  79. package/lib/types/state/domain/compatibility.js +36 -0
  80. package/lib/types/state/domain/index.d.ts +81 -0
  81. package/lib/types/state/domain/index.js +592 -0
  82. package/lib/types/state/index.d.ts +63 -0
  83. package/lib/types/state/index.js +174 -0
  84. package/lib/types/state/medium-declaration.d.ts +37 -0
  85. package/lib/types/state/medium-declaration.js +53 -0
  86. package/lib/types/state/migrate.d.ts +34 -0
  87. package/lib/types/state/migrate.js +103 -0
  88. package/lib/types/state/record-contract.d.ts +56 -0
  89. package/lib/types/state/record-contract.js +120 -0
  90. package/lib/types/state/storage.d.ts +112 -0
  91. package/lib/types/state/storage.js +178 -0
  92. package/lib/types/state/store-plugin.d.ts +14 -0
  93. package/lib/types/state/store-plugin.js +18 -0
  94. package/lib/types/state/store.d.ts +39 -0
  95. package/lib/types/state/store.js +270 -0
  96. package/lib/types/store-ledger.js +2 -2
  97. package/lib/types/subagent/run.d.ts +1 -1
  98. package/lib/types/subagent/types.d.ts +4 -4
  99. package/lib/types/system-skill-writer.d.ts +21 -0
  100. package/lib/types/system-skill-writer.js +15 -0
  101. package/lib/types/{write-kernel.d.ts → target-writer.d.ts} +32 -15
  102. package/lib/types/{write-kernel.js → target-writer.js} +40 -8
  103. package/lib/types/tool-dispatch.js +6 -3
  104. package/lib/types/{mutation-unit.d.ts → unit-kernel.d.ts} +44 -13
  105. package/lib/types/{mutation-unit.js → unit-kernel.js} +163 -120
  106. package/lib/types/write.d.ts +1 -2
  107. package/lib/types/write.js +1 -2
  108. package/lib/{usage-D7yHG2Cb.js → usage-BO4Zj_zB.js} +2 -2
  109. package/lib/write.js +4 -4
  110. package/package.json +30 -3
  111. package/persisted-write-inventory.json +14 -5
package/lib/skills.js CHANGED
@@ -1,16 +1,19 @@
1
- import { _ as probeMtime, b as probeText, c as transactIo, d as isAbsent, g as probeList, h as probeAbsent, i as isCommittedWarning, m as isUnknown, o as nodeEvolutionIo, p as isPresent, t as TransactionNotInvokedError, v as probePresent, x as probeUnknown, y as probeReason } from "./io-Cpa8wuvj.js";
2
- import { i as mutationLockFrom } from "./mutation-authority-CZpc9F20.js";
1
+ import { _ as probeMtime, b as probeText, c as transactIo, d as isAbsent, g as probeList, h as probeAbsent, i as isCommittedWarning, m as isUnknown, o as nodeEvolutionIo, p as isPresent, t as TransactionNotInvokedError, v as probePresent, x as probeUnknown, y as probeReason } from "./io-DT4-MXLr.js";
2
+ import { i as mutationLockFrom } from "./mutation-authority-C3RYyiaT.js";
3
3
  import { o as resolveCitations } from "./citations-CZKTUGQF.js";
4
4
  import { Q as SUPPORT_DIRS, Z as SKILL_NAME_RE, a as DEFAULT_SUPPORT_FILE_CHAR_POLICY, i as DEFAULT_SKILL_LIMITS, n as DEFAULT_CITATION_POLICY, o as POLICY_STAGE_DEFAULTS, q as PROTECTED_BUILTIN_SKILLS, r as DEFAULT_REFERENCE_REWRITE_POLICY, s as policyStageLimits, t as DEFAULT_ARCHIVE_RETENTION_POLICY, u as CONTENT_SPLIT_HINT } from "./limits-CO4JGSJL.js";
5
- import { B as READ_REQUIRED_ACTIONS, C as appendEvolutionEvent, F as lintBody, H as isUnreadWrite, I as softBodyTokenBudget, L as RULES, M as HEALTH_STAMP_RE, N as MIN_STAMP_BODY_CHARS, P as assessStructureHealth, R as diffFindings, U as sessionReadSkillNames, V as filterUnreadSkillOps, W as sessionReadSupportFiles, _ as fuzzyPatch, a as isReviewChannelSession, d as scanContentThreats, j as DEFAULT_HEALTH_THRESHOLDS, m as makeSerialQueue, q as authorityFrom, t as currentReviewContext, v as trimPatternBoundaries, w as eventsFile, z as lintSkill } from "./review-context-yNiZadPw.js";
5
+ import { B as READ_REQUIRED_ACTIONS, C as appendEvolutionEvent, F as lintBody, H as isUnreadWrite, I as softBodyTokenBudget, L as RULES, M as HEALTH_STAMP_RE, N as MIN_STAMP_BODY_CHARS, P as assessStructureHealth, R as diffFindings, U as sessionReadSkillNames, V as filterUnreadSkillOps, W as sessionReadSupportFiles, _ as fuzzyPatch, a as isReviewChannelSession, d as scanContentThreats, j as DEFAULT_HEALTH_THRESHOLDS, m as makeSerialQueue, q as authorityFrom, t as currentReviewContext, v as trimPatternBoundaries, w as eventsFile, z as lintSkill } from "./review-context-D2LIOEi-.js";
6
6
  import { a as measureUnit } from "./text-metrics-CyJhxWBs.js";
7
- import { E as usageFile, F as describeReferenceRewrite, I as planReferenceRewrite, L as planRehoming, N as supportRefs, O as selectSections, P as applyReferenceRewrite, _ as loadUsage, p as getRecord, w as suppressedFile, y as mutateUsage } from "./usage-D7yHG2Cb.js";
8
- import { _ as validateFrontmatter, c as ensureSkillFrontmatter, d as frontmatterCatalogInvalid, f as normalizeFrontmatter, g as skillMdOnDisk, h as shrinksOverLimit, i as loadMutations, l as exceedsContentLimit, m as relatedSkillNames, o as recordMutation, p as parseFrontmatter, r as contentHash, s as authoringFeedback, u as frontmatterBlock, v as yamlPlainScalarNeedsQuotes } from "./mutations-Y-wKod7W.js";
7
+ import { E as usageFile, F as describeReferenceRewrite, I as planReferenceRewrite, L as planRehoming, N as supportRefs, O as selectSections, P as applyReferenceRewrite, _ as loadUsage, p as getRecord, w as suppressedFile, y as mutateUsage } from "./usage-BO4Zj_zB.js";
8
+ import { _ as validateFrontmatter, c as ensureSkillFrontmatter, d as frontmatterCatalogInvalid, f as normalizeFrontmatter, g as skillMdOnDisk, h as shrinksOverLimit, i as loadMutations, l as exceedsContentLimit, m as relatedSkillNames, o as recordMutation, p as parseFrontmatter, r as contentHash, s as authoringFeedback, u as frontmatterBlock, v as yamlPlainScalarNeedsQuotes } from "./mutations-JKFlfhSO.js";
9
9
  import { n as evolutionRoot } from "./state-store-Jpa-iYIZ.js";
10
- import { C as partitionVersions, D as textDiffFacts, E as summaryChars, O as versionActionKind, S as parseHistoryIndex, T as recordVersions, _ as loadVersionContent, a as RETENTION_FEEDBACK_KEEP_RATIO, b as normalizeChangeSummary, c as TEXT_DIFF_MAX_LINES, d as contentRetentionFeedback, f as elapsedSince, g as latestVersionAt, h as historyRoot, i as HISTORY_INDEX_VERSION, k as versionTarget, l as blobPath, m as historyIndexFile, n as DEFAULT_SKILL_WRITE_SUMMARY_CHARS, o as RETENTION_FEEDBACK_MIN_CHARS, p as entryTarget, r as HISTORY_DIR, s as TEXT_DIFF_MAX_CHARS, t as BASELINE_ACTION, u as clipChangeSummary, v as loadVersions, w as readHistoryIndex, x as orderVersions, y as nextHistoryIndex } from "./skill-history-BvLWFoOo.js";
11
- import { D as fileMutationLock, E as MutationUnit, n as unitJournalPort, r as unitSnapshotPort, t as pruneTreeChangeUnits } from "./mutation-storage-adapter-z1_hyrQn.js";
12
- import { n as projectExtractBodies } from "./extract-plan-D3ALlAmN.js";
10
+ import { C as partitionVersions, D as textDiffFacts, E as summaryChars, O as versionActionKind, S as parseHistoryIndex, T as recordVersions, _ as loadVersionContent, a as RETENTION_FEEDBACK_KEEP_RATIO, b as normalizeChangeSummary, c as TEXT_DIFF_MAX_LINES, d as contentRetentionFeedback, f as elapsedSince, g as latestVersionAt, h as historyRoot, i as HISTORY_INDEX_VERSION, k as versionTarget, l as blobPath, m as historyIndexFile, n as DEFAULT_SKILL_WRITE_SUMMARY_CHARS, o as RETENTION_FEEDBACK_MIN_CHARS, p as entryTarget, r as HISTORY_DIR, s as TEXT_DIFF_MAX_CHARS, t as BASELINE_ACTION, u as clipChangeSummary, v as loadVersions, w as readHistoryIndex, x as orderVersions, y as nextHistoryIndex } from "./skill-history-BOZ4HCDB.js";
11
+ import { D as fileMutationLock, E as UnitKernel, n as unitJournalPort, r as unitSnapshotPort, t as pruneTreeChangeUnits } from "./mutation-storage-adapter-CSVn34dK.js";
12
+ import { n as projectExtractBodies } from "./extract-plan-CP__XlEs.js";
13
+ import { AsyncLocalStorage } from "node:async_hooks";
14
+ import { createHash } from "node:crypto";
13
15
  import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
16
+ import { realpathSync } from "node:fs";
14
17
  //#region lib/types/skill-stats.js
15
18
  /**
16
19
  * Skill statistics: the read-only domain model shared by the host projection and the browser table.
@@ -234,6 +237,19 @@ function normalizeRelPath(relPath) {
234
237
  * review task from retaining its reads; disposal blocks HMR from carrying stale
235
238
  * observations into a new implementation generation.
236
239
  */
240
+ /** The key a target uses in an observation map; identity wins over the logical key. */
241
+ function observationKey(target) {
242
+ return target.identityKey ?? target.targetKey;
243
+ }
244
+ /** Canonical realpath identity for an existing host path, matching SkillLibrary's lock key. */
245
+ function skillHostIdentity(hostPath) {
246
+ try {
247
+ const real = realpathSync.native(hostPath).replaceAll("\\", "/");
248
+ return "skillpath:" + createHash("sha256").update(real).digest("hex");
249
+ } catch {
250
+ return;
251
+ }
252
+ }
237
253
  var SkillObservationStore = class {
238
254
  byOwner = /* @__PURE__ */ new WeakMap();
239
255
  /**
@@ -248,14 +264,14 @@ var SkillObservationStore = class {
248
264
  reads = /* @__PURE__ */ new Map();
249
265
  this.byOwner.set(owner, reads);
250
266
  }
251
- reads.set(target.targetKey, observation);
267
+ reads.set(observationKey(target), observation);
252
268
  }
253
269
  /**
254
270
  * Read the newest observation for one owner/target.
255
271
  * @returns the observation, or `undefined` when this owner never read it.
256
272
  */
257
273
  get(owner, target) {
258
- return this.byOwner.get(owner)?.get(target.targetKey);
274
+ return this.byOwner.get(owner)?.get(observationKey(target));
259
275
  }
260
276
  /**
261
277
  * Resolve the observation a writer may rely on.
@@ -453,70 +469,6 @@ function matchOffsets(content, literal) {
453
469
  return offsets;
454
470
  }
455
471
  //#endregion
456
- //#region lib/types/skill-target-locks.js
457
- /**
458
- * Per-target promise locks for skill writes.
459
- *
460
- * The current SkillLibrary serial queue is per root, so writes to different
461
- * skills serialize even though they share no bytes. This table is the
462
- * replacement primitive: one tail promise per canonical target key, and a
463
- * multi-target acquisition that takes keys in lexical order to make deadlock
464
- * impossible. It is deliberately pure (no IO, no timeout) so the service can
465
- * compose it with transactIo/HomeFence rather than duplicate lock semantics.
466
- *
467
- * @module @lmzhen/dsh-evolution-core/skill-target-locks
468
- */
469
- /** A lock table keyed by canonical skill target key. */
470
- var SkillTargetLocks = class {
471
- tails = /* @__PURE__ */ new Map();
472
- /**
473
- * Run one task while holding one target key.
474
- * @param targetKey - canonical skill target key.
475
- * @param task - the read/compare/write critical section.
476
- * @returns the task's value.
477
- */
478
- async withLock(targetKey, task) {
479
- return await this.withLocks([targetKey], task);
480
- }
481
- /**
482
- * Run one task while holding several target keys.
483
- *
484
- * Keys are deduplicated and acquired in lexical order; the caller may pass
485
- * them in any order. A task must not call {@link withLock}/{@link withLocks}
486
- * for a key it already holds (the promise chain is not reentrant), so callers
487
- * should flatten multi-file units into one acquisition.
488
- * @param targetKeys - canonical target keys touched by the unit.
489
- * @param task - the unit's read/compare/write critical section.
490
- * @returns the task's value.
491
- */
492
- async withLocks(targetKeys, task) {
493
- const keys = [...new Set(targetKeys)].sort();
494
- return await this.acquire(keys, 0, task);
495
- }
496
- /** Number of live target queues; exposed for leak assertions in tests. */
497
- get size() {
498
- return this.tails.size;
499
- }
500
- async acquire(keys, index, task) {
501
- const key = keys[index];
502
- if (key === void 0) return await task();
503
- const prior = this.tails.get(key) ?? Promise.resolve();
504
- let release;
505
- const gate = new Promise((resolve) => {
506
- release = resolve;
507
- });
508
- const tail = prior.then(() => gate);
509
- this.tails.set(key, tail);
510
- await prior;
511
- try {
512
- return await this.acquire(keys, index + 1, task);
513
- } finally {
514
- release();
515
- if (this.tails.get(key) === tail) this.tails.delete(key);
516
- }
517
- }
518
- };
519
- //#endregion
520
472
  //#region lib/types/skill-write-service.js
521
473
  /**
522
474
  * The first service layer over skill observations and the CAS primitive.
@@ -538,7 +490,6 @@ var SkillTargetLocks = class {
538
490
  var SkillWriteService = class {
539
491
  library;
540
492
  observations;
541
- locks = new SkillTargetLocks();
542
493
  constructor(library, observations) {
543
494
  this.library = library;
544
495
  this.observations = observations;
@@ -550,7 +501,7 @@ var SkillWriteService = class {
550
501
  * @returns the body, or null when absent.
551
502
  */
552
503
  async readBody(owner, name) {
553
- const target = skillBodyTarget(name);
504
+ const target = await this.library.identify(skillBodyTarget(name));
554
505
  const content = await this.library.read(name);
555
506
  this.record(owner, target, content);
556
507
  return content;
@@ -563,12 +514,230 @@ var SkillWriteService = class {
563
514
  * @returns the bytes, or null when absent.
564
515
  */
565
516
  async readSupport(owner, name, filePath) {
566
- const target = skillSupportTarget(name, filePath);
517
+ const target = await this.library.identify(skillSupportTarget(name, filePath));
567
518
  const content = await this.library.readSupportFile(name, filePath);
568
519
  this.record(owner, target, content);
569
520
  return content;
570
521
  }
571
522
  /**
523
+ * Plan a create. Creation is createIfAbsent by definition and needs no prior
524
+ * read; the provider's `create` path keeps managed/protection semantics.
525
+ * @param owner - writer identity (unused for create, kept for a uniform API).
526
+ * @param name - skill name.
527
+ * @param content - full body.
528
+ * @param managed - add the managed marker (non-foreground origin).
529
+ * @returns the plan or a typed refusal.
530
+ */
531
+ async planCreate(owner, name, content, origin = "foreground", managed = false) {
532
+ return {
533
+ ok: true,
534
+ plan: {
535
+ origin,
536
+ ops: [{
537
+ kind: "createSkill",
538
+ skill: name,
539
+ content,
540
+ ...managed ? { managed: true } : {}
541
+ }]
542
+ }
543
+ };
544
+ }
545
+ /**
546
+ * Plan a full body replacement from this owner's observation.
547
+ * @param owner - exact writer.
548
+ * @param name - skill name.
549
+ * @param content - next body.
550
+ * @param origin - write face.
551
+ * @returns the plan or a typed refusal.
552
+ */
553
+ async planUpdate(owner, name, content, origin = "foreground") {
554
+ const target = await this.library.identify(skillBodyTarget(name));
555
+ const observed = this.observations.requirePresent(owner, target);
556
+ if (!("version" in observed)) return planRefusal(observed.kind);
557
+ return {
558
+ ok: true,
559
+ plan: {
560
+ origin,
561
+ ops: [{
562
+ kind: "write",
563
+ target,
564
+ content,
565
+ expect: {
566
+ kind: "present",
567
+ version: observed.version
568
+ }
569
+ }]
570
+ }
571
+ };
572
+ }
573
+ /**
574
+ * Plan a literal patch against a body or support target.
575
+ *
576
+ * A section patch always targets the body and ignores `filePath`; that is the
577
+ * same contract the library has always had, but now it is explicit in the
578
+ * plan instead of a tool branch.
579
+ * @param owner - exact writer.
580
+ * @param name - skill name.
581
+ * @param input - literal edit or section edit.
582
+ * @param origin - write face.
583
+ * @returns the plan or a typed refusal.
584
+ */
585
+ async planPatch(owner, name, input, origin = "foreground") {
586
+ if (input.section !== void 0) {
587
+ const target = await this.library.identify(skillBodyTarget(name));
588
+ const observed = this.observations.requirePresent(owner, target);
589
+ if (!("version" in observed)) return planRefusal(observed.kind);
590
+ return {
591
+ ok: true,
592
+ plan: {
593
+ origin,
594
+ ops: [{
595
+ kind: "patchSection",
596
+ target,
597
+ section: input.section,
598
+ expect: {
599
+ kind: "present",
600
+ version: observed.version
601
+ }
602
+ }]
603
+ }
604
+ };
605
+ }
606
+ const filePath = input.filePath ?? "";
607
+ const logicalTarget = filePath === "" ? skillBodyTarget(name) : skillSupportTarget(name, filePath);
608
+ const target = await this.library.identify(logicalTarget);
609
+ const observed = this.observations.requirePresent(owner, target);
610
+ if (!("version" in observed)) return planRefusal(observed.kind);
611
+ return {
612
+ ok: true,
613
+ plan: {
614
+ origin,
615
+ ops: [{
616
+ kind: "patch",
617
+ target,
618
+ oldString: input.oldString ?? "",
619
+ newString: input.newString ?? "",
620
+ replaceAll: input.replaceAll === true,
621
+ expect: {
622
+ kind: "present",
623
+ version: observed.version
624
+ }
625
+ }]
626
+ }
627
+ };
628
+ }
629
+ /**
630
+ * Plan a full support-file write. A newly observed/absent file is
631
+ * createIfAbsent; an already observed file is replaceIfVersion. An unread
632
+ * existing file is refused instead of overwritten.
633
+ * @param owner - exact writer.
634
+ * @param name - skill name.
635
+ * @param filePath - support path.
636
+ * @param content - next bytes.
637
+ * @param origin - write face.
638
+ * @returns the plan or a typed refusal.
639
+ */
640
+ async planWriteSupport(owner, name, filePath, content, origin = "foreground") {
641
+ const target = await this.library.identify(skillSupportTarget(name, filePath));
642
+ const observed = this.observations.get(owner, target);
643
+ if (observed === void 0) {
644
+ if (await this.library.readSupportFile(name, filePath) !== null) return notObserved();
645
+ return {
646
+ ok: true,
647
+ plan: {
648
+ origin,
649
+ ops: [{
650
+ kind: "write",
651
+ target,
652
+ content,
653
+ expect: { kind: "absent" }
654
+ }]
655
+ }
656
+ };
657
+ }
658
+ if (observed.kind === "absent") return {
659
+ ok: true,
660
+ plan: {
661
+ origin,
662
+ ops: [{
663
+ kind: "write",
664
+ target,
665
+ content,
666
+ expect: { kind: "absent" }
667
+ }]
668
+ }
669
+ };
670
+ return {
671
+ ok: true,
672
+ plan: {
673
+ origin,
674
+ ops: [{
675
+ kind: "write",
676
+ target,
677
+ content,
678
+ expect: {
679
+ kind: "present",
680
+ version: observed.version
681
+ }
682
+ }]
683
+ }
684
+ };
685
+ }
686
+ /**
687
+ * Plan removing one support file from this owner's observation.
688
+ * @param owner - exact writer.
689
+ * @param name - skill name.
690
+ * @param filePath - support path.
691
+ * @param origin - write face.
692
+ * @returns the plan or a typed refusal.
693
+ */
694
+ async planRemoveSupport(owner, name, filePath, origin = "foreground") {
695
+ const target = await this.library.identify(skillSupportTarget(name, filePath));
696
+ const observed = this.observations.requirePresent(owner, target);
697
+ if (!("version" in observed)) return planRefusal(observed.kind);
698
+ return {
699
+ ok: true,
700
+ plan: {
701
+ origin,
702
+ ops: [{
703
+ kind: "remove",
704
+ target,
705
+ expect: {
706
+ kind: "present",
707
+ version: observed.version
708
+ }
709
+ }]
710
+ }
711
+ };
712
+ }
713
+ /**
714
+ * Apply one plan through the provider and record the committed result for
715
+ * this owner. The re-read is temporary H2 bookkeeping; H5 replaces it with
716
+ * the provider's `SkillWriteOutcome`, so a post-commit read failure can never
717
+ * turn a landed write into a tool failure.
718
+ * @param plan - the write plan.
719
+ * @param owner - exact writer identity; omitted by internal callers that do
720
+ * not own observations.
721
+ * @returns the service-level result.
722
+ */
723
+ async apply(plan, owner) {
724
+ const result = await this.library.apply(plan);
725
+ if (result.ok && owner !== void 0) try {
726
+ await this.observeOutcomes(result, owner);
727
+ } catch {}
728
+ return actionResult(result, plan);
729
+ }
730
+ async observeOutcomes(result, owner) {
731
+ for (const outcome of result.outcomes) {
732
+ if (outcome.version === void 0) continue;
733
+ const target = outcome.target.identityKey === void 0 ? await this.library.identify(outcome.target) : outcome.target;
734
+ this.observations.record(owner, target, outcome.version === "" ? { kind: "absent" } : {
735
+ kind: "present",
736
+ version: outcome.version
737
+ });
738
+ }
739
+ }
740
+ /**
572
741
  * Replace SKILL.md only when this owner observed its current version.
573
742
  * @param owner - exact writer identity.
574
743
  * @param name - skill name.
@@ -576,14 +745,12 @@ var SkillWriteService = class {
576
745
  * @returns write outcome or a typed refusal.
577
746
  */
578
747
  async updateBody(owner, name, content, origin = "foreground") {
579
- const target = skillBodyTarget(name);
748
+ const target = await this.library.identify(skillBodyTarget(name));
580
749
  const observed = this.observations.requirePresent(owner, target);
581
750
  if (!("version" in observed)) return refusal(observed.kind);
582
- return await this.locks.withLock(target.targetKey, async () => {
583
- const result = await this.library.update(name, content, origin, anchorOf(observed.version));
584
- if (result.ok) await this.readBody(owner, name);
585
- return actionResult(result);
586
- });
751
+ const result = await this.library.update(name, content, origin, anchorOf(observed.version));
752
+ if (result.ok) await this.readBody(owner, name);
753
+ return actionResult(result);
587
754
  }
588
755
  /**
589
756
  * Patch SKILL.md only when this owner observed its current version.
@@ -595,14 +762,12 @@ var SkillWriteService = class {
595
762
  * @returns write outcome or a typed refusal.
596
763
  */
597
764
  async patchBody(owner, name, oldString, newString, replaceAll = false, origin = "foreground") {
598
- const target = skillBodyTarget(name);
765
+ const target = await this.library.identify(skillBodyTarget(name));
599
766
  const observed = this.observations.requirePresent(owner, target);
600
767
  if (!("version" in observed)) return refusal(observed.kind);
601
- return await this.locks.withLock(target.targetKey, async () => {
602
- const result = await this.library.patch(name, oldString, newString, "", replaceAll, origin, anchorOf(observed.version));
603
- if (result.ok) await this.readBody(owner, name);
604
- return actionResult(result);
605
- });
768
+ const result = await this.library.patch(name, oldString, newString, "", replaceAll, origin, anchorOf(observed.version));
769
+ if (result.ok) await this.readBody(owner, name);
770
+ return actionResult(result);
606
771
  }
607
772
  /**
608
773
  * Replace one support file only when this owner observed its current version.
@@ -613,25 +778,21 @@ var SkillWriteService = class {
613
778
  * @returns write outcome or a typed refusal.
614
779
  */
615
780
  async updateSupport(owner, name, filePath, content, origin = "foreground") {
616
- const target = skillSupportTarget(name, filePath);
781
+ const target = await this.library.identify(skillSupportTarget(name, filePath));
617
782
  const observed = this.observations.requirePresent(owner, target);
618
783
  if (!("version" in observed)) return refusal(observed.kind);
619
- return await this.locks.withLock(target.targetKey, async () => {
620
- const result = await this.library.writeSupportFile(name, filePath, content, origin, anchorOf(observed.version));
621
- if (result.ok) await this.readSupport(owner, name, filePath);
622
- return actionResult(result);
623
- });
784
+ const result = await this.library.writeSupportFile(name, filePath, content, origin, anchorOf(observed.version));
785
+ if (result.ok) await this.readSupport(owner, name, filePath);
786
+ return actionResult(result);
624
787
  }
625
788
  /** Remove a support file only after this owner read it at the observed version. */
626
789
  async removeSupport(owner, name, filePath, origin = "foreground") {
627
- const target = skillSupportTarget(name, filePath);
790
+ const target = await this.library.identify(skillSupportTarget(name, filePath));
628
791
  const observed = this.observations.requirePresent(owner, target);
629
792
  if (!("version" in observed)) return refusal(observed.kind);
630
- return await this.locks.withLock(target.targetKey, async () => {
631
- const result = await this.library.removeSupportFile(name, filePath, origin, anchorOf(observed.version));
632
- if (result.ok) this.observations.record(owner, target, { kind: "absent" });
633
- return actionResult(result);
634
- });
793
+ const result = await this.library.removeSupportFile(name, filePath, origin, anchorOf(observed.version));
794
+ if (result.ok) this.observations.record(owner, target, { kind: "absent" });
795
+ return actionResult(result);
635
796
  }
636
797
  /**
637
798
  * Create a support file when absent, or update it only after this owner read it.
@@ -639,7 +800,7 @@ var SkillWriteService = class {
639
800
  * existing unread file is refused rather than overwritten.
640
801
  */
641
802
  async writeSupport(owner, name, filePath, content, origin = "foreground") {
642
- const target = skillSupportTarget(name, filePath);
803
+ const target = await this.library.identify(skillSupportTarget(name, filePath));
643
804
  const observed = this.observations.get(owner, target);
644
805
  if (observed === void 0) {
645
806
  if (await this.library.readSupportFile(name, filePath) !== null) return {
@@ -685,14 +846,28 @@ function refusal(kind) {
685
846
  message: "skill target does not exist"
686
847
  };
687
848
  }
849
+ function planRefusal(kind) {
850
+ return refusal(kind);
851
+ }
852
+ function notObserved() {
853
+ return planRefusal("unobserved");
854
+ }
688
855
  function anchorOf(version) {
689
856
  return { sha256: version };
690
857
  }
691
- function actionResult(result) {
858
+ function actionResult(result, plan) {
692
859
  if (result.ok) return {
693
860
  ok: true,
694
861
  message: result.message,
695
- ...result.noop === true ? { noop: true } : {}
862
+ ...result.noop === true ? { noop: true } : {},
863
+ ...result.path === void 0 ? {} : { path: result.path },
864
+ ...result.normalizedFrontmatterFields === void 0 ? {} : { normalizedFrontmatterFields: result.normalizedFrontmatterFields }
865
+ };
866
+ const only = plan?.ops.length === 1 ? plan.ops[0] : void 0;
867
+ if (only !== void 0 && (only.kind === "createSkill" || only.kind === "write" && only.target.relPath === "" && only.expect.kind === "absent" && only.create !== false) && (result.stale === true || /已存在|target appeared|changed after plan|concurrent modification/i.test(result.message))) return {
868
+ ok: false,
869
+ code: "SKILL_ALREADY_EXISTS",
870
+ message: result.message
696
871
  };
697
872
  if (result.stale === true) return {
698
873
  ok: false,
@@ -706,6 +881,86 @@ function actionResult(result) {
706
881
  };
707
882
  }
708
883
  //#endregion
884
+ //#region lib/types/system-skill-writer.js
885
+ var SystemSkillWriter = class {
886
+ library;
887
+ constructor(library) {
888
+ this.library = library;
889
+ }
890
+ /**
891
+ * Apply one explicit plan through the single provider.
892
+ * @param plan - origin, ops and the caller's snapshot anchors.
893
+ * @returns the provider result; no observation is recorded.
894
+ */
895
+ async apply(plan) {
896
+ return await this.library.apply(plan);
897
+ }
898
+ };
899
+ //#endregion
900
+ //#region lib/types/skill-target-locks.js
901
+ /**
902
+ * Per-target promise locks for skill writes.
903
+ *
904
+ * The current SkillLibrary serial queue is per root, so writes to different
905
+ * skills serialize even though they share no bytes. This table is the
906
+ * replacement primitive: one tail promise per canonical target key, and a
907
+ * multi-target acquisition that takes keys in lexical order to make deadlock
908
+ * impossible. It is deliberately pure (no IO, no timeout) so the service can
909
+ * compose it with transactIo/HomeFence rather than duplicate lock semantics.
910
+ *
911
+ * @module @lmzhen/dsh-evolution-core/skill-target-locks
912
+ */
913
+ /** A lock table keyed by canonical skill target key. */
914
+ var SkillTargetLocks = class {
915
+ tails = /* @__PURE__ */ new Map();
916
+ /**
917
+ * Run one task while holding one target key.
918
+ * @param targetKey - canonical skill target key.
919
+ * @param task - the read/compare/write critical section.
920
+ * @returns the task's value.
921
+ */
922
+ async withLock(targetKey, task) {
923
+ return await this.withLocks([targetKey], task);
924
+ }
925
+ /**
926
+ * Run one task while holding several target keys.
927
+ *
928
+ * Keys are deduplicated and acquired in lexical order; the caller may pass
929
+ * them in any order. A task must not call {@link withLock}/{@link withLocks}
930
+ * for a key it already holds (the promise chain is not reentrant), so callers
931
+ * should flatten multi-file units into one acquisition.
932
+ * @param targetKeys - canonical target keys touched by the unit.
933
+ * @param task - the unit's read/compare/write critical section.
934
+ * @returns the task's value.
935
+ */
936
+ async withLocks(targetKeys, task) {
937
+ const keys = [...new Set(targetKeys)].sort();
938
+ return await this.acquire(keys, 0, task);
939
+ }
940
+ /** Number of live target queues; exposed for leak assertions in tests. */
941
+ get size() {
942
+ return this.tails.size;
943
+ }
944
+ async acquire(keys, index, task) {
945
+ const key = keys[index];
946
+ if (key === void 0) return await task();
947
+ const prior = this.tails.get(key) ?? Promise.resolve();
948
+ let release;
949
+ const gate = new Promise((resolve) => {
950
+ release = resolve;
951
+ });
952
+ const tail = prior.then(() => gate);
953
+ this.tails.set(key, tail);
954
+ await prior;
955
+ try {
956
+ return await this.acquire(keys, index + 1, task);
957
+ } finally {
958
+ release();
959
+ if (this.tails.get(key) === tail) this.tails.delete(key);
960
+ }
961
+ }
962
+ };
963
+ //#endregion
709
964
  //#region lib/types/skill-root-gate.js
710
965
  /**
711
966
  * Root-level shared/exclusive gate for skill-tree operations.
@@ -1497,6 +1752,26 @@ function planRestructureSections(body, moves) {
1497
1752
  }))
1498
1753
  };
1499
1754
  }
1755
+ /** Project one restructure without writing: the operator preview and the store share the planner. */
1756
+ function projectRestructureMarkdown(markdown, moves) {
1757
+ const block = frontmatterBlock(markdown);
1758
+ if (!block) return {
1759
+ ok: false,
1760
+ message: "SKILL.md 没有有效的 frontmatter;拒绝重构。"
1761
+ };
1762
+ const header = block.lines.slice(0, block.end + 1).join("\n");
1763
+ const plan = planRestructureSections(markdown.slice(header.length).replace(/\r\n/g, "\n"), moves);
1764
+ if ("error" in plan) return {
1765
+ ok: false,
1766
+ message: "重构被拒绝:" + plan.error
1767
+ };
1768
+ const newMd = (header + plan.body).replace(/\r\n/g, "\n");
1769
+ return {
1770
+ ok: true,
1771
+ body: block.nl === "\r\n" ? newMd.replace(/\n/g, "\r\n") : newMd,
1772
+ sections: plan.sections
1773
+ };
1774
+ }
1500
1775
  /**
1501
1776
  * WHY MODULE SCOPE (S4.4): the serial queue must be shared ACROSS SkillLibrary instances. Six services
1502
1777
  * each build their own store over the SAME skill root (tool face / curator face / review face), and a
@@ -1511,8 +1786,15 @@ const ROOT_SERIAL = /* @__PURE__ */ new Map();
1511
1786
  * @param root - the resolved skill root; the key, so two spellings of one directory share a queue.
1512
1787
  * @returns the queue every instance over this root serializes through.
1513
1788
  */
1789
+ function canonicalRootKey(root) {
1790
+ try {
1791
+ return realpathSync.native(resolve(root));
1792
+ } catch {
1793
+ return resolve(root);
1794
+ }
1795
+ }
1514
1796
  function serialForRoot(root) {
1515
- const key = resolve(root);
1797
+ const key = canonicalRootKey(root);
1516
1798
  const existing = ROOT_SERIAL.get(key);
1517
1799
  if (existing !== void 0) return existing;
1518
1800
  const created = makeSerialQueue();
@@ -1526,14 +1808,30 @@ function sameRevisionAnchor(expected, live) {
1526
1808
  }
1527
1809
  /** One target-lock registry per skill ROOT, shared by every library instance in this process. */
1528
1810
  const TARGET_LOCKS_BY_ROOT = /* @__PURE__ */ new Map();
1811
+ /** One structural gate per canonical root, shared by every library instance. */
1812
+ const ROOT_GATES = /* @__PURE__ */ new Map();
1813
+ function rootGateFor(root) {
1814
+ const key = canonicalRootKey(root);
1815
+ let gate = ROOT_GATES.get(key);
1816
+ if (gate === void 0) {
1817
+ gate = new SkillRootGate();
1818
+ ROOT_GATES.set(key, gate);
1819
+ }
1820
+ return gate;
1821
+ }
1529
1822
  function targetLocksFor(root) {
1530
- let locks = TARGET_LOCKS_BY_ROOT.get(root);
1823
+ const key = canonicalRootKey(root);
1824
+ let locks = TARGET_LOCKS_BY_ROOT.get(key);
1531
1825
  if (locks === void 0) {
1532
1826
  locks = new SkillTargetLocks();
1533
- TARGET_LOCKS_BY_ROOT.set(root, locks);
1827
+ TARGET_LOCKS_BY_ROOT.set(key, locks);
1534
1828
  }
1535
1829
  return locks;
1536
1830
  }
1831
+ /** Async-local collector: a normal single-op write never sees another plan's sink. */
1832
+ const PLAN_SINK = new AsyncLocalStorage();
1833
+ /** The model-supplied plan summary that must reach history/audit, not just command output. */
1834
+ const PLAN_SUMMARY = new AsyncLocalStorage();
1537
1835
  var SkillLibrary = class {
1538
1836
  root;
1539
1837
  /** The ONE read face owner/health/panel consume; a thin adapter, not a store. */
@@ -1553,8 +1851,8 @@ var SkillLibrary = class {
1553
1851
  serial;
1554
1852
  /** Transitional target locks (same key as SkillWriteService). */
1555
1853
  targetLocks;
1556
- /** Root structural gate; simple writes still use the serial until D.5d. */
1557
- rootGate = new SkillRootGate();
1854
+ /** Root structural gate; shared per canonical root across library instances. */
1855
+ rootGate;
1558
1856
  /** V10-03 (P2-18): see the constructor's threatExemptLabels. Empty by
1559
1857
  * default — the strict ANY-hit-blocks policy is unchanged. */
1560
1858
  threatExemptLabels;
@@ -1570,6 +1868,7 @@ var SkillLibrary = class {
1570
1868
  constructor(root = skillsRoot(), io = nodeEvolutionIo(), limits = DEFAULT_SKILL_LIMITS, onMutation, transact, threatExemptLabels, authority = CLASS_DEFAULT_AUTHORITY, mutationLock, fence) {
1571
1869
  this.root = root;
1572
1870
  this.targetLocks = targetLocksFor(root);
1871
+ this.rootGate = rootGateFor(root);
1573
1872
  this.io = io;
1574
1873
  this.limits = limits;
1575
1874
  this.onMutation = onMutation;
@@ -1592,7 +1891,7 @@ var SkillLibrary = class {
1592
1891
  }
1593
1892
  /**
1594
1893
  * Transitional root lock for mutators that still own their write path. The
1595
- * extract/restructure path takes the same lock through MutationUnit, so those
1894
+ * extract/restructure path takes the same lock through UnitKernel, so those
1596
1895
  * two paths cannot interleave with create/update/patch across processes.
1597
1896
  */
1598
1897
  unitHeadForOps(ops, roots, provenance = /* @__PURE__ */ new Map()) {
@@ -1618,22 +1917,100 @@ var SkillLibrary = class {
1618
1917
  }
1619
1918
  /** Transitional: serialize one target even while the root serial remains. */
1620
1919
  async withTarget(targetKey, task) {
1621
- return await this.targetLocks.withLock(targetKey, task);
1920
+ return await this.targetLocks.withLock(await this.canonicalTargetKey(targetKey), task);
1921
+ }
1922
+ /** Canonicalize several logical target keys for one lock acquisition. */
1923
+ async canonicalLockKeys(keys) {
1924
+ return await Promise.all(keys.map((key) => this.canonicalTargetKey(key)));
1925
+ }
1926
+ /**
1927
+ * Attach the canonical realpath identity to one observation target.
1928
+ * @param target - logical skill target.
1929
+ * @returns the target with `identityKey`; the logical targetKey is unchanged.
1930
+ */
1931
+ async identify(target) {
1932
+ const key = target.relPath === "" ? "skill::" + target.skill : "skill::" + target.skill + "::" + target.relPath;
1933
+ return {
1934
+ ...target,
1935
+ identityKey: await this.canonicalTargetKey(key)
1936
+ };
1937
+ }
1938
+ /**
1939
+ * Canonical in-process lock identity for one skill target key.
1940
+ *
1941
+ * A logical `skill::name::path` key is resolved through realpath (or the
1942
+ * nearest existing ancestor for a not-yet-created file) and hashed, so two
1943
+ * spellings/symlinks of the same host file share one promise-lock queue. The
1944
+ * logical targetKey stays the observation/approval key until the observation
1945
+ * resolver phase; this method only fixes the provider lock identity.
1946
+ * @param targetKey - the family's logical skill target key.
1947
+ * @returns the canonical lock key, or the input for non-skill keys.
1948
+ */
1949
+ async canonicalTargetKey(targetKey) {
1950
+ if (!targetKey.startsWith("skill::")) return targetKey;
1951
+ try {
1952
+ realpathSync.native(this.root);
1953
+ } catch {
1954
+ return targetKey;
1955
+ }
1956
+ const [name, ...tail] = targetKey.slice(7).split("::");
1957
+ if (name === void 0 || name === "") return targetKey;
1958
+ const rel = tail.join("::");
1959
+ const dir = this.dirOf(name);
1960
+ const namespace = rel === "*";
1961
+ let cursor = namespace ? dir : rel === "" ? join(dir, "SKILL.md") : join(dir, ...rel.replace(/\\/g, "/").split("/").filter(Boolean));
1962
+ const suffix = [];
1963
+ let identity;
1964
+ while (true) try {
1965
+ identity = join(realpathSync.native(cursor), ...suffix.reverse());
1966
+ break;
1967
+ } catch {
1968
+ const parent = dirname(cursor);
1969
+ if (parent === cursor) return targetKey;
1970
+ suffix.push(basename(cursor));
1971
+ cursor = parent;
1972
+ }
1973
+ return "skillpath:" + createHash("sha256").update(identity.replace(/\\/g, "/")).digest("hex") + (namespace ? "::*" : "");
1622
1974
  }
1623
1975
  async withMutationLock(task, targetKeys) {
1624
- const lease = await this.lockPort().acquire(targetKeys);
1976
+ const keys = targetKeys === void 0 ? void 0 : await this.canonicalLockKeys(targetKeys);
1977
+ const lease = await this.lockPort().acquire(keys);
1625
1978
  try {
1626
1979
  return await task();
1627
1980
  } finally {
1628
1981
  await lease.release();
1629
1982
  }
1630
1983
  }
1631
- /** The one MutationUnit constructor: storage ports are fixed here, callers pass the rest. */
1984
+ /** The one UnitKernel constructor: storage ports are fixed here, callers pass the rest. */
1632
1985
  commitUnit(options) {
1633
- return new MutationUnit({
1986
+ const plan = PLAN_SINK.getStore();
1987
+ if (plan !== void 0) return { apply: async (request) => {
1988
+ for (const op of request.ops) {
1989
+ const skill = op.skill ?? request.name;
1990
+ const rel = relative(this.dirOf(skill), op.target).split(String.fromCharCode(92)).join("/");
1991
+ plan.writes.push({
1992
+ target: op.target,
1993
+ expected: op.expected ?? null,
1994
+ content: op.kind === "delete" ? null : op.content,
1995
+ skill,
1996
+ path: rel === "SKILL.md" ? void 0 : rel,
1997
+ auditAction: request.auditAction,
1998
+ auditSummary: request.auditSummary
1999
+ });
2000
+ }
2001
+ return {
2002
+ ok: true,
2003
+ unitId: request.unitId ?? "plan-item-" + Date.now().toString(36) + "-" + Math.random().toString(36).slice(2, 8),
2004
+ dryRun: false,
2005
+ changed: request.ops.map((op) => op.target),
2006
+ errors: []
2007
+ };
2008
+ } };
2009
+ return new UnitKernel({
1634
2010
  io: this.io,
1635
2011
  journal: unitJournalPort(this.io, dirname(this.root)),
1636
2012
  snapshots: unitSnapshotPort(this.io, dirname(this.root)),
2013
+ targetKeyResolver: (keys) => this.canonicalLockKeys(keys),
1637
2014
  ...options
1638
2015
  });
1639
2016
  }
@@ -1692,7 +2069,10 @@ var SkillLibrary = class {
1692
2069
  recovery;
1693
2070
  /** Run the boot recovery once per library instance, before the first write. */
1694
2071
  async ensureRecovered() {
1695
- this.recovery ??= this.recoverPreparedUnits().then(() => void 0).catch((error) => {
2072
+ this.recovery ??= this.recoverPreparedUnits().then((results) => {
2073
+ const unresolved = results.filter((result) => !result.ok);
2074
+ if (unresolved.length > 0) console.warn("skill-store: prepared-unit recovery left " + String(unresolved.length) + " unit(s) unresolved; first: " + unresolved.slice(0, 5).map((result) => result.unitId + "=" + (result.errors[0]?.code ?? "unknown") + ":" + (result.errors[0]?.message ?? "")).join("; "));
2075
+ }).catch((error) => {
1696
2076
  console.warn("skill-store: prepared-unit recovery failed; writes continue: " + (error instanceof Error ? error.message : String(error)));
1697
2077
  });
1698
2078
  await this.recovery;
@@ -2220,7 +2600,14 @@ var SkillLibrary = class {
2220
2600
  async audit(skillName, action, before, after, summary, path, unitId, unitHead, origin, fenceHeld = false, change) {
2221
2601
  const fence = fenceHeld ? void 0 : this.fence;
2222
2602
  const at = (/* @__PURE__ */ new Date()).toISOString();
2223
- const finalSummary = change === void 0 ? this.hostChangeSummary(action, before, after, path, summary) : (() => {
2603
+ const planSummary = PLAN_SUMMARY.getStore();
2604
+ const finalSummary = planSummary !== void 0 ? (() => {
2605
+ const normalized = normalizeChangeSummary(planSummary, 50);
2606
+ return normalized.ok ? {
2607
+ text: normalized.text,
2608
+ source: "model"
2609
+ } : this.hostChangeSummary(action, before, after, path, summary);
2610
+ })() : change === void 0 ? this.hostChangeSummary(action, before, after, path, summary) : (() => {
2224
2611
  const normalized = normalizeChangeSummary(change.text, 50);
2225
2612
  return normalized.ok ? {
2226
2613
  text: normalized.text,
@@ -2530,17 +2917,20 @@ var SkillLibrary = class {
2530
2917
  };
2531
2918
  }
2532
2919
  }
2533
- await this.audit(normalized, "create", null, onDisk, "created", void 0, result.unitId, options.unitHead, void 0, fenceHeld);
2534
- this.notifyMutation({
2535
- action: "create",
2536
- name: normalized,
2537
- skillDir: dir
2538
- });
2920
+ if (PLAN_SINK.getStore() === void 0) {
2921
+ await this.audit(normalized, "create", null, onDisk, "created", void 0, result.unitId, options.unitHead, void 0, fenceHeld);
2922
+ this.notifyMutation({
2923
+ action: "create",
2924
+ name: normalized,
2925
+ skillDir: dir
2926
+ });
2927
+ }
2539
2928
  const warnings = [createDurabilityWarning !== "" ? `写入已落盘,但目录 fsync 失败 —— 持久性未确认:${createDurabilityWarning}` : "", markerWarning].filter((warning) => warning !== "");
2540
2929
  return {
2541
2930
  ok: true,
2542
2931
  message: `已创建技能「${normalized}」。${warnings.length === 0 ? "" : ` (警告:${warnings.join(";")})`}`,
2543
2932
  path: dir,
2933
+ after: onDisk,
2544
2934
  ...norm.changed ? { normalizedFrontmatterFields: norm.fields } : {}
2545
2935
  };
2546
2936
  }
@@ -2655,6 +3045,7 @@ var SkillLibrary = class {
2655
3045
  ok: true,
2656
3046
  message: `技能「${name}」已更新。${warning}${retention === null ? "" : "\n" + retention}`,
2657
3047
  path: dir,
3048
+ after: onDisk,
2658
3049
  ...prepared.norm.changed ? { normalizedFrontmatterFields: prepared.norm.fields } : {}
2659
3050
  };
2660
3051
  }
@@ -2738,14 +3129,16 @@ var SkillLibrary = class {
2738
3129
  ok: true,
2739
3130
  message: `技能「${name}」未变更:章节内容一致,未写入。`,
2740
3131
  noop: true,
2741
- path: dir
3132
+ path: dir,
3133
+ after: md
2742
3134
  };
2743
3135
  const result = await this.update(name, finalMd, origin, { sha256: contentHash(md) });
2744
3136
  if (!result.ok) return result;
2745
3137
  return {
2746
3138
  ok: true,
2747
3139
  message: `已更新「${name}」的「${edit.heading}」章节(正文 ${md.length} → ${finalMd.length} 字符)。`,
2748
- path: dir
3140
+ path: dir,
3141
+ ...result.after === void 0 ? {} : { after: result.after }
2749
3142
  };
2750
3143
  }
2751
3144
  async patchCore(name, oldString, newString, filePath, replaceAll, origin, anchor) {
@@ -2879,6 +3272,7 @@ var SkillLibrary = class {
2879
3272
  ok: true,
2880
3273
  message: `技能「${name}」已修补(${patchLabel})。${patchNote}${capAdvisory}`,
2881
3274
  path: dir,
3275
+ after: onDisk,
2882
3276
  ...normalizedFields ? { normalizedFrontmatterFields: normalizedFields } : {}
2883
3277
  },
2884
3278
  write: onDisk,
@@ -4584,6 +4978,201 @@ var SkillLibrary = class {
4584
4978
  };
4585
4979
  }));
4586
4980
  }
4981
+ /**
4982
+ * Execute one plan-level write through the existing mutators.
4983
+ *
4984
+ * H1 deliberately supports one op only: it is the stable seam the tool and
4985
+ * approval will move onto, while the multi-op UnitTransaction path is the
4986
+ * next phase. Refusing a partial plan is safer than committing half of it.
4987
+ * @param plan - origin plus the single operation to apply.
4988
+ * @returns the action result; `outcomes` stays empty until the provider
4989
+ * returns before/after/version in the next phase.
4990
+ */
4991
+ async apply(plan) {
4992
+ const op = plan.ops[0];
4993
+ if (op === void 0) return {
4994
+ ok: false,
4995
+ message: "skill write plan is empty",
4996
+ outcomes: []
4997
+ };
4998
+ if (plan.ops.length > 1) return plan.summary === void 0 || plan.summary === "" ? await this.applyMulti(plan) : await PLAN_SUMMARY.run(plan.summary, () => this.applyMulti(plan));
4999
+ const result = plan.summary === void 0 || plan.summary === "" ? await this.applyOne(op, plan.origin) : await PLAN_SUMMARY.run(plan.summary, () => this.applyOne(op, plan.origin));
5000
+ const target = op.kind === "createSkill" ? skillBodyTarget(op.skill) : op.target;
5001
+ const outcomes = result.ok && result.after !== void 0 ? [{
5002
+ op,
5003
+ target,
5004
+ after: result.after,
5005
+ version: result.after === null ? "" : contentHash(result.after)
5006
+ }] : [];
5007
+ return {
5008
+ ok: result.ok,
5009
+ message: result.message,
5010
+ outcomes,
5011
+ ...result.stale === true ? { stale: true } : {},
5012
+ ...result.noop === true ? { noop: true } : {},
5013
+ ...result.path === void 0 ? {} : { path: result.path },
5014
+ ...result.normalizedFrontmatterFields === void 0 ? {} : { normalizedFrontmatterFields: result.normalizedFrontmatterFields }
5015
+ };
5016
+ }
5017
+ /**
5018
+ * Commit a multi-op plan as one atomic unit. Each op is first prepared by the
5019
+ * existing single-op mutator in a collector context (so its validation and
5020
+ * anchor/CAS checks stay the source of truth), then all collected writes are
5021
+ * handed to ONE UnitKernel. Any preparation failure or stale anchor leaves
5022
+ * every target untouched.
5023
+ */
5024
+ async applyMulti(plan) {
5025
+ const creating = plan.ops.find((op) => op.kind === "createSkill" || op.kind === "write" && op.target.relPath === "" && op.expect.kind === "absent" && op.create !== false);
5026
+ if (creating !== void 0 && (plan.origin !== "foreground" || creating.kind === "createSkill" && creating.managed === true)) return {
5027
+ ok: false,
5028
+ message: "multi-op plans cannot create a managed/non-foreground skill; create it in its own plan first",
5029
+ outcomes: []
5030
+ };
5031
+ const sink = { writes: [] };
5032
+ const results = [];
5033
+ const writeCounts = [];
5034
+ const refusal = await PLAN_SINK.run(sink, async () => {
5035
+ for (const op of plan.ops) {
5036
+ const start = sink.writes.length;
5037
+ const result = await this.applyOne(op, plan.origin);
5038
+ results.push(result);
5039
+ writeCounts.push(sink.writes.length - start);
5040
+ if (!result.ok) return result;
5041
+ }
5042
+ });
5043
+ if (refusal !== void 0) return {
5044
+ ok: false,
5045
+ message: refusal.message,
5046
+ outcomes: [],
5047
+ ...refusal.stale === true ? { stale: true } : {}
5048
+ };
5049
+ if (new Set(sink.writes.map((write) => write.target)).size !== sink.writes.length) return {
5050
+ ok: false,
5051
+ message: "multi-op plan targets the same path more than once",
5052
+ outcomes: []
5053
+ };
5054
+ if (sink.writes.length === 0) return {
5055
+ ok: true,
5056
+ message: "没有写入变更。",
5057
+ outcomes: plan.ops.map((op, index) => ({
5058
+ op,
5059
+ target: op.kind === "createSkill" ? skillBodyTarget(op.skill) : op.target,
5060
+ ...results[index]?.after === void 0 ? {} : { after: results[index].after },
5061
+ noop: true
5062
+ }))
5063
+ };
5064
+ const skills = [...new Set(sink.writes.map((write) => write.skill))];
5065
+ const roots = skills.map((name) => ({
5066
+ name,
5067
+ protection: "write"
5068
+ }));
5069
+ const rootDirs = Object.fromEntries(skills.map((name) => [name, this.dirOf(name)]));
5070
+ const targetKeys = [...new Set(sink.writes.flatMap((write) => [write.path === void 0 ? "skill::" + write.skill : "skill::" + write.skill + "::" + write.path, skillNamespaceKey(write.skill)]))];
5071
+ const applied = await this.commitUnit({
5072
+ limits: {
5073
+ maxSkillFileBytes: Number.MAX_SAFE_INTEGER,
5074
+ maxSkillContentChars: Number.MAX_SAFE_INTEGER
5075
+ },
5076
+ serial: this.serial,
5077
+ lock: this.lockPort(),
5078
+ targetKeys,
5079
+ ...this.transact === void 0 ? {} : { transact: this.transact },
5080
+ hooks: { committed: async (event) => {
5081
+ for (const write of sink.writes) {
5082
+ const before = write.expected;
5083
+ const after = write.content;
5084
+ await this.audit(write.skill, write.auditAction, before, after, write.auditSummary, write.path, event.unitId, { sources: [{ skill: write.skill }] }, plan.origin, true);
5085
+ this.notifyMutation({
5086
+ action: write.auditAction,
5087
+ name: write.skill,
5088
+ skillDir: this.dirOf(write.skill),
5089
+ ...write.path === void 0 ? {} : { file: write.target }
5090
+ });
5091
+ }
5092
+ } },
5093
+ validateWrite: (op) => op.kind === "write" ? this.contentThreatBlock(op.content) : null
5094
+ }).apply({
5095
+ name: skills[0] ?? "",
5096
+ origin: plan.origin,
5097
+ roots,
5098
+ rootDirs,
5099
+ ops: sink.writes.map((write) => write.content === null ? {
5100
+ kind: "delete",
5101
+ target: write.target,
5102
+ expected: write.expected,
5103
+ skill: write.skill
5104
+ } : {
5105
+ kind: "write",
5106
+ target: write.target,
5107
+ content: write.content,
5108
+ expected: write.expected,
5109
+ skill: write.skill
5110
+ }),
5111
+ auditAction: "update",
5112
+ auditSummary: plan.summary ?? "applied write plan",
5113
+ eventAction: "update"
5114
+ });
5115
+ if (!applied.ok) return {
5116
+ ok: false,
5117
+ message: applied.errors.map((error) => error.message).join(";"),
5118
+ outcomes: [],
5119
+ ...applied.warnings === void 0 ? {} : { warnings: applied.warnings }
5120
+ };
5121
+ let cursor = 0;
5122
+ const outcomes = plan.ops.map((op, index) => {
5123
+ if ((writeCounts[index] ?? 0) === 0) {
5124
+ const after = results[index]?.after;
5125
+ return {
5126
+ op,
5127
+ target: op.kind === "createSkill" ? skillBodyTarget(op.skill) : op.target,
5128
+ ...after === void 0 ? {} : { after },
5129
+ ...typeof after === "string" ? { version: contentHash(after) } : {},
5130
+ noop: true
5131
+ };
5132
+ }
5133
+ const write = sink.writes[cursor++];
5134
+ return {
5135
+ op,
5136
+ target: op.kind === "createSkill" ? skillBodyTarget(op.skill) : op.target,
5137
+ before: write.expected,
5138
+ after: write.content,
5139
+ version: write.content === null ? "" : contentHash(write.content)
5140
+ };
5141
+ });
5142
+ return {
5143
+ ok: true,
5144
+ message: "已原子应用 " + String(outcomes.length) + " 个写入。",
5145
+ outcomes,
5146
+ ...applied.warnings === void 0 || applied.warnings.length === 0 ? {} : { warnings: applied.warnings }
5147
+ };
5148
+ }
5149
+ async applyOne(op, origin) {
5150
+ switch (op.kind) {
5151
+ case "createSkill": return await this.create(op.skill, op.content, origin, op.managed === true ? { managed: true } : {});
5152
+ case "write": {
5153
+ if (op.target.relPath === "") {
5154
+ if (op.expect.kind === "absent") {
5155
+ if (op.create !== false) return await this.create(op.target.skill, op.content, origin);
5156
+ return await this.update(op.target.skill, op.content, origin, { absent: true });
5157
+ }
5158
+ return await this.update(op.target.skill, op.content, origin, { sha256: op.expect.version });
5159
+ }
5160
+ const anchor = op.expect.kind === "absent" ? { absent: true } : { sha256: op.expect.version };
5161
+ return await this.writeSupportFile(op.target.skill, op.target.relPath, op.content, origin, anchor);
5162
+ }
5163
+ case "patch": {
5164
+ const anchor = op.expect.kind === "absent" ? { absent: true } : { sha256: op.expect.version };
5165
+ return await this.patch(op.target.skill, op.oldString, op.newString, op.target.relPath, op.replaceAll, origin, anchor);
5166
+ }
5167
+ case "patchSection": return await this.patchSection(op.target.skill, op.section, origin, op.expect.kind === "absent" ? { absent: true } : { sha256: op.expect.version });
5168
+ case "remove":
5169
+ if (op.target.relPath === "") return {
5170
+ ok: false,
5171
+ message: "removing SKILL.md must use the structural archive path, not a plan remove"
5172
+ };
5173
+ return await this.removeSupportFile(op.target.skill, op.target.relPath, origin, op.expect.kind === "absent" ? { absent: true } : { sha256: op.expect.version }, op.unitId);
5174
+ }
5175
+ }
4587
5176
  async writeSupportFile(rawName, filePath, content, origin = this.authority.origin, anchor) {
4588
5177
  const name = rawName.trim();
4589
5178
  const key = "skill::" + name + "::" + filePath.replace(/\\/g, "/");
@@ -4596,7 +5185,7 @@ var SkillLibrary = class {
4596
5185
  message: badName
4597
5186
  };
4598
5187
  const dir = this.dirOf(name);
4599
- if (!await this.io.exists(join(dir, "SKILL.md"))) return {
5188
+ if (!(PLAN_SINK.getStore()?.writes.some((write) => write.skill === name && write.path === void 0 && write.expected === null) === true) && !await this.io.exists(join(dir, "SKILL.md"))) return {
4600
5189
  ok: false,
4601
5190
  message: `技能「${name}」不存在。`
4602
5191
  };
@@ -4639,7 +5228,8 @@ var SkillLibrary = class {
4639
5228
  ok: true,
4640
5229
  message: `支撑文件「${filePath}」未变更:提供的内容与当前文件一致,未写入。`,
4641
5230
  noop: true,
4642
- path: target
5231
+ path: target,
5232
+ after: current
4643
5233
  };
4644
5234
  const result = await this.commitUnit({
4645
5235
  limits: {
@@ -4688,7 +5278,8 @@ var SkillLibrary = class {
4688
5278
  return {
4689
5279
  ok: true,
4690
5280
  message: `支撑文件「${filePath}」已写入「${name}」。${capAdvisory}${result.warnings === void 0 || result.warnings.length === 0 ? "" : ` (警告:写入已落盘,但目录 fsync 失败 —— 持久性未确认:${result.warnings.join(";")})`}`,
4691
- path: target
5281
+ path: target,
5282
+ after: content
4692
5283
  };
4693
5284
  }
4694
5285
  async removeSupportFile(rawName, filePath, origin = this.authority.origin, anchor, unitId) {
@@ -4735,6 +5326,24 @@ var SkillLibrary = class {
4735
5326
  const before = beforeProbe.value;
4736
5327
  let verdict = anchorVerdict(anchor, before);
4737
5328
  let lockedBefore = before;
5329
+ const planSink = PLAN_SINK.getStore();
5330
+ if (planSink !== void 0 && verdict === "match") {
5331
+ planSink.writes.push({
5332
+ target,
5333
+ expected: before,
5334
+ content: null,
5335
+ skill: name,
5336
+ path: filePath.replace(/\\/g, "/"),
5337
+ auditAction: "remove_file",
5338
+ auditSummary: "removed " + filePath
5339
+ });
5340
+ return {
5341
+ ok: true,
5342
+ message: "支撑文件「" + filePath + "」已从「" + name + "」移除。",
5343
+ path: target,
5344
+ after: null
5345
+ };
5346
+ }
4738
5347
  if (verdict === "match" && this.transact) {
4739
5348
  const ran = { done: false };
4740
5349
  try {
@@ -4767,7 +5376,8 @@ var SkillLibrary = class {
4767
5376
  return {
4768
5377
  ok: true,
4769
5378
  message: `支撑文件「${filePath}」已从「${name}」移除。`,
4770
- path: target
5379
+ path: target,
5380
+ after: null
4771
5381
  };
4772
5382
  }
4773
5383
  /**
@@ -5171,4 +5781,4 @@ function newSkillLibrary(options) {
5171
5781
  } : void 0, transact, [...threatExemptLabels ?? []], authority, options.mutationLock ?? mutationLockFrom(ctx), options.fence ?? ctx?.get?.("evolutionMutationAuthority")?.homeFence);
5172
5782
  }
5173
5783
  //#endregion
5174
- export { BASELINE_ACTION, DEFAULT_ARCHIVE_RETENTION_POLICY, DEFAULT_CITATION_POLICY, DEFAULT_HEALTH_THRESHOLDS, DEFAULT_REFERENCE_REWRITE_POLICY, DEFAULT_SKILL_LIMITS, DEFAULT_SKILL_WRITE_SUMMARY_CHARS, DEFAULT_SUPPORT_FILE_CHAR_POLICY, HEALTH_STAMP_RE, HISTORY_DIR, HISTORY_INDEX_VERSION, MAX_RESTRUCTURE_MOVES, MIN_STAMP_BODY_CHARS, POLICY_STAGE_DEFAULTS, READ_REQUIRED_ACTIONS, RECENT_USE_WINDOW_DAYS, RESTRUCTURE_TARGET_RE, RETENTION_FEEDBACK_KEEP_RATIO, RETENTION_FEEDBACK_MIN_CHARS, RULES, SKILL_OPERATIONS, SNAPSHOT_EXTRA_NAME_RE, SkillLibrary, SkillModel, SkillObservationStore, SkillRootGate, SkillTargetLocks, SkillWriteService, TEXT_DIFF_MAX_CHARS, TEXT_DIFF_MAX_LINES, ageCopyKey, anchorVerdict, assertSkillsRootAliasRetired, assessStructureHealth, authoringFeedback, blobPath, clipChangeSummary, compareSkillStats, computeSkillStatsTotals, contentRetentionFeedback, decideLiteralEdit, decideSkillWrite, diffFindings, elapsedSince, ensureSkillFrontmatter, entryTarget, exceedsContentLimit, filterSkillStats, filterUnreadSkillOps, frontmatterBlock, frontmatterCatalogInvalid, historyIndexFile, historyRoot, isUnreadWrite, latestActivityAt, latestVersionAt, lintBody, lintSkill, loadVersionContent, loadVersions, markerEntryName, needsAttention, newSkillLibrary, nextHistoryIndex, normalizeChangeSummary, normalizeFrontmatter, orderVersions, parseFrontmatter, parseHistoryIndex, partitionVersions, policyStageLimits, readHistoryIndex, recentlyUsedAt, recordFsSkillObservation, recordVersions, relatedSkillNames, resolveExecOrigins, resolveOrigins, resolveRootConfig, resolveSkillsRoot, revisionAnchor, revisionAnchorOf, revisionFingerprint, revisionSupportDigest, sessionReadSkillNames, sessionReadSupportFiles, shrinksOverLimit, skillBodyTarget, skillContentVersion, skillMdOnDisk, skillNamespaceKey, skillRowCells, skillStateKey, skillSupportTarget, skillTarget, skillTargetFromHostPath, skillVersionOf, skillsRoot, softBodyTokenBudget, sortSkillStats, sortValue, summaryChars, textDiffFacts, validateFrontmatter, validateRestructureTarget, validateSupportPath, verdictRank, versionActionKind, versionRowCells, versionTarget, yamlPlainScalarNeedsQuotes };
5784
+ export { BASELINE_ACTION, DEFAULT_ARCHIVE_RETENTION_POLICY, DEFAULT_CITATION_POLICY, DEFAULT_HEALTH_THRESHOLDS, DEFAULT_REFERENCE_REWRITE_POLICY, DEFAULT_SKILL_LIMITS, DEFAULT_SKILL_WRITE_SUMMARY_CHARS, DEFAULT_SUPPORT_FILE_CHAR_POLICY, HEALTH_STAMP_RE, HISTORY_DIR, HISTORY_INDEX_VERSION, MAX_RESTRUCTURE_MOVES, MIN_STAMP_BODY_CHARS, POLICY_STAGE_DEFAULTS, READ_REQUIRED_ACTIONS, RECENT_USE_WINDOW_DAYS, RESTRUCTURE_TARGET_RE, RETENTION_FEEDBACK_KEEP_RATIO, RETENTION_FEEDBACK_MIN_CHARS, RULES, SKILL_OPERATIONS, SNAPSHOT_EXTRA_NAME_RE, SkillLibrary, SkillModel, SkillObservationStore, SkillRootGate, SkillTargetLocks, SkillWriteService, SystemSkillWriter, TEXT_DIFF_MAX_CHARS, TEXT_DIFF_MAX_LINES, ageCopyKey, anchorVerdict, assertSkillsRootAliasRetired, assessStructureHealth, authoringFeedback, blobPath, clipChangeSummary, compareSkillStats, computeSkillStatsTotals, contentRetentionFeedback, decideLiteralEdit, decideSkillWrite, diffFindings, elapsedSince, ensureSkillFrontmatter, entryTarget, exceedsContentLimit, filterSkillStats, filterUnreadSkillOps, frontmatterBlock, frontmatterCatalogInvalid, historyIndexFile, historyRoot, isUnreadWrite, latestActivityAt, latestVersionAt, lintBody, lintSkill, loadVersionContent, loadVersions, markerEntryName, needsAttention, newSkillLibrary, nextHistoryIndex, normalizeChangeSummary, normalizeFrontmatter, orderVersions, parseFrontmatter, parseHistoryIndex, partitionVersions, policyStageLimits, projectRestructureMarkdown, readHistoryIndex, recentlyUsedAt, recordFsSkillObservation, recordVersions, relatedSkillNames, resolveExecOrigins, resolveOrigins, resolveRootConfig, resolveSkillsRoot, revisionAnchor, revisionAnchorOf, revisionFingerprint, revisionSupportDigest, sessionReadSkillNames, sessionReadSupportFiles, shrinksOverLimit, skillBodyTarget, skillContentVersion, skillHostIdentity, skillMdOnDisk, skillNamespaceKey, skillRowCells, skillStateKey, skillSupportTarget, skillTarget, skillTargetFromHostPath, skillVersionOf, skillsRoot, softBodyTokenBudget, sortSkillStats, sortValue, summaryChars, textDiffFacts, validateFrontmatter, validateRestructureTarget, validateSupportPath, verdictRank, versionActionKind, versionRowCells, versionTarget, yamlPlainScalarNeedsQuotes };