@lmzhen/dsh-evolution-core 0.59.2 → 0.59.3
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/authority-plugin.js +7 -4
- package/lib/{extract-plan-BxDhKSki.js → extract-plan-D3ALlAmN.js} +2 -2
- package/lib/extract.js +4 -4
- package/lib/index.js +9 -9
- package/lib/io-node.js +1 -1
- package/lib/{mutation-authority-Du-ON0NY.js → mutation-authority-CZpc9F20.js} +222 -4
- package/lib/{mutation-storage-adapter-7R3ra0wj.js → mutation-storage-adapter-z1_hyrQn.js} +10 -6
- package/lib/{mutations-mvTnWkua.js → mutations-Y-wKod7W.js} +2 -2
- package/lib/{quality-CREp6s1G.js → quality-NPGr3VzA.js} +3 -3
- package/lib/{review-context-CW_kJAzn.js → review-context-yNiZadPw.js} +1 -1
- package/lib/{skill-history-YX84wO20.js → skill-history-BvLWFoOo.js} +2 -2
- package/lib/skills.js +1023 -189
- package/lib/types/authority-plugin.d.ts +7 -1
- package/lib/types/authority-plugin.js +10 -2
- package/lib/types/authority.d.ts +49 -0
- package/lib/types/authority.js +194 -0
- package/lib/types/events.d.ts +2 -0
- package/lib/types/mutation-authority.d.ts +31 -2
- package/lib/types/mutation-authority.js +45 -1
- package/lib/types/mutation-unit.d.ts +23 -1
- package/lib/types/mutation-unit.js +7 -3
- package/lib/types/skill-observation-source.d.ts +26 -0
- package/lib/types/skill-observation-source.js +56 -0
- package/lib/types/skill-observation.d.ts +87 -0
- package/lib/types/skill-observation.js +110 -0
- package/lib/types/skill-root-gate.d.ts +40 -0
- package/lib/types/skill-root-gate.js +98 -0
- package/lib/types/skill-store.d.ts +22 -3
- package/lib/types/skill-store.js +437 -217
- package/lib/types/skill-target-locks.d.ts +39 -0
- package/lib/types/skill-target-locks.js +64 -0
- package/lib/types/skill-write-intent.d.ts +63 -0
- package/lib/types/skill-write-intent.js +104 -0
- package/lib/types/skill-write-service.d.ts +85 -0
- package/lib/types/skill-write-service.js +180 -0
- package/lib/types/skills.d.ts +6 -0
- package/lib/types/skills.js +6 -0
- package/lib/{usage-DrczLTP4.js → usage-D7yHG2Cb.js} +2 -2
- package/lib/write.js +3 -3
- package/package.json +3 -3
- package/lib/{io-GxghO3Ip.js → io-Cpa8wuvj.js} +1 -1
package/lib/types/skill-store.js
CHANGED
|
@@ -57,6 +57,10 @@ import { pruneTreeChangeUnits, unitJournalPort, unitSnapshotPort } from "./mutat
|
|
|
57
57
|
import { projectExtractBodies } from "./extract-plan.js";
|
|
58
58
|
import { diffFindings } from "./skill-lint.js";
|
|
59
59
|
import { contentHash, loadMutations, recordMutation } from "./mutations.js";
|
|
60
|
+
import { decideSkillWrite } from "./skill-write-intent.js";
|
|
61
|
+
import { skillNamespaceKey } from "./skill-observation.js";
|
|
62
|
+
import { SkillTargetLocks } from "./skill-target-locks.js";
|
|
63
|
+
import { SkillRootGate } from "./skill-root-gate.js";
|
|
60
64
|
import { revisionFingerprint, revisionSupportDigest } from "./skill-revision.js";
|
|
61
65
|
import { clipChangeSummary, contentRetentionFeedback, DEFAULT_SKILL_WRITE_SUMMARY_CHARS, HISTORY_DIR, loadVersionContent, loadVersions, normalizeChangeSummary, recordVersions } from "./skill-history.js";
|
|
62
66
|
import { getRecord, loadUsage, mutateUsage, suppressedFile, usageFile } from "./usage.js";
|
|
@@ -461,6 +465,16 @@ function sameRevisionAnchor(expected, live) {
|
|
|
461
465
|
return false;
|
|
462
466
|
return expected.kind === 'absent' || expected.sha256 === live.sha256;
|
|
463
467
|
}
|
|
468
|
+
/** One target-lock registry per skill ROOT, shared by every library instance in this process. */
|
|
469
|
+
const TARGET_LOCKS_BY_ROOT = new Map();
|
|
470
|
+
function targetLocksFor(root) {
|
|
471
|
+
let locks = TARGET_LOCKS_BY_ROOT.get(root);
|
|
472
|
+
if (locks === undefined) {
|
|
473
|
+
locks = new SkillTargetLocks();
|
|
474
|
+
TARGET_LOCKS_BY_ROOT.set(root, locks);
|
|
475
|
+
}
|
|
476
|
+
return locks;
|
|
477
|
+
}
|
|
464
478
|
export class SkillLibrary {
|
|
465
479
|
root;
|
|
466
480
|
/** The ONE read face owner/health/panel consume; a thin adapter, not a store. */
|
|
@@ -478,6 +492,10 @@ export class SkillLibrary {
|
|
|
478
492
|
* one skill never interleave their read-modify-write (the cross-process layer
|
|
479
493
|
* is the IO backend's transact lock; this chain is the second layer). */
|
|
480
494
|
serial;
|
|
495
|
+
/** Transitional target locks (same key as SkillWriteService). */
|
|
496
|
+
targetLocks;
|
|
497
|
+
/** Root structural gate; simple writes still use the serial until D.5d. */
|
|
498
|
+
rootGate = new SkillRootGate();
|
|
481
499
|
/** V10-03 (P2-18): see the constructor's threatExemptLabels. Empty by
|
|
482
500
|
* default — the strict ANY-hit-blocks policy is unchanged. */
|
|
483
501
|
threatExemptLabels;
|
|
@@ -492,6 +510,7 @@ export class SkillLibrary {
|
|
|
492
510
|
historyWarned = false;
|
|
493
511
|
constructor(root = skillsRoot(), io = nodeEvolutionIo(), limits = DEFAULT_SKILL_LIMITS, onMutation, transact, threatExemptLabels, authority = CLASS_DEFAULT_AUTHORITY, mutationLock, fence) {
|
|
494
512
|
this.root = root;
|
|
513
|
+
this.targetLocks = targetLocksFor(root);
|
|
495
514
|
this.io = io;
|
|
496
515
|
this.limits = limits;
|
|
497
516
|
this.onMutation = onMutation;
|
|
@@ -543,11 +562,15 @@ export class SkillLibrary {
|
|
|
543
562
|
const runId = currentReviewContext()?.runId;
|
|
544
563
|
return { ...(runId === undefined ? {} : { runId }), moves, sources: roots.map(skill => ({ skill })) };
|
|
545
564
|
}
|
|
546
|
-
|
|
565
|
+
/** Transitional: serialize one target even while the root serial remains. */
|
|
566
|
+
async withTarget(targetKey, task) {
|
|
567
|
+
return await this.targetLocks.withLock(targetKey, task);
|
|
568
|
+
}
|
|
569
|
+
async withMutationLock(task, targetKeys) {
|
|
547
570
|
// Fail closed: a missing authority/lock is an assembly error, not a reason to run
|
|
548
571
|
// the write outside the fence. The old catch-and-fallback inverted this guard: the
|
|
549
572
|
// "refusing an unfenced production write" error itself took the fallback path.
|
|
550
|
-
const lease = await this.lockPort().acquire();
|
|
573
|
+
const lease = await this.lockPort().acquire(targetKeys);
|
|
551
574
|
try {
|
|
552
575
|
return await task();
|
|
553
576
|
}
|
|
@@ -593,6 +616,17 @@ export class SkillLibrary {
|
|
|
593
616
|
}
|
|
594
617
|
return { ok: true, body, onDisk: body.trimEnd() + '\n', norm };
|
|
595
618
|
}
|
|
619
|
+
/** True when the injected lock port is per-target rather than the home fence. */
|
|
620
|
+
keyedTargetLocks() {
|
|
621
|
+
if (this.mutationLock !== undefined)
|
|
622
|
+
return this.mutationLock.keyed === true;
|
|
623
|
+
// A test library may have no injected lock (fileMutationLock fallback). A
|
|
624
|
+
// production library without one must still fail closed, never silently
|
|
625
|
+
// bypass the fence because the keyed probe swallowed the assembly error.
|
|
626
|
+
if (process.env['VITEST'] !== 'true' && process.env['NODE_ENV'] !== 'test')
|
|
627
|
+
this.lockPort();
|
|
628
|
+
return false;
|
|
629
|
+
}
|
|
596
630
|
lockPort() {
|
|
597
631
|
if (this.mutationLock !== undefined)
|
|
598
632
|
return this.mutationLock;
|
|
@@ -616,12 +650,33 @@ export class SkillLibrary {
|
|
|
616
650
|
/** Recover every prepared tree-change snapshot in the shared unit store. */
|
|
617
651
|
async recoverPreparedUnits() {
|
|
618
652
|
const home = dirname(this.root);
|
|
653
|
+
try {
|
|
654
|
+
await this.lockPort().repair?.();
|
|
655
|
+
}
|
|
656
|
+
catch { /* diagnostics only */ }
|
|
619
657
|
const unit = this.commitUnit({
|
|
620
658
|
limits: { maxSkillFileBytes: this.limits.maxSkillFileBytes, maxSkillContentChars: this.limits.maxSkillContentChars },
|
|
621
659
|
serial: this.serial,
|
|
622
660
|
lock: this.lockPort(),
|
|
661
|
+
targetKeysForSnapshot: snapshot => {
|
|
662
|
+
const keys = new Set();
|
|
663
|
+
for (const op of snapshot.ops) {
|
|
664
|
+
const rel = relative(this.root, op.target);
|
|
665
|
+
if (rel === '' || rel.startsWith('..') || isAbsolute(rel))
|
|
666
|
+
continue;
|
|
667
|
+
const parts = rel.split(/[\\/]+/);
|
|
668
|
+
const skill = parts[0];
|
|
669
|
+
if (skill === undefined || skill === '')
|
|
670
|
+
continue;
|
|
671
|
+
keys.add('skill::' + skill);
|
|
672
|
+
keys.add(skillNamespaceKey(skill));
|
|
673
|
+
if (parts.length > 1)
|
|
674
|
+
keys.add('skill::' + skill + '::' + parts.slice(1).join('/'));
|
|
675
|
+
}
|
|
676
|
+
return [...keys];
|
|
677
|
+
},
|
|
623
678
|
});
|
|
624
|
-
const results = await unit.recoverPrepared();
|
|
679
|
+
const results = await this.rootGate.write(() => unit.recoverPrepared());
|
|
625
680
|
await pruneTreeChangeUnits(this.io, home).catch(() => { });
|
|
626
681
|
return results;
|
|
627
682
|
}
|
|
@@ -1441,7 +1496,15 @@ export class SkillLibrary {
|
|
|
1441
1496
|
// the other single-file mutators on the in-process serial chain — a
|
|
1442
1497
|
// concurrent update could otherwise pass its protection check before the
|
|
1443
1498
|
// marker lands and rewrite a skill the user just froze.
|
|
1444
|
-
return await this.
|
|
1499
|
+
return await this.rootGate.read(async () => {
|
|
1500
|
+
const lease = await this.lockPort().acquire([skillNamespaceKey(name)]);
|
|
1501
|
+
try {
|
|
1502
|
+
return await this.withTarget('pin::' + name, () => this.setPinnedCore(name, pinned, origin));
|
|
1503
|
+
}
|
|
1504
|
+
finally {
|
|
1505
|
+
await lease.release();
|
|
1506
|
+
}
|
|
1507
|
+
});
|
|
1445
1508
|
}
|
|
1446
1509
|
async setPinnedCore(name, pinned, origin) {
|
|
1447
1510
|
const normalized = name.trim();
|
|
@@ -1499,7 +1562,7 @@ export class SkillLibrary {
|
|
|
1499
1562
|
else {
|
|
1500
1563
|
await this.io.remove(marker);
|
|
1501
1564
|
}
|
|
1502
|
-
await this.audit(normalized, pinned ? 'pin' : 'unpin', null, null, pinned ? 'pinned' : 'unpinned');
|
|
1565
|
+
await this.audit(normalized, pinned ? 'pin' : 'unpin', null, null, pinned ? 'pinned' : 'unpinned', undefined, undefined, undefined, undefined, true);
|
|
1503
1566
|
return {
|
|
1504
1567
|
ok: true,
|
|
1505
1568
|
message: `${pinned
|
|
@@ -1515,7 +1578,7 @@ export class SkillLibrary {
|
|
|
1515
1578
|
// serialize queue (F-208 discipline, like update/patch) — two concurrent
|
|
1516
1579
|
// create calls for one name used to both pass exists() and double-write
|
|
1517
1580
|
// (double audit, double mutation event).
|
|
1518
|
-
return await this.
|
|
1581
|
+
return await this.rootGate.read(() => this.withTarget('skill::' + normalized, () => this.withMutationLock(() => this.createCore(normalized, content, origin, options, true), ['skill::' + normalized, skillNamespaceKey(normalized)])));
|
|
1519
1582
|
}
|
|
1520
1583
|
async createCore(normalized, content, origin, options = {}, fenceHeld = false) {
|
|
1521
1584
|
// C-12 (v10 audit): the inline badName() copy is gone (see setPinned).
|
|
@@ -1668,7 +1731,7 @@ export class SkillLibrary {
|
|
|
1668
1731
|
await this.ensureRecovered();
|
|
1669
1732
|
// F-208: the whole read→validate→write runs under the in-process serialize
|
|
1670
1733
|
// queue so two concurrent updates on one skill never interleave.
|
|
1671
|
-
return await this.
|
|
1734
|
+
return await this.rootGate.read(() => this.withTarget('skill::' + name, () => this.updateCore(name, content, origin, anchor)));
|
|
1672
1735
|
}
|
|
1673
1736
|
async updateCore(name, content, origin, anchor) {
|
|
1674
1737
|
// P3 (v15): guard BEFORE dirOf — same order as patchCore, so no path
|
|
@@ -1718,6 +1781,7 @@ export class SkillLibrary {
|
|
|
1718
1781
|
const unit = this.commitUnit({
|
|
1719
1782
|
limits: { maxSkillFileBytes: Number.MAX_SAFE_INTEGER, maxSkillContentChars: Number.MAX_SAFE_INTEGER },
|
|
1720
1783
|
lock: this.lockPort(),
|
|
1784
|
+
targetKeys: ['skill::' + name, skillNamespaceKey(name)],
|
|
1721
1785
|
...(this.transact === undefined ? {} : { transact: this.transact }),
|
|
1722
1786
|
hooks: {
|
|
1723
1787
|
committed: async (event) => {
|
|
@@ -1750,13 +1814,14 @@ export class SkillLibrary {
|
|
|
1750
1814
|
const retention = contentRetentionFeedback({ name, action: 'update', before: current, after: onDisk });
|
|
1751
1815
|
return { ok: true, message: `技能「${name}」已更新。${warning}${retention === null ? '' : '\n' + retention}`, path: dir, ...(prepared.norm.changed ? { normalizedFrontmatterFields: prepared.norm.fields } : {}) };
|
|
1752
1816
|
}
|
|
1753
|
-
async patch(rawName, oldString, newString, filePath = '', replaceAll = false, origin = this.authority.origin) {
|
|
1817
|
+
async patch(rawName, oldString, newString, filePath = '', replaceAll = false, origin = this.authority.origin, anchor) {
|
|
1754
1818
|
await this.ensureRecovered();
|
|
1755
1819
|
// One trim per entry: paths (dirOf), validation and messages all see the same name.
|
|
1756
1820
|
const name = rawName.trim();
|
|
1757
1821
|
// F-208: the whole read→patch→write runs under the in-process serialize
|
|
1758
1822
|
// queue so two concurrent patches on one skill never interleave.
|
|
1759
|
-
|
|
1823
|
+
const key = 'skill::' + name + (filePath === '' ? '' : '::' + filePath.replace(/\\/g, '/'));
|
|
1824
|
+
return await this.rootGate.read(() => this.withTarget(key, () => this.patchCore(name, oldString, newString, filePath, replaceAll, origin, anchor)));
|
|
1760
1825
|
}
|
|
1761
1826
|
/**
|
|
1762
1827
|
* Replace ONE section's content (or one exact sub-block) in place. Keeps the
|
|
@@ -1821,7 +1886,7 @@ export class SkillLibrary {
|
|
|
1821
1886
|
return result;
|
|
1822
1887
|
return { ok: true, message: `已更新「${name}」的「${edit.heading}」章节(正文 ${md.length} → ${finalMd.length} 字符)。`, path: dir };
|
|
1823
1888
|
}
|
|
1824
|
-
async patchCore(name, oldString, newString, filePath, replaceAll, origin) {
|
|
1889
|
+
async patchCore(name, oldString, newString, filePath, replaceAll, origin, anchor) {
|
|
1825
1890
|
// P1-1 (v14): patch was the ONE path-building mutator without the name
|
|
1826
1891
|
// guard — `name = '../outside'` plus a `file_path` escaped the skills root
|
|
1827
1892
|
// and rewrote an existing support file there (the SKILL.md branch was
|
|
@@ -1937,6 +2002,9 @@ export class SkillLibrary {
|
|
|
1937
2002
|
await this.cleanupGhostDir(target);
|
|
1938
2003
|
return { ok: false, message: `文件不存在:${patchLabel}` };
|
|
1939
2004
|
}
|
|
2005
|
+
const verdict = anchorVerdict(anchor, current);
|
|
2006
|
+
if (verdict !== 'match')
|
|
2007
|
+
return anchorRefusalFile(name, patchLabel, verdict);
|
|
1940
2008
|
const outcome = compute(current);
|
|
1941
2009
|
if (outcome.write === null) {
|
|
1942
2010
|
if (outcome.hardCapHit !== undefined)
|
|
@@ -1947,6 +2015,7 @@ export class SkillLibrary {
|
|
|
1947
2015
|
const unit = this.commitUnit({
|
|
1948
2016
|
limits: { maxSkillFileBytes: Number.MAX_SAFE_INTEGER, maxSkillContentChars: Number.MAX_SAFE_INTEGER },
|
|
1949
2017
|
lock: this.lockPort(),
|
|
2018
|
+
targetKeys: [filePath === '' ? 'skill::' + name : 'skill::' + name + '::' + filePath.replace(/\\/g, '/'), skillNamespaceKey(name)],
|
|
1950
2019
|
...(this.transact === undefined ? {} : { transact: this.transact }),
|
|
1951
2020
|
hooks: {
|
|
1952
2021
|
committed: async (event) => {
|
|
@@ -2076,8 +2145,28 @@ export class SkillLibrary {
|
|
|
2076
2145
|
}
|
|
2077
2146
|
catch { /* lifecycle telemetry is best-effort; the archive already landed */ }
|
|
2078
2147
|
}
|
|
2079
|
-
async archive(rawName, options = {}, origin = this.authority.origin, change) {
|
|
2080
|
-
|
|
2148
|
+
async archive(rawName, options = {}, origin = this.authority.origin, change, rootHeld = false, namespaceHeld = false) {
|
|
2149
|
+
if (rootHeld) {
|
|
2150
|
+
if (!this.keyedTargetLocks() || namespaceHeld)
|
|
2151
|
+
return await this.archiveCore(rawName, options, origin, true, change);
|
|
2152
|
+
const lease = await this.lockPort().acquire([skillNamespaceKey(rawName)]);
|
|
2153
|
+
try {
|
|
2154
|
+
return await this.archiveCore(rawName, options, origin, true, change);
|
|
2155
|
+
}
|
|
2156
|
+
finally {
|
|
2157
|
+
await lease.release();
|
|
2158
|
+
}
|
|
2159
|
+
}
|
|
2160
|
+
const namespace = skillNamespaceKey(rawName);
|
|
2161
|
+
return await this.rootGate.write(async () => {
|
|
2162
|
+
const lease = await this.lockPort().acquire([namespace]);
|
|
2163
|
+
try {
|
|
2164
|
+
return await this.archiveCore(rawName, options, origin, true, change);
|
|
2165
|
+
}
|
|
2166
|
+
finally {
|
|
2167
|
+
await lease.release();
|
|
2168
|
+
}
|
|
2169
|
+
});
|
|
2081
2170
|
}
|
|
2082
2171
|
async archiveCore(rawName, options, origin, fenceHeld, change) {
|
|
2083
2172
|
// One trim per entry: paths (dirOf), validation and messages all see the same name.
|
|
@@ -2224,13 +2313,38 @@ export class SkillLibrary {
|
|
|
2224
2313
|
if (protectedSource !== undefined)
|
|
2225
2314
|
return { ok: false, message: `来源技能「${protectedSource}」是受保护的内置技能。` };
|
|
2226
2315
|
const limits = plan.limits ?? this.limits;
|
|
2227
|
-
const
|
|
2316
|
+
const serialized = options?.serialized === true;
|
|
2317
|
+
const run = async (sourceHeld) => {
|
|
2228
2318
|
// A nested merge already holds the home fence; its archive/restore bookkeeping
|
|
2229
2319
|
// must run inline instead of queueing behind that same lease.
|
|
2230
2320
|
const fenceHeld = plan.nested === true;
|
|
2231
|
-
const
|
|
2232
|
-
|
|
2233
|
-
|
|
2321
|
+
const keyed = this.keyedTargetLocks();
|
|
2322
|
+
const archive = async (name, archiveOptions) => {
|
|
2323
|
+
if (!fenceHeld)
|
|
2324
|
+
return await this.archive(name, archiveOptions, plan.origin, undefined, true, sourceHeld);
|
|
2325
|
+
if (!keyed || sourceHeld)
|
|
2326
|
+
return await this.archiveCore(name, archiveOptions, plan.origin, true);
|
|
2327
|
+
const lease = await this.lockPort().acquire([skillNamespaceKey(name)]);
|
|
2328
|
+
try {
|
|
2329
|
+
return await this.archiveCore(name, archiveOptions, plan.origin, true);
|
|
2330
|
+
}
|
|
2331
|
+
finally {
|
|
2332
|
+
await lease.release();
|
|
2333
|
+
}
|
|
2334
|
+
};
|
|
2335
|
+
const restore = async (source) => {
|
|
2336
|
+
if (!fenceHeld)
|
|
2337
|
+
return await this.restoreFromArchive(source, plan.origin, true, sourceHeld);
|
|
2338
|
+
if (!keyed || sourceHeld)
|
|
2339
|
+
return await this.restoreFromArchiveCore(source, plan.origin, true);
|
|
2340
|
+
const lease = await this.lockPort().acquire([skillNamespaceKey(source)]);
|
|
2341
|
+
try {
|
|
2342
|
+
return await this.restoreFromArchiveCore(source, plan.origin, true);
|
|
2343
|
+
}
|
|
2344
|
+
finally {
|
|
2345
|
+
await lease.release();
|
|
2346
|
+
}
|
|
2347
|
+
};
|
|
2234
2348
|
const dir = this.dirOf(target);
|
|
2235
2349
|
const targetPath = join(dir, 'SKILL.md');
|
|
2236
2350
|
if (!plan.targetExists && await this.io.exists(dir)) {
|
|
@@ -2350,7 +2464,7 @@ export class SkillLibrary {
|
|
|
2350
2464
|
const stuck = [];
|
|
2351
2465
|
for (const source of [...archived].reverse()) {
|
|
2352
2466
|
try {
|
|
2353
|
-
const restored =
|
|
2467
|
+
const restored = await restore(source);
|
|
2354
2468
|
if (!restored.ok)
|
|
2355
2469
|
stuck.push(source);
|
|
2356
2470
|
}
|
|
@@ -2551,7 +2665,22 @@ export class SkillLibrary {
|
|
|
2551
2665
|
await plan.onPhase?.('unit-written');
|
|
2552
2666
|
return { ok: true, message: `已把 ${sources.join(', ')} 合并进「${target}」。`, unitId, targetPath: dir, archived, mutations: 1 + sources.length };
|
|
2553
2667
|
};
|
|
2554
|
-
|
|
2668
|
+
const acquireSourcesAndRun = async () => {
|
|
2669
|
+
const sourceHeld = this.keyedTargetLocks() && sources.length > 0;
|
|
2670
|
+
const lease = sourceHeld
|
|
2671
|
+
? await this.lockPort().acquire(sources.map(skillNamespaceKey))
|
|
2672
|
+
: undefined;
|
|
2673
|
+
try {
|
|
2674
|
+
return serialized ? await run(sourceHeld) : await this.serial(() => run(sourceHeld));
|
|
2675
|
+
}
|
|
2676
|
+
finally {
|
|
2677
|
+
if (lease !== undefined)
|
|
2678
|
+
await lease.release();
|
|
2679
|
+
}
|
|
2680
|
+
};
|
|
2681
|
+
if (serialized)
|
|
2682
|
+
return await acquireSourcesAndRun();
|
|
2683
|
+
return await this.rootGate.write(acquireSourcesAndRun);
|
|
2555
2684
|
}
|
|
2556
2685
|
/**
|
|
2557
2686
|
* V2 (design §16.7): what an apply-mode consolidation would do for ONE source,
|
|
@@ -2660,208 +2789,219 @@ export class SkillLibrary {
|
|
|
2660
2789
|
// Every refusal below (protection, missing skill, package integrity)
|
|
2661
2790
|
// still fires before ANY side effect, so the pre-side-effect refusal
|
|
2662
2791
|
// semantics are unchanged.
|
|
2663
|
-
return await this.
|
|
2664
|
-
const
|
|
2665
|
-
|
|
2666
|
-
|
|
2667
|
-
|
|
2668
|
-
|
|
2669
|
-
|
|
2670
|
-
|
|
2671
|
-
|
|
2672
|
-
|
|
2673
|
-
|
|
2674
|
-
|
|
2675
|
-
|
|
2676
|
-
|
|
2677
|
-
|
|
2678
|
-
|
|
2679
|
-
|
|
2680
|
-
|
|
2681
|
-
|
|
2682
|
-
|
|
2683
|
-
|
|
2684
|
-
|
|
2685
|
-
|
|
2686
|
-
|
|
2687
|
-
|
|
2688
|
-
|
|
2689
|
-
|
|
2690
|
-
|
|
2691
|
-
|
|
2692
|
-
|
|
2693
|
-
|
|
2694
|
-
|
|
2695
|
-
|
|
2696
|
-
|
|
2697
|
-
|
|
2698
|
-
|
|
2699
|
-
const
|
|
2700
|
-
|
|
2701
|
-
|
|
2702
|
-
|
|
2792
|
+
return await this.rootGate.write(async () => {
|
|
2793
|
+
const sourceLease = this.keyedTargetLocks()
|
|
2794
|
+
? await this.lockPort().acquire([...normalizedSources].map(skillNamespaceKey))
|
|
2795
|
+
: undefined;
|
|
2796
|
+
try {
|
|
2797
|
+
return await this.serial(async () => {
|
|
2798
|
+
const referenceWrites = [];
|
|
2799
|
+
// V2 (design §16.7): support files copied into the target from an apply-mode
|
|
2800
|
+
// source, staged before any side effect and committed in the same tree change.
|
|
2801
|
+
const rehomed = [];
|
|
2802
|
+
// V3: one pointer block per demoted source (pointer line + link list).
|
|
2803
|
+
const demotedPointers = [];
|
|
2804
|
+
const parts = [];
|
|
2805
|
+
// S1-E5: the plan-time bytes per source, re-verified right before that
|
|
2806
|
+
// source is archived. The serial queue closes the read→merge window for
|
|
2807
|
+
// THIS process only; a cross-process writer (shared DSH_HOME, transact
|
|
2808
|
+
// is a supported deployment) could still land a patch between the plan
|
|
2809
|
+
// read and the archive — the OPT-04 "closed for the sources too" claim
|
|
2810
|
+
// was true only in-process. A mismatch aborts through the rollback below.
|
|
2811
|
+
const plannedSourceBytes = new Map();
|
|
2812
|
+
if (mode === 'append') {
|
|
2813
|
+
for (const source of normalizedSources) {
|
|
2814
|
+
const protection = await this.deleteProtection(source);
|
|
2815
|
+
if (protection)
|
|
2816
|
+
return { ok: false, message: `技能「${source}」受保护(${protection})。` };
|
|
2817
|
+
const sourceMd = await this.io.readText(join(this.dirOf(source), 'SKILL.md'));
|
|
2818
|
+
if (!sourceMd)
|
|
2819
|
+
return { ok: false, message: `技能「${source}」不存在。` };
|
|
2820
|
+
const parsed = parseFrontmatter(sourceMd);
|
|
2821
|
+
if (!parsed)
|
|
2822
|
+
return { ok: false, message: `技能「${source}」没有有效的 frontmatter;拒绝合并。` };
|
|
2823
|
+
// Package integrity (009-I): an append must never leave dangling
|
|
2824
|
+
// support links — refuse before ANY side effect (no archive, no write).
|
|
2825
|
+
const carriesSupport = await this.countSupportDirs(source) > 0;
|
|
2826
|
+
const parsedRefs = supportRefs(parsed.body);
|
|
2827
|
+
const rawRefs = [...parsed.body.matchAll(/(?:references|scripts|templates|assets)\/[A-Za-z0-9._/-]+/g)].map(match => match[0]);
|
|
2828
|
+
const refs = parsedRefs.length > 0 ? parsedRefs : rawRefs;
|
|
2829
|
+
let appendedBody = parsed.body;
|
|
2830
|
+
if (carriesSupport || refs.length > 0) {
|
|
2831
|
+
const decision = await this.planSourceRehoming(source, targetName, parsed.body, rehomed.map(file => file.to));
|
|
2832
|
+
if (decision.kind === 'blocked') {
|
|
2833
|
+
const reason = carriesSupport
|
|
2834
|
+
? `source "${source}" carries support files`
|
|
2835
|
+
: `source "${source}" body references support files (${refs.join(', ')})`;
|
|
2836
|
+
return { ok: false, message: `合并被拒绝:${reason} 会被落下。请改用 mode:'reference',或直接归档整个包。${decision.note}` };
|
|
2837
|
+
}
|
|
2838
|
+
rehomed.push(...decision.files);
|
|
2839
|
+
appendedBody = decision.rewritten;
|
|
2840
|
+
}
|
|
2841
|
+
parts.push(`\n<!-- consolidated from ${source} at ${new Date().toISOString()} -->\n${appendedBody.trim()}`);
|
|
2842
|
+
plannedSourceBytes.set(source, sourceMd);
|
|
2703
2843
|
}
|
|
2704
|
-
rehomed.push(...decision.files);
|
|
2705
|
-
appendedBody = decision.rewritten;
|
|
2706
2844
|
}
|
|
2707
|
-
|
|
2708
|
-
|
|
2709
|
-
|
|
2710
|
-
|
|
2711
|
-
|
|
2712
|
-
|
|
2713
|
-
|
|
2714
|
-
|
|
2715
|
-
|
|
2716
|
-
|
|
2717
|
-
|
|
2718
|
-
|
|
2719
|
-
|
|
2720
|
-
|
|
2721
|
-
|
|
2722
|
-
|
|
2723
|
-
|
|
2724
|
-
|
|
2725
|
-
|
|
2726
|
-
|
|
2727
|
-
|
|
2845
|
+
else {
|
|
2846
|
+
for (const source of normalizedSources) {
|
|
2847
|
+
const protection = await this.deleteProtection(source);
|
|
2848
|
+
if (protection)
|
|
2849
|
+
return { ok: false, message: `技能「${source}」受保护(${protection})。` };
|
|
2850
|
+
const sourceMd = await this.io.readText(join(this.dirOf(source), 'SKILL.md'));
|
|
2851
|
+
if (!sourceMd)
|
|
2852
|
+
return { ok: false, message: `技能「${source}」不存在。` };
|
|
2853
|
+
const parsed = parseFrontmatter(sourceMd);
|
|
2854
|
+
if (!parsed)
|
|
2855
|
+
return { ok: false, message: `技能「${source}」没有有效的 frontmatter;拒绝降级。` };
|
|
2856
|
+
const refs = supportRefs(parsed.body);
|
|
2857
|
+
let demotedBody = parsed.body;
|
|
2858
|
+
if (refs.length > 0) {
|
|
2859
|
+
const decision = await this.planSourceRehoming(source, targetName, parsed.body, rehomed.map(file => file.to));
|
|
2860
|
+
if (decision.kind === 'blocked') {
|
|
2861
|
+
return { ok: false, message: `合并被拒绝:来源技能「${source}」的正文引用了会被落下的支撑文件(${refs.join(', ')}):请改为归档整个包。${decision.note}` };
|
|
2862
|
+
}
|
|
2863
|
+
rehomed.push(...decision.files);
|
|
2864
|
+
demotedBody = decision.rewritten;
|
|
2865
|
+
}
|
|
2866
|
+
const target = join(targetDir, 'references', `${source}.md`);
|
|
2867
|
+
referenceWrites.push({ target, content: `<!-- demoted from ${source} at ${new Date().toISOString()} -->\n${demotedBody.trim()}\n` });
|
|
2868
|
+
// Same convention as restructure: the pointer carries the link list of
|
|
2869
|
+
// what the demoted body cited, so the target body keeps mentioning them.
|
|
2870
|
+
demotedPointers.push(pointerBlock(`references/${source}.md`, demotedBody));
|
|
2871
|
+
plannedSourceBytes.set(source, sourceMd);
|
|
2728
2872
|
}
|
|
2729
|
-
|
|
2730
|
-
|
|
2873
|
+
// Discoverability: the umbrella's body gains one pointer per demoted
|
|
2874
|
+
// source — built INSIDE the serial queue below against the fresh target
|
|
2875
|
+
// (V8-11), so it never merges over a concurrent patch.
|
|
2731
2876
|
}
|
|
2732
|
-
|
|
2733
|
-
|
|
2734
|
-
//
|
|
2735
|
-
//
|
|
2736
|
-
|
|
2737
|
-
|
|
2738
|
-
|
|
2739
|
-
|
|
2740
|
-
|
|
2741
|
-
|
|
2742
|
-
|
|
2743
|
-
|
|
2744
|
-
|
|
2745
|
-
|
|
2746
|
-
|
|
2747
|
-
|
|
2748
|
-
|
|
2749
|
-
|
|
2750
|
-
|
|
2751
|
-
|
|
2752
|
-
|
|
2753
|
-
|
|
2754
|
-
|
|
2755
|
-
|
|
2756
|
-
|
|
2757
|
-
|
|
2758
|
-
|
|
2759
|
-
|
|
2760
|
-
|
|
2761
|
-
|
|
2762
|
-
|
|
2763
|
-
|
|
2764
|
-
|
|
2765
|
-
|
|
2766
|
-
|
|
2877
|
+
// Two-phase commit so a failure partway never leaves the tree inconsistent:
|
|
2878
|
+
// (1) archive every source first — a source that cannot be archived aborts
|
|
2879
|
+
// before target is touched; (2) only when all sources are safely in
|
|
2880
|
+
// .archive does the kernel commit the writes (byte-level rollback).
|
|
2881
|
+
const archived = [];
|
|
2882
|
+
try {
|
|
2883
|
+
// V9-04 (0.3.50): restore the cheap target-existence pre-check BEFORE
|
|
2884
|
+
// the destructive archive loop — V8-11 moved the authoritative read into
|
|
2885
|
+
// the serial queue, which silently turned a clean "Skill not found"
|
|
2886
|
+
// refusal into "archive ALL sources, then roll back" (a half-completed
|
|
2887
|
+
// tree when a restore fails). The serial read stays authoritative for
|
|
2888
|
+
// the merge; this probe keeps the failure path non-destructive.
|
|
2889
|
+
const preTargetMd = await this.io.readText(join(targetDir, 'SKILL.md'));
|
|
2890
|
+
if (!preTargetMd)
|
|
2891
|
+
return { ok: false, message: `技能「${targetName}」不存在。` };
|
|
2892
|
+
for (const source of normalizedSources) {
|
|
2893
|
+
// S1-E5: verify the plan-time bytes right before THIS source is
|
|
2894
|
+
// archived. A mismatch throws into the rollback below, so sources
|
|
2895
|
+
// archived before the abort are brought back and nothing lands —
|
|
2896
|
+
// the cross-process gap the serial queue cannot close.
|
|
2897
|
+
if (plannedSourceBytes.has(source)) {
|
|
2898
|
+
const freshSource = await this.io.readText(join(this.dirOf(source), 'SKILL.md'));
|
|
2899
|
+
if (freshSource !== plannedSourceBytes.get(source)) {
|
|
2900
|
+
throw new Error(`Consolidation aborted: source "${source}" changed while the consolidation ran (its planned bytes are no longer current).`);
|
|
2901
|
+
}
|
|
2902
|
+
}
|
|
2903
|
+
const result = await this.archive(source, { absorbedInto: targetName }, undefined, undefined, true, true);
|
|
2904
|
+
if (!result.ok)
|
|
2905
|
+
throw new Error(result.message);
|
|
2906
|
+
archived.push(source);
|
|
2907
|
+
}
|
|
2908
|
+
// V8-11 (0.3.46): the target pre-read and the merged/pointer construction
|
|
2909
|
+
// happen INSIDE the in-process serialize queue — a concurrent
|
|
2910
|
+
// patch/update between the old pre-read and the commit used to be
|
|
2911
|
+
// silently overwritten (the serial chain is the same second layer
|
|
2912
|
+
// update/patch/restructure/writeSupportFile use).
|
|
2913
|
+
const freshTargetMd = await this.io.readText(join(targetDir, 'SKILL.md'));
|
|
2914
|
+
// S1-E1: everything below runs AFTER the sources are already archived —
|
|
2915
|
+
// these three exits used to `return`, which skips the catch's rollback
|
|
2916
|
+
// (JS: return does not pass through catch) and left every source in
|
|
2917
|
+
// .archive while the message implied nothing had happened. Throw so
|
|
2918
|
+
// the T-14 rollback below brings them back; the catch prefixes the
|
|
2919
|
+
// reason with the rollback outcome, so the reasons here name only the
|
|
2920
|
+
// failure itself.
|
|
2921
|
+
if (!freshTargetMd)
|
|
2922
|
+
throw new Error(`target "${targetName}" disappeared mid-consolidate`);
|
|
2923
|
+
// V10-01 (P2-2): reference-mode targets APPEND, mirroring restructure
|
|
2924
|
+
// (base + '\n\n' + new text) — a second consolidate of a re-created
|
|
2925
|
+
// source used to overwrite the first demotion's bytes (silent loss of
|
|
2926
|
+
// the older degraded knowledge). The previous bytes are read INSIDE
|
|
2927
|
+
// the serial queue (V8-11 discipline), so a concurrent patch between
|
|
2928
|
+
// planning and commit is never silently overwritten; applyTreeChange
|
|
2929
|
+
// re-reads at commit for the rollback bytes.
|
|
2930
|
+
const writes = [];
|
|
2931
|
+
for (const reference of referenceWrites) {
|
|
2932
|
+
const previous = await this.readForCas(reference.target);
|
|
2933
|
+
const base = previous?.trimEnd() ?? '';
|
|
2934
|
+
// V24-01: carry the plan-time bytes as the CAS baseline — a read
|
|
2935
|
+
// error here reads as null and stays fail-closed at commit (an
|
|
2936
|
+
// existing file then counts as drift).
|
|
2937
|
+
writes.push({ target: reference.target, content: base === '' ? reference.content : `${base}\n\n${reference.content}`, expected: previous });
|
|
2938
|
+
}
|
|
2939
|
+
// V2 (design §16.7): the re-homed support files ride the SAME commit as the
|
|
2940
|
+
// merged body — one tree change, one rollback domain, and the body's
|
|
2941
|
+
// rewritten references can never be committed without their targets.
|
|
2942
|
+
for (const file of rehomed) {
|
|
2943
|
+
const target = join(targetDir, ...file.to.split('/'));
|
|
2944
|
+
const previous = await this.readForCas(target);
|
|
2945
|
+
writes.push({ target, content: file.content, expected: previous });
|
|
2767
2946
|
}
|
|
2947
|
+
if (mode === 'append') {
|
|
2948
|
+
const merged = freshTargetMd.trimEnd() + parts.join('\n') + '\n';
|
|
2949
|
+
const validation = validateFrontmatter(merged, targetName, this.limits);
|
|
2950
|
+
if (validation)
|
|
2951
|
+
throw new Error(`merge validation failed: ${validation}`);
|
|
2952
|
+
writes.push({ target: join(targetDir, 'SKILL.md'), content: merged, expected: freshTargetMd });
|
|
2953
|
+
}
|
|
2954
|
+
else {
|
|
2955
|
+
const pointerLines = demotedPointers.map(lines => `\n${lines.join('\n')}`).join('');
|
|
2956
|
+
const extended = freshTargetMd.trimEnd() + pointerLines + '\n';
|
|
2957
|
+
const validation = validateFrontmatter(extended, targetName, this.limits);
|
|
2958
|
+
if (validation)
|
|
2959
|
+
throw new Error(`merge validation failed: ${validation}`);
|
|
2960
|
+
writes.push({ target: join(targetDir, 'SKILL.md'), content: extended, expected: freshTargetMd });
|
|
2961
|
+
}
|
|
2962
|
+
const result = await this.applyTreeChange({
|
|
2963
|
+
name: targetName,
|
|
2964
|
+
origin,
|
|
2965
|
+
protection: 'write',
|
|
2966
|
+
writes,
|
|
2967
|
+
auditAction: 'consolidate',
|
|
2968
|
+
auditSummary: `consolidated ${normalizedSources.join(', ')} (${mode}) into ${targetName}`
|
|
2969
|
+
+ (rehomed.length === 0 ? '' : `; re-homed ${rehomed.map(file => `${file.from}->${file.to}`).join(', ')}`),
|
|
2970
|
+
eventAction: 'consolidate',
|
|
2971
|
+
});
|
|
2972
|
+
if (!result.ok)
|
|
2973
|
+
throw new Error(result.message);
|
|
2974
|
+
return { ok: true, message: `已把 ${normalizedSources.join(', ')} 合并进「${targetName}」。`, path: targetDir };
|
|
2975
|
+
}
|
|
2976
|
+
catch (error) {
|
|
2977
|
+
// Bring back every source we already archived so the merge is fully
|
|
2978
|
+
// undone. 0.3.16 (T-14): a failed restore used to be swallowed by
|
|
2979
|
+
// `.catch(() => {})` while the message still claimed a full rollback —
|
|
2980
|
+
// the source stayed in .archive silently. Surface it.
|
|
2981
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
2982
|
+
const failedRestores = [];
|
|
2983
|
+
for (const source of archived.reverse()) {
|
|
2984
|
+
try {
|
|
2985
|
+
const restored = await this.restoreFromArchive(source, undefined, true, true);
|
|
2986
|
+
if (!restored.ok)
|
|
2987
|
+
failedRestores.push(source);
|
|
2988
|
+
}
|
|
2989
|
+
catch {
|
|
2990
|
+
// restoreFromArchive never rejects by contract; if it ever does,
|
|
2991
|
+
// count the source as unrestored rather than replacing the report.
|
|
2992
|
+
failedRestores.push(source);
|
|
2993
|
+
}
|
|
2994
|
+
}
|
|
2995
|
+
if (failedRestores.length > 0) {
|
|
2996
|
+
return { ok: false, message: `合并失败(${reason});已回滚,但以下未回滚:${failedRestores.join(', ')}:它们仍在 .archive 里,请用 /evolution skill restore 恢复。` };
|
|
2997
|
+
}
|
|
2998
|
+
return { ok: false, message: `合并失败,已回滚:${reason}` };
|
|
2768
2999
|
}
|
|
2769
|
-
const result = await this.archive(source, { absorbedInto: targetName });
|
|
2770
|
-
if (!result.ok)
|
|
2771
|
-
throw new Error(result.message);
|
|
2772
|
-
archived.push(source);
|
|
2773
|
-
}
|
|
2774
|
-
// V8-11 (0.3.46): the target pre-read and the merged/pointer construction
|
|
2775
|
-
// happen INSIDE the in-process serialize queue — a concurrent
|
|
2776
|
-
// patch/update between the old pre-read and the commit used to be
|
|
2777
|
-
// silently overwritten (the serial chain is the same second layer
|
|
2778
|
-
// update/patch/restructure/writeSupportFile use).
|
|
2779
|
-
const freshTargetMd = await this.io.readText(join(targetDir, 'SKILL.md'));
|
|
2780
|
-
// S1-E1: everything below runs AFTER the sources are already archived —
|
|
2781
|
-
// these three exits used to `return`, which skips the catch's rollback
|
|
2782
|
-
// (JS: return does not pass through catch) and left every source in
|
|
2783
|
-
// .archive while the message implied nothing had happened. Throw so
|
|
2784
|
-
// the T-14 rollback below brings them back; the catch prefixes the
|
|
2785
|
-
// reason with the rollback outcome, so the reasons here name only the
|
|
2786
|
-
// failure itself.
|
|
2787
|
-
if (!freshTargetMd)
|
|
2788
|
-
throw new Error(`target "${targetName}" disappeared mid-consolidate`);
|
|
2789
|
-
// V10-01 (P2-2): reference-mode targets APPEND, mirroring restructure
|
|
2790
|
-
// (base + '\n\n' + new text) — a second consolidate of a re-created
|
|
2791
|
-
// source used to overwrite the first demotion's bytes (silent loss of
|
|
2792
|
-
// the older degraded knowledge). The previous bytes are read INSIDE
|
|
2793
|
-
// the serial queue (V8-11 discipline), so a concurrent patch between
|
|
2794
|
-
// planning and commit is never silently overwritten; applyTreeChange
|
|
2795
|
-
// re-reads at commit for the rollback bytes.
|
|
2796
|
-
const writes = [];
|
|
2797
|
-
for (const reference of referenceWrites) {
|
|
2798
|
-
const previous = await this.readForCas(reference.target);
|
|
2799
|
-
const base = previous?.trimEnd() ?? '';
|
|
2800
|
-
// V24-01: carry the plan-time bytes as the CAS baseline — a read
|
|
2801
|
-
// error here reads as null and stays fail-closed at commit (an
|
|
2802
|
-
// existing file then counts as drift).
|
|
2803
|
-
writes.push({ target: reference.target, content: base === '' ? reference.content : `${base}\n\n${reference.content}`, expected: previous });
|
|
2804
|
-
}
|
|
2805
|
-
// V2 (design §16.7): the re-homed support files ride the SAME commit as the
|
|
2806
|
-
// merged body — one tree change, one rollback domain, and the body's
|
|
2807
|
-
// rewritten references can never be committed without their targets.
|
|
2808
|
-
for (const file of rehomed) {
|
|
2809
|
-
const target = join(targetDir, ...file.to.split('/'));
|
|
2810
|
-
const previous = await this.readForCas(target);
|
|
2811
|
-
writes.push({ target, content: file.content, expected: previous });
|
|
2812
|
-
}
|
|
2813
|
-
if (mode === 'append') {
|
|
2814
|
-
const merged = freshTargetMd.trimEnd() + parts.join('\n') + '\n';
|
|
2815
|
-
const validation = validateFrontmatter(merged, targetName, this.limits);
|
|
2816
|
-
if (validation)
|
|
2817
|
-
throw new Error(`merge validation failed: ${validation}`);
|
|
2818
|
-
writes.push({ target: join(targetDir, 'SKILL.md'), content: merged, expected: freshTargetMd });
|
|
2819
|
-
}
|
|
2820
|
-
else {
|
|
2821
|
-
const pointerLines = demotedPointers.map(lines => `\n${lines.join('\n')}`).join('');
|
|
2822
|
-
const extended = freshTargetMd.trimEnd() + pointerLines + '\n';
|
|
2823
|
-
const validation = validateFrontmatter(extended, targetName, this.limits);
|
|
2824
|
-
if (validation)
|
|
2825
|
-
throw new Error(`merge validation failed: ${validation}`);
|
|
2826
|
-
writes.push({ target: join(targetDir, 'SKILL.md'), content: extended, expected: freshTargetMd });
|
|
2827
|
-
}
|
|
2828
|
-
const result = await this.applyTreeChange({
|
|
2829
|
-
name: targetName,
|
|
2830
|
-
origin,
|
|
2831
|
-
protection: 'write',
|
|
2832
|
-
writes,
|
|
2833
|
-
auditAction: 'consolidate',
|
|
2834
|
-
auditSummary: `consolidated ${normalizedSources.join(', ')} (${mode}) into ${targetName}`
|
|
2835
|
-
+ (rehomed.length === 0 ? '' : `; re-homed ${rehomed.map(file => `${file.from}->${file.to}`).join(', ')}`),
|
|
2836
|
-
eventAction: 'consolidate',
|
|
2837
3000
|
});
|
|
2838
|
-
if (!result.ok)
|
|
2839
|
-
throw new Error(result.message);
|
|
2840
|
-
return { ok: true, message: `已把 ${normalizedSources.join(', ')} 合并进「${targetName}」。`, path: targetDir };
|
|
2841
3001
|
}
|
|
2842
|
-
|
|
2843
|
-
|
|
2844
|
-
|
|
2845
|
-
// `.catch(() => {})` while the message still claimed a full rollback —
|
|
2846
|
-
// the source stayed in .archive silently. Surface it.
|
|
2847
|
-
const reason = error instanceof Error ? error.message : String(error);
|
|
2848
|
-
const failedRestores = [];
|
|
2849
|
-
for (const source of archived.reverse()) {
|
|
2850
|
-
try {
|
|
2851
|
-
const restored = await this.restoreFromArchive(source);
|
|
2852
|
-
if (!restored.ok)
|
|
2853
|
-
failedRestores.push(source);
|
|
2854
|
-
}
|
|
2855
|
-
catch {
|
|
2856
|
-
// restoreFromArchive never rejects by contract; if it ever does,
|
|
2857
|
-
// count the source as unrestored rather than replacing the report.
|
|
2858
|
-
failedRestores.push(source);
|
|
2859
|
-
}
|
|
2860
|
-
}
|
|
2861
|
-
if (failedRestores.length > 0) {
|
|
2862
|
-
return { ok: false, message: `合并失败(${reason});已回滚,但以下未回滚:${failedRestores.join(', ')}:它们仍在 .archive 里,请用 /evolution skill restore 恢复。` };
|
|
2863
|
-
}
|
|
2864
|
-
return { ok: false, message: `合并失败,已回滚:${reason}` };
|
|
3002
|
+
finally {
|
|
3003
|
+
if (sourceLease !== undefined)
|
|
3004
|
+
await sourceLease.release();
|
|
2865
3005
|
}
|
|
2866
3006
|
});
|
|
2867
3007
|
}
|
|
@@ -2882,7 +3022,7 @@ export class SkillLibrary {
|
|
|
2882
3022
|
await this.ensureRecovered();
|
|
2883
3023
|
// F-208: the whole read→plan→write runs under the in-process serialize
|
|
2884
3024
|
// queue so two concurrent restructures on one skill never interleave.
|
|
2885
|
-
return await this.restructureCore(name, moves, origin, change);
|
|
3025
|
+
return await this.rootGate.write(() => this.restructureCore(name, moves, origin, change));
|
|
2886
3026
|
}
|
|
2887
3027
|
async restructureCore(name, moves, origin, change) {
|
|
2888
3028
|
const badName = this.badName(name);
|
|
@@ -3019,6 +3159,7 @@ export class SkillLibrary {
|
|
|
3019
3159
|
limits: { maxSkillFileBytes: this.limits.maxSkillFileBytes, maxSkillContentChars: this.limits.maxSkillContentChars },
|
|
3020
3160
|
serial: this.serial,
|
|
3021
3161
|
lock: this.lockPort(),
|
|
3162
|
+
targetKeys: [skillNamespaceKey(name)],
|
|
3022
3163
|
hooks,
|
|
3023
3164
|
validateWrite: op => op.kind === 'write' ? this.contentThreatBlock(op.content) : null,
|
|
3024
3165
|
});
|
|
@@ -3053,6 +3194,9 @@ export class SkillLibrary {
|
|
|
3053
3194
|
*/
|
|
3054
3195
|
async extract(plan, origin = this.authority.origin, change) {
|
|
3055
3196
|
await this.ensureRecovered();
|
|
3197
|
+
return await this.rootGate.write(() => this.extractCore(plan, origin, change));
|
|
3198
|
+
}
|
|
3199
|
+
async extractCore(plan, origin, change) {
|
|
3056
3200
|
if (plan.outcome === 'owner-gap' || plan.owner.mode !== 'covered')
|
|
3057
3201
|
return { ok: false, message: '提取被拒绝:owner-gap 不是写操作。' };
|
|
3058
3202
|
if (plan.support.unresolved.length > 0 || plan.support.dangling.length > 0)
|
|
@@ -3148,6 +3292,7 @@ export class SkillLibrary {
|
|
|
3148
3292
|
limits: { maxSkillFileBytes: this.limits.maxSkillFileBytes, maxSkillContentChars: this.limits.maxSkillContentChars },
|
|
3149
3293
|
serial: this.serial,
|
|
3150
3294
|
lock: this.lockPort(),
|
|
3295
|
+
targetKeys: [skillNamespaceKey(source), skillNamespaceKey(target)],
|
|
3151
3296
|
hooks,
|
|
3152
3297
|
validateWrite: op => op.kind === 'write' ? this.contentThreatBlock(op.content) : null,
|
|
3153
3298
|
});
|
|
@@ -3233,6 +3378,7 @@ export class SkillLibrary {
|
|
|
3233
3378
|
const unit = this.commitUnit({
|
|
3234
3379
|
limits: this.limits,
|
|
3235
3380
|
...(plan.nested === true ? { nested: true } : { lock: this.lockPort() }),
|
|
3381
|
+
targetKeys: [...new Set(landing.map(entry => entry.skill))].map(skillNamespaceKey),
|
|
3236
3382
|
...(this.transact === undefined ? {} : { transact: this.transact }),
|
|
3237
3383
|
now: () => Date.now(),
|
|
3238
3384
|
});
|
|
@@ -3291,8 +3437,28 @@ export class SkillLibrary {
|
|
|
3291
3437
|
* recoverability: archival never deletes, and this is the control-plane
|
|
3292
3438
|
* path back. The `.archive-reason` marker is dropped on restore.
|
|
3293
3439
|
*/
|
|
3294
|
-
async restoreFromArchive(rawName, origin = this.authority.origin) {
|
|
3295
|
-
|
|
3440
|
+
async restoreFromArchive(rawName, origin = this.authority.origin, rootHeld = false, namespaceHeld = false) {
|
|
3441
|
+
if (rootHeld) {
|
|
3442
|
+
if (!this.keyedTargetLocks() || namespaceHeld)
|
|
3443
|
+
return await this.restoreFromArchiveCore(rawName, origin, true);
|
|
3444
|
+
const lease = await this.lockPort().acquire([skillNamespaceKey(rawName)]);
|
|
3445
|
+
try {
|
|
3446
|
+
return await this.restoreFromArchiveCore(rawName, origin, true);
|
|
3447
|
+
}
|
|
3448
|
+
finally {
|
|
3449
|
+
await lease.release();
|
|
3450
|
+
}
|
|
3451
|
+
}
|
|
3452
|
+
const namespace = skillNamespaceKey(rawName);
|
|
3453
|
+
return await this.rootGate.write(async () => {
|
|
3454
|
+
const lease = await this.lockPort().acquire([namespace]);
|
|
3455
|
+
try {
|
|
3456
|
+
return await this.restoreFromArchiveCore(rawName, origin, true);
|
|
3457
|
+
}
|
|
3458
|
+
finally {
|
|
3459
|
+
await lease.release();
|
|
3460
|
+
}
|
|
3461
|
+
});
|
|
3296
3462
|
}
|
|
3297
3463
|
async restoreFromArchiveCore(rawName, origin, fenceHeld) {
|
|
3298
3464
|
const name = rawName.trim();
|
|
@@ -3450,9 +3616,61 @@ export class SkillLibrary {
|
|
|
3450
3616
|
this.notifyMutation({ action: 'restore', name, skillDir: dest });
|
|
3451
3617
|
return { ok: true, message: `技能「${name}」已从 .archive 恢复。`, path: dest };
|
|
3452
3618
|
}
|
|
3619
|
+
/** Result of the low-level CAS primitive. It intentionally has no audit/event. */
|
|
3620
|
+
async writeFileCas(rawName, filePath, intent) {
|
|
3621
|
+
await this.ensureRecovered();
|
|
3622
|
+
const name = rawName.trim();
|
|
3623
|
+
const badName = this.badName(name);
|
|
3624
|
+
if (badName !== null)
|
|
3625
|
+
return { ok: false, message: badName, reason: 'invalid' };
|
|
3626
|
+
let target;
|
|
3627
|
+
if (filePath === '') {
|
|
3628
|
+
target = join(this.dirOf(name), 'SKILL.md');
|
|
3629
|
+
}
|
|
3630
|
+
else {
|
|
3631
|
+
const validation = validateSupportPath(filePath);
|
|
3632
|
+
if (validation !== null)
|
|
3633
|
+
return { ok: false, message: validation, reason: 'invalid' };
|
|
3634
|
+
target = join(this.dirOf(name), ...filePath.replace(/\\/g, '/').split('/').filter(Boolean));
|
|
3635
|
+
}
|
|
3636
|
+
return await this.serial(() => this.withMutationLock(async () => {
|
|
3637
|
+
let refusal;
|
|
3638
|
+
const apply = (current) => {
|
|
3639
|
+
const decision = decideSkillWrite(intent, current === null
|
|
3640
|
+
? { kind: 'absent' }
|
|
3641
|
+
: { kind: 'present', version: contentHash(current), content: current });
|
|
3642
|
+
if (decision.kind === 'refuse') {
|
|
3643
|
+
refusal = { reason: decision.reason, message: decision.message };
|
|
3644
|
+
return current;
|
|
3645
|
+
}
|
|
3646
|
+
return decision.next;
|
|
3647
|
+
};
|
|
3648
|
+
let next;
|
|
3649
|
+
if (this.transact !== undefined) {
|
|
3650
|
+
next = null;
|
|
3651
|
+
await this.transact(this.io, target, (current) => {
|
|
3652
|
+
next = apply(current);
|
|
3653
|
+
return next;
|
|
3654
|
+
});
|
|
3655
|
+
}
|
|
3656
|
+
else {
|
|
3657
|
+
const current = await probeText(this.io, target);
|
|
3658
|
+
if (isUnknown(current))
|
|
3659
|
+
return { ok: false, message: `cannot read ${target}: ${current.reason}`, reason: 'invalid' };
|
|
3660
|
+
const value = isPresent(current) ? current.value : null;
|
|
3661
|
+
next = apply(value);
|
|
3662
|
+
if (next !== null && next !== value)
|
|
3663
|
+
await this.io.writeText(target, next);
|
|
3664
|
+
}
|
|
3665
|
+
if (refusal !== undefined)
|
|
3666
|
+
return { ok: false, message: refusal.message, reason: refusal.reason };
|
|
3667
|
+
return { ok: true, message: 'skill file written', path: target };
|
|
3668
|
+
}));
|
|
3669
|
+
}
|
|
3453
3670
|
async writeSupportFile(rawName, filePath, content, origin = this.authority.origin, anchor) {
|
|
3454
3671
|
const name = rawName.trim();
|
|
3455
|
-
|
|
3672
|
+
const key = 'skill::' + name + '::' + filePath.replace(/\\/g, '/');
|
|
3673
|
+
return await this.rootGate.read(() => this.withTarget(key, () => this.writeSupportFileCore(name, filePath, content, origin, anchor)));
|
|
3456
3674
|
}
|
|
3457
3675
|
async writeSupportFileCore(name, filePath, content, origin, anchor) {
|
|
3458
3676
|
const badName = this.badName(name);
|
|
@@ -3496,6 +3714,7 @@ export class SkillLibrary {
|
|
|
3496
3714
|
limits: { maxSkillFileBytes: Number.MAX_SAFE_INTEGER, maxSkillContentChars: Number.MAX_SAFE_INTEGER },
|
|
3497
3715
|
serial: this.serial,
|
|
3498
3716
|
lock: this.lockPort(),
|
|
3717
|
+
targetKeys: ['skill::' + name + '::' + filePath.replace(/\\/g, '/'), skillNamespaceKey(name)],
|
|
3499
3718
|
...(this.transact === undefined ? {} : { transact: this.transact }),
|
|
3500
3719
|
hooks: {
|
|
3501
3720
|
committed: async (event) => {
|
|
@@ -3524,7 +3743,8 @@ export class SkillLibrary {
|
|
|
3524
3743
|
return { ok: true, message: `支撑文件「${filePath}」已写入「${name}」。${capAdvisory}${warning}`, path: target };
|
|
3525
3744
|
}
|
|
3526
3745
|
async removeSupportFile(rawName, filePath, origin = this.authority.origin, anchor, unitId) {
|
|
3527
|
-
|
|
3746
|
+
const key = 'skill::' + rawName.trim() + '::' + filePath.replace(/\\/g, '/');
|
|
3747
|
+
return await this.rootGate.read(() => this.withTarget(key, () => this.removeSupportFileCore(rawName.trim(), filePath, origin, anchor, unitId)));
|
|
3528
3748
|
}
|
|
3529
3749
|
async removeSupportFileCore(name, filePath, origin, anchor, unitId) {
|
|
3530
3750
|
const badName = this.badName(name);
|