@lmzhen/dsh-evolution-core 0.59.5 → 0.60.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/README.md +3 -1
  2. package/lib/authority-plugin.js +3 -2
  3. package/lib/composition/index.js +2 -2
  4. package/lib/{composition-B_F4TYOD.js → composition-BSqh70z_.js} +1 -1
  5. package/lib/{ensure-BpVDuDnA.js → ensure-DTCuxAxR.js} +1 -1
  6. package/lib/{extract-plan-D3ALlAmN.js → extract-plan-CP__XlEs.js} +2 -2
  7. package/lib/extract.js +4 -4
  8. package/lib/http-routes.js +3 -2
  9. package/lib/index.js +15 -15
  10. package/lib/{io-Cpa8wuvj.js → io-DT4-MXLr.js} +25 -1
  11. package/lib/io-node.js +1 -1
  12. package/lib/io-platform.js +163 -0
  13. package/lib/io-registry.js +10 -0
  14. package/lib/{mutation-authority-CZpc9F20.js → mutation-authority-C3RYyiaT.js} +66 -41
  15. package/lib/{mutation-storage-adapter-z1_hyrQn.js → mutation-storage-adapter-CSVn34dK.js} +334 -212
  16. package/lib/{mutations-Y-wKod7W.js → mutations-JKFlfhSO.js} +1 -1
  17. package/lib/policy.js +1 -1
  18. package/lib/{quality-NPGr3VzA.js → quality-C0ri2SgY.js} +2 -2
  19. package/lib/restrictor.js +1 -1
  20. package/lib/result.js +1 -1
  21. package/lib/{review-context-yNiZadPw.js → review-context-D2LIOEi-.js} +2 -2
  22. package/lib/runtime/plugin.js +2 -2
  23. package/lib/{session-projection-DM15fsRp.js → session-projection-Dnmm5bzt.js} +1 -1
  24. package/lib/{skill-history-BvLWFoOo.js → skill-history-BOZ4HCDB.js} +2 -2
  25. package/lib/skills.js +739 -129
  26. package/lib/state/domain/index.js +433 -0
  27. package/lib/state/index.js +136 -0
  28. package/lib/state/migrate.js +90 -0
  29. package/lib/state/storage.js +605 -0
  30. package/lib/state/store-plugin.js +23 -0
  31. package/lib/state/store.js +268 -0
  32. package/lib/subagent/index.js +1 -1
  33. package/lib/types/authority-plugin.d.ts +1 -1
  34. package/lib/types/authority-plugin.js +2 -1
  35. package/lib/types/authority.d.ts +1 -1
  36. package/lib/types/authority.js +75 -48
  37. package/lib/types/composition/ensure.js +1 -1
  38. package/lib/types/contract.d.ts +8 -0
  39. package/lib/types/http-routes.d.ts +1 -0
  40. package/lib/types/http-routes.js +2 -1
  41. package/lib/types/io-platform.d.ts +74 -0
  42. package/lib/types/io-platform.js +178 -0
  43. package/lib/types/io-registry.d.ts +4 -0
  44. package/lib/types/io-registry.js +10 -0
  45. package/lib/types/io.d.ts +7 -0
  46. package/lib/types/io.js +25 -1
  47. package/lib/types/mutation-authority.d.ts +1 -1
  48. package/lib/types/mutation-storage-adapter.d.ts +1 -1
  49. package/lib/types/opt-in.js +2 -2
  50. package/lib/types/params.js +2 -2
  51. package/lib/types/policy.js +1 -1
  52. package/lib/types/restrictor.js +2 -2
  53. package/lib/types/result.d.ts +1 -1
  54. package/lib/types/result.js +1 -1
  55. package/lib/types/runtime/coherence.js +1 -1
  56. package/lib/types/runtime/llm.d.ts +1 -1
  57. package/lib/types/runtime/llm.js +1 -1
  58. package/lib/types/runtime/platform.d.ts +3 -3
  59. package/lib/types/runtime/platform.js +2 -2
  60. package/lib/types/runtime/projections.d.ts +1 -1
  61. package/lib/types/scope.js +1 -1
  62. package/lib/types/session-projection.d.ts +1 -1
  63. package/lib/types/signals.d.ts +1 -1
  64. package/lib/types/skill-observation.d.ts +4 -5
  65. package/lib/types/skill-observation.js +18 -2
  66. package/lib/types/skill-store.d.ts +73 -4
  67. package/lib/types/skill-store.js +376 -29
  68. package/lib/types/skill-write-plan.d.ts +80 -0
  69. package/lib/types/skill-write-plan.js +2 -0
  70. package/lib/types/skill-write-service.d.ts +84 -2
  71. package/lib/types/skill-write-service.js +214 -35
  72. package/lib/types/skills.d.ts +2 -0
  73. package/lib/types/skills.js +2 -0
  74. package/lib/types/state/conformance.d.ts +47 -0
  75. package/lib/types/state/conformance.js +246 -0
  76. package/lib/types/state/constants.d.ts +52 -0
  77. package/lib/types/state/constants.js +52 -0
  78. package/lib/types/state/domain/compatibility.d.ts +40 -0
  79. package/lib/types/state/domain/compatibility.js +36 -0
  80. package/lib/types/state/domain/index.d.ts +81 -0
  81. package/lib/types/state/domain/index.js +592 -0
  82. package/lib/types/state/index.d.ts +63 -0
  83. package/lib/types/state/index.js +174 -0
  84. package/lib/types/state/medium-declaration.d.ts +37 -0
  85. package/lib/types/state/medium-declaration.js +53 -0
  86. package/lib/types/state/migrate.d.ts +34 -0
  87. package/lib/types/state/migrate.js +103 -0
  88. package/lib/types/state/record-contract.d.ts +56 -0
  89. package/lib/types/state/record-contract.js +120 -0
  90. package/lib/types/state/storage.d.ts +112 -0
  91. package/lib/types/state/storage.js +178 -0
  92. package/lib/types/state/store-plugin.d.ts +14 -0
  93. package/lib/types/state/store-plugin.js +18 -0
  94. package/lib/types/state/store.d.ts +39 -0
  95. package/lib/types/state/store.js +270 -0
  96. package/lib/types/store-ledger.js +2 -2
  97. package/lib/types/subagent/run.d.ts +1 -1
  98. package/lib/types/subagent/types.d.ts +4 -4
  99. package/lib/types/system-skill-writer.d.ts +21 -0
  100. package/lib/types/system-skill-writer.js +15 -0
  101. package/lib/types/{write-kernel.d.ts → target-writer.d.ts} +32 -15
  102. package/lib/types/{write-kernel.js → target-writer.js} +40 -8
  103. package/lib/types/tool-dispatch.js +6 -3
  104. package/lib/types/{mutation-unit.d.ts → unit-kernel.d.ts} +44 -13
  105. package/lib/types/{mutation-unit.js → unit-kernel.js} +163 -120
  106. package/lib/types/write.d.ts +1 -2
  107. package/lib/types/write.js +1 -2
  108. package/lib/{usage-D7yHG2Cb.js → usage-BO4Zj_zB.js} +2 -2
  109. package/lib/write.js +4 -4
  110. package/package.json +30 -3
  111. package/persisted-write-inventory.json +14 -5
@@ -33,6 +33,9 @@
33
33
  * (OPT-07); the movers' probe→rename window is owned by the io.ts protocol.
34
34
  */
35
35
  import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
36
+ import { realpathSync } from 'node:fs';
37
+ import { createHash } from 'node:crypto';
38
+ import { AsyncLocalStorage } from 'node:async_hooks';
36
39
  import { authorityFrom } from "./write-authority.js";
37
40
  import { resolveCitations } from "./citations.js";
38
41
  import { scanContentThreats } from "./threats.js";
@@ -50,7 +53,7 @@ import { FUZZY_MAX_PATTERN_CHARS, FUZZY_MAX_WORK, trimPatternBoundaries, fuzzyPa
50
53
  import { makeSerialQueue } from "./serial.js";
51
54
  import { supportRefs } from "./support-refs.js";
52
55
  import { selectSections } from "./section-selection.js";
53
- import { MutationUnit, fileMutationLock } from "./mutation-unit.js";
56
+ import { UnitKernel, fileMutationLock } from "./unit-kernel.js";
54
57
  import { mutationLockFrom } from "./mutation-authority.js";
55
58
  import { SkillModel } from "./skill-model.js";
56
59
  import { pruneTreeChangeUnits, unitJournalPort, unitSnapshotPort } from "./mutation-storage-adapter.js";
@@ -58,7 +61,7 @@ import { projectExtractBodies } from "./extract-plan.js";
58
61
  import { diffFindings } from "./skill-lint.js";
59
62
  import { contentHash, loadMutations, recordMutation } from "./mutations.js";
60
63
  import { decideSkillWrite } from "./skill-write-intent.js";
61
- import { skillNamespaceKey } from "./skill-observation.js";
64
+ import { skillBodyTarget, skillNamespaceKey } from "./skill-observation.js";
62
65
  import { SkillTargetLocks } from "./skill-target-locks.js";
63
66
  import { SkillRootGate } from "./skill-root-gate.js";
64
67
  import { revisionFingerprint, revisionSupportDigest } from "./skill-revision.js";
@@ -436,6 +439,19 @@ function planRestructureSections(body, moves) {
436
439
  }
437
440
  return { body: rebuilt.join('\n'), sections: spans.map(({ rel, heading, text }) => ({ rel, heading, text })) };
438
441
  }
442
+ /** Project one restructure without writing: the operator preview and the store share the planner. */
443
+ export function projectRestructureMarkdown(markdown, moves) {
444
+ const block = frontmatterBlock(markdown);
445
+ if (!block)
446
+ return { ok: false, message: 'SKILL.md 没有有效的 frontmatter;拒绝重构。' };
447
+ const header = block.lines.slice(0, block.end + 1).join('\n');
448
+ const bodyRaw = markdown.slice(header.length);
449
+ const plan = planRestructureSections(bodyRaw.replace(/\r\n/g, '\n'), moves);
450
+ if ('error' in plan)
451
+ return { ok: false, message: '重构被拒绝:' + plan.error };
452
+ const newMd = (header + plan.body).replace(/\r\n/g, '\n');
453
+ return { ok: true, body: block.nl === '\r\n' ? newMd.replace(/\n/g, '\r\n') : newMd, sections: plan.sections };
454
+ }
439
455
  /**
440
456
  * WHY MODULE SCOPE (S4.4): the serial queue must be shared ACROSS SkillLibrary instances. Six services
441
457
  * each build their own store over the SAME skill root (tool face / curator face / review face), and a
@@ -450,8 +466,16 @@ const ROOT_SERIAL = new Map();
450
466
  * @param root - the resolved skill root; the key, so two spellings of one directory share a queue.
451
467
  * @returns the queue every instance over this root serializes through.
452
468
  */
469
+ function canonicalRootKey(root) {
470
+ try {
471
+ return realpathSync.native(resolve(root));
472
+ }
473
+ catch {
474
+ return resolve(root);
475
+ }
476
+ }
453
477
  function serialForRoot(root) {
454
- const key = resolve(root);
478
+ const key = canonicalRootKey(root);
455
479
  const existing = ROOT_SERIAL.get(key);
456
480
  if (existing !== undefined)
457
481
  return existing;
@@ -467,14 +491,30 @@ function sameRevisionAnchor(expected, live) {
467
491
  }
468
492
  /** One target-lock registry per skill ROOT, shared by every library instance in this process. */
469
493
  const TARGET_LOCKS_BY_ROOT = new Map();
494
+ /** One structural gate per canonical root, shared by every library instance. */
495
+ const ROOT_GATES = new Map();
496
+ function rootGateFor(root) {
497
+ const key = canonicalRootKey(root);
498
+ let gate = ROOT_GATES.get(key);
499
+ if (gate === undefined) {
500
+ gate = new SkillRootGate();
501
+ ROOT_GATES.set(key, gate);
502
+ }
503
+ return gate;
504
+ }
470
505
  function targetLocksFor(root) {
471
- let locks = TARGET_LOCKS_BY_ROOT.get(root);
506
+ const key = canonicalRootKey(root);
507
+ let locks = TARGET_LOCKS_BY_ROOT.get(key);
472
508
  if (locks === undefined) {
473
509
  locks = new SkillTargetLocks();
474
- TARGET_LOCKS_BY_ROOT.set(root, locks);
510
+ TARGET_LOCKS_BY_ROOT.set(key, locks);
475
511
  }
476
512
  return locks;
477
513
  }
514
+ /** Async-local collector: a normal single-op write never sees another plan's sink. */
515
+ const PLAN_SINK = new AsyncLocalStorage();
516
+ /** The model-supplied plan summary that must reach history/audit, not just command output. */
517
+ const PLAN_SUMMARY = new AsyncLocalStorage();
478
518
  export class SkillLibrary {
479
519
  root;
480
520
  /** The ONE read face owner/health/panel consume; a thin adapter, not a store. */
@@ -494,8 +534,8 @@ export class SkillLibrary {
494
534
  serial;
495
535
  /** Transitional target locks (same key as SkillWriteService). */
496
536
  targetLocks;
497
- /** Root structural gate; simple writes still use the serial until D.5d. */
498
- rootGate = new SkillRootGate();
537
+ /** Root structural gate; shared per canonical root across library instances. */
538
+ rootGate;
499
539
  /** V10-03 (P2-18): see the constructor's threatExemptLabels. Empty by
500
540
  * default — the strict ANY-hit-blocks policy is unchanged. */
501
541
  threatExemptLabels;
@@ -511,6 +551,7 @@ export class SkillLibrary {
511
551
  constructor(root = skillsRoot(), io = nodeEvolutionIo(), limits = DEFAULT_SKILL_LIMITS, onMutation, transact, threatExemptLabels, authority = CLASS_DEFAULT_AUTHORITY, mutationLock, fence) {
512
552
  this.root = root;
513
553
  this.targetLocks = targetLocksFor(root);
554
+ this.rootGate = rootGateFor(root);
514
555
  this.io = io;
515
556
  this.limits = limits;
516
557
  this.onMutation = onMutation;
@@ -540,7 +581,7 @@ export class SkillLibrary {
540
581
  }
541
582
  /**
542
583
  * Transitional root lock for mutators that still own their write path. The
543
- * extract/restructure path takes the same lock through MutationUnit, so those
584
+ * extract/restructure path takes the same lock through UnitKernel, so those
544
585
  * two paths cannot interleave with create/update/patch across processes.
545
586
  */
546
587
  unitHeadForOps(ops, roots, provenance = new Map()) {
@@ -564,13 +605,77 @@ export class SkillLibrary {
564
605
  }
565
606
  /** Transitional: serialize one target even while the root serial remains. */
566
607
  async withTarget(targetKey, task) {
567
- return await this.targetLocks.withLock(targetKey, task);
608
+ return await this.targetLocks.withLock(await this.canonicalTargetKey(targetKey), task);
609
+ }
610
+ /** Canonicalize several logical target keys for one lock acquisition. */
611
+ async canonicalLockKeys(keys) {
612
+ return await Promise.all(keys.map(key => this.canonicalTargetKey(key)));
613
+ }
614
+ /**
615
+ * Attach the canonical realpath identity to one observation target.
616
+ * @param target - logical skill target.
617
+ * @returns the target with `identityKey`; the logical targetKey is unchanged.
618
+ */
619
+ async identify(target) {
620
+ const key = target.relPath === '' ? 'skill::' + target.skill : 'skill::' + target.skill + '::' + target.relPath;
621
+ return { ...target, identityKey: await this.canonicalTargetKey(key) };
622
+ }
623
+ /**
624
+ * Canonical in-process lock identity for one skill target key.
625
+ *
626
+ * A logical `skill::name::path` key is resolved through realpath (or the
627
+ * nearest existing ancestor for a not-yet-created file) and hashed, so two
628
+ * spellings/symlinks of the same host file share one promise-lock queue. The
629
+ * logical targetKey stays the observation/approval key until the observation
630
+ * resolver phase; this method only fixes the provider lock identity.
631
+ * @param targetKey - the family's logical skill target key.
632
+ * @returns the canonical lock key, or the input for non-skill keys.
633
+ */
634
+ async canonicalTargetKey(targetKey) {
635
+ if (!targetKey.startsWith('skill::'))
636
+ return targetKey;
637
+ // Fake/virtual IO roots do not exist on this host: fall back to the logical key
638
+ // so two library instances over the same virtual root still share one queue.
639
+ try {
640
+ realpathSync.native(this.root);
641
+ }
642
+ catch {
643
+ return targetKey;
644
+ }
645
+ const rest = targetKey.slice('skill::'.length);
646
+ const [name, ...tail] = rest.split('::');
647
+ if (name === undefined || name === '')
648
+ return targetKey;
649
+ const rel = tail.join('::');
650
+ const dir = this.dirOf(name);
651
+ const namespace = rel === '*';
652
+ const body = rel === '';
653
+ const path = namespace ? dir : body ? join(dir, 'SKILL.md') : join(dir, ...rel.replace(/\\/g, '/').split('/').filter(Boolean));
654
+ let cursor = path;
655
+ const suffix = [];
656
+ let identity;
657
+ while (true) {
658
+ try {
659
+ identity = join(realpathSync.native(cursor), ...suffix.reverse());
660
+ break;
661
+ }
662
+ catch {
663
+ const parent = dirname(cursor);
664
+ if (parent === cursor)
665
+ return targetKey;
666
+ suffix.push(basename(cursor));
667
+ cursor = parent;
668
+ }
669
+ }
670
+ const digest = createHash('sha256').update(identity.replace(/\\/g, '/')).digest('hex');
671
+ return 'skillpath:' + digest + (namespace ? '::*' : '');
568
672
  }
569
673
  async withMutationLock(task, targetKeys) {
570
674
  // Fail closed: a missing authority/lock is an assembly error, not a reason to run
571
675
  // the write outside the fence. The old catch-and-fallback inverted this guard: the
572
676
  // "refusing an unfenced production write" error itself took the fallback path.
573
- const lease = await this.lockPort().acquire(targetKeys);
677
+ const keys = targetKeys === undefined ? undefined : await this.canonicalLockKeys(targetKeys);
678
+ const lease = await this.lockPort().acquire(keys);
574
679
  try {
575
680
  return await task();
576
681
  }
@@ -578,12 +683,38 @@ export class SkillLibrary {
578
683
  await lease.release();
579
684
  }
580
685
  }
581
- /** The one MutationUnit constructor: storage ports are fixed here, callers pass the rest. */
686
+ /** The one UnitKernel constructor: storage ports are fixed here, callers pass the rest. */
582
687
  commitUnit(options) {
583
- return new MutationUnit({
688
+ const plan = PLAN_SINK.getStore();
689
+ if (plan !== undefined) {
690
+ // Multi-op plan collection: the core mutators still perform every read,
691
+ // validation and CAS anchor check, but their write unit only records the
692
+ // final op. The plan then commits the collected ops through one real unit.
693
+ return {
694
+ apply: async (request) => {
695
+ for (const op of request.ops) {
696
+ const skill = op.skill ?? request.name;
697
+ const dir = this.dirOf(skill);
698
+ const rel = relative(dir, op.target).split(String.fromCharCode(92)).join('/');
699
+ plan.writes.push({
700
+ target: op.target,
701
+ expected: op.expected ?? null,
702
+ content: op.kind === 'delete' ? null : op.content,
703
+ skill,
704
+ path: rel === 'SKILL.md' ? undefined : rel,
705
+ auditAction: request.auditAction,
706
+ auditSummary: request.auditSummary,
707
+ });
708
+ }
709
+ return { ok: true, unitId: request.unitId ?? 'plan-item-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 8), dryRun: false, changed: request.ops.map(op => op.target), errors: [] };
710
+ },
711
+ };
712
+ }
713
+ return new UnitKernel({
584
714
  io: this.io,
585
715
  journal: unitJournalPort(this.io, dirname(this.root)),
586
716
  snapshots: unitSnapshotPort(this.io, dirname(this.root)),
717
+ targetKeyResolver: keys => this.canonicalLockKeys(keys),
587
718
  ...options,
588
719
  });
589
720
  }
@@ -638,7 +769,15 @@ export class SkillLibrary {
638
769
  recovery;
639
770
  /** Run the boot recovery once per library instance, before the first write. */
640
771
  async ensureRecovered() {
641
- this.recovery ??= this.recoverPreparedUnits().then(() => undefined).catch(error => {
772
+ this.recovery ??= this.recoverPreparedUnits().then(results => {
773
+ const unresolved = results.filter(result => !result.ok);
774
+ if (unresolved.length > 0) {
775
+ // A3: a drifted prepared unit is a structured recover refusal, not a throw. Ignoring the
776
+ // results made it invisible while undo kept refusing with undo-needs-recovery.
777
+ console.warn('skill-store: prepared-unit recovery left ' + String(unresolved.length) + ' unit(s) unresolved; first: '
778
+ + unresolved.slice(0, 5).map(result => result.unitId + '=' + (result.errors[0]?.code ?? 'unknown') + ':' + (result.errors[0]?.message ?? '')).join('; '));
779
+ }
780
+ }).catch(error => {
642
781
  console.warn('skill-store: prepared-unit recovery failed; writes continue: ' + (error instanceof Error ? error.message : String(error)));
643
782
  });
644
783
  await this.recovery;
@@ -1311,12 +1450,18 @@ export class SkillLibrary {
1311
1450
  // Keep per-file transactions, but do not queue behind our own lease.
1312
1451
  const fence = fenceHeld ? undefined : this.fence;
1313
1452
  const at = new Date().toISOString();
1314
- const finalSummary = change === undefined
1315
- ? this.hostChangeSummary(action, before, after, path, summary)
1316
- : (() => {
1317
- const normalized = normalizeChangeSummary(change.text, DEFAULT_SKILL_WRITE_SUMMARY_CHARS);
1318
- return normalized.ok ? { text: normalized.text, source: change.source } : this.hostChangeSummary(action, before, after, path, summary);
1319
- })();
1453
+ const planSummary = PLAN_SUMMARY.getStore();
1454
+ const finalSummary = planSummary !== undefined
1455
+ ? (() => {
1456
+ const normalized = normalizeChangeSummary(planSummary, DEFAULT_SKILL_WRITE_SUMMARY_CHARS);
1457
+ return normalized.ok ? { text: normalized.text, source: 'model' } : this.hostChangeSummary(action, before, after, path, summary);
1458
+ })()
1459
+ : change === undefined
1460
+ ? this.hostChangeSummary(action, before, after, path, summary)
1461
+ : (() => {
1462
+ const normalized = normalizeChangeSummary(change.text, DEFAULT_SKILL_WRITE_SUMMARY_CHARS);
1463
+ return normalized.ok ? { text: normalized.text, source: change.source } : this.hostChangeSummary(action, before, after, path, summary);
1464
+ })();
1320
1465
  let versions = null;
1321
1466
  try {
1322
1467
  const keep = this.limits.versionKeep ?? DEFAULT_SKILL_VERSION_KEEP;
@@ -1710,8 +1855,14 @@ export class SkillLibrary {
1710
1855
  return { ok: false, message: `创建过程中技能「${normalized}」被并发归档;残留标记已移除:等搬运完成后重试一次。` };
1711
1856
  }
1712
1857
  }
1713
- await this.audit(normalized, 'create', null, onDisk, 'created', undefined, result.unitId, options.unitHead, undefined, fenceHeld);
1714
- this.notifyMutation({ action: 'create', name: normalized, skillDir: dir });
1858
+ // A multi-op plan prepares every op before the shared unit commits. Its
1859
+ // collected unit is a no-write recorder, so a direct audit/event here would
1860
+ // land during PREPARE: duplicated on success and phantom when a later op is
1861
+ // refused. The final unit's committed hook audits each collected write.
1862
+ if (PLAN_SINK.getStore() === undefined) {
1863
+ await this.audit(normalized, 'create', null, onDisk, 'created', undefined, result.unitId, options.unitHead, undefined, fenceHeld);
1864
+ this.notifyMutation({ action: 'create', name: normalized, skillDir: dir });
1865
+ }
1715
1866
  // Both warnings ride the normal success path (audit/event included) — a
1716
1867
  // durability warning must never skip the accounting.
1717
1868
  const warnings = [
@@ -1722,6 +1873,7 @@ export class SkillLibrary {
1722
1873
  ok: true,
1723
1874
  message: `已创建技能「${normalized}」。${warnings.length === 0 ? '' : ` (警告:${warnings.join(';')})`}`,
1724
1875
  path: dir,
1876
+ after: onDisk,
1725
1877
  ...(norm.changed ? { normalizedFrontmatterFields: norm.fields } : {}),
1726
1878
  };
1727
1879
  }
@@ -1812,7 +1964,7 @@ export class SkillLibrary {
1812
1964
  }
1813
1965
  const warning = result.warnings === undefined || result.warnings.length === 0 ? '' : ` (警告:写入已落盘,但目录 fsync 失败 —— 持久性未确认:${result.warnings.join(';')})`;
1814
1966
  const retention = contentRetentionFeedback({ name, action: 'update', before: current, after: onDisk });
1815
- return { ok: true, message: `技能「${name}」已更新。${warning}${retention === null ? '' : '\n' + retention}`, path: dir, ...(prepared.norm.changed ? { normalizedFrontmatterFields: prepared.norm.fields } : {}) };
1967
+ return { ok: true, message: `技能「${name}」已更新。${warning}${retention === null ? '' : '\n' + retention}`, path: dir, after: onDisk, ...(prepared.norm.changed ? { normalizedFrontmatterFields: prepared.norm.fields } : {}) };
1816
1968
  }
1817
1969
  async patch(rawName, oldString, newString, filePath = '', replaceAll = false, origin = this.authority.origin, anchor) {
1818
1970
  await this.ensureRecovered();
@@ -1883,11 +2035,11 @@ export class SkillLibrary {
1883
2035
  const next = `${header}${nextBody}`;
1884
2036
  const finalMd = block.nl === '\r\n' ? next.replace(/\n/g, '\r\n') : next;
1885
2037
  if (finalMd.trimEnd() === md.trimEnd())
1886
- return { ok: true, message: `技能「${name}」未变更:章节内容一致,未写入。`, noop: true, path: dir };
2038
+ return { ok: true, message: `技能「${name}」未变更:章节内容一致,未写入。`, noop: true, path: dir, after: md };
1887
2039
  const result = await this.update(name, finalMd, origin, { sha256: contentHash(md) });
1888
2040
  if (!result.ok)
1889
2041
  return result;
1890
- return { ok: true, message: `已更新「${name}」的「${edit.heading}」章节(正文 ${md.length} → ${finalMd.length} 字符)。`, path: dir };
2042
+ return { ok: true, message: `已更新「${name}」的「${edit.heading}」章节(正文 ${md.length} → ${finalMd.length} 字符)。`, path: dir, ...(result.after === undefined ? {} : { after: result.after }) };
1891
2043
  }
1892
2044
  async patchCore(name, oldString, newString, filePath, replaceAll, origin, anchor) {
1893
2045
  // P1-1 (v14): patch was the ONE path-building mutator without the name
@@ -1988,7 +2140,7 @@ export class SkillLibrary {
1988
2140
  // trimEnd()+'\n'), so the audit afterHash is replay-identical to the file.
1989
2141
  const onDisk = writeContent.trimEnd() + '\n';
1990
2142
  return {
1991
- result: { ok: true, message: `技能「${name}」已修补(${patchLabel})。${patchNote}${capAdvisory}`, path: dir, ...(normalizedFields ? { normalizedFrontmatterFields: normalizedFields } : {}) },
2143
+ result: { ok: true, message: `技能「${name}」已修补(${patchLabel})。${patchNote}${capAdvisory}`, path: dir, after: onDisk, ...(normalizedFields ? { normalizedFrontmatterFields: normalizedFields } : {}) },
1992
2144
  write: onDisk,
1993
2145
  audit: { skillName: name, action: 'patch', before: md, after: onDisk, summary: `patched ${patchLabel}` },
1994
2146
  event: { action: 'patch', name, skillDir: dir },
@@ -3670,6 +3822,187 @@ export class SkillLibrary {
3670
3822
  return { ok: true, message: 'skill file written', path: target };
3671
3823
  }));
3672
3824
  }
3825
+ /**
3826
+ * Execute one plan-level write through the existing mutators.
3827
+ *
3828
+ * H1 deliberately supports one op only: it is the stable seam the tool and
3829
+ * approval will move onto, while the multi-op UnitTransaction path is the
3830
+ * next phase. Refusing a partial plan is safer than committing half of it.
3831
+ * @param plan - origin plus the single operation to apply.
3832
+ * @returns the action result; `outcomes` stays empty until the provider
3833
+ * returns before/after/version in the next phase.
3834
+ */
3835
+ async apply(plan) {
3836
+ const op = plan.ops[0];
3837
+ if (op === undefined)
3838
+ return { ok: false, message: 'skill write plan is empty', outcomes: [] };
3839
+ if (plan.ops.length > 1) {
3840
+ return plan.summary === undefined || plan.summary === ''
3841
+ ? await this.applyMulti(plan)
3842
+ : await PLAN_SUMMARY.run(plan.summary, () => this.applyMulti(plan));
3843
+ }
3844
+ const result = plan.summary === undefined || plan.summary === ''
3845
+ ? await this.applyOne(op, plan.origin)
3846
+ : await PLAN_SUMMARY.run(plan.summary, () => this.applyOne(op, plan.origin));
3847
+ const target = op.kind === 'createSkill' ? skillBodyTarget(op.skill) : op.target;
3848
+ const outcomes = result.ok && result.after !== undefined
3849
+ ? [{ op, target, after: result.after, version: result.after === null ? '' : contentHash(result.after) }]
3850
+ : [];
3851
+ return {
3852
+ ok: result.ok,
3853
+ message: result.message,
3854
+ outcomes,
3855
+ ...(result.stale === true ? { stale: true } : {}),
3856
+ ...(result.noop === true ? { noop: true } : {}),
3857
+ ...(result.path === undefined ? {} : { path: result.path }),
3858
+ ...(result.normalizedFrontmatterFields === undefined ? {} : { normalizedFrontmatterFields: result.normalizedFrontmatterFields }),
3859
+ };
3860
+ }
3861
+ /**
3862
+ * Commit a multi-op plan as one atomic unit. Each op is first prepared by the
3863
+ * existing single-op mutator in a collector context (so its validation and
3864
+ * anchor/CAS checks stay the source of truth), then all collected writes are
3865
+ * handed to ONE UnitKernel. Any preparation failure or stale anchor leaves
3866
+ * every target untouched.
3867
+ */
3868
+ async applyMulti(plan) {
3869
+ const creating = plan.ops.find(op => op.kind === 'createSkill'
3870
+ || (op.kind === 'write' && op.target.relPath === '' && op.expect.kind === 'absent' && op.create !== false));
3871
+ // A non-foreground create writes the hermes-managed marker directly after its
3872
+ // body; that side effect cannot be deferred into the shared unit. Foreground
3873
+ // creates have no marker and can join a multi-op unit.
3874
+ if (creating !== undefined && (plan.origin !== 'foreground' || (creating.kind === 'createSkill' && creating.managed === true))) {
3875
+ return { ok: false, message: 'multi-op plans cannot create a managed/non-foreground skill; create it in its own plan first', outcomes: [] };
3876
+ }
3877
+ const sink = { writes: [] };
3878
+ const results = [];
3879
+ const writeCounts = [];
3880
+ const refusal = await PLAN_SINK.run(sink, async () => {
3881
+ for (const op of plan.ops) {
3882
+ const start = sink.writes.length;
3883
+ const result = await this.applyOne(op, plan.origin);
3884
+ results.push(result);
3885
+ writeCounts.push(sink.writes.length - start);
3886
+ if (!result.ok)
3887
+ return result;
3888
+ }
3889
+ return undefined;
3890
+ });
3891
+ if (refusal !== undefined)
3892
+ return { ok: false, message: refusal.message, outcomes: [], ...(refusal.stale === true ? { stale: true } : {}) };
3893
+ if (new Set(sink.writes.map(write => write.target)).size !== sink.writes.length) {
3894
+ return { ok: false, message: 'multi-op plan targets the same path more than once', outcomes: [] };
3895
+ }
3896
+ if (sink.writes.length === 0) {
3897
+ return {
3898
+ ok: true,
3899
+ message: '没有写入变更。',
3900
+ outcomes: plan.ops.map((op, index) => ({
3901
+ op,
3902
+ target: op.kind === 'createSkill' ? skillBodyTarget(op.skill) : op.target,
3903
+ ...(results[index]?.after === undefined ? {} : { after: results[index].after }),
3904
+ noop: true,
3905
+ })),
3906
+ };
3907
+ }
3908
+ const skills = [...new Set(sink.writes.map(write => write.skill))];
3909
+ const roots = skills.map(name => ({ name, protection: 'write' }));
3910
+ const rootDirs = Object.fromEntries(skills.map(name => [name, this.dirOf(name)]));
3911
+ const targetKeys = [...new Set(sink.writes.flatMap(write => [
3912
+ write.path === undefined ? 'skill::' + write.skill : 'skill::' + write.skill + '::' + write.path,
3913
+ skillNamespaceKey(write.skill),
3914
+ ]))];
3915
+ const unit = this.commitUnit({
3916
+ limits: { maxSkillFileBytes: Number.MAX_SAFE_INTEGER, maxSkillContentChars: Number.MAX_SAFE_INTEGER },
3917
+ serial: this.serial,
3918
+ lock: this.lockPort(),
3919
+ targetKeys,
3920
+ ...(this.transact === undefined ? {} : { transact: this.transact }),
3921
+ hooks: {
3922
+ committed: async (event) => {
3923
+ for (const write of sink.writes) {
3924
+ const before = write.expected;
3925
+ const after = write.content;
3926
+ await this.audit(write.skill, write.auditAction, before, after, write.auditSummary, write.path, event.unitId, { sources: [{ skill: write.skill }] }, plan.origin, true);
3927
+ this.notifyMutation({ action: write.auditAction, name: write.skill, skillDir: this.dirOf(write.skill), ...(write.path === undefined ? {} : { file: write.target }) });
3928
+ }
3929
+ },
3930
+ },
3931
+ validateWrite: op => op.kind === 'write' ? this.contentThreatBlock(op.content) : null,
3932
+ });
3933
+ const applied = await unit.apply({
3934
+ name: skills[0] ?? '',
3935
+ origin: plan.origin,
3936
+ roots,
3937
+ rootDirs,
3938
+ ops: sink.writes.map(write => write.content === null
3939
+ ? { kind: 'delete', target: write.target, expected: write.expected, skill: write.skill }
3940
+ : { kind: 'write', target: write.target, content: write.content, expected: write.expected, skill: write.skill }),
3941
+ auditAction: 'update',
3942
+ auditSummary: plan.summary ?? 'applied write plan',
3943
+ eventAction: 'update',
3944
+ });
3945
+ if (!applied.ok)
3946
+ return { ok: false, message: applied.errors.map(error => error.message).join(';'), outcomes: [], ...(applied.warnings === undefined ? {} : { warnings: applied.warnings }) };
3947
+ let cursor = 0;
3948
+ const outcomes = plan.ops.map((op, index) => {
3949
+ if ((writeCounts[index] ?? 0) === 0) {
3950
+ const after = results[index]?.after;
3951
+ return {
3952
+ op,
3953
+ target: op.kind === 'createSkill' ? skillBodyTarget(op.skill) : op.target,
3954
+ ...(after === undefined ? {} : { after }),
3955
+ ...(typeof after === 'string' ? { version: contentHash(after) } : {}),
3956
+ noop: true,
3957
+ };
3958
+ }
3959
+ const write = sink.writes[cursor++];
3960
+ return {
3961
+ op,
3962
+ target: op.kind === 'createSkill' ? skillBodyTarget(op.skill) : op.target,
3963
+ before: write.expected,
3964
+ after: write.content,
3965
+ version: write.content === null ? '' : contentHash(write.content),
3966
+ };
3967
+ });
3968
+ return {
3969
+ ok: true,
3970
+ message: '已原子应用 ' + String(outcomes.length) + ' 个写入。',
3971
+ outcomes,
3972
+ ...(applied.warnings === undefined || applied.warnings.length === 0 ? {} : { warnings: applied.warnings }),
3973
+ };
3974
+ }
3975
+ async applyOne(op, origin) {
3976
+ switch (op.kind) {
3977
+ case 'createSkill':
3978
+ return await this.create(op.skill, op.content, origin, op.managed === true ? { managed: true } : {});
3979
+ case 'write': {
3980
+ if (op.target.relPath === '') {
3981
+ if (op.expect.kind === 'absent') {
3982
+ if (op.create !== false)
3983
+ return await this.create(op.target.skill, op.content, origin);
3984
+ return await this.update(op.target.skill, op.content, origin, { absent: true });
3985
+ }
3986
+ return await this.update(op.target.skill, op.content, origin, { sha256: op.expect.version });
3987
+ }
3988
+ const anchor = op.expect.kind === 'absent'
3989
+ ? { absent: true }
3990
+ : { sha256: op.expect.version };
3991
+ return await this.writeSupportFile(op.target.skill, op.target.relPath, op.content, origin, anchor);
3992
+ }
3993
+ case 'patch': {
3994
+ const anchor = op.expect.kind === 'absent' ? { absent: true } : { sha256: op.expect.version };
3995
+ return await this.patch(op.target.skill, op.oldString, op.newString, op.target.relPath, op.replaceAll, origin, anchor);
3996
+ }
3997
+ case 'patchSection':
3998
+ return await this.patchSection(op.target.skill, op.section, origin, op.expect.kind === 'absent' ? { absent: true } : { sha256: op.expect.version });
3999
+ case 'remove':
4000
+ if (op.target.relPath === '') {
4001
+ return { ok: false, message: 'removing SKILL.md must use the structural archive path, not a plan remove' };
4002
+ }
4003
+ return await this.removeSupportFile(op.target.skill, op.target.relPath, origin, op.expect.kind === 'absent' ? { absent: true } : { sha256: op.expect.version }, op.unitId);
4004
+ }
4005
+ }
3673
4006
  async writeSupportFile(rawName, filePath, content, origin = this.authority.origin, anchor) {
3674
4007
  const name = rawName.trim();
3675
4008
  const key = 'skill::' + name + '::' + filePath.replace(/\\/g, '/');
@@ -3680,7 +4013,8 @@ export class SkillLibrary {
3680
4013
  if (badName)
3681
4014
  return { ok: false, message: badName };
3682
4015
  const dir = this.dirOf(name);
3683
- if (!await this.io.exists(join(dir, 'SKILL.md')))
4016
+ const pendingCreate = PLAN_SINK.getStore()?.writes.some(write => write.skill === name && write.path === undefined && write.expected === null) === true;
4017
+ if (!pendingCreate && !await this.io.exists(join(dir, 'SKILL.md')))
3684
4018
  return { ok: false, message: `技能「${name}」不存在。` };
3685
4019
  const protection = await this.writeProtection(name, origin);
3686
4020
  if (protection)
@@ -3711,7 +4045,7 @@ export class SkillLibrary {
3711
4045
  return { ok: false, message: `支撑文件「${filePath}」的内容超过 ${this.limits.maxSkillContentChars} 个字符。${CONTENT_SPLIT_HINT}` };
3712
4046
  }
3713
4047
  if (current !== null && content.trimEnd() === current.trimEnd()) {
3714
- return { ok: true, message: `支撑文件「${filePath}」未变更:提供的内容与当前文件一致,未写入。`, noop: true, path: target };
4048
+ return { ok: true, message: `支撑文件「${filePath}」未变更:提供的内容与当前文件一致,未写入。`, noop: true, path: target, after: current };
3715
4049
  }
3716
4050
  const unit = this.commitUnit({
3717
4051
  limits: { maxSkillFileBytes: Number.MAX_SAFE_INTEGER, maxSkillContentChars: Number.MAX_SAFE_INTEGER },
@@ -3743,7 +4077,7 @@ export class SkillLibrary {
3743
4077
  if (!result.ok)
3744
4078
  return { ok: false, message: result.errors.map(error => error.message).join(';') };
3745
4079
  const warning = result.warnings === undefined || result.warnings.length === 0 ? '' : ` (警告:写入已落盘,但目录 fsync 失败 —— 持久性未确认:${result.warnings.join(';')})`;
3746
- return { ok: true, message: `支撑文件「${filePath}」已写入「${name}」。${capAdvisory}${warning}`, path: target };
4080
+ return { ok: true, message: `支撑文件「${filePath}」已写入「${name}」。${capAdvisory}${warning}`, path: target, after: content };
3747
4081
  }
3748
4082
  async removeSupportFile(rawName, filePath, origin = this.authority.origin, anchor, unitId) {
3749
4083
  const key = 'skill::' + rawName.trim() + '::' + filePath.replace(/\\/g, '/');
@@ -3777,6 +4111,19 @@ export class SkillLibrary {
3777
4111
  const before = beforeProbe.value;
3778
4112
  let verdict = anchorVerdict(anchor, before);
3779
4113
  let lockedBefore = before;
4114
+ const planSink = PLAN_SINK.getStore();
4115
+ if (planSink !== undefined && verdict === 'match') {
4116
+ planSink.writes.push({
4117
+ target,
4118
+ expected: before,
4119
+ content: null,
4120
+ skill: name,
4121
+ path: filePath.replace(/\\/g, '/'),
4122
+ auditAction: 'remove_file',
4123
+ auditSummary: 'removed ' + filePath,
4124
+ });
4125
+ return { ok: true, message: '支撑文件「' + filePath + '」已从「' + name + '」移除。', path: target, after: null };
4126
+ }
3780
4127
  if (verdict === 'match' && this.transact) {
3781
4128
  const ran = { done: false };
3782
4129
  try {
@@ -3803,7 +4150,7 @@ export class SkillLibrary {
3803
4150
  return anchorRefusalFile(name, filePath, verdict);
3804
4151
  await this.audit(name, 'remove_file', lockedBefore, null, `removed ${filePath}`, filePath, unitId);
3805
4152
  this.notifyMutation({ action: 'remove_file', name, skillDir: dir, file: target });
3806
- return { ok: true, message: `支撑文件「${filePath}」已从「${name}」移除。`, path: target };
4153
+ return { ok: true, message: `支撑文件「${filePath}」已从「${name}」移除。`, path: target, after: null };
3807
4154
  }
3808
4155
  /**
3809
4156
  * v23 (ML-1): `.archive` retention. Archived skills are recoverable history,
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Plan-level write types for the single skill-write provider.
3
+ *
4
+ * This is NOT a second low-level intent layer: `skill-write-intent.ts` owns
5
+ * create/replace/edit decisions and `unit-kernel.ts` owns the transaction.
6
+ * A plan is the domain-level unit the tool, approval and system writers share;
7
+ * `SkillLibrary.apply(plan)` maps each op to the existing mutators/intent.
8
+ *
9
+ * @module @lmzhen/dsh-evolution-core/skill-write-plan
10
+ */
11
+ import type { SkillTarget } from './skill-observation.ts';
12
+ import type { SkillSectionEdit, WriteOrigin } from './skill-store.ts';
13
+ /** What the writer observed for one target before planning the write. */
14
+ export type SkillWriteExpect = {
15
+ readonly kind: 'absent';
16
+ } | {
17
+ readonly kind: 'present';
18
+ readonly version: string;
19
+ };
20
+ /** One domain write in a plan. */
21
+ export type SkillWriteOp = {
22
+ readonly kind: 'createSkill';
23
+ readonly skill: string;
24
+ readonly content: string;
25
+ readonly managed?: boolean;
26
+ } | {
27
+ readonly kind: 'write';
28
+ readonly target: SkillTarget;
29
+ readonly content: string;
30
+ readonly expect: SkillWriteExpect;
31
+ /** false keeps update semantics: a missing target is NOT_FOUND, never a create. */
32
+ readonly create?: boolean;
33
+ } | {
34
+ readonly kind: 'patch';
35
+ readonly target: SkillTarget;
36
+ readonly oldString: string;
37
+ readonly newString: string;
38
+ readonly replaceAll: boolean;
39
+ readonly expect: SkillWriteExpect;
40
+ } | {
41
+ readonly kind: 'patchSection';
42
+ readonly target: SkillTarget;
43
+ readonly section: SkillSectionEdit;
44
+ readonly expect: SkillWriteExpect;
45
+ } | {
46
+ readonly kind: 'remove';
47
+ readonly target: SkillTarget;
48
+ readonly expect: SkillWriteExpect;
49
+ readonly unitId?: string;
50
+ };
51
+ /** The complete write a caller intends to commit. */
52
+ export interface SkillWritePlan {
53
+ readonly origin: WriteOrigin;
54
+ readonly ops: readonly SkillWriteOp[];
55
+ readonly summary?: string;
56
+ readonly stagedAt?: string;
57
+ }
58
+ /** One target's committed result; bytes/version are filled by the provider. */
59
+ export interface SkillWriteOutcome {
60
+ readonly op: SkillWriteOp;
61
+ readonly target: SkillTarget;
62
+ readonly before?: string | null;
63
+ readonly after?: string | null;
64
+ readonly version?: string;
65
+ readonly noop?: boolean;
66
+ }
67
+ /** Result of one plan. H1 wrappers leave `outcomes` empty until the provider fills it. */
68
+ export interface SkillWriteResult {
69
+ readonly ok: boolean;
70
+ readonly message: string;
71
+ readonly outcomes: readonly SkillWriteOutcome[];
72
+ readonly warnings?: readonly string[];
73
+ /** Frontmatter keys the write normalized for catalog-loadable YAML. */
74
+ readonly normalizedFrontmatterFields?: readonly string[];
75
+ readonly path?: string;
76
+ /** The provider refused because an expected version/absence no longer held. */
77
+ readonly stale?: true;
78
+ readonly noop?: boolean;
79
+ }
80
+ //# sourceMappingURL=skill-write-plan.d.ts.map