@lmzhen/dsh-evolution-core 0.46.0 → 0.48.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 (101) hide show
  1. package/lib/authority-plugin.js +1 -1
  2. package/lib/composition/index.js +3 -3
  3. package/lib/{composition-Da8NfRI7.js → composition-Cqjbho0t.js} +1 -1
  4. package/lib/{ensure-C5Mo1dbB.js → ensure-CAjLGd9f.js} +1 -2
  5. package/lib/http-routes.js +21 -96
  6. package/lib/index.js +47 -246
  7. package/lib/{io-AmUf4lVY.js → io-GxghO3Ip.js} +30 -70
  8. package/lib/io-node.js +1 -1
  9. package/lib/io-registry.js +1 -35
  10. package/lib/{mutation-authority-DeJ_Wz14.js → mutation-authority-l57R626O.js} +17 -15
  11. package/lib/{mutations-DwvbjRHF.js → mutations-DQXddSJd.js} +1 -1
  12. package/lib/{numeric-DLeLvvGb.js → numeric-D8js3sqC.js} +1 -5
  13. package/lib/platform/index.js +1 -1
  14. package/lib/{platform-CFA12Jam.js → platform-Cc9cNt5j.js} +4 -28
  15. package/lib/policy.js +1 -1
  16. package/lib/runtime/plugin.js +21 -43
  17. package/lib/{session-projection-EB7mUOlJ.js → session-projection-DSXnUNZG.js} +3 -21
  18. package/lib/{skill-health-D1pZGk5V.js → skill-health-DP8z9TPf.js} +4 -25
  19. package/lib/{skill-history-CjypdYqv.js → skill-history-CxrDE3Rb.js} +54 -102
  20. package/lib/skills.js +166 -184
  21. package/lib/subagent/index.js +4 -10
  22. package/lib/types/authority.d.ts +2 -0
  23. package/lib/types/authority.js +5 -0
  24. package/lib/types/composition/preset-ids.d.ts +0 -1
  25. package/lib/types/composition/preset-ids.js +0 -1
  26. package/lib/types/constants.d.ts +0 -4
  27. package/lib/types/constants.js +0 -4
  28. package/lib/types/contract.d.ts +0 -5
  29. package/lib/types/curator.d.ts +0 -1
  30. package/lib/types/curator.js +0 -1
  31. package/lib/types/document-body.d.ts +0 -12
  32. package/lib/types/document-body.js +0 -14
  33. package/lib/types/health-baseline.d.ts +0 -13
  34. package/lib/types/health-baseline.js +0 -20
  35. package/lib/types/home-fence.d.ts +2 -0
  36. package/lib/types/home-fence.js +11 -1
  37. package/lib/types/http-routes.d.ts +9 -4
  38. package/lib/types/http-routes.js +36 -116
  39. package/lib/types/index.d.ts +0 -3
  40. package/lib/types/index.js +0 -3
  41. package/lib/types/io-registry.d.ts +0 -16
  42. package/lib/types/io-registry.js +0 -27
  43. package/lib/types/io.d.ts +6 -54
  44. package/lib/types/io.js +35 -65
  45. package/lib/types/journal-protocol.d.ts +0 -15
  46. package/lib/types/journal-protocol.js +1 -19
  47. package/lib/types/lease-store.d.ts +1 -1
  48. package/lib/types/lease-store.js +4 -15
  49. package/lib/types/live.d.ts +0 -12
  50. package/lib/types/live.js +0 -18
  51. package/lib/types/memory-store.d.ts +0 -1
  52. package/lib/types/memory-store.js +13 -6
  53. package/lib/types/mutation-authority.js +5 -0
  54. package/lib/types/mutation-unit.d.ts +1 -1
  55. package/lib/types/mutation-unit.js +14 -31
  56. package/lib/types/params.d.ts +11 -29
  57. package/lib/types/params.js +13 -60
  58. package/lib/types/platform/llm.d.ts +2 -3
  59. package/lib/types/platform/llm.js +3 -10
  60. package/lib/types/platform/projections.d.ts +4 -5
  61. package/lib/types/platform/projections.js +4 -18
  62. package/lib/types/probe.d.ts +0 -3
  63. package/lib/types/probe.js +0 -7
  64. package/lib/types/run-registry.js +10 -12
  65. package/lib/types/runtime/llm.js +2 -2
  66. package/lib/types/runtime/platform.d.ts +7 -11
  67. package/lib/types/runtime/platform.js +13 -19
  68. package/lib/types/runtime/plugin.d.ts +1 -1
  69. package/lib/types/runtime/plugin.js +6 -4
  70. package/lib/types/runtime/projections.js +1 -2
  71. package/lib/types/session-fold.d.ts +0 -8
  72. package/lib/types/session-fold.js +0 -5
  73. package/lib/types/session-projection.js +2 -2
  74. package/lib/types/skill-discovery.d.ts +0 -2
  75. package/lib/types/skill-discovery.js +1 -2
  76. package/lib/types/skill-health.d.ts +29 -1
  77. package/lib/types/skill-history.d.ts +0 -24
  78. package/lib/types/skill-history.js +0 -41
  79. package/lib/types/skill-lint.d.ts +0 -3
  80. package/lib/types/skill-lint.js +0 -12
  81. package/lib/types/skill-store.d.ts +6 -0
  82. package/lib/types/skill-store.js +130 -142
  83. package/lib/types/subagent/readiness.d.ts +0 -1
  84. package/lib/types/subagent/readiness.js +2 -8
  85. package/lib/types/tool-dispatch.d.ts +1 -16
  86. package/lib/types/tool-dispatch.js +0 -18
  87. package/lib/types/unit-journal.d.ts +1 -1
  88. package/lib/types/unit-journal.js +20 -15
  89. package/lib/types/unit-storage.d.ts +1 -1
  90. package/lib/types/unit-storage.js +5 -16
  91. package/lib/types/write-inventory.d.ts +0 -4
  92. package/lib/types/write-inventory.js +0 -9
  93. package/lib/types/write-kernel.d.ts +3 -4
  94. package/lib/types/write-kernel.js +13 -25
  95. package/lib/write.js +2 -2
  96. package/package.json +1 -1
  97. package/persisted-write-inventory.json +72 -9
  98. package/lib/types/fold-untrusted.d.ts +0 -35
  99. package/lib/types/fold-untrusted.js +0 -44
  100. package/lib/types/unit-recovery.d.ts +0 -5
  101. package/lib/types/unit-recovery.js +0 -12
@@ -38,7 +38,7 @@ import { resolveCitations } from "./citations.js";
38
38
  import { scanContentThreats } from "./threats.js";
39
39
  import { isReviewChannelSession } from "./review-channel.js";
40
40
  import { currentReviewContext } from "./review-context.js";
41
- import { isCommittedWarning, nodeEvolutionIo, transactIo } from "./io.js";
41
+ import { isCommittedWarning, nodeEvolutionIo, TransactionNotInvokedError, transactIo } from "./io.js";
42
42
  import { appendEvolutionEvent, eventsFile } from "./evolution-events.js";
43
43
  import { isAbsent, isPresent, isUnknown, probeAbsent, probeList, probeMtime, probePresent, probeReason, probeText, probeUnknown } from "./probe.js";
44
44
  import { evolutionRoot } from "./state-store.js";
@@ -494,18 +494,11 @@ export class SkillLibrary {
494
494
  this.authority = authority;
495
495
  this.mutationLock = mutationLock;
496
496
  this.fence = fence;
497
- // V4-20: bind the IO backend's own transact by default. Explicit injection
498
- // stays first; a backend WITHOUT transact keeps the old plain read→write
499
- // (the in-process serial chain is the second layer). The wrapper adapts the
500
- // backend's `(path, task)` instance signature to the standard `(io, path,
501
- // task)` form the rest of the core expects, guarding the optional method
502
- // rather than asserting it.
503
- this.transact = transact ?? (io.transact
504
- ? (ioLike, path, task) => {
505
- const t = ioLike.transact;
506
- return t ? t(path, task) : transactIo(ioLike, path, task);
507
- }
508
- : undefined);
497
+ // V4-20: bind the ONE transaction seam by default. Explicit injection stays
498
+ // first; a backend without transact keeps the plain read→write (the
499
+ // in-process serial chain is the second layer). transactIo owns the backend
500
+ // signature adaptation, the typed not-invoked error and committed warnings.
501
+ this.transact = transact ?? (io.transact ? transactIo : undefined);
509
502
  // G1/1.4 (S2-02): the queue is per ROOT and shared by every instance (see ROOT_SERIAL above); a
510
503
  // per-instance queue ordered nothing across the six services that write this tree.
511
504
  this.serial = serialForRoot(this.root);
@@ -556,6 +549,44 @@ export class SkillLibrary {
556
549
  await lease.release();
557
550
  }
558
551
  }
552
+ /** The one MutationUnit constructor: storage ports are fixed here, callers pass the rest. */
553
+ commitUnit(options) {
554
+ return new MutationUnit({
555
+ io: this.io,
556
+ journal: unitJournalPort(this.io, dirname(this.root)),
557
+ snapshots: unitSnapshotPort(this.io, dirname(this.root)),
558
+ ...options,
559
+ });
560
+ }
561
+ /** The one frontmatter pipeline for create/update/patch; patch keeps its cap checks outside. */
562
+ prepareBody(content, name, current, mode) {
563
+ const validation = validateFrontmatter(content, name, this.limits, current ?? undefined);
564
+ if (validation)
565
+ return { ok: false, message: validation, validation: true };
566
+ const norm = normalizeFrontmatter(content);
567
+ if (norm.issues.length > 0) {
568
+ const issue = norm.issues[0];
569
+ return {
570
+ ok: false,
571
+ message: mode === 'skill'
572
+ ? `技能「${name}」的 frontmatter 无法自动修复:${issue}:请用双引号包住取值后重试。`
573
+ : `frontmatter 无法自动修复(${issue})。`,
574
+ validation: false,
575
+ };
576
+ }
577
+ const body = norm.changed ? norm.content : content;
578
+ if (norm.changed) {
579
+ const revalidated = validateFrontmatter(body, name, this.limits, current ?? undefined);
580
+ if (revalidated)
581
+ return { ok: false, message: revalidated, validation: false };
582
+ }
583
+ if (mode === 'skill') {
584
+ const threat = this.contentThreatBlock(body);
585
+ if (threat)
586
+ return { ok: false, message: threat, validation: false };
587
+ }
588
+ return { ok: true, body, onDisk: body.trimEnd() + '\n', norm };
589
+ }
559
590
  lockPort() {
560
591
  if (this.mutationLock !== undefined)
561
592
  return this.mutationLock;
@@ -579,13 +610,10 @@ export class SkillLibrary {
579
610
  /** Recover every prepared tree-change snapshot in the shared unit store. */
580
611
  async recoverPreparedUnits() {
581
612
  const home = dirname(this.root);
582
- const unit = new MutationUnit({
583
- io: this.io,
613
+ const unit = this.commitUnit({
584
614
  limits: { maxSkillFileBytes: this.limits.maxSkillFileBytes, maxSkillContentChars: this.limits.maxSkillContentChars },
585
615
  serial: this.serial,
586
616
  lock: this.lockPort(),
587
- journal: unitJournalPort(this.io, home),
588
- snapshots: unitSnapshotPort(this.io, home),
589
617
  });
590
618
  const results = await unit.recoverPrepared();
591
619
  await pruneTreeChangeUnits(this.io, home).catch(() => { });
@@ -1175,7 +1203,7 @@ export class SkillLibrary {
1175
1203
  }
1176
1204
  }
1177
1205
  /** S2: mechanical hard-cap event; failure must not change the refusal. */
1178
- async recordHardCapHit(name, bodyChars, source, supportFiles = null) {
1206
+ async recordHardCapHit(name, bodyChars, source, supportFiles = null, fenceHeld = false) {
1179
1207
  try {
1180
1208
  await appendEvolutionEvent(this.io, eventsFile(dirname(this.root)), {
1181
1209
  type: 'hard-cap',
@@ -1184,7 +1212,7 @@ export class SkillLibrary {
1184
1212
  supportFiles,
1185
1213
  restructureRounds: 0,
1186
1214
  source,
1187
- }, undefined, this.fence);
1215
+ }, undefined, fenceHeld ? undefined : this.fence);
1188
1216
  }
1189
1217
  catch (error) {
1190
1218
  console.warn('skill-store: hard-cap event not recorded for "' + name + '": ' + (error instanceof Error ? error.message : String(error)));
@@ -1205,7 +1233,10 @@ export class SkillLibrary {
1205
1233
  // migration step). Optional so existing callers keep their behaviour; the ledger stores it when
1206
1234
  // given, and old records without it stay readable.
1207
1235
  // G3a: one tree change writes N paths under ONE unit id; the entries it writes share it.
1208
- unitId, unitHead, origin) {
1236
+ unitId, unitHead, origin, fenceHeld = false) {
1237
+ // A committed hook or outer tree operation already holds the home fence.
1238
+ // Keep per-file transactions, but do not queue behind our own lease.
1239
+ const fence = fenceHeld ? undefined : this.fence;
1209
1240
  const at = new Date().toISOString();
1210
1241
  let versions = null;
1211
1242
  try {
@@ -1221,7 +1252,7 @@ export class SkillLibrary {
1221
1252
  ...unitId === undefined ? {} : { unitId },
1222
1253
  ...unitHead === undefined ? {} : { unitHead },
1223
1254
  };
1224
- versions = await recordVersions(this.root, this.io, input, keep, this.fence);
1255
+ versions = await recordVersions(this.root, this.io, input, keep, fence);
1225
1256
  }
1226
1257
  catch (error) {
1227
1258
  if (!this.historyWarned) {
@@ -1266,7 +1297,7 @@ export class SkillLibrary {
1266
1297
  summary: summary + healthNote + danglingNote,
1267
1298
  at,
1268
1299
  ...origin === undefined ? {} : { origin },
1269
- }, undefined, this.fence);
1300
+ }, undefined, fence);
1270
1301
  }
1271
1302
  catch {
1272
1303
  // Auditing is best-effort; a transient disk failure must not surface
@@ -1458,34 +1489,20 @@ export class SkillLibrary {
1458
1489
  // serialize queue (F-208 discipline, like update/patch) — two concurrent
1459
1490
  // create calls for one name used to both pass exists() and double-write
1460
1491
  // (double audit, double mutation event).
1461
- return await this.serial(() => this.withMutationLock(() => this.createCore(normalized, content, origin, options)));
1492
+ return await this.serial(() => this.withMutationLock(() => this.createCore(normalized, content, origin, options, true)));
1462
1493
  }
1463
- async createCore(normalized, content, origin, options = {}) {
1494
+ async createCore(normalized, content, origin, options = {}, fenceHeld = false) {
1464
1495
  // C-12 (v10 audit): the inline badName() copy is gone (see setPinned).
1465
1496
  const bad = this.badName(normalized);
1466
1497
  if (bad)
1467
1498
  return { ok: false, message: bad };
1468
- const validation = validateFrontmatter(content, normalized, this.limits);
1469
- if (validation) {
1470
- if (exceedsContentLimit(content, this.limits.maxSkillContentChars))
1471
- await this.recordHardCapHit(normalized, content.length, 'create');
1472
- return { ok: false, message: validation };
1473
- }
1474
- // 0.3.11: frontmatter normalization happens at the write point — the
1475
- // platform catalog parses strict YAML, so unquoted plain scalars carrying
1476
- // `: ` (etc.) would silently make the skill invisible to the platform.
1477
- const norm = normalizeFrontmatter(content);
1478
- if (norm.issues.length > 0)
1479
- return { ok: false, message: `技能「${normalized}」的 frontmatter 无法自动修复:${norm.issues[0]}:请用双引号包住取值后重试。` };
1480
- const finalContent = norm.changed ? norm.content : content;
1481
- if (norm.changed) {
1482
- const revalidated = validateFrontmatter(finalContent, normalized, this.limits);
1483
- if (revalidated)
1484
- return { ok: false, message: revalidated };
1499
+ const prepared = this.prepareBody(content, normalized, null, 'skill');
1500
+ if (!prepared.ok) {
1501
+ if (prepared.validation && exceedsContentLimit(content, this.limits.maxSkillContentChars))
1502
+ await this.recordHardCapHit(normalized, content.length, 'create', null, fenceHeld);
1503
+ return { ok: false, message: prepared.message };
1485
1504
  }
1486
- const threat = this.contentThreatBlock(finalContent);
1487
- if (threat)
1488
- return { ok: false, message: threat };
1505
+ const { onDisk, norm } = prepared;
1489
1506
  const dir = this.dirOf(normalized);
1490
1507
  if (await this.io.exists(join(dir, 'SKILL.md')))
1491
1508
  return { ok: false, message: `技能「${normalized}」已存在。` };
@@ -1525,21 +1542,15 @@ export class SkillLibrary {
1525
1542
  const protection = await this.writeProtection(normalized, origin);
1526
1543
  if (protection)
1527
1544
  return { ok: false, message: `技能「${normalized}」受保护(${protection})。` };
1528
- // F-337: hash the bytes that actually land on disk (write uses
1529
- // trimEnd()+'\n'), so the audit afterHash is replay-identical to the file.
1530
- const onDisk = finalContent.trimEnd() + '\n';
1531
1545
  const createPath = join(dir, 'SKILL.md');
1532
1546
  // P3 (v17): the already-exists refusal moves INSIDE the cross-process
1533
1547
  // transact — the lock-free probe above could be raced by a concurrent
1534
1548
  // create on another instance/process, and the later write silently
1535
1549
  // overwrote the winner's bytes (double audit, double event). In-lock
1536
1550
  // re-check: current bytes present -> structured refusal, nothing written.
1537
- const unit = new MutationUnit({
1538
- io: this.io,
1551
+ const unit = this.commitUnit({
1539
1552
  limits: { maxSkillFileBytes: Number.MAX_SAFE_INTEGER, maxSkillContentChars: Number.MAX_SAFE_INTEGER },
1540
1553
  nested: true,
1541
- journal: unitJournalPort(this.io, dirname(this.root)),
1542
- snapshots: unitSnapshotPort(this.io, dirname(this.root)),
1543
1554
  transactGuard: false,
1544
1555
  hooks: {
1545
1556
  undone: async () => {
@@ -1610,7 +1621,7 @@ export class SkillLibrary {
1610
1621
  return { ok: false, message: `创建过程中技能「${normalized}」被并发归档;残留标记已移除:等搬运完成后重试一次。` };
1611
1622
  }
1612
1623
  }
1613
- await this.audit(normalized, 'create', null, onDisk, 'created', undefined, result.unitId, options.unitHead);
1624
+ await this.audit(normalized, 'create', null, onDisk, 'created', undefined, result.unitId, options.unitHead, undefined, fenceHeld);
1614
1625
  this.notifyMutation({ action: 'create', name: normalized, skillDir: dir });
1615
1626
  // Both warnings ride the normal success path (audit/event included) — a
1616
1627
  // durability warning must never skip the accounting.
@@ -1654,25 +1665,12 @@ export class SkillLibrary {
1654
1665
  if (isUnknown(limitProbe))
1655
1666
  console.warn(`skill-store: could not re-read ${path} for the shrink exemption (${limitProbe.reason}); validating without it — an over-limit repair is refused, not accepted`);
1656
1667
  const currentForLimit = isPresent(limitProbe) ? limitProbe.value : null;
1657
- const validation = validateFrontmatter(content, name, this.limits, currentForLimit);
1658
- if (validation) {
1659
- if (exceedsContentLimit(content, this.limits.maxSkillContentChars))
1668
+ const prepared = this.prepareBody(content, name, currentForLimit, 'skill');
1669
+ if (!prepared.ok) {
1670
+ if (prepared.validation && exceedsContentLimit(content, this.limits.maxSkillContentChars))
1660
1671
  await this.recordHardCapHit(name, content.length, 'update');
1661
- return { ok: false, message: validation };
1662
- }
1663
- // 0.3.11: normalize at the write point (see create) — same reasoning.
1664
- const norm = normalizeFrontmatter(content);
1665
- if (norm.issues.length > 0)
1666
- return { ok: false, message: `技能「${name}」的 frontmatter 无法自动修复:${norm.issues[0]}:请用双引号包住取值后重试。` };
1667
- const finalContent = norm.changed ? norm.content : content;
1668
- if (norm.changed) {
1669
- const revalidated = validateFrontmatter(finalContent, name, this.limits, currentForLimit);
1670
- if (revalidated)
1671
- return { ok: false, message: revalidated };
1672
+ return { ok: false, message: prepared.message };
1672
1673
  }
1673
- const threat = this.contentThreatBlock(finalContent);
1674
- if (threat)
1675
- return { ok: false, message: threat };
1676
1674
  let current;
1677
1675
  try {
1678
1676
  current = await this.io.readText(path);
@@ -1687,23 +1685,20 @@ export class SkillLibrary {
1687
1685
  await this.cleanupGhostDir(path);
1688
1686
  return { ok: false, message: `技能「${name}」不存在。` };
1689
1687
  }
1690
- if (finalContent.trimEnd() === current.trimEnd()) {
1688
+ if (prepared.body.trimEnd() === current.trimEnd()) {
1691
1689
  return { ok: true, message: `技能「${name}」未变更:提供的内容与当前文件一致,未写入。`, noop: true, path: dir };
1692
1690
  }
1693
- const onDisk = finalContent.trimEnd() + '\n';
1694
- const unit = new MutationUnit({
1695
- io: this.io,
1691
+ const onDisk = prepared.onDisk;
1692
+ const unit = this.commitUnit({
1696
1693
  limits: { maxSkillFileBytes: Number.MAX_SAFE_INTEGER, maxSkillContentChars: Number.MAX_SAFE_INTEGER },
1697
1694
  lock: this.lockPort(),
1698
- journal: unitJournalPort(this.io, dirname(this.root)),
1699
- snapshots: unitSnapshotPort(this.io, dirname(this.root)),
1700
1695
  ...(this.transact === undefined ? {} : { transact: this.transact }),
1701
1696
  hooks: {
1702
1697
  committed: async (event) => {
1703
1698
  const op = event.ops[0];
1704
1699
  if (op === undefined)
1705
1700
  return;
1706
- await this.audit(name, 'update', op.before, op.after, 'updated', undefined, event.unitId, { sources: [{ skill: name }] }, origin);
1701
+ await this.audit(name, 'update', op.before, op.after, 'updated', undefined, event.unitId, { sources: [{ skill: name }] }, origin, true);
1707
1702
  this.notifyMutation({ action: 'update', name, skillDir: dir });
1708
1703
  },
1709
1704
  },
@@ -1721,13 +1716,13 @@ export class SkillLibrary {
1721
1716
  });
1722
1717
  if (!result.ok) {
1723
1718
  const messages = result.errors.map(error => error.message);
1724
- if (messages.some(message => message.includes('mutation-lock-transact-not-run') || message.includes('did not invoke the task')))
1719
+ if (result.errors.some(error => error.code === 'transact-not-invoked'))
1725
1720
  return { ok: false, message: '内部错误:写事务没有调用任务;未执行任何写入' };
1726
1721
  return { ok: false, message: messages.join(';') };
1727
1722
  }
1728
1723
  const warning = result.warnings === undefined || result.warnings.length === 0 ? '' : ` (警告:写入已落盘,但目录 fsync 失败 —— 持久性未确认:${result.warnings.join(';')})`;
1729
1724
  const retention = contentRetentionFeedback({ name, action: 'update', before: current, after: onDisk });
1730
- return { ok: true, message: `技能「${name}」已更新。${warning}${retention === null ? '' : '\n' + retention}`, path: dir, ...(norm.changed ? { normalizedFrontmatterFields: norm.fields } : {}) };
1725
+ return { ok: true, message: `技能「${name}」已更新。${warning}${retention === null ? '' : '\n' + retention}`, path: dir, ...(prepared.norm.changed ? { normalizedFrontmatterFields: prepared.norm.fields } : {}) };
1731
1726
  }
1732
1727
  async patch(rawName, oldString, newString, filePath = '', replaceAll = false, origin = this.authority.origin) {
1733
1728
  await this.ensureRecovered();
@@ -1794,21 +1789,12 @@ export class SkillLibrary {
1794
1789
  let writeContent = patched;
1795
1790
  let normalizedFields;
1796
1791
  if (target === skillMd) {
1797
- const validation = validateFrontmatter(patched, name, this.limits, md);
1798
- if (validation)
1799
- return { result: { ok: false, message: `补丁被拒绝:${validation}` }, write: null };
1800
- // 0.3.11: normalize at the write point (see create) — a patch may edit
1801
- // the frontmatter directly.
1802
- const norm = normalizeFrontmatter(patched);
1803
- if (norm.issues.length > 0)
1804
- return { result: { ok: false, message: `补丁被拒绝:frontmatter 无法自动修复(${norm.issues[0]})。` }, write: null };
1805
- if (norm.changed) {
1806
- writeContent = norm.content;
1807
- normalizedFields = norm.fields;
1808
- const revalidated = validateFrontmatter(writeContent, name, this.limits, md);
1809
- if (revalidated)
1810
- return { result: { ok: false, message: `补丁被拒绝:${revalidated}` }, write: null };
1811
- }
1792
+ const prepared = this.prepareBody(patched, name, md, 'patch');
1793
+ if (!prepared.ok)
1794
+ return { result: { ok: false, message: `补丁被拒绝:${prepared.message}` }, write: null };
1795
+ writeContent = prepared.body;
1796
+ if (prepared.norm.changed)
1797
+ normalizedFields = prepared.norm.fields;
1812
1798
  }
1813
1799
  if (Buffer.byteLength(writeContent, 'utf8') > this.limits.maxSkillFileBytes && target !== skillMd) {
1814
1800
  return { result: { ok: false, message: `修补后的文件超过 ${this.limits.maxSkillFileBytes} 字节。` }, write: null };
@@ -1869,16 +1855,13 @@ export class SkillLibrary {
1869
1855
  return outcome.result;
1870
1856
  }
1871
1857
  const onDisk = outcome.write;
1872
- const unit = new MutationUnit({
1873
- io: this.io,
1858
+ const unit = this.commitUnit({
1874
1859
  limits: { maxSkillFileBytes: Number.MAX_SAFE_INTEGER, maxSkillContentChars: Number.MAX_SAFE_INTEGER },
1875
1860
  lock: this.lockPort(),
1876
- journal: unitJournalPort(this.io, dirname(this.root)),
1877
- snapshots: unitSnapshotPort(this.io, dirname(this.root)),
1878
1861
  ...(this.transact === undefined ? {} : { transact: this.transact }),
1879
1862
  hooks: {
1880
1863
  committed: async (event) => {
1881
- await this.audit(name, 'patch', outcome.audit?.before ?? current, event.ops[0]?.after ?? onDisk, outcome.audit?.summary ?? `patched ${patchLabel}`, filePath === '' ? undefined : filePath, event.unitId, { sources: [{ skill: name }] }, origin);
1864
+ await this.audit(name, 'patch', outcome.audit?.before ?? current, event.ops[0]?.after ?? onDisk, outcome.audit?.summary ?? `patched ${patchLabel}`, filePath === '' ? undefined : filePath, event.unitId, { sources: [{ skill: name }] }, origin, true);
1882
1865
  this.notifyMutation({ action: 'patch', name, skillDir: dir });
1883
1866
  },
1884
1867
  },
@@ -1896,7 +1879,7 @@ export class SkillLibrary {
1896
1879
  });
1897
1880
  if (!result.ok) {
1898
1881
  const messages = result.errors.map(error => error.message);
1899
- if (messages.some(message => message.includes('mutation-lock-transact-not-run') || message.includes('did not invoke the task')))
1882
+ if (result.errors.some(error => error.code === 'transact-not-invoked'))
1900
1883
  return { ok: false, message: '内部错误:写事务没有调用任务;未执行任何写入' };
1901
1884
  return { ok: false, message: messages.join(';') };
1902
1885
  }
@@ -2005,6 +1988,9 @@ export class SkillLibrary {
2005
1988
  catch { /* lifecycle telemetry is best-effort; the archive already landed */ }
2006
1989
  }
2007
1990
  async archive(rawName, options = {}, origin = this.authority.origin) {
1991
+ return await this.archiveCore(rawName, options, origin, false);
1992
+ }
1993
+ async archiveCore(rawName, options, origin, fenceHeld) {
2008
1994
  // One trim per entry: paths (dirOf), validation and messages all see the same name.
2009
1995
  const name = rawName.trim();
2010
1996
  const badName = this.badName(name, { allowReserved: true });
@@ -2118,7 +2104,7 @@ export class SkillLibrary {
2118
2104
  catch {
2119
2105
  // Same posture as .archive-reason: metadata only, never abort the archive.
2120
2106
  }
2121
- await this.audit(name, 'archive', md, null, reason, undefined, options.unitId, options.unitHead, origin);
2107
+ await this.audit(name, 'archive', md, null, reason, undefined, options.unitId, options.unitHead, origin, fenceHeld);
2122
2108
  this.notifyMutation({ action: 'archive', name, archivedPath: dest });
2123
2109
  return { ok: true, message: `技能「${name}」已归档到 .archive。`, path: dest };
2124
2110
  }
@@ -2150,6 +2136,12 @@ export class SkillLibrary {
2150
2136
  return { ok: false, message: `来源技能「${protectedSource}」是受保护的内置技能。` };
2151
2137
  const limits = plan.limits ?? this.limits;
2152
2138
  const run = async () => {
2139
+ // A nested merge already holds the home fence; its archive/restore bookkeeping
2140
+ // must run inline instead of queueing behind that same lease.
2141
+ const fenceHeld = plan.nested === true;
2142
+ const archive = (name, archiveOptions) => fenceHeld
2143
+ ? this.archiveCore(name, archiveOptions, plan.origin, true)
2144
+ : this.archive(name, archiveOptions, plan.origin);
2153
2145
  const dir = this.dirOf(target);
2154
2146
  const targetPath = join(dir, 'SKILL.md');
2155
2147
  if (!plan.targetExists && await this.io.exists(dir)) {
@@ -2269,7 +2261,7 @@ export class SkillLibrary {
2269
2261
  const stuck = [];
2270
2262
  for (const source of [...archived].reverse()) {
2271
2263
  try {
2272
- const restored = await this.restoreFromArchive(source, plan.origin);
2264
+ const restored = fenceHeld ? await this.restoreFromArchiveCore(source, plan.origin, true) : await this.restoreFromArchive(source, plan.origin);
2273
2265
  if (!restored.ok)
2274
2266
  stuck.push(source);
2275
2267
  }
@@ -2370,12 +2362,12 @@ export class SkillLibrary {
2370
2362
  return { ok: false, message: 'tree fence lost before source archive; recovery required' };
2371
2363
  }
2372
2364
  await plan.onPhase?.('source-archiving', { source });
2373
- const archivedResult = await this.archive(source, {
2365
+ const archivedResult = await archive(source, {
2374
2366
  absorbedInto: target,
2375
2367
  unitId,
2376
2368
  unitHead: { skill: target },
2377
2369
  reason: `Merged into ${target}`,
2378
- }, plan.origin);
2370
+ });
2379
2371
  if (!archivedResult.ok) {
2380
2372
  const stuck = await rollbackSources();
2381
2373
  stuck.push(...await rollbackTarget());
@@ -2391,19 +2383,19 @@ export class SkillLibrary {
2391
2383
  await plan.onPhase?.('target-pending');
2392
2384
  if (plan.assertFence !== undefined && !(await plan.assertFence()))
2393
2385
  return { ok: false, message: 'tree fence lost before target write' };
2394
- const created = await this.createCore(target, plan.body, plan.origin, { unitId, unitHead, managed: true });
2386
+ const created = await this.createCore(target, plan.body, plan.origin, { unitId, unitHead, managed: true }, fenceHeld);
2395
2387
  if (!created.ok)
2396
2388
  return { ok: false, message: created.message };
2397
2389
  await plan.onPhase?.('target-applied');
2398
2390
  await plan.onPhase?.('target-written');
2399
2391
  if (plan.signal?.aborted) {
2400
- const targetRollback = await this.archive(target, { reason: 'merge cancelled' }, plan.origin);
2392
+ const targetRollback = await archive(target, { reason: 'merge cancelled' });
2401
2393
  return rollbackMessage('cancelled before sources archived', targetRollback.ok ? [] : [target]);
2402
2394
  }
2403
2395
  for (const source of sources) {
2404
2396
  if (plan.signal?.aborted) {
2405
2397
  const stuck = await rollbackSources();
2406
- const targetRollback = await this.archive(target, { reason: 'merge cancelled' }, plan.origin);
2398
+ const targetRollback = await archive(target, { reason: 'merge cancelled' });
2407
2399
  if (!targetRollback.ok)
2408
2400
  stuck.push(target);
2409
2401
  return rollbackMessage('cancelled before next source archive', stuck);
@@ -2411,7 +2403,7 @@ export class SkillLibrary {
2411
2403
  const fresh = await this.io.readText(join(this.dirOf(source), 'SKILL.md'));
2412
2404
  if (fresh !== sourceBodies.get(source)) {
2413
2405
  const stuck = await rollbackSources();
2414
- const targetRollback = await this.archive(target, { reason: 'merge rolled back' }, plan.origin);
2406
+ const targetRollback = await archive(target, { reason: 'merge rolled back' });
2415
2407
  if (!targetRollback.ok)
2416
2408
  stuck.push(target);
2417
2409
  return rollbackMessage(`来源技能「${source}」在归档前被改过`, stuck);
@@ -2420,15 +2412,15 @@ export class SkillLibrary {
2420
2412
  return { ok: false, message: 'tree fence lost before source archive; recovery required' };
2421
2413
  }
2422
2414
  await plan.onPhase?.('source-archiving', { source });
2423
- const result = await this.archive(source, {
2415
+ const result = await archive(source, {
2424
2416
  absorbedInto: target,
2425
2417
  unitId,
2426
2418
  unitHead: { skill: target },
2427
2419
  reason: `Merged into ${target}`,
2428
- }, plan.origin);
2420
+ });
2429
2421
  if (!result.ok) {
2430
2422
  const stuck = await rollbackSources();
2431
- const targetRollback = await this.archive(target, { reason: 'merge rolled back' }, plan.origin);
2423
+ const targetRollback = await archive(target, { reason: 'merge rolled back' });
2432
2424
  if (!targetRollback.ok)
2433
2425
  stuck.push(target);
2434
2426
  return rollbackMessage(result.message, stuck);
@@ -2459,7 +2451,7 @@ export class SkillLibrary {
2459
2451
  });
2460
2452
  if (!result.ok) {
2461
2453
  const stuck = await rollbackSources();
2462
- const targetRollback = await this.archive(target, { reason: 'merge rolled back' }, plan.origin);
2454
+ const targetRollback = await archive(target, { reason: 'merge rolled back' });
2463
2455
  if (!targetRollback.ok)
2464
2456
  stuck.push(target);
2465
2457
  return rollbackMessage(result.message, stuck);
@@ -2922,20 +2914,16 @@ export class SkillLibrary {
2922
2914
  let headPlaced = false;
2923
2915
  for (const op of event.ops) {
2924
2916
  const rel = relative(dir, op.target).split(String.fromCharCode(92)).join('/');
2925
- await this.audit(name, 'restructure', op.before, op.after, summary, rel === 'SKILL.md' ? undefined : rel, event.unitId, headPlaced ? undefined : this.unitHeadForOps(event.ops, [name]), origin);
2917
+ await this.audit(name, 'restructure', op.before, op.after, summary, rel === 'SKILL.md' ? undefined : rel, event.unitId, headPlaced ? undefined : this.unitHeadForOps(event.ops, [name]), origin, true);
2926
2918
  headPlaced = true;
2927
2919
  }
2928
2920
  this.notifyMutation({ action: 'restructure', name, skillDir: dir });
2929
2921
  },
2930
2922
  };
2931
- const home = dirname(this.root);
2932
- const unit = new MutationUnit({
2933
- io: this.io,
2923
+ const unit = this.commitUnit({
2934
2924
  limits: { maxSkillFileBytes: this.limits.maxSkillFileBytes, maxSkillContentChars: this.limits.maxSkillContentChars },
2935
2925
  serial: this.serial,
2936
2926
  lock: this.lockPort(),
2937
- journal: unitJournalPort(this.io, home),
2938
- snapshots: unitSnapshotPort(this.io, home),
2939
2927
  hooks,
2940
2928
  validateWrite: op => op.kind === 'write' ? this.contentThreatBlock(op.content) : null,
2941
2929
  });
@@ -3054,21 +3042,17 @@ export class SkillLibrary {
3054
3042
  if (op.skill === undefined)
3055
3043
  continue;
3056
3044
  const rel = relative(this.dirOf(op.skill), op.target).split(String.fromCharCode(92)).join('/');
3057
- await this.audit(op.skill, 'extract', op.before, op.after, summary, rel === 'SKILL.md' ? undefined : rel, event.unitId, headPlaced ? undefined : head, origin);
3045
+ await this.audit(op.skill, 'extract', op.before, op.after, summary, rel === 'SKILL.md' ? undefined : rel, event.unitId, headPlaced ? undefined : head, origin, true);
3058
3046
  headPlaced = true;
3059
3047
  }
3060
3048
  for (const name of roots)
3061
3049
  this.notifyMutation({ action: 'extract', name, skillDir: this.dirOf(name) });
3062
3050
  },
3063
3051
  };
3064
- const home = dirname(this.root);
3065
- const unit = new MutationUnit({
3066
- io: this.io,
3052
+ const unit = this.commitUnit({
3067
3053
  limits: { maxSkillFileBytes: this.limits.maxSkillFileBytes, maxSkillContentChars: this.limits.maxSkillContentChars },
3068
3054
  serial: this.serial,
3069
3055
  lock: this.lockPort(),
3070
- journal: unitJournalPort(this.io, home),
3071
- snapshots: unitSnapshotPort(this.io, home),
3072
3056
  hooks,
3073
3057
  validateWrite: op => op.kind === 'write' ? this.contentThreatBlock(op.content) : null,
3074
3058
  });
@@ -3099,7 +3083,7 @@ export class SkillLibrary {
3099
3083
  return { ok: false, message: badName };
3100
3084
  const dir = this.dirOf(name);
3101
3085
  const body = await this.io.readText(join(dir, 'SKILL.md'));
3102
- if (!body)
3086
+ if (body === null)
3103
3087
  return { ok: false, message: '技能「' + name + '」不存在。' };
3104
3088
  const protection = root.protection === 'write'
3105
3089
  ? await this.writeProtection(name, plan.origin)
@@ -3151,12 +3135,9 @@ export class SkillLibrary {
3151
3135
  landing.push({ kind: op.kind, target: op.target, content: op.kind === 'write' ? op.content : null, previous, expected: op.expected, skill, dir: owner.dir, rel });
3152
3136
  }
3153
3137
  const unitId = plan.unitId ?? 'u-' + Date.now().toString(36) + '-' + (nextUnitSeq += 1).toString(36);
3154
- const unit = new MutationUnit({
3155
- io: this.io,
3138
+ const unit = this.commitUnit({
3156
3139
  limits: this.limits,
3157
3140
  ...(plan.nested === true ? { nested: true } : { lock: this.lockPort() }),
3158
- journal: unitJournalPort(this.io, dirname(this.root)),
3159
- snapshots: unitSnapshotPort(this.io, dirname(this.root)),
3160
3141
  ...(this.transact === undefined ? {} : { transact: this.transact }),
3161
3142
  now: () => Date.now(),
3162
3143
  });
@@ -3192,7 +3173,7 @@ export class SkillLibrary {
3192
3173
  const entry = landing[index];
3193
3174
  if (entry === undefined)
3194
3175
  continue;
3195
- await this.audit(entry.skill, plan.auditAction, entry.previous, entry.kind === 'delete' ? null : entry.content, plan.auditSummary, entry.rel === 'SKILL.md' ? undefined : entry.rel, unitId, index === 0 ? (plan.unitHead ?? defaultHead) : undefined, plan.origin);
3176
+ await this.audit(entry.skill, plan.auditAction, entry.previous, entry.kind === 'delete' ? null : entry.content, plan.auditSummary, entry.rel === 'SKILL.md' ? undefined : entry.rel, unitId, index === 0 ? (plan.unitHead ?? defaultHead) : undefined, plan.origin, plan.nested === true);
3196
3177
  affected.add(entry.skill);
3197
3178
  }
3198
3179
  for (const skill of affected) {
@@ -3216,6 +3197,9 @@ export class SkillLibrary {
3216
3197
  * path back. The `.archive-reason` marker is dropped on restore.
3217
3198
  */
3218
3199
  async restoreFromArchive(rawName, origin = this.authority.origin) {
3200
+ return await this.restoreFromArchiveCore(rawName, origin, false);
3201
+ }
3202
+ async restoreFromArchiveCore(rawName, origin, fenceHeld) {
3219
3203
  const name = rawName.trim();
3220
3204
  // P2-2 (v11): the inline regex + hand-written message bypassed badName()
3221
3205
  // (C-12 single source — the regex carries no length bound, so a >64-char
@@ -3367,7 +3351,7 @@ export class SkillLibrary {
3367
3351
  if (isUnknown(restoredProbe)) {
3368
3352
  console.warn(`evolution-skill-store: the restored SKILL.md of "${name}" could not be read back (${restoredProbe.reason}); the restore is recorded without after-bytes`);
3369
3353
  }
3370
- await this.audit(name, 'restore', null, isPresent(restoredProbe) ? restoredProbe.value : null, `restored from ${source}`, undefined, undefined, undefined, origin);
3354
+ await this.audit(name, 'restore', null, isPresent(restoredProbe) ? restoredProbe.value : null, `restored from ${source}`, undefined, undefined, undefined, origin, fenceHeld);
3371
3355
  this.notifyMutation({ action: 'restore', name, skillDir: dest });
3372
3356
  return { ok: true, message: `技能「${name}」已从 .archive 恢复。`, path: dest };
3373
3357
  }
@@ -3413,20 +3397,17 @@ export class SkillLibrary {
3413
3397
  if (current !== null && content.trimEnd() === current.trimEnd()) {
3414
3398
  return { ok: true, message: `支撑文件「${filePath}」未变更:提供的内容与当前文件一致,未写入。`, noop: true, path: target };
3415
3399
  }
3416
- const unit = new MutationUnit({
3417
- io: this.io,
3400
+ const unit = this.commitUnit({
3418
3401
  limits: { maxSkillFileBytes: Number.MAX_SAFE_INTEGER, maxSkillContentChars: Number.MAX_SAFE_INTEGER },
3419
3402
  serial: this.serial,
3420
3403
  lock: this.lockPort(),
3421
- journal: unitJournalPort(this.io, dirname(this.root)),
3422
- snapshots: unitSnapshotPort(this.io, dirname(this.root)),
3423
3404
  ...(this.transact === undefined ? {} : { transact: this.transact }),
3424
3405
  hooks: {
3425
3406
  committed: async (event) => {
3426
3407
  const op = event.ops[0];
3427
3408
  if (op === undefined)
3428
3409
  return;
3429
- await this.audit(name, 'write_file', op.before, op.after, `wrote ${filePath}`, filePath, event.unitId, undefined, origin);
3410
+ await this.audit(name, 'write_file', op.before, op.after, `wrote ${filePath}`, filePath, event.unitId, undefined, origin, true);
3430
3411
  this.notifyMutation({ action: 'write_file', name, skillDir: dir, file: target });
3431
3412
  },
3432
3413
  },
@@ -3480,13 +3461,20 @@ export class SkillLibrary {
3480
3461
  let lockedBefore = before;
3481
3462
  if (verdict === 'match' && this.transact) {
3482
3463
  const ran = { done: false };
3483
- await this.transact(this.io, target, (current) => {
3484
- ran.done = true;
3485
- verdict = anchorVerdict(anchor, current);
3486
- if (verdict === 'match' && current !== null)
3487
- lockedBefore = current;
3488
- return verdict === 'match' ? null : current;
3489
- });
3464
+ try {
3465
+ await this.transact(this.io, target, (current) => {
3466
+ ran.done = true;
3467
+ verdict = anchorVerdict(anchor, current);
3468
+ if (verdict === 'match' && current !== null)
3469
+ lockedBefore = current;
3470
+ return verdict === 'match' ? null : current;
3471
+ });
3472
+ }
3473
+ catch (error) {
3474
+ if (error instanceof TransactionNotInvokedError)
3475
+ return { ok: false, message: '内部错误:删除事务没有调用任务;没有删除任何东西' };
3476
+ throw error;
3477
+ }
3490
3478
  if (!ran.done)
3491
3479
  return { ok: false, message: '内部错误:删除事务没有调用任务;没有删除任何东西' };
3492
3480
  }
@@ -2,5 +2,4 @@ import type { Context } from '@deepseek-ai/cordis';
2
2
  import type { ChannelKind, ChannelState } from './types.ts';
3
3
  /** Pure derivation (no side effects): the doctor reads this, the channel re-probes on every run. */
4
4
  export declare function probeChannelState(ctx: Context, kind: ChannelKind): ChannelState;
5
- export declare function subagentChannelState(ctx: Context, kind: ChannelKind): ChannelState;
6
5
  //# sourceMappingURL=readiness.d.ts.map
@@ -3,9 +3,6 @@ import { restrictedPresetId } from "../composition/preset-ids.js";
3
3
  function serviceOf(ctx, name) {
4
4
  return ctx.get(name);
5
5
  }
6
- function kindOf(kind) {
7
- return kind === 'reviewer' ? 'reviewer' : 'maintainer';
8
- }
9
6
  /** Pure derivation (no side effects): the doctor reads this, the channel re-probes on every run. */
10
7
  export function probeChannelState(ctx, kind) {
11
8
  const subagents = serviceOf(ctx, 'subagents');
@@ -25,11 +22,8 @@ export function probeChannelState(ctx, kind) {
25
22
  if (agentPresets === undefined || typeof agentPresets.readDocument !== 'function' || typeof agentPresets.register !== 'function') {
26
23
  return { kind: 'unavailable', code: 'E-323', reason: 'agentPresets service unavailable or incomplete' };
27
24
  }
28
- const id = restrictedPresetId(kindOf(kind));
29
- const state = restrictedPresetState(ctx, kindOf(kind));
25
+ const id = restrictedPresetId(kind);
26
+ const state = restrictedPresetState(ctx, kind);
30
27
  return { kind: 'available', provider: 'spawn', preset: { id, registered: state?.kind === 'ready' } };
31
28
  }
32
- export function subagentChannelState(ctx, kind) {
33
- return probeChannelState(ctx, kind);
34
- }
35
29
  //# sourceMappingURL=readiness.js.map