@lmzhen/dsh-evolution-core 0.59.5 → 0.59.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -138,6 +138,8 @@ export interface MutationUnitOptions {
138
138
  readonly target: string;
139
139
  }[];
140
140
  }) => readonly string[];
141
+ /** Resolve logical target keys to the backend's canonical lock identity. */
142
+ targetKeyResolver?: (keys: readonly string[]) => Promise<readonly string[]> | readonly string[];
141
143
  /** Explicit escape for a caller that already holds the home fence (nested merge/skill write). */
142
144
  nested?: boolean;
143
145
  journal?: MutationJournalPort;
@@ -175,6 +177,7 @@ export declare class MutationUnit {
175
177
  private readonly lock;
176
178
  private readonly targetKeys;
177
179
  private readonly targetKeysForSnapshot;
180
+ private readonly targetKeyResolver;
178
181
  private readonly journal;
179
182
  private readonly snapshots;
180
183
  private readonly claim;
@@ -187,6 +190,7 @@ export declare class MutationUnit {
187
190
  private readonly now;
188
191
  private readonly journalId;
189
192
  constructor(options: MutationUnitOptions);
193
+ private resolveTargetKeys;
190
194
  preview(request: MutationRequest): MutationPreviewResult;
191
195
  apply(request: MutationRequest): Promise<MutationResult>;
192
196
  /** Recover every prepared snapshot known to the port; safe to call at boot. */
@@ -101,6 +101,7 @@ export class MutationUnit {
101
101
  lock;
102
102
  targetKeys;
103
103
  targetKeysForSnapshot;
104
+ targetKeyResolver;
104
105
  journal;
105
106
  snapshots;
106
107
  claim;
@@ -135,6 +136,11 @@ export class MutationUnit {
135
136
  const transact = options.transact;
136
137
  this.kernel = new WriteKernel({ io: this.io, ...(transact === undefined ? {} : { transact }), now: this.now });
137
138
  }
139
+ async resolveTargetKeys(keys) {
140
+ if (keys === undefined || this.targetKeyResolver === undefined)
141
+ return keys;
142
+ return await this.targetKeyResolver(keys);
143
+ }
138
144
  preview(request) {
139
145
  const validation = validateMutationRequest(request, this.limits);
140
146
  return {
@@ -156,7 +162,7 @@ export class MutationUnit {
156
162
  return await this.serial(async () => {
157
163
  let lease;
158
164
  try {
159
- lease = await this.lock.acquire(this.targetKeys);
165
+ lease = await this.lock.acquire(await this.resolveTargetKeys(this.targetKeys));
160
166
  }
161
167
  catch (error) {
162
168
  const code = error instanceof TransactionNotInvokedError ? 'transact-not-invoked' : 'unit-fence-failed';
@@ -302,7 +308,7 @@ export class MutationUnit {
302
308
  return await this.serial(async () => {
303
309
  let lease;
304
310
  try {
305
- lease = await this.lock.acquire(this.targetKeysForSnapshot?.(snapshot) ?? this.targetKeys);
311
+ lease = await this.lock.acquire(await this.resolveTargetKeys(this.targetKeysForSnapshot?.(snapshot) ?? this.targetKeys));
306
312
  }
307
313
  catch (error) {
308
314
  const code = error instanceof TransactionNotInvokedError ? 'transact-not-invoked' : 'unit-fence-failed';
@@ -360,7 +366,7 @@ export class MutationUnit {
360
366
  return await this.serial(async () => {
361
367
  let lease;
362
368
  try {
363
- lease = await this.lock.acquire(this.targetKeys);
369
+ lease = await this.lock.acquire(await this.resolveTargetKeys(this.targetKeys));
364
370
  }
365
371
  catch (error) {
366
372
  return { ok: false, unitId, dryRun: false, changed: [], errors: [{ code: 'lock-failed', message: error instanceof Error ? error.message : String(error) }] };
@@ -22,6 +22,8 @@ export interface SkillTarget {
22
22
  readonly skill: string;
23
23
  readonly relPath: string;
24
24
  readonly targetKey: string;
25
+ /** Canonical realpath-derived lock/observation identity, when the caller can resolve it. */
26
+ readonly identityKey?: string;
25
27
  }
26
28
  /** One authoritative read observation. */
27
29
  export type SkillObservation = {
@@ -55,11 +57,8 @@ export declare function skillBodyTarget(skill: string): SkillTarget;
55
57
  export declare function skillSupportTarget(skill: string, relPath: string): SkillTarget;
56
58
  /** Derive the version a write must observe for these current bytes. */
57
59
  export declare function skillVersionOf(content: string): SkillContentVersion;
58
- /**
59
- * Per-owner observation state. A WeakMap owner key keeps a collected session or
60
- * review task from retaining its reads; disposal blocks HMR from carrying stale
61
- * observations into a new implementation generation.
62
- */
60
+ /** Canonical realpath identity for an existing host path, matching SkillLibrary's lock key. */
61
+ export declare function skillHostIdentity(hostPath: string): string | undefined;
63
62
  export declare class SkillObservationStore {
64
63
  private byOwner;
65
64
  /**
@@ -12,6 +12,8 @@
12
12
  *
13
13
  * @module @lmzhen/dsh-evolution-core/skill-observation
14
14
  */
15
+ import { createHash } from 'node:crypto';
16
+ import { realpathSync } from 'node:fs';
15
17
  import { contentHash } from "./mutations.js";
16
18
  /**
17
19
  * Canonical target key. Skill names are trimmed; support paths are slash
@@ -67,6 +69,20 @@ function normalizeRelPath(relPath) {
67
69
  * review task from retaining its reads; disposal blocks HMR from carrying stale
68
70
  * observations into a new implementation generation.
69
71
  */
72
+ /** The key a target uses in an observation map; identity wins over the logical key. */
73
+ function observationKey(target) {
74
+ return target.identityKey ?? target.targetKey;
75
+ }
76
+ /** Canonical realpath identity for an existing host path, matching SkillLibrary's lock key. */
77
+ export function skillHostIdentity(hostPath) {
78
+ try {
79
+ const real = realpathSync.native(hostPath).replaceAll('\\', '/');
80
+ return 'skillpath:' + createHash('sha256').update(real).digest('hex');
81
+ }
82
+ catch {
83
+ return undefined;
84
+ }
85
+ }
70
86
  export class SkillObservationStore {
71
87
  byOwner = new WeakMap();
72
88
  /**
@@ -81,14 +97,14 @@ export class SkillObservationStore {
81
97
  reads = new Map();
82
98
  this.byOwner.set(owner, reads);
83
99
  }
84
- reads.set(target.targetKey, observation);
100
+ reads.set(observationKey(target), observation);
85
101
  }
86
102
  /**
87
103
  * Read the newest observation for one owner/target.
88
104
  * @returns the observation, or `undefined` when this owner never read it.
89
105
  */
90
106
  get(owner, target) {
91
- return this.byOwner.get(owner)?.get(target.targetKey);
107
+ return this.byOwner.get(owner)?.get(observationKey(target));
92
108
  }
93
109
  /**
94
110
  * Resolve the observation a writer may rely on.
@@ -41,6 +41,8 @@ import { SkillModel } from './skill-model.ts';
41
41
  import { type ExtractPlanDraft } from './extract-plan.ts';
42
42
  import { type MutationRecord } from './mutations.ts';
43
43
  import { type SkillWriteIntent, type SkillWriteRefusalReason } from './skill-write-intent.ts';
44
+ import type { SkillWritePlan, SkillWriteResult } from './skill-write-plan.ts';
45
+ import { type SkillTarget } from './skill-observation.ts';
44
46
  import { type RevisionAnchor, type RevisionFile } from './skill-revision.ts';
45
47
  import { type ChangeSummary, type UnitHead, type HistoryFence, type SkillVersion } from './skill-history.ts';
46
48
  import { type SkillHealthAssessment, type SkillHealthThresholds } from './skill-health.ts';
@@ -120,6 +122,8 @@ export interface SkillActionResult {
120
122
  stale?: true;
121
123
  /** The locked read's verdict for the caller's anchor. */
122
124
  anchor?: AnchorVerdict;
125
+ /** Committed bytes of this write; null for a removal. */
126
+ after?: string | null;
123
127
  }
124
128
  /**
125
129
  * One section move of a restructure proposal (008 batch B): a body section
@@ -391,6 +395,26 @@ export declare class SkillLibrary {
391
395
  private unitHeadForOps;
392
396
  /** Transitional: serialize one target even while the root serial remains. */
393
397
  private withTarget;
398
+ /** Canonicalize several logical target keys for one lock acquisition. */
399
+ private canonicalLockKeys;
400
+ /**
401
+ * Attach the canonical realpath identity to one observation target.
402
+ * @param target - logical skill target.
403
+ * @returns the target with `identityKey`; the logical targetKey is unchanged.
404
+ */
405
+ identify(target: SkillTarget): Promise<SkillTarget>;
406
+ /**
407
+ * Canonical in-process lock identity for one skill target key.
408
+ *
409
+ * A logical `skill::name::path` key is resolved through realpath (or the
410
+ * nearest existing ancestor for a not-yet-created file) and hashed, so two
411
+ * spellings/symlinks of the same host file share one promise-lock queue. The
412
+ * logical targetKey stays the observation/approval key until the observation
413
+ * resolver phase; this method only fixes the provider lock identity.
414
+ * @param targetKey - the family's logical skill target key.
415
+ * @returns the canonical lock key, or the input for non-skill keys.
416
+ */
417
+ private canonicalTargetKey;
394
418
  private withMutationLock;
395
419
  /** The one MutationUnit constructor: storage ports are fixed here, callers pass the rest. */
396
420
  private commitUnit;
@@ -772,6 +796,18 @@ export declare class SkillLibrary {
772
796
  private restoreFromArchiveCore;
773
797
  /** Result of the low-level CAS primitive. It intentionally has no audit/event. */
774
798
  writeFileCas(rawName: string, filePath: string, intent: SkillWriteIntent): Promise<SkillFileCasResult>;
799
+ /**
800
+ * Execute one plan-level write through the existing mutators.
801
+ *
802
+ * H1 deliberately supports one op only: it is the stable seam the tool and
803
+ * approval will move onto, while the multi-op UnitTransaction path is the
804
+ * next phase. Refusing a partial plan is safer than committing half of it.
805
+ * @param plan - origin plus the single operation to apply.
806
+ * @returns the action result; `outcomes` stays empty until the provider
807
+ * returns before/after/version in the next phase.
808
+ */
809
+ apply(plan: SkillWritePlan): Promise<SkillWriteResult>;
810
+ private applyOne;
775
811
  writeSupportFile(rawName: string, filePath: string, content: string, origin?: WriteOrigin, anchor?: WriteAnchor): Promise<SkillActionResult>;
776
812
  private writeSupportFileCore;
777
813
  removeSupportFile(rawName: string, filePath: string, origin?: WriteOrigin, anchor?: WriteAnchor, unitId?: string): Promise<SkillActionResult>;
@@ -33,6 +33,8 @@
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';
37
+ import { createHash } from 'node:crypto';
36
38
  import { authorityFrom } from "./write-authority.js";
37
39
  import { resolveCitations } from "./citations.js";
38
40
  import { scanContentThreats } from "./threats.js";
@@ -58,7 +60,7 @@ import { projectExtractBodies } from "./extract-plan.js";
58
60
  import { diffFindings } from "./skill-lint.js";
59
61
  import { contentHash, loadMutations, recordMutation } from "./mutations.js";
60
62
  import { decideSkillWrite } from "./skill-write-intent.js";
61
- import { skillNamespaceKey } from "./skill-observation.js";
63
+ import { skillBodyTarget, skillNamespaceKey } from "./skill-observation.js";
62
64
  import { SkillTargetLocks } from "./skill-target-locks.js";
63
65
  import { SkillRootGate } from "./skill-root-gate.js";
64
66
  import { revisionFingerprint, revisionSupportDigest } from "./skill-revision.js";
@@ -564,13 +566,77 @@ export class SkillLibrary {
564
566
  }
565
567
  /** Transitional: serialize one target even while the root serial remains. */
566
568
  async withTarget(targetKey, task) {
567
- return await this.targetLocks.withLock(targetKey, task);
569
+ return await this.targetLocks.withLock(await this.canonicalTargetKey(targetKey), task);
570
+ }
571
+ /** Canonicalize several logical target keys for one lock acquisition. */
572
+ async canonicalLockKeys(keys) {
573
+ return await Promise.all(keys.map(key => this.canonicalTargetKey(key)));
574
+ }
575
+ /**
576
+ * Attach the canonical realpath identity to one observation target.
577
+ * @param target - logical skill target.
578
+ * @returns the target with `identityKey`; the logical targetKey is unchanged.
579
+ */
580
+ async identify(target) {
581
+ const key = target.relPath === '' ? 'skill::' + target.skill : 'skill::' + target.skill + '::' + target.relPath;
582
+ return { ...target, identityKey: await this.canonicalTargetKey(key) };
583
+ }
584
+ /**
585
+ * Canonical in-process lock identity for one skill target key.
586
+ *
587
+ * A logical `skill::name::path` key is resolved through realpath (or the
588
+ * nearest existing ancestor for a not-yet-created file) and hashed, so two
589
+ * spellings/symlinks of the same host file share one promise-lock queue. The
590
+ * logical targetKey stays the observation/approval key until the observation
591
+ * resolver phase; this method only fixes the provider lock identity.
592
+ * @param targetKey - the family's logical skill target key.
593
+ * @returns the canonical lock key, or the input for non-skill keys.
594
+ */
595
+ async canonicalTargetKey(targetKey) {
596
+ if (!targetKey.startsWith('skill::'))
597
+ return targetKey;
598
+ // Fake/virtual IO roots do not exist on this host: fall back to the logical key
599
+ // so two library instances over the same virtual root still share one queue.
600
+ try {
601
+ await realpathFs(this.root);
602
+ }
603
+ catch {
604
+ return targetKey;
605
+ }
606
+ const rest = targetKey.slice('skill::'.length);
607
+ const [name, ...tail] = rest.split('::');
608
+ if (name === undefined || name === '')
609
+ return targetKey;
610
+ const rel = tail.join('::');
611
+ const dir = this.dirOf(name);
612
+ const namespace = rel === '*';
613
+ const body = rel === '';
614
+ const path = namespace ? dir : body ? join(dir, 'SKILL.md') : join(dir, ...rel.replace(/\\/g, '/').split('/').filter(Boolean));
615
+ let cursor = path;
616
+ const suffix = [];
617
+ let identity;
618
+ while (true) {
619
+ try {
620
+ identity = join(await realpathFs(cursor), ...suffix.reverse());
621
+ break;
622
+ }
623
+ catch {
624
+ const parent = dirname(cursor);
625
+ if (parent === cursor)
626
+ return targetKey;
627
+ suffix.push(basename(cursor));
628
+ cursor = parent;
629
+ }
630
+ }
631
+ const digest = createHash('sha256').update(identity.replace(/\\/g, '/')).digest('hex');
632
+ return 'skillpath:' + digest + (namespace ? '::*' : '');
568
633
  }
569
634
  async withMutationLock(task, targetKeys) {
570
635
  // Fail closed: a missing authority/lock is an assembly error, not a reason to run
571
636
  // the write outside the fence. The old catch-and-fallback inverted this guard: the
572
637
  // "refusing an unfenced production write" error itself took the fallback path.
573
- const lease = await this.lockPort().acquire(targetKeys);
638
+ const keys = targetKeys === undefined ? undefined : await this.canonicalLockKeys(targetKeys);
639
+ const lease = await this.lockPort().acquire(keys);
574
640
  try {
575
641
  return await task();
576
642
  }
@@ -584,6 +650,7 @@ export class SkillLibrary {
584
650
  io: this.io,
585
651
  journal: unitJournalPort(this.io, dirname(this.root)),
586
652
  snapshots: unitSnapshotPort(this.io, dirname(this.root)),
653
+ targetKeyResolver: keys => this.canonicalLockKeys(keys),
587
654
  ...options,
588
655
  });
589
656
  }
@@ -1722,6 +1789,7 @@ export class SkillLibrary {
1722
1789
  ok: true,
1723
1790
  message: `已创建技能「${normalized}」。${warnings.length === 0 ? '' : ` (警告:${warnings.join(';')})`}`,
1724
1791
  path: dir,
1792
+ after: onDisk,
1725
1793
  ...(norm.changed ? { normalizedFrontmatterFields: norm.fields } : {}),
1726
1794
  };
1727
1795
  }
@@ -1812,7 +1880,7 @@ export class SkillLibrary {
1812
1880
  }
1813
1881
  const warning = result.warnings === undefined || result.warnings.length === 0 ? '' : ` (警告:写入已落盘,但目录 fsync 失败 —— 持久性未确认:${result.warnings.join(';')})`;
1814
1882
  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 } : {}) };
1883
+ return { ok: true, message: `技能「${name}」已更新。${warning}${retention === null ? '' : '\n' + retention}`, path: dir, after: onDisk, ...(prepared.norm.changed ? { normalizedFrontmatterFields: prepared.norm.fields } : {}) };
1816
1884
  }
1817
1885
  async patch(rawName, oldString, newString, filePath = '', replaceAll = false, origin = this.authority.origin, anchor) {
1818
1886
  await this.ensureRecovered();
@@ -1883,11 +1951,11 @@ export class SkillLibrary {
1883
1951
  const next = `${header}${nextBody}`;
1884
1952
  const finalMd = block.nl === '\r\n' ? next.replace(/\n/g, '\r\n') : next;
1885
1953
  if (finalMd.trimEnd() === md.trimEnd())
1886
- return { ok: true, message: `技能「${name}」未变更:章节内容一致,未写入。`, noop: true, path: dir };
1954
+ return { ok: true, message: `技能「${name}」未变更:章节内容一致,未写入。`, noop: true, path: dir, after: md };
1887
1955
  const result = await this.update(name, finalMd, origin, { sha256: contentHash(md) });
1888
1956
  if (!result.ok)
1889
1957
  return result;
1890
- return { ok: true, message: `已更新「${name}」的「${edit.heading}」章节(正文 ${md.length} → ${finalMd.length} 字符)。`, path: dir };
1958
+ return { ok: true, message: `已更新「${name}」的「${edit.heading}」章节(正文 ${md.length} → ${finalMd.length} 字符)。`, path: dir, ...(result.after === undefined ? {} : { after: result.after }) };
1891
1959
  }
1892
1960
  async patchCore(name, oldString, newString, filePath, replaceAll, origin, anchor) {
1893
1961
  // P1-1 (v14): patch was the ONE path-building mutator without the name
@@ -1988,7 +2056,7 @@ export class SkillLibrary {
1988
2056
  // trimEnd()+'\n'), so the audit afterHash is replay-identical to the file.
1989
2057
  const onDisk = writeContent.trimEnd() + '\n';
1990
2058
  return {
1991
- result: { ok: true, message: `技能「${name}」已修补(${patchLabel})。${patchNote}${capAdvisory}`, path: dir, ...(normalizedFields ? { normalizedFrontmatterFields: normalizedFields } : {}) },
2059
+ result: { ok: true, message: `技能「${name}」已修补(${patchLabel})。${patchNote}${capAdvisory}`, path: dir, after: onDisk, ...(normalizedFields ? { normalizedFrontmatterFields: normalizedFields } : {}) },
1992
2060
  write: onDisk,
1993
2061
  audit: { skillName: name, action: 'patch', before: md, after: onDisk, summary: `patched ${patchLabel}` },
1994
2062
  event: { action: 'patch', name, skillDir: dir },
@@ -3670,6 +3738,69 @@ export class SkillLibrary {
3670
3738
  return { ok: true, message: 'skill file written', path: target };
3671
3739
  }));
3672
3740
  }
3741
+ /**
3742
+ * Execute one plan-level write through the existing mutators.
3743
+ *
3744
+ * H1 deliberately supports one op only: it is the stable seam the tool and
3745
+ * approval will move onto, while the multi-op UnitTransaction path is the
3746
+ * next phase. Refusing a partial plan is safer than committing half of it.
3747
+ * @param plan - origin plus the single operation to apply.
3748
+ * @returns the action result; `outcomes` stays empty until the provider
3749
+ * returns before/after/version in the next phase.
3750
+ */
3751
+ async apply(plan) {
3752
+ const op = plan.ops[0];
3753
+ if (op === undefined)
3754
+ return { ok: false, message: 'skill write plan is empty', outcomes: [] };
3755
+ if (plan.ops.length > 1) {
3756
+ return { ok: false, message: 'multi-op skill write plans are not implemented in H1', outcomes: [] };
3757
+ }
3758
+ const result = await this.applyOne(op, plan.origin);
3759
+ const target = op.kind === 'createSkill' ? skillBodyTarget(op.skill) : op.target;
3760
+ const outcomes = result.ok && result.after !== undefined
3761
+ ? [{ op, target, after: result.after, version: result.after === null ? '' : contentHash(result.after) }]
3762
+ : [];
3763
+ return {
3764
+ ok: result.ok,
3765
+ message: result.message,
3766
+ outcomes,
3767
+ ...(result.stale === true ? { stale: true } : {}),
3768
+ ...(result.noop === true ? { noop: true } : {}),
3769
+ ...(result.path === undefined ? {} : { path: result.path }),
3770
+ ...(result.normalizedFrontmatterFields === undefined ? {} : { normalizedFrontmatterFields: result.normalizedFrontmatterFields }),
3771
+ };
3772
+ }
3773
+ async applyOne(op, origin) {
3774
+ switch (op.kind) {
3775
+ case 'createSkill':
3776
+ return await this.create(op.skill, op.content, origin, op.managed === true ? { managed: true } : {});
3777
+ case 'write': {
3778
+ if (op.target.relPath === '') {
3779
+ if (op.expect.kind === 'absent') {
3780
+ if (op.create !== false)
3781
+ return await this.create(op.target.skill, op.content, origin);
3782
+ return await this.update(op.target.skill, op.content, origin, { absent: true });
3783
+ }
3784
+ return await this.update(op.target.skill, op.content, origin, { sha256: op.expect.version });
3785
+ }
3786
+ const anchor = op.expect.kind === 'absent'
3787
+ ? { absent: true }
3788
+ : { sha256: op.expect.version };
3789
+ return await this.writeSupportFile(op.target.skill, op.target.relPath, op.content, origin, anchor);
3790
+ }
3791
+ case 'patch': {
3792
+ const anchor = op.expect.kind === 'absent' ? { absent: true } : { sha256: op.expect.version };
3793
+ return await this.patch(op.target.skill, op.oldString, op.newString, op.target.relPath, op.replaceAll, origin, anchor);
3794
+ }
3795
+ case 'patchSection':
3796
+ return await this.patchSection(op.target.skill, op.section, origin, op.expect.kind === 'absent' ? { absent: true } : { sha256: op.expect.version });
3797
+ case 'remove':
3798
+ if (op.target.relPath === '') {
3799
+ return { ok: false, message: 'removing SKILL.md must use the structural archive path, not a plan remove' };
3800
+ }
3801
+ return await this.removeSupportFile(op.target.skill, op.target.relPath, origin, op.expect.kind === 'absent' ? { absent: true } : { sha256: op.expect.version }, op.unitId);
3802
+ }
3803
+ }
3673
3804
  async writeSupportFile(rawName, filePath, content, origin = this.authority.origin, anchor) {
3674
3805
  const name = rawName.trim();
3675
3806
  const key = 'skill::' + name + '::' + filePath.replace(/\\/g, '/');
@@ -3711,7 +3842,7 @@ export class SkillLibrary {
3711
3842
  return { ok: false, message: `支撑文件「${filePath}」的内容超过 ${this.limits.maxSkillContentChars} 个字符。${CONTENT_SPLIT_HINT}` };
3712
3843
  }
3713
3844
  if (current !== null && content.trimEnd() === current.trimEnd()) {
3714
- return { ok: true, message: `支撑文件「${filePath}」未变更:提供的内容与当前文件一致,未写入。`, noop: true, path: target };
3845
+ return { ok: true, message: `支撑文件「${filePath}」未变更:提供的内容与当前文件一致,未写入。`, noop: true, path: target, after: current };
3715
3846
  }
3716
3847
  const unit = this.commitUnit({
3717
3848
  limits: { maxSkillFileBytes: Number.MAX_SAFE_INTEGER, maxSkillContentChars: Number.MAX_SAFE_INTEGER },
@@ -3743,7 +3874,7 @@ export class SkillLibrary {
3743
3874
  if (!result.ok)
3744
3875
  return { ok: false, message: result.errors.map(error => error.message).join(';') };
3745
3876
  const warning = result.warnings === undefined || result.warnings.length === 0 ? '' : ` (警告:写入已落盘,但目录 fsync 失败 —— 持久性未确认:${result.warnings.join(';')})`;
3746
- return { ok: true, message: `支撑文件「${filePath}」已写入「${name}」。${capAdvisory}${warning}`, path: target };
3877
+ return { ok: true, message: `支撑文件「${filePath}」已写入「${name}」。${capAdvisory}${warning}`, path: target, after: content };
3747
3878
  }
3748
3879
  async removeSupportFile(rawName, filePath, origin = this.authority.origin, anchor, unitId) {
3749
3880
  const key = 'skill::' + rawName.trim() + '::' + filePath.replace(/\\/g, '/');
@@ -3803,7 +3934,7 @@ export class SkillLibrary {
3803
3934
  return anchorRefusalFile(name, filePath, verdict);
3804
3935
  await this.audit(name, 'remove_file', lockedBefore, null, `removed ${filePath}`, filePath, unitId);
3805
3936
  this.notifyMutation({ action: 'remove_file', name, skillDir: dir, file: target });
3806
- return { ok: true, message: `支撑文件「${filePath}」已从「${name}」移除。`, path: target };
3937
+ return { ok: true, message: `支撑文件「${filePath}」已从「${name}」移除。`, path: target, after: null };
3807
3938
  }
3808
3939
  /**
3809
3940
  * 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 `mutation-unit.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
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=skill-write-plan.js.map
@@ -1,5 +1,6 @@
1
- import type { SkillLibrary, WriteOrigin } from './skill-store.ts';
1
+ import type { SkillLibrary, SkillSectionEdit, WriteOrigin } from './skill-store.ts';
2
2
  import type { SkillObservationStore } from './skill-observation.ts';
3
+ import type { SkillWritePlan } from './skill-write-plan.ts';
3
4
  /** Exact execution identity for observations. */
4
5
  export type SkillWriteOwner = object;
5
6
  /** Stable failure codes for the future model-facing error map. */
@@ -10,6 +11,17 @@ export type SkillWriteServiceResult = {
10
11
  readonly message: string;
11
12
  readonly noop?: boolean;
12
13
  readonly content?: string | null;
14
+ readonly path?: string;
15
+ readonly normalizedFrontmatterFields?: readonly string[];
16
+ } | {
17
+ readonly ok: false;
18
+ readonly code: SkillWriteErrorCode;
19
+ readonly message: string;
20
+ };
21
+ /** Result of planning one write action. */
22
+ export type SkillWritePlanResult = {
23
+ readonly ok: true;
24
+ readonly plan: SkillWritePlan;
13
25
  } | {
14
26
  readonly ok: false;
15
27
  readonly code: SkillWriteErrorCode;
@@ -24,7 +36,6 @@ export type SkillWriteServiceResult = {
24
36
  export declare class SkillWriteService {
25
37
  private readonly library;
26
38
  private readonly observations;
27
- private readonly locks;
28
39
  constructor(library: SkillLibrary, observations: SkillObservationStore);
29
40
  /**
30
41
  * Read SKILL.md and record present/absent for this owner.
@@ -41,6 +52,77 @@ export declare class SkillWriteService {
41
52
  * @returns the bytes, or null when absent.
42
53
  */
43
54
  readSupport(owner: SkillWriteOwner, name: string, filePath: string): Promise<string | null>;
55
+ /**
56
+ * Plan a create. Creation is createIfAbsent by definition and needs no prior
57
+ * read; the provider's `create` path keeps managed/protection semantics.
58
+ * @param owner - writer identity (unused for create, kept for a uniform API).
59
+ * @param name - skill name.
60
+ * @param content - full body.
61
+ * @param managed - add the managed marker (non-foreground origin).
62
+ * @returns the plan or a typed refusal.
63
+ */
64
+ planCreate(owner: SkillWriteOwner, name: string, content: string, origin?: WriteOrigin, managed?: boolean): Promise<SkillWritePlanResult>;
65
+ /**
66
+ * Plan a full body replacement from this owner's observation.
67
+ * @param owner - exact writer.
68
+ * @param name - skill name.
69
+ * @param content - next body.
70
+ * @param origin - write face.
71
+ * @returns the plan or a typed refusal.
72
+ */
73
+ planUpdate(owner: SkillWriteOwner, name: string, content: string, origin?: WriteOrigin): Promise<SkillWritePlanResult>;
74
+ /**
75
+ * Plan a literal patch against a body or support target.
76
+ *
77
+ * A section patch always targets the body and ignores `filePath`; that is the
78
+ * same contract the library has always had, but now it is explicit in the
79
+ * plan instead of a tool branch.
80
+ * @param owner - exact writer.
81
+ * @param name - skill name.
82
+ * @param input - literal edit or section edit.
83
+ * @param origin - write face.
84
+ * @returns the plan or a typed refusal.
85
+ */
86
+ planPatch(owner: SkillWriteOwner, name: string, input: {
87
+ readonly oldString?: string;
88
+ readonly newString?: string;
89
+ readonly replaceAll?: boolean;
90
+ readonly filePath?: string;
91
+ readonly section?: SkillSectionEdit;
92
+ }, origin?: WriteOrigin): Promise<SkillWritePlanResult>;
93
+ /**
94
+ * Plan a full support-file write. A newly observed/absent file is
95
+ * createIfAbsent; an already observed file is replaceIfVersion. An unread
96
+ * existing file is refused instead of overwritten.
97
+ * @param owner - exact writer.
98
+ * @param name - skill name.
99
+ * @param filePath - support path.
100
+ * @param content - next bytes.
101
+ * @param origin - write face.
102
+ * @returns the plan or a typed refusal.
103
+ */
104
+ planWriteSupport(owner: SkillWriteOwner, name: string, filePath: string, content: string, origin?: WriteOrigin): Promise<SkillWritePlanResult>;
105
+ /**
106
+ * Plan removing one support file from this owner's observation.
107
+ * @param owner - exact writer.
108
+ * @param name - skill name.
109
+ * @param filePath - support path.
110
+ * @param origin - write face.
111
+ * @returns the plan or a typed refusal.
112
+ */
113
+ planRemoveSupport(owner: SkillWriteOwner, name: string, filePath: string, origin?: WriteOrigin): Promise<SkillWritePlanResult>;
114
+ /**
115
+ * Apply one plan through the provider and record the committed result for
116
+ * this owner. The re-read is temporary H2 bookkeeping; H5 replaces it with
117
+ * the provider's `SkillWriteOutcome`, so a post-commit read failure can never
118
+ * turn a landed write into a tool failure.
119
+ * @param plan - the write plan.
120
+ * @param owner - exact writer identity; omitted by internal callers that do
121
+ * not own observations.
122
+ * @returns the service-level result.
123
+ */
124
+ apply(plan: SkillWritePlan, owner?: SkillWriteOwner): Promise<SkillWriteServiceResult>;
125
+ private observeOutcomes;
44
126
  /**
45
127
  * Replace SKILL.md only when this owner observed its current version.
46
128
  * @param owner - exact writer identity.