@lmzhen/dsh-evolution-core 0.59.4 → 0.59.6

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.
package/lib/skills.js CHANGED
@@ -8,9 +8,12 @@ import { E as usageFile, F as describeReferenceRewrite, I as planReferenceRewrit
8
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";
9
9
  import { n as evolutionRoot } from "./state-store-Jpa-iYIZ.js";
10
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";
11
+ import { D as fileMutationLock, E as MutationUnit, n as unitJournalPort, r as unitSnapshotPort, t as pruneTreeChangeUnits } from "./mutation-storage-adapter-Cq1bmS1E.js";
12
12
  import { n as projectExtractBodies } from "./extract-plan-D3ALlAmN.js";
13
+ import { createHash } from "node:crypto";
14
+ import { realpath } from "node:fs/promises";
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);
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,6 +846,12 @@ 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
  }
@@ -692,7 +859,9 @@ function actionResult(result) {
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 }
696
865
  };
697
866
  if (result.stale === true) return {
698
867
  ok: false,
@@ -706,6 +875,86 @@ function actionResult(result) {
706
875
  };
707
876
  }
708
877
  //#endregion
878
+ //#region lib/types/system-skill-writer.js
879
+ var SystemSkillWriter = class {
880
+ library;
881
+ constructor(library) {
882
+ this.library = library;
883
+ }
884
+ /**
885
+ * Apply one explicit plan through the single provider.
886
+ * @param plan - origin, ops and the caller's snapshot anchors.
887
+ * @returns the provider result; no observation is recorded.
888
+ */
889
+ async apply(plan) {
890
+ return await this.library.apply(plan);
891
+ }
892
+ };
893
+ //#endregion
894
+ //#region lib/types/skill-target-locks.js
895
+ /**
896
+ * Per-target promise locks for skill writes.
897
+ *
898
+ * The current SkillLibrary serial queue is per root, so writes to different
899
+ * skills serialize even though they share no bytes. This table is the
900
+ * replacement primitive: one tail promise per canonical target key, and a
901
+ * multi-target acquisition that takes keys in lexical order to make deadlock
902
+ * impossible. It is deliberately pure (no IO, no timeout) so the service can
903
+ * compose it with transactIo/HomeFence rather than duplicate lock semantics.
904
+ *
905
+ * @module @lmzhen/dsh-evolution-core/skill-target-locks
906
+ */
907
+ /** A lock table keyed by canonical skill target key. */
908
+ var SkillTargetLocks = class {
909
+ tails = /* @__PURE__ */ new Map();
910
+ /**
911
+ * Run one task while holding one target key.
912
+ * @param targetKey - canonical skill target key.
913
+ * @param task - the read/compare/write critical section.
914
+ * @returns the task's value.
915
+ */
916
+ async withLock(targetKey, task) {
917
+ return await this.withLocks([targetKey], task);
918
+ }
919
+ /**
920
+ * Run one task while holding several target keys.
921
+ *
922
+ * Keys are deduplicated and acquired in lexical order; the caller may pass
923
+ * them in any order. A task must not call {@link withLock}/{@link withLocks}
924
+ * for a key it already holds (the promise chain is not reentrant), so callers
925
+ * should flatten multi-file units into one acquisition.
926
+ * @param targetKeys - canonical target keys touched by the unit.
927
+ * @param task - the unit's read/compare/write critical section.
928
+ * @returns the task's value.
929
+ */
930
+ async withLocks(targetKeys, task) {
931
+ const keys = [...new Set(targetKeys)].sort();
932
+ return await this.acquire(keys, 0, task);
933
+ }
934
+ /** Number of live target queues; exposed for leak assertions in tests. */
935
+ get size() {
936
+ return this.tails.size;
937
+ }
938
+ async acquire(keys, index, task) {
939
+ const key = keys[index];
940
+ if (key === void 0) return await task();
941
+ const prior = this.tails.get(key) ?? Promise.resolve();
942
+ let release;
943
+ const gate = new Promise((resolve) => {
944
+ release = resolve;
945
+ });
946
+ const tail = prior.then(() => gate);
947
+ this.tails.set(key, tail);
948
+ await prior;
949
+ try {
950
+ return await this.acquire(keys, index + 1, task);
951
+ } finally {
952
+ release();
953
+ if (this.tails.get(key) === tail) this.tails.delete(key);
954
+ }
955
+ }
956
+ };
957
+ //#endregion
709
958
  //#region lib/types/skill-root-gate.js
710
959
  /**
711
960
  * Root-level shared/exclusive gate for skill-tree operations.
@@ -1618,10 +1867,64 @@ var SkillLibrary = class {
1618
1867
  }
1619
1868
  /** Transitional: serialize one target even while the root serial remains. */
1620
1869
  async withTarget(targetKey, task) {
1621
- return await this.targetLocks.withLock(targetKey, task);
1870
+ return await this.targetLocks.withLock(await this.canonicalTargetKey(targetKey), task);
1871
+ }
1872
+ /** Canonicalize several logical target keys for one lock acquisition. */
1873
+ async canonicalLockKeys(keys) {
1874
+ return await Promise.all(keys.map((key) => this.canonicalTargetKey(key)));
1875
+ }
1876
+ /**
1877
+ * Attach the canonical realpath identity to one observation target.
1878
+ * @param target - logical skill target.
1879
+ * @returns the target with `identityKey`; the logical targetKey is unchanged.
1880
+ */
1881
+ async identify(target) {
1882
+ const key = target.relPath === "" ? "skill::" + target.skill : "skill::" + target.skill + "::" + target.relPath;
1883
+ return {
1884
+ ...target,
1885
+ identityKey: await this.canonicalTargetKey(key)
1886
+ };
1887
+ }
1888
+ /**
1889
+ * Canonical in-process lock identity for one skill target key.
1890
+ *
1891
+ * A logical `skill::name::path` key is resolved through realpath (or the
1892
+ * nearest existing ancestor for a not-yet-created file) and hashed, so two
1893
+ * spellings/symlinks of the same host file share one promise-lock queue. The
1894
+ * logical targetKey stays the observation/approval key until the observation
1895
+ * resolver phase; this method only fixes the provider lock identity.
1896
+ * @param targetKey - the family's logical skill target key.
1897
+ * @returns the canonical lock key, or the input for non-skill keys.
1898
+ */
1899
+ async canonicalTargetKey(targetKey) {
1900
+ if (!targetKey.startsWith("skill::")) return targetKey;
1901
+ try {
1902
+ await realpath(this.root);
1903
+ } catch {
1904
+ return targetKey;
1905
+ }
1906
+ const [name, ...tail] = targetKey.slice(7).split("::");
1907
+ if (name === void 0 || name === "") return targetKey;
1908
+ const rel = tail.join("::");
1909
+ const dir = this.dirOf(name);
1910
+ const namespace = rel === "*";
1911
+ let cursor = namespace ? dir : rel === "" ? join(dir, "SKILL.md") : join(dir, ...rel.replace(/\\/g, "/").split("/").filter(Boolean));
1912
+ const suffix = [];
1913
+ let identity;
1914
+ while (true) try {
1915
+ identity = join(await realpath(cursor), ...suffix.reverse());
1916
+ break;
1917
+ } catch {
1918
+ const parent = dirname(cursor);
1919
+ if (parent === cursor) return targetKey;
1920
+ suffix.push(basename(cursor));
1921
+ cursor = parent;
1922
+ }
1923
+ return "skillpath:" + createHash("sha256").update(identity.replace(/\\/g, "/")).digest("hex") + (namespace ? "::*" : "");
1622
1924
  }
1623
1925
  async withMutationLock(task, targetKeys) {
1624
- const lease = await this.lockPort().acquire(targetKeys);
1926
+ const keys = targetKeys === void 0 ? void 0 : await this.canonicalLockKeys(targetKeys);
1927
+ const lease = await this.lockPort().acquire(keys);
1625
1928
  try {
1626
1929
  return await task();
1627
1930
  } finally {
@@ -1634,6 +1937,7 @@ var SkillLibrary = class {
1634
1937
  io: this.io,
1635
1938
  journal: unitJournalPort(this.io, dirname(this.root)),
1636
1939
  snapshots: unitSnapshotPort(this.io, dirname(this.root)),
1940
+ targetKeyResolver: (keys) => this.canonicalLockKeys(keys),
1637
1941
  ...options
1638
1942
  });
1639
1943
  }
@@ -2541,6 +2845,7 @@ var SkillLibrary = class {
2541
2845
  ok: true,
2542
2846
  message: `已创建技能「${normalized}」。${warnings.length === 0 ? "" : ` (警告:${warnings.join(";")})`}`,
2543
2847
  path: dir,
2848
+ after: onDisk,
2544
2849
  ...norm.changed ? { normalizedFrontmatterFields: norm.fields } : {}
2545
2850
  };
2546
2851
  }
@@ -2655,6 +2960,7 @@ var SkillLibrary = class {
2655
2960
  ok: true,
2656
2961
  message: `技能「${name}」已更新。${warning}${retention === null ? "" : "\n" + retention}`,
2657
2962
  path: dir,
2963
+ after: onDisk,
2658
2964
  ...prepared.norm.changed ? { normalizedFrontmatterFields: prepared.norm.fields } : {}
2659
2965
  };
2660
2966
  }
@@ -2675,11 +2981,11 @@ var SkillLibrary = class {
2675
2981
  * @param origin - write face.
2676
2982
  * @returns the normalized result, with before/after body sizes.
2677
2983
  */
2678
- async patchSection(rawName, edit, origin = this.authority.origin) {
2984
+ async patchSection(rawName, edit, origin = this.authority.origin, anchor) {
2679
2985
  await this.ensureRecovered();
2680
- return await this.patchSectionCore(rawName.trim(), edit, origin);
2986
+ return await this.patchSectionCore(rawName.trim(), edit, origin, anchor);
2681
2987
  }
2682
- async patchSectionCore(name, edit, origin) {
2988
+ async patchSectionCore(name, edit, origin, anchor) {
2683
2989
  const badName = this.badName(name);
2684
2990
  if (badName) return {
2685
2991
  ok: false,
@@ -2701,6 +3007,8 @@ var SkillLibrary = class {
2701
3007
  ok: false,
2702
3008
  message: `技能「${name}」不存在。`
2703
3009
  };
3010
+ const verdict = anchorVerdict(anchor, md);
3011
+ if (verdict !== "match") return anchorRefusalFile(name, "SKILL.md", verdict);
2704
3012
  const block = frontmatterBlock(md);
2705
3013
  if (!block) return {
2706
3014
  ok: false,
@@ -2736,14 +3044,16 @@ var SkillLibrary = class {
2736
3044
  ok: true,
2737
3045
  message: `技能「${name}」未变更:章节内容一致,未写入。`,
2738
3046
  noop: true,
2739
- path: dir
3047
+ path: dir,
3048
+ after: md
2740
3049
  };
2741
3050
  const result = await this.update(name, finalMd, origin, { sha256: contentHash(md) });
2742
3051
  if (!result.ok) return result;
2743
3052
  return {
2744
3053
  ok: true,
2745
3054
  message: `已更新「${name}」的「${edit.heading}」章节(正文 ${md.length} → ${finalMd.length} 字符)。`,
2746
- path: dir
3055
+ path: dir,
3056
+ ...result.after === void 0 ? {} : { after: result.after }
2747
3057
  };
2748
3058
  }
2749
3059
  async patchCore(name, oldString, newString, filePath, replaceAll, origin, anchor) {
@@ -2877,6 +3187,7 @@ var SkillLibrary = class {
2877
3187
  ok: true,
2878
3188
  message: `技能「${name}」已修补(${patchLabel})。${patchNote}${capAdvisory}`,
2879
3189
  path: dir,
3190
+ after: onDisk,
2880
3191
  ...normalizedFields ? { normalizedFrontmatterFields: normalizedFields } : {}
2881
3192
  },
2882
3193
  write: onDisk,
@@ -4582,6 +4893,73 @@ var SkillLibrary = class {
4582
4893
  };
4583
4894
  }));
4584
4895
  }
4896
+ /**
4897
+ * Execute one plan-level write through the existing mutators.
4898
+ *
4899
+ * H1 deliberately supports one op only: it is the stable seam the tool and
4900
+ * approval will move onto, while the multi-op UnitTransaction path is the
4901
+ * next phase. Refusing a partial plan is safer than committing half of it.
4902
+ * @param plan - origin plus the single operation to apply.
4903
+ * @returns the action result; `outcomes` stays empty until the provider
4904
+ * returns before/after/version in the next phase.
4905
+ */
4906
+ async apply(plan) {
4907
+ const op = plan.ops[0];
4908
+ if (op === void 0) return {
4909
+ ok: false,
4910
+ message: "skill write plan is empty",
4911
+ outcomes: []
4912
+ };
4913
+ if (plan.ops.length > 1) return {
4914
+ ok: false,
4915
+ message: "multi-op skill write plans are not implemented in H1",
4916
+ outcomes: []
4917
+ };
4918
+ const result = await this.applyOne(op, plan.origin);
4919
+ const target = op.kind === "createSkill" ? skillBodyTarget(op.skill) : op.target;
4920
+ const outcomes = result.ok && result.after !== void 0 ? [{
4921
+ op,
4922
+ target,
4923
+ after: result.after,
4924
+ version: result.after === null ? "" : contentHash(result.after)
4925
+ }] : [];
4926
+ return {
4927
+ ok: result.ok,
4928
+ message: result.message,
4929
+ outcomes,
4930
+ ...result.stale === true ? { stale: true } : {},
4931
+ ...result.noop === true ? { noop: true } : {},
4932
+ ...result.path === void 0 ? {} : { path: result.path },
4933
+ ...result.normalizedFrontmatterFields === void 0 ? {} : { normalizedFrontmatterFields: result.normalizedFrontmatterFields }
4934
+ };
4935
+ }
4936
+ async applyOne(op, origin) {
4937
+ switch (op.kind) {
4938
+ case "createSkill": return await this.create(op.skill, op.content, origin, op.managed === true ? { managed: true } : {});
4939
+ case "write": {
4940
+ if (op.target.relPath === "") {
4941
+ if (op.expect.kind === "absent") {
4942
+ if (op.create !== false) return await this.create(op.target.skill, op.content, origin);
4943
+ return await this.update(op.target.skill, op.content, origin, { absent: true });
4944
+ }
4945
+ return await this.update(op.target.skill, op.content, origin, { sha256: op.expect.version });
4946
+ }
4947
+ const anchor = op.expect.kind === "absent" ? { absent: true } : { sha256: op.expect.version };
4948
+ return await this.writeSupportFile(op.target.skill, op.target.relPath, op.content, origin, anchor);
4949
+ }
4950
+ case "patch": {
4951
+ const anchor = op.expect.kind === "absent" ? { absent: true } : { sha256: op.expect.version };
4952
+ return await this.patch(op.target.skill, op.oldString, op.newString, op.target.relPath, op.replaceAll, origin, anchor);
4953
+ }
4954
+ case "patchSection": return await this.patchSection(op.target.skill, op.section, origin, op.expect.kind === "absent" ? { absent: true } : { sha256: op.expect.version });
4955
+ case "remove":
4956
+ if (op.target.relPath === "") return {
4957
+ ok: false,
4958
+ message: "removing SKILL.md must use the structural archive path, not a plan remove"
4959
+ };
4960
+ return await this.removeSupportFile(op.target.skill, op.target.relPath, origin, op.expect.kind === "absent" ? { absent: true } : { sha256: op.expect.version }, op.unitId);
4961
+ }
4962
+ }
4585
4963
  async writeSupportFile(rawName, filePath, content, origin = this.authority.origin, anchor) {
4586
4964
  const name = rawName.trim();
4587
4965
  const key = "skill::" + name + "::" + filePath.replace(/\\/g, "/");
@@ -4637,7 +5015,8 @@ var SkillLibrary = class {
4637
5015
  ok: true,
4638
5016
  message: `支撑文件「${filePath}」未变更:提供的内容与当前文件一致,未写入。`,
4639
5017
  noop: true,
4640
- path: target
5018
+ path: target,
5019
+ after: current
4641
5020
  };
4642
5021
  const result = await this.commitUnit({
4643
5022
  limits: {
@@ -4686,7 +5065,8 @@ var SkillLibrary = class {
4686
5065
  return {
4687
5066
  ok: true,
4688
5067
  message: `支撑文件「${filePath}」已写入「${name}」。${capAdvisory}${result.warnings === void 0 || result.warnings.length === 0 ? "" : ` (警告:写入已落盘,但目录 fsync 失败 —— 持久性未确认:${result.warnings.join(";")})`}`,
4689
- path: target
5068
+ path: target,
5069
+ after: content
4690
5070
  };
4691
5071
  }
4692
5072
  async removeSupportFile(rawName, filePath, origin = this.authority.origin, anchor, unitId) {
@@ -4765,7 +5145,8 @@ var SkillLibrary = class {
4765
5145
  return {
4766
5146
  ok: true,
4767
5147
  message: `支撑文件「${filePath}」已从「${name}」移除。`,
4768
- path: target
5148
+ path: target,
5149
+ after: null
4769
5150
  };
4770
5151
  }
4771
5152
  /**
@@ -5169,4 +5550,4 @@ function newSkillLibrary(options) {
5169
5550
  } : void 0, transact, [...threatExemptLabels ?? []], authority, options.mutationLock ?? mutationLockFrom(ctx), options.fence ?? ctx?.get?.("evolutionMutationAuthority")?.homeFence);
5170
5551
  }
5171
5552
  //#endregion
5172
- 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 };
5553
+ 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, 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 };