@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
@@ -33,8 +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 { realpath as realpathFs } from 'node:fs/promises';
36
+ import { realpathSync } from 'node:fs';
37
37
  import { createHash } from 'node:crypto';
38
+ import { AsyncLocalStorage } from 'node:async_hooks';
38
39
  import { authorityFrom } from "./write-authority.js";
39
40
  import { resolveCitations } from "./citations.js";
40
41
  import { scanContentThreats } from "./threats.js";
@@ -52,7 +53,7 @@ import { FUZZY_MAX_PATTERN_CHARS, FUZZY_MAX_WORK, trimPatternBoundaries, fuzzyPa
52
53
  import { makeSerialQueue } from "./serial.js";
53
54
  import { supportRefs } from "./support-refs.js";
54
55
  import { selectSections } from "./section-selection.js";
55
- import { MutationUnit, fileMutationLock } from "./mutation-unit.js";
56
+ import { UnitKernel, fileMutationLock } from "./unit-kernel.js";
56
57
  import { mutationLockFrom } from "./mutation-authority.js";
57
58
  import { SkillModel } from "./skill-model.js";
58
59
  import { pruneTreeChangeUnits, unitJournalPort, unitSnapshotPort } from "./mutation-storage-adapter.js";
@@ -438,6 +439,19 @@ function planRestructureSections(body, moves) {
438
439
  }
439
440
  return { body: rebuilt.join('\n'), sections: spans.map(({ rel, heading, text }) => ({ rel, heading, text })) };
440
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
+ }
441
455
  /**
442
456
  * WHY MODULE SCOPE (S4.4): the serial queue must be shared ACROSS SkillLibrary instances. Six services
443
457
  * each build their own store over the SAME skill root (tool face / curator face / review face), and a
@@ -452,8 +466,16 @@ const ROOT_SERIAL = new Map();
452
466
  * @param root - the resolved skill root; the key, so two spellings of one directory share a queue.
453
467
  * @returns the queue every instance over this root serializes through.
454
468
  */
469
+ function canonicalRootKey(root) {
470
+ try {
471
+ return realpathSync.native(resolve(root));
472
+ }
473
+ catch {
474
+ return resolve(root);
475
+ }
476
+ }
455
477
  function serialForRoot(root) {
456
- const key = resolve(root);
478
+ const key = canonicalRootKey(root);
457
479
  const existing = ROOT_SERIAL.get(key);
458
480
  if (existing !== undefined)
459
481
  return existing;
@@ -469,14 +491,30 @@ function sameRevisionAnchor(expected, live) {
469
491
  }
470
492
  /** One target-lock registry per skill ROOT, shared by every library instance in this process. */
471
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
+ }
472
505
  function targetLocksFor(root) {
473
- let locks = TARGET_LOCKS_BY_ROOT.get(root);
506
+ const key = canonicalRootKey(root);
507
+ let locks = TARGET_LOCKS_BY_ROOT.get(key);
474
508
  if (locks === undefined) {
475
509
  locks = new SkillTargetLocks();
476
- TARGET_LOCKS_BY_ROOT.set(root, locks);
510
+ TARGET_LOCKS_BY_ROOT.set(key, locks);
477
511
  }
478
512
  return locks;
479
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();
480
518
  export class SkillLibrary {
481
519
  root;
482
520
  /** The ONE read face owner/health/panel consume; a thin adapter, not a store. */
@@ -496,8 +534,8 @@ export class SkillLibrary {
496
534
  serial;
497
535
  /** Transitional target locks (same key as SkillWriteService). */
498
536
  targetLocks;
499
- /** Root structural gate; simple writes still use the serial until D.5d. */
500
- rootGate = new SkillRootGate();
537
+ /** Root structural gate; shared per canonical root across library instances. */
538
+ rootGate;
501
539
  /** V10-03 (P2-18): see the constructor's threatExemptLabels. Empty by
502
540
  * default — the strict ANY-hit-blocks policy is unchanged. */
503
541
  threatExemptLabels;
@@ -513,6 +551,7 @@ export class SkillLibrary {
513
551
  constructor(root = skillsRoot(), io = nodeEvolutionIo(), limits = DEFAULT_SKILL_LIMITS, onMutation, transact, threatExemptLabels, authority = CLASS_DEFAULT_AUTHORITY, mutationLock, fence) {
514
552
  this.root = root;
515
553
  this.targetLocks = targetLocksFor(root);
554
+ this.rootGate = rootGateFor(root);
516
555
  this.io = io;
517
556
  this.limits = limits;
518
557
  this.onMutation = onMutation;
@@ -542,7 +581,7 @@ export class SkillLibrary {
542
581
  }
543
582
  /**
544
583
  * Transitional root lock for mutators that still own their write path. The
545
- * extract/restructure path takes the same lock through MutationUnit, so those
584
+ * extract/restructure path takes the same lock through UnitKernel, so those
546
585
  * two paths cannot interleave with create/update/patch across processes.
547
586
  */
548
587
  unitHeadForOps(ops, roots, provenance = new Map()) {
@@ -598,7 +637,7 @@ export class SkillLibrary {
598
637
  // Fake/virtual IO roots do not exist on this host: fall back to the logical key
599
638
  // so two library instances over the same virtual root still share one queue.
600
639
  try {
601
- await realpathFs(this.root);
640
+ realpathSync.native(this.root);
602
641
  }
603
642
  catch {
604
643
  return targetKey;
@@ -617,7 +656,7 @@ export class SkillLibrary {
617
656
  let identity;
618
657
  while (true) {
619
658
  try {
620
- identity = join(await realpathFs(cursor), ...suffix.reverse());
659
+ identity = join(realpathSync.native(cursor), ...suffix.reverse());
621
660
  break;
622
661
  }
623
662
  catch {
@@ -644,9 +683,34 @@ export class SkillLibrary {
644
683
  await lease.release();
645
684
  }
646
685
  }
647
- /** 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. */
648
687
  commitUnit(options) {
649
- 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({
650
714
  io: this.io,
651
715
  journal: unitJournalPort(this.io, dirname(this.root)),
652
716
  snapshots: unitSnapshotPort(this.io, dirname(this.root)),
@@ -705,7 +769,15 @@ export class SkillLibrary {
705
769
  recovery;
706
770
  /** Run the boot recovery once per library instance, before the first write. */
707
771
  async ensureRecovered() {
708
- 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 => {
709
781
  console.warn('skill-store: prepared-unit recovery failed; writes continue: ' + (error instanceof Error ? error.message : String(error)));
710
782
  });
711
783
  await this.recovery;
@@ -1378,12 +1450,18 @@ export class SkillLibrary {
1378
1450
  // Keep per-file transactions, but do not queue behind our own lease.
1379
1451
  const fence = fenceHeld ? undefined : this.fence;
1380
1452
  const at = new Date().toISOString();
1381
- const finalSummary = change === undefined
1382
- ? this.hostChangeSummary(action, before, after, path, summary)
1383
- : (() => {
1384
- const normalized = normalizeChangeSummary(change.text, DEFAULT_SKILL_WRITE_SUMMARY_CHARS);
1385
- return normalized.ok ? { text: normalized.text, source: change.source } : this.hostChangeSummary(action, before, after, path, summary);
1386
- })();
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
+ })();
1387
1465
  let versions = null;
1388
1466
  try {
1389
1467
  const keep = this.limits.versionKeep ?? DEFAULT_SKILL_VERSION_KEEP;
@@ -1777,8 +1855,14 @@ export class SkillLibrary {
1777
1855
  return { ok: false, message: `创建过程中技能「${normalized}」被并发归档;残留标记已移除:等搬运完成后重试一次。` };
1778
1856
  }
1779
1857
  }
1780
- await this.audit(normalized, 'create', null, onDisk, 'created', undefined, result.unitId, options.unitHead, undefined, fenceHeld);
1781
- 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
+ }
1782
1866
  // Both warnings ride the normal success path (audit/event included) — a
1783
1867
  // durability warning must never skip the accounting.
1784
1868
  const warnings = [
@@ -3753,9 +3837,13 @@ export class SkillLibrary {
3753
3837
  if (op === undefined)
3754
3838
  return { ok: false, message: 'skill write plan is empty', outcomes: [] };
3755
3839
  if (plan.ops.length > 1) {
3756
- return { ok: false, message: 'multi-op skill write plans are not implemented in H1', outcomes: [] };
3840
+ return plan.summary === undefined || plan.summary === ''
3841
+ ? await this.applyMulti(plan)
3842
+ : await PLAN_SUMMARY.run(plan.summary, () => this.applyMulti(plan));
3757
3843
  }
3758
- const result = await this.applyOne(op, plan.origin);
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));
3759
3847
  const target = op.kind === 'createSkill' ? skillBodyTarget(op.skill) : op.target;
3760
3848
  const outcomes = result.ok && result.after !== undefined
3761
3849
  ? [{ op, target, after: result.after, version: result.after === null ? '' : contentHash(result.after) }]
@@ -3770,6 +3858,120 @@ export class SkillLibrary {
3770
3858
  ...(result.normalizedFrontmatterFields === undefined ? {} : { normalizedFrontmatterFields: result.normalizedFrontmatterFields }),
3771
3859
  };
3772
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
+ }
3773
3975
  async applyOne(op, origin) {
3774
3976
  switch (op.kind) {
3775
3977
  case 'createSkill':
@@ -3811,7 +4013,8 @@ export class SkillLibrary {
3811
4013
  if (badName)
3812
4014
  return { ok: false, message: badName };
3813
4015
  const dir = this.dirOf(name);
3814
- 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')))
3815
4018
  return { ok: false, message: `技能「${name}」不存在。` };
3816
4019
  const protection = await this.writeProtection(name, origin);
3817
4020
  if (protection)
@@ -3908,6 +4111,19 @@ export class SkillLibrary {
3908
4111
  const before = beforeProbe.value;
3909
4112
  let verdict = anchorVerdict(anchor, before);
3910
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
+ }
3911
4127
  if (verdict === 'match' && this.transact) {
3912
4128
  const ran = { done: false };
3913
4129
  try {
@@ -2,7 +2,7 @@
2
2
  * Plan-level write types for the single skill-write provider.
3
3
  *
4
4
  * This is NOT a second low-level intent layer: `skill-write-intent.ts` owns
5
- * create/replace/edit decisions and `mutation-unit.ts` owns the transaction.
5
+ * create/replace/edit decisions and `unit-kernel.ts` owns the transaction.
6
6
  * A plan is the domain-level unit the tool, approval and system writers share;
7
7
  * `SkillLibrary.apply(plan)` maps each op to the existing mutators/intent.
8
8
  *
@@ -216,7 +216,7 @@ export class SkillWriteService {
216
216
  // turn a landed write into a tool failure (K6).
217
217
  }
218
218
  }
219
- return actionResult(result);
219
+ return actionResult(result, plan);
220
220
  }
221
221
  async observeOutcomes(result, owner) {
222
222
  for (const outcome of result.outcomes) {
@@ -343,9 +343,15 @@ function notObserved() {
343
343
  return planRefusal('unobserved');
344
344
  }
345
345
  function anchorOf(version) { return { sha256: version }; }
346
- function actionResult(result) {
346
+ function actionResult(result, plan) {
347
347
  if (result.ok)
348
348
  return { ok: true, message: result.message, ...(result.noop === true ? { noop: true } : {}), ...(result.path === undefined ? {} : { path: result.path }), ...(result.normalizedFrontmatterFields === undefined ? {} : { normalizedFrontmatterFields: result.normalizedFrontmatterFields }) };
349
+ const only = plan?.ops.length === 1 ? plan.ops[0] : undefined;
350
+ const absentCreate = only !== undefined
351
+ && (only.kind === 'createSkill' || (only.kind === 'write' && only.target.relPath === '' && only.expect.kind === 'absent' && only.create !== false))
352
+ && (result.stale === true || /已存在|target appeared|changed after plan|concurrent modification/i.test(result.message));
353
+ if (absentCreate)
354
+ return { ok: false, code: 'SKILL_ALREADY_EXISTS', message: result.message };
349
355
  if (result.stale === true)
350
356
  return { ok: false, code: 'SKILL_STALE_VERSION', message: result.message };
351
357
  return { ok: false, code: 'SKILL_INVALID', message: result.message };
@@ -0,0 +1,47 @@
1
+ import type { EvolutionStateStorage } from './index.ts';
2
+ /**
3
+ * The assertion surface this suite needs. Vitest's `expect` satisfies it in-tree;
4
+ * a host with any other runner wraps its own in a few lines. Deliberately
5
+ * structural and minimal — the suite must not import a test runner.
6
+ */
7
+ export interface ConformanceAssert {
8
+ (actual: unknown): {
9
+ toBe(expected: unknown): void;
10
+ toEqual(expected: unknown): void;
11
+ toBeDefined(): void;
12
+ toBeUndefined(): void;
13
+ toBeNull(): void;
14
+ toContain(expected: unknown): void;
15
+ toHaveLength(length: number): void;
16
+ toBeGreaterThan(expected: number): void;
17
+ not: {
18
+ toBe(expected: unknown): void;
19
+ toContain(expected: unknown): void;
20
+ };
21
+ rejects: {
22
+ toThrow(expected?: unknown): Promise<void>;
23
+ };
24
+ };
25
+ }
26
+ /**
27
+ * The values a PROVIDER UNDER TEST may need to vary (U-2): a third-party medium can already hold
28
+ * records in the `c-…` namespace, and a strict schema may insist on a parseable `createdAt`. Every
29
+ * field defaults to the in-tree literals, so an existing caller's two-argument call is unchanged.
30
+ */
31
+ export interface ConformanceOptions {
32
+ /** Namespace for every pending record this run creates (default `'c-'`). */
33
+ idPrefix?: string;
34
+ /** Namespace for every claim id (default `'claim-'`). */
35
+ claimPrefix?: string;
36
+ /** The `createdAt` stamp every fixture record carries (default `'now'`). A provider whose
37
+ * schema requires a parseable time passes a real stamp here. */
38
+ createdAt?: string;
39
+ /** The review-state session the round-trip vector writes (default `'s-consistent'`). */
40
+ sessionId?: string;
41
+ /** The review-state session the ATTRIBUTION vector pins (default `attributionSessionId`). */
42
+ attributionSessionId?: string;
43
+ /** Namespace for the per-session cap vector's sessions (default `'s-cap-'`). */
44
+ reviewSessionPrefix?: string;
45
+ }
46
+ export declare function runStateProviderConsistency(provider: EvolutionStateStorage, assert: ConformanceAssert, options?: ConformanceOptions): Promise<void>;
47
+ //# sourceMappingURL=conformance.d.ts.map