@lmzhen/dsh-evolution-core 0.59.6 → 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 (103) 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-Cq1bmS1E.js → mutation-storage-adapter-CSVn34dK.js} +327 -210
  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 +268 -37
  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-store.d.ts +37 -4
  65. package/lib/types/skill-store.js +240 -24
  66. package/lib/types/skill-write-plan.d.ts +1 -1
  67. package/lib/types/skill-write-service.js +8 -2
  68. package/lib/types/state/conformance.d.ts +47 -0
  69. package/lib/types/state/conformance.js +246 -0
  70. package/lib/types/state/constants.d.ts +52 -0
  71. package/lib/types/state/constants.js +52 -0
  72. package/lib/types/state/domain/compatibility.d.ts +40 -0
  73. package/lib/types/state/domain/compatibility.js +36 -0
  74. package/lib/types/state/domain/index.d.ts +81 -0
  75. package/lib/types/state/domain/index.js +592 -0
  76. package/lib/types/state/index.d.ts +63 -0
  77. package/lib/types/state/index.js +174 -0
  78. package/lib/types/state/medium-declaration.d.ts +37 -0
  79. package/lib/types/state/medium-declaration.js +53 -0
  80. package/lib/types/state/migrate.d.ts +34 -0
  81. package/lib/types/state/migrate.js +103 -0
  82. package/lib/types/state/record-contract.d.ts +56 -0
  83. package/lib/types/state/record-contract.js +120 -0
  84. package/lib/types/state/storage.d.ts +112 -0
  85. package/lib/types/state/storage.js +178 -0
  86. package/lib/types/state/store-plugin.d.ts +14 -0
  87. package/lib/types/state/store-plugin.js +18 -0
  88. package/lib/types/state/store.d.ts +39 -0
  89. package/lib/types/state/store.js +270 -0
  90. package/lib/types/store-ledger.js +2 -2
  91. package/lib/types/subagent/run.d.ts +1 -1
  92. package/lib/types/subagent/types.d.ts +4 -4
  93. package/lib/types/{write-kernel.d.ts → target-writer.d.ts} +32 -15
  94. package/lib/types/{write-kernel.js → target-writer.js} +40 -8
  95. package/lib/types/tool-dispatch.js +6 -3
  96. package/lib/types/{mutation-unit.d.ts → unit-kernel.d.ts} +40 -13
  97. package/lib/types/{mutation-unit.js → unit-kernel.js} +155 -118
  98. package/lib/types/write.d.ts +1 -2
  99. package/lib/types/write.js +1 -2
  100. package/lib/{usage-D7yHG2Cb.js → usage-BO4Zj_zB.js} +2 -2
  101. package/lib/write.js +4 -4
  102. package/package.json +30 -3
  103. package/persisted-write-inventory.json +14 -5
package/lib/restrictor.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { n as errorText } from "./errors-BxzLTVbS.js";
2
- import { presetsPort, toolsPort } from "@lmzhen/dsh-evolution-adapter/ports";
2
+ import { presetsPort, toolsPort } from "@lmzhen/dsh-evolution-platform/ports";
3
3
  //#region lib/types/restrictor.js
4
4
  const name = "evolution-restrictor";
5
5
  const inject = ["agentPresets"];
package/lib/result.js CHANGED
@@ -1,2 +1,2 @@
1
- export * from "@lmzhen/dsh-evolution-platform-contract/result";
1
+ export * from "@lmzhen/dsh-evolution-platform/contract/result";
2
2
  export {};
@@ -1,6 +1,6 @@
1
- import { c as transactIo } from "./io-Cpa8wuvj.js";
1
+ import { c as transactIo } from "./io-DT4-MXLr.js";
2
2
  import { N as DEFAULT_THREAT_MAX_SCAN_CHARS, O as DEFAULT_SOFT_BODY_TOKENS, tt as UPSTREAM_LIMIT_CHARS_PER_TOKEN } from "./limits-CO4JGSJL.js";
3
- import { O as collectReadSkillNames, R as supportFileReadFromPath, k as collectReadSupportFiles, l as sessionReadNames, o as isProjectableSession, v as DEFAULT_SUPPORT_READ_TOOL_NAMES } from "./session-projection-DM15fsRp.js";
3
+ import { O as collectReadSkillNames, R as supportFileReadFromPath, k as collectReadSupportFiles, l as sessionReadNames, o as isProjectableSession, v as DEFAULT_SUPPORT_READ_TOOL_NAMES } from "./session-projection-Dnmm5bzt.js";
4
4
  import { a as measureUnit, i as measureText } from "./text-metrics-CyJhxWBs.js";
5
5
  import { t as clampedNumber } from "./numeric-Dc53KQoe.js";
6
6
  import { AsyncLocalStorage } from "node:async_hooks";
@@ -1,7 +1,7 @@
1
- import { a as evolutionSignalsProjection, i as evolutionReadsProjection, n as evolutionEvidenceProjection, r as evolutionProjectionHistoryProjection, t as evolutionActivityProjection } from "../session-projection-DM15fsRp.js";
1
+ import { a as evolutionSignalsProjection, i as evolutionReadsProjection, n as evolutionEvidenceProjection, r as evolutionProjectionHistoryProjection, t as evolutionActivityProjection } from "../session-projection-Dnmm5bzt.js";
2
2
  import { join } from "node:path";
3
3
  import { existsSync, readFileSync } from "node:fs";
4
- import { EvolutionLlmError, modelRoute, profileContextPort } from "@lmzhen/dsh-evolution-adapter/ports";
4
+ import { EvolutionLlmError, modelRoute, profileContextPort } from "@lmzhen/dsh-evolution-platform/ports";
5
5
  import { Service } from "@deepseek-ai/cordis";
6
6
  //#region lib/types/runtime/coherence.js
7
7
  /**
@@ -112,7 +112,7 @@ function readDispatchRecord(event) {
112
112
  rootCallId: callId,
113
113
  name: "",
114
114
  arguments: void 0,
115
- outcome: { ok: data.isError !== true && data.error === void 0 && block?.isError !== true }
115
+ outcome: { ok: data.isError !== true && data.message?.isError !== true && data.error === void 0 && block?.isError !== true }
116
116
  };
117
117
  }
118
118
  const isPtc = event.type === "tool/ptc-dispatch-start" || event.type === "tool/ptc-dispatch";
@@ -1,7 +1,7 @@
1
- import { b as probeText, c as transactIo, m as isUnknown, p as isPresent } from "./io-Cpa8wuvj.js";
1
+ import { b as probeText, c as transactIo, m as isUnknown, p as isPresent } from "./io-DT4-MXLr.js";
2
2
  import { et as TEXT_DIFF_MAX_GRAPHEMES } from "./limits-CO4JGSJL.js";
3
3
  import { o as truncateGraphemes, r as graphemeCount } from "./text-metrics-CyJhxWBs.js";
4
- import { r as contentHash } from "./mutations-Y-wKod7W.js";
4
+ import { r as contentHash } from "./mutations-JKFlfhSO.js";
5
5
  import { join } from "node:path";
6
6
  //#region lib/types/skill-history.js
7
7
  /**
package/lib/skills.js CHANGED
@@ -1,17 +1,17 @@
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-Cq1bmS1E.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";
13
14
  import { createHash } from "node:crypto";
14
- import { realpath } from "node:fs/promises";
15
15
  import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
16
16
  import { realpathSync } from "node:fs";
17
17
  //#region lib/types/skill-stats.js
@@ -725,7 +725,7 @@ var SkillWriteService = class {
725
725
  if (result.ok && owner !== void 0) try {
726
726
  await this.observeOutcomes(result, owner);
727
727
  } catch {}
728
- return actionResult(result);
728
+ return actionResult(result, plan);
729
729
  }
730
730
  async observeOutcomes(result, owner) {
731
731
  for (const outcome of result.outcomes) {
@@ -855,7 +855,7 @@ function notObserved() {
855
855
  function anchorOf(version) {
856
856
  return { sha256: version };
857
857
  }
858
- function actionResult(result) {
858
+ function actionResult(result, plan) {
859
859
  if (result.ok) return {
860
860
  ok: true,
861
861
  message: result.message,
@@ -863,6 +863,12 @@ function actionResult(result) {
863
863
  ...result.path === void 0 ? {} : { path: result.path },
864
864
  ...result.normalizedFrontmatterFields === void 0 ? {} : { normalizedFrontmatterFields: result.normalizedFrontmatterFields }
865
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
871
+ };
866
872
  if (result.stale === true) return {
867
873
  ok: false,
868
874
  code: "SKILL_STALE_VERSION",
@@ -1746,6 +1752,26 @@ function planRestructureSections(body, moves) {
1746
1752
  }))
1747
1753
  };
1748
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
+ }
1749
1775
  /**
1750
1776
  * WHY MODULE SCOPE (S4.4): the serial queue must be shared ACROSS SkillLibrary instances. Six services
1751
1777
  * each build their own store over the SAME skill root (tool face / curator face / review face), and a
@@ -1760,8 +1786,15 @@ const ROOT_SERIAL = /* @__PURE__ */ new Map();
1760
1786
  * @param root - the resolved skill root; the key, so two spellings of one directory share a queue.
1761
1787
  * @returns the queue every instance over this root serializes through.
1762
1788
  */
1789
+ function canonicalRootKey(root) {
1790
+ try {
1791
+ return realpathSync.native(resolve(root));
1792
+ } catch {
1793
+ return resolve(root);
1794
+ }
1795
+ }
1763
1796
  function serialForRoot(root) {
1764
- const key = resolve(root);
1797
+ const key = canonicalRootKey(root);
1765
1798
  const existing = ROOT_SERIAL.get(key);
1766
1799
  if (existing !== void 0) return existing;
1767
1800
  const created = makeSerialQueue();
@@ -1775,14 +1808,30 @@ function sameRevisionAnchor(expected, live) {
1775
1808
  }
1776
1809
  /** One target-lock registry per skill ROOT, shared by every library instance in this process. */
1777
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
+ }
1778
1822
  function targetLocksFor(root) {
1779
- let locks = TARGET_LOCKS_BY_ROOT.get(root);
1823
+ const key = canonicalRootKey(root);
1824
+ let locks = TARGET_LOCKS_BY_ROOT.get(key);
1780
1825
  if (locks === void 0) {
1781
1826
  locks = new SkillTargetLocks();
1782
- TARGET_LOCKS_BY_ROOT.set(root, locks);
1827
+ TARGET_LOCKS_BY_ROOT.set(key, locks);
1783
1828
  }
1784
1829
  return locks;
1785
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();
1786
1835
  var SkillLibrary = class {
1787
1836
  root;
1788
1837
  /** The ONE read face owner/health/panel consume; a thin adapter, not a store. */
@@ -1802,8 +1851,8 @@ var SkillLibrary = class {
1802
1851
  serial;
1803
1852
  /** Transitional target locks (same key as SkillWriteService). */
1804
1853
  targetLocks;
1805
- /** Root structural gate; simple writes still use the serial until D.5d. */
1806
- rootGate = new SkillRootGate();
1854
+ /** Root structural gate; shared per canonical root across library instances. */
1855
+ rootGate;
1807
1856
  /** V10-03 (P2-18): see the constructor's threatExemptLabels. Empty by
1808
1857
  * default — the strict ANY-hit-blocks policy is unchanged. */
1809
1858
  threatExemptLabels;
@@ -1819,6 +1868,7 @@ var SkillLibrary = class {
1819
1868
  constructor(root = skillsRoot(), io = nodeEvolutionIo(), limits = DEFAULT_SKILL_LIMITS, onMutation, transact, threatExemptLabels, authority = CLASS_DEFAULT_AUTHORITY, mutationLock, fence) {
1820
1869
  this.root = root;
1821
1870
  this.targetLocks = targetLocksFor(root);
1871
+ this.rootGate = rootGateFor(root);
1822
1872
  this.io = io;
1823
1873
  this.limits = limits;
1824
1874
  this.onMutation = onMutation;
@@ -1841,7 +1891,7 @@ var SkillLibrary = class {
1841
1891
  }
1842
1892
  /**
1843
1893
  * Transitional root lock for mutators that still own their write path. The
1844
- * extract/restructure path takes the same lock through MutationUnit, so those
1894
+ * extract/restructure path takes the same lock through UnitKernel, so those
1845
1895
  * two paths cannot interleave with create/update/patch across processes.
1846
1896
  */
1847
1897
  unitHeadForOps(ops, roots, provenance = /* @__PURE__ */ new Map()) {
@@ -1899,7 +1949,7 @@ var SkillLibrary = class {
1899
1949
  async canonicalTargetKey(targetKey) {
1900
1950
  if (!targetKey.startsWith("skill::")) return targetKey;
1901
1951
  try {
1902
- await realpath(this.root);
1952
+ realpathSync.native(this.root);
1903
1953
  } catch {
1904
1954
  return targetKey;
1905
1955
  }
@@ -1912,7 +1962,7 @@ var SkillLibrary = class {
1912
1962
  const suffix = [];
1913
1963
  let identity;
1914
1964
  while (true) try {
1915
- identity = join(await realpath(cursor), ...suffix.reverse());
1965
+ identity = join(realpathSync.native(cursor), ...suffix.reverse());
1916
1966
  break;
1917
1967
  } catch {
1918
1968
  const parent = dirname(cursor);
@@ -1931,9 +1981,32 @@ var SkillLibrary = class {
1931
1981
  await lease.release();
1932
1982
  }
1933
1983
  }
1934
- /** 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. */
1935
1985
  commitUnit(options) {
1936
- 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({
1937
2010
  io: this.io,
1938
2011
  journal: unitJournalPort(this.io, dirname(this.root)),
1939
2012
  snapshots: unitSnapshotPort(this.io, dirname(this.root)),
@@ -1996,7 +2069,10 @@ var SkillLibrary = class {
1996
2069
  recovery;
1997
2070
  /** Run the boot recovery once per library instance, before the first write. */
1998
2071
  async ensureRecovered() {
1999
- 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) => {
2000
2076
  console.warn("skill-store: prepared-unit recovery failed; writes continue: " + (error instanceof Error ? error.message : String(error)));
2001
2077
  });
2002
2078
  await this.recovery;
@@ -2524,7 +2600,14 @@ var SkillLibrary = class {
2524
2600
  async audit(skillName, action, before, after, summary, path, unitId, unitHead, origin, fenceHeld = false, change) {
2525
2601
  const fence = fenceHeld ? void 0 : this.fence;
2526
2602
  const at = (/* @__PURE__ */ new Date()).toISOString();
2527
- 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) : (() => {
2528
2611
  const normalized = normalizeChangeSummary(change.text, 50);
2529
2612
  return normalized.ok ? {
2530
2613
  text: normalized.text,
@@ -2834,12 +2917,14 @@ var SkillLibrary = class {
2834
2917
  };
2835
2918
  }
2836
2919
  }
2837
- await this.audit(normalized, "create", null, onDisk, "created", void 0, result.unitId, options.unitHead, void 0, fenceHeld);
2838
- this.notifyMutation({
2839
- action: "create",
2840
- name: normalized,
2841
- skillDir: dir
2842
- });
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
+ }
2843
2928
  const warnings = [createDurabilityWarning !== "" ? `写入已落盘,但目录 fsync 失败 —— 持久性未确认:${createDurabilityWarning}` : "", markerWarning].filter((warning) => warning !== "");
2844
2929
  return {
2845
2930
  ok: true,
@@ -4910,12 +4995,8 @@ var SkillLibrary = class {
4910
4995
  message: "skill write plan is empty",
4911
4996
  outcomes: []
4912
4997
  };
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);
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));
4919
5000
  const target = op.kind === "createSkill" ? skillBodyTarget(op.skill) : op.target;
4920
5001
  const outcomes = result.ok && result.after !== void 0 ? [{
4921
5002
  op,
@@ -4933,6 +5014,138 @@ var SkillLibrary = class {
4933
5014
  ...result.normalizedFrontmatterFields === void 0 ? {} : { normalizedFrontmatterFields: result.normalizedFrontmatterFields }
4934
5015
  };
4935
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
+ }
4936
5149
  async applyOne(op, origin) {
4937
5150
  switch (op.kind) {
4938
5151
  case "createSkill": return await this.create(op.skill, op.content, origin, op.managed === true ? { managed: true } : {});
@@ -4972,7 +5185,7 @@ var SkillLibrary = class {
4972
5185
  message: badName
4973
5186
  };
4974
5187
  const dir = this.dirOf(name);
4975
- 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 {
4976
5189
  ok: false,
4977
5190
  message: `技能「${name}」不存在。`
4978
5191
  };
@@ -5113,6 +5326,24 @@ var SkillLibrary = class {
5113
5326
  const before = beforeProbe.value;
5114
5327
  let verdict = anchorVerdict(anchor, before);
5115
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
+ }
5116
5347
  if (verdict === "match" && this.transact) {
5117
5348
  const ran = { done: false };
5118
5349
  try {
@@ -5550,4 +5781,4 @@ function newSkillLibrary(options) {
5550
5781
  } : void 0, transact, [...threatExemptLabels ?? []], authority, options.mutationLock ?? mutationLockFrom(ctx), options.fence ?? ctx?.get?.("evolutionMutationAuthority")?.homeFence);
5551
5782
  }
5552
5783
  //#endregion
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 };
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 };