@lmzhen/dsh-evolution-core 0.41.0 → 0.43.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/composition/index.js +2 -2
- package/lib/{composition-Da8NfRI7.js → composition-CVafrlEw.js} +2 -2
- package/lib/guards-3f02mnf2.js +29 -0
- package/lib/http-routes.js +205 -1
- package/lib/index.js +3584 -15050
- package/lib/mutations-jUuOPaCn.js +718 -0
- package/lib/platform/index.js +2 -2
- package/lib/{platform-CFp373_0.js → platform-B06_h8t-.js} +4 -1
- package/lib/runtime/plugin.js +2 -2
- package/lib/{session-projection-CXUNPkq9.js → session-projection-EB7mUOlJ.js} +63 -63
- package/lib/skill-health-BLGZTIv8.js +3773 -0
- package/lib/skill-history-_Cssts5o.js +1912 -0
- package/lib/skills.js +4067 -0
- package/lib/subagent/index.js +1 -1
- package/lib/types/home-fence.d.ts +7 -0
- package/lib/types/home-fence.js +58 -3
- package/lib/types/index.d.ts +1 -18
- package/lib/types/index.js +1 -18
- package/lib/types/io.js +1 -1
- package/lib/types/mutation-authority.d.ts +14 -37
- package/lib/types/mutation-authority.js +16 -103
- package/lib/types/mutation-storage-adapter.js +9 -6
- package/lib/types/mutation-unit.d.ts +14 -0
- package/lib/types/mutation-unit.js +30 -10
- package/lib/types/opt-in.js +1 -1
- package/lib/types/params.js +1 -1
- package/lib/types/platform/index.d.ts +8 -1
- package/lib/types/platform/index.js +3 -0
- package/lib/types/platform-services.js +0 -1
- package/lib/types/review-channel.js +3 -1
- package/lib/types/review-context.js +3 -1
- package/lib/types/run-registry.d.ts +2 -24
- package/lib/types/scope.js +1 -1
- package/lib/types/signals.d.ts +1 -1
- package/lib/types/skill-store.d.ts +7 -1
- package/lib/types/skill-store.js +43 -80
- package/lib/types/skills.d.ts +11 -0
- package/lib/types/skills.js +11 -0
- package/lib/types/subagent/types.d.ts +3 -3
- package/lib/types/tree-lock.js +4 -1
- package/lib/types/unit-claim.d.ts +8 -0
- package/lib/types/unit-claim.js +3 -0
- package/lib/types/unit-journal.d.ts +3 -1
- package/lib/types/unit-journal.js +12 -3
- package/lib/types/unit-storage.d.ts +1 -0
- package/lib/types/write-gates.d.ts +1 -1
- package/lib/types/write-gates.js +3 -1
- package/lib/types/write.d.ts +11 -0
- package/lib/types/write.js +11 -0
- package/lib/write.js +357 -0
- package/package.json +16 -4
- package/lib/http-routes-_anZVlPf.js +0 -233
- package/lib/types/unit-backend.d.ts +0 -5
- package/lib/types/unit-backend.js +0 -55
- package/lib/types/unit-transaction.d.ts +0 -225
- package/lib/types/unit-transaction.js +0 -501
- package/lib/{ensure-C5Mo1dbB.js → ensure-BjToTMMj.js} +1 -1
package/lib/skills.js
ADDED
|
@@ -0,0 +1,4067 @@
|
|
|
1
|
+
import { q as resolveCitations } from "./session-projection-EB7mUOlJ.js";
|
|
2
|
+
import { $t as supportRefs, B as appendEvolutionEvent, Bt as authoringFeedback, Ct as loadUsage, D as scanContentThreats, F as trimPatternBoundaries, Ft as selectSections, Gt as normalizeFrontmatter, Ht as exceedsContentLimit, J as RULES, Jt as shrinksOverLimit, Kt as parseFrontmatter, P as fuzzyPatch, Pt as projectExtractBodies, Tt as mutateUsage, Ut as frontmatterBlock, V as eventsFile, Vt as ensureSkillFrontmatter, Wt as frontmatterCatalogInvalid, X as diffFindings, Xt as validateFrontmatter, Y as countReferenceFiles, Yt as skillMdOnDisk, Z as lintSkill, Zt as yamlPlainScalarNeedsQuotes, _n as POLICY_STAGE_DEFAULTS, a as lintBody, an as filterUnreadSkillOps, cn as sessionReadSupportFiles, dn as authorityFrom, en as applyReferenceRewrite, fn as DEFAULT_ARCHIVE_RETENTION_POLICY, gn as DEFAULT_SUPPORT_FILE_CHAR_POLICY, hn as DEFAULT_SKILL_LIMITS, i as assessStructureHealth, in as READ_REQUIRED_ACTIONS, j as makeSerialQueue, jt as usageFile, kt as suppressedFile, mn as DEFAULT_REFERENCE_REWRITE_POLICY, n as HEALTH_STAMP_RE, nn as planReferenceRewrite, on as isUnreadWrite, or as SKILL_NAME_RE, pn as DEFAULT_CITATION_POLICY, qt as relatedSkillNames, r as MIN_STAMP_BODY_CHARS, rn as planRehoming, rr as PROTECTED_BUILTIN_SKILLS, s as mutationLockFrom, sn as sessionReadSkillNames, sr as SUPPORT_DIRS, st as evolutionRoot, t as DEFAULT_HEALTH_THRESHOLDS, tn as describeReferenceRewrite, v as currentReviewContext, vn as policyStageLimits, x as isReviewChannelSession, xn as CONTENT_SPLIT_HINT, yt as getRecord } from "./skill-health-BLGZTIv8.js";
|
|
3
|
+
import { C as probeList, D as probeText, E as probeReason, O as probeUnknown, S as probeAbsent, T as probePresent, _ as isAbsent, b as isUnknown, d as nodeEvolutionIo, i as loadMutations, l as isCommittedWarning, o as recordMutation, p as transactIo, r as contentHash, w as probeMtime, y as isPresent } from "./mutations-jUuOPaCn.js";
|
|
4
|
+
import { A as unitJournalPort, C as readHistoryIndex, D as versionSummaryPrompt, E as versionActionKind, O as versionTarget, S as partitionVersions, T as textDiffFacts, _ as loadVersions, a as RETENTION_FEEDBACK_MIN_CHARS, b as orderVersions, c as VERSION_SUMMARY_MAX_CHARS, d as elapsedSince, et as MutationUnit, f as entryTarget, g as loadVersionContent, h as latestVersionAt, i as RETENTION_FEEDBACK_KEEP_RATIO, j as unitSnapshotPort, k as pruneTreeChangeUnits, l as blobPath, m as historyRoot, n as HISTORY_DIR, o as TEXT_DIFF_MAX_CHARS, p as historyIndexFile, r as HISTORY_INDEX_VERSION, s as TEXT_DIFF_MAX_LINES, t as BASELINE_ACTION, tt as fileMutationLock, u as contentRetentionFeedback, v as nextHistoryIndex, w as recordVersions, x as parseHistoryIndex, y as normalizeVersionSummary } from "./skill-history-_Cssts5o.js";
|
|
5
|
+
import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
6
|
+
//#region lib/types/skill-row-cells.js
|
|
7
|
+
/**
|
|
8
|
+
* The cells one row shows, decided here and rendered by the client.
|
|
9
|
+
*
|
|
10
|
+
* Why it exists: until 0.14.1 a row's information architecture lived inside one JSX expression
|
|
11
|
+
* (description + ' · ' + state + ' · ' + age), so which facts survived the browser's single-line
|
|
12
|
+
* ellipsis was an accident of concatenation order — on a real library the skill row's age and
|
|
13
|
+
* curation state were clipped away on EVERY row (measured 2026-09-28: 6 skills, descriptions
|
|
14
|
+
* 49–61 characters, ~240px of line). A row now arrives as an ORDERED list of cells, each declaring
|
|
15
|
+
* its slot, and the renderer lays them out: `aside` cells are right-aligned and never truncate, so a
|
|
16
|
+
* decision fact cannot be eaten by a long description again.
|
|
17
|
+
*
|
|
18
|
+
* Invariants: no words live here. A cell carries either a locale key (`copy`, with the values its
|
|
19
|
+
* template needs) or a verbatim fact (`literal` — numbers, hashes, recorded paths). Facts come from
|
|
20
|
+
* the host; the dictionary owns every sentence and every number format, including the ones the panel
|
|
21
|
+
* used to build itself (`row.delta.up`, `time.<unit>.one`, `versions.count`).
|
|
22
|
+
* @module @lmzhen/dsh-evolution-core/skill-row-cells
|
|
23
|
+
*/
|
|
24
|
+
/** The actions whose row carries an explanatory hover text. */
|
|
25
|
+
const ACTION_NOTES = {
|
|
26
|
+
delete: "action.delete.note",
|
|
27
|
+
archive: "action.archive.note"
|
|
28
|
+
};
|
|
29
|
+
/** The actions whose bytes come from a support file rather than from SKILL.md. */
|
|
30
|
+
const SUPPORT_ACTIONS = ["support-write", "support-remove"];
|
|
31
|
+
/**
|
|
32
|
+
* The relative-time key for one bucket: a count of one is spelled on its own.
|
|
33
|
+
* @param age - the bucket the host reported.
|
|
34
|
+
* @returns the locale key, singular or plural.
|
|
35
|
+
*/
|
|
36
|
+
function ageCopyKey(age) {
|
|
37
|
+
if (age.unit === "now") return "time.now";
|
|
38
|
+
return age.n === 1 ? "time." + age.unit + ".one" : "time." + age.unit;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* The state word one skill row carries, from the facts the listing reported.
|
|
42
|
+
* @param skill - the row's facts.
|
|
43
|
+
* @returns the locale key for its state.
|
|
44
|
+
*/
|
|
45
|
+
function skillStateKey(skill) {
|
|
46
|
+
if (skill.protectionUnknown) return "state.unknown";
|
|
47
|
+
if (skill.protectedBy !== null) return "state.protected";
|
|
48
|
+
return skill.managed ? "state.managed" : "state.foreign";
|
|
49
|
+
}
|
|
50
|
+
/** The hover text one action word needs, or nothing when it needs none. */
|
|
51
|
+
function actionNote(actionKind) {
|
|
52
|
+
const note = ACTION_NOTES[actionKind];
|
|
53
|
+
return note === void 0 ? {} : { note };
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* The cells of one version row: the facts on the title line, the summary (if any) under it.
|
|
57
|
+
* @param row - the row's facts.
|
|
58
|
+
* @returns both lines.
|
|
59
|
+
*/
|
|
60
|
+
function versionRowCells(row) {
|
|
61
|
+
const title = [
|
|
62
|
+
{
|
|
63
|
+
key: "v",
|
|
64
|
+
copy: "row.version",
|
|
65
|
+
values: { n: row.v },
|
|
66
|
+
tone: "tertiary",
|
|
67
|
+
slot: "meta"
|
|
68
|
+
},
|
|
69
|
+
{
|
|
70
|
+
key: "action",
|
|
71
|
+
copy: "action." + row.actionKind,
|
|
72
|
+
tone: "primary",
|
|
73
|
+
slot: "lead",
|
|
74
|
+
...actionNote(row.actionKind)
|
|
75
|
+
},
|
|
76
|
+
{
|
|
77
|
+
key: "time",
|
|
78
|
+
copy: ageCopyKey(row.age),
|
|
79
|
+
values: { n: row.age.n },
|
|
80
|
+
tone: "tertiary",
|
|
81
|
+
slot: "meta"
|
|
82
|
+
}
|
|
83
|
+
];
|
|
84
|
+
if (row.path !== void 0) title.push({
|
|
85
|
+
key: "path",
|
|
86
|
+
literal: row.path,
|
|
87
|
+
tone: "tertiary",
|
|
88
|
+
slot: "meta",
|
|
89
|
+
note: row.path
|
|
90
|
+
});
|
|
91
|
+
else if (SUPPORT_ACTIONS.includes(row.actionKind)) title.push({
|
|
92
|
+
key: "path",
|
|
93
|
+
copy: "path.unrecorded",
|
|
94
|
+
tone: "tertiary",
|
|
95
|
+
slot: "meta"
|
|
96
|
+
});
|
|
97
|
+
const delta = row.charsDelta;
|
|
98
|
+
if (delta !== void 0 && delta !== 0) title.push({
|
|
99
|
+
key: "delta",
|
|
100
|
+
copy: delta > 0 ? "row.delta.up" : "row.delta.down",
|
|
101
|
+
values: { n: Math.abs(delta) },
|
|
102
|
+
tone: "tertiary",
|
|
103
|
+
slot: "meta"
|
|
104
|
+
});
|
|
105
|
+
if (row.hash !== void 0 && row.hash !== "") title.push({
|
|
106
|
+
key: "hash",
|
|
107
|
+
literal: row.hash.slice(0, 7),
|
|
108
|
+
tone: "tertiary",
|
|
109
|
+
slot: "meta",
|
|
110
|
+
note: row.hash
|
|
111
|
+
});
|
|
112
|
+
const meta = [];
|
|
113
|
+
if (row.summary !== void 0 && row.summary !== "") meta.push({
|
|
114
|
+
key: "summary",
|
|
115
|
+
literal: row.summary,
|
|
116
|
+
tone: "secondary",
|
|
117
|
+
slot: "lead"
|
|
118
|
+
});
|
|
119
|
+
return {
|
|
120
|
+
title,
|
|
121
|
+
meta
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* The cells of one skill row: the name line, then the facts that describe it.
|
|
126
|
+
*
|
|
127
|
+
* The description is a `lead` cell (it is the one allowed to truncate, with the full text on hover),
|
|
128
|
+
* while the version count and the last-changed time are `aside` cells — they survive any description.
|
|
129
|
+
* The description is NOT pre-truncated in JavaScript: the browser's ellipsis already clips it at the
|
|
130
|
+
* layout's real width, and a character cut on top of that only hides where the fact ends.
|
|
131
|
+
* @param skill - the row's facts.
|
|
132
|
+
* @returns both lines.
|
|
133
|
+
*/
|
|
134
|
+
function skillRowCells(skill) {
|
|
135
|
+
const title = [{
|
|
136
|
+
key: "name",
|
|
137
|
+
literal: skill.name,
|
|
138
|
+
tone: "primary",
|
|
139
|
+
slot: "lead",
|
|
140
|
+
note: skill.name
|
|
141
|
+
}, {
|
|
142
|
+
key: "count",
|
|
143
|
+
copy: "versions.count",
|
|
144
|
+
values: { n: skill.versions },
|
|
145
|
+
tone: "tertiary",
|
|
146
|
+
slot: "aside"
|
|
147
|
+
}];
|
|
148
|
+
const meta = [{
|
|
149
|
+
key: "description",
|
|
150
|
+
literal: skill.description,
|
|
151
|
+
tone: "tertiary",
|
|
152
|
+
slot: "lead",
|
|
153
|
+
note: skill.description
|
|
154
|
+
}];
|
|
155
|
+
if (!skill.managed || skill.protectedBy !== null || skill.protectionUnknown) meta.push({
|
|
156
|
+
key: "state",
|
|
157
|
+
copy: skillStateKey(skill),
|
|
158
|
+
tone: "tertiary",
|
|
159
|
+
slot: "meta"
|
|
160
|
+
});
|
|
161
|
+
if (skill.protectedBy !== null) meta.push({
|
|
162
|
+
key: "protectedBy",
|
|
163
|
+
literal: skill.protectedBy,
|
|
164
|
+
tone: "tertiary",
|
|
165
|
+
slot: "meta",
|
|
166
|
+
note: skill.protectedBy
|
|
167
|
+
});
|
|
168
|
+
if (skill.age !== null) meta.push({
|
|
169
|
+
key: "age",
|
|
170
|
+
copy: ageCopyKey(skill.age),
|
|
171
|
+
values: { n: skill.age.n },
|
|
172
|
+
tone: "tertiary",
|
|
173
|
+
slot: "aside"
|
|
174
|
+
});
|
|
175
|
+
return {
|
|
176
|
+
title,
|
|
177
|
+
meta
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
//#endregion
|
|
181
|
+
//#region lib/types/skill-model.js
|
|
182
|
+
function canonical(value) {
|
|
183
|
+
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
|
184
|
+
if (Array.isArray(value)) return "[" + value.map(canonical).join(",") + "]";
|
|
185
|
+
const record = value;
|
|
186
|
+
return "{" + Object.keys(record).sort().map((key) => JSON.stringify(key) + ":" + canonical(record[key])).join(",") + "}";
|
|
187
|
+
}
|
|
188
|
+
function threeFieldHash(summary) {
|
|
189
|
+
return contentHash(canonical([
|
|
190
|
+
summary.name,
|
|
191
|
+
summary.description,
|
|
192
|
+
summary.whenToUse ?? ""
|
|
193
|
+
]));
|
|
194
|
+
}
|
|
195
|
+
function supportHash(files) {
|
|
196
|
+
return contentHash(canonical(files.map((file) => [
|
|
197
|
+
file.path,
|
|
198
|
+
file.sha256,
|
|
199
|
+
file.bytes
|
|
200
|
+
])));
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Canonical read face for skill consumers.
|
|
204
|
+
*
|
|
205
|
+
* This is an adapter, not a second store: the provider owns IO and summary
|
|
206
|
+
* extraction. Every consumer reads the same SkillDocument contract so owner,
|
|
207
|
+
* health, panel and future domain/search surfaces cannot drift on parsing,
|
|
208
|
+
* whenToUse or support hashing.
|
|
209
|
+
*/
|
|
210
|
+
var SkillModel = class {
|
|
211
|
+
provider;
|
|
212
|
+
constructor(provider) {
|
|
213
|
+
this.provider = provider;
|
|
214
|
+
}
|
|
215
|
+
async list(query = {}) {
|
|
216
|
+
return await this.provider.list(query);
|
|
217
|
+
}
|
|
218
|
+
async get(name) {
|
|
219
|
+
const summary = (await this.provider.list({ withFrontmatter: true })).find((candidate) => candidate.name === name);
|
|
220
|
+
if (summary === void 0) return null;
|
|
221
|
+
let content = null;
|
|
222
|
+
let readable = true;
|
|
223
|
+
try {
|
|
224
|
+
content = await this.provider.read(name);
|
|
225
|
+
} catch {
|
|
226
|
+
readable = false;
|
|
227
|
+
}
|
|
228
|
+
if (content === null) readable = false;
|
|
229
|
+
const paths = readable ? await this.provider.listSupportFiles(name) : [];
|
|
230
|
+
const support = [];
|
|
231
|
+
for (const path of paths) {
|
|
232
|
+
const file = await this.provider.readSupportFile(name, path);
|
|
233
|
+
if (file === null) continue;
|
|
234
|
+
support.push({
|
|
235
|
+
path,
|
|
236
|
+
bytes: Buffer.byteLength(file, "utf8"),
|
|
237
|
+
sha256: contentHash(file)
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
support.sort((a, b) => a.path.localeCompare(b.path));
|
|
241
|
+
return {
|
|
242
|
+
summary,
|
|
243
|
+
content: content ?? "",
|
|
244
|
+
frontmatter: summary.frontmatter ?? {},
|
|
245
|
+
support,
|
|
246
|
+
hashes: {
|
|
247
|
+
threeField: threeFieldHash(summary),
|
|
248
|
+
content: contentHash(content ?? ""),
|
|
249
|
+
support: supportHash(support)
|
|
250
|
+
},
|
|
251
|
+
readable
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
};
|
|
255
|
+
//#endregion
|
|
256
|
+
//#region lib/types/skill-revision.js
|
|
257
|
+
/**
|
|
258
|
+
* Content-revision identity shared by every planner that records a decision and every
|
|
259
|
+
* committer that re-checks it.
|
|
260
|
+
*
|
|
261
|
+
* A skill's revision covers the trimmed NAME, the SKILL.md body and every support file
|
|
262
|
+
* (`references/…`, `templates/…`, `scripts/…`, `assets/…`), each as read through the
|
|
263
|
+
* store. The merge domain records a decision-time anchor and the store compares the live
|
|
264
|
+
* anchor before writing; both sides must hash the same bytes or the compare is meaningless,
|
|
265
|
+
* so the hash lives HERE and nowhere else.
|
|
266
|
+
*/
|
|
267
|
+
/**
|
|
268
|
+
* Canonical fingerprint of one skill's content.
|
|
269
|
+
*
|
|
270
|
+
* Field order and separators are a wire format: decisions persist anchors derived from
|
|
271
|
+
* this string, and a later commit compares against it. Do not reorder.
|
|
272
|
+
* @param name - the (trimmed) skill name.
|
|
273
|
+
* @param body - the SKILL.md text.
|
|
274
|
+
* @param files - every support file under SUPPORT_DIRS.
|
|
275
|
+
* @returns the fingerprint string to hash.
|
|
276
|
+
*/
|
|
277
|
+
function revisionFingerprint(name, body, files) {
|
|
278
|
+
const ordered = [...files].sort((left, right) => left.path.localeCompare(right.path));
|
|
279
|
+
return name + "\0" + body + "\0" + ordered.map((file) => file.path + "\0" + file.content).join("\0");
|
|
280
|
+
}
|
|
281
|
+
/** Hash one fingerprint into its anchor (CRLF-normalized by contentHash). */
|
|
282
|
+
function revisionAnchor(name, body, files) {
|
|
283
|
+
return {
|
|
284
|
+
kind: "present",
|
|
285
|
+
sha256: contentHash(revisionFingerprint(name, body, files))
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
/** Anchor for a skill whose body may be absent. */
|
|
289
|
+
function revisionAnchorOf(name, body, files) {
|
|
290
|
+
return body === null ? { kind: "absent" } : revisionAnchor(name, body, files);
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* Support digest over several skills' fingerprints: the union of their full content.
|
|
294
|
+
*
|
|
295
|
+
* Sort is by fingerprint (name-prefixed), so name order and fingerprint order agree and
|
|
296
|
+
* a decision-time digest can be recomputed by a committer that only has hashes.
|
|
297
|
+
* @param fingerprints - one fingerprint per involved skill (missing skills simply absent).
|
|
298
|
+
* @returns the digest recorded on a decision and re-checked at commit.
|
|
299
|
+
*/
|
|
300
|
+
function revisionSupportDigest(fingerprints) {
|
|
301
|
+
return contentHash([...fingerprints].sort().join("\0"));
|
|
302
|
+
}
|
|
303
|
+
//#endregion
|
|
304
|
+
//#region lib/types/skill-store.js
|
|
305
|
+
/**
|
|
306
|
+
* Skill library management for the self-evolution plugin.
|
|
307
|
+
*
|
|
308
|
+
* Skills live under `$DSH_HOME/skills` (`~/.dsh/skills` by default), matching
|
|
309
|
+
* the default dsh skill-filesystem user root. The plugin only manages skills
|
|
310
|
+
* it created unless a `.hermes-managed` marker opts a skill in. Archival is a
|
|
311
|
+
* move to `.archive/` — never a hard delete.
|
|
312
|
+
*
|
|
313
|
+
* ## Concurrency discipline (OPT-09, 2026-09) — read before adding a mutator
|
|
314
|
+
*
|
|
315
|
+
* Three primitives, three distinct jobs (they compose, they do not replace
|
|
316
|
+
* each other):
|
|
317
|
+
*
|
|
318
|
+
* 1. **In-process serial queue** (`this.serial`, makeSerialQueue) — orders the
|
|
319
|
+
* read→plan→commit phases of one skill's mutation against OTHER mutators
|
|
320
|
+
* in this process. Used by: create/update/patch/setPinned/restructure/
|
|
321
|
+
* writeSupportFile/removeSupportFile and (whole-mutation) consolidate.
|
|
322
|
+
* NON-reentrant: a callback must never call a public method that wraps
|
|
323
|
+
* itself in `this.serial` (archive/restoreFromArchive deliberately do not).
|
|
324
|
+
* 2. **Per-directory write lock** (io.ts LOCK_*) — cross-process mutual
|
|
325
|
+
* exclusion plus in-process crash ownership (tickets, takeover). Checked
|
|
326
|
+
* with `supportDirsUnlistable` before any destructive move (archive/restore/
|
|
327
|
+
* snapshot); held inside transactIo by byte writers.
|
|
328
|
+
* 3. **CAS baseline (`expected:`)** — any read whose bytes feed a later write
|
|
329
|
+
* must either live inside the serial section that commits the write, or
|
|
330
|
+
* carry its plan-time bytes as `expected` so the commit fails closed on
|
|
331
|
+
* drift (V8-11 / V24-01). A read outside the serial section WITHOUT a
|
|
332
|
+
* baseline is a lost-update bug; this file's history is the test suite.
|
|
333
|
+
*
|
|
334
|
+
* Known residuals (deliberate, documented at their sites): the archive commit
|
|
335
|
+
* re-check narrows but does not close the pin race (OPT-06); snapshotAll
|
|
336
|
+
* re-probes after its copies so a mid-copy writer demotes to `skipped`
|
|
337
|
+
* (OPT-07); the movers' probe→rename window is owned by the io.ts protocol.
|
|
338
|
+
*/
|
|
339
|
+
/**
|
|
340
|
+
* The CLASS boundary default authority (G1/1.1, Stage 2).
|
|
341
|
+
*
|
|
342
|
+
* The FACTORY (newSkillLibrary) requires an explicit authority and the v35 A6 register pins every
|
|
343
|
+
* production construction, so a production caller cannot omit one. The class is the INTERNAL
|
|
344
|
+
* boundary: arch rule N7 forbids constructing it directly in production, while ~200 test fixtures do
|
|
345
|
+
* exactly that and ARE the operator, so an omitted authority reads as foreground here - named and
|
|
346
|
+
* stated instead of silent.
|
|
347
|
+
*/
|
|
348
|
+
const CLASS_DEFAULT_AUTHORITY = authorityFrom({ origin: "foreground" });
|
|
349
|
+
/** 0.3.16 (S1.13, T-6): the pointer-line prefix written into a body when a
|
|
350
|
+
* section is moved to references/ — single literal, both restructure and
|
|
351
|
+
* append-mode consolidation emit the same discoverability line. */
|
|
352
|
+
const POINTER_LINE_PREFIX = "> 详见 references/";
|
|
353
|
+
/** V3: the pure LINK LIST that travels with a pointer line. A moved section's
|
|
354
|
+
* citations move one hop deeper, so without this line the body stops mentioning
|
|
355
|
+
* those files at all and `pointer_missing` (body-level by design) reports them as
|
|
356
|
+
* unpointed — measured on the live skill, moving 验证手法 took `missing` from 0 to
|
|
357
|
+
* 8 until the list was emitted. Design §2.3 explicitly allows link-list lines in
|
|
358
|
+
* the body, and a list of paths carries no content claim. */
|
|
359
|
+
const POINTER_REFS_PREFIX = "> 本节引用:";
|
|
360
|
+
/** Cap keeps the line readable; an ellipsis marks a truncated list (visible, never
|
|
361
|
+
* silently short). */
|
|
362
|
+
const POINTER_REFS_CAP = 12;
|
|
363
|
+
/**
|
|
364
|
+
* The body lines one moved section collapses to: the pointer plus the link list of
|
|
365
|
+
* the support files it cited (excluding the file it moved into).
|
|
366
|
+
* @param rel - the support path the section moved into.
|
|
367
|
+
* @param sectionText - the moved section's text.
|
|
368
|
+
* @returns one or two body lines.
|
|
369
|
+
*/
|
|
370
|
+
function pointerBlock(rel, sectionText) {
|
|
371
|
+
const cited = [...new Set(resolveCitations({
|
|
372
|
+
content: sectionText,
|
|
373
|
+
file: "SKILL.md",
|
|
374
|
+
files: []
|
|
375
|
+
}).refs.filter((ref) => ref.kind === "citation" && ref.target !== null).map((ref) => ref.target))].filter((target) => target !== rel).sort();
|
|
376
|
+
const lines = [`${POINTER_LINE_PREFIX}${rel.split("/").at(-1)}`];
|
|
377
|
+
if (cited.length > 0) {
|
|
378
|
+
const shown = cited.slice(0, POINTER_REFS_CAP);
|
|
379
|
+
lines.push(`${POINTER_REFS_PREFIX}${shown.join(" · ")}${cited.length > shown.length ? " …" : ""}`);
|
|
380
|
+
}
|
|
381
|
+
return lines;
|
|
382
|
+
}
|
|
383
|
+
/** Collision tail for the refusal plan note (empty when nothing collided). */
|
|
384
|
+
function collisionsNote(collisions) {
|
|
385
|
+
return collisions.length === 0 ? "" : ` collisions: ${collisions.slice(0, 5).join(", ")}`;
|
|
386
|
+
}
|
|
387
|
+
let nextUnitSeq = 0;
|
|
388
|
+
/**
|
|
389
|
+
* Evaluate a stage-time anchor against the bytes a locked read observed.
|
|
390
|
+
* @param anchor - the caller's anchor, or `undefined` for an unanchored write.
|
|
391
|
+
* @param current - the bytes the write lock read (`null` = the target is absent).
|
|
392
|
+
* @returns `match` when the write may proceed, otherwise the refusal verdict.
|
|
393
|
+
*/
|
|
394
|
+
function anchorVerdict(anchor, current) {
|
|
395
|
+
if (anchor === void 0) return "match";
|
|
396
|
+
if ("absent" in anchor) return current === null ? "match" : "drift";
|
|
397
|
+
if (current === null) return "missing";
|
|
398
|
+
return contentHash(current) === anchor.sha256 ? "match" : "drift";
|
|
399
|
+
}
|
|
400
|
+
/**
|
|
401
|
+
* Build the refusal for a skill write whose anchor did not hold. The wording is
|
|
402
|
+
* the library's own; a caller with staged-replay wording (the skill tool, the
|
|
403
|
+
* review plan) re-words it from {@link SkillActionResult.anchor}.
|
|
404
|
+
* @param name - the skill name the refusal names.
|
|
405
|
+
* @param verdict - the non-matching verdict.
|
|
406
|
+
* @returns the refusal result (nothing was written).
|
|
407
|
+
*/
|
|
408
|
+
function anchorRefusal(name, verdict) {
|
|
409
|
+
return {
|
|
410
|
+
ok: false,
|
|
411
|
+
stale: true,
|
|
412
|
+
anchor: verdict,
|
|
413
|
+
message: verdict === "missing" ? `技能「${name}」不存在。` : `技能 "${name}" 在读取之后被改动过;为避免覆盖更新的内容,本次写入被拒绝。`
|
|
414
|
+
};
|
|
415
|
+
}
|
|
416
|
+
/**
|
|
417
|
+
* Build the refusal for a support-file write/remove whose anchor did not hold.
|
|
418
|
+
* @param name - the owning skill name.
|
|
419
|
+
* @param filePath - the support-file path inside the skill.
|
|
420
|
+
* @param verdict - the non-matching verdict.
|
|
421
|
+
* @returns the refusal result (nothing was written or removed).
|
|
422
|
+
*/
|
|
423
|
+
/**
|
|
424
|
+
* Refusal for a target the locked read could not verify at all (EISDIR, an
|
|
425
|
+
* unreadable file). A staged replay reports "could not be verified" instead of
|
|
426
|
+
* propagating an exception: nothing was read, so nothing can have been written.
|
|
427
|
+
* @param name - the owning skill name.
|
|
428
|
+
* @param filePath - the support-file path, or `null` for the skill body.
|
|
429
|
+
* @returns the refusal result.
|
|
430
|
+
*/
|
|
431
|
+
function anchorUnverifiable(name, filePath) {
|
|
432
|
+
return {
|
|
433
|
+
ok: false,
|
|
434
|
+
stale: true,
|
|
435
|
+
anchor: "drift",
|
|
436
|
+
message: filePath === null ? `无法读取技能 "${name}" 以校验暂存内容。` : `无法读取技能 "${name}" 的支撑文件 "${filePath}" 以校验暂存内容。`
|
|
437
|
+
};
|
|
438
|
+
}
|
|
439
|
+
function anchorRefusalFile(name, filePath, verdict) {
|
|
440
|
+
return {
|
|
441
|
+
ok: false,
|
|
442
|
+
stale: true,
|
|
443
|
+
anchor: verdict,
|
|
444
|
+
message: verdict === "missing" ? `文件「${filePath}」不在技能「${name}」里。` : `技能 "${name}" 的支撑文件 "${filePath}" 在读取之后被改动过;为避免覆盖更新的内容,本次写入被拒绝。`
|
|
445
|
+
};
|
|
446
|
+
}
|
|
447
|
+
/**
|
|
448
|
+
* v43 S2-14 (FLOW2-1/flow-3): the target could not be READ at all — EISDIR, an
|
|
449
|
+
* unreadable file, a failing backend. `io.readText` returns null only for a
|
|
450
|
+
* genuinely missing path and throws for everything else, so a raw errno used to
|
|
451
|
+
* escape `update` / `patch` / `write_file` to the model while the remove path had
|
|
452
|
+
* classified the same condition since A-5 (v15). Structured refusal, nothing
|
|
453
|
+
* written.
|
|
454
|
+
*
|
|
455
|
+
* @param label - `name` or `name/filePath`, as the caller's surface names it.
|
|
456
|
+
* @param error - the read failure.
|
|
457
|
+
* @returns the refusal result.
|
|
458
|
+
*/
|
|
459
|
+
function unreadableTarget(label, error) {
|
|
460
|
+
return {
|
|
461
|
+
ok: false,
|
|
462
|
+
message: `读不出「${label}」:${(error?.code ?? (typeof error === "string" && error.startsWith("EISDIR") ? "EISDIR" : void 0)) === "EISDIR" ? "the path is a DIRECTORY, not a file" : error instanceof Error ? error.message : String(error)}。没有写入任何内容。`
|
|
463
|
+
};
|
|
464
|
+
}
|
|
465
|
+
/** Upper bound of moves per restructure proposal (validator and core agree). */
|
|
466
|
+
const MAX_RESTRUCTURE_MOVES = 5;
|
|
467
|
+
/** Restructure targets are plain markdown files under references/ — no
|
|
468
|
+
* subdirectories, no other support kind. V8-10 (0.3.47): the regex-level
|
|
469
|
+
* `(?!.*\.\.)` keeps the restructure-created set EXACTLY the set
|
|
470
|
+
* validateSupportPath can reopen — a `references/my..notes.md` target (double
|
|
471
|
+
* dots) used to pass here while every later patch/write/remove on it was
|
|
472
|
+
* refused as traversal (an orphan file the user could not touch). */
|
|
473
|
+
const RESTRUCTURE_TARGET_RE = /^references\/[a-z0-9](?!.*\.\.)[a-z0-9._-]*\.md$/;
|
|
474
|
+
/** F-20 (v18): the character rule shared by support-file names and snapshot
|
|
475
|
+
* `extras/` entry names. The two exported names used to carry the same literal
|
|
476
|
+
* independently; both now derive from this one. */
|
|
477
|
+
const SUPPORT_ENTRY_NAME_RE = /^[a-z0-9][a-z0-9._-]*$/;
|
|
478
|
+
/** Extra file name carried inside a snapshot's `extras/` directory. */
|
|
479
|
+
const SNAPSHOT_EXTRA_NAME_RE = SUPPORT_ENTRY_NAME_RE;
|
|
480
|
+
function skillsRoot(env = process.env) {
|
|
481
|
+
return join(evolutionRoot(env), "skills");
|
|
482
|
+
}
|
|
483
|
+
/** 0.3.18 (S4.1, E-30): the ONE root resolution for every member that reads
|
|
484
|
+
* the skills tree — tool-skill-manage / evolution-skill-catalog / skill-usage
|
|
485
|
+
* / evolution-learning-graph used to each resolve `config.root || skillsRoot()`
|
|
486
|
+
* (and the graph ignored config entirely). Empty/whitespace config falls
|
|
487
|
+
* through to the default; callers pass their raw Config. The optional field is
|
|
488
|
+
* declared `| undefined` so a config object whose root field is explicitly
|
|
489
|
+
* `string | undefined` still assignable under exactOptionalPropertyTypes.
|
|
490
|
+
* P2-31 core half (S2.2 batch, PLAN 2026-09-16): an explicit non-empty root
|
|
491
|
+
* is `resolve()`d — the same normalization `evolutionRoot` applies and the
|
|
492
|
+
* same one upstream skill-filesystem applies to `customSkillDirs`
|
|
493
|
+
* (`(config.customSkillDirs ?? []).map(root => resolve(root))`). The former
|
|
494
|
+
* verbatim return left a RELATIVE config root CWD-relative, so the family's
|
|
495
|
+
* skill tree moved with the host process's launch directory while every
|
|
496
|
+
* absolute consumer (watchers, the platform catalog) resolved it — a
|
|
497
|
+
* split-brain tree; a trailing slash or `..` segment likewise landed
|
|
498
|
+
* unnormalized. A clean absolute root is byte-identical (resolve is a no-op). */
|
|
499
|
+
function resolveSkillsRoot(config = {}) {
|
|
500
|
+
const explicit = (config.root ?? "").trim();
|
|
501
|
+
return explicit ? resolve(explicit) : skillsRoot();
|
|
502
|
+
}
|
|
503
|
+
/** E-7 (v18) → V27 G2.4 (M-08): every family row reads ONE root key. `root` is
|
|
504
|
+
* canonical; the `skillsRoot` alias was honoured for one minor version and its
|
|
505
|
+
* window closed at 0.3.65 — it is now two releases past expiry, so this
|
|
506
|
+
* resolver no longer reads it at all. A deployment that still sets the alias
|
|
507
|
+
* must fail LOUDLY at load (see {@link assertSkillsRootAliasRetired}): silently
|
|
508
|
+
* ignoring a config key leaves the deployment pointing at a root nobody reads,
|
|
509
|
+
* which is the worst form of compatibility.
|
|
510
|
+
* @param config - the raw plugin config.
|
|
511
|
+
* @returns the effective root (empty when the key is unset or blank).
|
|
512
|
+
*/
|
|
513
|
+
function resolveRootConfig(config = {}) {
|
|
514
|
+
return { root: (config.root ?? "").trim() };
|
|
515
|
+
}
|
|
516
|
+
/** V27 G2.4 (M-08): the retirement gate for the expired `skillsRoot` alias.
|
|
517
|
+
* Called at each plugin's load boundary (before the root is resolved), it turns
|
|
518
|
+
* a stale key into an explicit load error naming the replacement — the
|
|
519
|
+
* fail-loud form the plan requires instead of a silent no-op.
|
|
520
|
+
* @param config - the raw plugin config (the alias field stays DECLARED in each
|
|
521
|
+
* schema so the loader can hand it here instead of dropping it).
|
|
522
|
+
*/
|
|
523
|
+
function assertSkillsRootAliasRetired(config = {}) {
|
|
524
|
+
if ((config.skillsRoot ?? "").trim() !== "") throw new Error("evolution: config \"skillsRoot\" was removed after 0.3.65 — rename the key to \"root\" (the alias is no longer honoured)");
|
|
525
|
+
}
|
|
526
|
+
/**
|
|
527
|
+
* Map a requesting session onto the two origin surfaces (rc.44 plan M2-2.3):
|
|
528
|
+
* the APPROVAL surface treats every delegated subagent as the autonomous
|
|
529
|
+
* review channel, while the LIBRARY surface keeps the Hermes distinction -
|
|
530
|
+
* the review fork is 'background_review' (the pinned guard blocks its
|
|
531
|
+
* writes) and any other subagent is 'subagent' (agent-authored, not
|
|
532
|
+
* review-channel). `isReview` marks the caller as the background review
|
|
533
|
+
* pipeline itself. Single source: the two tools and the review executor all
|
|
534
|
+
* read this table instead of re-deriving it.
|
|
535
|
+
*/
|
|
536
|
+
function resolveOrigins(headerOrigin, isReview = false) {
|
|
537
|
+
if (isReview) return {
|
|
538
|
+
approval: "background_review",
|
|
539
|
+
library: "background_review"
|
|
540
|
+
};
|
|
541
|
+
if (headerOrigin === "subagent") return {
|
|
542
|
+
approval: "background_review",
|
|
543
|
+
library: "subagent"
|
|
544
|
+
};
|
|
545
|
+
return {
|
|
546
|
+
approval: "foreground",
|
|
547
|
+
library: "foreground"
|
|
548
|
+
};
|
|
549
|
+
}
|
|
550
|
+
/**
|
|
551
|
+
* S1-E8 (0.3.80): ONE exec→origins resolution for the two write tools — reads
|
|
552
|
+
* the session header origin AND the v37 S2.2 review-channel session mark, so a
|
|
553
|
+
* tool cannot forget the mark half (tool-memory shipped without it, which
|
|
554
|
+
* mislabeled every inject-mode review memory write as `foreground` and let it
|
|
555
|
+
* bypass staging under `stageForeground: false`).
|
|
556
|
+
* Single source: both tools call this instead of re-deriving the pair.
|
|
557
|
+
*/
|
|
558
|
+
function resolveExecOrigins(exec) {
|
|
559
|
+
if (currentReviewContext() !== void 0) return {
|
|
560
|
+
approval: "background_review",
|
|
561
|
+
library: "background_review"
|
|
562
|
+
};
|
|
563
|
+
const session = exec?.agent?.session;
|
|
564
|
+
return resolveOrigins(session?.header?.origin, isReviewChannelSession(typeof session?.id === "string" ? session.id : void 0));
|
|
565
|
+
}
|
|
566
|
+
function skillDir(root, name) {
|
|
567
|
+
return join(root, name);
|
|
568
|
+
}
|
|
569
|
+
/** Dot-prefixed on-disk marker name. SINGLE source: `list()` matches directory
|
|
570
|
+
* entries against this name, and path builders must never hardcode a marker
|
|
571
|
+
* literal (N-1: the rc.49 exists()-probe convergence dropped the dot,
|
|
572
|
+
* poisoning every protectedBy/managed report). Exported for cross-package
|
|
573
|
+
* consumers that must probe markers without re-deriving the name (curator's
|
|
574
|
+
* archive-copy bundled probe, 0.3.26 V4-02). */
|
|
575
|
+
function markerEntryName(marker) {
|
|
576
|
+
return `.${marker}`;
|
|
577
|
+
}
|
|
578
|
+
/** v23 (ML-1): `.archive` retention window (see pruneExpiredArchives). */
|
|
579
|
+
const ARCHIVE_RETENTION_DAYS = 365;
|
|
580
|
+
function markerPath(dir, marker) {
|
|
581
|
+
return join(dir, markerEntryName(marker));
|
|
582
|
+
}
|
|
583
|
+
function isCommittedOnly(error) {
|
|
584
|
+
return isCommittedWarning(error);
|
|
585
|
+
}
|
|
586
|
+
/** v28 G2.5 (CORE-SK-03): every pre-clear refusal in restoreSnapshotIntoRoot
|
|
587
|
+
* says "refus…" (manifest / traversal / live-writer gates) or "is incomplete"
|
|
588
|
+
* (completeness gate). Anything else thrown from that method means the
|
|
589
|
+
* destructive clear already happened and a rollback is load-bearing. */
|
|
590
|
+
function isPreClearRefusal(message) {
|
|
591
|
+
return message.includes("refus") || message.includes("is incomplete");
|
|
592
|
+
}
|
|
593
|
+
async function listNames(root, io) {
|
|
594
|
+
const entries = await io.list(root);
|
|
595
|
+
const names = [];
|
|
596
|
+
for (const entry of entries) {
|
|
597
|
+
if (entry.startsWith(".")) continue;
|
|
598
|
+
if (await io.exists(join(root, entry, "SKILL.md"))) names.push(entry);
|
|
599
|
+
}
|
|
600
|
+
return names.sort();
|
|
601
|
+
}
|
|
602
|
+
/** C-18: support file names are restricted to the
|
|
603
|
+
* RESTRUCTURE_TARGET_RE character class (leading `[a-z0-9]`, then
|
|
604
|
+
* `[a-z0-9._-]`) — drive-colon / odd-character / uppercase names can no
|
|
605
|
+
* longer reach the filesystem through writeSupportFile / patch /
|
|
606
|
+
* removeSupportFile. */
|
|
607
|
+
const SUPPORT_FILE_NAME_RE = SUPPORT_ENTRY_NAME_RE;
|
|
608
|
+
/** C-18: win32 reserves these stems with ANY extension (`nul.md` hits the
|
|
609
|
+
* NUL device), and they are fully inside the charset above — so the reserved
|
|
610
|
+
* set is checked on the first-dot prefix as well; the charset close alone
|
|
611
|
+
* cannot refuse them. Exported single source: `badName` (skill directories,
|
|
612
|
+
* P2-11/v15) and `validateSupportPath` (support-file stems, C-18) both
|
|
613
|
+
* consume this one set — a third copy would drift. */
|
|
614
|
+
const WIN32_RESERVED_DEVICE_NAMES = new Set([
|
|
615
|
+
"con",
|
|
616
|
+
"prn",
|
|
617
|
+
"aux",
|
|
618
|
+
"nul",
|
|
619
|
+
"com1",
|
|
620
|
+
"com2",
|
|
621
|
+
"com3",
|
|
622
|
+
"com4",
|
|
623
|
+
"com5",
|
|
624
|
+
"com6",
|
|
625
|
+
"com7",
|
|
626
|
+
"com8",
|
|
627
|
+
"com9",
|
|
628
|
+
"lpt1",
|
|
629
|
+
"lpt2",
|
|
630
|
+
"lpt3",
|
|
631
|
+
"lpt4",
|
|
632
|
+
"lpt5",
|
|
633
|
+
"lpt6",
|
|
634
|
+
"lpt7",
|
|
635
|
+
"lpt8",
|
|
636
|
+
"lpt9"
|
|
637
|
+
]);
|
|
638
|
+
/** A1-6 (v18): the regex alone admits `references/nul.md` (a Windows device
|
|
639
|
+
* stem), which the support-file layer refuses. Restructure must use the same
|
|
640
|
+
* rule, or it creates an orphan the later patch/write/remove paths refuse.
|
|
641
|
+
* Single source shared with the plan validator. */
|
|
642
|
+
function validateRestructureTarget(filePath) {
|
|
643
|
+
if (!RESTRUCTURE_TARGET_RE.test(filePath)) return `toFile must be references/<topic>.md (got "${filePath}").`;
|
|
644
|
+
const stem = filePath.slice(filePath.lastIndexOf("/") + 1).split(".")[0]?.toLowerCase() ?? "";
|
|
645
|
+
if (WIN32_RESERVED_DEVICE_NAMES.has(stem)) return `toFile "${filePath}" uses a Windows reserved device name.`;
|
|
646
|
+
return null;
|
|
647
|
+
}
|
|
648
|
+
function validateSupportPath(filePath) {
|
|
649
|
+
const normalized = filePath.replace(/\\/g, "/");
|
|
650
|
+
if (normalized.includes("..")) return "不允许路径穿越。";
|
|
651
|
+
const parts = normalized.split("/").filter(Boolean);
|
|
652
|
+
if (parts.length === 0 || !SUPPORT_DIRS.includes(parts[0])) return `file_path must be under one of: ${SUPPORT_DIRS.join(", ")}.`;
|
|
653
|
+
if (parts.length < 2) return "请给出文件名,不能只给目录。";
|
|
654
|
+
for (const part of parts.slice(1)) {
|
|
655
|
+
if (!SUPPORT_FILE_NAME_RE.test(part)) return `不支持的文件名「${part}」:请只用小写字母、数字、点、连字符和下划线(首字符须为字母或数字)。`;
|
|
656
|
+
if (part.toLowerCase().endsWith(".corrupt") || part.toLowerCase().endsWith(".tmp")) return `不支持的文件名「${part}」:.corrupt/.tmp 后缀由状态与 IO 协议保留。`;
|
|
657
|
+
const stem = part.split(".")[0]?.toLowerCase() ?? "";
|
|
658
|
+
if (WIN32_RESERVED_DEVICE_NAMES.has(stem)) return `不支持的文件名「${part}」:这是 Windows 保留设备名。`;
|
|
659
|
+
}
|
|
660
|
+
return null;
|
|
661
|
+
}
|
|
662
|
+
function planRestructureSections(body, moves) {
|
|
663
|
+
const selection = selectSections(body, moves.map((move) => ({ heading: move.heading })));
|
|
664
|
+
if (!selection.ok) return { error: selection.message };
|
|
665
|
+
const lines = body.split("\n");
|
|
666
|
+
const spans = selection.sections.map((section) => {
|
|
667
|
+
const move = moves[section.requestIndex];
|
|
668
|
+
return {
|
|
669
|
+
start: section.start,
|
|
670
|
+
end: section.end,
|
|
671
|
+
rel: move?.toFile ?? "",
|
|
672
|
+
heading: section.heading,
|
|
673
|
+
text: section.text
|
|
674
|
+
};
|
|
675
|
+
});
|
|
676
|
+
const byStart = new Map(spans.map((span) => [span.start, span]));
|
|
677
|
+
const rebuilt = [];
|
|
678
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
679
|
+
const span = byStart.get(i);
|
|
680
|
+
if (span) {
|
|
681
|
+
rebuilt.push(...pointerBlock(span.rel, span.text));
|
|
682
|
+
i = span.end - 1;
|
|
683
|
+
} else rebuilt.push(lines[i] ?? "");
|
|
684
|
+
}
|
|
685
|
+
return {
|
|
686
|
+
body: rebuilt.join("\n"),
|
|
687
|
+
sections: spans.map(({ rel, heading, text }) => ({
|
|
688
|
+
rel,
|
|
689
|
+
heading,
|
|
690
|
+
text
|
|
691
|
+
}))
|
|
692
|
+
};
|
|
693
|
+
}
|
|
694
|
+
/**
|
|
695
|
+
* WHY MODULE SCOPE (S4.4): the serial queue must be shared ACROSS SkillLibrary instances. Six services
|
|
696
|
+
* each build their own store over the SAME skill root (tool face / curator face / review face), and a
|
|
697
|
+
* per-instance queue - which is what `this.serial = makeSerialQueue()` was - let two of them run
|
|
698
|
+
* read->plan->commit against one tree at the same time. The mutex cannot live on an instance because
|
|
699
|
+
* instances share nothing (S2-02, G1/1.4); it cannot be a file lock either, because the point is to
|
|
700
|
+
* order IN-PROCESS phases before the io transact layer sees them. Keyed by root: two roots are
|
|
701
|
+
* independent trees and must not wait on each other.
|
|
702
|
+
*/
|
|
703
|
+
const ROOT_SERIAL = /* @__PURE__ */ new Map();
|
|
704
|
+
/** The ONE queue for a skill root, created on first use (module scope, see above).
|
|
705
|
+
* @param root - the resolved skill root; the key, so two spellings of one directory share a queue.
|
|
706
|
+
* @returns the queue every instance over this root serializes through.
|
|
707
|
+
*/
|
|
708
|
+
function serialForRoot(root) {
|
|
709
|
+
const key = resolve(root);
|
|
710
|
+
const existing = ROOT_SERIAL.get(key);
|
|
711
|
+
if (existing !== void 0) return existing;
|
|
712
|
+
const created = makeSerialQueue();
|
|
713
|
+
ROOT_SERIAL.set(key, created);
|
|
714
|
+
return created;
|
|
715
|
+
}
|
|
716
|
+
/** Same-content test for two revision anchors (absent only equals absent). */
|
|
717
|
+
function sameRevisionAnchor(expected, live) {
|
|
718
|
+
if (expected.kind !== live.kind) return false;
|
|
719
|
+
return expected.kind === "absent" || expected.sha256 === live.sha256;
|
|
720
|
+
}
|
|
721
|
+
var SkillLibrary = class {
|
|
722
|
+
root;
|
|
723
|
+
/** The ONE read face owner/health/panel consume; a thin adapter, not a store. */
|
|
724
|
+
model;
|
|
725
|
+
limits;
|
|
726
|
+
io;
|
|
727
|
+
onMutation;
|
|
728
|
+
/** 0.3.21 (F-208) + V4-20: cross-process RMW transactor. An explicitly
|
|
729
|
+
* injected value wins; otherwise the IO backend's own `transact` is bound
|
|
730
|
+
* when it provides one (cross-process atomicity on by default for any
|
|
731
|
+
* transact-capable backend), and a backend without `transact` leaves this
|
|
732
|
+
* undefined (each write falls back to the plain read→task→write path). */
|
|
733
|
+
transact;
|
|
734
|
+
/** 0.3.21 (F-208): in-process serialize queue so two concurrent mutators on
|
|
735
|
+
* one skill never interleave their read-modify-write (the cross-process layer
|
|
736
|
+
* is the IO backend's transact lock; this chain is the second layer). */
|
|
737
|
+
serial;
|
|
738
|
+
/** V10-03 (P2-18): see the constructor's threatExemptLabels. Empty by
|
|
739
|
+
* default — the strict ANY-hit-blocks policy is unchanged. */
|
|
740
|
+
threatExemptLabels;
|
|
741
|
+
/** G1/1.1: default authority; a call may override (origin is per-invocation). */
|
|
742
|
+
/** G1/1.1/Stage 2: the ONE default every mutator reads. Per-call overrides still win. */
|
|
743
|
+
authority;
|
|
744
|
+
/** When supplied by the family MutationAuthority, replaces the per-directory file lock. */
|
|
745
|
+
mutationLock;
|
|
746
|
+
fence;
|
|
747
|
+
/** skill-history.ts: the content history is best-effort, so a failure must not be SILENT —
|
|
748
|
+
* but it is a deployment condition, not a per-write event, so it warns once per instance. */
|
|
749
|
+
historyWarned = false;
|
|
750
|
+
constructor(root = skillsRoot(), io = nodeEvolutionIo(), limits = DEFAULT_SKILL_LIMITS, onMutation, transact, threatExemptLabels, authority = CLASS_DEFAULT_AUTHORITY, mutationLock, fence) {
|
|
751
|
+
this.root = root;
|
|
752
|
+
this.io = io;
|
|
753
|
+
this.limits = limits;
|
|
754
|
+
this.onMutation = onMutation;
|
|
755
|
+
this.threatExemptLabels = threatExemptLabels ?? [];
|
|
756
|
+
this.authority = authority;
|
|
757
|
+
this.mutationLock = mutationLock;
|
|
758
|
+
this.fence = fence;
|
|
759
|
+
this.transact = transact ?? (io.transact ? (ioLike, path, task) => {
|
|
760
|
+
const t = ioLike.transact;
|
|
761
|
+
return t ? t(path, task) : transactIo(ioLike, path, task);
|
|
762
|
+
} : void 0);
|
|
763
|
+
this.serial = serialForRoot(this.root);
|
|
764
|
+
this.model = new SkillModel({
|
|
765
|
+
list: async (query) => await this.list(query),
|
|
766
|
+
read: async (name) => await this.read(name),
|
|
767
|
+
listSupportFiles: async (name) => {
|
|
768
|
+
const probe = await this.listSupportFiles(name);
|
|
769
|
+
if (!isPresent(probe)) throw new Error("support listing unreadable for " + name);
|
|
770
|
+
return probe.value;
|
|
771
|
+
},
|
|
772
|
+
readSupportFile: async (name, path) => await this.readSupportFile(name, path)
|
|
773
|
+
});
|
|
774
|
+
}
|
|
775
|
+
/**
|
|
776
|
+
* Transitional root lock for mutators that still own their write path. The
|
|
777
|
+
* extract/restructure path takes the same lock through MutationUnit, so those
|
|
778
|
+
* two paths cannot interleave with create/update/patch across processes.
|
|
779
|
+
*/
|
|
780
|
+
unitHeadForOps(ops, roots, provenance = /* @__PURE__ */ new Map()) {
|
|
781
|
+
const moves = [];
|
|
782
|
+
for (const op of ops) {
|
|
783
|
+
if (op.skill === void 0 || basename(op.target) === "SKILL.md") continue;
|
|
784
|
+
const path = relative(this.dirOf(op.skill), op.target).split(String.fromCharCode(92)).join("/");
|
|
785
|
+
if (path === "" || path.startsWith("..")) continue;
|
|
786
|
+
moves.push({
|
|
787
|
+
path,
|
|
788
|
+
kind: op.before === null ? "created" : op.after === null ? "removed" : "moved",
|
|
789
|
+
...op.before === null ? {} : { beforeRef: contentHash(op.before) },
|
|
790
|
+
...op.after === null ? {} : { afterRef: contentHash(op.after) },
|
|
791
|
+
...provenance.get(op.target) === void 0 ? {} : { provenance: provenance.get(op.target) }
|
|
792
|
+
});
|
|
793
|
+
}
|
|
794
|
+
return {
|
|
795
|
+
moves,
|
|
796
|
+
sources: roots.map((skill) => ({ skill }))
|
|
797
|
+
};
|
|
798
|
+
}
|
|
799
|
+
async withMutationLock(task) {
|
|
800
|
+
const lease = await this.lockPort().acquire();
|
|
801
|
+
try {
|
|
802
|
+
return await task();
|
|
803
|
+
} finally {
|
|
804
|
+
await lease.release();
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
lockPort() {
|
|
808
|
+
if (this.mutationLock !== void 0) return this.mutationLock;
|
|
809
|
+
if (process.env["VITEST"] === "true" || process.env["NODE_ENV"] === "test") return fileMutationLock(this.io, this.root);
|
|
810
|
+
throw new Error("skill-store: no authority mutationLock was supplied; refusing an unfenced production write");
|
|
811
|
+
}
|
|
812
|
+
recovery;
|
|
813
|
+
/** Run the boot recovery once per library instance, before the first write. */
|
|
814
|
+
async ensureRecovered() {
|
|
815
|
+
this.recovery ??= this.recoverPreparedUnits().then(() => void 0).catch((error) => {
|
|
816
|
+
console.warn("skill-store: prepared-unit recovery failed; writes continue: " + (error instanceof Error ? error.message : String(error)));
|
|
817
|
+
});
|
|
818
|
+
await this.recovery;
|
|
819
|
+
}
|
|
820
|
+
/** Public boot hook: idempotent with the first-write recovery. */
|
|
821
|
+
async recoverOnBoot() {
|
|
822
|
+
await this.ensureRecovered();
|
|
823
|
+
}
|
|
824
|
+
/** Recover every prepared tree-change snapshot in the shared unit store. */
|
|
825
|
+
async recoverPreparedUnits() {
|
|
826
|
+
const home = dirname(this.root);
|
|
827
|
+
const results = await new MutationUnit({
|
|
828
|
+
io: this.io,
|
|
829
|
+
limits: {
|
|
830
|
+
maxSkillFileBytes: this.limits.maxSkillFileBytes,
|
|
831
|
+
maxSkillContentChars: this.limits.maxSkillContentChars
|
|
832
|
+
},
|
|
833
|
+
serial: this.serial,
|
|
834
|
+
lock: this.lockPort(),
|
|
835
|
+
journal: unitJournalPort(this.io, home),
|
|
836
|
+
snapshots: unitSnapshotPort(this.io, home)
|
|
837
|
+
}).recoverPrepared();
|
|
838
|
+
await pruneTreeChangeUnits(this.io, home).catch(() => {});
|
|
839
|
+
return results;
|
|
840
|
+
}
|
|
841
|
+
/**
|
|
842
|
+
* Run one single-file read-modify-write for a mutator. When `transact` was
|
|
843
|
+
* injected the read and the write run inside it (cross-process atomicity);
|
|
844
|
+
* otherwise a plain read → task → write sequence runs (the process-level
|
|
845
|
+
* `serial` chain is the second layer). `task` receives the current content
|
|
846
|
+
* (null when missing) and returns a {@link SingleWriteOutcome}. Audit and the
|
|
847
|
+
* mutation event are issued ONLY when a write actually lands, so a no-op
|
|
848
|
+
* never inflates the mutation-maturity counter.
|
|
849
|
+
*/
|
|
850
|
+
/**
|
|
851
|
+
* v28 G1.1 (EVO-IO-02): shared compensating cleanup for a locked write that
|
|
852
|
+
* found no SKILL.md — remove the possibly-resurrected directory ONLY when it
|
|
853
|
+
* holds nothing but this path's own write-lock file. The BR-5 rule from
|
|
854
|
+
* setPinnedCore/createCore applies unchanged: a concurrent mover can land a
|
|
855
|
+
* full directory between the list probe and the remove, so ANY content at all (support files, a
|
|
856
|
+
* fresh restore) must never be recursed away. Best-effort: a failed cleanup leaves the "not found" result
|
|
857
|
+
* unchanged (the operator-facing ghost-dir refusal is fail-loud already).
|
|
858
|
+
*/
|
|
859
|
+
async cleanupGhostDir(skillFilePath) {
|
|
860
|
+
const dir = dirname(skillFilePath);
|
|
861
|
+
try {
|
|
862
|
+
if ((await this.io.list(dir)).length > 0) return;
|
|
863
|
+
await this.io.remove(dir);
|
|
864
|
+
} catch {}
|
|
865
|
+
}
|
|
866
|
+
/** Notify the mutation observer after a successful write; observers must never fail the mutation. */
|
|
867
|
+
notifyMutation(event) {
|
|
868
|
+
try {
|
|
869
|
+
this.onMutation?.(event);
|
|
870
|
+
} catch {}
|
|
871
|
+
}
|
|
872
|
+
/** V10-03 (P2-18): ScanOptions shared by every write-path threat check —
|
|
873
|
+
* the constructor's exempt labels, empty by default (behavior unchanged). */
|
|
874
|
+
threatScanOptions() {
|
|
875
|
+
return this.threatExemptLabels.length > 0 ? { excludeLabels: this.threatExemptLabels } : {};
|
|
876
|
+
}
|
|
877
|
+
/** V10-03 (P2-18): the strict-scan write gate. A block message names the hit
|
|
878
|
+
* label (scanContentThreats already embeds it) plus the self-heal hint, so a
|
|
879
|
+
* false-positive rewrite direction is actionable instead of a dead end. */
|
|
880
|
+
contentThreatBlock(content) {
|
|
881
|
+
return scanContentThreats(content, void 0, this.threatScanOptions());
|
|
882
|
+
}
|
|
883
|
+
/**
|
|
884
|
+
* v30 REV-03: read a support file's bytes for staleness anchoring (the
|
|
885
|
+
* write/remove replay guard). Same validation as writeSupportFile; a
|
|
886
|
+
* missing file (or a directory squatting on the path) reads as `null`, any
|
|
887
|
+
* other failure RETHROWS — the callers are the staging/replay anchors, and
|
|
888
|
+
* a swallowed error would silently downgrade the anchor to
|
|
889
|
+
* last-writer-wins.
|
|
890
|
+
*/
|
|
891
|
+
/**
|
|
892
|
+
* S4-01 (G0/0.7): the ONE three-state read the staging/replay anchors use.
|
|
893
|
+
*
|
|
894
|
+
* The two absorbing reads below absorb ENOENT/EISDIR and rethrow everything else, and the callers then
|
|
895
|
+
* each wrote their own try/catch to turn a rethrow into a decision - three near-copies of one posture,
|
|
896
|
+
* and the newest of them silently dropped the anchor instead of refusing. A read failure is its own
|
|
897
|
+
* state, so it gets its own name here: `unknown` with the reason, next to `present` and `absent`.
|
|
898
|
+
* Failing closed is then the CALLER decision (they refuse on unknown), not something each call site has
|
|
899
|
+
* to re-derive from a thrown error.
|
|
900
|
+
*/
|
|
901
|
+
async readSkillProbe(rawName) {
|
|
902
|
+
return await this.probeOf(() => this.read(rawName));
|
|
903
|
+
}
|
|
904
|
+
/** The support-file face of {@link readSkillProbe}. */
|
|
905
|
+
async readSupportFileProbe(rawName, filePath) {
|
|
906
|
+
return await this.probeOf(() => this.readSupportFile(rawName, filePath));
|
|
907
|
+
}
|
|
908
|
+
/** One place that turns the absorbing reads into three states. `null` is absent; a throw is unknown. */
|
|
909
|
+
async probeOf(read) {
|
|
910
|
+
try {
|
|
911
|
+
const value = await read();
|
|
912
|
+
return value === null ? probeAbsent() : probePresent(value);
|
|
913
|
+
} catch (error) {
|
|
914
|
+
return probeUnknown(probeReason(error));
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
async readSupportFile(name, filePath) {
|
|
918
|
+
const bad = this.badName(name, { allowReserved: true });
|
|
919
|
+
if (bad) throw new Error(bad);
|
|
920
|
+
const validation = validateSupportPath(filePath);
|
|
921
|
+
if (validation) throw new Error(validation);
|
|
922
|
+
const target = join(this.dirOf(name), ...filePath.replace(/\\/g, "/").split("/").filter(Boolean));
|
|
923
|
+
try {
|
|
924
|
+
return await this.io.readText(target);
|
|
925
|
+
} catch (error) {
|
|
926
|
+
const code = error?.code;
|
|
927
|
+
if (code === "ENOENT" || code === "EISDIR") return null;
|
|
928
|
+
throw error;
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
/**
|
|
932
|
+
* Summarize the skill tree.
|
|
933
|
+
* @param options - `withContent` attaches each skill's whole SKILL.md body to
|
|
934
|
+
* its summary (v35 C11), `withFrontmatter` its parsed frontmatter record
|
|
935
|
+
* (T2-07/A22): the read this listing already performs is the one either would
|
|
936
|
+
* cost again, so a caller pays no second pass over the tree.
|
|
937
|
+
* @returns one summary per readable skill directory.
|
|
938
|
+
*/
|
|
939
|
+
/** T2-V2/A27: the skill names the TREE holds — the same listing rule {@link list} applies (dot
|
|
940
|
+
* entries skipped, a SKILL.md must exist), WITHOUT reading any SKILL.md. A consumer that needs the
|
|
941
|
+
* member set rather than the summaries (the learning graph's node set) pays one directory listing
|
|
942
|
+
* instead of a whole-tree read pass.
|
|
943
|
+
* @returns the sorted skill directory names. */
|
|
944
|
+
async treeNames() {
|
|
945
|
+
return await listNames(this.root, this.io);
|
|
946
|
+
}
|
|
947
|
+
async list(options = {}) {
|
|
948
|
+
const summaries = [];
|
|
949
|
+
for (const entry of await this.io.list(this.root)) {
|
|
950
|
+
if (entry.startsWith(".")) continue;
|
|
951
|
+
const name = entry;
|
|
952
|
+
const dir = this.dirOf(name);
|
|
953
|
+
let md;
|
|
954
|
+
try {
|
|
955
|
+
md = await this.io.readText(join(dir, "SKILL.md"));
|
|
956
|
+
} catch (error) {
|
|
957
|
+
if (error?.code === "EISDIR") continue;
|
|
958
|
+
throw error;
|
|
959
|
+
}
|
|
960
|
+
if (md === null) continue;
|
|
961
|
+
const parsed = parseFrontmatter(md);
|
|
962
|
+
let entries = null;
|
|
963
|
+
try {
|
|
964
|
+
entries = await this.io.list(dir);
|
|
965
|
+
} catch {
|
|
966
|
+
entries = null;
|
|
967
|
+
}
|
|
968
|
+
const probeMarker = async (marker) => {
|
|
969
|
+
if (entries !== null) return entries.includes(markerEntryName(marker));
|
|
970
|
+
try {
|
|
971
|
+
return await this.io.exists(join(dir, markerEntryName(marker)));
|
|
972
|
+
} catch {
|
|
973
|
+
return null;
|
|
974
|
+
}
|
|
975
|
+
};
|
|
976
|
+
const [bundled, hubInstalled, pinned, hermesManaged] = await Promise.all([
|
|
977
|
+
probeMarker("bundled"),
|
|
978
|
+
probeMarker("hub-installed"),
|
|
979
|
+
probeMarker("pinned"),
|
|
980
|
+
probeMarker("hermes-managed")
|
|
981
|
+
]);
|
|
982
|
+
const protectedBy = bundled === true ? "bundled" : hubInstalled === true ? "hub-installed" : pinned === true ? "pinned" : null;
|
|
983
|
+
const parsedDescription = parsed?.frontmatter.description;
|
|
984
|
+
const parsedWhenToUse = parsed?.frontmatter.whenToUse;
|
|
985
|
+
summaries.push({
|
|
986
|
+
name,
|
|
987
|
+
description: typeof parsedDescription === "string" ? parsedDescription : "",
|
|
988
|
+
path: dir,
|
|
989
|
+
protectedBy,
|
|
990
|
+
protectionUnknown: [
|
|
991
|
+
bundled,
|
|
992
|
+
hubInstalled,
|
|
993
|
+
pinned,
|
|
994
|
+
hermesManaged
|
|
995
|
+
].some((value) => value === null),
|
|
996
|
+
managed: hermesManaged === true,
|
|
997
|
+
...typeof parsedWhenToUse === "string" && parsedWhenToUse.trim() !== "" ? { whenToUse: parsedWhenToUse } : {},
|
|
998
|
+
...options.withContent === true ? { content: md } : {},
|
|
999
|
+
...options.withFrontmatter === true && parsed !== null ? { frontmatter: parsed.frontmatter } : {}
|
|
1000
|
+
});
|
|
1001
|
+
}
|
|
1002
|
+
return summaries;
|
|
1003
|
+
}
|
|
1004
|
+
async read(rawName) {
|
|
1005
|
+
const name = rawName.trim();
|
|
1006
|
+
if (this.badName(name) !== null) return null;
|
|
1007
|
+
try {
|
|
1008
|
+
return await this.io.readText(join(this.dirOf(name), "SKILL.md"));
|
|
1009
|
+
} catch (error) {
|
|
1010
|
+
if (error?.code === "EISDIR") return null;
|
|
1011
|
+
throw error;
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
/**
|
|
1015
|
+
* Content anchor of one live skill: name + body + every support file under SUPPORT_DIRS.
|
|
1016
|
+
*
|
|
1017
|
+
* This is the commit-side counterpart of the decision-time anchor recorded by the merge
|
|
1018
|
+
* domain (see skill-revision.ts): both sides call the same fingerprint, so a changed
|
|
1019
|
+
* source, target or support file cannot slip past the commit CAS.
|
|
1020
|
+
* @param rawName - caller-supplied skill name (trimmed here).
|
|
1021
|
+
* @returns present anchor, or absent when the skill has no SKILL.md.
|
|
1022
|
+
*/
|
|
1023
|
+
async revisionFingerprint(rawName) {
|
|
1024
|
+
const name = rawName.trim();
|
|
1025
|
+
if (this.badName(name) !== null) return null;
|
|
1026
|
+
let body;
|
|
1027
|
+
try {
|
|
1028
|
+
body = await this.io.readText(join(this.dirOf(name), "SKILL.md"));
|
|
1029
|
+
} catch (error) {
|
|
1030
|
+
if (error?.code === "EISDIR") return null;
|
|
1031
|
+
throw error;
|
|
1032
|
+
}
|
|
1033
|
+
if (body === null) return null;
|
|
1034
|
+
return revisionFingerprint(name, body, await this.liveSupportFiles(name));
|
|
1035
|
+
}
|
|
1036
|
+
/** Content anchor of one live skill; the hash a decision records and a commit re-checks. */
|
|
1037
|
+
async revisionAnchor(rawName) {
|
|
1038
|
+
const fingerprint = await this.revisionFingerprint(rawName);
|
|
1039
|
+
return fingerprint === null ? { kind: "absent" } : {
|
|
1040
|
+
kind: "present",
|
|
1041
|
+
sha256: contentHash(fingerprint)
|
|
1042
|
+
};
|
|
1043
|
+
}
|
|
1044
|
+
/** Every support file of one live skill, in listing order; unreadable/missing files fail loud. */
|
|
1045
|
+
async liveSupportFiles(rawName) {
|
|
1046
|
+
const name = rawName.trim();
|
|
1047
|
+
if (this.badName(name) !== null) return [];
|
|
1048
|
+
const listed = await this.listSupportFiles(name);
|
|
1049
|
+
if (isUnknown(listed)) throw new Error("support file list is unknown: " + name);
|
|
1050
|
+
if (!isPresent(listed)) return [];
|
|
1051
|
+
const dir = this.dirOf(name);
|
|
1052
|
+
return await Promise.all(listed.value.map(async (path) => {
|
|
1053
|
+
const content = await this.io.readText(join(dir, ...path.replace(/\\/g, "/").split("/").filter(Boolean)));
|
|
1054
|
+
if (content === null) throw new Error("support file disappeared: " + name + "/" + path);
|
|
1055
|
+
return {
|
|
1056
|
+
path,
|
|
1057
|
+
content
|
|
1058
|
+
};
|
|
1059
|
+
}));
|
|
1060
|
+
}
|
|
1061
|
+
/**
|
|
1062
|
+
* Single path-building choke point (rc.42 audit P2-5): every directory path
|
|
1063
|
+
|
|
1064
|
+
* is built from the TRIMMED name, so a name that passes `badName` (which
|
|
1065
|
+
|
|
1066
|
+
* trims before validating) can never mint a second, whitespace-padded
|
|
1067
|
+
|
|
1068
|
+
* directory next to the real one. Callers keep passing raw user input.
|
|
1069
|
+
|
|
1070
|
+
*/
|
|
1071
|
+
dirOf(name) {
|
|
1072
|
+
return skillDir(this.root, name.trim());
|
|
1073
|
+
}
|
|
1074
|
+
/**
|
|
1075
|
+
* Name-format guard for every path-building entry point (P1-1/v14 closed the
|
|
1076
|
+
* one gap: `patch`). Write paths, protection probes and support-file
|
|
1077
|
+
* enumeration all call it before `dirOf`, so no directory path is ever built
|
|
1078
|
+
* from a name that could escape the skills root. `list()` and `snapshotAll()`
|
|
1079
|
+
* are the deliberate exceptions — their names come from `listNames()`, i.e.
|
|
1080
|
+
* from the tree itself, never from caller input.
|
|
1081
|
+
*/
|
|
1082
|
+
badName(name, opts = {}) {
|
|
1083
|
+
const normalized = name.trim();
|
|
1084
|
+
if (!SKILL_NAME_RE.test(normalized) || normalized.length > this.limits.maxNameLength) return `技能名「${normalized}」不合法:请只用小写字母、数字和连字符(不超过 ${this.limits.maxNameLength} 个)。`;
|
|
1085
|
+
if (!opts.allowReserved && WIN32_RESERVED_DEVICE_NAMES.has(normalized)) return `"${normalized}" is a Windows reserved device name and cannot be used as a skill name.`;
|
|
1086
|
+
return null;
|
|
1087
|
+
}
|
|
1088
|
+
/**
|
|
1089
|
+
* Refusal reason for a write to `rawName`, or null when the write may
|
|
1090
|
+
* proceed: a protection marker on the directory, or an invalid name
|
|
1091
|
+
* (P1-1/v14 — the name guard lives HERE as well as at every entry point, so
|
|
1092
|
+
* no caller can build a path from an unvalidated name).
|
|
1093
|
+
*/
|
|
1094
|
+
async writeProtection(rawName, origin = this.authority.origin) {
|
|
1095
|
+
const name = rawName.trim();
|
|
1096
|
+
const badName = this.badName(name);
|
|
1097
|
+
if (badName) return badName;
|
|
1098
|
+
const dir = this.dirOf(name);
|
|
1099
|
+
for (const marker of ["bundled", "hub-installed"]) if (await this.io.exists(markerPath(dir, marker))) return marker;
|
|
1100
|
+
if (origin === "background_review" && await this.io.exists(markerPath(dir, "pinned"))) return "pinned";
|
|
1101
|
+
return null;
|
|
1102
|
+
}
|
|
1103
|
+
async deleteProtection(rawName, options = {}) {
|
|
1104
|
+
const name = rawName.trim();
|
|
1105
|
+
const badName = this.badName(name, { allowReserved: true });
|
|
1106
|
+
if (badName) return badName;
|
|
1107
|
+
const dir = this.dirOf(name);
|
|
1108
|
+
const markers = options.allowBundled ? ["hub-installed", "pinned"] : [
|
|
1109
|
+
"bundled",
|
|
1110
|
+
"hub-installed",
|
|
1111
|
+
"pinned"
|
|
1112
|
+
];
|
|
1113
|
+
for (const marker of markers) if (await this.io.exists(markerPath(dir, marker))) return marker;
|
|
1114
|
+
return null;
|
|
1115
|
+
}
|
|
1116
|
+
/** Whether the target directory exists at all (a SKILL.md-less ghost still occupies the name). */
|
|
1117
|
+
async skillDirExists(rawName) {
|
|
1118
|
+
const name = rawName.trim();
|
|
1119
|
+
if (this.badName(name) !== null) return false;
|
|
1120
|
+
return await this.io.exists(this.dirOf(name));
|
|
1121
|
+
}
|
|
1122
|
+
async isManaged(rawName) {
|
|
1123
|
+
const name = rawName.trim();
|
|
1124
|
+
if (this.badName(name) !== null) return false;
|
|
1125
|
+
const dir = this.dirOf(name);
|
|
1126
|
+
return await this.io.exists(markerPath(dir, "hermes-managed"));
|
|
1127
|
+
}
|
|
1128
|
+
/** Whether the skill carries the bundled marker (curator prune-builtins eligibility). */
|
|
1129
|
+
async isBundled(rawName) {
|
|
1130
|
+
const name = rawName.trim();
|
|
1131
|
+
if (this.badName(name) !== null) return false;
|
|
1132
|
+
const dir = this.dirOf(name);
|
|
1133
|
+
return await this.io.exists(markerPath(dir, "bundled"));
|
|
1134
|
+
}
|
|
1135
|
+
/** Whether the skill carries the pinned marker (the marker is the factual source; usage.pinned mirrors it). */
|
|
1136
|
+
async isPinned(rawName) {
|
|
1137
|
+
const name = rawName.trim();
|
|
1138
|
+
if (this.badName(name) !== null) return false;
|
|
1139
|
+
const dir = this.dirOf(name);
|
|
1140
|
+
return await this.io.exists(markerPath(dir, "pinned"));
|
|
1141
|
+
}
|
|
1142
|
+
/** Count non-empty support subdirectories (richness input for quality scoring). */
|
|
1143
|
+
/** G4 ⑤-d: the dangling targets THIS write introduced, as a receipt note (empty when none).
|
|
1144
|
+
*
|
|
1145
|
+
* Uses the SAME resolver as the drift signal, so a receipt and a drift row can never disagree;
|
|
1146
|
+
* an absent or unknown listing reports nothing rather than inventing a dead link.
|
|
1147
|
+
*/
|
|
1148
|
+
async danglingNoteFor(skillName, before, after) {
|
|
1149
|
+
try {
|
|
1150
|
+
const listing = await this.listSupportFiles(skillName);
|
|
1151
|
+
if (!isPresent(listing)) return "";
|
|
1152
|
+
const files = listing.value;
|
|
1153
|
+
const owner = "SKILL.md";
|
|
1154
|
+
const seen = new Set(resolveCitations({
|
|
1155
|
+
content: before,
|
|
1156
|
+
file: owner,
|
|
1157
|
+
files
|
|
1158
|
+
}).dangling.map((ref) => ref.target ?? ref.raw));
|
|
1159
|
+
const introduced = resolveCitations({
|
|
1160
|
+
content: after,
|
|
1161
|
+
file: owner,
|
|
1162
|
+
files
|
|
1163
|
+
}).dangling.map((ref) => ref.target ?? ref.raw).filter((target) => !seen.has(target));
|
|
1164
|
+
return introduced.length > 0 ? " [dangling: " + introduced.join(",") + "]" : "";
|
|
1165
|
+
} catch {
|
|
1166
|
+
return "";
|
|
1167
|
+
}
|
|
1168
|
+
}
|
|
1169
|
+
async countSupportDirs(rawName) {
|
|
1170
|
+
const name = rawName.trim();
|
|
1171
|
+
if (this.badName(name) !== null) return 0;
|
|
1172
|
+
const dir = this.dirOf(name);
|
|
1173
|
+
const listed = await probeList(this.io, dir);
|
|
1174
|
+
if (!isPresent(listed)) return 0;
|
|
1175
|
+
let count = 0;
|
|
1176
|
+
for (const subdir of SUPPORT_DIRS) {
|
|
1177
|
+
if (!listed.value.includes(subdir)) continue;
|
|
1178
|
+
const files = await probeList(this.io, join(dir, subdir));
|
|
1179
|
+
if (isPresent(files) && files.value.some((file) => file !== ".gitkeep")) count += 1;
|
|
1180
|
+
}
|
|
1181
|
+
return count;
|
|
1182
|
+
}
|
|
1183
|
+
/**
|
|
1184
|
+
* Support-file paths (`references/x.md`) under SUPPORT_DIRS for one skill,
|
|
1185
|
+
* as a THREE-state read (N14): a missing skill directory is absent, an
|
|
1186
|
+
* unreadable one is unknown. A partial listing is unknown too — the union
|
|
1187
|
+
* promises the present branch is complete (011 §7 enrichment, probe reads).
|
|
1188
|
+
*/
|
|
1189
|
+
async listSupportFiles(rawName) {
|
|
1190
|
+
const name = rawName.trim();
|
|
1191
|
+
if (this.badName(name) !== null) return probeAbsent();
|
|
1192
|
+
const dir = this.dirOf(name);
|
|
1193
|
+
const listed = await probeList(this.io, dir);
|
|
1194
|
+
if (!isPresent(listed)) return listed;
|
|
1195
|
+
const out = [];
|
|
1196
|
+
for (const subdir of SUPPORT_DIRS) {
|
|
1197
|
+
if (!listed.value.includes(subdir)) continue;
|
|
1198
|
+
const files = await probeList(this.io, join(dir, subdir));
|
|
1199
|
+
if (isUnknown(files)) return files;
|
|
1200
|
+
if (!isPresent(files)) continue;
|
|
1201
|
+
for (const file of files.value) {
|
|
1202
|
+
if (file === ".gitkeep" || file.startsWith(".")) continue;
|
|
1203
|
+
out.push(`${subdir}/${file}`);
|
|
1204
|
+
}
|
|
1205
|
+
}
|
|
1206
|
+
return probePresent(out);
|
|
1207
|
+
}
|
|
1208
|
+
/**
|
|
1209
|
+
* V4 (design §16.6): exact character counts of the support files that can
|
|
1210
|
+
* POSSIBLY exceed the content cap. The pre-filter is BYTE size, and that is
|
|
1211
|
+
* sound rather than approximate: a UTF-16 code unit never costs less than one
|
|
1212
|
+
* UTF-8 byte, so a file whose bytes are within the cap provably cannot exceed
|
|
1213
|
+
* the cap in characters. The returned map is therefore COMPLETE for the
|
|
1214
|
+
* oversize question without reading the small files.
|
|
1215
|
+
* @param rawName - the skill's name.
|
|
1216
|
+
* @returns path -> character count (possibly empty), or null when the listing or
|
|
1217
|
+
* a size probe cannot answer — unknown is never an empty map.
|
|
1218
|
+
*/
|
|
1219
|
+
/** A plan-time read whose bytes become a tree change's CAS baseline (`expected`). A failed read is
|
|
1220
|
+
* NAMED and answers `null`, which is FAIL-CLOSED at commit: the baseline is then "absent", so an
|
|
1221
|
+
* existing file counts as drift and the commit refuses instead of overwriting bytes nobody read
|
|
1222
|
+
* (N36: the failure is not silently "the file is not there").
|
|
1223
|
+
* @param target - the file a tree change is about to write.
|
|
1224
|
+
* @returns its bytes, or `null` for both "absent" and "could not read". */
|
|
1225
|
+
async readForCas(target) {
|
|
1226
|
+
const probe = await probeText(this.io, target);
|
|
1227
|
+
if (isUnknown(probe)) {
|
|
1228
|
+
console.warn(`skill-store: could not read ${target} for the tree change's baseline (${probe.reason}); treating it as absent — an existing file then counts as drift and the commit refuses`);
|
|
1229
|
+
return null;
|
|
1230
|
+
}
|
|
1231
|
+
return isPresent(probe) ? probe.value : null;
|
|
1232
|
+
}
|
|
1233
|
+
async supportFileChars(rawName) {
|
|
1234
|
+
const name = rawName.trim();
|
|
1235
|
+
if (this.badName(name) !== null) return null;
|
|
1236
|
+
const listed = await this.listSupportFiles(name);
|
|
1237
|
+
if (!isPresent(listed)) return null;
|
|
1238
|
+
const dir = this.dirOf(name);
|
|
1239
|
+
const chars = {};
|
|
1240
|
+
for (const path of listed.value) {
|
|
1241
|
+
const full = join(dir, ...path.split("/").filter(Boolean));
|
|
1242
|
+
let bytes = null;
|
|
1243
|
+
if (this.io.size !== void 0) try {
|
|
1244
|
+
bytes = await this.io.size(full);
|
|
1245
|
+
} catch (error) {
|
|
1246
|
+
console.warn(`skill-store: size of ${full} could not be read (${error instanceof Error ? error.message : String(error)}); reporting no support-file char counts`);
|
|
1247
|
+
return null;
|
|
1248
|
+
}
|
|
1249
|
+
if (bytes === null) return null;
|
|
1250
|
+
if (bytes <= this.limits.maxSkillContentChars) continue;
|
|
1251
|
+
const contentProbe = await probeText(this.io, full);
|
|
1252
|
+
if (!isPresent(contentProbe)) {
|
|
1253
|
+
if (isUnknown(contentProbe)) console.warn(`skill-store: ${full} could not be read (${contentProbe.reason}); reporting no support-file char counts`);
|
|
1254
|
+
return null;
|
|
1255
|
+
}
|
|
1256
|
+
chars[path] = contentProbe.value.length;
|
|
1257
|
+
}
|
|
1258
|
+
return chars;
|
|
1259
|
+
}
|
|
1260
|
+
/**
|
|
1261
|
+
* Structure-health facts for one skill (rc.73 A1, 008 design): body
|
|
1262
|
+
* chars/density from SKILL.md, support groups from countSupportDirs, plus
|
|
1263
|
+
* optional usage counts (A2 churn dimension) when the caller has them.
|
|
1264
|
+
* Derived, never persisted. CONTRACT: `null` whenever the skill cannot be
|
|
1265
|
+
* read — a missing file AND any read failure (EACCES/EIO/…) both answer
|
|
1266
|
+
* null, so a whole health view degrades one ROW instead of throwing out of
|
|
1267
|
+
* its per-skill loop (A6, audit P2-10: the former code absorbed only
|
|
1268
|
+
* missing/EISDIR and let a transient win32 hold kill the entire view).
|
|
1269
|
+
*/
|
|
1270
|
+
async assessHealth(rawName, thresholds = DEFAULT_HEALTH_THRESHOLDS, counts) {
|
|
1271
|
+
try {
|
|
1272
|
+
const name = rawName.trim();
|
|
1273
|
+
const content = await this.read(name);
|
|
1274
|
+
if (content === null) return null;
|
|
1275
|
+
const support = await this.listSupportFiles(name);
|
|
1276
|
+
const supportFiles = isPresent(support) ? support.value.length : void 0;
|
|
1277
|
+
return assessStructureHealth({
|
|
1278
|
+
skillName: name,
|
|
1279
|
+
bodyChars: content.length,
|
|
1280
|
+
bodyText: content,
|
|
1281
|
+
supportGroups: await this.countSupportDirs(name),
|
|
1282
|
+
...supportFiles === void 0 ? {} : { supportFiles },
|
|
1283
|
+
patchCount: counts?.patchCount,
|
|
1284
|
+
readCount: counts?.readCount,
|
|
1285
|
+
...counts?.hardCapHits === void 0 ? {} : { hardCapHits: counts.hardCapHits }
|
|
1286
|
+
}, thresholds);
|
|
1287
|
+
} catch {
|
|
1288
|
+
return null;
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
/** S2: mechanical hard-cap event; failure must not change the refusal. */
|
|
1292
|
+
async recordHardCapHit(name, bodyChars, source, supportFiles = null) {
|
|
1293
|
+
try {
|
|
1294
|
+
await appendEvolutionEvent(this.io, eventsFile(dirname(this.root)), {
|
|
1295
|
+
type: "hard-cap",
|
|
1296
|
+
target: name,
|
|
1297
|
+
bodyChars,
|
|
1298
|
+
supportFiles,
|
|
1299
|
+
restructureRounds: 0,
|
|
1300
|
+
source
|
|
1301
|
+
}, void 0, this.fence);
|
|
1302
|
+
} catch (error) {
|
|
1303
|
+
console.warn("skill-store: hard-cap event not recorded for \"" + name + "\": " + (error instanceof Error ? error.message : String(error)));
|
|
1304
|
+
}
|
|
1305
|
+
}
|
|
1306
|
+
/** Best-effort audit trail entry; never blocks the mutation.
|
|
1307
|
+
*
|
|
1308
|
+
* Two independent best-effort writes run here, because either one failing must not cost the
|
|
1309
|
+
* other: the CONTENT history (skill-history.ts, so a version can be read back at all) and the
|
|
1310
|
+
* mutation ledger that points at it. The history failure is not silent — a deployment whose
|
|
1311
|
+
* history stopped growing is a degradation worth seeing once (the ledger keeps hashes either
|
|
1312
|
+
* way). */
|
|
1313
|
+
async audit(skillName, action, before, after, summary, path, unitId, unitHead, origin) {
|
|
1314
|
+
const at = (/* @__PURE__ */ new Date()).toISOString();
|
|
1315
|
+
let versions = null;
|
|
1316
|
+
try {
|
|
1317
|
+
const keep = this.limits.versionKeep ?? 20;
|
|
1318
|
+
const input = {
|
|
1319
|
+
skillName,
|
|
1320
|
+
action,
|
|
1321
|
+
before,
|
|
1322
|
+
after,
|
|
1323
|
+
at,
|
|
1324
|
+
...path === void 0 ? {} : { path },
|
|
1325
|
+
...unitId === void 0 ? {} : { unitId },
|
|
1326
|
+
...unitHead === void 0 ? {} : { unitHead }
|
|
1327
|
+
};
|
|
1328
|
+
versions = await recordVersions(this.root, this.io, input, keep, this.fence);
|
|
1329
|
+
} catch (error) {
|
|
1330
|
+
if (!this.historyWarned) {
|
|
1331
|
+
this.historyWarned = true;
|
|
1332
|
+
console.warn(`skill-store: content history not recorded for "${skillName}" (${error instanceof Error ? error.message : String(error)}); the mutation itself landed and the audit ledger keeps its hashes`);
|
|
1333
|
+
}
|
|
1334
|
+
}
|
|
1335
|
+
let healthNote = "";
|
|
1336
|
+
const danglingNote = before === null || after === null || before === after ? "" : await this.danglingNoteFor(skillName, before, after);
|
|
1337
|
+
if (before !== null && after !== null && before !== after) try {
|
|
1338
|
+
const groups = await this.countSupportDirs(skillName);
|
|
1339
|
+
const delta = diffFindings(lintBody(skillName, before, groups), lintBody(skillName, after, groups));
|
|
1340
|
+
const parts = [];
|
|
1341
|
+
if (delta.introduced.length > 0) parts.push("+" + delta.introduced.map((f) => f.rule).join(","));
|
|
1342
|
+
if (delta.worsened.length > 0) parts.push("^" + delta.worsened.map((f) => f.rule + " x" + String(f.count)).join(","));
|
|
1343
|
+
if (parts.length > 0) healthNote = " [health: " + parts.join(" ") + "]";
|
|
1344
|
+
} catch {
|
|
1345
|
+
healthNote = "";
|
|
1346
|
+
}
|
|
1347
|
+
try {
|
|
1348
|
+
await recordMutation(this.root, this.io, {
|
|
1349
|
+
skillName,
|
|
1350
|
+
action,
|
|
1351
|
+
...before === null ? {} : { beforeHash: contentHash(before) },
|
|
1352
|
+
...after === null ? {} : { afterHash: contentHash(after) },
|
|
1353
|
+
...versions?.beforeVersion === void 0 ? {} : { beforeVersion: versions.beforeVersion },
|
|
1354
|
+
...versions?.afterVersion === void 0 ? {} : { afterVersion: versions.afterVersion },
|
|
1355
|
+
summary: summary + healthNote + danglingNote,
|
|
1356
|
+
at,
|
|
1357
|
+
...origin === void 0 ? {} : { origin }
|
|
1358
|
+
}, void 0, this.fence);
|
|
1359
|
+
} catch {}
|
|
1360
|
+
}
|
|
1361
|
+
/** Recent mutation audit records (read-only inspection surface). */
|
|
1362
|
+
async listMutations() {
|
|
1363
|
+
return await loadMutations(this.root, this.io);
|
|
1364
|
+
}
|
|
1365
|
+
/**
|
|
1366
|
+
* Content versions recorded for one skill, oldest first (skill-history.ts, batch A).
|
|
1367
|
+
*
|
|
1368
|
+
* Read-only: the version seam never feeds a judgment — callers use it to LIST and to read content
|
|
1369
|
+
* back. A malformed or unreadable index reads as empty, and a bad name reads as empty too (the
|
|
1370
|
+
* caller is a human command, so "no versions" is the honest answer for a name that cannot exist).
|
|
1371
|
+
* @param rawName - the skill's name.
|
|
1372
|
+
* @returns the versions, oldest first.
|
|
1373
|
+
*/
|
|
1374
|
+
async listVersions(rawName) {
|
|
1375
|
+
const name = rawName.trim();
|
|
1376
|
+
if (this.badName(name) !== null) return [];
|
|
1377
|
+
return await loadVersions(this.root, this.io, name);
|
|
1378
|
+
}
|
|
1379
|
+
/** Versions from the latest merge baseline onward; old versions stay listable via listVersions. */
|
|
1380
|
+
async listBaselineVersions(rawName) {
|
|
1381
|
+
const versions = await this.listVersions(rawName);
|
|
1382
|
+
let start = -1;
|
|
1383
|
+
for (let index = versions.length - 1; index >= 0; index -= 1) if (versions[index]?.unitHead?.baseline === true) {
|
|
1384
|
+
start = index;
|
|
1385
|
+
break;
|
|
1386
|
+
}
|
|
1387
|
+
return start < 0 ? versions : versions.slice(start);
|
|
1388
|
+
}
|
|
1389
|
+
/**
|
|
1390
|
+
* One version's content, read back from the content-addressed blob store.
|
|
1391
|
+
* @param rawName - the skill's name.
|
|
1392
|
+
* @param v - the version number (see {@link SkillLibrary.listVersions}).
|
|
1393
|
+
* @returns the content, or null when the version does not exist, the name is unusable, or the
|
|
1394
|
+
* blob cannot be read — never an empty string.
|
|
1395
|
+
*/
|
|
1396
|
+
async readVersion(rawName, v) {
|
|
1397
|
+
const name = rawName.trim();
|
|
1398
|
+
if (this.badName(name) !== null) return null;
|
|
1399
|
+
return await loadVersionContent(this.root, this.io, name, v);
|
|
1400
|
+
}
|
|
1401
|
+
/** Read an archived skill's real archived_at, or null when the usage sidecar has no fact. */
|
|
1402
|
+
async readArchivedAt(rawName) {
|
|
1403
|
+
const name = rawName.trim();
|
|
1404
|
+
if (this.badName(name) !== null) return null;
|
|
1405
|
+
const raw = (await loadUsage(this.root, this.io)).get(name)?.archived_at;
|
|
1406
|
+
if (raw === null || raw === void 0) return null;
|
|
1407
|
+
const at = Date.parse(raw);
|
|
1408
|
+
return Number.isFinite(at) ? at : null;
|
|
1409
|
+
}
|
|
1410
|
+
/** Read an archived skill's human-readable reason, exact or stamped. */
|
|
1411
|
+
async readArchiveReason(rawName) {
|
|
1412
|
+
const name = rawName.trim();
|
|
1413
|
+
if (this.badName(name) !== null) return null;
|
|
1414
|
+
const archiveRoot = join(this.root, ".archive");
|
|
1415
|
+
const exact = await this.io.readText(join(archiveRoot, name, ".archive-reason"));
|
|
1416
|
+
if (exact !== null) return exact.trim();
|
|
1417
|
+
const entries = await this.io.list(archiveRoot).catch(() => []);
|
|
1418
|
+
for (const entry of [...entries].reverse()) {
|
|
1419
|
+
if (entry !== name && !entry.startsWith(name + "-")) continue;
|
|
1420
|
+
const marker = await this.io.readText(join(archiveRoot, entry, ".archive-name"));
|
|
1421
|
+
if (marker !== null && marker.trim() !== name) continue;
|
|
1422
|
+
const reason = await this.io.readText(join(archiveRoot, entry, ".archive-reason"));
|
|
1423
|
+
if (reason !== null) return reason.trim();
|
|
1424
|
+
}
|
|
1425
|
+
return null;
|
|
1426
|
+
}
|
|
1427
|
+
/** Read an archived skill body (SKILL.md) by its original name, exact or stamped. */
|
|
1428
|
+
async readArchived(rawName) {
|
|
1429
|
+
const name = rawName.trim();
|
|
1430
|
+
if (this.badName(name) !== null) return null;
|
|
1431
|
+
const archiveRoot = join(this.root, ".archive");
|
|
1432
|
+
const exact = await this.io.readText(join(archiveRoot, name, "SKILL.md"));
|
|
1433
|
+
if (exact !== null) return exact;
|
|
1434
|
+
const entries = await this.io.list(archiveRoot).catch(() => []);
|
|
1435
|
+
for (const entry of [...entries].reverse()) {
|
|
1436
|
+
if (entry !== name && !entry.startsWith(name + "-")) continue;
|
|
1437
|
+
const marker = await this.io.readText(join(archiveRoot, entry, ".archive-name"));
|
|
1438
|
+
if (marker !== null && marker.trim() !== name) continue;
|
|
1439
|
+
const text = await this.io.readText(join(archiveRoot, entry, "SKILL.md"));
|
|
1440
|
+
if (text !== null) return text;
|
|
1441
|
+
}
|
|
1442
|
+
return null;
|
|
1443
|
+
}
|
|
1444
|
+
/**
|
|
1445
|
+
* Pin or unpin a skill (`.pinned` marker). Pinned skills are protected from
|
|
1446
|
+
* deletion, from background-review writes, and from the lifecycle — a
|
|
1447
|
+
* protective mutation, so the autonomous pipeline may never call it. The
|
|
1448
|
+
* marker write is the only state change; content is untouched.
|
|
1449
|
+
*/
|
|
1450
|
+
async setPinned(name, pinned, origin = this.authority.origin) {
|
|
1451
|
+
return await this.serial(() => this.setPinnedCore(name, pinned, origin));
|
|
1452
|
+
}
|
|
1453
|
+
async setPinnedCore(name, pinned, origin) {
|
|
1454
|
+
const normalized = name.trim();
|
|
1455
|
+
const bad = this.badName(normalized);
|
|
1456
|
+
if (bad) return {
|
|
1457
|
+
ok: false,
|
|
1458
|
+
message: bad
|
|
1459
|
+
};
|
|
1460
|
+
if (origin === "background_review") return {
|
|
1461
|
+
ok: false,
|
|
1462
|
+
message: "只有前台(用户或主智能体)可以固定或取消固定技能。"
|
|
1463
|
+
};
|
|
1464
|
+
let durabilityWarning = "";
|
|
1465
|
+
const dir = this.dirOf(normalized);
|
|
1466
|
+
const marker = markerPath(dir, "pinned");
|
|
1467
|
+
const existing = await this.io.exists(marker);
|
|
1468
|
+
if (pinned && existing) return {
|
|
1469
|
+
ok: true,
|
|
1470
|
+
message: `技能「${normalized}」已被固定。`,
|
|
1471
|
+
path: dir
|
|
1472
|
+
};
|
|
1473
|
+
if (!pinned && !existing) return {
|
|
1474
|
+
ok: true,
|
|
1475
|
+
message: `技能「${normalized}」未被固定,无需处理。`,
|
|
1476
|
+
path: dir
|
|
1477
|
+
};
|
|
1478
|
+
if (!await this.io.exists(join(dir, "SKILL.md"))) return {
|
|
1479
|
+
ok: false,
|
|
1480
|
+
message: `技能「${normalized}」不存在。`
|
|
1481
|
+
};
|
|
1482
|
+
if (pinned) {
|
|
1483
|
+
try {
|
|
1484
|
+
await this.io.writeText(marker, "");
|
|
1485
|
+
} catch (error) {
|
|
1486
|
+
if (!isCommittedOnly(error)) throw error;
|
|
1487
|
+
durabilityWarning = error instanceof Error ? error.message : String(error);
|
|
1488
|
+
}
|
|
1489
|
+
if (!await this.io.exists(join(dir, "SKILL.md"))) {
|
|
1490
|
+
await this.io.remove(marker).catch(() => {});
|
|
1491
|
+
await this.cleanupGhostDir(join(dir, "SKILL.md"));
|
|
1492
|
+
return {
|
|
1493
|
+
ok: false,
|
|
1494
|
+
message: `固定过程中技能「${normalized}」被并发归档;残留标记已移除:等搬运完成后重试。`
|
|
1495
|
+
};
|
|
1496
|
+
}
|
|
1497
|
+
} else await this.io.remove(marker);
|
|
1498
|
+
await this.audit(normalized, pinned ? "pin" : "unpin", null, null, pinned ? "pinned" : "unpinned");
|
|
1499
|
+
return {
|
|
1500
|
+
ok: true,
|
|
1501
|
+
message: `${pinned ? `技能 "${normalized}" 已固定:免受删除、后台复核与生命周期影响。` : `技能 "${normalized}" 已取消固定。`}${durabilityWarning === "" ? "" : ` (警告:写入已落盘,但目录 fsync 失败 —— 持久性未确认:${durabilityWarning})`}`,
|
|
1502
|
+
path: dir
|
|
1503
|
+
};
|
|
1504
|
+
}
|
|
1505
|
+
async create(name, content, origin = this.authority.origin, options = {}) {
|
|
1506
|
+
await this.ensureRecovered();
|
|
1507
|
+
const normalized = name.trim();
|
|
1508
|
+
return await this.serial(() => this.withMutationLock(() => this.createCore(normalized, content, origin, options)));
|
|
1509
|
+
}
|
|
1510
|
+
async createCore(normalized, content, origin, options = {}) {
|
|
1511
|
+
const bad = this.badName(normalized);
|
|
1512
|
+
if (bad) return {
|
|
1513
|
+
ok: false,
|
|
1514
|
+
message: bad
|
|
1515
|
+
};
|
|
1516
|
+
const validation = validateFrontmatter(content, normalized, this.limits);
|
|
1517
|
+
if (validation) {
|
|
1518
|
+
if (exceedsContentLimit(content, this.limits.maxSkillContentChars)) await this.recordHardCapHit(normalized, content.length, "create");
|
|
1519
|
+
return {
|
|
1520
|
+
ok: false,
|
|
1521
|
+
message: validation
|
|
1522
|
+
};
|
|
1523
|
+
}
|
|
1524
|
+
const norm = normalizeFrontmatter(content);
|
|
1525
|
+
if (norm.issues.length > 0) return {
|
|
1526
|
+
ok: false,
|
|
1527
|
+
message: `技能「${normalized}」的 frontmatter 无法自动修复:${norm.issues[0]}:请用双引号包住取值后重试。`
|
|
1528
|
+
};
|
|
1529
|
+
const finalContent = norm.changed ? norm.content : content;
|
|
1530
|
+
if (norm.changed) {
|
|
1531
|
+
const revalidated = validateFrontmatter(finalContent, normalized, this.limits);
|
|
1532
|
+
if (revalidated) return {
|
|
1533
|
+
ok: false,
|
|
1534
|
+
message: revalidated
|
|
1535
|
+
};
|
|
1536
|
+
}
|
|
1537
|
+
const threat = this.contentThreatBlock(finalContent);
|
|
1538
|
+
if (threat) return {
|
|
1539
|
+
ok: false,
|
|
1540
|
+
message: threat
|
|
1541
|
+
};
|
|
1542
|
+
const dir = this.dirOf(normalized);
|
|
1543
|
+
if (await this.io.exists(join(dir, "SKILL.md"))) return {
|
|
1544
|
+
ok: false,
|
|
1545
|
+
message: `技能「${normalized}」已存在。`
|
|
1546
|
+
};
|
|
1547
|
+
let rootEntries;
|
|
1548
|
+
try {
|
|
1549
|
+
rootEntries = await this.io.list(this.root);
|
|
1550
|
+
} catch (error) {
|
|
1551
|
+
const cause = error instanceof Error ? error.message : String(error);
|
|
1552
|
+
return {
|
|
1553
|
+
ok: false,
|
|
1554
|
+
message: `无法检查技能「${normalized}」是否与大小写变体冲突:列出 ${this.root} 失败(${cause})。拒绝创建 —— 仅大小写不同的第二个目录在跨平台时无法撤销。`
|
|
1555
|
+
};
|
|
1556
|
+
}
|
|
1557
|
+
for (const entry of rootEntries) if (typeof entry === "string" && entry !== normalized && entry.toLowerCase() === normalized.toLowerCase()) return {
|
|
1558
|
+
ok: false,
|
|
1559
|
+
message: `技能「${normalized}」与已存在的大小写变体目录「${entry}」冲突(技能名只允许小写):请重命名其中一个。`
|
|
1560
|
+
};
|
|
1561
|
+
const protection = await this.writeProtection(normalized, origin);
|
|
1562
|
+
if (protection) return {
|
|
1563
|
+
ok: false,
|
|
1564
|
+
message: `技能「${normalized}」受保护(${protection})。`
|
|
1565
|
+
};
|
|
1566
|
+
const onDisk = finalContent.trimEnd() + "\n";
|
|
1567
|
+
const createPath = join(dir, "SKILL.md");
|
|
1568
|
+
const result = await new MutationUnit({
|
|
1569
|
+
io: this.io,
|
|
1570
|
+
limits: {
|
|
1571
|
+
maxSkillFileBytes: Number.MAX_SAFE_INTEGER,
|
|
1572
|
+
maxSkillContentChars: Number.MAX_SAFE_INTEGER
|
|
1573
|
+
},
|
|
1574
|
+
nested: true,
|
|
1575
|
+
journal: unitJournalPort(this.io, dirname(this.root)),
|
|
1576
|
+
snapshots: unitSnapshotPort(this.io, dirname(this.root)),
|
|
1577
|
+
transactGuard: false,
|
|
1578
|
+
hooks: { undone: async () => {
|
|
1579
|
+
await this.io.remove(markerPath(dir, "hermes-managed")).catch(() => {});
|
|
1580
|
+
} }
|
|
1581
|
+
}).apply({
|
|
1582
|
+
name: normalized,
|
|
1583
|
+
origin,
|
|
1584
|
+
roots: [{
|
|
1585
|
+
name: normalized,
|
|
1586
|
+
protection: "write"
|
|
1587
|
+
}],
|
|
1588
|
+
rootDirs: { [normalized]: dir },
|
|
1589
|
+
ops: [{
|
|
1590
|
+
kind: "write",
|
|
1591
|
+
target: createPath,
|
|
1592
|
+
content: onDisk,
|
|
1593
|
+
expected: null,
|
|
1594
|
+
skill: normalized
|
|
1595
|
+
}],
|
|
1596
|
+
auditAction: "create",
|
|
1597
|
+
auditSummary: "created",
|
|
1598
|
+
eventAction: "create",
|
|
1599
|
+
cleanupPaths: [markerPath(dir, "hermes-managed")],
|
|
1600
|
+
...options.unitId === void 0 ? {} : { unitId: options.unitId }
|
|
1601
|
+
});
|
|
1602
|
+
if (!result.ok) {
|
|
1603
|
+
if (result.errors.some((error) => error.code === "cas-drift" || error.message.includes("concurrent modification"))) return {
|
|
1604
|
+
ok: false,
|
|
1605
|
+
message: `技能「${normalized}」已存在。`
|
|
1606
|
+
};
|
|
1607
|
+
return {
|
|
1608
|
+
ok: false,
|
|
1609
|
+
message: result.errors.map((error) => error.message).join(";")
|
|
1610
|
+
};
|
|
1611
|
+
}
|
|
1612
|
+
const createDurabilityWarning = result.warnings === void 0 ? "" : result.warnings.join(";");
|
|
1613
|
+
let markerWarning = "";
|
|
1614
|
+
if (origin !== "foreground" || options.managed === true) {
|
|
1615
|
+
try {
|
|
1616
|
+
await this.io.writeText(markerPath(dir, "hermes-managed"), "");
|
|
1617
|
+
} catch (error) {
|
|
1618
|
+
if (isCommittedOnly(error)) markerWarning = `hermes-managed 标记已落盘,但其目录 fsync 失败 —— 持久性未确认:${error instanceof Error ? error.message : String(error)}`;
|
|
1619
|
+
else markerWarning = `hermes-managed marker write failed (${error instanceof Error ? error.message : String(error)}); the skill landed but is NOT lifecycle-managed — recreate or pin it manually`;
|
|
1620
|
+
}
|
|
1621
|
+
if (!await this.io.exists(createPath)) {
|
|
1622
|
+
await this.io.remove(markerPath(dir, "hermes-managed")).catch(() => {});
|
|
1623
|
+
await this.cleanupGhostDir(createPath);
|
|
1624
|
+
return {
|
|
1625
|
+
ok: false,
|
|
1626
|
+
message: `创建过程中技能「${normalized}」被并发归档;残留标记已移除:等搬运完成后重试一次。`
|
|
1627
|
+
};
|
|
1628
|
+
}
|
|
1629
|
+
}
|
|
1630
|
+
await this.audit(normalized, "create", null, onDisk, "created", void 0, result.unitId, options.unitHead);
|
|
1631
|
+
this.notifyMutation({
|
|
1632
|
+
action: "create",
|
|
1633
|
+
name: normalized,
|
|
1634
|
+
skillDir: dir
|
|
1635
|
+
});
|
|
1636
|
+
const warnings = [createDurabilityWarning !== "" ? `写入已落盘,但目录 fsync 失败 —— 持久性未确认:${createDurabilityWarning}` : "", markerWarning].filter((warning) => warning !== "");
|
|
1637
|
+
return {
|
|
1638
|
+
ok: true,
|
|
1639
|
+
message: `已创建技能「${normalized}」。${warnings.length === 0 ? "" : ` (警告:${warnings.join(";")})`}`,
|
|
1640
|
+
path: dir,
|
|
1641
|
+
...norm.changed ? { normalizedFrontmatterFields: norm.fields } : {}
|
|
1642
|
+
};
|
|
1643
|
+
}
|
|
1644
|
+
async update(rawName, content, origin = this.authority.origin, anchor) {
|
|
1645
|
+
const name = rawName.trim();
|
|
1646
|
+
await this.ensureRecovered();
|
|
1647
|
+
return await this.serial(() => this.updateCore(name, content, origin, anchor));
|
|
1648
|
+
}
|
|
1649
|
+
async updateCore(name, content, origin, anchor) {
|
|
1650
|
+
const badName = this.badName(name);
|
|
1651
|
+
if (badName) return {
|
|
1652
|
+
ok: false,
|
|
1653
|
+
message: badName
|
|
1654
|
+
};
|
|
1655
|
+
const dir = this.dirOf(name);
|
|
1656
|
+
const path = join(dir, "SKILL.md");
|
|
1657
|
+
const protection = await this.writeProtection(name, origin);
|
|
1658
|
+
if (protection) return {
|
|
1659
|
+
ok: false,
|
|
1660
|
+
message: `技能「${name}」受保护(${protection})。`
|
|
1661
|
+
};
|
|
1662
|
+
const limitProbe = await probeText(this.io, path);
|
|
1663
|
+
if (isUnknown(limitProbe)) console.warn(`skill-store: could not re-read ${path} for the shrink exemption (${limitProbe.reason}); validating without it — an over-limit repair is refused, not accepted`);
|
|
1664
|
+
const currentForLimit = isPresent(limitProbe) ? limitProbe.value : null;
|
|
1665
|
+
const validation = validateFrontmatter(content, name, this.limits, currentForLimit);
|
|
1666
|
+
if (validation) {
|
|
1667
|
+
if (exceedsContentLimit(content, this.limits.maxSkillContentChars)) await this.recordHardCapHit(name, content.length, "update");
|
|
1668
|
+
return {
|
|
1669
|
+
ok: false,
|
|
1670
|
+
message: validation
|
|
1671
|
+
};
|
|
1672
|
+
}
|
|
1673
|
+
const norm = normalizeFrontmatter(content);
|
|
1674
|
+
if (norm.issues.length > 0) return {
|
|
1675
|
+
ok: false,
|
|
1676
|
+
message: `技能「${name}」的 frontmatter 无法自动修复:${norm.issues[0]}:请用双引号包住取值后重试。`
|
|
1677
|
+
};
|
|
1678
|
+
const finalContent = norm.changed ? norm.content : content;
|
|
1679
|
+
if (norm.changed) {
|
|
1680
|
+
const revalidated = validateFrontmatter(finalContent, name, this.limits, currentForLimit);
|
|
1681
|
+
if (revalidated) return {
|
|
1682
|
+
ok: false,
|
|
1683
|
+
message: revalidated
|
|
1684
|
+
};
|
|
1685
|
+
}
|
|
1686
|
+
const threat = this.contentThreatBlock(finalContent);
|
|
1687
|
+
if (threat) return {
|
|
1688
|
+
ok: false,
|
|
1689
|
+
message: threat
|
|
1690
|
+
};
|
|
1691
|
+
let current;
|
|
1692
|
+
try {
|
|
1693
|
+
current = await this.io.readText(path);
|
|
1694
|
+
} catch (error) {
|
|
1695
|
+
return anchor !== void 0 ? anchorUnverifiable(name, null) : unreadableTarget(name, error);
|
|
1696
|
+
}
|
|
1697
|
+
const verdict = anchorVerdict(anchor, current);
|
|
1698
|
+
if (verdict !== "match") return anchorRefusal(name, verdict);
|
|
1699
|
+
if (current === null) {
|
|
1700
|
+
await this.cleanupGhostDir(path);
|
|
1701
|
+
return {
|
|
1702
|
+
ok: false,
|
|
1703
|
+
message: `技能「${name}」不存在。`
|
|
1704
|
+
};
|
|
1705
|
+
}
|
|
1706
|
+
if (finalContent.trimEnd() === current.trimEnd()) return {
|
|
1707
|
+
ok: true,
|
|
1708
|
+
message: `技能「${name}」未变更:提供的内容与当前文件一致,未写入。`,
|
|
1709
|
+
noop: true,
|
|
1710
|
+
path: dir
|
|
1711
|
+
};
|
|
1712
|
+
const onDisk = finalContent.trimEnd() + "\n";
|
|
1713
|
+
const result = await new MutationUnit({
|
|
1714
|
+
io: this.io,
|
|
1715
|
+
limits: {
|
|
1716
|
+
maxSkillFileBytes: Number.MAX_SAFE_INTEGER,
|
|
1717
|
+
maxSkillContentChars: Number.MAX_SAFE_INTEGER
|
|
1718
|
+
},
|
|
1719
|
+
lock: this.lockPort(),
|
|
1720
|
+
journal: unitJournalPort(this.io, dirname(this.root)),
|
|
1721
|
+
snapshots: unitSnapshotPort(this.io, dirname(this.root)),
|
|
1722
|
+
...this.transact === void 0 ? {} : { transact: this.transact },
|
|
1723
|
+
hooks: { committed: async (event) => {
|
|
1724
|
+
const op = event.ops[0];
|
|
1725
|
+
if (op === void 0) return;
|
|
1726
|
+
await this.audit(name, "update", op.before, op.after, "updated", void 0, event.unitId, { sources: [{ skill: name }] }, origin);
|
|
1727
|
+
this.notifyMutation({
|
|
1728
|
+
action: "update",
|
|
1729
|
+
name,
|
|
1730
|
+
skillDir: dir
|
|
1731
|
+
});
|
|
1732
|
+
} },
|
|
1733
|
+
validateWrite: (op) => op.kind === "write" ? this.contentThreatBlock(op.content) : null
|
|
1734
|
+
}).apply({
|
|
1735
|
+
name,
|
|
1736
|
+
origin,
|
|
1737
|
+
roots: [{
|
|
1738
|
+
name,
|
|
1739
|
+
protection: "write"
|
|
1740
|
+
}],
|
|
1741
|
+
rootDirs: { [name]: dir },
|
|
1742
|
+
ops: [{
|
|
1743
|
+
kind: "write",
|
|
1744
|
+
target: path,
|
|
1745
|
+
content: onDisk,
|
|
1746
|
+
expected: current,
|
|
1747
|
+
skill: name
|
|
1748
|
+
}],
|
|
1749
|
+
auditAction: "update",
|
|
1750
|
+
auditSummary: "updated",
|
|
1751
|
+
eventAction: "update"
|
|
1752
|
+
});
|
|
1753
|
+
if (!result.ok) {
|
|
1754
|
+
const messages = result.errors.map((error) => error.message);
|
|
1755
|
+
if (messages.some((message) => message.includes("mutation-lock-transact-not-run") || message.includes("did not invoke the task"))) return {
|
|
1756
|
+
ok: false,
|
|
1757
|
+
message: "内部错误:写事务没有调用任务;未执行任何写入"
|
|
1758
|
+
};
|
|
1759
|
+
return {
|
|
1760
|
+
ok: false,
|
|
1761
|
+
message: messages.join(";")
|
|
1762
|
+
};
|
|
1763
|
+
}
|
|
1764
|
+
const warning = result.warnings === void 0 || result.warnings.length === 0 ? "" : ` (警告:写入已落盘,但目录 fsync 失败 —— 持久性未确认:${result.warnings.join(";")})`;
|
|
1765
|
+
const retention = contentRetentionFeedback({
|
|
1766
|
+
name,
|
|
1767
|
+
action: "update",
|
|
1768
|
+
before: current,
|
|
1769
|
+
after: onDisk
|
|
1770
|
+
});
|
|
1771
|
+
return {
|
|
1772
|
+
ok: true,
|
|
1773
|
+
message: `技能「${name}」已更新。${warning}${retention === null ? "" : "\n" + retention}`,
|
|
1774
|
+
path: dir,
|
|
1775
|
+
...norm.changed ? { normalizedFrontmatterFields: norm.fields } : {}
|
|
1776
|
+
};
|
|
1777
|
+
}
|
|
1778
|
+
async patch(rawName, oldString, newString, filePath = "", replaceAll = false, origin = this.authority.origin) {
|
|
1779
|
+
await this.ensureRecovered();
|
|
1780
|
+
const name = rawName.trim();
|
|
1781
|
+
return await this.serial(() => this.patchCore(name, oldString, newString, filePath, replaceAll, origin));
|
|
1782
|
+
}
|
|
1783
|
+
async patchCore(name, oldString, newString, filePath, replaceAll, origin) {
|
|
1784
|
+
const badName = this.badName(name);
|
|
1785
|
+
if (badName) return {
|
|
1786
|
+
ok: false,
|
|
1787
|
+
message: badName
|
|
1788
|
+
};
|
|
1789
|
+
const dir = this.dirOf(name);
|
|
1790
|
+
const skillMd = join(dir, "SKILL.md");
|
|
1791
|
+
if (!await this.io.exists(skillMd)) return {
|
|
1792
|
+
ok: false,
|
|
1793
|
+
message: `技能「${name}」不存在。`
|
|
1794
|
+
};
|
|
1795
|
+
const protection = await this.writeProtection(name, origin);
|
|
1796
|
+
if (protection) return {
|
|
1797
|
+
ok: false,
|
|
1798
|
+
message: `技能「${name}」受保护(${protection})。`
|
|
1799
|
+
};
|
|
1800
|
+
let target = skillMd;
|
|
1801
|
+
let patchLabel = "SKILL.md";
|
|
1802
|
+
if (filePath) {
|
|
1803
|
+
const validation = validateSupportPath(filePath);
|
|
1804
|
+
if (validation) return {
|
|
1805
|
+
ok: false,
|
|
1806
|
+
message: validation
|
|
1807
|
+
};
|
|
1808
|
+
target = join(dir, ...filePath.replace(/\\/g, "/").split("/").filter(Boolean));
|
|
1809
|
+
patchLabel = filePath;
|
|
1810
|
+
}
|
|
1811
|
+
const compute = (current) => {
|
|
1812
|
+
const md = current;
|
|
1813
|
+
if (md === null) return {
|
|
1814
|
+
result: {
|
|
1815
|
+
ok: false,
|
|
1816
|
+
message: `文件不存在:${patchLabel}`
|
|
1817
|
+
},
|
|
1818
|
+
write: null
|
|
1819
|
+
};
|
|
1820
|
+
if (!md.includes(oldString) && (oldString.length > 4096 || md.length * oldString.length > 8e6)) return {
|
|
1821
|
+
result: {
|
|
1822
|
+
ok: false,
|
|
1823
|
+
message: `old_string too large for fuzzy match (${oldString.length} chars in ${patchLabel}); use update for a full rewrite or a narrower anchor.`
|
|
1824
|
+
},
|
|
1825
|
+
write: null
|
|
1826
|
+
};
|
|
1827
|
+
if (oldString === "" || trimPatternBoundaries(oldString) === "") return {
|
|
1828
|
+
result: {
|
|
1829
|
+
ok: false,
|
|
1830
|
+
message: `old_string is empty (or whitespace-only) — a patch of "${name}/${patchLabel}" needs an anchor; use update for a full rewrite.`
|
|
1831
|
+
},
|
|
1832
|
+
write: null
|
|
1833
|
+
};
|
|
1834
|
+
const patched = fuzzyPatch(md, oldString, newString, replaceAll);
|
|
1835
|
+
if (patched === null) return {
|
|
1836
|
+
result: {
|
|
1837
|
+
ok: false,
|
|
1838
|
+
message: `在「${name}/${patchLabel}」里找不到 old_string(或 replaceAll 的模糊匹配预算已用尽)。整篇重写请改用 update。`
|
|
1839
|
+
},
|
|
1840
|
+
write: null
|
|
1841
|
+
};
|
|
1842
|
+
const anchorCount = oldString === "" ? 0 : md.split(oldString).length - 1;
|
|
1843
|
+
const patchNote = !replaceAll && anchorCount > 1 ? ` Replaced the FIRST of ${anchorCount} occurrences; pass replace_all=true to change every one.` : "";
|
|
1844
|
+
let writeContent = patched;
|
|
1845
|
+
let normalizedFields;
|
|
1846
|
+
if (target === skillMd) {
|
|
1847
|
+
const validation = validateFrontmatter(patched, name, this.limits, md);
|
|
1848
|
+
if (validation) return {
|
|
1849
|
+
result: {
|
|
1850
|
+
ok: false,
|
|
1851
|
+
message: `补丁被拒绝:${validation}`
|
|
1852
|
+
},
|
|
1853
|
+
write: null
|
|
1854
|
+
};
|
|
1855
|
+
const norm = normalizeFrontmatter(patched);
|
|
1856
|
+
if (norm.issues.length > 0) return {
|
|
1857
|
+
result: {
|
|
1858
|
+
ok: false,
|
|
1859
|
+
message: `补丁被拒绝:frontmatter 无法自动修复(${norm.issues[0]})。`
|
|
1860
|
+
},
|
|
1861
|
+
write: null
|
|
1862
|
+
};
|
|
1863
|
+
if (norm.changed) {
|
|
1864
|
+
writeContent = norm.content;
|
|
1865
|
+
normalizedFields = norm.fields;
|
|
1866
|
+
const revalidated = validateFrontmatter(writeContent, name, this.limits, md);
|
|
1867
|
+
if (revalidated) return {
|
|
1868
|
+
result: {
|
|
1869
|
+
ok: false,
|
|
1870
|
+
message: `补丁被拒绝:${revalidated}`
|
|
1871
|
+
},
|
|
1872
|
+
write: null
|
|
1873
|
+
};
|
|
1874
|
+
}
|
|
1875
|
+
}
|
|
1876
|
+
if (Buffer.byteLength(writeContent, "utf8") > this.limits.maxSkillFileBytes && target !== skillMd) return {
|
|
1877
|
+
result: {
|
|
1878
|
+
ok: false,
|
|
1879
|
+
message: `修补后的文件超过 ${this.limits.maxSkillFileBytes} 字节。`
|
|
1880
|
+
},
|
|
1881
|
+
write: null
|
|
1882
|
+
};
|
|
1883
|
+
const overLimit = exceedsContentLimit(writeContent, this.limits.maxSkillContentChars);
|
|
1884
|
+
const repairing = shrinksOverLimit(writeContent, md, this.limits.maxSkillContentChars);
|
|
1885
|
+
if (overLimit && target === skillMd && !repairing) return {
|
|
1886
|
+
result: {
|
|
1887
|
+
ok: false,
|
|
1888
|
+
message: `修补后的内容超过 ${this.limits.maxSkillContentChars} 个字符。${CONTENT_SPLIT_HINT}`
|
|
1889
|
+
},
|
|
1890
|
+
write: null,
|
|
1891
|
+
hardCapHit: {
|
|
1892
|
+
bodyChars: writeContent.length,
|
|
1893
|
+
supportFiles: null
|
|
1894
|
+
}
|
|
1895
|
+
};
|
|
1896
|
+
const supportOverCap = overLimit && target !== skillMd && !repairing;
|
|
1897
|
+
const capAdvisory = supportOverCap ? ` Warning: ${writeContent.length} characters is over the ${this.limits.maxSkillContentChars}-character cap upstream applies to every file; plan a split.` : "";
|
|
1898
|
+
if (supportOverCap && this.supportFileCharPolicy() === "enforce") return {
|
|
1899
|
+
result: {
|
|
1900
|
+
ok: false,
|
|
1901
|
+
message: `修补后的文件内容超过 ${this.limits.maxSkillContentChars} 个字符。${CONTENT_SPLIT_HINT}`
|
|
1902
|
+
},
|
|
1903
|
+
write: null,
|
|
1904
|
+
hardCapHit: {
|
|
1905
|
+
bodyChars: writeContent.length,
|
|
1906
|
+
supportFiles: 1
|
|
1907
|
+
}
|
|
1908
|
+
};
|
|
1909
|
+
const threat = this.contentThreatBlock(writeContent);
|
|
1910
|
+
if (threat) return {
|
|
1911
|
+
result: {
|
|
1912
|
+
ok: false,
|
|
1913
|
+
message: threat
|
|
1914
|
+
},
|
|
1915
|
+
write: null
|
|
1916
|
+
};
|
|
1917
|
+
if (writeContent.trimEnd() === md.trimEnd()) return {
|
|
1918
|
+
result: {
|
|
1919
|
+
ok: true,
|
|
1920
|
+
message: `技能「${name}」未变更:old_string 与替换内容相同(${patchLabel}),未写入。`,
|
|
1921
|
+
noop: true,
|
|
1922
|
+
path: dir
|
|
1923
|
+
},
|
|
1924
|
+
write: null
|
|
1925
|
+
};
|
|
1926
|
+
const onDisk = writeContent.trimEnd() + "\n";
|
|
1927
|
+
return {
|
|
1928
|
+
result: {
|
|
1929
|
+
ok: true,
|
|
1930
|
+
message: `技能「${name}」已修补(${patchLabel})。${patchNote}${capAdvisory}`,
|
|
1931
|
+
path: dir,
|
|
1932
|
+
...normalizedFields ? { normalizedFrontmatterFields: normalizedFields } : {}
|
|
1933
|
+
},
|
|
1934
|
+
write: onDisk,
|
|
1935
|
+
audit: {
|
|
1936
|
+
skillName: name,
|
|
1937
|
+
action: "patch",
|
|
1938
|
+
before: md,
|
|
1939
|
+
after: onDisk,
|
|
1940
|
+
summary: `patched ${patchLabel}`
|
|
1941
|
+
},
|
|
1942
|
+
event: {
|
|
1943
|
+
action: "patch",
|
|
1944
|
+
name,
|
|
1945
|
+
skillDir: dir
|
|
1946
|
+
}
|
|
1947
|
+
};
|
|
1948
|
+
};
|
|
1949
|
+
let current;
|
|
1950
|
+
try {
|
|
1951
|
+
current = await this.io.readText(target);
|
|
1952
|
+
} catch (error) {
|
|
1953
|
+
return unreadableTarget(name + "/" + patchLabel, error);
|
|
1954
|
+
}
|
|
1955
|
+
if (current === null) {
|
|
1956
|
+
await this.cleanupGhostDir(target);
|
|
1957
|
+
return {
|
|
1958
|
+
ok: false,
|
|
1959
|
+
message: `文件不存在:${patchLabel}`
|
|
1960
|
+
};
|
|
1961
|
+
}
|
|
1962
|
+
const outcome = compute(current);
|
|
1963
|
+
if (outcome.write === null) {
|
|
1964
|
+
if (outcome.hardCapHit !== void 0) await this.recordHardCapHit(name, outcome.hardCapHit.bodyChars, "patch", outcome.hardCapHit.supportFiles);
|
|
1965
|
+
return outcome.result;
|
|
1966
|
+
}
|
|
1967
|
+
const onDisk = outcome.write;
|
|
1968
|
+
const result = await new MutationUnit({
|
|
1969
|
+
io: this.io,
|
|
1970
|
+
limits: {
|
|
1971
|
+
maxSkillFileBytes: Number.MAX_SAFE_INTEGER,
|
|
1972
|
+
maxSkillContentChars: Number.MAX_SAFE_INTEGER
|
|
1973
|
+
},
|
|
1974
|
+
lock: this.lockPort(),
|
|
1975
|
+
journal: unitJournalPort(this.io, dirname(this.root)),
|
|
1976
|
+
snapshots: unitSnapshotPort(this.io, dirname(this.root)),
|
|
1977
|
+
...this.transact === void 0 ? {} : { transact: this.transact },
|
|
1978
|
+
hooks: { committed: async (event) => {
|
|
1979
|
+
await this.audit(name, "patch", outcome.audit?.before ?? current, event.ops[0]?.after ?? onDisk, outcome.audit?.summary ?? `patched ${patchLabel}`, filePath === "" ? void 0 : filePath, event.unitId, { sources: [{ skill: name }] }, origin);
|
|
1980
|
+
this.notifyMutation({
|
|
1981
|
+
action: "patch",
|
|
1982
|
+
name,
|
|
1983
|
+
skillDir: dir
|
|
1984
|
+
});
|
|
1985
|
+
} },
|
|
1986
|
+
validateWrite: (op) => op.kind === "write" ? this.contentThreatBlock(op.content) : null
|
|
1987
|
+
}).apply({
|
|
1988
|
+
name,
|
|
1989
|
+
origin,
|
|
1990
|
+
roots: [{
|
|
1991
|
+
name,
|
|
1992
|
+
protection: "write"
|
|
1993
|
+
}],
|
|
1994
|
+
rootDirs: { [name]: dir },
|
|
1995
|
+
ops: [{
|
|
1996
|
+
kind: "write",
|
|
1997
|
+
target,
|
|
1998
|
+
content: onDisk,
|
|
1999
|
+
expected: current,
|
|
2000
|
+
skill: name
|
|
2001
|
+
}],
|
|
2002
|
+
auditAction: "patch",
|
|
2003
|
+
auditSummary: outcome.audit?.summary ?? `patched ${patchLabel}`,
|
|
2004
|
+
eventAction: "patch"
|
|
2005
|
+
});
|
|
2006
|
+
if (!result.ok) {
|
|
2007
|
+
const messages = result.errors.map((error) => error.message);
|
|
2008
|
+
if (messages.some((message) => message.includes("mutation-lock-transact-not-run") || message.includes("did not invoke the task"))) return {
|
|
2009
|
+
ok: false,
|
|
2010
|
+
message: "内部错误:写事务没有调用任务;未执行任何写入"
|
|
2011
|
+
};
|
|
2012
|
+
return {
|
|
2013
|
+
ok: false,
|
|
2014
|
+
message: messages.join(";")
|
|
2015
|
+
};
|
|
2016
|
+
}
|
|
2017
|
+
const warning = result.warnings === void 0 || result.warnings.length === 0 ? "" : ` (警告:写入已落盘,但目录 fsync 失败 —— 持久性未确认:${result.warnings.join(";")})`;
|
|
2018
|
+
const retention = contentRetentionFeedback({
|
|
2019
|
+
name,
|
|
2020
|
+
action: "patch",
|
|
2021
|
+
before: current,
|
|
2022
|
+
after: onDisk
|
|
2023
|
+
});
|
|
2024
|
+
return {
|
|
2025
|
+
...outcome.result,
|
|
2026
|
+
message: `${outcome.result.message}${warning}${retention === null ? "" : "\n" + retention}`
|
|
2027
|
+
};
|
|
2028
|
+
}
|
|
2029
|
+
/**
|
|
2030
|
+
* P2-9 (v15): the destructive directory move shared by archive and
|
|
2031
|
+
* restoreFromArchive — rename first, copy+remove fallback when the backend
|
|
2032
|
+
* cannot rename across media (V5-35), with the E-14 rollback when the
|
|
2033
|
+
* fallback's source removal fails. Returns a failure MESSAGE on a failed
|
|
2034
|
+
* move (caller wraps into a structured result) or undefined on success.
|
|
2035
|
+
*/
|
|
2036
|
+
async moveDir(dir, dest) {
|
|
2037
|
+
try {
|
|
2038
|
+
await this.io.rename(dir, dest);
|
|
2039
|
+
return;
|
|
2040
|
+
} catch {
|
|
2041
|
+
if (await this.io.exists(dest)) return "the destination appeared mid-move (concurrent create or restore); refusing to merge — inspect both trees";
|
|
2042
|
+
try {
|
|
2043
|
+
await this.io.copy(dir, dest);
|
|
2044
|
+
} catch (copyError) {
|
|
2045
|
+
return `the move fell back to copy but failed (${copyError instanceof Error ? copyError.message : String(copyError)}); the tree stays where it is`;
|
|
2046
|
+
}
|
|
2047
|
+
try {
|
|
2048
|
+
await this.io.remove(dir);
|
|
2049
|
+
return;
|
|
2050
|
+
} catch (error) {
|
|
2051
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
2052
|
+
try {
|
|
2053
|
+
await this.io.remove(dest);
|
|
2054
|
+
return `复制成功,但源目录删不掉(${reason});已回滚复制出的目录树`;
|
|
2055
|
+
} catch {
|
|
2056
|
+
return `复制成功,但源目录删不掉(${reason}),且复制出的目录树也无法回滚 —— 该目录树现在同时存在于两处;请手动清理`;
|
|
2057
|
+
}
|
|
2058
|
+
}
|
|
2059
|
+
}
|
|
2060
|
+
}
|
|
2061
|
+
/**
|
|
2062
|
+
* P2 (v16): the write-lock probe for the DESTRUCTIVE MOVERS (archive /
|
|
2063
|
+
* restoreFromArchive). A byte-writer mid-flight is the ghost-generator —
|
|
2064
|
+
* after the move its transact commit re-creates `<dir>/…` (mkdir
|
|
2065
|
+
* recursive) and the tree ends half-archived.
|
|
2066
|
+
* G2 S4: the writer-lock probe that used to answer this question is retired — writes go through
|
|
2067
|
+
* the provider's versioned writes, so a writer that raced the move fails its own write loudly
|
|
2068
|
+
* instead of landing on a moved-away path. What REMAINS load-bearing here is the fail-closed
|
|
2069
|
+
* listing rule, which is about the filesystem misbehaving rather than about writers.
|
|
2070
|
+
*/
|
|
2071
|
+
async supportDirsUnlistable(dir) {
|
|
2072
|
+
for (const supportDir of SUPPORT_DIRS) try {
|
|
2073
|
+
await this.io.list(join(dir, supportDir));
|
|
2074
|
+
} catch {
|
|
2075
|
+
return true;
|
|
2076
|
+
}
|
|
2077
|
+
return false;
|
|
2078
|
+
}
|
|
2079
|
+
/** A1-4 (v18): a manifest-declared name is copied with `join(root, name)`;
|
|
2080
|
+
* only a single, non-traversing path component is safe. Dotfiles
|
|
2081
|
+
* (`.usage.json`) stay allowed — sidecars are legitimately dot-prefixed.
|
|
2082
|
+
* P2-4 (v19): a non-string entry (`skills: [123]`) is refused structurally
|
|
2083
|
+
* instead of throwing `name.includes is not a function`. */
|
|
2084
|
+
safeSnapshotEntryName(name) {
|
|
2085
|
+
if (typeof name !== "string") return false;
|
|
2086
|
+
return name !== "" && name !== "." && name !== ".." && !name.includes("/") && !name.includes("\\") && basename(name) === name;
|
|
2087
|
+
}
|
|
2088
|
+
/** Mark merge-absorbed sources archived in the usage sidecar (FR-DATA-07). */
|
|
2089
|
+
async foldArchivedUsage(sources, at) {
|
|
2090
|
+
try {
|
|
2091
|
+
await mutateUsage(this.root, this.io, (map) => {
|
|
2092
|
+
for (const name of sources) {
|
|
2093
|
+
const record = getRecord(map, name);
|
|
2094
|
+
record.state = "archived";
|
|
2095
|
+
record.archived_at = at;
|
|
2096
|
+
}
|
|
2097
|
+
});
|
|
2098
|
+
} catch {}
|
|
2099
|
+
}
|
|
2100
|
+
async archive(rawName, options = {}, origin = this.authority.origin) {
|
|
2101
|
+
const name = rawName.trim();
|
|
2102
|
+
const badName = this.badName(name, { allowReserved: true });
|
|
2103
|
+
if (badName) return {
|
|
2104
|
+
ok: false,
|
|
2105
|
+
message: badName
|
|
2106
|
+
};
|
|
2107
|
+
const dir = this.dirOf(name);
|
|
2108
|
+
const md = await this.io.readText(join(dir, "SKILL.md"));
|
|
2109
|
+
if (md === null) return {
|
|
2110
|
+
ok: false,
|
|
2111
|
+
message: `技能「${name}」不存在。`
|
|
2112
|
+
};
|
|
2113
|
+
const protection = await this.deleteProtection(name, options);
|
|
2114
|
+
if (protection) return {
|
|
2115
|
+
ok: false,
|
|
2116
|
+
message: protection === "pinned" ? `Skill "${name}" is pinned and cannot be archived. Remove the \`.pinned\` marker in its directory, then retry.` : `技能「${name}」受保护(${protection})。`
|
|
2117
|
+
};
|
|
2118
|
+
if (options.absorbedInto) {
|
|
2119
|
+
if (options.absorbedInto.trim() === name) return {
|
|
2120
|
+
ok: false,
|
|
2121
|
+
message: "absorbed_into 不能是正在归档的技能本身(不能吸收到自己)。"
|
|
2122
|
+
};
|
|
2123
|
+
const intoBad = this.badName(options.absorbedInto.trim());
|
|
2124
|
+
if (intoBad) return {
|
|
2125
|
+
ok: false,
|
|
2126
|
+
message: `absorbed_into: ${intoBad}`
|
|
2127
|
+
};
|
|
2128
|
+
if (!await this.io.readText(join(this.dirOf(options.absorbedInto), "SKILL.md"))) return {
|
|
2129
|
+
ok: false,
|
|
2130
|
+
message: `absorbed_into="${options.absorbedInto}" does not exist.`
|
|
2131
|
+
};
|
|
2132
|
+
}
|
|
2133
|
+
const archiveRoot = join(this.root, ".archive");
|
|
2134
|
+
let dest = join(archiveRoot, name.trim());
|
|
2135
|
+
if (await this.io.exists(dest)) {
|
|
2136
|
+
const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[-:T]/g, "").slice(0, 14);
|
|
2137
|
+
dest = join(archiveRoot, `${name.trim()}-${stamp}`);
|
|
2138
|
+
while (await this.io.exists(dest)) dest = join(archiveRoot, `${name.trim()}-${stamp}-${Math.random().toString(36).slice(2, 8)}`);
|
|
2139
|
+
}
|
|
2140
|
+
if (this.io.isSymlink) {
|
|
2141
|
+
if (await this.io.isSymlink(dir) === true) return {
|
|
2142
|
+
ok: false,
|
|
2143
|
+
message: `技能「${name}」是符号链接;拒绝归档。`
|
|
2144
|
+
};
|
|
2145
|
+
}
|
|
2146
|
+
if (await this.supportDirsUnlistable(dir)) return {
|
|
2147
|
+
ok: false,
|
|
2148
|
+
message: `无法检查技能「${name}」是否有写入方(有一个支撑目录列不出来):请重试归档。`
|
|
2149
|
+
};
|
|
2150
|
+
const commitProtection = await this.deleteProtection(name, options);
|
|
2151
|
+
if (commitProtection) return {
|
|
2152
|
+
ok: false,
|
|
2153
|
+
message: commitProtection === "pinned" ? `Skill "${name}" is pinned and cannot be archived. Remove the \`.pinned\` marker in its directory, then retry.` : `技能「${name}」受保护(${commitProtection})。`
|
|
2154
|
+
};
|
|
2155
|
+
const moveFailure = await this.moveDir(dir, dest);
|
|
2156
|
+
if (moveFailure !== void 0) return {
|
|
2157
|
+
ok: false,
|
|
2158
|
+
message: `技能「${name}」归档失败:${moveFailure}。`
|
|
2159
|
+
};
|
|
2160
|
+
const reason = options.reason ?? (options.absorbedInto ? `Consolidated into ${options.absorbedInto}` : "Archived by self-evolution curator");
|
|
2161
|
+
try {
|
|
2162
|
+
await this.io.writeText(join(dest, ".archive-reason"), `${(/* @__PURE__ */ new Date()).toISOString()}: ${reason}\n`);
|
|
2163
|
+
} catch {}
|
|
2164
|
+
try {
|
|
2165
|
+
await this.io.writeText(join(dest, ".archive-name"), `${name}\n`);
|
|
2166
|
+
} catch {}
|
|
2167
|
+
await this.audit(name, "archive", md, null, reason, void 0, options.unitId, options.unitHead, origin);
|
|
2168
|
+
this.notifyMutation({
|
|
2169
|
+
action: "archive",
|
|
2170
|
+
name,
|
|
2171
|
+
archivedPath: dest
|
|
2172
|
+
});
|
|
2173
|
+
return {
|
|
2174
|
+
ok: true,
|
|
2175
|
+
message: `技能「${name}」已归档到 .archive。`,
|
|
2176
|
+
path: dest
|
|
2177
|
+
};
|
|
2178
|
+
}
|
|
2179
|
+
/**
|
|
2180
|
+
* Commit one merge plan as a single multi-skill transaction.
|
|
2181
|
+
*
|
|
2182
|
+
* Existing target: archive every source first, then write the target through the
|
|
2183
|
+
* tree-change kernel. Create target: create the target with its final body first
|
|
2184
|
+
* (so absorbedInto can see it), then archive sources and write support files.
|
|
2185
|
+
* Every failure rolls back what already landed; a rollback failure names the
|
|
2186
|
+
* unrestored skills instead of claiming success.
|
|
2187
|
+
*/
|
|
2188
|
+
/** Expose the store's writer queue so a caller can acquire it BEFORE the home fence. */
|
|
2189
|
+
async runSerial(task) {
|
|
2190
|
+
return await this.serial(task);
|
|
2191
|
+
}
|
|
2192
|
+
async commitMerge(plan, options) {
|
|
2193
|
+
const target = plan.target.trim();
|
|
2194
|
+
const sources = [...new Set(plan.sources.map((name) => name.trim()))].filter((name) => name !== target);
|
|
2195
|
+
if (sources.length === 0) return {
|
|
2196
|
+
ok: false,
|
|
2197
|
+
message: "合并至少需要一个互不相同的来源技能。"
|
|
2198
|
+
};
|
|
2199
|
+
for (const name of [target, ...sources]) {
|
|
2200
|
+
const bad = this.badName(name);
|
|
2201
|
+
if (bad) return {
|
|
2202
|
+
ok: false,
|
|
2203
|
+
message: bad
|
|
2204
|
+
};
|
|
2205
|
+
}
|
|
2206
|
+
if (PROTECTED_BUILTIN_SKILLS.has(target)) return {
|
|
2207
|
+
ok: false,
|
|
2208
|
+
message: `目标技能「${target}」是受保护的内置技能。`
|
|
2209
|
+
};
|
|
2210
|
+
const protectedSource = sources.find((name) => PROTECTED_BUILTIN_SKILLS.has(name));
|
|
2211
|
+
if (protectedSource !== void 0) return {
|
|
2212
|
+
ok: false,
|
|
2213
|
+
message: `来源技能「${protectedSource}」是受保护的内置技能。`
|
|
2214
|
+
};
|
|
2215
|
+
const limits = plan.limits ?? this.limits;
|
|
2216
|
+
const run = async () => {
|
|
2217
|
+
const dir = this.dirOf(target);
|
|
2218
|
+
const targetPath = join(dir, "SKILL.md");
|
|
2219
|
+
if (!plan.targetExists && await this.io.exists(dir)) return {
|
|
2220
|
+
ok: false,
|
|
2221
|
+
message: `目标目录「${target}」已存在但不是技能;拒绝把 SKILL.md 写进同名目录。`
|
|
2222
|
+
};
|
|
2223
|
+
const currentTarget = await this.io.readText(targetPath);
|
|
2224
|
+
if (plan.targetExists !== (currentTarget !== null)) return {
|
|
2225
|
+
ok: false,
|
|
2226
|
+
message: plan.targetExists ? `目标技能「${target}」不存在。` : `目标技能「${target}」已存在。`
|
|
2227
|
+
};
|
|
2228
|
+
if (currentTarget !== plan.expectedTargetBody) return {
|
|
2229
|
+
ok: false,
|
|
2230
|
+
message: `目标技能「${target}」在计划之后被改过;拒绝提交(未写入任何内容)。`
|
|
2231
|
+
};
|
|
2232
|
+
if (plan.targetExists && !await this.isManaged(target)) return {
|
|
2233
|
+
ok: false,
|
|
2234
|
+
message: `目标技能「${target}」不是 family-managed;拒绝提交。`
|
|
2235
|
+
};
|
|
2236
|
+
if (await this.io.exists(markerPath(dir, "pinned"))) return {
|
|
2237
|
+
ok: false,
|
|
2238
|
+
message: `目标技能「${target}」已被固定;拒绝提交。`
|
|
2239
|
+
};
|
|
2240
|
+
const targetProtection = await this.writeProtection(target, plan.origin);
|
|
2241
|
+
if (targetProtection) return {
|
|
2242
|
+
ok: false,
|
|
2243
|
+
message: `技能「${target}」受保护(${targetProtection})。`
|
|
2244
|
+
};
|
|
2245
|
+
const expectedSources = new Map(plan.expectedSourceBodies.map((entry) => [entry.name.trim(), entry.body]));
|
|
2246
|
+
const sourceBodies = /* @__PURE__ */ new Map();
|
|
2247
|
+
for (const source of sources) {
|
|
2248
|
+
const protection = await this.deleteProtection(source);
|
|
2249
|
+
if (protection) return {
|
|
2250
|
+
ok: false,
|
|
2251
|
+
message: `技能「${source}」受保护(${protection})。`
|
|
2252
|
+
};
|
|
2253
|
+
const body = await this.io.readText(join(this.dirOf(source), "SKILL.md"));
|
|
2254
|
+
if (body === null) return {
|
|
2255
|
+
ok: false,
|
|
2256
|
+
message: `来源技能「${source}」不存在。`
|
|
2257
|
+
};
|
|
2258
|
+
const expected = expectedSources.get(source);
|
|
2259
|
+
if (expected === void 0) return {
|
|
2260
|
+
ok: false,
|
|
2261
|
+
message: `来源技能「${source}」缺少计划字节;拒绝提交。`
|
|
2262
|
+
};
|
|
2263
|
+
if (body !== expected) return {
|
|
2264
|
+
ok: false,
|
|
2265
|
+
message: `来源技能「${source}」在计划之后被改过;拒绝提交(未写入任何内容)。`
|
|
2266
|
+
};
|
|
2267
|
+
sourceBodies.set(source, body);
|
|
2268
|
+
}
|
|
2269
|
+
if (plan.targetRevision !== void 0) {
|
|
2270
|
+
const liveTargetRevision = await this.revisionAnchor(target);
|
|
2271
|
+
if (!sameRevisionAnchor(plan.targetRevision, liveTargetRevision)) return {
|
|
2272
|
+
ok: false,
|
|
2273
|
+
code: "target-changed",
|
|
2274
|
+
message: `目标技能「${target}」的内容在决策之后被改过;拒绝提交(未写入任何内容)。`
|
|
2275
|
+
};
|
|
2276
|
+
}
|
|
2277
|
+
if (plan.sourceRevisions !== void 0) for (const [name, expected] of Object.entries(plan.sourceRevisions)) {
|
|
2278
|
+
if (!sources.includes(name)) continue;
|
|
2279
|
+
if (!sameRevisionAnchor(expected, await this.revisionAnchor(name))) return {
|
|
2280
|
+
ok: false,
|
|
2281
|
+
code: "source-changed",
|
|
2282
|
+
message: `来源技能「${name}」的内容在决策之后被改过;拒绝提交(未写入任何内容)。`
|
|
2283
|
+
};
|
|
2284
|
+
}
|
|
2285
|
+
if (plan.supportDigest !== void 0) {
|
|
2286
|
+
const fingerprints = [];
|
|
2287
|
+
for (const name of [target, ...sources]) {
|
|
2288
|
+
const fingerprint = await this.revisionFingerprint(name);
|
|
2289
|
+
if (fingerprint !== null) fingerprints.push(fingerprint);
|
|
2290
|
+
}
|
|
2291
|
+
if (revisionSupportDigest(fingerprints) !== plan.supportDigest) return {
|
|
2292
|
+
ok: false,
|
|
2293
|
+
code: "support-changed",
|
|
2294
|
+
message: "参与合并的技能支撑文件在决策之后被改过;拒绝提交(未写入任何内容)。"
|
|
2295
|
+
};
|
|
2296
|
+
}
|
|
2297
|
+
const validation = validateFrontmatter(plan.body, target, limits);
|
|
2298
|
+
if (validation) return {
|
|
2299
|
+
ok: false,
|
|
2300
|
+
message: validation
|
|
2301
|
+
};
|
|
2302
|
+
const supportPaths = /* @__PURE__ */ new Set();
|
|
2303
|
+
const supportPrevious = /* @__PURE__ */ new Map();
|
|
2304
|
+
for (const file of plan.supportFiles) {
|
|
2305
|
+
const badPath = validateSupportPath(file.path);
|
|
2306
|
+
if (badPath) return {
|
|
2307
|
+
ok: false,
|
|
2308
|
+
message: badPath
|
|
2309
|
+
};
|
|
2310
|
+
if (supportPaths.has(file.path)) return {
|
|
2311
|
+
ok: false,
|
|
2312
|
+
message: `支撑文件重复:${file.path}`
|
|
2313
|
+
};
|
|
2314
|
+
supportPaths.add(file.path);
|
|
2315
|
+
if (Buffer.byteLength(file.content, "utf8") > limits.maxSkillFileBytes) return {
|
|
2316
|
+
ok: false,
|
|
2317
|
+
message: `支撑文件超过 ${limits.maxSkillFileBytes} 字节:${file.path}`
|
|
2318
|
+
};
|
|
2319
|
+
const threat = this.contentThreatBlock(file.content);
|
|
2320
|
+
if (threat) return {
|
|
2321
|
+
ok: false,
|
|
2322
|
+
message: threat
|
|
2323
|
+
};
|
|
2324
|
+
const previous = await this.io.readText(join(dir, ...file.path.replace(/\\/g, "/").split("/").filter(Boolean)));
|
|
2325
|
+
supportPrevious.set(file.path, previous);
|
|
2326
|
+
}
|
|
2327
|
+
for (const ref of supportRefs(plan.body)) {
|
|
2328
|
+
if (supportPaths.has(ref)) continue;
|
|
2329
|
+
if (!(plan.targetExists ? await this.io.exists(join(dir, ...ref.replace(/\\/g, "/").split("/").filter(Boolean))) : false)) return {
|
|
2330
|
+
ok: false,
|
|
2331
|
+
message: `正文引用了未提供的支撑文件「${ref}」;拒绝提交。`
|
|
2332
|
+
};
|
|
2333
|
+
}
|
|
2334
|
+
const unitId = plan.unitId ?? "u-" + Date.now().toString(36) + "-" + (nextUnitSeq += 1).toString(36);
|
|
2335
|
+
const supportMoves = plan.supportFiles.map((file) => {
|
|
2336
|
+
const previous = supportPrevious.get(file.path) ?? null;
|
|
2337
|
+
return {
|
|
2338
|
+
path: file.path,
|
|
2339
|
+
kind: previous === null ? "created" : "moved",
|
|
2340
|
+
to: file.path,
|
|
2341
|
+
...previous === null ? {} : { beforeRef: contentHash(previous) },
|
|
2342
|
+
afterRef: contentHash(file.content)
|
|
2343
|
+
};
|
|
2344
|
+
});
|
|
2345
|
+
const unitHead = {
|
|
2346
|
+
...plan.runId === void 0 ? {} : { runId: plan.runId },
|
|
2347
|
+
baseline: true,
|
|
2348
|
+
moves: supportMoves,
|
|
2349
|
+
sources: [{ skill: target }, ...sources.map((source) => ({ skill: source }))]
|
|
2350
|
+
};
|
|
2351
|
+
const archived = [];
|
|
2352
|
+
const rollbackSources = async () => {
|
|
2353
|
+
const stuck = [];
|
|
2354
|
+
for (const source of [...archived].reverse()) try {
|
|
2355
|
+
if (!(await this.restoreFromArchive(source, plan.origin)).ok) stuck.push(source);
|
|
2356
|
+
} catch {
|
|
2357
|
+
stuck.push(source);
|
|
2358
|
+
}
|
|
2359
|
+
return stuck;
|
|
2360
|
+
};
|
|
2361
|
+
const rollbackMessage = (reason, stuck) => ({
|
|
2362
|
+
ok: false,
|
|
2363
|
+
message: stuck.length === 0 ? `合并失败,已回滚:${reason}` : `合并失败(${reason});已回滚,但以下未回滚:${stuck.join(", ")}:它们仍在 .archive 里,请用 /evolution skill restore 恢复。`
|
|
2364
|
+
});
|
|
2365
|
+
const rollbackTarget = async () => {
|
|
2366
|
+
const stuck = [];
|
|
2367
|
+
const support = plan.supportFiles.map((file) => ({
|
|
2368
|
+
target: join(dir, ...file.path.replace(/\\/g, "/").split("/").filter(Boolean)),
|
|
2369
|
+
content: supportPrevious.get(file.path) ?? null,
|
|
2370
|
+
previous: file.content
|
|
2371
|
+
}));
|
|
2372
|
+
const writes = [{
|
|
2373
|
+
target: targetPath,
|
|
2374
|
+
content: plan.expectedTargetBody ?? "",
|
|
2375
|
+
expected: plan.body.trimEnd() + "\n"
|
|
2376
|
+
}, ...support.map((file) => ({
|
|
2377
|
+
target: file.target,
|
|
2378
|
+
content: file.content ?? "",
|
|
2379
|
+
expected: file.previous
|
|
2380
|
+
}))];
|
|
2381
|
+
try {
|
|
2382
|
+
if (!(await this.applyTreeChange({
|
|
2383
|
+
name: target,
|
|
2384
|
+
origin: plan.origin,
|
|
2385
|
+
protection: "write",
|
|
2386
|
+
nested: plan.nested === true,
|
|
2387
|
+
writes,
|
|
2388
|
+
auditAction: "merge-rollback",
|
|
2389
|
+
auditSummary: "merge rollback: restore target snapshot",
|
|
2390
|
+
eventAction: "merge-rollback",
|
|
2391
|
+
unitId,
|
|
2392
|
+
unitHead
|
|
2393
|
+
})).ok) stuck.push(target);
|
|
2394
|
+
} catch {
|
|
2395
|
+
stuck.push(target);
|
|
2396
|
+
}
|
|
2397
|
+
return stuck;
|
|
2398
|
+
};
|
|
2399
|
+
if (plan.targetExists) {
|
|
2400
|
+
for (const source of sources) if (await this.io.readText(join(this.dirOf(source), "SKILL.md")) !== sourceBodies.get(source)) return rollbackMessage(`来源技能「${source}」在归档前被改过`, []);
|
|
2401
|
+
const writes = [{
|
|
2402
|
+
target: targetPath,
|
|
2403
|
+
content: plan.body.trimEnd() + "\n",
|
|
2404
|
+
expected: plan.expectedTargetBody
|
|
2405
|
+
}, ...plan.supportFiles.map((file) => ({
|
|
2406
|
+
target: join(dir, ...file.path.replace(/\\/g, "/").split("/").filter(Boolean)),
|
|
2407
|
+
content: file.content,
|
|
2408
|
+
expected: supportPrevious.get(file.path) ?? null
|
|
2409
|
+
}))];
|
|
2410
|
+
await plan.onPhase?.("target-pending");
|
|
2411
|
+
if (plan.assertFence !== void 0 && !await plan.assertFence()) return {
|
|
2412
|
+
ok: false,
|
|
2413
|
+
message: "tree fence lost before target write"
|
|
2414
|
+
};
|
|
2415
|
+
const result = await this.applyTreeChange({
|
|
2416
|
+
name: target,
|
|
2417
|
+
origin: plan.origin,
|
|
2418
|
+
protection: "write",
|
|
2419
|
+
nested: plan.nested === true,
|
|
2420
|
+
writes,
|
|
2421
|
+
auditAction: "merge",
|
|
2422
|
+
auditSummary: plan.summary,
|
|
2423
|
+
eventAction: "merge",
|
|
2424
|
+
unitId,
|
|
2425
|
+
unitHead
|
|
2426
|
+
});
|
|
2427
|
+
if (!result.ok) return rollbackMessage(result.message, []);
|
|
2428
|
+
await plan.onPhase?.("target-applied");
|
|
2429
|
+
await plan.onPhase?.("target-written");
|
|
2430
|
+
if (plan.signal?.aborted) return rollbackMessage("cancelled before sources archived", await rollbackTarget());
|
|
2431
|
+
for (const source of sources) {
|
|
2432
|
+
if (plan.signal?.aborted) {
|
|
2433
|
+
const stuck = await rollbackSources();
|
|
2434
|
+
stuck.push(...await rollbackTarget());
|
|
2435
|
+
return rollbackMessage("cancelled before next source archive", stuck);
|
|
2436
|
+
}
|
|
2437
|
+
if (await this.io.readText(join(this.dirOf(source), "SKILL.md")) !== sourceBodies.get(source)) {
|
|
2438
|
+
const stuck = await rollbackSources();
|
|
2439
|
+
stuck.push(...await rollbackTarget());
|
|
2440
|
+
return rollbackMessage(`来源技能「${source}」在归档前被改过`, stuck);
|
|
2441
|
+
}
|
|
2442
|
+
if (plan.assertFence !== void 0 && !await plan.assertFence()) return {
|
|
2443
|
+
ok: false,
|
|
2444
|
+
message: "tree fence lost before source archive; recovery required"
|
|
2445
|
+
};
|
|
2446
|
+
await plan.onPhase?.("source-archiving", { source });
|
|
2447
|
+
const archivedResult = await this.archive(source, {
|
|
2448
|
+
absorbedInto: target,
|
|
2449
|
+
unitId,
|
|
2450
|
+
unitHead: { skill: target },
|
|
2451
|
+
reason: `Merged into ${target}`
|
|
2452
|
+
}, plan.origin);
|
|
2453
|
+
if (!archivedResult.ok) {
|
|
2454
|
+
const stuck = await rollbackSources();
|
|
2455
|
+
stuck.push(...await rollbackTarget());
|
|
2456
|
+
return rollbackMessage(archivedResult.message, stuck);
|
|
2457
|
+
}
|
|
2458
|
+
archived.push(source);
|
|
2459
|
+
}
|
|
2460
|
+
await plan.onPhase?.("sources-archived");
|
|
2461
|
+
await this.foldArchivedUsage(sources, (/* @__PURE__ */ new Date()).toISOString());
|
|
2462
|
+
await plan.onPhase?.("unit-written");
|
|
2463
|
+
return {
|
|
2464
|
+
ok: true,
|
|
2465
|
+
message: `已把 ${sources.join(", ")} 合并进「${target}」。`,
|
|
2466
|
+
unitId,
|
|
2467
|
+
targetPath: dir,
|
|
2468
|
+
archived,
|
|
2469
|
+
mutations: 1 + sources.length
|
|
2470
|
+
};
|
|
2471
|
+
}
|
|
2472
|
+
await plan.onPhase?.("target-pending");
|
|
2473
|
+
if (plan.assertFence !== void 0 && !await plan.assertFence()) return {
|
|
2474
|
+
ok: false,
|
|
2475
|
+
message: "tree fence lost before target write"
|
|
2476
|
+
};
|
|
2477
|
+
const created = await this.createCore(target, plan.body, plan.origin, {
|
|
2478
|
+
unitId,
|
|
2479
|
+
unitHead,
|
|
2480
|
+
managed: true
|
|
2481
|
+
});
|
|
2482
|
+
if (!created.ok) return {
|
|
2483
|
+
ok: false,
|
|
2484
|
+
message: created.message
|
|
2485
|
+
};
|
|
2486
|
+
await plan.onPhase?.("target-applied");
|
|
2487
|
+
await plan.onPhase?.("target-written");
|
|
2488
|
+
if (plan.signal?.aborted) return rollbackMessage("cancelled before sources archived", (await this.archive(target, { reason: "merge cancelled" }, plan.origin)).ok ? [] : [target]);
|
|
2489
|
+
for (const source of sources) {
|
|
2490
|
+
if (plan.signal?.aborted) {
|
|
2491
|
+
const stuck = await rollbackSources();
|
|
2492
|
+
if (!(await this.archive(target, { reason: "merge cancelled" }, plan.origin)).ok) stuck.push(target);
|
|
2493
|
+
return rollbackMessage("cancelled before next source archive", stuck);
|
|
2494
|
+
}
|
|
2495
|
+
if (await this.io.readText(join(this.dirOf(source), "SKILL.md")) !== sourceBodies.get(source)) {
|
|
2496
|
+
const stuck = await rollbackSources();
|
|
2497
|
+
if (!(await this.archive(target, { reason: "merge rolled back" }, plan.origin)).ok) stuck.push(target);
|
|
2498
|
+
return rollbackMessage(`来源技能「${source}」在归档前被改过`, stuck);
|
|
2499
|
+
}
|
|
2500
|
+
if (plan.assertFence !== void 0 && !await plan.assertFence()) return {
|
|
2501
|
+
ok: false,
|
|
2502
|
+
message: "tree fence lost before source archive; recovery required"
|
|
2503
|
+
};
|
|
2504
|
+
await plan.onPhase?.("source-archiving", { source });
|
|
2505
|
+
const result = await this.archive(source, {
|
|
2506
|
+
absorbedInto: target,
|
|
2507
|
+
unitId,
|
|
2508
|
+
unitHead: { skill: target },
|
|
2509
|
+
reason: `Merged into ${target}`
|
|
2510
|
+
}, plan.origin);
|
|
2511
|
+
if (!result.ok) {
|
|
2512
|
+
const stuck = await rollbackSources();
|
|
2513
|
+
if (!(await this.archive(target, { reason: "merge rolled back" }, plan.origin)).ok) stuck.push(target);
|
|
2514
|
+
return rollbackMessage(result.message, stuck);
|
|
2515
|
+
}
|
|
2516
|
+
archived.push(source);
|
|
2517
|
+
}
|
|
2518
|
+
if (plan.supportFiles.length > 0) {
|
|
2519
|
+
await plan.onPhase?.("support-pending");
|
|
2520
|
+
if (plan.assertFence !== void 0 && !await plan.assertFence()) return {
|
|
2521
|
+
ok: false,
|
|
2522
|
+
message: "tree fence lost before support write; recovery required"
|
|
2523
|
+
};
|
|
2524
|
+
const writes = plan.supportFiles.map((file) => ({
|
|
2525
|
+
target: join(dir, ...file.path.replace(/\\/g, "/").split("/").filter(Boolean)),
|
|
2526
|
+
content: file.content,
|
|
2527
|
+
expected: supportPrevious.get(file.path) ?? null
|
|
2528
|
+
}));
|
|
2529
|
+
const result = await this.applyTreeChange({
|
|
2530
|
+
name: target,
|
|
2531
|
+
origin: plan.origin,
|
|
2532
|
+
protection: "write",
|
|
2533
|
+
nested: plan.nested === true,
|
|
2534
|
+
writes,
|
|
2535
|
+
auditAction: "merge",
|
|
2536
|
+
auditSummary: plan.summary,
|
|
2537
|
+
eventAction: "merge",
|
|
2538
|
+
unitId,
|
|
2539
|
+
unitHead
|
|
2540
|
+
});
|
|
2541
|
+
if (!result.ok) {
|
|
2542
|
+
const stuck = await rollbackSources();
|
|
2543
|
+
if (!(await this.archive(target, { reason: "merge rolled back" }, plan.origin)).ok) stuck.push(target);
|
|
2544
|
+
return rollbackMessage(result.message, stuck);
|
|
2545
|
+
}
|
|
2546
|
+
}
|
|
2547
|
+
await this.foldArchivedUsage(sources, (/* @__PURE__ */ new Date()).toISOString());
|
|
2548
|
+
await plan.onPhase?.("sources-archived");
|
|
2549
|
+
await plan.onPhase?.("unit-written");
|
|
2550
|
+
return {
|
|
2551
|
+
ok: true,
|
|
2552
|
+
message: `已把 ${sources.join(", ")} 合并进「${target}」。`,
|
|
2553
|
+
unitId,
|
|
2554
|
+
targetPath: dir,
|
|
2555
|
+
archived,
|
|
2556
|
+
mutations: 1 + sources.length
|
|
2557
|
+
};
|
|
2558
|
+
};
|
|
2559
|
+
return options?.serialized === true ? await run() : await this.serial(run);
|
|
2560
|
+
}
|
|
2561
|
+
/**
|
|
2562
|
+
* V2 (design §16.7): what an apply-mode consolidation would do for ONE source,
|
|
2563
|
+
* computed BEFORE any side effect. `blocked` means behaviour is exactly the
|
|
2564
|
+
* plan-mode refusal (with the reason named); `apply` carries the rewritten body
|
|
2565
|
+
* and the support files that must be copied into the target.
|
|
2566
|
+
* @param source - the moving skill's name.
|
|
2567
|
+
* @param targetName - the destination skill's name.
|
|
2568
|
+
* @param body - the moving body (frontmatter stripped).
|
|
2569
|
+
* @returns the decision plus the note to append to a refusal.
|
|
2570
|
+
*/
|
|
2571
|
+
async planSourceRehoming(source, targetName, body, extraTargetFiles = []) {
|
|
2572
|
+
const policy = this.limits.referenceRewrite ?? "plan";
|
|
2573
|
+
if (policy === "off") return {
|
|
2574
|
+
kind: "blocked",
|
|
2575
|
+
note: ""
|
|
2576
|
+
};
|
|
2577
|
+
const sourceFiles = await this.listSupportFiles(source);
|
|
2578
|
+
const targetFiles = await this.listSupportFiles(targetName);
|
|
2579
|
+
if (!isPresent(sourceFiles) || !isPresent(targetFiles)) return {
|
|
2580
|
+
kind: "blocked",
|
|
2581
|
+
note: " plan: unavailable (support-file listing unknown)"
|
|
2582
|
+
};
|
|
2583
|
+
const { moves, collisions } = planRehoming(sourceFiles.value, [...targetFiles.value, ...extraTargetFiles], source);
|
|
2584
|
+
const plan = planReferenceRewrite({
|
|
2585
|
+
content: body,
|
|
2586
|
+
files: sourceFiles.value,
|
|
2587
|
+
moves,
|
|
2588
|
+
targetFiles: [
|
|
2589
|
+
...targetFiles.value,
|
|
2590
|
+
...extraTargetFiles,
|
|
2591
|
+
...moves.map((move) => move.to)
|
|
2592
|
+
]
|
|
2593
|
+
});
|
|
2594
|
+
const described = ` ${describeReferenceRewrite(plan)}${collisionsNote(collisions)}`;
|
|
2595
|
+
if (policy === "plan") return {
|
|
2596
|
+
kind: "blocked",
|
|
2597
|
+
note: described
|
|
2598
|
+
};
|
|
2599
|
+
if (plan.residualDangling.length > 0 || plan.unresolved.length > 0) return {
|
|
2600
|
+
kind: "blocked",
|
|
2601
|
+
note: `${described} (cannot apply)`
|
|
2602
|
+
};
|
|
2603
|
+
const files = [];
|
|
2604
|
+
for (const move of plan.moves) {
|
|
2605
|
+
const bytes = await this.io.readText(join(this.dirOf(source), ...move.from.split("/")));
|
|
2606
|
+
if (bytes === null) return {
|
|
2607
|
+
kind: "blocked",
|
|
2608
|
+
note: ` plan: unavailable (cannot read ${move.from})`
|
|
2609
|
+
};
|
|
2610
|
+
files.push({
|
|
2611
|
+
from: move.from,
|
|
2612
|
+
to: move.to,
|
|
2613
|
+
content: bytes
|
|
2614
|
+
});
|
|
2615
|
+
}
|
|
2616
|
+
return {
|
|
2617
|
+
kind: "apply",
|
|
2618
|
+
note: described,
|
|
2619
|
+
rewritten: applyReferenceRewrite(body, plan.edits),
|
|
2620
|
+
files
|
|
2621
|
+
};
|
|
2622
|
+
}
|
|
2623
|
+
/**
|
|
2624
|
+
* Merge the bodies of `sources` into `target` and archive the sources with
|
|
2625
|
+
* an absorbed-into marker. Hermes-style consolidation: overlapping skills
|
|
2626
|
+
* collapse into one, and the originals stay recoverable under `.archive/`.
|
|
2627
|
+
*
|
|
2628
|
+
* `mode:'append'` (default) appends each source body to the target. The
|
|
2629
|
+
* target write goes through the tree-change kernel (009) — byte-level
|
|
2630
|
+
* rollback, audit and the mutation event are kernel-owned. Package-integrity
|
|
2631
|
+
* (009-I): append-mode consolidation REFUSES a source whose directory has
|
|
2632
|
+
* support files or whose body carries support-directory links — an append
|
|
2633
|
+
* would leave those references pointing at an archived package (dangling);
|
|
2634
|
+
* the refusal message directs to the reference mode / whole-package archive.
|
|
2635
|
+
*
|
|
2636
|
+
* `mode:'reference'` writes each source's body (frontmatter stripped) into
|
|
2637
|
+
* `target/references/<source>.md` and archives the source — the demote path
|
|
2638
|
+
* (009-II). A source body with support-directory links is refused there too
|
|
2639
|
+
* (the references file would carry links whose files were archived).
|
|
2640
|
+
*
|
|
2641
|
+
* V2 (design §16.7) lifts that refusal when `referenceRewrite:'apply'` and the
|
|
2642
|
+
* plan proves the move is safe: the support files the body NEEDS are copied into
|
|
2643
|
+
* the target under their own paths (renamed only on a collision) and the body's
|
|
2644
|
+
* references are rewritten to match, in the same commit. Anything the plan
|
|
2645
|
+
* cannot place — a cited file the source no longer has, an unreadable listing —
|
|
2646
|
+
* still refuses, and the refusal names it. The archived source keeps whatever
|
|
2647
|
+
* the body did not need.
|
|
2648
|
+
*/
|
|
2649
|
+
async consolidate(target, sources, origin = this.authority.origin, options = {}) {
|
|
2650
|
+
const targetName = target.trim();
|
|
2651
|
+
const normalizedSources = [...new Set(sources.map((name) => name.trim()))].filter((name) => name !== targetName);
|
|
2652
|
+
const mode = options.mode ?? "append";
|
|
2653
|
+
if (normalizedSources.length === 0) return {
|
|
2654
|
+
ok: false,
|
|
2655
|
+
message: "合并至少需要一个互不相同的来源技能。"
|
|
2656
|
+
};
|
|
2657
|
+
for (const name of [targetName, ...normalizedSources]) {
|
|
2658
|
+
const bad = this.badName(name);
|
|
2659
|
+
if (bad) return {
|
|
2660
|
+
ok: false,
|
|
2661
|
+
message: bad
|
|
2662
|
+
};
|
|
2663
|
+
}
|
|
2664
|
+
const targetDir = this.dirOf(targetName);
|
|
2665
|
+
const targetProtection = await this.writeProtection(targetName, origin);
|
|
2666
|
+
if (targetProtection) return {
|
|
2667
|
+
ok: false,
|
|
2668
|
+
message: `技能「${targetName}」受保护(${targetProtection})。`
|
|
2669
|
+
};
|
|
2670
|
+
return await this.serial(async () => {
|
|
2671
|
+
const referenceWrites = [];
|
|
2672
|
+
const rehomed = [];
|
|
2673
|
+
const demotedPointers = [];
|
|
2674
|
+
const parts = [];
|
|
2675
|
+
const plannedSourceBytes = /* @__PURE__ */ new Map();
|
|
2676
|
+
if (mode === "append") for (const source of normalizedSources) {
|
|
2677
|
+
const protection = await this.deleteProtection(source);
|
|
2678
|
+
if (protection) return {
|
|
2679
|
+
ok: false,
|
|
2680
|
+
message: `技能「${source}」受保护(${protection})。`
|
|
2681
|
+
};
|
|
2682
|
+
const sourceMd = await this.io.readText(join(this.dirOf(source), "SKILL.md"));
|
|
2683
|
+
if (!sourceMd) return {
|
|
2684
|
+
ok: false,
|
|
2685
|
+
message: `技能「${source}」不存在。`
|
|
2686
|
+
};
|
|
2687
|
+
const parsed = parseFrontmatter(sourceMd);
|
|
2688
|
+
if (!parsed) return {
|
|
2689
|
+
ok: false,
|
|
2690
|
+
message: `技能「${source}」没有有效的 frontmatter;拒绝合并。`
|
|
2691
|
+
};
|
|
2692
|
+
const carriesSupport = await this.countSupportDirs(source) > 0;
|
|
2693
|
+
const parsedRefs = supportRefs(parsed.body);
|
|
2694
|
+
const rawRefs = [...parsed.body.matchAll(/(?:references|scripts|templates|assets)\/[A-Za-z0-9._/-]+/g)].map((match) => match[0]);
|
|
2695
|
+
const refs = parsedRefs.length > 0 ? parsedRefs : rawRefs;
|
|
2696
|
+
let appendedBody = parsed.body;
|
|
2697
|
+
if (carriesSupport || refs.length > 0) {
|
|
2698
|
+
const decision = await this.planSourceRehoming(source, targetName, parsed.body, rehomed.map((file) => file.to));
|
|
2699
|
+
if (decision.kind === "blocked") return {
|
|
2700
|
+
ok: false,
|
|
2701
|
+
message: `合并被拒绝:${carriesSupport ? `source "${source}" carries support files` : `source "${source}" body references support files (${refs.join(", ")})`} 会被落下。请改用 mode:'reference',或直接归档整个包。${decision.note}`
|
|
2702
|
+
};
|
|
2703
|
+
rehomed.push(...decision.files);
|
|
2704
|
+
appendedBody = decision.rewritten;
|
|
2705
|
+
}
|
|
2706
|
+
parts.push(`\n<!-- consolidated from ${source} at ${(/* @__PURE__ */ new Date()).toISOString()} -->\n${appendedBody.trim()}`);
|
|
2707
|
+
plannedSourceBytes.set(source, sourceMd);
|
|
2708
|
+
}
|
|
2709
|
+
else for (const source of normalizedSources) {
|
|
2710
|
+
const protection = await this.deleteProtection(source);
|
|
2711
|
+
if (protection) return {
|
|
2712
|
+
ok: false,
|
|
2713
|
+
message: `技能「${source}」受保护(${protection})。`
|
|
2714
|
+
};
|
|
2715
|
+
const sourceMd = await this.io.readText(join(this.dirOf(source), "SKILL.md"));
|
|
2716
|
+
if (!sourceMd) return {
|
|
2717
|
+
ok: false,
|
|
2718
|
+
message: `技能「${source}」不存在。`
|
|
2719
|
+
};
|
|
2720
|
+
const parsed = parseFrontmatter(sourceMd);
|
|
2721
|
+
if (!parsed) return {
|
|
2722
|
+
ok: false,
|
|
2723
|
+
message: `技能「${source}」没有有效的 frontmatter;拒绝降级。`
|
|
2724
|
+
};
|
|
2725
|
+
const refs = supportRefs(parsed.body);
|
|
2726
|
+
let demotedBody = parsed.body;
|
|
2727
|
+
if (refs.length > 0) {
|
|
2728
|
+
const decision = await this.planSourceRehoming(source, targetName, parsed.body, rehomed.map((file) => file.to));
|
|
2729
|
+
if (decision.kind === "blocked") return {
|
|
2730
|
+
ok: false,
|
|
2731
|
+
message: `合并被拒绝:来源技能「${source}」的正文引用了会被落下的支撑文件(${refs.join(", ")}):请改为归档整个包。${decision.note}`
|
|
2732
|
+
};
|
|
2733
|
+
rehomed.push(...decision.files);
|
|
2734
|
+
demotedBody = decision.rewritten;
|
|
2735
|
+
}
|
|
2736
|
+
const target = join(targetDir, "references", `${source}.md`);
|
|
2737
|
+
referenceWrites.push({
|
|
2738
|
+
target,
|
|
2739
|
+
content: `<!-- demoted from ${source} at ${(/* @__PURE__ */ new Date()).toISOString()} -->\n${demotedBody.trim()}\n`
|
|
2740
|
+
});
|
|
2741
|
+
demotedPointers.push(pointerBlock(`references/${source}.md`, demotedBody));
|
|
2742
|
+
plannedSourceBytes.set(source, sourceMd);
|
|
2743
|
+
}
|
|
2744
|
+
const archived = [];
|
|
2745
|
+
try {
|
|
2746
|
+
if (!await this.io.readText(join(targetDir, "SKILL.md"))) return {
|
|
2747
|
+
ok: false,
|
|
2748
|
+
message: `技能「${targetName}」不存在。`
|
|
2749
|
+
};
|
|
2750
|
+
for (const source of normalizedSources) {
|
|
2751
|
+
if (plannedSourceBytes.has(source)) {
|
|
2752
|
+
if (await this.io.readText(join(this.dirOf(source), "SKILL.md")) !== plannedSourceBytes.get(source)) throw new Error(`Consolidation aborted: source "${source}" changed while the consolidation ran (its planned bytes are no longer current).`);
|
|
2753
|
+
}
|
|
2754
|
+
const result = await this.archive(source, { absorbedInto: targetName });
|
|
2755
|
+
if (!result.ok) throw new Error(result.message);
|
|
2756
|
+
archived.push(source);
|
|
2757
|
+
}
|
|
2758
|
+
const freshTargetMd = await this.io.readText(join(targetDir, "SKILL.md"));
|
|
2759
|
+
if (!freshTargetMd) throw new Error(`target "${targetName}" disappeared mid-consolidate`);
|
|
2760
|
+
const writes = [];
|
|
2761
|
+
for (const reference of referenceWrites) {
|
|
2762
|
+
const previous = await this.readForCas(reference.target);
|
|
2763
|
+
const base = previous?.trimEnd() ?? "";
|
|
2764
|
+
writes.push({
|
|
2765
|
+
target: reference.target,
|
|
2766
|
+
content: base === "" ? reference.content : `${base}\n\n${reference.content}`,
|
|
2767
|
+
expected: previous
|
|
2768
|
+
});
|
|
2769
|
+
}
|
|
2770
|
+
for (const file of rehomed) {
|
|
2771
|
+
const target = join(targetDir, ...file.to.split("/"));
|
|
2772
|
+
const previous = await this.readForCas(target);
|
|
2773
|
+
writes.push({
|
|
2774
|
+
target,
|
|
2775
|
+
content: file.content,
|
|
2776
|
+
expected: previous
|
|
2777
|
+
});
|
|
2778
|
+
}
|
|
2779
|
+
if (mode === "append") {
|
|
2780
|
+
const merged = freshTargetMd.trimEnd() + parts.join("\n") + "\n";
|
|
2781
|
+
const validation = validateFrontmatter(merged, targetName, this.limits);
|
|
2782
|
+
if (validation) throw new Error(`merge validation failed: ${validation}`);
|
|
2783
|
+
writes.push({
|
|
2784
|
+
target: join(targetDir, "SKILL.md"),
|
|
2785
|
+
content: merged,
|
|
2786
|
+
expected: freshTargetMd
|
|
2787
|
+
});
|
|
2788
|
+
} else {
|
|
2789
|
+
const pointerLines = demotedPointers.map((lines) => `\n${lines.join("\n")}`).join("");
|
|
2790
|
+
const extended = freshTargetMd.trimEnd() + pointerLines + "\n";
|
|
2791
|
+
const validation = validateFrontmatter(extended, targetName, this.limits);
|
|
2792
|
+
if (validation) throw new Error(`merge validation failed: ${validation}`);
|
|
2793
|
+
writes.push({
|
|
2794
|
+
target: join(targetDir, "SKILL.md"),
|
|
2795
|
+
content: extended,
|
|
2796
|
+
expected: freshTargetMd
|
|
2797
|
+
});
|
|
2798
|
+
}
|
|
2799
|
+
const result = await this.applyTreeChange({
|
|
2800
|
+
name: targetName,
|
|
2801
|
+
origin,
|
|
2802
|
+
protection: "write",
|
|
2803
|
+
writes,
|
|
2804
|
+
auditAction: "consolidate",
|
|
2805
|
+
auditSummary: `consolidated ${normalizedSources.join(", ")} (${mode}) into ${targetName}` + (rehomed.length === 0 ? "" : `; re-homed ${rehomed.map((file) => `${file.from}->${file.to}`).join(", ")}`),
|
|
2806
|
+
eventAction: "consolidate"
|
|
2807
|
+
});
|
|
2808
|
+
if (!result.ok) throw new Error(result.message);
|
|
2809
|
+
return {
|
|
2810
|
+
ok: true,
|
|
2811
|
+
message: `已把 ${normalizedSources.join(", ")} 合并进「${targetName}」。`,
|
|
2812
|
+
path: targetDir
|
|
2813
|
+
};
|
|
2814
|
+
} catch (error) {
|
|
2815
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
2816
|
+
const failedRestores = [];
|
|
2817
|
+
for (const source of archived.reverse()) try {
|
|
2818
|
+
if (!(await this.restoreFromArchive(source)).ok) failedRestores.push(source);
|
|
2819
|
+
} catch {
|
|
2820
|
+
failedRestores.push(source);
|
|
2821
|
+
}
|
|
2822
|
+
if (failedRestores.length > 0) return {
|
|
2823
|
+
ok: false,
|
|
2824
|
+
message: `合并失败(${reason});已回滚,但以下未回滚:${failedRestores.join(", ")}:它们仍在 .archive 里,请用 /evolution skill restore 恢复。`
|
|
2825
|
+
};
|
|
2826
|
+
return {
|
|
2827
|
+
ok: false,
|
|
2828
|
+
message: `合并失败,已回滚:${reason}`
|
|
2829
|
+
};
|
|
2830
|
+
}
|
|
2831
|
+
});
|
|
2832
|
+
}
|
|
2833
|
+
/**
|
|
2834
|
+
* Content-distribution repair (008 batch B, 009-R kernel): move body
|
|
2835
|
+
* sections — anchored by their exact `## heading` lines — into references/
|
|
2836
|
+
* support files and replace each span with a pointer line. The skill
|
|
2837
|
+
* name/dir never change (routing stays; only content location shifts, so a
|
|
2838
|
+
* fat body sheds its log-like detail). Deterministic, never automatic:
|
|
2839
|
+
* candidates come from an approved review plan. The write batch goes
|
|
2840
|
+
* through the tree-change kernel — one commit point, byte-level rollback.
|
|
2841
|
+
* Package integrity (009-R): a moved section whose text carries
|
|
2842
|
+
* support-directory links is refused (those links' files stay behind in the
|
|
2843
|
+
* same package; the moved text belongs in references/ beside them).
|
|
2844
|
+
*/
|
|
2845
|
+
async restructure(rawName, moves, origin = this.authority.origin) {
|
|
2846
|
+
const name = rawName.trim();
|
|
2847
|
+
await this.ensureRecovered();
|
|
2848
|
+
return await this.restructureCore(name, moves, origin);
|
|
2849
|
+
}
|
|
2850
|
+
async restructureCore(name, moves, origin) {
|
|
2851
|
+
const badName = this.badName(name);
|
|
2852
|
+
if (badName) return {
|
|
2853
|
+
ok: false,
|
|
2854
|
+
message: badName
|
|
2855
|
+
};
|
|
2856
|
+
if (moves.length === 0) return {
|
|
2857
|
+
ok: false,
|
|
2858
|
+
message: "重构至少需要一次章节搬移。"
|
|
2859
|
+
};
|
|
2860
|
+
if (moves.length > 5) return {
|
|
2861
|
+
ok: false,
|
|
2862
|
+
message: `重构超过 5 次搬移。`
|
|
2863
|
+
};
|
|
2864
|
+
for (const move of moves) {
|
|
2865
|
+
const raw = move;
|
|
2866
|
+
if (raw === null || typeof raw !== "object") return {
|
|
2867
|
+
ok: false,
|
|
2868
|
+
message: "每次重构搬移都必须是带 heading 的对象。"
|
|
2869
|
+
};
|
|
2870
|
+
if (typeof move.heading !== "string" || !move.heading.trim()) return {
|
|
2871
|
+
ok: false,
|
|
2872
|
+
message: "每次重构搬移都需要非空的 heading。"
|
|
2873
|
+
};
|
|
2874
|
+
const targetIssue = validateRestructureTarget(move.toFile);
|
|
2875
|
+
if (targetIssue) return {
|
|
2876
|
+
ok: false,
|
|
2877
|
+
message: targetIssue
|
|
2878
|
+
};
|
|
2879
|
+
}
|
|
2880
|
+
const dir = this.dirOf(name);
|
|
2881
|
+
const md = await this.io.readText(join(dir, "SKILL.md"));
|
|
2882
|
+
if (!md) return {
|
|
2883
|
+
ok: false,
|
|
2884
|
+
message: `技能「${name}」不存在。`
|
|
2885
|
+
};
|
|
2886
|
+
const block = frontmatterBlock(md);
|
|
2887
|
+
if (!block) return {
|
|
2888
|
+
ok: false,
|
|
2889
|
+
message: "SKILL.md 没有有效的 frontmatter;拒绝重构。"
|
|
2890
|
+
};
|
|
2891
|
+
const header = block.lines.slice(0, block.end + 1).join("\n");
|
|
2892
|
+
const plan = planRestructureSections(md.slice(header.length).replace(/\r\n/g, "\n"), moves);
|
|
2893
|
+
if ("error" in plan) return {
|
|
2894
|
+
ok: false,
|
|
2895
|
+
message: `重构被拒绝:${plan.error}`
|
|
2896
|
+
};
|
|
2897
|
+
const newMd = `${header}${plan.body}`.replace(/\r\n/g, "\n");
|
|
2898
|
+
const finalMd = block.nl === "\r\n" ? newMd.replace(/\n/g, "\r\n") : newMd;
|
|
2899
|
+
const newMdCheck = validateFrontmatter(finalMd, name, this.limits);
|
|
2900
|
+
if (newMdCheck) return {
|
|
2901
|
+
ok: false,
|
|
2902
|
+
message: `重构被拒绝:${newMdCheck}`
|
|
2903
|
+
};
|
|
2904
|
+
const listing = (this.limits.citationPolicy ?? "verify") === "refuse" ? null : await this.listSupportFiles(name);
|
|
2905
|
+
const files = listing !== null && isPresent(listing) ? listing.value : null;
|
|
2906
|
+
for (const section of plan.sections) {
|
|
2907
|
+
const refs = supportRefs(section.text);
|
|
2908
|
+
if (refs.length === 0) continue;
|
|
2909
|
+
if (files === null) return {
|
|
2910
|
+
ok: false,
|
|
2911
|
+
message: `重构被拒绝:章节「## ${section.heading}」引用了会留在原地的支撑文件(${refs.join(", ")}):请拆开该章节,或连同它的文件一起搬。`
|
|
2912
|
+
};
|
|
2913
|
+
const report = resolveCitations({
|
|
2914
|
+
content: section.text,
|
|
2915
|
+
file: "SKILL.md",
|
|
2916
|
+
files
|
|
2917
|
+
});
|
|
2918
|
+
if (report.dangling.length > 0) {
|
|
2919
|
+
const missing = report.dangling.map((ref) => ref.target ?? ref.raw).join(", ");
|
|
2920
|
+
return {
|
|
2921
|
+
ok: false,
|
|
2922
|
+
message: `重构被拒绝:章节「## ${section.heading}」引用的支撑文件不存在(${missing}):请修正引用,或先创建该文件。`
|
|
2923
|
+
};
|
|
2924
|
+
}
|
|
2925
|
+
}
|
|
2926
|
+
const byRel = /* @__PURE__ */ new Map();
|
|
2927
|
+
for (const section of plan.sections) {
|
|
2928
|
+
const entry = byRel.get(section.rel) ?? {
|
|
2929
|
+
rel: section.rel,
|
|
2930
|
+
texts: []
|
|
2931
|
+
};
|
|
2932
|
+
entry.texts.push(section.text);
|
|
2933
|
+
byRel.set(section.rel, entry);
|
|
2934
|
+
}
|
|
2935
|
+
const writes = [];
|
|
2936
|
+
for (const entry of byRel.values()) {
|
|
2937
|
+
const target = join(dir, ...entry.rel.split("/"));
|
|
2938
|
+
const previous = await this.readForCas(target);
|
|
2939
|
+
const base = previous?.trimEnd() ?? "";
|
|
2940
|
+
writes.push({
|
|
2941
|
+
target,
|
|
2942
|
+
content: base === "" ? entry.texts.join("\n\n") : `${base}\n\n${entry.texts.join("\n\n")}`,
|
|
2943
|
+
expected: previous
|
|
2944
|
+
});
|
|
2945
|
+
}
|
|
2946
|
+
writes.push({
|
|
2947
|
+
target: join(dir, "SKILL.md"),
|
|
2948
|
+
content: finalMd,
|
|
2949
|
+
expected: md
|
|
2950
|
+
});
|
|
2951
|
+
const protection = await this.writeProtection(name, origin);
|
|
2952
|
+
if (protection !== null) return {
|
|
2953
|
+
ok: false,
|
|
2954
|
+
message: `技能「${name}」受保护(${protection})。`
|
|
2955
|
+
};
|
|
2956
|
+
const summary = `moved ${plan.sections.length} section(s): ${[...byRel.keys()].join(", ")}`;
|
|
2957
|
+
const ops = writes.map((write) => ({
|
|
2958
|
+
kind: "write",
|
|
2959
|
+
target: write.target,
|
|
2960
|
+
content: write.content,
|
|
2961
|
+
...write.expected === void 0 ? {} : { expected: write.expected },
|
|
2962
|
+
skill: name
|
|
2963
|
+
}));
|
|
2964
|
+
const hooks = { committed: async (event) => {
|
|
2965
|
+
let headPlaced = false;
|
|
2966
|
+
for (const op of event.ops) {
|
|
2967
|
+
const rel = relative(dir, op.target).split(String.fromCharCode(92)).join("/");
|
|
2968
|
+
await this.audit(name, "restructure", op.before, op.after, summary, rel === "SKILL.md" ? void 0 : rel, event.unitId, headPlaced ? void 0 : this.unitHeadForOps(event.ops, [name]), origin);
|
|
2969
|
+
headPlaced = true;
|
|
2970
|
+
}
|
|
2971
|
+
this.notifyMutation({
|
|
2972
|
+
action: "restructure",
|
|
2973
|
+
name,
|
|
2974
|
+
skillDir: dir
|
|
2975
|
+
});
|
|
2976
|
+
} };
|
|
2977
|
+
const home = dirname(this.root);
|
|
2978
|
+
const result = await new MutationUnit({
|
|
2979
|
+
io: this.io,
|
|
2980
|
+
limits: {
|
|
2981
|
+
maxSkillFileBytes: this.limits.maxSkillFileBytes,
|
|
2982
|
+
maxSkillContentChars: this.limits.maxSkillContentChars
|
|
2983
|
+
},
|
|
2984
|
+
serial: this.serial,
|
|
2985
|
+
lock: this.lockPort(),
|
|
2986
|
+
journal: unitJournalPort(this.io, home),
|
|
2987
|
+
snapshots: unitSnapshotPort(this.io, home),
|
|
2988
|
+
hooks,
|
|
2989
|
+
validateWrite: (op) => op.kind === "write" ? this.contentThreatBlock(op.content) : null
|
|
2990
|
+
}).apply({
|
|
2991
|
+
name,
|
|
2992
|
+
origin,
|
|
2993
|
+
roots: [{
|
|
2994
|
+
name,
|
|
2995
|
+
protection: "write"
|
|
2996
|
+
}],
|
|
2997
|
+
rootDirs: { [name]: dir },
|
|
2998
|
+
ops,
|
|
2999
|
+
auditAction: "restructure",
|
|
3000
|
+
auditSummary: summary,
|
|
3001
|
+
eventAction: "restructure"
|
|
3002
|
+
});
|
|
3003
|
+
if (!result.ok) return {
|
|
3004
|
+
ok: false,
|
|
3005
|
+
message: result.errors.map((error) => error.message).join(";")
|
|
3006
|
+
};
|
|
3007
|
+
return {
|
|
3008
|
+
ok: true,
|
|
3009
|
+
message: `已重构「${name}」:把 ${plan.sections.length} 个章节搬到 references/。`,
|
|
3010
|
+
path: dir
|
|
3011
|
+
};
|
|
3012
|
+
}
|
|
3013
|
+
/**
|
|
3014
|
+
* Unified tree-change commit point (009 kernel): owns validation order,
|
|
3015
|
+
* pre-read rollback bytes, two-phase write with byte-level rollback, audit
|
|
3016
|
+
* and the mutation event. Mutators compose `TreeChangePlan`s — consolidate,
|
|
3017
|
+
* restructure (and future reference-mode consolidations) never implement
|
|
3018
|
+
* two-phase commit themselves.
|
|
3019
|
+
*/
|
|
3020
|
+
/**
|
|
3021
|
+
* Apply one G1 ExtractPlan as one cross-skill unit. This is a thin adapter:
|
|
3022
|
+
* selection, residual, pointer and support closure were already decided by
|
|
3023
|
+
* planExtract; this method only projects them into ordered kernel operations.
|
|
3024
|
+
* @param plan - pure plan from extract-plan.ts.
|
|
3025
|
+
* @param origin - write face recorded in the audit ledger.
|
|
3026
|
+
* @returns the kernel result; a refusal writes nothing.
|
|
3027
|
+
*/
|
|
3028
|
+
async extract(plan, origin = this.authority.origin) {
|
|
3029
|
+
await this.ensureRecovered();
|
|
3030
|
+
if (plan.outcome === "owner-gap" || plan.owner.mode !== "covered") return {
|
|
3031
|
+
ok: false,
|
|
3032
|
+
message: "提取被拒绝:owner-gap 不是写操作。"
|
|
3033
|
+
};
|
|
3034
|
+
if (plan.support.unresolved.length > 0 || plan.support.dangling.length > 0) return {
|
|
3035
|
+
ok: false,
|
|
3036
|
+
message: "提取被拒绝:support closure 存在 unresolved/dangling。"
|
|
3037
|
+
};
|
|
3038
|
+
if (plan.parts.length === 0) return {
|
|
3039
|
+
ok: false,
|
|
3040
|
+
message: "提取被拒绝:没有 part。"
|
|
3041
|
+
};
|
|
3042
|
+
const source = plan.source.trim();
|
|
3043
|
+
const target = plan.target.name.trim();
|
|
3044
|
+
if (source === target) return {
|
|
3045
|
+
ok: false,
|
|
3046
|
+
message: "提取被拒绝:source 与 target 相同。"
|
|
3047
|
+
};
|
|
3048
|
+
if (plan.target.exists !== true) return {
|
|
3049
|
+
ok: false,
|
|
3050
|
+
message: "提取被拒绝:target 不存在;owner-gap 不自动 create。"
|
|
3051
|
+
};
|
|
3052
|
+
const sourceDir = this.dirOf(source);
|
|
3053
|
+
const targetDir = this.dirOf(target);
|
|
3054
|
+
const sourceMd = await this.io.readText(join(sourceDir, "SKILL.md"));
|
|
3055
|
+
const targetMd = await this.io.readText(join(targetDir, "SKILL.md"));
|
|
3056
|
+
if (sourceMd === null) return {
|
|
3057
|
+
ok: false,
|
|
3058
|
+
message: "技能「" + source + "」不存在。"
|
|
3059
|
+
};
|
|
3060
|
+
if (targetMd === null) return {
|
|
3061
|
+
ok: false,
|
|
3062
|
+
message: "技能「" + target + "」不存在。"
|
|
3063
|
+
};
|
|
3064
|
+
if (plan.anchors !== void 0) {
|
|
3065
|
+
const sourceHash = contentHash(sourceMd);
|
|
3066
|
+
const targetHash = contentHash(targetMd);
|
|
3067
|
+
if (sourceHash !== plan.anchors.sourceMdSha256 || targetHash !== plan.anchors.targetMdSha256) return {
|
|
3068
|
+
ok: false,
|
|
3069
|
+
message: "提取被拒绝:source/target 在计划之后发生了变化;请重新计划。"
|
|
3070
|
+
};
|
|
3071
|
+
}
|
|
3072
|
+
const projected = projectExtractBodies(plan, sourceMd, targetMd);
|
|
3073
|
+
if (!projected.ok) return {
|
|
3074
|
+
ok: false,
|
|
3075
|
+
message: "提取被拒绝:" + projected.message
|
|
3076
|
+
};
|
|
3077
|
+
const sourceNew = projected.projection.sourceAfter;
|
|
3078
|
+
const targetNew = projected.projection.targetAfter;
|
|
3079
|
+
const ops = [];
|
|
3080
|
+
for (const move of [...plan.support.shared, ...plan.support.exclusive]) {
|
|
3081
|
+
const fromPath = join(sourceDir, ...move.from.split("/"));
|
|
3082
|
+
const toPath = join(targetDir, ...move.to.split("/"));
|
|
3083
|
+
const content = await this.io.readText(fromPath);
|
|
3084
|
+
if (content === null) return {
|
|
3085
|
+
ok: false,
|
|
3086
|
+
message: "提取被拒绝:support 文件不存在 " + move.from
|
|
3087
|
+
};
|
|
3088
|
+
const previous = await this.readForCas(toPath);
|
|
3089
|
+
ops.push({
|
|
3090
|
+
kind: "write",
|
|
3091
|
+
target: toPath,
|
|
3092
|
+
content,
|
|
3093
|
+
expected: previous,
|
|
3094
|
+
skill: target
|
|
3095
|
+
});
|
|
3096
|
+
}
|
|
3097
|
+
for (const file of plan.support.external) {
|
|
3098
|
+
if (file.content === void 0) return {
|
|
3099
|
+
ok: false,
|
|
3100
|
+
message: "提取被拒绝:external support 缺少已验证的内容 " + file.from
|
|
3101
|
+
};
|
|
3102
|
+
if (file.to.startsWith("/") || file.to.includes("..") || !/^(?:references|templates|scripts|assets)\//.test(file.to)) return {
|
|
3103
|
+
ok: false,
|
|
3104
|
+
message: "提取被拒绝:external target 不安全 " + file.to
|
|
3105
|
+
};
|
|
3106
|
+
const toPath = join(targetDir, ...file.to.split("/"));
|
|
3107
|
+
const previous = await this.readForCas(toPath);
|
|
3108
|
+
ops.push({
|
|
3109
|
+
kind: "write",
|
|
3110
|
+
target: toPath,
|
|
3111
|
+
content: file.content,
|
|
3112
|
+
expected: previous,
|
|
3113
|
+
skill: target
|
|
3114
|
+
});
|
|
3115
|
+
}
|
|
3116
|
+
ops.push({
|
|
3117
|
+
kind: "write",
|
|
3118
|
+
target: join(targetDir, "SKILL.md"),
|
|
3119
|
+
content: targetNew,
|
|
3120
|
+
expected: targetMd,
|
|
3121
|
+
skill: target
|
|
3122
|
+
});
|
|
3123
|
+
for (const move of plan.support.exclusive) {
|
|
3124
|
+
const sourcePath = join(sourceDir, ...move.from.split("/"));
|
|
3125
|
+
const previous = await this.readForCas(sourcePath);
|
|
3126
|
+
if (previous === null) return {
|
|
3127
|
+
ok: false,
|
|
3128
|
+
message: "提取被拒绝:待删除 support 不存在 " + move.from
|
|
3129
|
+
};
|
|
3130
|
+
ops.push({
|
|
3131
|
+
kind: "delete",
|
|
3132
|
+
target: sourcePath,
|
|
3133
|
+
expected: previous,
|
|
3134
|
+
skill: source
|
|
3135
|
+
});
|
|
3136
|
+
}
|
|
3137
|
+
ops.push({
|
|
3138
|
+
kind: "write",
|
|
3139
|
+
target: join(sourceDir, "SKILL.md"),
|
|
3140
|
+
content: sourceNew,
|
|
3141
|
+
expected: sourceMd,
|
|
3142
|
+
skill: source
|
|
3143
|
+
});
|
|
3144
|
+
const targetSummary = (await this.list({ withFrontmatter: true })).find((summary) => summary.name === target);
|
|
3145
|
+
if (targetSummary === void 0) return {
|
|
3146
|
+
ok: false,
|
|
3147
|
+
message: "提取被拒绝:target 不在技能库中。"
|
|
3148
|
+
};
|
|
3149
|
+
if (!targetSummary.managed) return {
|
|
3150
|
+
ok: false,
|
|
3151
|
+
message: "提取被拒绝:target 不是家族管理的技能。"
|
|
3152
|
+
};
|
|
3153
|
+
for (const name of [source, target]) {
|
|
3154
|
+
const protection = await this.writeProtection(name, origin);
|
|
3155
|
+
if (protection !== null) return {
|
|
3156
|
+
ok: false,
|
|
3157
|
+
message: "技能「" + name + "」受保护(" + protection + ")。"
|
|
3158
|
+
};
|
|
3159
|
+
}
|
|
3160
|
+
const summary = "extract " + plan.parts.map((part) => part.heading).join(", ") + " from " + source + " to " + target;
|
|
3161
|
+
const roots = [source, target];
|
|
3162
|
+
const hooks = { committed: async (event) => {
|
|
3163
|
+
const provenance = /* @__PURE__ */ new Map();
|
|
3164
|
+
for (const move of [...plan.support.shared, ...plan.support.external]) provenance.set(join(targetDir, ...move.to.split("/")), move.provenance);
|
|
3165
|
+
const head = this.unitHeadForOps(event.ops, roots, provenance);
|
|
3166
|
+
let headPlaced = false;
|
|
3167
|
+
for (const op of event.ops) {
|
|
3168
|
+
if (op.skill === void 0) continue;
|
|
3169
|
+
const rel = relative(this.dirOf(op.skill), op.target).split(String.fromCharCode(92)).join("/");
|
|
3170
|
+
await this.audit(op.skill, "extract", op.before, op.after, summary, rel === "SKILL.md" ? void 0 : rel, event.unitId, headPlaced ? void 0 : head, origin);
|
|
3171
|
+
headPlaced = true;
|
|
3172
|
+
}
|
|
3173
|
+
for (const name of roots) this.notifyMutation({
|
|
3174
|
+
action: "extract",
|
|
3175
|
+
name,
|
|
3176
|
+
skillDir: this.dirOf(name)
|
|
3177
|
+
});
|
|
3178
|
+
} };
|
|
3179
|
+
const home = dirname(this.root);
|
|
3180
|
+
const result = await new MutationUnit({
|
|
3181
|
+
io: this.io,
|
|
3182
|
+
limits: {
|
|
3183
|
+
maxSkillFileBytes: this.limits.maxSkillFileBytes,
|
|
3184
|
+
maxSkillContentChars: this.limits.maxSkillContentChars
|
|
3185
|
+
},
|
|
3186
|
+
serial: this.serial,
|
|
3187
|
+
lock: this.lockPort(),
|
|
3188
|
+
journal: unitJournalPort(this.io, home),
|
|
3189
|
+
snapshots: unitSnapshotPort(this.io, home),
|
|
3190
|
+
hooks,
|
|
3191
|
+
validateWrite: (op) => op.kind === "write" ? this.contentThreatBlock(op.content) : null
|
|
3192
|
+
}).apply({
|
|
3193
|
+
name: source,
|
|
3194
|
+
origin,
|
|
3195
|
+
roots: roots.map((name) => ({
|
|
3196
|
+
name,
|
|
3197
|
+
protection: "write"
|
|
3198
|
+
})),
|
|
3199
|
+
rootDirs: Object.fromEntries(roots.map((name) => [name, this.dirOf(name)])),
|
|
3200
|
+
ops,
|
|
3201
|
+
auditAction: "extract",
|
|
3202
|
+
auditSummary: summary,
|
|
3203
|
+
eventAction: "extract"
|
|
3204
|
+
});
|
|
3205
|
+
if (!result.ok) return {
|
|
3206
|
+
ok: false,
|
|
3207
|
+
message: "提取失败:" + result.errors.map((error) => error.message).join(";")
|
|
3208
|
+
};
|
|
3209
|
+
return {
|
|
3210
|
+
ok: true,
|
|
3211
|
+
message: summary + " succeeded.",
|
|
3212
|
+
path: this.dirOf(source)
|
|
3213
|
+
};
|
|
3214
|
+
}
|
|
3215
|
+
async applyTreeChange(plan) {
|
|
3216
|
+
const primaryName = plan.name.trim();
|
|
3217
|
+
const declared = plan.roots ?? [{
|
|
3218
|
+
name: primaryName,
|
|
3219
|
+
protection: plan.protection
|
|
3220
|
+
}];
|
|
3221
|
+
const roots = [];
|
|
3222
|
+
for (const root of declared) {
|
|
3223
|
+
const name = root.name.trim();
|
|
3224
|
+
if (roots.some((entry) => entry.name === name)) return {
|
|
3225
|
+
ok: false,
|
|
3226
|
+
message: "目录树变更声明了重复的根「" + name + "」。"
|
|
3227
|
+
};
|
|
3228
|
+
const badName = this.badName(name, { allowReserved: true });
|
|
3229
|
+
if (badName) return {
|
|
3230
|
+
ok: false,
|
|
3231
|
+
message: badName
|
|
3232
|
+
};
|
|
3233
|
+
const dir = this.dirOf(name);
|
|
3234
|
+
if (!await this.io.readText(join(dir, "SKILL.md"))) return {
|
|
3235
|
+
ok: false,
|
|
3236
|
+
message: "技能「" + name + "」不存在。"
|
|
3237
|
+
};
|
|
3238
|
+
const protection = root.protection === "write" ? await this.writeProtection(name, plan.origin) : root.protection === "delete" ? await this.deleteProtection(name) : null;
|
|
3239
|
+
if (protection) return {
|
|
3240
|
+
ok: false,
|
|
3241
|
+
message: "技能「" + name + "」受保护(" + protection + ")。"
|
|
3242
|
+
};
|
|
3243
|
+
roots.push({
|
|
3244
|
+
name,
|
|
3245
|
+
protection: root.protection,
|
|
3246
|
+
dir
|
|
3247
|
+
});
|
|
3248
|
+
}
|
|
3249
|
+
if (!roots.some((root) => root.name === primaryName)) return {
|
|
3250
|
+
ok: false,
|
|
3251
|
+
message: "目录树变更的 primary skill「" + primaryName + "」不在 roots 中。"
|
|
3252
|
+
};
|
|
3253
|
+
const provided = plan.ops ?? [...plan.writes.map((write) => ({
|
|
3254
|
+
kind: "write",
|
|
3255
|
+
...write
|
|
3256
|
+
})), ...(plan.deletes ?? []).map((del) => ({
|
|
3257
|
+
kind: "delete",
|
|
3258
|
+
...del
|
|
3259
|
+
}))];
|
|
3260
|
+
if (provided.length === 0) return {
|
|
3261
|
+
ok: false,
|
|
3262
|
+
message: "目录树变更为空。"
|
|
3263
|
+
};
|
|
3264
|
+
const landing = [];
|
|
3265
|
+
for (const op of provided) {
|
|
3266
|
+
const owner = roots.find((root) => {
|
|
3267
|
+
const rel = relative(root.dir, op.target);
|
|
3268
|
+
return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);
|
|
3269
|
+
});
|
|
3270
|
+
if (owner === void 0) return {
|
|
3271
|
+
ok: false,
|
|
3272
|
+
message: "目标不属于任何声明的技能根:" + op.target
|
|
3273
|
+
};
|
|
3274
|
+
const skill = op.skill ?? owner.name;
|
|
3275
|
+
if (!roots.some((root) => root.name === skill)) return {
|
|
3276
|
+
ok: false,
|
|
3277
|
+
message: "目标声明的技能「" + skill + "」不在 roots 中:" + op.target
|
|
3278
|
+
};
|
|
3279
|
+
let previous;
|
|
3280
|
+
try {
|
|
3281
|
+
previous = await this.io.readText(op.target);
|
|
3282
|
+
} catch (error) {
|
|
3283
|
+
return {
|
|
3284
|
+
ok: false,
|
|
3285
|
+
message: "拒绝目录树变更:无法安全预读 " + op.target + "(" + (error instanceof Error ? error.message : String(error)) + ");未执行任何写入"
|
|
3286
|
+
};
|
|
3287
|
+
}
|
|
3288
|
+
if (op.kind === "delete" && previous === null) return {
|
|
3289
|
+
ok: false,
|
|
3290
|
+
message: "拒绝目录树变更:删除目标不存在 " + op.target
|
|
3291
|
+
};
|
|
3292
|
+
if (op.kind === "write") {
|
|
3293
|
+
if (Buffer.byteLength(op.content, "utf8") > this.limits.maxSkillFileBytes) return {
|
|
3294
|
+
ok: false,
|
|
3295
|
+
message: "写入超过 " + this.limits.maxSkillFileBytes + " 字节:" + op.target
|
|
3296
|
+
};
|
|
3297
|
+
const threat = this.contentThreatBlock(op.content);
|
|
3298
|
+
if (threat) return {
|
|
3299
|
+
ok: false,
|
|
3300
|
+
message: threat
|
|
3301
|
+
};
|
|
3302
|
+
}
|
|
3303
|
+
const rel = relative(owner.dir, op.target).split(String.fromCharCode(92)).join("/");
|
|
3304
|
+
landing.push({
|
|
3305
|
+
kind: op.kind,
|
|
3306
|
+
target: op.target,
|
|
3307
|
+
content: op.kind === "write" ? op.content : null,
|
|
3308
|
+
previous,
|
|
3309
|
+
expected: op.expected,
|
|
3310
|
+
skill,
|
|
3311
|
+
dir: owner.dir,
|
|
3312
|
+
rel
|
|
3313
|
+
});
|
|
3314
|
+
}
|
|
3315
|
+
const unitId = plan.unitId ?? "u-" + Date.now().toString(36) + "-" + (nextUnitSeq += 1).toString(36);
|
|
3316
|
+
const applied = await new MutationUnit({
|
|
3317
|
+
io: this.io,
|
|
3318
|
+
limits: this.limits,
|
|
3319
|
+
...plan.nested === true ? { nested: true } : { lock: this.lockPort() },
|
|
3320
|
+
journal: unitJournalPort(this.io, dirname(this.root)),
|
|
3321
|
+
snapshots: unitSnapshotPort(this.io, dirname(this.root)),
|
|
3322
|
+
...this.transact === void 0 ? {} : { transact: this.transact },
|
|
3323
|
+
now: () => Date.now()
|
|
3324
|
+
}).apply({
|
|
3325
|
+
name: primaryName,
|
|
3326
|
+
roots: roots.map((root) => ({
|
|
3327
|
+
name: root.name,
|
|
3328
|
+
protection: root.protection
|
|
3329
|
+
})),
|
|
3330
|
+
ops: landing.map((entry) => entry.kind === "delete" ? {
|
|
3331
|
+
kind: "delete",
|
|
3332
|
+
target: entry.target,
|
|
3333
|
+
...entry.expected === void 0 ? {} : { expected: entry.expected }
|
|
3334
|
+
} : {
|
|
3335
|
+
kind: "write",
|
|
3336
|
+
target: entry.target,
|
|
3337
|
+
content: entry.content ?? "",
|
|
3338
|
+
...entry.expected === void 0 ? {} : { expected: entry.expected }
|
|
3339
|
+
}),
|
|
3340
|
+
rootDirs: Object.fromEntries(roots.map((root) => [root.name, root.dir])),
|
|
3341
|
+
origin: plan.origin,
|
|
3342
|
+
auditAction: plan.auditAction,
|
|
3343
|
+
auditSummary: plan.auditSummary,
|
|
3344
|
+
eventAction: plan.eventAction,
|
|
3345
|
+
unitId
|
|
3346
|
+
});
|
|
3347
|
+
if (!applied.ok) return {
|
|
3348
|
+
ok: false,
|
|
3349
|
+
message: "目录树变更失败:" + applied.errors.map((error) => error.message).join("; ")
|
|
3350
|
+
};
|
|
3351
|
+
const defaultHead = {
|
|
3352
|
+
moves: landing.filter((entry) => basename(entry.target) !== "SKILL.md").map((entry) => ({
|
|
3353
|
+
path: entry.rel,
|
|
3354
|
+
kind: entry.kind === "delete" ? "removed" : entry.previous === null ? "created" : "moved",
|
|
3355
|
+
...entry.previous === null ? {} : { beforeRef: contentHash(entry.previous) },
|
|
3356
|
+
...entry.kind === "delete" || entry.content === null ? {} : { afterRef: contentHash(entry.content) }
|
|
3357
|
+
})),
|
|
3358
|
+
sources: roots.map((root) => ({ skill: root.name }))
|
|
3359
|
+
};
|
|
3360
|
+
const affected = /* @__PURE__ */ new Set();
|
|
3361
|
+
for (let index = 0; index < landing.length; index += 1) {
|
|
3362
|
+
const entry = landing[index];
|
|
3363
|
+
if (entry === void 0) continue;
|
|
3364
|
+
await this.audit(entry.skill, plan.auditAction, entry.previous, entry.kind === "delete" ? null : entry.content, plan.auditSummary, entry.rel === "SKILL.md" ? void 0 : entry.rel, unitId, index === 0 ? plan.unitHead ?? defaultHead : void 0, plan.origin);
|
|
3365
|
+
affected.add(entry.skill);
|
|
3366
|
+
}
|
|
3367
|
+
for (const skill of affected) {
|
|
3368
|
+
const dir = roots.find((root) => root.name === skill)?.dir;
|
|
3369
|
+
if (dir !== void 0) this.notifyMutation({
|
|
3370
|
+
action: plan.eventAction,
|
|
3371
|
+
name: skill,
|
|
3372
|
+
skillDir: dir
|
|
3373
|
+
});
|
|
3374
|
+
}
|
|
3375
|
+
const primaryDir = roots.find((root) => root.name === primaryName)?.dir ?? roots[0]?.dir ?? "";
|
|
3376
|
+
const warnings = applied.warnings ?? [];
|
|
3377
|
+
return {
|
|
3378
|
+
ok: true,
|
|
3379
|
+
message: warnings.length === 0 ? plan.eventAction + " \"" + primaryName + "\" succeeded." : plan.eventAction + " \"" + primaryName + "\" succeeded (警告:" + warnings.join("; ") + ")",
|
|
3380
|
+
path: primaryDir
|
|
3381
|
+
};
|
|
3382
|
+
}
|
|
3383
|
+
/**
|
|
3384
|
+
* Restore one skill from `.archive/` back to the active root. Hermes-style
|
|
3385
|
+
* recoverability: archival never deletes, and this is the control-plane
|
|
3386
|
+
* path back. The `.archive-reason` marker is dropped on restore.
|
|
3387
|
+
*/
|
|
3388
|
+
async restoreFromArchive(rawName, origin = this.authority.origin) {
|
|
3389
|
+
const name = rawName.trim();
|
|
3390
|
+
const bad = this.badName(name, { allowReserved: true });
|
|
3391
|
+
if (bad) return {
|
|
3392
|
+
ok: false,
|
|
3393
|
+
message: bad
|
|
3394
|
+
};
|
|
3395
|
+
const dest = this.dirOf(name);
|
|
3396
|
+
if (await this.io.exists(dest)) return {
|
|
3397
|
+
ok: false,
|
|
3398
|
+
message: await this.io.exists(join(dest, "SKILL.md")) ? `技能「${name}」已存在于当前根目录;拒绝覆盖。` : `技能目录「${name}」已存在于当前根目录,但没有 SKILL.md;恢复前请先移除或修复它。`
|
|
3399
|
+
};
|
|
3400
|
+
let caseVariant;
|
|
3401
|
+
try {
|
|
3402
|
+
caseVariant = (await this.io.list(this.root)).find((entry) => entry !== name && entry.toLowerCase() === name.toLowerCase());
|
|
3403
|
+
} catch {}
|
|
3404
|
+
if (caseVariant !== void 0) return {
|
|
3405
|
+
ok: false,
|
|
3406
|
+
message: `技能「${caseVariant}」(同名、仅大小写不同)已存在于当前根目录;把「${name}」恢复到它旁边会造成含义不清的重复:请恢复为「${caseVariant}」,或先移除该变体。`
|
|
3407
|
+
};
|
|
3408
|
+
const archiveRoot = join(this.root, ".archive");
|
|
3409
|
+
let entries;
|
|
3410
|
+
try {
|
|
3411
|
+
entries = await this.io.list(archiveRoot);
|
|
3412
|
+
} catch {
|
|
3413
|
+
return {
|
|
3414
|
+
ok: false,
|
|
3415
|
+
message: "没有可用的技能归档。"
|
|
3416
|
+
};
|
|
3417
|
+
}
|
|
3418
|
+
const candidates = entries.filter((entry) => entry === name || entry.startsWith(`${name}-`)).sort().reverse();
|
|
3419
|
+
let chosen;
|
|
3420
|
+
const unreadable = [];
|
|
3421
|
+
for (const candidate of candidates) {
|
|
3422
|
+
const markerProbe = await probeText(this.io, join(archiveRoot, candidate, ".archive-name"));
|
|
3423
|
+
if (isUnknown(markerProbe)) {
|
|
3424
|
+
unreadable.push(candidate);
|
|
3425
|
+
continue;
|
|
3426
|
+
}
|
|
3427
|
+
if ((isPresent(markerProbe) ? markerProbe.value.trim() : "") === name) {
|
|
3428
|
+
chosen = candidate;
|
|
3429
|
+
break;
|
|
3430
|
+
}
|
|
3431
|
+
const mdProbe = await probeText(this.io, join(archiveRoot, candidate, "SKILL.md"));
|
|
3432
|
+
if (isUnknown(mdProbe)) {
|
|
3433
|
+
unreadable.push(candidate);
|
|
3434
|
+
continue;
|
|
3435
|
+
}
|
|
3436
|
+
const parsed = parseFrontmatter(isPresent(mdProbe) ? mdProbe.value : "");
|
|
3437
|
+
if (parsed?.frontmatter.name === name) {
|
|
3438
|
+
chosen = candidate;
|
|
3439
|
+
break;
|
|
3440
|
+
}
|
|
3441
|
+
if (parsed === null && candidate === name) {
|
|
3442
|
+
chosen = candidate;
|
|
3443
|
+
break;
|
|
3444
|
+
}
|
|
3445
|
+
if (parsed === null) unreadable.push(candidate);
|
|
3446
|
+
}
|
|
3447
|
+
if (!chosen) {
|
|
3448
|
+
if (unreadable.length === 0) return {
|
|
3449
|
+
ok: false,
|
|
3450
|
+
message: `技能「${name}」不在 .archive 里。`
|
|
3451
|
+
};
|
|
3452
|
+
return {
|
|
3453
|
+
ok: false,
|
|
3454
|
+
message: `.archive 里没有「${name}」对应的 frontmatter 名,但有 ${unreadable.length} 个名字相似的归档项:${unreadable.join(", ")}。这些归档项没有可读的 SKILL.md(或名字对不上),按名字恢复无法区分它们:请把目录改成技能名后再次恢复;快照这条路的当前状态是:${await this.snapshotRecoveryAvailability()}。`
|
|
3455
|
+
};
|
|
3456
|
+
}
|
|
3457
|
+
const source = join(archiveRoot, chosen);
|
|
3458
|
+
if (this.io.isSymlink) {
|
|
3459
|
+
if (await this.io.isSymlink(source) === true) return {
|
|
3460
|
+
ok: false,
|
|
3461
|
+
message: `归档项「${chosen}」是符号链接;拒绝恢复。`
|
|
3462
|
+
};
|
|
3463
|
+
}
|
|
3464
|
+
if (await this.supportDirsUnlistable(dest)) return {
|
|
3465
|
+
ok: false,
|
|
3466
|
+
message: `无法检查技能「${name}」是否有写入方(有一个支撑目录列不出来):请重试恢复。`
|
|
3467
|
+
};
|
|
3468
|
+
const moveFailure = await this.moveDir(source, dest);
|
|
3469
|
+
if (moveFailure !== void 0) return {
|
|
3470
|
+
ok: false,
|
|
3471
|
+
message: `从 .archive 恢复「${name}」失败:${moveFailure}`
|
|
3472
|
+
};
|
|
3473
|
+
for (const marker of [".archive-reason", ".archive-name"]) if (await this.io.exists(join(dest, marker))) await this.io.remove(join(dest, marker));
|
|
3474
|
+
const restoredProbe = await probeText(this.io, join(dest, "SKILL.md"));
|
|
3475
|
+
if (isUnknown(restoredProbe)) console.warn(`evolution-skill-store: the restored SKILL.md of "${name}" could not be read back (${restoredProbe.reason}); the restore is recorded without after-bytes`);
|
|
3476
|
+
await this.audit(name, "restore", null, isPresent(restoredProbe) ? restoredProbe.value : null, `restored from ${source}`, void 0, void 0, void 0, origin);
|
|
3477
|
+
this.notifyMutation({
|
|
3478
|
+
action: "restore",
|
|
3479
|
+
name,
|
|
3480
|
+
skillDir: dest
|
|
3481
|
+
});
|
|
3482
|
+
return {
|
|
3483
|
+
ok: true,
|
|
3484
|
+
message: `技能「${name}」已从 .archive 恢复。`,
|
|
3485
|
+
path: dest
|
|
3486
|
+
};
|
|
3487
|
+
}
|
|
3488
|
+
async writeSupportFile(rawName, filePath, content, origin = this.authority.origin, anchor) {
|
|
3489
|
+
const name = rawName.trim();
|
|
3490
|
+
return await this.writeSupportFileCore(name, filePath, content, origin, anchor);
|
|
3491
|
+
}
|
|
3492
|
+
async writeSupportFileCore(name, filePath, content, origin, anchor) {
|
|
3493
|
+
const badName = this.badName(name);
|
|
3494
|
+
if (badName) return {
|
|
3495
|
+
ok: false,
|
|
3496
|
+
message: badName
|
|
3497
|
+
};
|
|
3498
|
+
const dir = this.dirOf(name);
|
|
3499
|
+
if (!await this.io.exists(join(dir, "SKILL.md"))) return {
|
|
3500
|
+
ok: false,
|
|
3501
|
+
message: `技能「${name}」不存在。`
|
|
3502
|
+
};
|
|
3503
|
+
const protection = await this.writeProtection(name, origin);
|
|
3504
|
+
if (protection) return {
|
|
3505
|
+
ok: false,
|
|
3506
|
+
message: `技能「${name}」受保护(${protection})。`
|
|
3507
|
+
};
|
|
3508
|
+
const validation = validateSupportPath(filePath);
|
|
3509
|
+
if (validation) return {
|
|
3510
|
+
ok: false,
|
|
3511
|
+
message: validation
|
|
3512
|
+
};
|
|
3513
|
+
if (Buffer.byteLength(content, "utf8") > this.limits.maxSkillFileBytes) return {
|
|
3514
|
+
ok: false,
|
|
3515
|
+
message: `支撑文件超过 ${this.limits.maxSkillFileBytes} 字节。`
|
|
3516
|
+
};
|
|
3517
|
+
const threat = this.contentThreatBlock(content);
|
|
3518
|
+
if (threat) return {
|
|
3519
|
+
ok: false,
|
|
3520
|
+
message: threat
|
|
3521
|
+
};
|
|
3522
|
+
const target = join(dir, ...filePath.replace(/\\/g, "/").split("/").filter(Boolean));
|
|
3523
|
+
const probe = await probeText(this.io, target);
|
|
3524
|
+
if (isUnknown(probe)) return unreadableTarget(name + "/" + filePath, probe.reason);
|
|
3525
|
+
const current = isPresent(probe) ? probe.value : null;
|
|
3526
|
+
const verdict = anchorVerdict(anchor, current);
|
|
3527
|
+
if (verdict !== "match") return anchorRefusalFile(name, filePath, verdict);
|
|
3528
|
+
const overCap = exceedsContentLimit(content, this.limits.maxSkillContentChars);
|
|
3529
|
+
const repairing = shrinksOverLimit(content, current, this.limits.maxSkillContentChars);
|
|
3530
|
+
const capAdvisory = overCap && !repairing ? ` Warning: ${content.length} characters is over the ${this.limits.maxSkillContentChars}-character cap upstream applies to every file; plan a split.` : "";
|
|
3531
|
+
if (overCap && !repairing && this.supportFileCharPolicy() === "enforce") {
|
|
3532
|
+
await this.recordHardCapHit(name, content.length, "write_file", 1);
|
|
3533
|
+
return {
|
|
3534
|
+
ok: false,
|
|
3535
|
+
message: `支撑文件「${filePath}」的内容超过 ${this.limits.maxSkillContentChars} 个字符。${CONTENT_SPLIT_HINT}`
|
|
3536
|
+
};
|
|
3537
|
+
}
|
|
3538
|
+
if (current !== null && content.trimEnd() === current.trimEnd()) return {
|
|
3539
|
+
ok: true,
|
|
3540
|
+
message: `支撑文件「${filePath}」未变更:提供的内容与当前文件一致,未写入。`,
|
|
3541
|
+
noop: true,
|
|
3542
|
+
path: target
|
|
3543
|
+
};
|
|
3544
|
+
const result = await new MutationUnit({
|
|
3545
|
+
io: this.io,
|
|
3546
|
+
limits: {
|
|
3547
|
+
maxSkillFileBytes: Number.MAX_SAFE_INTEGER,
|
|
3548
|
+
maxSkillContentChars: Number.MAX_SAFE_INTEGER
|
|
3549
|
+
},
|
|
3550
|
+
serial: this.serial,
|
|
3551
|
+
lock: this.lockPort(),
|
|
3552
|
+
journal: unitJournalPort(this.io, dirname(this.root)),
|
|
3553
|
+
snapshots: unitSnapshotPort(this.io, dirname(this.root)),
|
|
3554
|
+
...this.transact === void 0 ? {} : { transact: this.transact },
|
|
3555
|
+
hooks: { committed: async (event) => {
|
|
3556
|
+
const op = event.ops[0];
|
|
3557
|
+
if (op === void 0) return;
|
|
3558
|
+
await this.audit(name, "write_file", op.before, op.after, `wrote ${filePath}`, filePath, event.unitId, void 0, origin);
|
|
3559
|
+
this.notifyMutation({
|
|
3560
|
+
action: "write_file",
|
|
3561
|
+
name,
|
|
3562
|
+
skillDir: dir,
|
|
3563
|
+
file: target
|
|
3564
|
+
});
|
|
3565
|
+
} },
|
|
3566
|
+
validateWrite: (op) => op.kind === "write" ? this.contentThreatBlock(op.content) : null
|
|
3567
|
+
}).apply({
|
|
3568
|
+
name,
|
|
3569
|
+
origin,
|
|
3570
|
+
roots: [{
|
|
3571
|
+
name,
|
|
3572
|
+
protection: "write"
|
|
3573
|
+
}],
|
|
3574
|
+
rootDirs: { [name]: dir },
|
|
3575
|
+
ops: [{
|
|
3576
|
+
kind: "write",
|
|
3577
|
+
target,
|
|
3578
|
+
content,
|
|
3579
|
+
expected: current,
|
|
3580
|
+
skill: name
|
|
3581
|
+
}],
|
|
3582
|
+
auditAction: "write_file",
|
|
3583
|
+
auditSummary: `wrote ${filePath}`,
|
|
3584
|
+
eventAction: "write_file"
|
|
3585
|
+
});
|
|
3586
|
+
if (!result.ok) return {
|
|
3587
|
+
ok: false,
|
|
3588
|
+
message: result.errors.map((error) => error.message).join(";")
|
|
3589
|
+
};
|
|
3590
|
+
return {
|
|
3591
|
+
ok: true,
|
|
3592
|
+
message: `支撑文件「${filePath}」已写入「${name}」。${capAdvisory}${result.warnings === void 0 || result.warnings.length === 0 ? "" : ` (警告:写入已落盘,但目录 fsync 失败 —— 持久性未确认:${result.warnings.join(";")})`}`,
|
|
3593
|
+
path: target
|
|
3594
|
+
};
|
|
3595
|
+
}
|
|
3596
|
+
async removeSupportFile(rawName, filePath, origin = this.authority.origin, anchor, unitId) {
|
|
3597
|
+
return await this.serial(() => this.removeSupportFileCore(rawName.trim(), filePath, origin, anchor, unitId));
|
|
3598
|
+
}
|
|
3599
|
+
async removeSupportFileCore(name, filePath, origin, anchor, unitId) {
|
|
3600
|
+
const badName = this.badName(name);
|
|
3601
|
+
if (badName) return {
|
|
3602
|
+
ok: false,
|
|
3603
|
+
message: badName
|
|
3604
|
+
};
|
|
3605
|
+
const dir = this.dirOf(name);
|
|
3606
|
+
if (!await this.io.exists(join(dir, "SKILL.md"))) return {
|
|
3607
|
+
ok: false,
|
|
3608
|
+
message: `技能「${name}」不存在。`
|
|
3609
|
+
};
|
|
3610
|
+
const protection = await this.writeProtection(name, origin);
|
|
3611
|
+
if (protection) return {
|
|
3612
|
+
ok: false,
|
|
3613
|
+
message: `技能「${name}」受保护(${protection})。`
|
|
3614
|
+
};
|
|
3615
|
+
const validation = validateSupportPath(filePath);
|
|
3616
|
+
if (validation) return {
|
|
3617
|
+
ok: false,
|
|
3618
|
+
message: validation
|
|
3619
|
+
};
|
|
3620
|
+
const target = join(dir, ...filePath.replace(/\\/g, "/").split("/").filter(Boolean));
|
|
3621
|
+
if (!await this.io.exists(target)) {
|
|
3622
|
+
if (anchor !== void 0) return anchorRefusalFile(name, filePath, "missing");
|
|
3623
|
+
return {
|
|
3624
|
+
ok: false,
|
|
3625
|
+
message: `文件「${filePath}」不在技能「${name}」里。`
|
|
3626
|
+
};
|
|
3627
|
+
}
|
|
3628
|
+
const beforeProbe = await probeText(this.io, target);
|
|
3629
|
+
if (!isPresent(beforeProbe)) {
|
|
3630
|
+
if (isUnknown(beforeProbe)) console.warn(`skill-store: could not read ${target} before removing it (${beforeProbe.reason}); refusing the removal`);
|
|
3631
|
+
return {
|
|
3632
|
+
ok: false,
|
|
3633
|
+
message: `"${filePath}" is not a readable regular file — remove the files inside it one by one.`
|
|
3634
|
+
};
|
|
3635
|
+
}
|
|
3636
|
+
const before = beforeProbe.value;
|
|
3637
|
+
let verdict = anchorVerdict(anchor, before);
|
|
3638
|
+
let lockedBefore = before;
|
|
3639
|
+
if (verdict === "match" && this.transact) {
|
|
3640
|
+
const ran = { done: false };
|
|
3641
|
+
await this.transact(this.io, target, (current) => {
|
|
3642
|
+
ran.done = true;
|
|
3643
|
+
verdict = anchorVerdict(anchor, current);
|
|
3644
|
+
if (verdict === "match" && current !== null) lockedBefore = current;
|
|
3645
|
+
return verdict === "match" ? null : current;
|
|
3646
|
+
});
|
|
3647
|
+
if (!ran.done) return {
|
|
3648
|
+
ok: false,
|
|
3649
|
+
message: "内部错误:删除事务没有调用任务;没有删除任何东西"
|
|
3650
|
+
};
|
|
3651
|
+
} else if (verdict === "match") await this.io.remove(target);
|
|
3652
|
+
if (verdict !== "match") return anchorRefusalFile(name, filePath, verdict);
|
|
3653
|
+
await this.audit(name, "remove_file", lockedBefore, null, `removed ${filePath}`, filePath, unitId);
|
|
3654
|
+
this.notifyMutation({
|
|
3655
|
+
action: "remove_file",
|
|
3656
|
+
name,
|
|
3657
|
+
skillDir: dir,
|
|
3658
|
+
file: target
|
|
3659
|
+
});
|
|
3660
|
+
return {
|
|
3661
|
+
ok: true,
|
|
3662
|
+
message: `支撑文件「${filePath}」已从「${name}」移除。`,
|
|
3663
|
+
path: target
|
|
3664
|
+
};
|
|
3665
|
+
}
|
|
3666
|
+
/**
|
|
3667
|
+
* v23 (ML-1): `.archive` retention. Archived skills are recoverable history,
|
|
3668
|
+
* but nothing bounded their growth — the curator auto-archives idle skills,
|
|
3669
|
+
* consolidation and manual deletes take the same path, and every snapshot
|
|
3670
|
+
* copies the whole `.archive` (keep-5 retention amplifies it ×6). Entries
|
|
3671
|
+
* older than this many days are pruned at snapshot time. Generous by
|
|
3672
|
+
* design: a year-old auto-archive is effectively dead recoverability.
|
|
3673
|
+
* Backends without the mtime probe skip pruning (no false deletes on
|
|
3674
|
+
* unknown age).
|
|
3675
|
+
*/
|
|
3676
|
+
/**
|
|
3677
|
+
* 0.5.0 V1 (design §16.6-④): the retention window's READ half. Names every
|
|
3678
|
+
* archived entry past the window without touching it — the report path the
|
|
3679
|
+
* default policy uses, and the input the curator's run report carries.
|
|
3680
|
+
* @returns the expired entry names ([] when the backend has no mtime probe,
|
|
3681
|
+
* because an unknown age must never read as expired).
|
|
3682
|
+
*/
|
|
3683
|
+
/** Names currently in .archive, for target occupancy; unknown listing is null. */
|
|
3684
|
+
async archivedNames() {
|
|
3685
|
+
const listed = await probeList(this.io, join(this.root, ".archive"));
|
|
3686
|
+
if (isUnknown(listed)) return null;
|
|
3687
|
+
return isPresent(listed) ? listed.value.slice() : [];
|
|
3688
|
+
}
|
|
3689
|
+
async expiredArchives() {
|
|
3690
|
+
const archiveRoot = join(this.root, ".archive");
|
|
3691
|
+
const listed = await probeList(this.io, archiveRoot);
|
|
3692
|
+
if (isUnknown(listed)) return null;
|
|
3693
|
+
if (!isPresent(listed)) return [];
|
|
3694
|
+
if (!this.io.mtime) return null;
|
|
3695
|
+
const cutoff = Date.now() - ARCHIVE_RETENTION_DAYS * 864e5;
|
|
3696
|
+
const expired = [];
|
|
3697
|
+
let undated = 0;
|
|
3698
|
+
for (const entry of listed.value) {
|
|
3699
|
+
const probe = await probeMtime(this.io, join(archiveRoot, entry));
|
|
3700
|
+
if (isUnknown(probe)) {
|
|
3701
|
+
undated += 1;
|
|
3702
|
+
continue;
|
|
3703
|
+
}
|
|
3704
|
+
if (isAbsent(probe) || probe.value > cutoff) continue;
|
|
3705
|
+
expired.push(entry);
|
|
3706
|
+
}
|
|
3707
|
+
if (undated > 0) console.warn(`skill-store: ${undated} archived entr(ies) could not be dated (mtime probe failed); they are retained — a failed probe never expires an entry`);
|
|
3708
|
+
return expired;
|
|
3709
|
+
}
|
|
3710
|
+
/** V4 (design §16.6): support-file char policy, resolved at the call site. */
|
|
3711
|
+
supportFileCharPolicy() {
|
|
3712
|
+
return this.limits.supportFileCharPolicy ?? "report";
|
|
3713
|
+
}
|
|
3714
|
+
/** Retention policy resolved at the call site (absent limits object = report).
|
|
3715
|
+
* Public so a run report can say WHICH policy produced its numbers. */
|
|
3716
|
+
archiveRetentionPolicy() {
|
|
3717
|
+
return this.limits.archiveRetention ?? "report";
|
|
3718
|
+
}
|
|
3719
|
+
async pruneExpiredArchives() {
|
|
3720
|
+
const expired = await this.expiredArchives();
|
|
3721
|
+
if (expired === null) return;
|
|
3722
|
+
for (const entry of expired) {
|
|
3723
|
+
const entryPath = join(this.root, ".archive", entry);
|
|
3724
|
+
await this.io.remove(entryPath).catch(() => {});
|
|
3725
|
+
console.warn(`skill-store: pruned archived skill "${entry}" (older than ${ARCHIVE_RETENTION_DAYS} days; recoverable from snapshots until they rotate)`);
|
|
3726
|
+
}
|
|
3727
|
+
}
|
|
3728
|
+
/**
|
|
3729
|
+
* Snapshot the recoverable skills state: active tree, usage/suppression
|
|
3730
|
+
* sidecars, `.archive/` and caller-supplied extras. `extras` are opaque
|
|
3731
|
+
* side files the Snapshot owner cares about (curator state); they are
|
|
3732
|
+
* listed in the manifest and only those names are ever read back.
|
|
3733
|
+
*/
|
|
3734
|
+
async snapshotAll(reason = "pre-mutation", extras = []) {
|
|
3735
|
+
if (this.archiveRetentionPolicy() === "prune") await this.pruneExpiredArchives();
|
|
3736
|
+
else {
|
|
3737
|
+
const expired = await this.expiredArchives();
|
|
3738
|
+
if (expired === null) console.warn("skill-store: archive retention state UNKNOWN — the .archive listing could not be read (archiveRetention=report, nothing deleted)");
|
|
3739
|
+
else if (expired.length > 0) console.warn(`skill-store: ${expired.length} archived skill(s) past the ${ARCHIVE_RETENTION_DAYS}-day window kept (archiveRetention=report): ${expired.slice(0, 5).join(", ")}`);
|
|
3740
|
+
}
|
|
3741
|
+
const backupRoot = join(this.root, ".backups");
|
|
3742
|
+
const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
|
|
3743
|
+
let dest = join(backupRoot, `skills-${stamp}`);
|
|
3744
|
+
while (await this.io.exists(dest)) dest = join(backupRoot, `skills-${stamp}-${Math.random().toString(36).slice(2, 8)}`);
|
|
3745
|
+
try {
|
|
3746
|
+
const names = await listNames(this.root, this.io);
|
|
3747
|
+
const skipped = [];
|
|
3748
|
+
const copyable = [];
|
|
3749
|
+
for (const name of names) if (await this.supportDirsUnlistable(this.dirOf(name))) {
|
|
3750
|
+
console.warn(`skill-store: snapshot skipped "${name}" — its support directory could not be listed; the skill is recorded as skipped in the manifest`);
|
|
3751
|
+
skipped.push(name);
|
|
3752
|
+
} else copyable.push(name);
|
|
3753
|
+
const copyFailure = (await Promise.allSettled(copyable.map(async (name) => {
|
|
3754
|
+
await this.io.copy(this.dirOf(name), join(dest, name));
|
|
3755
|
+
}))).find((result) => result.status === "rejected");
|
|
3756
|
+
if (copyFailure) throw copyFailure.reason;
|
|
3757
|
+
const suspect = [];
|
|
3758
|
+
for (const name of copyable) if (await this.supportDirsUnlistable(this.dirOf(name))) suspect.push(name);
|
|
3759
|
+
if (suspect.length > 0) {
|
|
3760
|
+
for (const name of suspect) console.warn(`skill-store: snapshot demoted "${name}" to skipped — a write lock appeared while its copy ran; the copied bytes are suspect`);
|
|
3761
|
+
for (const name of suspect) copyable.splice(copyable.indexOf(name), 1);
|
|
3762
|
+
skipped.push(...suspect);
|
|
3763
|
+
}
|
|
3764
|
+
const sidecars = [];
|
|
3765
|
+
for (const sidecar of [usageFile(this.root), suppressedFile(this.root)]) if (await this.io.exists(sidecar)) {
|
|
3766
|
+
const name = basename(sidecar);
|
|
3767
|
+
await this.io.copy(sidecar, join(dest, name));
|
|
3768
|
+
sidecars.push(name);
|
|
3769
|
+
}
|
|
3770
|
+
const archiveRoot = join(this.root, ".archive");
|
|
3771
|
+
let hasArchive = false;
|
|
3772
|
+
if (await this.io.exists(archiveRoot)) {
|
|
3773
|
+
await this.io.copy(archiveRoot, join(dest, ".archive"));
|
|
3774
|
+
hasArchive = true;
|
|
3775
|
+
}
|
|
3776
|
+
const rejectedExtras = extras.filter((extra) => typeof extra?.name !== "string" || !SNAPSHOT_EXTRA_NAME_RE.test(extra.name)).map((extra) => JSON.stringify(extra?.name ?? extra));
|
|
3777
|
+
if (rejectedExtras.length > 0) throw new Error(`snapshotAll: refusing invalid snapshot extras (name must match ${SNAPSHOT_EXTRA_NAME_RE.source}): ${rejectedExtras.join(", ")}`);
|
|
3778
|
+
const validExtras = extras;
|
|
3779
|
+
const extraNames = validExtras.map((extra) => extra.name);
|
|
3780
|
+
const extraFailure = (await Promise.allSettled(validExtras.map(async (extra) => {
|
|
3781
|
+
await this.io.writeText(join(dest, "extras", extra.name), extra.content);
|
|
3782
|
+
}))).find((result) => result.status === "rejected");
|
|
3783
|
+
if (extraFailure) throw extraFailure.reason;
|
|
3784
|
+
await this.io.writeText(join(dest, "manifest.json"), JSON.stringify({
|
|
3785
|
+
reason,
|
|
3786
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3787
|
+
skills: copyable,
|
|
3788
|
+
skipped,
|
|
3789
|
+
sidecars,
|
|
3790
|
+
hasArchive,
|
|
3791
|
+
extras: extraNames
|
|
3792
|
+
}, null, 2));
|
|
3793
|
+
await this.retainSnapshots(5);
|
|
3794
|
+
} catch (error) {
|
|
3795
|
+
await this.io.remove(dest).catch(() => {});
|
|
3796
|
+
throw error;
|
|
3797
|
+
}
|
|
3798
|
+
return dest;
|
|
3799
|
+
}
|
|
3800
|
+
/** Read and normalize a snapshot manifest; null when the file is missing or unparsable. */
|
|
3801
|
+
/**
|
|
3802
|
+
* V26-03 (v25/v26): sanitize the manifest's `skipped` list before it can
|
|
3803
|
+
* reach a user-visible restore message. Entries must pass the same name
|
|
3804
|
+
* gate as snapshot entries (a corrupted or hand-edited manifest cannot
|
|
3805
|
+
* inject arbitrary text into the result), bounded to 50 entries of at most
|
|
3806
|
+
* 64 chars each (the name-rule maximum — real skill names always fit).
|
|
3807
|
+
*/
|
|
3808
|
+
sanitizeSkippedNames(raw) {
|
|
3809
|
+
if (!Array.isArray(raw)) return [];
|
|
3810
|
+
const out = [];
|
|
3811
|
+
for (const entry of raw) {
|
|
3812
|
+
if (typeof entry !== "string") continue;
|
|
3813
|
+
if (!this.safeSnapshotEntryName(entry)) continue;
|
|
3814
|
+
out.push(entry.length > 64 ? entry.slice(0, 64) : entry);
|
|
3815
|
+
if (out.length >= 50) break;
|
|
3816
|
+
}
|
|
3817
|
+
return out;
|
|
3818
|
+
}
|
|
3819
|
+
/**
|
|
3820
|
+
* V27 G0.4 (core-a-01): the per-entry gate `skipped` already has. A corrupted
|
|
3821
|
+
* or hand-edited manifest could carry `extras: [123]`: the array check passed,
|
|
3822
|
+
* `SNAPSHOT_EXTRA_NAME_RE.test(123)` coerced the number to the string "123"
|
|
3823
|
+
* and matched, and the value then threw `TypeError` inside `path.join` — which
|
|
3824
|
+
* `readSnapshotExtras` reached only AFTER a whole-tree restore had committed.
|
|
3825
|
+
* Extras are path components under `extras/`, so they take the entry gate too;
|
|
3826
|
+
* bounded like `skipped` so a hostile manifest cannot grow the read set.
|
|
3827
|
+
*/
|
|
3828
|
+
sanitizeExtraNames(raw) {
|
|
3829
|
+
if (!Array.isArray(raw)) return [];
|
|
3830
|
+
const out = [];
|
|
3831
|
+
for (const entry of raw) {
|
|
3832
|
+
if (typeof entry !== "string") continue;
|
|
3833
|
+
if (!SNAPSHOT_EXTRA_NAME_RE.test(entry)) continue;
|
|
3834
|
+
if (!this.safeSnapshotEntryName(entry)) continue;
|
|
3835
|
+
out.push(entry);
|
|
3836
|
+
if (out.length >= 50) break;
|
|
3837
|
+
}
|
|
3838
|
+
return out;
|
|
3839
|
+
}
|
|
3840
|
+
async readSnapshotManifest(path) {
|
|
3841
|
+
const raw = await this.io.readText(join(path, "manifest.json"));
|
|
3842
|
+
if (raw === null) return null;
|
|
3843
|
+
try {
|
|
3844
|
+
const manifest = JSON.parse(raw);
|
|
3845
|
+
if (!Array.isArray(manifest.skills)) return null;
|
|
3846
|
+
return {
|
|
3847
|
+
reason: typeof manifest.reason === "string" ? manifest.reason : "",
|
|
3848
|
+
createdAt: typeof manifest.createdAt === "string" ? manifest.createdAt : "",
|
|
3849
|
+
skills: manifest.skills,
|
|
3850
|
+
skipped: this.sanitizeSkippedNames(manifest.skipped),
|
|
3851
|
+
sidecars: Array.isArray(manifest.sidecars) ? manifest.sidecars : [],
|
|
3852
|
+
...typeof manifest.hasArchive === "boolean" ? { hasArchive: manifest.hasArchive } : {},
|
|
3853
|
+
extras: this.sanitizeExtraNames(manifest.extras)
|
|
3854
|
+
};
|
|
3855
|
+
} catch {
|
|
3856
|
+
return null;
|
|
3857
|
+
}
|
|
3858
|
+
}
|
|
3859
|
+
/** Keep only the newest N snapshots (Hermes keep=5 parity); older ones are removed outright. */
|
|
3860
|
+
/**
|
|
3861
|
+
* G3/3.4: can a snapshot actually be used right now?
|
|
3862
|
+
*
|
|
3863
|
+
* The recovery messages used to promise "restore it from a snapshot" without asking whether a usable
|
|
3864
|
+
* snapshot exists (audit S1-01: the message promised recoverability from a chain that is five deep and
|
|
3865
|
+
* whose newest member held 9 of 35 skills). Three states, like every other reading here: a fragment
|
|
3866
|
+
* naming the usable snapshot, a fragment saying there is none, or a fragment saying the directory could
|
|
3867
|
+
* not be read - the caller embeds whichever it gets, so the sentence is generated by the capability.
|
|
3868
|
+
*/
|
|
3869
|
+
async snapshotRecoveryAvailability() {
|
|
3870
|
+
const listed = await this.listSnapshots();
|
|
3871
|
+
if (isUnknown(listed)) return "快照目录读不出来(" + listed.reason + ")";
|
|
3872
|
+
const latest = isPresent(listed) ? listed.value[0] : void 0;
|
|
3873
|
+
if (!latest) return "当前没有可用快照";
|
|
3874
|
+
return "最新快照 " + latest.path;
|
|
3875
|
+
}
|
|
3876
|
+
async retainSnapshots(keep) {
|
|
3877
|
+
const listed = await this.listSnapshots();
|
|
3878
|
+
if (isUnknown(listed)) {
|
|
3879
|
+
console.warn(`skill-store: snapshot retention skipped — the snapshot directory could not be listed (${listed.reason})`);
|
|
3880
|
+
return;
|
|
3881
|
+
}
|
|
3882
|
+
const snapshots = isPresent(listed) ? listed.value : [];
|
|
3883
|
+
for (const snapshot of snapshots.slice(keep)) try {
|
|
3884
|
+
await this.io.remove(snapshot.path);
|
|
3885
|
+
} catch {}
|
|
3886
|
+
}
|
|
3887
|
+
/** Snapshots as a THREE-state read (N14): absent = no .backups directory,
|
|
3888
|
+
* unknown = it exists but could not be listed (a caller must not read a
|
|
3889
|
+
* failed listing as "no snapshots to restore"). */
|
|
3890
|
+
async listSnapshots() {
|
|
3891
|
+
const backupRoot = join(this.root, ".backups");
|
|
3892
|
+
const listed = await probeList(this.io, backupRoot);
|
|
3893
|
+
if (!isPresent(listed)) return listed;
|
|
3894
|
+
const out = [];
|
|
3895
|
+
for (const name of listed.value.sort().reverse()) {
|
|
3896
|
+
if (!name.startsWith("skills-")) continue;
|
|
3897
|
+
const manifest = await this.readSnapshotManifest(join(backupRoot, name));
|
|
3898
|
+
if (manifest === null) {
|
|
3899
|
+
out.push({
|
|
3900
|
+
path: join(backupRoot, name),
|
|
3901
|
+
createdAt: "",
|
|
3902
|
+
reason: "清单读不出来或缺失(孤儿快照)"
|
|
3903
|
+
});
|
|
3904
|
+
continue;
|
|
3905
|
+
}
|
|
3906
|
+
out.push({
|
|
3907
|
+
path: join(backupRoot, name),
|
|
3908
|
+
createdAt: manifest.createdAt,
|
|
3909
|
+
reason: manifest.reason
|
|
3910
|
+
});
|
|
3911
|
+
}
|
|
3912
|
+
out.sort((a, b) => (b.createdAt || "").localeCompare(a.createdAt || "") || b.path.localeCompare(a.path));
|
|
3913
|
+
return probePresent(out);
|
|
3914
|
+
}
|
|
3915
|
+
/**
|
|
3916
|
+
* Read the extras of a snapshot, restricted to the names declared in the
|
|
3917
|
+
* manifest — an `extras/` directory is never listed directly, so unknown
|
|
3918
|
+
* files cannot leak back as state on the next restore.
|
|
3919
|
+
*/
|
|
3920
|
+
async readSnapshotExtras(path) {
|
|
3921
|
+
const manifest = await this.readSnapshotManifest(path);
|
|
3922
|
+
if (manifest === null) return [];
|
|
3923
|
+
const extras = [];
|
|
3924
|
+
for (const name of manifest.extras) {
|
|
3925
|
+
if (!SNAPSHOT_EXTRA_NAME_RE.test(name)) continue;
|
|
3926
|
+
const content = await this.io.readText(join(path, "extras", name));
|
|
3927
|
+
if (content !== null) extras.push({
|
|
3928
|
+
name,
|
|
3929
|
+
content
|
|
3930
|
+
});
|
|
3931
|
+
}
|
|
3932
|
+
return extras;
|
|
3933
|
+
}
|
|
3934
|
+
/**
|
|
3935
|
+
* Manifest-driven restore of the latest snapshot: active tree, sidecars,
|
|
3936
|
+
* `.archive/` and (for full-state snapshots) the extras read back by the
|
|
3937
|
+
* caller. `extras` are additionally written into the pre-rollback safety
|
|
3938
|
+
* snapshot so the rollback itself is undoable with the same state.
|
|
3939
|
+
*/
|
|
3940
|
+
async restoreLatestSnapshot(extras = []) {
|
|
3941
|
+
const listed = await this.listSnapshots();
|
|
3942
|
+
if (isUnknown(listed)) return {
|
|
3943
|
+
ok: false,
|
|
3944
|
+
message: `拒绝快照恢复:快照目录读不出来(${listed.reason})—— 未做任何改动。`
|
|
3945
|
+
};
|
|
3946
|
+
const latest = isPresent(listed) ? listed.value[0] : void 0;
|
|
3947
|
+
if (!latest) return {
|
|
3948
|
+
ok: false,
|
|
3949
|
+
message: "没有可用的技能快照。"
|
|
3950
|
+
};
|
|
3951
|
+
let preRollbackPath;
|
|
3952
|
+
try {
|
|
3953
|
+
preRollbackPath = await this.snapshotAll("pre-rollback", extras);
|
|
3954
|
+
} catch (error) {
|
|
3955
|
+
return {
|
|
3956
|
+
ok: false,
|
|
3957
|
+
message: `在任何清理之前就拒绝了快照恢复:生成回滚前快照失败(${error instanceof Error ? error.message : String(error)})—— 活动目录树未改变。请解决快照写入失败后重试。`
|
|
3958
|
+
};
|
|
3959
|
+
}
|
|
3960
|
+
let snapshotExtras;
|
|
3961
|
+
try {
|
|
3962
|
+
snapshotExtras = await this.readSnapshotExtras(latest.path);
|
|
3963
|
+
} catch (error) {
|
|
3964
|
+
return {
|
|
3965
|
+
ok: false,
|
|
3966
|
+
message: `在任何清理之前就拒绝了快照恢复:读取快照清单或附属文件失败(${error instanceof Error ? error.message : String(error)})—— 活动目录树未改变。请解决读取失败后重试。`
|
|
3967
|
+
};
|
|
3968
|
+
}
|
|
3969
|
+
try {
|
|
3970
|
+
await this.restoreSnapshotIntoRoot(latest.path);
|
|
3971
|
+
} catch (error) {
|
|
3972
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
3973
|
+
try {
|
|
3974
|
+
await this.restoreSnapshotIntoRoot(preRollbackPath);
|
|
3975
|
+
return {
|
|
3976
|
+
ok: false,
|
|
3977
|
+
message: `快照恢复失败(${reason});活动目录树已回滚到回滚前的快照。`
|
|
3978
|
+
};
|
|
3979
|
+
} catch (rollbackError) {
|
|
3980
|
+
const rb = rollbackError instanceof Error ? rollbackError.message : String(rollbackError);
|
|
3981
|
+
if (isPreClearRefusal(reason) && isPreClearRefusal(rb)) return {
|
|
3982
|
+
ok: false,
|
|
3983
|
+
message: `在任何清理之前就拒绝了快照恢复; 活动目录树未改变。\n- 目标:${reason}\n- 回滚前快照:${rb}\n请解决原因(有存活的技能写入,或快照不完整)后重试 —— 无需手动抢救。`
|
|
3984
|
+
};
|
|
3985
|
+
return {
|
|
3986
|
+
ok: false,
|
|
3987
|
+
message: `快照恢复失败(${reason}),且回滚前快照的恢复也失败(${rb})。请手动抢救:${preRollbackPath}(回滚前)、${latest.path}(目标)。`
|
|
3988
|
+
};
|
|
3989
|
+
}
|
|
3990
|
+
}
|
|
3991
|
+
this.notifyMutation({
|
|
3992
|
+
action: "restore",
|
|
3993
|
+
name: "snapshot"
|
|
3994
|
+
});
|
|
3995
|
+
return {
|
|
3996
|
+
ok: true,
|
|
3997
|
+
message: `已从 ${latest.path} 恢复技能目录树`,
|
|
3998
|
+
path: latest.path,
|
|
3999
|
+
...snapshotExtras.length === 0 ? {} : { extras: snapshotExtras }
|
|
4000
|
+
};
|
|
4001
|
+
}
|
|
4002
|
+
/**
|
|
4003
|
+
* Whole-tree replacement from one snapshot path (rc.50 P2-14): every
|
|
4004
|
+
* NON-system entry in the active root is cleared first, then the manifest
|
|
4005
|
+
* drives the repopulation (skills, sidecars, `.archive`). Extracted from
|
|
4006
|
+
* restoreLatestSnapshot so a failed restore can roll itself back (E-13).
|
|
4007
|
+
*/
|
|
4008
|
+
async restoreSnapshotIntoRoot(snapshotPath) {
|
|
4009
|
+
const manifest = await this.readSnapshotManifest(snapshotPath);
|
|
4010
|
+
if (manifest === null) throw new Error(await this.io.exists(join(snapshotPath, "manifest.json")) ? `snapshot ${snapshotPath} has an unreadable manifest.json; refusing to clear the active tree` : `snapshot ${snapshotPath} has no readable manifest.json; refusing to restore`);
|
|
4011
|
+
for (const name of [...manifest.skills, ...manifest.sidecars]) if (!this.safeSnapshotEntryName(name)) throw new Error(`snapshot ${snapshotPath} declares an unsafe entry name ${JSON.stringify(name)}; refusing to restore`);
|
|
4012
|
+
if (manifest.skipped.length > 0) throw new Error(`snapshot ${snapshotPath} is incomplete: ${manifest.skipped.length} skill(s) were skipped when it was taken (a live writer held their write lock: ${manifest.skipped.join(", ")}); restoring it would clear the active tree without bringing them back — let the writer finish and take a fresh snapshot, then restore that one`);
|
|
4013
|
+
if (manifest.skills.length === 0) {
|
|
4014
|
+
const snapshotEntries = await this.io.list(snapshotPath);
|
|
4015
|
+
const declared = new Set([
|
|
4016
|
+
"manifest.json",
|
|
4017
|
+
"extras",
|
|
4018
|
+
".archive",
|
|
4019
|
+
...manifest.skills,
|
|
4020
|
+
...manifest.sidecars
|
|
4021
|
+
]);
|
|
4022
|
+
const undeclared = snapshotEntries.filter((entry) => !declared.has(entry));
|
|
4023
|
+
if (undeclared.length > 0) throw new Error(`snapshot ${snapshotPath} declares no skills but contains undeclared entries (${undeclared.join(", ")}); refusing to clear the active tree`);
|
|
4024
|
+
}
|
|
4025
|
+
let rootEntries;
|
|
4026
|
+
try {
|
|
4027
|
+
rootEntries = await this.io.list(this.root);
|
|
4028
|
+
} catch (error) {
|
|
4029
|
+
throw new Error(`snapshot restore refused: the skill root could not be listed (${error instanceof Error ? error.message : String(error)}) — nothing was changed`);
|
|
4030
|
+
}
|
|
4031
|
+
for (const entry of rootEntries) {
|
|
4032
|
+
if (entry === ".archive" || entry === ".backups" || entry === ".mutations.json" || entry === ".curator-suppressed.json" || entry === ".history") continue;
|
|
4033
|
+
const dir = join(this.root, entry);
|
|
4034
|
+
if (await this.io.exists(join(dir, "SKILL.md"))) {
|
|
4035
|
+
if (await this.supportDirsUnlistable(dir)) throw new Error(`snapshot restore refused: skill "${entry}" is being written (write lock present); retry once the write completes`);
|
|
4036
|
+
}
|
|
4037
|
+
}
|
|
4038
|
+
const restoresSuppressed = manifest.sidecars.includes(".curator-suppressed.json");
|
|
4039
|
+
const declared = new Set([...manifest.skills, ...manifest.sidecars]);
|
|
4040
|
+
const doomed = rootEntries.filter((entry) => {
|
|
4041
|
+
if (entry === ".archive" || entry === ".backups" || entry === ".mutations.json") return false;
|
|
4042
|
+
if (entry === ".history") return false;
|
|
4043
|
+
if (entry === ".curator-suppressed.json" && restoresSuppressed) return false;
|
|
4044
|
+
return !declared.has(entry);
|
|
4045
|
+
});
|
|
4046
|
+
if (doomed.length > 0) console.warn("skill-store: snapshot restore will delete " + String(doomed.length) + " live entr(y|ies) the snapshot does not declare: " + doomed.join(", "));
|
|
4047
|
+
for (const entry of doomed) await this.io.remove(join(this.root, entry));
|
|
4048
|
+
for (const name of manifest.skills) await this.io.copy(join(snapshotPath, name), join(this.root, name));
|
|
4049
|
+
for (const sidecar of manifest.sidecars) await this.io.copy(join(snapshotPath, sidecar), join(this.root, sidecar));
|
|
4050
|
+
{
|
|
4051
|
+
const archiveRoot = join(this.root, ".archive");
|
|
4052
|
+
if (manifest.hasArchive === true) {
|
|
4053
|
+
await this.io.remove(archiveRoot);
|
|
4054
|
+
await this.io.copy(join(snapshotPath, ".archive"), archiveRoot);
|
|
4055
|
+
} else if (manifest.hasArchive === false) await this.io.remove(archiveRoot);
|
|
4056
|
+
}
|
|
4057
|
+
for (const entry of await this.io.list(this.root)) if (entry.startsWith(".")) continue;
|
|
4058
|
+
}
|
|
4059
|
+
};
|
|
4060
|
+
function newSkillLibrary(options) {
|
|
4061
|
+
const { config, io, limits, ctx, transact, threatExemptLabels, authority } = options;
|
|
4062
|
+
return new SkillLibrary(resolveSkillsRoot(config ?? {}), io, limits, ctx ? (event) => {
|
|
4063
|
+
ctx.emit("evolution/skill-mutated", event);
|
|
4064
|
+
} : void 0, transact, [...threatExemptLabels ?? []], authority, options.mutationLock ?? mutationLockFrom(ctx), options.fence ?? ctx?.get?.("evolutionMutationAuthority")?.homeFence);
|
|
4065
|
+
}
|
|
4066
|
+
//#endregion
|
|
4067
|
+
export { BASELINE_ACTION, DEFAULT_ARCHIVE_RETENTION_POLICY, DEFAULT_CITATION_POLICY, DEFAULT_HEALTH_THRESHOLDS, DEFAULT_REFERENCE_REWRITE_POLICY, DEFAULT_SKILL_LIMITS, DEFAULT_SUPPORT_FILE_CHAR_POLICY, HEALTH_STAMP_RE, HISTORY_DIR, HISTORY_INDEX_VERSION, MAX_RESTRUCTURE_MOVES, MIN_STAMP_BODY_CHARS, POLICY_STAGE_DEFAULTS, READ_REQUIRED_ACTIONS, RESTRUCTURE_TARGET_RE, RETENTION_FEEDBACK_KEEP_RATIO, RETENTION_FEEDBACK_MIN_CHARS, RULES, SNAPSHOT_EXTRA_NAME_RE, SkillLibrary, SkillModel, TEXT_DIFF_MAX_CHARS, TEXT_DIFF_MAX_LINES, VERSION_SUMMARY_MAX_CHARS, ageCopyKey, anchorVerdict, assertSkillsRootAliasRetired, assessStructureHealth, authoringFeedback, blobPath, contentRetentionFeedback, countReferenceFiles, diffFindings, elapsedSince, ensureSkillFrontmatter, entryTarget, exceedsContentLimit, filterUnreadSkillOps, frontmatterBlock, frontmatterCatalogInvalid, historyIndexFile, historyRoot, isUnreadWrite, latestVersionAt, lintBody, lintSkill, loadVersionContent, loadVersions, markerEntryName, newSkillLibrary, nextHistoryIndex, normalizeFrontmatter, normalizeVersionSummary, orderVersions, parseFrontmatter, parseHistoryIndex, partitionVersions, policyStageLimits, readHistoryIndex, recordVersions, relatedSkillNames, resolveExecOrigins, resolveOrigins, resolveRootConfig, resolveSkillsRoot, revisionAnchor, revisionAnchorOf, revisionFingerprint, revisionSupportDigest, sessionReadSkillNames, sessionReadSupportFiles, shrinksOverLimit, skillMdOnDisk, skillRowCells, skillStateKey, skillsRoot, textDiffFacts, validateFrontmatter, validateRestructureTarget, validateSupportPath, versionActionKind, versionRowCells, versionSummaryPrompt, versionTarget, yamlPlainScalarNeedsQuotes };
|