@hit-sudomaker/ccw 0.4.1 → 0.5.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.
package/dist/skills.js CHANGED
@@ -1,286 +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, SKILL_ENTRY, skillMembers, skillSuites } from './management-catalog.js';
5
- import { errorCode, isGitRevision, isObject } from './machine.js';
6
- import { json, kindOf, REPLACE_CONSENT, restOf, sequence, success, unchanged } from './model.js';
7
- import { currentSkill, disableSkillEntry, prepareSkillFiles, repairSkillSource, skillFilesStamp, } from './skill-files.js';
8
- import { sourcesFile } from './storage.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';
9
10
  const ASSET_ROOT = fileURLToPath(new URL('../assets/', import.meta.url));
10
- function memberSuite(name) {
11
- const member = Object.entries(skillMembers).find(([id]) => id === name)?.[1];
12
- return member === undefined ? undefined : skillSuites[member.suite];
13
- }
14
- function assertRelativeSkillPath(value) {
15
- if (!value ||
16
- value.includes('\\') ||
17
- value.includes(':') ||
18
- path.isAbsolute(value) ||
19
- value.split('/').some(part => part === '.' || part === '..' || part === ''))
20
- throw new Error('invalid-target');
21
- }
22
- /** 固定 Git 来源与载荷 */
23
- /** 套件载荷内技能入口的路径形状(入口名单一出处 SKILL_ENTRY) */
24
- const suiteEntryPattern = new RegExp(`^(?:[\\w.-]+/)+${SKILL_ENTRY.replaceAll('.', '\\.')}$`);
25
- async function gitSkillSource(ctx, source) {
26
- assertRelativeSkillPath(source.folder);
27
- const revision = success(await ctx.machine.execute('git', ['ls-remote', source.repository, 'HEAD'])).split(/\s+/)[0];
28
- if (!revision || !isGitRevision(revision))
29
- throw new Error('source-unavailable');
30
- const files = await ctx.machine.source(source.repository, revision, source.folder);
31
- return { repository: source.repository, revision, files };
32
- }
33
- /** 从来源记录反查套件:未登记成员(如 mattpocock 成员)凭 sources.json 获得更新来源 */
34
- function suiteOfRecord(saved) {
35
- const repository = isObject(saved) ? saved.repository : undefined;
36
- return typeof repository === 'string'
37
- ? Object.values(skillSuites).find(source => source.repository === repository)
38
- : undefined;
39
- }
40
- async function memberSkillSource(ctx, name, saved) {
41
- const bundled = Object.entries(bundledSkills).find(([id]) => id === name)?.[1];
42
- if (bundled !== undefined) {
43
- assertRelativeSkillPath(bundled.asset);
44
- const text = await ctx.machine.read(path.join(ASSET_ROOT, bundled.asset));
45
- if (!text?.trim())
46
- throw new Error('skill-payload-missing');
47
- return {
48
- repository: bundled.repository,
49
- revision: bundled.revision,
50
- files: [{ path: SKILL_ENTRY, data: Buffer.from(text) }],
51
- };
52
- }
53
- const source = memberSuite(name) ?? (name.includes('/') ? undefined : suiteOfRecord(saved));
54
- if (source === undefined)
55
- throw new Error('not-in-update-catalog');
56
- return gitSkillSource(ctx, { repository: source.repository, folder: `${source.folder}/${name}` });
57
- }
58
- /** 读取来源记录:损坏或不可读时保持未知,不以查无代替 */
59
- async function readSkillMetadata(ctx) {
60
- try {
61
- return await json(ctx.machine, sourcesFile(ctx));
62
- }
63
- catch (error) {
64
- throw new Error('source-metadata-unavailable', { cause: error });
65
- }
66
- }
67
- /** 创建技能域渠道:余段即名字,组别由 kind 决定 */
11
+ const MAX_SKILL_DIRECTORY_LENGTH = 255;
12
+ /**
13
+ * 按固定来源管理技能及套件
14
+ *
15
+ * @remarks 官方 CLI 负责发现和安装,CCW 限定清理范围并记录归属
16
+ * 检查错误归入对应条目,不中断其他技能
17
+ */
68
18
  export function createSkillsDomain(ctx) {
69
19
  return {
70
- 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
+ },
71
82
  prepare(selection) {
72
83
  const name = restOf(selection.id);
73
- if (name === undefined)
84
+ if (!name)
74
85
  throw new Error('unknown-selection');
75
- const kind = kindOf(selection.id);
76
- if (kind === 'skill-set')
77
- return prepareSkillSet(ctx, name, selection);
78
- if (kind === 'skill' || kind === 'command')
79
- return prepareSkill(ctx, name, kind === 'skill' ? 'skills' : 'commands', selection);
80
- 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);
81
90
  },
82
91
  };
83
92
  }
84
- async function inspectSkills(ctx) {
85
- const result = [];
86
- let metadata = {};
87
- let metadataReadable = true;
88
- const problems = [];
89
- try {
90
- metadata = await json(ctx.machine, sourcesFile(ctx));
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);
91
122
  }
92
- catch {
93
- metadataReadable = false;
94
- problems.push({ code: 'source-metadata-unavailable', detail: sourcesFile(ctx) });
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]);
95
127
  }
96
- for (const group of ['skills', 'commands']) {
97
- const root = path.join(ctx.claudeRoot, group);
98
- const collect = async (directory) => {
99
- let entries;
100
- try {
101
- 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;
102
175
  }
103
- catch (error) {
104
- problems.push({ code: errorCode(error), detail: directory });
105
- 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
+ }
106
280
  }
107
- for (const entry of entries) {
108
- if (entry.name.startsWith('.'))
109
- continue;
110
- const location = path.join(directory, entry.name);
111
- if (group === 'commands' && entry.kind === 'directory') {
112
- await collect(location);
113
- 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;
114
288
  }
115
- if (group === 'commands' && entry.kind !== 'link' && (entry.kind !== 'file' || !entry.name.endsWith('.md')))
116
- continue;
117
- if (group === 'skills' && entry.kind !== 'directory' && entry.kind !== 'link')
118
- continue;
119
- let problem;
120
- if (group === 'skills') {
121
- try {
122
- const text = await ctx.machine.read(path.join(location, SKILL_ENTRY));
123
- 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))
124
345
  continue;
125
- if (!text?.trim())
126
- problem = 'skill-entry-invalid';
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];
127
352
  }
128
- catch (error) {
129
- problem = errorCode(error);
130
- }
131
- }
132
- const name = path.relative(root, location).split(path.sep).join('/');
133
- const saved = metadata[location];
134
- const skillSet = group === 'skills'
135
- ? Object.entries(skillSuites).find(([, source]) => source.repository === (isObject(saved) ? saved.repository : memberSuite(name)?.repository))?.[0]
136
- : undefined;
137
- // 更新资格取并集:登记成员、捆绑技能,以及凭来源记录归属到套件的已装成员
138
- const isOffered = group === 'skills' &&
139
- (Object.hasOwn(skillMembers, name) || Object.hasOwn(bundledSkills, name) || skillSet !== undefined);
140
- // 已发现条目标题用内联键真身(目录名/相对名),与磁盘及 Claude 所见一致;官方名只归方案入口
141
- result.push({
142
- id: `${group === 'skills' ? 'skill' : 'command'}:${name}`,
143
- title: name,
144
- kind: group === 'skills' ? 'skill' : 'command',
145
- location,
146
- ...(Object.hasOwn(bundledSkills, name) ? { canInstall: true } : {}),
147
- ...(skillSet ? { skillSet } : {}),
148
- facts: [{ code: entry.kind === 'link' ? 'shared-link' : 'entry-exists' }],
149
- ...(problem ? { problem } : {}),
150
- actions: isOffered ? ['update', 'detach'] : ['detach'],
151
353
  });
152
354
  }
153
- };
154
- await collect(root);
155
- }
156
- for (const name of Object.keys(bundledSkills)) {
157
- if (result.some(item => item.id === `skill:${name}`))
158
- continue;
159
- result.push({
160
- id: `skill:${name}`,
161
- title: knownTitle(`skill:${name}`, name),
162
- kind: 'skill',
163
- canInstall: true,
164
- facts: [{ code: 'not-installed' }],
165
- actions: ['install'],
166
- });
167
- }
168
- // 方案入口只有整套套件;状态从已发现的成员聚合推导(本地事实),不虚构未安装的成员占位
169
- for (const id of Object.keys(skillSuites)) {
170
- const members = result.filter(item => item.kind === 'skill' && item.skillSet === id).length;
171
- const registered = Object.values(skillMembers).filter(member => member.suite === id).length;
172
- result.push({
173
- id: `skill-set:${id}`,
174
- title: knownTitle(`skill-set:${id}`),
175
- kind: 'skill',
176
- canInstall: true,
177
- facts: [
178
- ...(members > 0
179
- ? [{ code: 'skill-members-present', detail: registered > 0 ? `${members}/${registered}` : `${members}` }]
180
- : metadataReadable
181
- ? [{ code: 'not-installed' }]
182
- : []),
183
- ],
184
- actions: ['install'],
185
- });
186
- }
187
- 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
+ };
188
366
  }
189
- /** 安装整套技能,只补齐缺失成员,保留已有内容 */
190
- async function prepareSkillSet(ctx, name, selection) {
191
- const source = Object.entries(skillSuites).find(([id]) => id === name)?.[1];
192
- if (!source || selection.action !== 'install')
193
- throw new Error('action-unavailable');
194
- const { revision, files } = await gitSkillSource(ctx, source);
195
- const candidates = files
196
- .filter(file => suiteEntryPattern.test(file.path) && file.data.length > 0)
197
- .map(file => path.posix.dirname(file.path))
198
- .filter(folder => folder.split('/').every(part => part !== '.' && part !== '..'))
199
- .sort((a, b) => a.length - b.length || a.localeCompare(b));
200
- const folders = [];
201
- for (const folder of candidates) {
202
- // 技能内部的示例 SKILL.md 属于原技能资源,不是另一个安装项
203
- if (!folders.some(parent => folder.startsWith(`${parent}/`)))
204
- folders.push(folder);
205
- }
206
- 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)
207
379
  throw new Error('skill-payload-missing');
208
- const names = folders.map(folder => path.posix.basename(folder).toLowerCase());
209
- if (new Set(names).size !== names.length)
380
+ names.forEach(validName);
381
+ if (new Set(names.map(name => name.toLowerCase())).size !== names.length)
210
382
  throw new Error('skill-name-conflict');
211
- const operations = [];
212
- const metadata = await readSkillMetadata(ctx);
213
- for (const folder of folders) {
214
- const member = path.posix.basename(folder);
215
- const directory = path.join(ctx.claudeRoot, 'skills', member);
216
- const before = await ctx.machine.treeStamp(directory);
217
- const entry = before === null ? null : await ctx.machine.read(path.join(directory, SKILL_ENTRY));
218
- const isEmptyDirectory = before !== null && entry === null && (await ctx.machine.entries(directory)).length === 0;
219
- if (before !== null && !isEmptyDirectory) {
220
- if (entry === null || !entry.trim())
221
- throw new Error('local-edits-preserved');
222
- operations.push({
223
- changes: [{ code: 'skill-existing-kept', detail: member }],
224
- async verify() {
225
- unchanged(await ctx.machine.treeStamp(directory), before);
226
- },
227
- async run(report) {
228
- unchanged(await ctx.machine.treeStamp(directory), before);
229
- report({ state: 'kept', code: 'skill-existing-kept', detail: member });
230
- },
231
- });
232
- continue;
233
- }
234
- const payload = files
235
- .filter(file => file.path.startsWith(`${folder}/`))
236
- .map(file => ({ ...file, path: file.path.slice(folder.length + 1) }));
237
- operations.push(prepareSkillFiles(ctx, { name: member, directory, stamp: before, sourceRecord: metadata[directory] }, { repository: source.repository, revision, files: payload, stamp: skillFilesStamp(payload) }));
238
- }
239
- return sequence(operations);
383
+ return names;
240
384
  }
241
- export async function prepareSkill(ctx, name, group, selection) {
242
- assertRelativeSkillPath(name);
243
- if (group === 'skills' && name.includes('/'))
244
- throw new Error('invalid-target');
245
- const directory = path.join(ctx.claudeRoot, group, name);
246
- const before = await ctx.machine.treeStamp(directory);
247
- const action = selection.action;
248
- if (!['install', 'update', 'detach'].includes(action))
249
- throw new Error('action-unavailable');
250
- if (action === 'detach') {
251
- if (before === null)
252
- throw new Error('no-connection');
253
- 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));
254
402
  }
255
- if (action === 'install' &&
256
- before !== null &&
257
- selection.fields?.replace !== REPLACE_CONSENT &&
258
- (await ctx.machine.read(path.join(directory, SKILL_ENTRY)))?.trim())
259
- return currentSkill(ctx, name, directory, before);
260
- const metadata = await readSkillMetadata(ctx);
261
- const saved = metadata[directory];
262
- if (!Object.hasOwn(skillMembers, name) &&
263
- !(group === 'skills' && Object.hasOwn(bundledSkills, name)) &&
264
- !(group === 'skills' && suiteOfRecord(saved) !== undefined))
265
- throw new Error('not-in-update-catalog');
266
- const { repository, revision, files } = await memberSkillSource(ctx, name, saved);
267
- const expected = skillFilesStamp(files);
268
- const target = { name, directory, stamp: before, sourceRecord: saved };
269
- const release = { repository, revision, files, stamp: expected };
270
- if (before !== null &&
271
- (!isObject(saved) || saved.stamp !== before) &&
272
- selection.fields?.replace !== REPLACE_CONSENT) {
273
- if (before === expected)
274
- return repairSkillSource(ctx, target, release);
275
- throw new Error('local-edits-preserved');
403
+ catch {
404
+ throw new Error('source-metadata-unavailable');
276
405
  }
277
- if (before !== null &&
278
- isObject(saved) &&
279
- saved.stamp === before &&
280
- saved.revision === revision &&
281
- before === expected)
282
- return currentSkill(ctx, name, directory, before);
283
- if (before === expected)
284
- return repairSkillSource(ctx, target, release);
285
- 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');
286
420
  }