@hit-sudomaker/ccw 0.4.0 → 0.5.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/dist/skills.js CHANGED
@@ -1,264 +1,420 @@
1
1
  import path from 'node:path';
2
2
  import { fileURLToPath } from 'node:url';
3
- import { knownTitle } from './titles.js';
4
- import { bundledSkills, skillMembers, skillSuites } from './management-catalog.js';
5
- import { errorCode, isObject } from './machine.js';
6
- import { json, kindOf, restOf, sequence, success, unchanged } from './model.js';
7
- import { currentSkill, disableSkillEntry, prepareSkillFiles, repairSkillSource, skillFilesStamp, } from './skill-files.js';
3
+ import { stripVTControlCharacters } from 'node:util';
4
+ import { knownTitle, catalogEntry, BUNDLED_SKILLS, SKILL_ENTRY, SKILL_MEMBERS, SKILL_SUITES, SKILLS_CLI, } from './management-catalog.js';
5
+ import { isObject, isGitRevision, errorCode } from './machine.js';
6
+ import { json, object, kindOf, restOf, success, normalizePath, unchanged, commandReceipt } from './model.js';
7
+ import { sourcesFile, disableSkillEntry, ownsSkill, checkSkillSource } from './skill-files.js';
8
+ import { step, work } from './work.js';
9
+ import { jsonFingerprint } from './frozen-json.js';
8
10
  const ASSET_ROOT = fileURLToPath(new URL('../assets/', import.meta.url));
9
- function memberSuite(name) {
10
- const member = Object.entries(skillMembers).find(([id]) => id === name)?.[1];
11
- return member === undefined ? undefined : skillSuites[member.suite];
12
- }
13
- function assertRelativeSkillPath(value) {
14
- if (!value ||
15
- value.includes('\\') ||
16
- value.includes(':') ||
17
- path.isAbsolute(value) ||
18
- value.split('/').some(part => part === '.' || part === '..' || part === ''))
19
- throw new Error('invalid-target');
20
- }
21
- /** 固定 Git 来源与载荷 */
22
- async function gitSkillSource(ctx, source) {
23
- assertRelativeSkillPath(source.folder);
24
- const revision = success(await ctx.machine.execute('git', ['ls-remote', source.repository, 'HEAD'])).split(/\s+/)[0];
25
- if (!revision || !/^[a-f0-9]{40}$/.test(revision))
26
- throw new Error('source-unavailable');
27
- const files = await ctx.machine.source(source.repository, revision, source.folder);
28
- return { repository: source.repository, revision, files };
29
- }
30
- async function memberSkillSource(ctx, name) {
31
- const bundled = Object.entries(bundledSkills).find(([id]) => id === name)?.[1];
32
- if (bundled !== undefined) {
33
- assertRelativeSkillPath(bundled.asset);
34
- const text = await ctx.machine.read(path.join(ASSET_ROOT, bundled.asset));
35
- if (!text?.trim())
36
- throw new Error('skill-payload-missing');
37
- return {
38
- repository: bundled.repository,
39
- revision: bundled.revision,
40
- files: [{ path: 'SKILL.md', data: Buffer.from(text) }],
41
- };
42
- }
43
- const source = memberSuite(name);
44
- if (source === undefined)
45
- throw new Error('not-in-update-catalog');
46
- return gitSkillSource(ctx, { repository: source.repository, folder: `${source.folder}/${name}` });
47
- }
48
- /** 读取来源记录:损坏或不可读时保持未知,不以查无代替 */
49
- async function readSkillMetadata(ctx) {
50
- try {
51
- return await json(ctx.machine, path.join(ctx.storage, 'sources.json'));
52
- }
53
- catch (error) {
54
- throw new Error('source-metadata-unavailable', { cause: error });
55
- }
56
- }
57
- /** 创建技能域渠道:余段即名字,组别由 kind 决定 */
11
+ const MAX_SKILL_DIRECTORY_LENGTH = 255;
12
+ /**
13
+ * 按固定来源管理技能及套件
14
+ *
15
+ * @remarks 官方 CLI 负责发现和安装,CCW 限定清理范围并记录归属
16
+ * 检查错误归入对应条目,不中断其他技能
17
+ */
58
18
  export function createSkillsDomain(ctx) {
59
19
  return {
60
- inspect: () => inspectSkills(ctx),
20
+ async inspect() {
21
+ let records = {};
22
+ let problem;
23
+ try {
24
+ records = await metadata(ctx);
25
+ }
26
+ catch (error) {
27
+ problem = errorCode(error);
28
+ }
29
+ const names = new Set([
30
+ ...Object.keys(SKILL_MEMBERS),
31
+ ...Object.keys(BUNDLED_SKILLS),
32
+ ...Object.keys(records)
33
+ .filter(directory => path.dirname(directory) === path.join(ctx.claudeRoot, 'skills') && suiteFor(records[directory]))
34
+ .map(directory => path.basename(directory)),
35
+ ]);
36
+ const items = [];
37
+ for (const name of names) {
38
+ validName(name);
39
+ const directory = path.join(ctx.claudeRoot, 'skills', name);
40
+ const record = records[directory];
41
+ const suite = Object.entries(SKILL_SUITES).find(([, value]) => isObject(record) && record.repository === value.repository)?.[0];
42
+ const item = {
43
+ id: 'skill:' + name,
44
+ title: knownTitle('skill:' + name, name),
45
+ kind: 'skill',
46
+ location: directory,
47
+ ...(suite ? { skillSet: suite } : {}),
48
+ canInstall: Object.hasOwn(BUNDLED_SKILLS, name),
49
+ };
50
+ try {
51
+ const stamp = await ctx.machine.treeStamp(directory);
52
+ const present = stamp !== null && !!(await ctx.machine.read(path.join(directory, SKILL_ENTRY)))?.trim();
53
+ const issue = problem ?? (stamp !== null && !present ? 'skill-entry-missing' : undefined);
54
+ items.push({
55
+ ...item,
56
+ canUninstall: ownsSkill(record, repositoryFor(name, record), stamp),
57
+ facts: [{ code: present ? 'entry-exists' : 'not-installed' }],
58
+ ...(issue ? { problem: issue } : {}),
59
+ });
60
+ }
61
+ catch (error) {
62
+ items.push({ ...item, facts: [], problem: errorCode(error) });
63
+ }
64
+ }
65
+ for (const [name, suite] of Object.entries(SKILL_SUITES)) {
66
+ const members = items.filter(item => item.skillSet === name);
67
+ const count = members.filter(item => item.facts.some(fact => fact.code === 'entry-exists')).length;
68
+ const issue = problem ?? members.find(item => item.problem)?.problem;
69
+ items.push({
70
+ id: 'skill-set:' + name,
71
+ title: suite.title,
72
+ kind: 'skill',
73
+ location: path.join(ctx.claudeRoot, 'skills'),
74
+ canInstall: true,
75
+ canUninstall: members.some(item => item.canUninstall),
76
+ facts: count ? [{ code: 'skill-members-present', detail: String(count) }] : [{ code: 'not-installed' }],
77
+ ...(issue ? { problem: issue } : {}),
78
+ });
79
+ }
80
+ return { items, problems: [] };
81
+ },
61
82
  prepare(selection) {
62
83
  const name = restOf(selection.id);
63
- if (name === undefined)
84
+ if (!name)
64
85
  throw new Error('unknown-selection');
65
- const kind = kindOf(selection.id);
66
- if (kind === 'skill-set')
67
- return prepareSkillSet(ctx, name, selection);
68
- if (kind === 'skill' || kind === 'command')
69
- return prepareSkill(ctx, name, kind === 'skill' ? 'skills' : 'commands', selection);
70
- throw new Error('unknown-selection');
86
+ const shouldDetach = selection.action === 'detach';
87
+ return kindOf(selection.id) === 'skill-set'
88
+ ? prepareSuite(ctx, name, shouldDetach)
89
+ : prepareSkill(ctx, name, shouldDetach);
71
90
  },
72
91
  };
73
92
  }
74
- async function inspectSkills(ctx) {
75
- const result = [];
76
- let metadata = {};
77
- const problems = [];
78
- try {
79
- metadata = await json(ctx.machine, path.join(ctx.storage, 'sources.json'));
93
+ /**
94
+ * 找出与同批套件计划覆盖目录重叠的单项技能
95
+ *
96
+ * @param prepared - 已准备计划的目录范围;尚未准备的条目按无目录处理
97
+ * @returns 需要按重叠处理的单项技能 ID 集合,不修改选择或计划
98
+ */
99
+ export function overlappingSkillSelections(ctx, selections, prepared) {
100
+ const targets = (id) => prepared.get(id)?.skillDirectories?.map(directory => normalizePath(ctx.platform, directory)) ?? [];
101
+ const suiteTargets = new Set(selections.filter(selection => kindOf(selection.id) === 'skill-set').flatMap(selection => targets(selection.id)));
102
+ return new Set(selections
103
+ .filter(selection => kindOf(selection.id) === 'skill' && targets(selection.id).some(target => suiteTargets.has(target)))
104
+ .map(selection => selection.id));
105
+ }
106
+ async function prepareSkill(ctx, name, shouldDetach) {
107
+ validName(name);
108
+ const directory = path.join(ctx.claudeRoot, 'skills', name);
109
+ const records = await metadata(ctx);
110
+ const record = records[directory];
111
+ const before = await ctx.machine.treeStamp(directory);
112
+ if (shouldDetach) {
113
+ if (before === null)
114
+ throw new Error('no-connection');
115
+ const repository = repositoryFor(name, record);
116
+ if (!repository)
117
+ throw new Error('integration-source-conflict');
118
+ checkSkillSource(record, repository);
119
+ if (!ownsSkill(record, repository, before))
120
+ throw new Error('local-edits-preserved');
121
+ return disableSkillEntry(ctx, directory, before, record);
80
122
  }
81
- catch {
82
- problems.push({ code: 'source-metadata-unavailable', detail: path.join(ctx.storage, 'sources.json') });
123
+ const bundled = catalogEntry(BUNDLED_SKILLS, name);
124
+ if (bundled) {
125
+ const source = path.dirname(path.join(ASSET_ROOT, bundled.asset));
126
+ return refresh(ctx, { ...bundled, source, stamp: await ctx.machine.treeStamp(source) }, records, [name]);
83
127
  }
84
- for (const group of ['skills', 'commands']) {
85
- const root = path.join(ctx.claudeRoot, group);
86
- const collect = async (directory) => {
87
- let entries;
88
- try {
89
- entries = await ctx.machine.entries(directory);
128
+ const member = catalogEntry(SKILL_MEMBERS, name);
129
+ const suite = member ? SKILL_SUITES[member.suite] : suiteFor(record);
130
+ if (!suite)
131
+ throw new Error('not-in-update-catalog');
132
+ return refresh(ctx, await remoteSource(ctx, suite.repository, suite.folder + '/' + name), records, [name]);
133
+ }
134
+ async function prepareSuite(ctx, name, shouldDetach) {
135
+ const suite = catalogEntry(SKILL_SUITES, name);
136
+ if (!suite)
137
+ throw new Error('unknown-selection');
138
+ const records = await metadata(ctx);
139
+ if (shouldDetach) {
140
+ const children = [];
141
+ for (const [directory, record] of Object.entries(records)) {
142
+ if (path.dirname(directory) !== path.join(ctx.claudeRoot, 'skills') ||
143
+ !isObject(record) ||
144
+ record.repository !== suite.repository ||
145
+ repositoryFor(path.basename(directory), record) !== suite.repository)
146
+ continue;
147
+ const stamp = await ctx.machine.treeStamp(directory);
148
+ if (stamp !== record.stamp)
149
+ throw new Error('local-edits-preserved');
150
+ if (stamp !== null)
151
+ children.push(disableSkillEntry(ctx, directory, stamp, record));
152
+ }
153
+ if (!children.length)
154
+ throw new Error('no-connection');
155
+ return work(children);
156
+ }
157
+ return refresh(ctx, await remoteSource(ctx, suite.repository, suite.folder), records);
158
+ }
159
+ async function refresh(ctx, source, records, selected) {
160
+ const root = path.join(ctx.claudeRoot, 'skills');
161
+ const verifyRoots = async () => {
162
+ for (const directory of [root, path.join(ctx.storage, 'skills'), path.join(ctx.storage, 'skills-cli')]) {
163
+ let parent = directory;
164
+ while (true) {
165
+ const real = await ctx.machine.realpath(parent);
166
+ if (real !== null) {
167
+ if (normalizePath(ctx.platform, real) !== normalizePath(ctx.platform, parent))
168
+ throw new Error('linked-parent');
169
+ break;
170
+ }
171
+ const ancestor = path.dirname(parent);
172
+ if (ancestor === parent)
173
+ throw new Error('invalid-config-root');
174
+ parent = ancestor;
90
175
  }
91
- catch (error) {
92
- problems.push({ code: errorCode(error), detail: directory });
93
- return;
176
+ }
177
+ };
178
+ await verifyRoots();
179
+ const listing = success(await ctx.machine.npm([...SKILLS_CLI, 'a', source.source, '--list'], { env: cliEnvironment(ctx) }), 'skill-source-unavailable');
180
+ const available = listedSkills(listing);
181
+ const lockFiles = [
182
+ path.join(ctx.home, '.agents/.skill-lock.json'),
183
+ path.join(ctx.storage, 'skills/.skill-lock.json'),
184
+ ];
185
+ const locks = await Promise.all(lockFiles.map(async (file) => {
186
+ const skills = object((await json(ctx.machine, file)).skills);
187
+ return { file, skills };
188
+ }));
189
+ const repositoryName = source.repository.replace('https://github.com/', '');
190
+ const officialNames = new Set(locks.flatMap(lock => Object.entries(lock.skills)
191
+ .filter(([, record]) => isObject(record) && record.sourceType === 'github' && record.source === repositoryName)
192
+ .map(([name]) => installedName(name))));
193
+ const entries = await ctx.machine.entries(root);
194
+ const names = selected ? [...selected] : available;
195
+ if (names.some(name => !available.includes(name)))
196
+ throw new Error('skill-payload-missing');
197
+ const oldNames = selected ?? [
198
+ ...officialNames,
199
+ ...Object.entries(records)
200
+ .filter(([directory, record]) => path.dirname(directory) === root && isObject(record) && record.repository === source.repository)
201
+ .map(([directory]) => path.basename(directory)),
202
+ ];
203
+ const targets = await Promise.all([...new Set([...names, ...oldNames])].map(async (name) => {
204
+ validName(name);
205
+ const directory = path.join(root, name);
206
+ const record = records[directory];
207
+ const before = await ctx.machine.treeStamp(directory);
208
+ checkSkillSource(record, source.repository);
209
+ if (before !== null &&
210
+ !ownsSkill(record, source.repository, before) &&
211
+ !(officialNames.has(name) && entries.find(entry => entry.name === name)?.kind === 'link') &&
212
+ (await ctx.machine.entries(directory)).length)
213
+ throw new Error('local-edits-preserved');
214
+ return { name, directory, record, before };
215
+ }));
216
+ const installed = new Map();
217
+ const removed = new Set();
218
+ const targetNames = new Set(targets.map(target => target.name));
219
+ // 共享锁会被同批其他来源更新,只冻结当前来源及目标名称
220
+ const lockScope = (skills) => Object.fromEntries(Object.entries(skills).filter(([name, record]) => targetNames.has(installedName(name)) ||
221
+ (isObject(record) && record.sourceType === 'github' && record.source === repositoryName)));
222
+ const verifyBefore = async () => {
223
+ await verifyRoots();
224
+ const current = await metadata(ctx);
225
+ if (source.stamp !== undefined)
226
+ unchanged(await ctx.machine.treeStamp(source.source), source.stamp);
227
+ for (const lock of locks)
228
+ unchanged(lockScope(object((await json(ctx.machine, lock.file)).skills)), lockScope(lock.skills));
229
+ for (const target of targets) {
230
+ unchanged(await ctx.machine.treeStamp(target.directory), target.before);
231
+ unchanged(jsonFingerprint(current[target.directory]), jsonFingerprint(target.record));
232
+ }
233
+ };
234
+ const operation = step([{ code: 'skills-refresh', detail: `${names.length} · ${source.repository}` }], async (fact) => {
235
+ if (!fact.dispatched) {
236
+ await verifyBefore();
237
+ return { state: 'ready' };
238
+ }
239
+ for (const target of targets) {
240
+ const expected = installed.get(target.name) ?? null;
241
+ if ((await ctx.machine.treeStamp(target.directory)) !== expected)
242
+ return { state: 'blocked', problem: fact.receipt?.failure ?? 'skill-install-unconfirmed' };
243
+ }
244
+ if (names.some(name => !installed.has(name)))
245
+ return { state: 'blocked', problem: fact.receipt?.failure ?? 'skill-install-unconfirmed' };
246
+ if (fact.receipt?.failure)
247
+ return { state: 'blocked', problem: fact.receipt.failure };
248
+ return { state: 'complete' };
249
+ }, async (signal, verify) => {
250
+ const effects = [];
251
+ let receipt;
252
+ try {
253
+ await verifyBefore();
254
+ const existing = targets.filter(target => target.before !== null);
255
+ if (existing.length) {
256
+ const privateHome = path.join(ctx.storage, 'skills-cli');
257
+ try {
258
+ success(await ctx.effects.npm([
259
+ ...SKILLS_CLI,
260
+ 'remove',
261
+ ...existing.map(target => target.name),
262
+ '--global',
263
+ '--agent',
264
+ 'claude-code',
265
+ '--yes',
266
+ ], {
267
+ env: { ...cliEnvironment(ctx), HOME: privateHome, USERPROFILE: privateHome },
268
+ ...(signal ? { signal } : {}),
269
+ }), 'skill-remove-failed');
270
+ }
271
+ finally {
272
+ await verify(async () => {
273
+ for (const target of existing)
274
+ if ((await ctx.machine.treeStamp(target.directory)) === null) {
275
+ removed.add(target.name);
276
+ effects.push({ state: 'done', code: 'skill-removed', detail: target.name });
277
+ }
278
+ });
279
+ }
94
280
  }
95
- for (const entry of entries) {
96
- if (entry.name.startsWith('.'))
97
- continue;
98
- const location = path.join(directory, entry.name);
99
- if (group === 'commands' && entry.kind === 'directory') {
100
- await collect(location);
101
- continue;
281
+ for (const target of targets) {
282
+ let current = await ctx.machine.treeStamp(target.directory);
283
+ if (current !== null &&
284
+ current === target.before &&
285
+ (await ctx.machine.entries(target.directory)).length === 0) {
286
+ await ctx.effects.removeTree(target.directory, current);
287
+ current = null;
102
288
  }
103
- if (group === 'commands' && entry.kind !== 'link' && (entry.kind !== 'file' || !entry.name.endsWith('.md')))
104
- continue;
105
- if (group === 'skills' && entry.kind !== 'directory' && entry.kind !== 'link')
106
- continue;
107
- let problem;
108
- if (group === 'skills') {
109
- try {
110
- const text = await ctx.machine.read(path.join(location, 'SKILL.md'));
111
- if (text === null && entry.kind === 'directory')
289
+ if (current !== null)
290
+ throw new Error('skill-remove-failed');
291
+ if (target.before !== null && !removed.has(target.name))
292
+ effects.push({ state: 'done', code: 'skill-removed', detail: target.name });
293
+ removed.add(target.name);
294
+ }
295
+ const result = await ctx.effects.npm([
296
+ ...SKILLS_CLI,
297
+ 'a',
298
+ source.source,
299
+ '--skill',
300
+ ...(selected ?? ['*']),
301
+ '--agent',
302
+ 'claude-code',
303
+ '--global',
304
+ '--yes',
305
+ '--copy',
306
+ '--json',
307
+ ], { env: cliEnvironment(ctx), ...(signal ? { signal } : {}) });
308
+ receipt = commandReceipt(result, 'skill-command-failed');
309
+ const entries = JSON.parse(result.stdout);
310
+ if (!Array.isArray(entries))
311
+ throw new Error('skill-cli-output-invalid');
312
+ await verify(async () => {
313
+ for (const entry of entries) {
314
+ if (!isObject(entry) || entry.status !== 'installed')
315
+ continue;
316
+ const name = typeof entry.name === 'string' ? installedName(entry.name) : undefined;
317
+ const target = targets.find(target => target.name === name && names.includes(target.name));
318
+ if (!target ||
319
+ entry.scope !== 'global' ||
320
+ entry.mode !== 'copy' ||
321
+ !Array.isArray(entry.agents) ||
322
+ entry.agents.length !== 1 ||
323
+ entry.agents[0] !== 'Claude Code' ||
324
+ typeof entry.path !== 'string' ||
325
+ normalizePath(ctx.platform, entry.path) !== normalizePath(ctx.platform, target.directory))
326
+ throw new Error('skill-cli-output-invalid');
327
+ const text = await ctx.machine.read(path.join(target.directory, SKILL_ENTRY));
328
+ const stamp = await ctx.machine.treeStamp(target.directory);
329
+ if (!text?.trim() || stamp === null)
330
+ throw new Error('skill-payload-missing');
331
+ installed.set(target.name, stamp);
332
+ effects.push({ state: 'done', code: 'skill-installed', detail: target.name });
333
+ }
334
+ });
335
+ }
336
+ catch (error) {
337
+ receipt = { kind: 'unknown', failure: errorCode(error) };
338
+ }
339
+ // 部分失败仍登记已核实结果,仅修改本次来源的记录
340
+ if (removed.size) {
341
+ try {
342
+ await ctx.effects.editJson(sourcesFile(ctx), current => {
343
+ for (const target of targets) {
344
+ if (!removed.has(target.name))
112
345
  continue;
113
- if (!text?.trim())
114
- problem = 'skill-entry-invalid';
115
- }
116
- catch (error) {
117
- problem = errorCode(error);
346
+ unchanged(jsonFingerprint(current[target.directory]), jsonFingerprint(target.record));
347
+ const stamp = installed.get(target.name);
348
+ if (stamp)
349
+ current[target.directory] = { repository: source.repository, revision: source.revision, stamp };
350
+ else
351
+ delete current[target.directory];
118
352
  }
119
- }
120
- const name = path.relative(root, location).split(path.sep).join('/');
121
- const isOffered = group === 'skills' && (Object.hasOwn(skillMembers, name) || Object.hasOwn(bundledSkills, name));
122
- const saved = metadata[location];
123
- const skillSet = group === 'skills'
124
- ? Object.entries(skillSuites).find(([, source]) => source.repository === (isObject(saved) ? saved.repository : memberSuite(name)?.repository))?.[0]
125
- : undefined;
126
- // 已发现条目标题用内联键真身(目录名/相对名):与磁盘及 Claude 所见一致,
127
- // 官方名只归方案入口承载——用户据此知道自己装的是什么、怎么解除
128
- result.push({
129
- id: `${group === 'skills' ? 'skill' : 'command'}:${name}`,
130
- title: name,
131
- kind: group === 'skills' ? 'skill' : 'command',
132
- location,
133
- ...(Object.hasOwn(bundledSkills, name) ? { canInstall: true } : {}),
134
- ...(skillSet ? { skillSet } : {}),
135
- facts: [{ code: entry.kind === 'link' ? 'shared-link' : 'entry-exists' }],
136
- ...(problem ? { problem } : {}),
137
- actions: isOffered ? ['update', 'detach'] : ['detach'],
138
353
  });
139
354
  }
140
- };
141
- await collect(root);
142
- }
143
- for (const name of Object.keys(bundledSkills)) {
144
- if (result.some(item => item.id === `skill:${name}`))
145
- continue;
146
- result.push({
147
- id: `skill:${name}`,
148
- title: knownTitle(`skill:${name}`, name),
149
- kind: 'skill',
150
- canInstall: true,
151
- facts: [{ code: 'not-installed' }],
152
- actions: ['install'],
153
- });
154
- }
155
- // 方案入口只有整套套件;检查只列实际发现的成员,不虚构未安装的成员占位
156
- for (const id of Object.keys(skillSuites))
157
- result.push({
158
- id: `skill-set:${id}`,
159
- title: knownTitle(`skill-set:${id}`),
160
- kind: 'skill',
161
- canInstall: true,
162
- facts: [],
163
- actions: ['install'],
164
- });
165
- return { items: result, problems };
355
+ catch {
356
+ effects.push({ state: 'kept', code: 'source-metadata-unavailable' });
357
+ }
358
+ }
359
+ return { receipt, effects };
360
+ });
361
+ return {
362
+ ...operation,
363
+ action: targets.some(target => target.before !== null) ? 'update' : 'install',
364
+ skillDirectories: targets.map(target => target.directory),
365
+ };
166
366
  }
167
- /** 安装整套技能,只补齐缺失成员,保留已有内容 */
168
- async function prepareSkillSet(ctx, name, selection) {
169
- const source = Object.entries(skillSuites).find(([id]) => id === name)?.[1];
170
- if (!source || selection.action !== 'install')
171
- throw new Error('action-unavailable');
172
- const { revision, files } = await gitSkillSource(ctx, source);
173
- const candidates = files
174
- .filter(file => /^(?:[\w.-]+\/)+SKILL\.md$/.test(file.path) && file.data.length > 0)
175
- .map(file => path.posix.dirname(file.path))
176
- .filter(folder => folder.split('/').every(part => part !== '.' && part !== '..'))
177
- .sort((a, b) => a.length - b.length || a.localeCompare(b));
178
- const folders = [];
179
- for (const folder of candidates) {
180
- // 技能内部的示例 SKILL.md 属于原技能资源,不是另一个安装项
181
- if (!folders.some(parent => folder.startsWith(`${parent}/`)))
182
- folders.push(folder);
183
- }
184
- if (!folders.length)
367
+ function cliEnvironment(ctx) {
368
+ return { CLAUDE_CONFIG_DIR: ctx.claudeRoot, XDG_STATE_HOME: ctx.storage, NO_COLOR: '1', FORCE_COLOR: undefined };
369
+ }
370
+ function listedSkills(output) {
371
+ const plain = stripVTControlCharacters(output);
372
+ const listed = plain.split('Available Skills')[1];
373
+ const end = 'Use --skill <name> to install specific skills';
374
+ if (!listed?.includes(end))
375
+ throw new Error('skill-cli-output-invalid');
376
+ const section = listed.split(end)[0];
377
+ const names = [...section.matchAll(/^[│|] {4}(\S[^\r\n]*)/gm)].map(match => installedName(match[1]));
378
+ if (!names.length)
185
379
  throw new Error('skill-payload-missing');
186
- const names = folders.map(folder => path.posix.basename(folder).toLowerCase());
187
- if (new Set(names).size !== names.length)
380
+ names.forEach(validName);
381
+ if (new Set(names.map(name => name.toLowerCase())).size !== names.length)
188
382
  throw new Error('skill-name-conflict');
189
- const operations = [];
190
- const metadata = await readSkillMetadata(ctx);
191
- for (const folder of folders) {
192
- const member = path.posix.basename(folder);
193
- const directory = path.join(ctx.claudeRoot, 'skills', member);
194
- const before = await ctx.machine.treeStamp(directory);
195
- const entry = before === null ? null : await ctx.machine.read(path.join(directory, 'SKILL.md'));
196
- const isEmptyDirectory = before !== null && entry === null && (await ctx.machine.entries(directory)).length === 0;
197
- if (before !== null && !isEmptyDirectory) {
198
- if (entry === null || !entry.trim())
199
- throw new Error('local-edits-preserved');
200
- operations.push({
201
- changes: [{ code: 'skill-existing-kept', detail: member }],
202
- async verify() {
203
- unchanged(await ctx.machine.treeStamp(directory), before);
204
- },
205
- async run(report) {
206
- unchanged(await ctx.machine.treeStamp(directory), before);
207
- report({ state: 'kept', code: 'skill-existing-kept', detail: member });
208
- },
209
- });
210
- continue;
211
- }
212
- const payload = files
213
- .filter(file => file.path.startsWith(`${folder}/`))
214
- .map(file => ({ ...file, path: file.path.slice(folder.length + 1) }));
215
- operations.push(prepareSkillFiles(ctx, { name: member, directory, stamp: before, sourceRecord: metadata[directory] }, { repository: source.repository, revision, files: payload, stamp: skillFilesStamp(payload) }));
216
- }
217
- return sequence(operations);
383
+ return names;
218
384
  }
219
- export async function prepareSkill(ctx, name, group, selection) {
220
- if (!name ||
221
- name.includes('\\') ||
222
- name.includes(':') ||
223
- path.isAbsolute(name) ||
224
- name.split('/').some(part => part === '.' || part === '..' || part === '') ||
225
- (group === 'skills' && name.includes('/')))
226
- throw new Error('invalid-target');
227
- const directory = path.join(ctx.claudeRoot, group, name);
228
- const before = await ctx.machine.treeStamp(directory);
229
- const action = selection.action;
230
- if (!['install', 'update', 'detach'].includes(action))
231
- throw new Error('action-unavailable');
232
- if (action === 'detach') {
233
- if (before === null)
234
- throw new Error('no-connection');
235
- return disableSkillEntry(ctx, directory, before);
385
+ // CLI 显示名需按其规则转换为目录名
386
+ function installedName(name) {
387
+ return (name
388
+ .toLowerCase()
389
+ .replace(/[^a-z0-9._]+/g, '-')
390
+ .replace(/^[.-]+|[.-]+$/g, '')
391
+ .slice(0, MAX_SKILL_DIRECTORY_LENGTH) || 'unnamed-skill');
392
+ }
393
+ async function remoteSource(ctx, repository, folder) {
394
+ const revision = success(await ctx.machine.execute('git', ['ls-remote', repository, 'HEAD'])).split(/\s+/)[0];
395
+ if (!revision || !isGitRevision(revision))
396
+ throw new Error('source-unavailable');
397
+ return { repository, revision, source: `${repository}/tree/${revision}/${folder}` };
398
+ }
399
+ async function metadata(ctx) {
400
+ try {
401
+ return await json(ctx.machine, sourcesFile(ctx));
236
402
  }
237
- if (action === 'install' &&
238
- before !== null &&
239
- selection.fields?.replace !== 'yes' &&
240
- (await ctx.machine.read(path.join(directory, 'SKILL.md')))?.trim())
241
- return currentSkill(ctx, name, directory, before);
242
- if (!Object.hasOwn(skillMembers, name) && !(group === 'skills' && Object.hasOwn(bundledSkills, name)))
243
- throw new Error('not-in-update-catalog');
244
- const metadata = await readSkillMetadata(ctx);
245
- const saved = metadata[directory];
246
- const { repository, revision, files } = await memberSkillSource(ctx, name);
247
- const expected = skillFilesStamp(files);
248
- const target = { name, directory, stamp: before, sourceRecord: saved };
249
- const release = { repository, revision, files, stamp: expected };
250
- if (before !== null && (!isObject(saved) || saved.stamp !== before) && selection.fields?.replace !== 'yes') {
251
- if (before === expected)
252
- return repairSkillSource(ctx, target, release);
253
- throw new Error('local-edits-preserved');
403
+ catch {
404
+ throw new Error('source-metadata-unavailable');
254
405
  }
255
- if (before !== null &&
256
- isObject(saved) &&
257
- saved.stamp === before &&
258
- saved.revision === revision &&
259
- before === expected)
260
- return currentSkill(ctx, name, directory, before);
261
- if (before === expected)
262
- return repairSkillSource(ctx, target, release);
263
- return prepareSkillFiles(ctx, target, release);
406
+ }
407
+ function repositoryFor(name, record) {
408
+ const bundled = catalogEntry(BUNDLED_SKILLS, name);
409
+ const member = catalogEntry(SKILL_MEMBERS, name);
410
+ return bundled?.repository ?? (member ? SKILL_SUITES[member.suite].repository : suiteFor(record)?.repository);
411
+ }
412
+ function suiteFor(record) {
413
+ return isObject(record)
414
+ ? Object.values(SKILL_SUITES).find(suite => suite.repository === record.repository)
415
+ : undefined;
416
+ }
417
+ function validName(name) {
418
+ if (!/^[\w.-]+$/.test(name) || name === '.' || name === '..')
419
+ throw new Error('invalid-target');
264
420
  }