skill-evolution 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,344 @@
1
+ /**
2
+ * Curator 合并执行器(Consolidation)
3
+ *
4
+ * 移植自 Hermes `agent/curator.py` 的 LLM 合并 pass。
5
+ *
6
+ * 与 `usage.js` 的分工:
7
+ * - `usage.js` 做**确定性**状态转换(active/stale/archived),不需要模型
8
+ * - 本模块做 **LLM 驱动**的建伞合并,需要模型判断
9
+ *
10
+ * Hermes 的核心洞察(写在 CURATOR_REVIEW_PROMPT 里):
11
+ * 几百个各捕获一次会话 bug 的窄技能是**失败**,不是特性。
12
+ * 一个带小节的宽伞技能在可发现性上胜过五个窄兄弟。
13
+ *
14
+ * 不变量(全部来自 Hermes):
15
+ * 1. 永不删除,只归档
16
+ * 2. pinned / protected 技能完全跳过
17
+ * 3. 归档必须带 `absorbedInto`(吸收目标),无目标的归档属于确定性修剪,不归这里
18
+ * 4. 每次操作都走账本,可回滚
19
+ * 5. 包完整性:有 support 文件的技能不能只搬 SKILL.md
20
+ */
21
+
22
+ import fs from "node:fs/promises";
23
+ import path from "node:path";
24
+
25
+ import { captureSnapshot, appendEntry } from "./ledger.js";
26
+ import { parseSkillMarkdown, renderSkillMarkdown, gate, validateSkillName } from "./gatekeeper.js";
27
+ import { listSkills, readExistingSkill } from "./applier.js";
28
+ import { archiveSkill, loadUsage, entryOf, PROTECTED_SKILLS } from "./usage.js";
29
+ import { buildCuratorPrompt } from "./prompts.js";
30
+ import { extractJsonBlock } from "./synthesizer.js";
31
+
32
+ /** 从模型输出里抽结构化合并结果。 */
33
+ export function extractCuratorOps(text) {
34
+ const parsed = extractJsonBlock(text);
35
+ if (!parsed) return { ok: false, error: "no JSON block in curator output", ops: [], summary: "" };
36
+ const ops = Array.isArray(parsed.operations) ? parsed.operations : [];
37
+ return { ok: true, ops, summary: String(parsed.summary ?? "") };
38
+ }
39
+
40
+ /** 列出可参与合并的候选技能(已过滤 pinned / protected,并附上完整正文供 Curator LLM 蒸馏合并)。 */
41
+ export async function listConsolidationCandidates(skillsRoot) {
42
+ const skills = await listSkills(skillsRoot);
43
+ const usage = await loadUsage(skillsRoot);
44
+ const out = [];
45
+ for (const s of skills) {
46
+ const u = entryOf(usage, s.name);
47
+ if (u.pinned || PROTECTED_SKILLS.has(s.name)) continue;
48
+ const raw = await readExistingSkill(skillsRoot, s.name);
49
+ const parsed = raw ? parseSkillMarkdown(raw) : null;
50
+ out.push({
51
+ ...s,
52
+ useCount: u.useCount,
53
+ state: u.state,
54
+ pinned: u.pinned,
55
+ body: (parsed?.body ?? "").slice(0, 4000),
56
+ });
57
+ }
58
+ return out;
59
+ }
60
+
61
+ /**
62
+ * 校验一组合并操作是否安全可执行。
63
+ * 这是"闸门"——任何一条不合规,整批拒绝(原子性)。
64
+ *
65
+ * @returns {{ok: boolean, errors: string[], normalized: object[]}}
66
+ */
67
+ export function validateCuratorOps(ops, { existingNames = new Set(), protectedNames = new Set() } = {}) {
68
+ const errors = [];
69
+ const normalized = [];
70
+ const willCreate = new Set();
71
+
72
+ for (const raw of ops) {
73
+ if (!raw || typeof raw !== "object") {
74
+ errors.push("operation is not an object");
75
+ continue;
76
+ }
77
+ const op = String(raw.op ?? "").trim();
78
+
79
+ if (op === "archive") {
80
+ const target = String(raw.target ?? "").trim();
81
+ const absorbedInto = String(raw.absorbedInto ?? raw.absorbed_into ?? "").trim();
82
+ if (!target) errors.push("archive: missing target");
83
+ if (protectedNames.has(target) || PROTECTED_SKILLS.has(target)) {
84
+ errors.push(`archive: "${target}" is protected and must never be archived`);
85
+ continue;
86
+ }
87
+ if (!absorbedInto) {
88
+ errors.push(
89
+ `archive "${target}": missing absorbedInto — archiving without an absorption target is the ` +
90
+ `deterministic staleness pass's job, not the curator's`,
91
+ );
92
+ continue;
93
+ }
94
+ if (!existingNames.has(absorbedInto) && !willCreate.has(absorbedInto)) {
95
+ errors.push(`archive "${target}": absorbedInto "${absorbedInto}" does not exist and is not created in this batch`);
96
+ continue;
97
+ }
98
+ if (target === absorbedInto) {
99
+ errors.push(`archive "${target}": absorbedInto is itself`);
100
+ continue;
101
+ }
102
+ normalized.push({ op: "archive", target, absorbedInto, reason: String(raw.reason ?? "") });
103
+ continue;
104
+ }
105
+
106
+ if (op === "create") {
107
+ const target = String(raw.target ?? "").trim();
108
+ const nameCheck = validateSkillName(target);
109
+ if (!nameCheck.ok) {
110
+ errors.push(`create: ${nameCheck.error}`);
111
+ continue;
112
+ }
113
+ const g = gate({
114
+ action: "create",
115
+ target,
116
+ frontmatter: raw.frontmatter ?? { name: target, description: "" },
117
+ body: String(raw.body ?? ""),
118
+ });
119
+ if (!g.ok) {
120
+ errors.push(`create "${target}": ${g.errors.join("; ")}`);
121
+ continue;
122
+ }
123
+ willCreate.add(target);
124
+ normalized.push({
125
+ op: "create",
126
+ target,
127
+ frontmatter: raw.frontmatter ?? { name: target },
128
+ body: String(raw.body ?? ""),
129
+ });
130
+ continue;
131
+ }
132
+
133
+ if (op === "patch") {
134
+ const target = String(raw.target ?? "").trim();
135
+ if (!existingNames.has(target)) {
136
+ errors.push(`patch "${target}": skill does not exist`);
137
+ continue;
138
+ }
139
+ if (protectedNames.has(target) || PROTECTED_SKILLS.has(target)) {
140
+ errors.push(`patch "${target}": protected skill`);
141
+ continue;
142
+ }
143
+ const body = String(raw.body ?? "");
144
+ if (!body.trim()) {
145
+ errors.push(`patch "${target}": empty body`);
146
+ continue;
147
+ }
148
+ if (body.length > 24000) {
149
+ errors.push(`patch "${target}": body ${body.length} chars over 24000 limit`);
150
+ continue;
151
+ }
152
+ normalized.push({ op: "patch", target, body });
153
+ continue;
154
+ }
155
+
156
+ if (op === "write_file") {
157
+ const target = String(raw.target ?? "").trim();
158
+ const filePath = String(raw.filePath ?? raw.file_path ?? "").trim();
159
+ if (!existingNames.has(target) && !willCreate.has(target)) {
160
+ errors.push(`write_file "${target}": skill does not exist`);
161
+ continue;
162
+ }
163
+ if (!/^(references|templates|scripts|assets)\/[a-z0-9][a-z0-9._-]*\.[a-z0-9]+$/i.test(filePath)) {
164
+ errors.push(`write_file "${target}": filePath must be references|templates|scripts|assets/<name>.<ext>, got "${filePath}"`);
165
+ continue;
166
+ }
167
+ if (!String(raw.body ?? "").trim()) {
168
+ errors.push(`write_file "${target}": empty body`);
169
+ continue;
170
+ }
171
+ normalized.push({ op: "write_file", target, filePath, body: String(raw.body ?? "") });
172
+ continue;
173
+ }
174
+
175
+ errors.push(`unknown operation "${op}"`);
176
+ }
177
+
178
+ return { ok: errors.length === 0, errors, normalized };
179
+ }
180
+
181
+ /**
182
+ * 执行一批合并操作。
183
+ *
184
+ * 顺序很重要:create → patch → write_file → archive。
185
+ * 归档放最后,确保吸收目标已经存在。
186
+ */
187
+ export async function applyCuratorOps(skillsRoot, normalized, { actor = "curator" } = {}) {
188
+ const done = [];
189
+ const errors = [];
190
+
191
+ const order = { create: 0, patch: 1, write_file: 2, archive: 3 };
192
+ const sorted = [...normalized].sort((a, b) => (order[a.op] ?? 9) - (order[b.op] ?? 9));
193
+
194
+ for (const op of sorted) {
195
+ try {
196
+ if (op.op === "create") {
197
+ const dir = path.join(skillsRoot, op.target);
198
+ const before = await captureSnapshot(skillsRoot, dir);
199
+ await fs.mkdir(dir, { recursive: true });
200
+ const md = renderSkillMarkdown(
201
+ {
202
+ name: op.frontmatter.name ?? op.target,
203
+ description: op.frontmatter.description ?? "",
204
+ metadata: { createdBy: "agent", ...(op.frontmatter.metadata ?? {}) },
205
+ },
206
+ op.body,
207
+ );
208
+ await fs.writeFile(path.join(dir, "SKILL.md"), md, "utf8");
209
+ const after = await captureSnapshot(skillsRoot, dir);
210
+ await appendEntry(skillsRoot, { action: "curator_create", target: op.target, actor, before, after });
211
+ done.push(`create ${op.target}`);
212
+ continue;
213
+ }
214
+
215
+ if (op.op === "patch") {
216
+ const dir = path.join(skillsRoot, op.target);
217
+ const existing = await readExistingSkill(skillsRoot, op.target);
218
+ if (!existing) {
219
+ errors.push(`patch ${op.target}: vanished`);
220
+ continue;
221
+ }
222
+ const parsed = parseSkillMarkdown(existing);
223
+ const before = await captureSnapshot(skillsRoot, dir);
224
+ const md = renderSkillMarkdown(
225
+ { ...(parsed?.frontmatter ?? { name: op.target }), metadata: { ...(parsed?.frontmatter?.metadata ?? {}), createdBy: "agent" } },
226
+ op.body,
227
+ );
228
+ await fs.writeFile(path.join(dir, "SKILL.md"), md, "utf8");
229
+ const after = await captureSnapshot(skillsRoot, dir);
230
+ await appendEntry(skillsRoot, { action: "curator_patch", target: op.target, actor, before, after });
231
+ done.push(`patch ${op.target}`);
232
+ continue;
233
+ }
234
+
235
+ if (op.op === "write_file") {
236
+ const dir = path.join(skillsRoot, op.target);
237
+ const dest = path.join(dir, op.filePath);
238
+ const before = await captureSnapshot(skillsRoot, dir);
239
+ await fs.mkdir(path.dirname(dest), { recursive: true });
240
+ await fs.writeFile(dest, op.body.trim() + "\n", "utf8");
241
+ const after = await captureSnapshot(skillsRoot, dir);
242
+ await appendEntry(skillsRoot, {
243
+ action: "curator_write_file",
244
+ target: op.target,
245
+ actor,
246
+ before,
247
+ after,
248
+ extra: { filePath: op.filePath },
249
+ });
250
+ done.push(`write_file ${op.target}/${op.filePath}`);
251
+ continue;
252
+ }
253
+
254
+ if (op.op === "archive") {
255
+ const dir = path.join(skillsRoot, op.target);
256
+ const before = await captureSnapshot(skillsRoot, dir);
257
+ const r = await archiveSkill(skillsRoot, op.target);
258
+ if (!r.moved) {
259
+ errors.push(`archive ${op.target}: ${r.error}`);
260
+ continue;
261
+ }
262
+ await appendEntry(skillsRoot, {
263
+ action: "curator_archive",
264
+ target: op.target,
265
+ actor,
266
+ before,
267
+ after: null,
268
+ extra: { absorbedInto: op.absorbedInto, reason: op.reason, archivedTo: r.to },
269
+ });
270
+ done.push(`archive ${op.target} → ${op.absorbedInto}`);
271
+ continue;
272
+ }
273
+ } catch (error) {
274
+ errors.push(`${op.op} ${op.target}: ${error?.message ?? error}`);
275
+ }
276
+ }
277
+
278
+ return { ok: errors.length === 0, done, errors };
279
+ }
280
+
281
+ /**
282
+ * 运行一次完整的合并 pass。
283
+ *
284
+ * @param {string} skillsRoot
285
+ * @param {object} ctx Cordis 上下文(用于 fork 子代理)
286
+ * @param {object} opts
287
+ * @param {object} opts.parent 父 agent
288
+ * @param {Function} opts.runFork (prompt) => Promise<string> 执行只读 fork 并返回文本
289
+ * @param {boolean} [opts.dryRun=true] 只分析不执行
290
+ */
291
+ export async function runConsolidation(skillsRoot, opts = {}) {
292
+ const candidates = await listConsolidationCandidates(skillsRoot);
293
+ if (candidates.length < 2) {
294
+ return { ok: true, skipped: true, reason: `only ${candidates.length} candidate(s); nothing to consolidate`, done: [], errors: [] };
295
+ }
296
+
297
+ const prompt = buildCuratorPrompt({
298
+ candidates,
299
+ protectedNames: [...PROTECTED_SKILLS],
300
+ });
301
+
302
+ if (typeof opts.runFork !== "function") {
303
+ return { ok: false, error: "runFork is required", done: [], errors: ["no fork runner"] };
304
+ }
305
+
306
+ let raw;
307
+ try {
308
+ raw = await opts.runFork(prompt);
309
+ } catch (error) {
310
+ return { ok: false, error: String(error?.message ?? error), done: [], errors: [] };
311
+ }
312
+
313
+ const extracted = extractCuratorOps(raw);
314
+ if (!extracted.ok) {
315
+ return { ok: false, error: extracted.error, done: [], errors: [] };
316
+ }
317
+ if (extracted.ops.length === 0) {
318
+ return { ok: true, skipped: true, reason: extracted.summary || "curator found nothing to merge", done: [], errors: [] };
319
+ }
320
+
321
+ const existingNames = new Set((await listSkills(skillsRoot)).map((s) => s.name));
322
+ const verdict = validateCuratorOps(extracted.ops, {
323
+ existingNames,
324
+ protectedNames: PROTECTED_SKILLS,
325
+ });
326
+
327
+ if (!verdict.ok) {
328
+ return { ok: false, error: "validation failed", errors: verdict.errors, done: [], summary: extracted.summary };
329
+ }
330
+
331
+ if (opts.dryRun !== false) {
332
+ return {
333
+ ok: true,
334
+ dryRun: true,
335
+ summary: extracted.summary,
336
+ planned: verdict.normalized.map((o) => `${o.op} ${o.target}${o.absorbedInto ? " → " + o.absorbedInto : ""}`),
337
+ done: [],
338
+ errors: [],
339
+ };
340
+ }
341
+
342
+ const applied = await applyCuratorOps(skillsRoot, verdict.normalized);
343
+ return { ok: applied.ok, summary: extracted.summary, done: applied.done, errors: applied.errors };
344
+ }
@@ -0,0 +1,293 @@
1
+ /**
2
+ * 闸门(Gatekeeper)
3
+ *
4
+ * 技能是 Markdown 提示词,**没有可执行的单元测试**——所以"沙箱跑测试"这种
5
+ * 闸门在这里不成立。真正的闸门是四道:
6
+ *
7
+ * 1. 结构校验:frontmatter 合法(name kebab-case、description 非空)
8
+ * 2. 命名校验:类级别命名,拒绝会话产物(fix-X / debug-Y / PR 号 / 日期)
9
+ * 3. 禁词表:移植 Hermes `_DO_NOT_CAPTURE_BLOCK` 的负面断言与环境依赖失败
10
+ * 4. 干跑:写入 .staging/ 后用技能加载器验证可读,再决定是否落盘
11
+ *
12
+ * 第 3 道是整条链路里最重要的护栏。没有它,agent 会把自己写的
13
+ * "X 工具不能用" 硬化成引用几个月的拒绝理由。
14
+ */
15
+
16
+ /** 技能名必须是 kebab-case。 */
17
+ const KEBAB = /^[a-z0-9]+(-[a-z0-9]+)*$/;
18
+
19
+ /**
20
+ * 会话产物式命名——这些名字只能描述"今天这件事",不能描述"一类任务"。
21
+ * 命中即拒绝(对应提示词 rule 4)。
22
+ */
23
+ const SESSION_ARTIFACT_PATTERNS = [
24
+ /^(fix|debug|audit|patch|repair|hotfix)-/i,
25
+ /-(today|now|this-session|tmp|temp|wip)$/i,
26
+ /#?\d{3,}/, // PR / issue 号
27
+ /\b20\d{2}[-_]?\d{2}[-_]?\d{2}\b/, // 日期
28
+ /^(pr|issue|ticket|bug)[-_]?\d+/i,
29
+ ];
30
+
31
+ /** 这些词单独出现说明名字是库名/工具名而非任务类别。 */
32
+ const LIBRARY_ONLY_HINTS = new Set([
33
+ "react", "vue", "python", "node", "npm", "git", "docker", "bash", "zsh", "curl", "jq", "yaml", "json",
34
+ ]);
35
+
36
+ /**
37
+ * 负面断言禁词表(移植 `_DO_NOT_CAPTURE_BLOCK` 第 2 条)。
38
+ *
39
+ * 这些句子一旦写进技能,会变成 agent 自我施加的永久约束。
40
+ * 注意:这里只匹配"对工具/功能的否定断言",不匹配正常的技术描述。
41
+ */
42
+ const NEGATIVE_CLAIM_PATTERNS = [
43
+ /\b\w+\s+(tool|tools|feature|command|api|plugin)s?\s+(does\s+not|doesn'?t|do\s+not|don'?t)\s+work/i,
44
+ /\b(cannot|can'?t|unable\s+to)\s+(use|run|call|invoke)\s+\w+\s+(tool|feature|command|plugin)\b/i,
45
+ /\b(tool|tools|feature|plugin)\s+is\s+(broken|unusable|not\s+working|buggy)\b/i,
46
+ /\bnever\s+works?\b/i,
47
+ /工具.{0,6}(不能用|不可用|坏了|有\s*bug)/,
48
+ /无法(使用|调用|运行)\s*\w+工具/,
49
+ ];
50
+
51
+ /**
52
+ * 环境依赖失败禁词表(移植 `_DO_NOT_CAPTURE_BLOCK` 第 1 条)。
53
+ *
54
+ * 这类失败用户自己能修,写进技能就是噪音。
55
+ */
56
+ const ENV_FAILURE_PATTERNS = [
57
+ /command\s+not\s+found/i,
58
+ /no\s+such\s+file\s+or\s+directory/i,
59
+ /permission\s+denied/i,
60
+ /(not|isn'?t)\s+installed\b/i,
61
+ /\bunconfigured\b/i,
62
+ /\bmissing\s+(binary|dependency|package|credential)s?\b/i,
63
+ /找不到命令/,
64
+ /没有安装/,
65
+ /未配置/,
66
+ ];
67
+
68
+ /** 一次性任务叙事(移植 `_DO_NOT_CAPTURE_BLOCK` 第 4 条)。 */
69
+ const ONE_OFF_PATTERNS = [
70
+ /\b(summari[sz]e|analy[sz]e)\s+(today'?s|this|the)\s+(market|pr|report|data)\b/i,
71
+ /总结(今天|本次|这个)/,
72
+ ];
73
+
74
+ /**
75
+ * 校验技能名。
76
+ * @returns {{ok: boolean, error?: string}}
77
+ */
78
+ export function validateSkillName(name) {
79
+ if (typeof name !== "string" || !name.trim()) {
80
+ return { ok: false, error: "skill name is empty" };
81
+ }
82
+ const n = name.trim();
83
+ if (!KEBAB.test(n)) {
84
+ return { ok: false, error: `skill name "${n}" is not kebab-case (lowercase letters, digits, single hyphens)` };
85
+ }
86
+ if (n.length > 64) {
87
+ return { ok: false, error: `skill name "${n}" is too long (max 64 chars)` };
88
+ }
89
+ for (const re of SESSION_ARTIFACT_PATTERNS) {
90
+ if (re.test(n)) {
91
+ return {
92
+ ok: false,
93
+ error:
94
+ `skill name "${n}" looks like a session artifact, not a class of task. ` +
95
+ `Names must be class-level (e.g. "cordis-plugin-development"), never fix-X / debug-Y / PR numbers / dates.`,
96
+ };
97
+ }
98
+ }
99
+ if (LIBRARY_ONLY_HINTS.has(n)) {
100
+ return { ok: false, error: `skill name "${n}" is a bare library name; name the class of task instead` };
101
+ }
102
+ return { ok: true };
103
+ }
104
+
105
+ /**
106
+ * 扫描正文里的禁词。返回命中列表。
107
+ * @returns {{ok: boolean, violations: {kind: string, match: string}[]}}
108
+ */
109
+ export function scanForbiddenContent(text) {
110
+ const violations = [];
111
+ if (typeof text !== "string") return { ok: true, violations };
112
+ const checks = [
113
+ ["negative-claim", NEGATIVE_CLAIM_PATTERNS],
114
+ ["env-failure", ENV_FAILURE_PATTERNS],
115
+ ["one-off-narrative", ONE_OFF_PATTERNS],
116
+ ];
117
+ for (const [kind, patterns] of checks) {
118
+ for (const re of patterns) {
119
+ const m = re.exec(text);
120
+ if (m) violations.push({ kind, match: m[0] });
121
+ }
122
+ }
123
+ return { ok: violations.length === 0, violations };
124
+ }
125
+
126
+ /**
127
+ * 技能描述长度上限(对齐 Hermes `skill_utils.py:846` 的 `SKILL_PROMPT_DESC_LIMIT` 短触发窗)。
128
+ * 目录中的每个 description 每回合都会常驻上下文,且变更时会整表重发,因此必须严控在 80 字符以内。
129
+ */
130
+ export const MAX_SKILL_DESC_CHARS = 80;
131
+
132
+ /**
133
+ * 校验 frontmatter 对象。
134
+ * @returns {{ok: boolean, error?: string}}
135
+ */
136
+ export function validateFrontmatter(fm) {
137
+ if (!fm || typeof fm !== "object") return { ok: false, error: "frontmatter missing" };
138
+ const nameCheck = validateSkillName(fm.name);
139
+ if (!nameCheck.ok) return nameCheck;
140
+ if (typeof fm.description !== "string" || !fm.description.trim()) {
141
+ return { ok: false, error: "frontmatter.description is required and must be non-empty" };
142
+ }
143
+ if (fm.description.length > MAX_SKILL_DESC_CHARS) {
144
+ return {
145
+ ok: false,
146
+ error: `frontmatter.description is too long (${fm.description.length} > ${MAX_SKILL_DESC_CHARS} chars) — the skill index requires a concise trigger phrase (<= ${MAX_SKILL_DESC_CHARS} chars) to prevent prompt bloat`,
147
+ };
148
+ }
149
+ return { ok: true };
150
+ }
151
+
152
+ /** SKILL.md 正文长度上限。超过即拒绝——防止长引用让下次会话的 context 爆炸。 */
153
+ export const MAX_SKILL_BODY_CHARS = 24000;
154
+
155
+ /**
156
+ * 完整闸门:对一个候选产物做全部静态检查。
157
+ *
158
+ * @param {object} candidate
159
+ * @param {"create"|"patch"|"add_reference"} candidate.action
160
+ * @param {string} candidate.target
161
+ * @param {object} [candidate.frontmatter]
162
+ * @param {string} candidate.body
163
+ * @param {string} [candidate.filePath]
164
+ * @returns {{ok: boolean, errors: string[], warnings: string[]}}
165
+ */
166
+ export function gate(candidate) {
167
+ const errors = [];
168
+ const warnings = [];
169
+
170
+ const nameCheck = validateSkillName(candidate.target);
171
+ if (!nameCheck.ok) errors.push(nameCheck.error);
172
+
173
+ if (candidate.action === "add_reference") {
174
+ const fp = candidate.filePath ?? "";
175
+ if (!/^references\/[a-z0-9][a-z0-9._-]*\.md$/.test(fp)) {
176
+ errors.push(`add_reference filePath must match references/<topic>.md, got "${fp}"`);
177
+ }
178
+ if (/\d{4}-\d{2}-\d{2}/.test(fp)) {
179
+ errors.push(`reference filename must be topical, never date-stamped: "${fp}"`);
180
+ }
181
+ } else {
182
+ const fmCheck = validateFrontmatter(candidate.frontmatter);
183
+ if (!fmCheck.ok) errors.push(fmCheck.error);
184
+ if (candidate.frontmatter?.name && candidate.frontmatter.name !== candidate.target) {
185
+ errors.push(`frontmatter.name "${candidate.frontmatter.name}" != target "${candidate.target}"`);
186
+ }
187
+ }
188
+
189
+ if (typeof candidate.body !== "string" || !candidate.body.trim()) {
190
+ errors.push("body is empty");
191
+ } else {
192
+ if (candidate.body.length > MAX_SKILL_BODY_CHARS) {
193
+ errors.push(
194
+ `body is ${candidate.body.length} chars, over the ${MAX_SKILL_BODY_CHARS} limit — ` +
195
+ `split depth into references/ instead of growing SKILL.md`,
196
+ );
197
+ }
198
+ const scan = scanForbiddenContent(candidate.body);
199
+ for (const v of scan.violations) {
200
+ errors.push(
201
+ `forbidden content (${v.kind}): "${v.match}" — ` +
202
+ (v.kind === "negative-claim"
203
+ ? "negative claims about tools harden into refusals the agent cites against itself for months"
204
+ : v.kind === "env-failure"
205
+ ? "environment-dependent failures are fixable by the user, not durable rules"
206
+ : "one-off task narratives are not a class of work"),
207
+ );
208
+ }
209
+ // 软检查:追加式修补是坏味道
210
+ if (/\bUPDATE:\s*(actually|correction)/i.test(candidate.body)) {
211
+ warnings.push("body contains 'UPDATE: actually...' — fix the misleading sentence in place instead of appending");
212
+ }
213
+ if (/^#\s+.*\b(v\d+|version)\b/im.test(candidate.body)) {
214
+ warnings.push("body appears to embed a version header; skills should not carry version numbers");
215
+ }
216
+ }
217
+
218
+ return { ok: errors.length === 0, errors, warnings };
219
+ }
220
+
221
+ /** 把 frontmatter 对象 + body 组装成完整 SKILL.md 文本。 */
222
+ export function renderSkillMarkdown(frontmatter, body) {
223
+ const lines = ["---"];
224
+ for (const [k, v] of Object.entries(frontmatter)) {
225
+ if (v === undefined || v === null) continue;
226
+ if (typeof v === "object") {
227
+ lines.push(`${k}:`);
228
+ for (const [sk, sv] of Object.entries(v)) lines.push(` ${sk}: ${JSON.stringify(sv)}`);
229
+ } else {
230
+ lines.push(`${k}: ${JSON.stringify(v)}`);
231
+ }
232
+ }
233
+ lines.push("---", "", body.trim(), "");
234
+ return lines.join("\n");
235
+ }
236
+
237
+ /** 从 SKILL.md 文本里解析 frontmatter(极简 YAML 子集,够用即可)。 */
238
+ export function parseSkillMarkdown(text) {
239
+ if (typeof text !== "string") return null;
240
+ const m = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/.exec(text);
241
+ if (!m) return null;
242
+ const fm = {};
243
+ let nestedKey = null;
244
+ for (const raw of m[1].split(/\r?\n/)) {
245
+ if (!raw.trim() || raw.trim().startsWith("#")) continue;
246
+
247
+ // 缩进行 = 上一层 key 的子键(只支持一层嵌套,够 renderSkillMarkdown 用)
248
+ const indented = /^\s+\S/.test(raw);
249
+ if (indented && nestedKey) {
250
+ const sub = raw.trim();
251
+ const sIdx = sub.indexOf(":");
252
+ if (sIdx < 0) continue;
253
+ const sk = sub.slice(0, sIdx).trim();
254
+ let sv = sub.slice(sIdx + 1).trim();
255
+ if (sv.startsWith('"') && sv.endsWith('"')) {
256
+ try {
257
+ sv = JSON.parse(sv);
258
+ } catch {
259
+ sv = sv.slice(1, -1);
260
+ }
261
+ }
262
+ if (sk && typeof fm[nestedKey] === "object" && fm[nestedKey] !== null) fm[nestedKey][sk] = sv;
263
+ continue;
264
+ }
265
+
266
+ const line = raw.trimEnd();
267
+ const idx = line.indexOf(":");
268
+ if (idx < 0) continue;
269
+ const key = line.slice(0, idx).trim();
270
+ let value = line.slice(idx + 1).trim();
271
+ if (!key) continue;
272
+ if (value === "") {
273
+ // 可能是嵌套块的开始
274
+ fm[key] = {};
275
+ nestedKey = key;
276
+ continue;
277
+ }
278
+ nestedKey = null;
279
+ if (value.startsWith('"') && value.endsWith('"')) {
280
+ try {
281
+ value = JSON.parse(value);
282
+ } catch {
283
+ value = value.slice(1, -1);
284
+ }
285
+ }
286
+ fm[key] = value;
287
+ }
288
+ // 空对象没有子键 → 还原成空字符串,保持与旧行为一致
289
+ for (const [k, v] of Object.entries(fm)) {
290
+ if (v && typeof v === "object" && Object.keys(v).length === 0) fm[k] = "";
291
+ }
292
+ return { frontmatter: fm, body: m[2] ?? "" };
293
+ }