@lmzhen/dsh-evolution-core 0.59.4 → 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.
- package/lib/{mutation-storage-adapter-z1_hyrQn.js → mutation-storage-adapter-Cq1bmS1E.js} +8 -3
- package/lib/skills.js +488 -107
- package/lib/types/mutation-unit.d.ts +4 -0
- package/lib/types/mutation-unit.js +9 -3
- package/lib/types/skill-observation.d.ts +4 -5
- package/lib/types/skill-observation.js +18 -2
- package/lib/types/skill-store.d.ts +37 -1
- package/lib/types/skill-store.js +147 -13
- package/lib/types/skill-write-plan.d.ts +80 -0
- package/lib/types/skill-write-plan.js +2 -0
- package/lib/types/skill-write-service.d.ts +84 -2
- package/lib/types/skill-write-service.js +207 -34
- package/lib/types/skills.d.ts +2 -0
- package/lib/types/skills.js +2 -0
- package/lib/types/system-skill-writer.d.ts +21 -0
- package/lib/types/system-skill-writer.js +15 -0
- package/lib/write.js +1 -1
- package/package.json +3 -3
|
@@ -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
|
-
|
|
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
|
|
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
|
|
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;
|
|
@@ -645,7 +669,7 @@ export declare class SkillLibrary {
|
|
|
645
669
|
* @param origin - write face.
|
|
646
670
|
* @returns the normalized result, with before/after body sizes.
|
|
647
671
|
*/
|
|
648
|
-
patchSection(rawName: string, edit: SkillSectionEdit, origin?: WriteOrigin): Promise<SkillActionResult>;
|
|
672
|
+
patchSection(rawName: string, edit: SkillSectionEdit, origin?: WriteOrigin, anchor?: WriteAnchor): Promise<SkillActionResult>;
|
|
649
673
|
private patchSectionCore;
|
|
650
674
|
private patchCore;
|
|
651
675
|
/**
|
|
@@ -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>;
|
package/lib/types/skill-store.js
CHANGED
|
@@ -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
|
|
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();
|
|
@@ -1834,11 +1902,11 @@ export class SkillLibrary {
|
|
|
1834
1902
|
* @param origin - write face.
|
|
1835
1903
|
* @returns the normalized result, with before/after body sizes.
|
|
1836
1904
|
*/
|
|
1837
|
-
async patchSection(rawName, edit, origin = this.authority.origin) {
|
|
1905
|
+
async patchSection(rawName, edit, origin = this.authority.origin, anchor) {
|
|
1838
1906
|
await this.ensureRecovered();
|
|
1839
|
-
return await this.patchSectionCore(rawName.trim(), edit, origin);
|
|
1907
|
+
return await this.patchSectionCore(rawName.trim(), edit, origin, anchor);
|
|
1840
1908
|
}
|
|
1841
|
-
async patchSectionCore(name, edit, origin) {
|
|
1909
|
+
async patchSectionCore(name, edit, origin, anchor) {
|
|
1842
1910
|
const badName = this.badName(name);
|
|
1843
1911
|
if (badName)
|
|
1844
1912
|
return { ok: false, message: badName };
|
|
@@ -1855,6 +1923,9 @@ export class SkillLibrary {
|
|
|
1855
1923
|
}
|
|
1856
1924
|
if (md === null)
|
|
1857
1925
|
return { ok: false, message: `技能「${name}」不存在。` };
|
|
1926
|
+
const verdict = anchorVerdict(anchor, md);
|
|
1927
|
+
if (verdict !== 'match')
|
|
1928
|
+
return anchorRefusalFile(name, 'SKILL.md', verdict);
|
|
1858
1929
|
const block = frontmatterBlock(md);
|
|
1859
1930
|
if (!block)
|
|
1860
1931
|
return { ok: false, message: 'SKILL.md 没有有效的 frontmatter;拒绝章节改写。' };
|
|
@@ -1880,11 +1951,11 @@ export class SkillLibrary {
|
|
|
1880
1951
|
const next = `${header}${nextBody}`;
|
|
1881
1952
|
const finalMd = block.nl === '\r\n' ? next.replace(/\n/g, '\r\n') : next;
|
|
1882
1953
|
if (finalMd.trimEnd() === md.trimEnd())
|
|
1883
|
-
return { ok: true, message: `技能「${name}」未变更:章节内容一致,未写入。`, noop: true, path: dir };
|
|
1954
|
+
return { ok: true, message: `技能「${name}」未变更:章节内容一致,未写入。`, noop: true, path: dir, after: md };
|
|
1884
1955
|
const result = await this.update(name, finalMd, origin, { sha256: contentHash(md) });
|
|
1885
1956
|
if (!result.ok)
|
|
1886
1957
|
return result;
|
|
1887
|
-
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 }) };
|
|
1888
1959
|
}
|
|
1889
1960
|
async patchCore(name, oldString, newString, filePath, replaceAll, origin, anchor) {
|
|
1890
1961
|
// P1-1 (v14): patch was the ONE path-building mutator without the name
|
|
@@ -1985,7 +2056,7 @@ export class SkillLibrary {
|
|
|
1985
2056
|
// trimEnd()+'\n'), so the audit afterHash is replay-identical to the file.
|
|
1986
2057
|
const onDisk = writeContent.trimEnd() + '\n';
|
|
1987
2058
|
return {
|
|
1988
|
-
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 } : {}) },
|
|
1989
2060
|
write: onDisk,
|
|
1990
2061
|
audit: { skillName: name, action: 'patch', before: md, after: onDisk, summary: `patched ${patchLabel}` },
|
|
1991
2062
|
event: { action: 'patch', name, skillDir: dir },
|
|
@@ -3667,6 +3738,69 @@ export class SkillLibrary {
|
|
|
3667
3738
|
return { ok: true, message: 'skill file written', path: target };
|
|
3668
3739
|
}));
|
|
3669
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
|
+
}
|
|
3670
3804
|
async writeSupportFile(rawName, filePath, content, origin = this.authority.origin, anchor) {
|
|
3671
3805
|
const name = rawName.trim();
|
|
3672
3806
|
const key = 'skill::' + name + '::' + filePath.replace(/\\/g, '/');
|
|
@@ -3708,7 +3842,7 @@ export class SkillLibrary {
|
|
|
3708
3842
|
return { ok: false, message: `支撑文件「${filePath}」的内容超过 ${this.limits.maxSkillContentChars} 个字符。${CONTENT_SPLIT_HINT}` };
|
|
3709
3843
|
}
|
|
3710
3844
|
if (current !== null && content.trimEnd() === current.trimEnd()) {
|
|
3711
|
-
return { ok: true, message: `支撑文件「${filePath}」未变更:提供的内容与当前文件一致,未写入。`, noop: true, path: target };
|
|
3845
|
+
return { ok: true, message: `支撑文件「${filePath}」未变更:提供的内容与当前文件一致,未写入。`, noop: true, path: target, after: current };
|
|
3712
3846
|
}
|
|
3713
3847
|
const unit = this.commitUnit({
|
|
3714
3848
|
limits: { maxSkillFileBytes: Number.MAX_SAFE_INTEGER, maxSkillContentChars: Number.MAX_SAFE_INTEGER },
|
|
@@ -3740,7 +3874,7 @@ export class SkillLibrary {
|
|
|
3740
3874
|
if (!result.ok)
|
|
3741
3875
|
return { ok: false, message: result.errors.map(error => error.message).join(';') };
|
|
3742
3876
|
const warning = result.warnings === undefined || result.warnings.length === 0 ? '' : ` (警告:写入已落盘,但目录 fsync 失败 —— 持久性未确认:${result.warnings.join(';')})`;
|
|
3743
|
-
return { ok: true, message: `支撑文件「${filePath}」已写入「${name}」。${capAdvisory}${warning}`, path: target };
|
|
3877
|
+
return { ok: true, message: `支撑文件「${filePath}」已写入「${name}」。${capAdvisory}${warning}`, path: target, after: content };
|
|
3744
3878
|
}
|
|
3745
3879
|
async removeSupportFile(rawName, filePath, origin = this.authority.origin, anchor, unitId) {
|
|
3746
3880
|
const key = 'skill::' + rawName.trim() + '::' + filePath.replace(/\\/g, '/');
|
|
@@ -3800,7 +3934,7 @@ export class SkillLibrary {
|
|
|
3800
3934
|
return anchorRefusalFile(name, filePath, verdict);
|
|
3801
3935
|
await this.audit(name, 'remove_file', lockedBefore, null, `removed ${filePath}`, filePath, unitId);
|
|
3802
3936
|
this.notifyMutation({ action: 'remove_file', name, skillDir: dir, file: target });
|
|
3803
|
-
return { ok: true, message: `支撑文件「${filePath}」已从「${name}」移除。`, path: target };
|
|
3937
|
+
return { ok: true, message: `支撑文件「${filePath}」已从「${name}」移除。`, path: target, after: null };
|
|
3804
3938
|
}
|
|
3805
3939
|
/**
|
|
3806
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
|