@hit-sudomaker/ccw 0.4.0 → 0.4.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/render.js CHANGED
@@ -1,10 +1,17 @@
1
+ import { createRequire } from 'node:module';
2
+ import { dataSizeDetailOf } from './cleanup.js';
1
3
  import { knownTitle, programCopySuffix } from './titles.js';
2
4
  import { ERROR_MESSAGES } from './errors.js';
3
5
  import { WARNING_MESSAGES } from './warnings.js';
4
- import { kindOf } from './model.js';
6
+ import { isObject } from './machine.js';
7
+ import { CLAUDE_DATA_ID, kindOf } from './model.js';
8
+ /** 版本唯一真值是 package.json;运行时读取,避免发布元数据与自报版本漂移 */
9
+ const manifest = createRequire(import.meta.url)('../package.json');
10
+ const packageVersion = isObject(manifest) && typeof manifest.version === 'string' ? manifest.version : '';
5
11
  export const BRAND = {
6
12
  title: 'Claude Code Workpack',
7
- version: 'V0.4.0',
13
+ versionNumber: packageVersion,
14
+ version: `V${packageVersion}`,
8
15
  credit: 'Designed By AMIRC',
9
16
  logo: [
10
17
  ' ██████╗ ██████╗ ██╗ ██╗',
@@ -15,8 +22,20 @@ export const BRAND = {
15
22
  ' ╚═════╝ ╚═════╝ ╚══╝╚══╝',
16
23
  ],
17
24
  };
18
- export const HELP_TEXT = `CCW ${BRAND.version.slice(1)}\n无参数:打开菜单\n--inspect:检查环境\n--version:查看版本\n--help:查看帮助\n--details:显示本次启动异常详情\n安装:勾选后执行\n卸载、清理:预览后确认\n`;
19
- export const HOME_TITLE = `CCW ${BRAND.version.slice(1)} · 当前用户`;
25
+ export const HELP_TEXT = `CCW ${BRAND.versionNumber}\n无参数:打开菜单\n--inspect:检查环境(默认摘要,--inspect --details 输出完整明细)\n--collect-logs:收集诊断日志到本地文件\n--version:查看版本\n--help:查看帮助\n--details:显示启动异常与检查完整明细\n安装:勾选后执行\n卸载、清理:预览后确认\n`;
26
+ /** 标题范围后缀与未确认状态词:首页/检查标题、终端通知与诊断收集共用 */
27
+ export const USER_SCOPE_SUFFIX = ' · 当前用户';
28
+ export const UNCONFIRMED = '待确认';
29
+ export const HOME_TITLE = `CCW ${BRAND.versionNumber}${USER_SCOPE_SUFFIX}`;
30
+ /** 问题行与分组标题的固定记号:渲染、终端视图与诊断收集共用 */
31
+ export const PROBLEM_MARK = '! ';
32
+ export const GROUP_MARK = '── ';
33
+ /** 横幅与边框的固定宽度:视图层五处引用 */
34
+ export const BANNER_WIDTH = 62;
35
+ /** 选择页与结果菜单的返回行标签 */
36
+ export const BACK_TO_HOME = '返回主菜单';
37
+ /** 平台与架构的摘要片段格式:诊断收集与界面页脚共用 */
38
+ export const platformSummary = (platform, arch) => `${platform} (${arch})`;
20
39
  const CONTENT_ORDER = {
21
40
  claude: 0,
22
41
  settings: 1,
@@ -28,7 +47,7 @@ const CONTENT_ORDER = {
28
47
  officecli: 7,
29
48
  data: 8,
30
49
  };
31
- const GROUPS = {
50
+ export const GROUPS = {
32
51
  claude: '基础配置',
33
52
  settings: '基础配置',
34
53
  plugin: 'Plugins',
@@ -51,12 +70,17 @@ export const ACTION_NAMES = {
51
70
  clean: '清理',
52
71
  };
53
72
  export function planVerb(item) {
54
- if (item.id === 'data:claude')
73
+ if (item.id === CLAUDE_DATA_ID)
55
74
  return '删除';
56
75
  return item.action === 'uninstall' ? '卸载' : ACTION_NAMES[item.action];
57
76
  }
77
+ const TASK_VERBS = {
78
+ install: '安装',
79
+ uninstall: '卸载',
80
+ clean: '清理',
81
+ };
58
82
  export function preparationTitle(task) {
59
- return { install: '准备安装', uninstall: '准备卸载', clean: '准备清理' }[task];
83
+ return `准备${TASK_VERBS[task]}`;
60
84
  }
61
85
  export const MODEL_FIELDS = [
62
86
  { key: 'model', label: 'Default Model' },
@@ -81,6 +105,8 @@ export const SETTINGS_FIELDS = {
81
105
  language: ['language'],
82
106
  outputStyle: ['outputStyle'],
83
107
  };
108
+ /** 偏好默认值:表单初值与行摘要共用;与选项表首项无关,是刻意的默认选择 */
109
+ export const DEFAULT_PREFERENCES = { language: 'Simplified Chinese', outputStyle: 'Explanatory' };
84
110
  export function contentEntries(items, shouldExpandEditors) {
85
111
  return items.flatMap(item => item.kind === 'settings' && shouldExpandEditors
86
112
  ? [
@@ -110,7 +136,7 @@ export function entryRows(entries, drafts) {
110
136
  detail: effectiveConnection(fields, entry.item.facts) === 'api' ? '第三方 API' : '官方登录',
111
137
  };
112
138
  const choices = editor === 'language' ? SETTINGS_LANGUAGES : SETTINGS_STYLES;
113
- const value = fields[editor] ?? (editor === 'language' ? 'Simplified Chinese' : 'Explanatory');
139
+ const value = fields[editor] ?? DEFAULT_PREFERENCES[editor];
114
140
  return {
115
141
  ...rows[index],
116
142
  label: editor === 'language' ? '默认输出语言' : '输出风格',
@@ -134,48 +160,57 @@ export function inspectedItems(items) {
134
160
  export function contentName(item) {
135
161
  return safeText(item.title);
136
162
  }
163
+ /** 附加工具两类 kind;shortStatus 的残留配置与待接入分支共用 */
164
+ const TOOL_KINDS = ['ccline', 'officecli'];
165
+ /** 摘要状态词:凡与事实码目录 brief 相同的一律经 reason() 取词,词表只活在目录里 */
137
166
  function shortStatus(item) {
138
167
  const has = (code) => item.facts.some(fact => fact.code === code);
139
168
  if (['invalid-appearance', 'appearance-migration-required', 'skill-entry-invalid', 'invalid-mcp-registration'].includes(item.problem ?? ''))
140
169
  return '配置异常';
141
170
  if (item.problem || has('inspection-incomplete'))
142
- return '待确认';
171
+ return UNCONFIRMED;
143
172
  if (has('program-missing'))
144
- return '程序入口缺失';
145
- if (kindOf(item.id) === 'skill-set')
146
- return '';
173
+ return reason('program-missing');
174
+ if (kindOf(item.id) === 'skill-set') {
175
+ const members = item.facts.find(fact => fact.code === 'skill-members-present')?.detail;
176
+ return has('not-installed') ? reason('not-installed') : members ? `已装 ${members} 项` : UNCONFIRMED;
177
+ }
147
178
  if (item.kind === 'settings')
148
- return has('api-configured') ? '已有连接字段' : '默认连接';
179
+ return has('api-configured') ? reason('api-configured') : reason('official-connection');
149
180
  if (item.kind === 'plugin')
150
181
  return has('plugin-files-missing')
151
- ? '插件文件缺失'
182
+ ? reason('plugin-files-missing')
152
183
  : has('plugin-installed')
153
184
  ? has('declared-disabled')
154
- ? '已停用'
185
+ ? reason('declared-disabled')
155
186
  : '已安装'
156
187
  : has('declared-enabled')
157
188
  ? '残留声明'
158
- : '未安装';
189
+ : reason('not-installed');
159
190
  if (item.kind === 'mcp')
160
- return has('registration-exists') ? '已注册' : has('amirc-permissions-present') ? '残留许可' : '未安装';
191
+ return has('registration-exists')
192
+ ? '已注册'
193
+ : has('amirc-permissions-present')
194
+ ? '残留许可'
195
+ : reason('not-installed');
161
196
  if (item.kind === 'data')
162
- return item.facts.find(fact => fact.code === 'data-size')?.detail ?? '无数据';
197
+ return dataSizeDetailOf(item) ?? '无数据';
163
198
  if (has('shared-link') || has('entry-exists'))
164
199
  return '已安装';
165
200
  if (has('program-identity-unchecked'))
166
- return '待确认';
167
- if (['ccline', 'officecli'].includes(item.kind) && !has('program-exists') && has('connected'))
201
+ return UNCONFIRMED;
202
+ if (TOOL_KINDS.includes(item.kind) && !has('program-exists') && has('connected'))
168
203
  return '残留配置';
169
204
  if (has('program-exists')) {
170
205
  const version = item.facts.find(fact => fact.code === 'program-version')?.detail;
171
- const status = ['ccline', 'officecli'].includes(item.kind) && !has('connected')
206
+ const status = TOOL_KINDS.includes(item.kind) && !has('connected')
172
207
  ? '待接入'
173
208
  : item.kind === 'ccline' && has('appearance-missing')
174
209
  ? '待配置'
175
210
  : '已安装';
176
211
  return `${status}${version ? ` ${version}` : ''}`;
177
212
  }
178
- return '未安装';
213
+ return reason('not-installed');
179
214
  }
180
215
  export function contentRows(items) {
181
216
  return items.map(item => ({
@@ -217,6 +252,7 @@ export const TEXT = {
217
252
  'program-exists': { brief: '程序存在', detail: '程序存在' },
218
253
  'program-version': { brief: '程序版本', detail: '程序版本' },
219
254
  'not-installed': { brief: '未安装', detail: '未安装' },
255
+ 'skill-members-present': { brief: '已装成员', detail: '套件在本机已发现的成员数量' },
220
256
  'not-connected': { brief: '未接入', detail: '未接入' },
221
257
  'appearance-missing': { brief: '外观待配置', detail: '外观未配置' },
222
258
  'program-install': { brief: '安装程序', detail: '安装程序' },
@@ -235,6 +271,7 @@ export const TEXT = {
235
271
  'keep-plugin-files': { brief: '保留插件文件', detail: '保留插件文件和市场' },
236
272
  'plugin-disabled': { brief: '插件已停用', detail: '停用用户插件' },
237
273
  'plugin-install': { brief: '安装插件', detail: '安装插件' },
274
+ 'plugin-connect': { brief: '启用插件', detail: '启用用户插件' },
238
275
  'plugin-keep-data': { brief: '保留插件数据', detail: '保留插件数据' },
239
276
  'plugin-delete-own-data': { brief: '可能删除数据', detail: '官方卸载可能删除插件数据' },
240
277
  'plugin-credentials-removed': { brief: '可能清除认证', detail: '官方卸载可能清除插件设置和认证' },
@@ -293,6 +330,8 @@ export const TEXT = {
293
330
  'appearance-kept': { brief: '外观已保留', detail: '保留外观配置' },
294
331
  'ccline-disconnect-before-uninstall': { brief: '先解除状态栏', detail: '解除 CCometixLine 主状态栏与子状态栏' },
295
332
  'ccline-companion-kept': { brief: '保留配套插件', detail: '保留配套插件与市场' },
333
+ 'ccline-companion-present': { brief: '配套插件已装', detail: 'CCometixLine 配套插件在场' },
334
+ 'ccline-companion-missing': { brief: '配套插件未装', detail: 'CCometixLine 配套插件不在场;需要时可重装程序补齐' },
296
335
  'ccline-detach': { brief: '解除状态栏', detail: '解除 CCometixLine 接入;保留程序与外观' },
297
336
  'ccline-program-kept': { brief: '程序已保留', detail: '保留 CCometixLine 程序' },
298
337
  'ccline-program-update': { brief: '更新程序', detail: '更新 npm 程序' },
@@ -345,20 +384,21 @@ export function reason(code) {
345
384
  function message(code) {
346
385
  return ERROR_MESSAGES[code] ?? WARNING_MESSAGES[code] ?? TEXT[code];
347
386
  }
387
+ const FAILURE_LABELS = {
388
+ install: '安装失败',
389
+ connect: '安装失败',
390
+ update: '更新失败',
391
+ reinstall: '重装失败',
392
+ configure: '配置失败',
393
+ login: '登录失败',
394
+ detach: '解除失败',
395
+ uninstall: '卸载失败',
396
+ clean: '清理失败',
397
+ };
348
398
  export function failureLabel(action) {
349
399
  if (action === undefined)
350
400
  return '操作失败';
351
- return {
352
- install: '安装失败',
353
- connect: '安装失败',
354
- update: '更新失败',
355
- reinstall: '重装失败',
356
- configure: '配置失败',
357
- login: '登录失败',
358
- detach: '解除失败',
359
- uninstall: '卸载失败',
360
- clean: '清理失败',
361
- }[action];
401
+ return FAILURE_LABELS[action];
362
402
  }
363
403
  export function startupFailure(code, shouldShowDetails) {
364
404
  const brief = ['unknown-argument', 'interactive-terminal-required', 'unsupported-platform'].includes(code)
@@ -367,8 +407,12 @@ export function startupFailure(code, shouldShowDetails) {
367
407
  return shouldShowDetails ? `${brief}\n${describeDiagnostic({ code })}` : brief;
368
408
  }
369
409
  export function describePreparation(event, task = 'install') {
370
- const inspect = { install: '检查安装', uninstall: '检查卸载', clean: '检查清理' }[task];
371
- const actions = { inspect, metadata: '查询来源', download: '下载程序', source: '获取技能' };
410
+ const actions = {
411
+ inspect: `检查${TASK_VERBS[task]}`,
412
+ metadata: '查询来源',
413
+ download: '下载程序',
414
+ source: '获取技能',
415
+ };
372
416
  return `${actions[event.stage]}:${contentName(event)}`;
373
417
  }
374
418
  /** detail 一律原文:注册键、配置键、成员名与路径不在此改名 */
@@ -384,16 +428,27 @@ export function describeItem(item, shouldShowDetails = false) {
384
428
  ? [
385
429
  `标识:${safeText(item.id)}`,
386
430
  ...item.facts.map(describeDiagnostic),
387
- ...(item.problem ? [`! ${describeDiagnostic({ code: item.problem })}`] : []),
431
+ ...(item.problem ? [`${PROBLEM_MARK}${describeDiagnostic({ code: item.problem })}`] : []),
388
432
  ]
389
433
  : [shortStatus(item)];
390
434
  return `${contentName(item)}\n${body.filter(Boolean).join('\n')}${item.location ? `\n位置:${safeText(item.location)}` : ''}`;
391
435
  }
392
- export function describeInspection(view) {
393
- return [
394
- ...inspectedItems(view.items).map(item => describeItem(item, true)),
395
- ...view.problems.map(problem => `! ${describeInspectionProblem(problem)}`),
396
- ].join('\n');
436
+ /** 检查输出默认摘要(每项一行,与界面列表同形);--details 才展开完整明细 */
437
+ export function describeInspection(view, shouldShowDetails = false) {
438
+ if (shouldShowDetails)
439
+ return [
440
+ ...inspectedItems(view.items).map(item => describeItem(item, true)),
441
+ ...view.problems.map(problem => `${PROBLEM_MARK}${describeInspectionProblem(problem)}`),
442
+ ].join('\n');
443
+ const lines = [];
444
+ let previous;
445
+ for (const row of contentRows(inspectedItems(contentOrder(view.items)))) {
446
+ if (row.group && row.group !== previous)
447
+ lines.push(`${GROUP_MARK}${row.group}`);
448
+ previous = row.group;
449
+ lines.push(row.detail ? `${row.label}:${row.detail}` : row.label);
450
+ }
451
+ return [...lines, ...view.problems.map(problem => `${PROBLEM_MARK}${describeInspectionProblem(problem)}`)].join('\n');
397
452
  }
398
453
  /** 检查问题按读取来源归组:集合名映射到列表分组,其余来源用已知标题表 */
399
454
  const PROBLEM_KINDS = {
@@ -10,10 +10,10 @@ const INDICATORS = {
10
10
  cancelled: { symbol: '○', status: '已停止', tone: 'muted' },
11
11
  };
12
12
  const EFFECTS = {
13
- done: { symbol: '✔', tone: 'success' },
14
- kept: { symbol: '—', tone: 'muted' },
15
- failed: { symbol: '✕', tone: 'danger' },
16
- skipped: { symbol: '○', tone: 'warning' },
13
+ done: { symbol: '✔', tone: 'success', statement: '已完成' },
14
+ kept: { symbol: '—', tone: 'muted', statement: '已保留' },
15
+ failed: { symbol: '✕', tone: 'danger', statement: '未完成' },
16
+ skipped: { symbol: '○', tone: 'warning', statement: '未执行' },
17
17
  };
18
18
  function executionState(item) {
19
19
  return item.state === 'failed' && item.effects.length > 0 && item.effects.every(effect => effect.state === 'skipped')
@@ -30,7 +30,7 @@ function detail(effect) {
30
30
  const presentation = EFFECTS[effect.state];
31
31
  return {
32
32
  symbol: presentation.symbol,
33
- text: `${{ done: '已完成', kept: '已保留', failed: '未完成', skipped: '未执行' }[effect.state]} · ${describeDiagnostic(effect)}`,
33
+ text: `${EFFECTS[effect.state].statement} · ${describeDiagnostic(effect)}`,
34
34
  tone: presentation.tone,
35
35
  };
36
36
  }
@@ -82,7 +82,7 @@ function resultTitle(result, items, action) {
82
82
  const actions = new Set(items.map(item => item.action));
83
83
  return failureLabel(action ?? (actions.size === 1 ? items[0]?.action : undefined));
84
84
  }
85
- return { done: '完成', partial: '部分完成', cancelled: '已停止' }[result.state];
85
+ return INDICATORS[result.state].status;
86
86
  }
87
87
  function resultView(result, items, action, detailsId) {
88
88
  return {
@@ -137,12 +137,14 @@ export function createRunPresentation(plan, action) {
137
137
  },
138
138
  };
139
139
  }
140
+ /** 状态行文本形状:交互窄屏回退与非交互输出共用 */
141
+ export const statusLine = (row) => `${row.symbol} ${row.status} ${row.title}`;
140
142
  export function describeRun(view) {
141
143
  return [
142
144
  view.title,
143
145
  view.summary,
144
146
  ...view.rows.flatMap(row => [
145
- `${row.symbol} ${row.status} ${row.title}`,
147
+ statusLine(row),
146
148
  ...row.details.map(value => ` ${value.symbol ? `${value.symbol} ` : ''}${value.text}`),
147
149
  ]),
148
150
  ]
@@ -1,22 +1,23 @@
1
1
  import path from 'node:path';
2
2
  import { randomUUID } from 'node:crypto';
3
3
  import { treeFilesStamp } from './machine.js';
4
- import { cancelled, unchanged } from './model.js';
4
+ import { SKILL_ENTRY } from './management-catalog.js';
5
+ import { cancelled, json, unchanged } from './model.js';
6
+ import { disabledDirectory, replacedDirectory, sourcesFile } from './storage.js';
5
7
  export function currentSkill(ctx, name, directory, before) {
8
+ const verify = async () => unchanged(await ctx.machine.treeStamp(directory), before);
6
9
  return {
7
10
  changes: [{ code: 'skill-current', detail: name }],
8
11
  async run(report) {
9
- unchanged(await ctx.machine.treeStamp(directory), before);
12
+ await verify();
10
13
  report({ state: 'kept', code: 'skill-current', detail: name });
11
14
  },
12
- async verify() {
13
- unchanged(await ctx.machine.treeStamp(directory), before);
14
- },
15
+ verify,
15
16
  };
16
17
  }
17
18
  /** 校验技能入口并冻结载荷摘要 */
18
19
  export function skillFilesStamp(files) {
19
- if (!files.some(file => file.path === 'SKILL.md' && file.data.length > 0))
20
+ if (!files.some(file => file.path === SKILL_ENTRY && file.data.length > 0))
20
21
  throw new Error('skill-payload-missing');
21
22
  return treeFilesStamp(files);
22
23
  }
@@ -30,7 +31,7 @@ export function repairSkillSource(ctx, target, source) {
30
31
  };
31
32
  }
32
33
  async function saveSkillSource(ctx, report, target, source) {
33
- const file = path.join(ctx.storage, 'sources.json');
34
+ const file = sourcesFile(ctx);
34
35
  try {
35
36
  await ctx.machine.editJson(file, values => {
36
37
  unchanged(values[target.directory], target.sourceRecord);
@@ -44,7 +45,7 @@ async function saveSkillSource(ctx, report, target, source) {
44
45
  }
45
46
  export function prepareSkillFiles(ctx, target, source) {
46
47
  const { name, directory, stamp: before } = target;
47
- const destination = before === null ? undefined : path.join(ctx.storage, 'replaced', `${randomUUID()}-${name}`);
48
+ const destination = before === null ? undefined : path.join(replacedDirectory(ctx), `${randomUUID()}-${name}`);
48
49
  let isDeployed = false;
49
50
  let isComplete = false;
50
51
  const verify = async () => unchanged(await ctx.machine.treeStamp(directory), source.stamp);
@@ -75,9 +76,10 @@ export function prepareSkillFiles(ctx, target, source) {
75
76
  return operation;
76
77
  }
77
78
  export function disableSkillEntry(ctx, directory, before) {
78
- const destination = path.join(ctx.storage, 'disabled', `${randomUUID()}-${path.basename(directory)}`);
79
+ const destination = path.join(disabledDirectory(ctx), `${randomUUID()}-${path.basename(directory)}`);
80
+ const records = sourcesFile(ctx);
79
81
  return {
80
- writes: [directory],
82
+ writes: [directory, records],
81
83
  changes: [
82
84
  { code: 'entry-disable', detail: directory },
83
85
  { code: 'preserved-at', detail: destination },
@@ -86,6 +88,25 @@ export function disableSkillEntry(ctx, directory, before) {
86
88
  async run(report) {
87
89
  await ctx.machine.removeTree(directory, before, destination);
88
90
  report({ state: 'done', code: 'entry-disabled', detail: destination });
91
+ // 解除后清除该路径的过期来源记录(防误归属旧套件);失败只降级提示
92
+ let metadata;
93
+ try {
94
+ metadata = await json(ctx.machine, records);
95
+ }
96
+ catch {
97
+ // 记录不可读时降级提示,不影响解除结果
98
+ report({ state: 'kept', code: 'source-metadata-unavailable' });
99
+ metadata = null;
100
+ }
101
+ if (metadata !== null && Object.hasOwn(metadata, directory))
102
+ try {
103
+ await ctx.machine.editJson(records, values => {
104
+ delete values[directory];
105
+ });
106
+ }
107
+ catch {
108
+ report({ state: 'kept', code: 'source-metadata-unavailable' });
109
+ }
89
110
  },
90
111
  };
91
112
  }
package/dist/skills.js CHANGED
@@ -1,10 +1,11 @@
1
1
  import path from 'node:path';
2
2
  import { fileURLToPath } from 'node:url';
3
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';
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
7
  import { currentSkill, disableSkillEntry, prepareSkillFiles, repairSkillSource, skillFilesStamp, } from './skill-files.js';
8
+ import { sourcesFile } from './storage.js';
8
9
  const ASSET_ROOT = fileURLToPath(new URL('../assets/', import.meta.url));
9
10
  function memberSuite(name) {
10
11
  const member = Object.entries(skillMembers).find(([id]) => id === name)?.[1];
@@ -19,15 +20,24 @@ function assertRelativeSkillPath(value) {
19
20
  throw new Error('invalid-target');
20
21
  }
21
22
  /** 固定 Git 来源与载荷 */
23
+ /** 套件载荷内技能入口的路径形状(入口名单一出处 SKILL_ENTRY) */
24
+ const suiteEntryPattern = new RegExp(`^(?:[\\w.-]+/)+${SKILL_ENTRY.replaceAll('.', '\\.')}$`);
22
25
  async function gitSkillSource(ctx, source) {
23
26
  assertRelativeSkillPath(source.folder);
24
27
  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))
28
+ if (!revision || !isGitRevision(revision))
26
29
  throw new Error('source-unavailable');
27
30
  const files = await ctx.machine.source(source.repository, revision, source.folder);
28
31
  return { repository: source.repository, revision, files };
29
32
  }
30
- async function memberSkillSource(ctx, name) {
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) {
31
41
  const bundled = Object.entries(bundledSkills).find(([id]) => id === name)?.[1];
32
42
  if (bundled !== undefined) {
33
43
  assertRelativeSkillPath(bundled.asset);
@@ -37,10 +47,10 @@ async function memberSkillSource(ctx, name) {
37
47
  return {
38
48
  repository: bundled.repository,
39
49
  revision: bundled.revision,
40
- files: [{ path: 'SKILL.md', data: Buffer.from(text) }],
50
+ files: [{ path: SKILL_ENTRY, data: Buffer.from(text) }],
41
51
  };
42
52
  }
43
- const source = memberSuite(name);
53
+ const source = memberSuite(name) ?? (name.includes('/') ? undefined : suiteOfRecord(saved));
44
54
  if (source === undefined)
45
55
  throw new Error('not-in-update-catalog');
46
56
  return gitSkillSource(ctx, { repository: source.repository, folder: `${source.folder}/${name}` });
@@ -48,7 +58,7 @@ async function memberSkillSource(ctx, name) {
48
58
  /** 读取来源记录:损坏或不可读时保持未知,不以查无代替 */
49
59
  async function readSkillMetadata(ctx) {
50
60
  try {
51
- return await json(ctx.machine, path.join(ctx.storage, 'sources.json'));
61
+ return await json(ctx.machine, sourcesFile(ctx));
52
62
  }
53
63
  catch (error) {
54
64
  throw new Error('source-metadata-unavailable', { cause: error });
@@ -74,12 +84,14 @@ export function createSkillsDomain(ctx) {
74
84
  async function inspectSkills(ctx) {
75
85
  const result = [];
76
86
  let metadata = {};
87
+ let metadataReadable = true;
77
88
  const problems = [];
78
89
  try {
79
- metadata = await json(ctx.machine, path.join(ctx.storage, 'sources.json'));
90
+ metadata = await json(ctx.machine, sourcesFile(ctx));
80
91
  }
81
92
  catch {
82
- problems.push({ code: 'source-metadata-unavailable', detail: path.join(ctx.storage, 'sources.json') });
93
+ metadataReadable = false;
94
+ problems.push({ code: 'source-metadata-unavailable', detail: sourcesFile(ctx) });
83
95
  }
84
96
  for (const group of ['skills', 'commands']) {
85
97
  const root = path.join(ctx.claudeRoot, group);
@@ -107,7 +119,7 @@ async function inspectSkills(ctx) {
107
119
  let problem;
108
120
  if (group === 'skills') {
109
121
  try {
110
- const text = await ctx.machine.read(path.join(location, 'SKILL.md'));
122
+ const text = await ctx.machine.read(path.join(location, SKILL_ENTRY));
111
123
  if (text === null && entry.kind === 'directory')
112
124
  continue;
113
125
  if (!text?.trim())
@@ -118,13 +130,14 @@ async function inspectSkills(ctx) {
118
130
  }
119
131
  }
120
132
  const name = path.relative(root, location).split(path.sep).join('/');
121
- const isOffered = group === 'skills' && (Object.hasOwn(skillMembers, name) || Object.hasOwn(bundledSkills, name));
122
133
  const saved = metadata[location];
123
134
  const skillSet = group === 'skills'
124
135
  ? Object.entries(skillSuites).find(([, source]) => source.repository === (isObject(saved) ? saved.repository : memberSuite(name)?.repository))?.[0]
125
136
  : undefined;
126
- // 已发现条目标题用内联键真身(目录名/相对名):与磁盘及 Claude 所见一致,
127
- // 官方名只归方案入口承载——用户据此知道自己装的是什么、怎么解除
137
+ // 更新资格取并集:登记成员、捆绑技能,以及凭来源记录归属到套件的已装成员
138
+ const isOffered = group === 'skills' &&
139
+ (Object.hasOwn(skillMembers, name) || Object.hasOwn(bundledSkills, name) || skillSet !== undefined);
140
+ // 已发现条目标题用内联键真身(目录名/相对名),与磁盘及 Claude 所见一致;官方名只归方案入口
128
141
  result.push({
129
142
  id: `${group === 'skills' ? 'skill' : 'command'}:${name}`,
130
143
  title: name,
@@ -152,16 +165,25 @@ async function inspectSkills(ctx) {
152
165
  actions: ['install'],
153
166
  });
154
167
  }
155
- // 方案入口只有整套套件;检查只列实际发现的成员,不虚构未安装的成员占位
156
- for (const id of Object.keys(skillSuites))
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;
157
172
  result.push({
158
173
  id: `skill-set:${id}`,
159
174
  title: knownTitle(`skill-set:${id}`),
160
175
  kind: 'skill',
161
176
  canInstall: true,
162
- facts: [],
177
+ facts: [
178
+ ...(members > 0
179
+ ? [{ code: 'skill-members-present', detail: registered > 0 ? `${members}/${registered}` : `${members}` }]
180
+ : metadataReadable
181
+ ? [{ code: 'not-installed' }]
182
+ : []),
183
+ ],
163
184
  actions: ['install'],
164
185
  });
186
+ }
165
187
  return { items: result, problems };
166
188
  }
167
189
  /** 安装整套技能,只补齐缺失成员,保留已有内容 */
@@ -171,7 +193,7 @@ async function prepareSkillSet(ctx, name, selection) {
171
193
  throw new Error('action-unavailable');
172
194
  const { revision, files } = await gitSkillSource(ctx, source);
173
195
  const candidates = files
174
- .filter(file => /^(?:[\w.-]+\/)+SKILL\.md$/.test(file.path) && file.data.length > 0)
196
+ .filter(file => suiteEntryPattern.test(file.path) && file.data.length > 0)
175
197
  .map(file => path.posix.dirname(file.path))
176
198
  .filter(folder => folder.split('/').every(part => part !== '.' && part !== '..'))
177
199
  .sort((a, b) => a.length - b.length || a.localeCompare(b));
@@ -192,7 +214,7 @@ async function prepareSkillSet(ctx, name, selection) {
192
214
  const member = path.posix.basename(folder);
193
215
  const directory = path.join(ctx.claudeRoot, 'skills', member);
194
216
  const before = await ctx.machine.treeStamp(directory);
195
- const entry = before === null ? null : await ctx.machine.read(path.join(directory, 'SKILL.md'));
217
+ const entry = before === null ? null : await ctx.machine.read(path.join(directory, SKILL_ENTRY));
196
218
  const isEmptyDirectory = before !== null && entry === null && (await ctx.machine.entries(directory)).length === 0;
197
219
  if (before !== null && !isEmptyDirectory) {
198
220
  if (entry === null || !entry.trim())
@@ -217,12 +239,8 @@ async function prepareSkillSet(ctx, name, selection) {
217
239
  return sequence(operations);
218
240
  }
219
241
  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('/')))
242
+ assertRelativeSkillPath(name);
243
+ if (group === 'skills' && name.includes('/'))
226
244
  throw new Error('invalid-target');
227
245
  const directory = path.join(ctx.claudeRoot, group, name);
228
246
  const before = await ctx.machine.treeStamp(directory);
@@ -236,18 +254,22 @@ export async function prepareSkill(ctx, name, group, selection) {
236
254
  }
237
255
  if (action === 'install' &&
238
256
  before !== null &&
239
- selection.fields?.replace !== 'yes' &&
240
- (await ctx.machine.read(path.join(directory, 'SKILL.md')))?.trim())
257
+ selection.fields?.replace !== REPLACE_CONSENT &&
258
+ (await ctx.machine.read(path.join(directory, SKILL_ENTRY)))?.trim())
241
259
  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
260
  const metadata = await readSkillMetadata(ctx);
245
261
  const saved = metadata[directory];
246
- const { repository, revision, files } = await memberSkillSource(ctx, name);
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);
247
267
  const expected = skillFilesStamp(files);
248
268
  const target = { name, directory, stamp: before, sourceRecord: saved };
249
269
  const release = { repository, revision, files, stamp: expected };
250
- if (before !== null && (!isObject(saved) || saved.stamp !== before) && selection.fields?.replace !== 'yes') {
270
+ if (before !== null &&
271
+ (!isObject(saved) || saved.stamp !== before) &&
272
+ selection.fields?.replace !== REPLACE_CONSENT) {
251
273
  if (before === expected)
252
274
  return repairSkillSource(ctx, target, release);
253
275
  throw new Error('local-edits-preserved');
@@ -0,0 +1,44 @@
1
+ import path from 'node:path';
2
+ import { json } from './model.js';
3
+ /** CCW 自有存储(~/.ccw)的文件与目录名单一出处:写入侧(各域)与读取侧(诊断收集)都经此取路径 */
4
+ export const sourcesFile = (ctx) => path.join(ctx.storage, 'sources.json');
5
+ export const lastRunFile = (ctx) => path.join(ctx.storage, 'last-run.json');
6
+ export const replacedDirectory = (ctx) => path.join(ctx.storage, 'replaced');
7
+ export const disabledDirectory = (ctx) => path.join(ctx.storage, 'disabled');
8
+ export const logsDirectory = (ctx) => path.join(ctx.storage, 'logs');
9
+ /** 安装类临时产物(install-claude-*、install-uv-*)在存储根下的共用名称前缀 */
10
+ export const INSTALL_SCRATCH_PREFIX = 'install-';
11
+ export const installScratch = (ctx, name) => path.join(ctx.storage, `${INSTALL_SCRATCH_PREFIX}${name}`);
12
+ /** apply 后尽力落盘最近执行摘要:写入失败静默吞掉,不抛给调用方、不影响执行结果 */
13
+ export async function writeLastRun(ctx, plan, result, remaining) {
14
+ try {
15
+ await ctx.machine.editJson(lastRunFile(ctx), values => {
16
+ values.schema = 1;
17
+ values.planId = plan.id;
18
+ values.finishedAt = new Date().toISOString();
19
+ values.state = result.state;
20
+ values.items = plan.items.map((item, index) => ({
21
+ id: item.id,
22
+ title: item.title,
23
+ action: item.action,
24
+ state: result.items[index]?.state ?? null,
25
+ effects: (result.items[index]?.effects ?? []).map(effect => ({
26
+ state: effect.state,
27
+ code: effect.code,
28
+ ...(effect.detail ? { detail: effect.detail } : {}),
29
+ })),
30
+ }));
31
+ if (remaining !== undefined)
32
+ values.remaining = remaining;
33
+ else
34
+ delete values.remaining;
35
+ });
36
+ }
37
+ catch {
38
+ return;
39
+ }
40
+ }
41
+ /** 读取最近执行记录:文件缺失得空对象(无历史),损坏或不可读抛错由调用方保留未知 */
42
+ export function readLastRun(ctx) {
43
+ return json(ctx.machine, lastRunFile(ctx));
44
+ }