@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/README.md CHANGED
@@ -23,7 +23,7 @@ local state -> inspect -> plan -> apply -> result
23
23
 
24
24
  ## Install
25
25
 
26
- CCW 0.4.0 需要 Node.js 22.20 或更高版本。使用 pnpm 或 npm 安装:
26
+ CCW 需要 Node.js 22.20 或更高版本。使用 pnpm 或 npm 安装:
27
27
 
28
28
  ```bash
29
29
  pnpm add -g @hit-sudomaker/ccw
package/dist/ccline.js CHANGED
@@ -3,17 +3,25 @@ import { fileURLToPath } from 'node:url';
3
3
  import { isDeepStrictEqual } from 'node:util';
4
4
  import { parse } from 'smol-toml';
5
5
  import { knownTitle } from './titles.js';
6
+ import { ENABLED_PLUGINS_KEY } from './claude-config.js';
6
7
  import { errorCode, isObject, READ_COMMAND_TIMEOUT_MS, succeeded } from './machine.js';
7
- import { cancelled, removeFields, sequence } from './model.js';
8
- import { npmInstallArgs, npmUninstallArgs, resolveNpmView } from './npm-registry.js';
8
+ import { cancelled, json, removeFields, sequence } from './model.js';
9
+ import { isExactVersion, NPM_ENABLE_SCRIPTS, npmInstallArgs, npmUninstallArgs, resolveNpmView, } from './npm-registry.js';
10
+ import { compareVersions } from './programs.js';
9
11
  import { freezeNpmScope, npmVersion, samePath } from './program-channels.js';
10
12
  const PACKAGE = '@cometix/ccline';
11
13
  const ASSET = fileURLToPath(new URL('../assets/ccline/config.toml', import.meta.url));
12
14
  const FIELDS = ['statusLine', 'subagentStatusLine'];
15
+ const COMPANION_PLUGIN = 'cometix@ccline';
16
+ /** ccline --version 输出形状:身份探测允许预发布后缀,执行确认要求精确 2.x.y */
17
+ const CCLINE_IDENTITY = /^(?:ccline|ccometixline) \d+\.\d+\.\d+(?:[-+][\w.-]+)?\s*$/i;
18
+ const CCLINE_BINARY_VERSION = /^(?:ccline|ccometixline) (2\.\d+\.\d+)\s*$/i;
13
19
  /** 准备 CCometixLine 变更;计划消费与执行互斥由调用方 CCW 统一管理 */
14
20
  export function createCcline(options) {
15
21
  const { machine } = options;
16
- const binaryFile = path.join(options.home, '.claude', 'ccline', options.platform === 'win32' ? 'ccline.exe' : 'ccline');
22
+ /** ccline 固定落点:不受 CCLINE_HOME 影响 */
23
+ const defaultCclineDirectory = path.join(options.home, '.claude', 'ccline');
24
+ const binaryFile = path.join(defaultCclineDirectory, options.platform === 'win32' ? 'ccline.exe' : 'ccline');
17
25
  const settingsFile = options.settingsFile;
18
26
  // 保留重装中断后的接入模板,供重新准备恢复用户设置
19
27
  let resumeTemplates;
@@ -39,10 +47,7 @@ export function createCcline(options) {
39
47
  }
40
48
  const packageVersion = (root) => npmVersion(options, PACKAGE, root, { needsNpm: true });
41
49
  async function observe(shouldIncludeNpm, shouldIncludeFiles = shouldIncludeNpm) {
42
- const text = await machine.read(settingsFile);
43
- const settings = text === null ? {} : JSON.parse(text);
44
- if (!isObject(settings))
45
- throw new Error('invalid-settings');
50
+ const settings = await json(machine, settingsFile);
46
51
  const fields = {
47
52
  ...Object.fromEntries(FIELDS.map(field => [field, settings[field]])),
48
53
  cclineHome: isObject(settings.env) ? settings.env.CCLINE_HOME : undefined,
@@ -63,21 +68,14 @@ export function createCcline(options) {
63
68
  binary: shouldIncludeFiles ? await machine.fingerprint(binaryFile) : null,
64
69
  appearance: shouldIncludeFiles ? await machine.read(path.join(cclineDirectory(fields), 'config.toml')) : null,
65
70
  fields,
66
- hasCompanionPlugin: isObject(settings.enabledPlugins) && settings.enabledPlugins['cometix@ccline'] === true,
71
+ hasCompanionPlugin: isObject(settings[ENABLED_PLUGINS_KEY]) && settings[ENABLED_PLUGINS_KEY][COMPANION_PLUGIN] === true,
67
72
  };
68
73
  }
69
74
  function noDowngrade(version, release) {
70
75
  if (version === null)
71
76
  return;
72
- const numbers = version.split('.').map(part => Number.parseInt(part, 10));
73
- const target = release.split('.').map(Number);
74
- for (let index = 0; index < 3; index++) {
75
- const difference = (numbers[index] ?? 0) - (target[index] ?? 0);
76
- if (difference > 0)
77
- throw new Error('newer-version-preserved');
78
- if (difference < 0)
79
- return;
80
- }
77
+ if (compareVersions(version, release) > 0)
78
+ throw new Error('newer-version-preserved');
81
79
  }
82
80
  function validateAppearance(text) {
83
81
  let config;
@@ -97,7 +95,7 @@ export function createCcline(options) {
97
95
  const before = Object.fromEntries(selected.map(field => [field, observed.fields[field]]));
98
96
  const cclineHome = observed.fields.cclineHome;
99
97
  const appearanceRoot = shouldConnect ? cclineDirectory(observed.fields) : undefined;
100
- const shouldConfigureHome = appearanceRoot !== undefined && appearanceRoot !== path.join(options.home, '.claude', 'ccline');
98
+ const shouldConfigureHome = appearanceRoot !== undefined && !samePath(options, appearanceRoot, defaultCclineDirectory);
101
99
  const values = Object.fromEntries(selected.map(field => {
102
100
  const template = templates?.[field];
103
101
  const previous = isObject(template) ? template : isObject(before[field]) ? before[field] : {};
@@ -117,10 +115,8 @@ export function createCcline(options) {
117
115
  const verify = async () => {
118
116
  if (!selected.length)
119
117
  return;
120
- const after = await machine.read(settingsFile);
121
- const value = after === null ? {} : JSON.parse(after);
122
- if (!isObject(value) ||
123
- selected.some(field => shouldConnect ? !isDeepStrictEqual(value[field], values[field]) : isCcline(value[field])))
118
+ const value = await json(machine, settingsFile);
119
+ if (selected.some(field => shouldConnect ? !isDeepStrictEqual(value[field], values[field]) : isCcline(value[field])))
124
120
  throw new Error('connection-not-applied');
125
121
  if (shouldConnect &&
126
122
  !isDeepStrictEqual(isObject(value.env) ? value.env.CCLINE_HOME : undefined, shouldConfigureHome ? appearanceRoot : cclineHome))
@@ -169,7 +165,7 @@ export function createCcline(options) {
169
165
  return false;
170
166
  try {
171
167
  const result = await machine.execute(binaryFile, ['--version'], { timeoutMs: READ_COMMAND_TIMEOUT_MS });
172
- return (succeeded(result) && /^(?:ccline|ccometixline) \d+\.\d+\.\d+(?:[-+][\w.-]+)?\s*$/i.test(result.stdout.trim()));
168
+ return succeeded(result) && CCLINE_IDENTITY.test(result.stdout.trim());
173
169
  }
174
170
  catch {
175
171
  return false;
@@ -222,7 +218,7 @@ export function createCcline(options) {
222
218
  : []),
223
219
  { code: 'keep-user-data' },
224
220
  { code: 'appearance-kept' },
225
- ...(observed.hasCompanionPlugin ? [{ code: 'ccline-companion-kept', detail: 'cometix@ccline' }] : []),
221
+ ...(observed.hasCompanionPlugin ? [{ code: 'ccline-companion-kept', detail: COMPANION_PLUGIN }] : []),
226
222
  ];
227
223
  async function verifyPackage(expected) {
228
224
  await npmScope?.verify();
@@ -363,9 +359,9 @@ export function createCcline(options) {
363
359
  return operation;
364
360
  }
365
361
  async function inspectItem() {
362
+ // 全量探测失败才降级只读探测
366
363
  let observed = null;
367
364
  try {
368
- observed = await observe(false, false);
369
365
  observed = await observe(true);
370
366
  const isConnected = FIELDS.some(field => isCcline(observed?.fields[field]));
371
367
  let problem = observed.npmProblem ?? undefined;
@@ -401,18 +397,23 @@ export function createCcline(options) {
401
397
  },
402
398
  { code: isConnected ? 'connected' : 'not-connected' },
403
399
  { code: observed.appearance !== null ? 'appearance-kept' : 'appearance-missing' },
400
+ { code: observed.hasCompanionPlugin ? 'ccline-companion-present' : 'ccline-companion-missing' },
404
401
  ],
405
402
  actions,
406
403
  };
407
404
  }
408
405
  catch (error) {
406
+ const fallback = await observe(false, false).catch(() => null);
409
407
  return {
410
408
  id: 'ccline',
411
409
  title: knownTitle('ccline'),
412
410
  kind: 'ccline',
413
411
  canInstall: true,
414
412
  facts: [],
415
- actions: ['install', ...(FIELDS.some(field => isCcline(observed?.fields[field])) ? ['detach'] : [])],
413
+ actions: [
414
+ 'install',
415
+ ...(fallback && FIELDS.some(field => isCcline(fallback.fields[field])) ? ['detach'] : []),
416
+ ],
416
417
  problem: errorCode(error),
417
418
  };
418
419
  }
@@ -450,7 +451,7 @@ export function createCcline(options) {
450
451
  if (npmScope !== null && (await packageVersion(npmScope.npmRoot)) !== observed.version)
451
452
  throw new Error('program-changed');
452
453
  if (action !== 'connect') {
453
- const resolved = await resolveNpmView(machine, `${PACKAGE}@latest`, 'version', value => typeof value === 'string' && /^\d+\.\d+\.\d+$/.test(value) ? value : null);
454
+ const resolved = await resolveNpmView(machine, `${PACKAGE}@latest`, 'version', value => isExactVersion(value) ? value : null);
454
455
  if (resolved === null)
455
456
  throw new Error('source-unavailable');
456
457
  release = resolved.value;
@@ -519,7 +520,7 @@ export function createCcline(options) {
519
520
  '-g',
520
521
  ...(npmScope?.args ?? []),
521
522
  ...(action === 'reinstall' ? ['--force'] : []),
522
- '--ignore-scripts=false',
523
+ ...NPM_ENABLE_SCRIPTS,
523
524
  `${PACKAGE}@${release}`,
524
525
  ], releaseRegistry);
525
526
  const installed = await machine.npm(args);
@@ -545,7 +546,7 @@ export function createCcline(options) {
545
546
  });
546
547
  if (versionSignal?.aborted)
547
548
  cancelled(signal);
548
- const binaryVersion = /^(?:ccline|ccometixline) (2\.\d+\.\d+)\s*$/i.exec(version.stdout.trim())?.[1];
549
+ const binaryVersion = CCLINE_BINARY_VERSION.exec(version.stdout.trim())?.[1];
549
550
  if (!succeeded(version) || binaryVersion === undefined || (action !== 'connect' && binaryVersion !== release))
550
551
  throw new Error('binary-version-mismatch');
551
552
  programStamp = await machine.fingerprint(binaryFile);
@@ -606,7 +607,7 @@ export function createCcline(options) {
606
607
  : 'ccline-connect',
607
608
  detail: settingsFile,
608
609
  },
609
- ...(cclineDirectory(observed.fields) !== path.join(options.home, '.claude', 'ccline')
610
+ ...(!samePath(options, cclineDirectory(observed.fields), defaultCclineDirectory)
610
611
  ? [{ code: 'ccline-root-configure', detail: cclineDirectory(observed.fields) }]
611
612
  : []),
612
613
  ],
package/dist/ccw.js CHANGED
@@ -8,15 +8,26 @@ import { createMcpDomain } from './mcp.js';
8
8
  import { createPluginsDomain } from './plugins.js';
9
9
  import { createSkillsDomain } from './skills.js';
10
10
  import { errorCode } from './machine.js';
11
- import { cancelled, context, kindOf, normalizePath, restOf } from './model.js';
12
- import { createOfficecli } from './officecli.js';
11
+ import { CLAUDE_DATA_ID, cancelled, context, defaultInstallAction, kindOf, normalizePath, restOf } from './model.js';
12
+ import { createOfficecli, OFFICECLI_ENTRY_IDS } from './officecli.js';
13
13
  import { createReadMachine } from './read-machine.js';
14
+ import { writeLastRun } from './storage.js';
14
15
  const INVALID_PROGRAM_PLAN_REASONS = new Set([
15
16
  'program-changed',
16
17
  'program-scope-unconfirmed',
17
18
  'program-installation-unconfirmed',
18
19
  'npm-changed',
19
20
  ]);
21
+ /** 内容域清单单一出处:kind 键供计划路由,标签进检查问题详情 */
22
+ const CONTENT_DOMAINS = [
23
+ [['claude'], 'claude', createClaudeDomain],
24
+ [['officecli'], 'officecli', createOfficecli],
25
+ [['settings'], 'settings', createSettingsDomain],
26
+ [['plugin'], 'plugins', createPluginsDomain],
27
+ [['mcp'], 'mcp', createMcpDomain],
28
+ [['skill', 'skill-set', 'command'], 'skills', createSkillsDomain],
29
+ [['ccline'], 'ccline', createCcline],
30
+ ];
20
31
  /** 约束观察器:回调失败即自失效,绝不打断流程 */
21
32
  function progressGuard(callback) {
22
33
  let observer = callback;
@@ -58,8 +69,6 @@ function planDisplayTitle(id, selected) {
58
69
  return key || id;
59
70
  if (kind === 'claude' || kind === 'officecli')
60
71
  return `${knownTitle(kind)}${programCopySuffix(id, selected.map(other => other.id))}`;
61
- if (kind === 'data')
62
- return knownTitle(id);
63
72
  return knownTitle(id);
64
73
  }
65
74
  /** 只并发解除操作;同一配置文件独占,独立入口最多同时处理四项 */
@@ -109,19 +118,13 @@ export function createCcw(options) {
109
118
  const preparation = new AsyncLocalStorage();
110
119
  const preparationContext = { ...ctx, machine: createReadMachine(ctx.machine, () => preparation.getStore()) };
111
120
  /** 登记 prepare 域:随 preparationContext 一次建成;inspect 域每次内联新建以吃当次读取预算 */
112
- const skillsDomain = createSkillsDomain(preparationContext);
113
- const prepareDomains = new Map([
114
- ['claude', createClaudeDomain(preparationContext)],
115
- ['officecli', createOfficecli(preparationContext)],
116
- ['settings', createSettingsDomain(preparationContext)],
117
- ['plugin', createPluginsDomain(preparationContext)],
118
- ['mcp', createMcpDomain(preparationContext)],
119
- ['skill-set', skillsDomain],
120
- ['skill', skillsDomain],
121
- ['command', skillsDomain],
122
- ['data', createCleanupDomain(preparationContext)],
123
- ['ccline', createCcline(preparationContext)],
124
- ]);
121
+ const prepareDomains = new Map();
122
+ for (const [keys, , factory] of CONTENT_DOMAINS) {
123
+ const domain = factory(preparationContext);
124
+ for (const key of keys)
125
+ prepareDomains.set(key, domain);
126
+ }
127
+ prepareDomains.set('data', createCleanupDomain(preparationContext));
125
128
  let lifecycle = { phase: 'idle' };
126
129
  let remaining;
127
130
  async function inspect(scope = 'contents', signal) {
@@ -144,15 +147,7 @@ export function createCcw(options) {
144
147
  };
145
148
  const results = scope === 'data'
146
149
  ? [await guard('data', createCleanupDomain(reading))]
147
- : await Promise.all([
148
- guard('claude', createClaudeDomain(reading)),
149
- guard('officecli', createOfficecli(reading)),
150
- guard('settings', createSettingsDomain(reading)),
151
- guard('plugins', createPluginsDomain(reading)),
152
- guard('mcp', createMcpDomain(reading)),
153
- guard('skills', createSkillsDomain(reading)),
154
- guard('ccline', createCcline(reading)),
155
- ]);
150
+ : await Promise.all(CONTENT_DOMAINS.map(([, label, factory]) => guard(label, factory(reading))));
156
151
  cancelled(signal);
157
152
  const grouped = new Set(results.flatMap(result => result.grouped ?? []));
158
153
  return {
@@ -205,7 +200,7 @@ export function createCcw(options) {
205
200
  throw new Error('action-unavailable');
206
201
  const isProgram = ['claude', 'officecli', 'ccline'].includes(kindOf(pick.id));
207
202
  const action = snapshot.task === 'install'
208
- ? (pick.maintenance ?? (pick.id === 'settings' ? 'configure' : 'install'))
203
+ ? (pick.maintenance ?? defaultInstallAction(pick.id))
209
204
  : snapshot.task === 'uninstall'
210
205
  ? pick.removal === 'detach' || !isProgram
211
206
  ? 'detach'
@@ -252,7 +247,7 @@ export function createCcw(options) {
252
247
  if (seen.has(selection.id))
253
248
  throw new Error('duplicate-selection');
254
249
  seen.add(selection.id);
255
- if (hasOfficeConnectionChange && ['skill:officecli', 'mcp:officecli'].includes(selection.id))
250
+ if (hasOfficeConnectionChange && OFFICECLI_ENTRY_IDS.includes(selection.id))
256
251
  throw new Error('overlapping-selection');
257
252
  return prepare(selection, resolved => {
258
253
  cancelled(signal);
@@ -280,9 +275,9 @@ export function createCcw(options) {
280
275
  if (result.status === 'rejected')
281
276
  throw result.reason;
282
277
  if (shouldRemoveData) {
283
- await preparation.run(observe('data:claude', knownTitle('data:claude')), async () => {
278
+ await preparation.run(observe(CLAUDE_DATA_ID, knownTitle(CLAUDE_DATA_ID)), async () => {
284
279
  preparation.getStore()?.report('inspect');
285
- const { changes, problem } = await attach('data:claude', () => prepareClaudeDataRemoval(preparationContext, async () => {
280
+ const { changes, problem } = await attach(CLAUDE_DATA_ID, () => prepareClaudeDataRemoval(preparationContext, async () => {
286
281
  for (const selection of claudeRemovals) {
287
282
  const program = work.get(selection.id);
288
283
  if (!program?.verify)
@@ -290,7 +285,13 @@ export function createCcw(options) {
290
285
  await program.verify();
291
286
  }
292
287
  }));
293
- items.push({ id: 'data:claude', title: knownTitle('data:claude'), action: 'uninstall', changes, problem });
288
+ items.push({
289
+ id: CLAUDE_DATA_ID,
290
+ title: knownTitle(CLAUDE_DATA_ID),
291
+ action: 'uninstall',
292
+ changes,
293
+ problem,
294
+ });
294
295
  });
295
296
  }
296
297
  const plan = { id: randomUUID(), items, problem: items.length === 0 ? 'empty-selection' : null };
@@ -343,7 +344,7 @@ export function createCcw(options) {
343
344
  cancelled(signal);
344
345
  if (hasClaudeFailure &&
345
346
  item.action !== 'detach' &&
346
- (kindOf(item.id) === 'plugin' || item.action === 'login' || item.id === 'data:claude'))
347
+ (kindOf(item.id) === 'plugin' || item.action === 'login' || item.id === CLAUDE_DATA_ID))
347
348
  throw new Error('dependency-not-ready');
348
349
  const operation = current.work.get(item.id);
349
350
  if (operation === undefined)
@@ -396,7 +397,7 @@ export function createCcw(options) {
396
397
  .map(item => unfinishedItems.find(value => value.id === item.id) ?? item),
397
398
  work: unfinished,
398
399
  };
399
- return {
400
+ const result = {
400
401
  state: results.some(item => item.state === 'cancelled')
401
402
  ? 'cancelled'
402
403
  : results.every(item => item.state === 'done') && current.plan.problem === null
@@ -407,6 +408,9 @@ export function createCcw(options) {
407
408
  items: results,
408
409
  ...(token ? { remaining: token } : {}),
409
410
  };
411
+ // 最近执行落盘供诊断收集读取,尽力而为
412
+ await writeLastRun(ctx, current.plan, result, token);
413
+ return result;
410
414
  }
411
415
  finally {
412
416
  lifecycle = { phase: 'idle' };
@@ -80,6 +80,8 @@ async function prepareClaudeProgram(ctx, selection) {
80
80
  return sequence([operation, defaults]);
81
81
  }
82
82
  // 保留字段只定位已有键;偏好默认值由编辑器提交,不能变成 initializer 默认值
83
+ /** settings 内用户插件启停表的键名:字段表、插件域与配套插件探测共用 */
84
+ export const ENABLED_PLUGINS_KEY = 'enabledPlugins';
83
85
  const ROOT_FIELDS = {
84
86
  $schema: { placement: 'prefix', role: 'preserve' },
85
87
  defaultShell: { placement: 'prefix', role: 'preserve' },
@@ -89,7 +91,7 @@ const ROOT_FIELDS = {
89
91
  language: { placement: 'prefix', role: 'preference' },
90
92
  outputStyle: { placement: 'prefix', role: 'preference' },
91
93
  statusLine: { placement: 'prefix', role: 'preserve' },
92
- enabledPlugins: { placement: 'prefix', role: 'preserve' },
94
+ [ENABLED_PLUGINS_KEY]: { placement: 'prefix', role: 'preserve' },
93
95
  autoCompactEnabled: { placement: 'prefix', role: 'preserve' },
94
96
  autoCompactWindow: { placement: 'prefix', role: 'preserve' },
95
97
  apiKeyHelper: { placement: 'suffix', role: 'helper' },
package/dist/cleanup.js CHANGED
@@ -6,8 +6,10 @@ const CATEGORIES = DATA_CATEGORY_KEYS;
6
6
  /** 删除循环内周期复核 Claude 进程:删除可能跨越进程启动 */
7
7
  const PROCESS_RECHECK_INTERVAL_MS = 1_000;
8
8
  /** 清理结果仍有保留(新增、再生或共享链接)时标题须警示:清理承诺删除所选数据,保留是异常;
9
- * 卸载/安装的保留项是承诺,不警示 */
10
- export const CLEANUP_RESIDUE_CODES = ['data-remains-or-regenerated', 'cleanup-link-kept'];
9
+ * 卸载/安装的保留项是承诺,不警示;发射点与消费表共用同名常量,新增保留码不得漏登记 */
10
+ const RESIDUE_REGENERATED = 'data-remains-or-regenerated';
11
+ const RESIDUE_LINK_KEPT = 'cleanup-link-kept';
12
+ export const CLEANUP_RESIDUE_CODES = [RESIDUE_REGENERATED, RESIDUE_LINK_KEPT];
11
13
  const DIRECTORIES = {
12
14
  backup: 'backups',
13
15
  backups: 'backups',
@@ -40,9 +42,23 @@ const FILES = {
40
42
  function isCategory(value) {
41
43
  return CATEGORIES.some(category => category === value);
42
44
  }
45
+ /** 人类可读字节:满 1024 即换算到下一单位(B/KB/MB/GB/TB),保留 1 位小数 */
46
+ export function formatBytes(bytes) {
47
+ const units = ['B', 'KB', 'MB', 'GB', 'TB'];
48
+ let value = bytes * 10n;
49
+ let unit = 0;
50
+ while (unit < units.length - 1 && value >= 10n * 1024n) {
51
+ value = (value + 512n) / 1024n;
52
+ unit++;
53
+ }
54
+ return unit === 0 ? `${value / 10n} B` : `${value / 10n}.${value % 10n} ${units[unit]}`;
55
+ }
43
56
  function size(files) {
44
- return `${files.length} · ${files.reduce((sum, file) => sum + file.sizeBytes, 0n)} B`;
57
+ return `${files.length} · ${formatBytes(files.reduce((sum, file) => sum + file.sizeBytes, 0n))}`;
45
58
  }
59
+ /** 「文件数 · 逻辑大小」事实的读取面:详情提取与空类别判定跟生产格式同处一地,消费者不反解格式 */
60
+ export const dataSizeDetailOf = (item) => item.facts.find(fact => fact.code === 'data-size')?.detail;
61
+ export const isEmptyDataSize = (detail) => detail === undefined || detail.startsWith('0 · ');
46
62
  /** 清点白名单;projects 的记忆独立选择,读取缺口按类别保留 */
47
63
  async function candidates(ctx, selected) {
48
64
  const empty = () => ({ files: [], directories: [], problems: [], preserved: [] });
@@ -54,7 +70,7 @@ async function candidates(ctx, selected) {
54
70
  };
55
71
  const preserve = (group, file) => {
56
72
  for (const category of groups(group))
57
- result[category].preserved.push({ code: 'cleanup-link-kept', detail: file });
73
+ result[category].preserved.push({ code: RESIDUE_LINK_KEPT, detail: file });
58
74
  };
59
75
  const regularFile = (file, category, sizeBytes) => {
60
76
  if (!groups(category).length)
@@ -249,7 +265,7 @@ async function prepareCleanup(ctx, category) {
249
265
  for (const preserved of remaining.preserved)
250
266
  report({ state: 'kept', ...preserved });
251
267
  if (remaining.files.length)
252
- report({ state: 'kept', code: 'data-remains-or-regenerated', detail: size(remaining.files) });
268
+ report({ state: 'kept', code: RESIDUE_REGENERATED, detail: size(remaining.files) });
253
269
  if (files.length === 0 && directories.length === 0)
254
270
  report({ state: 'kept', code: 'no-data' });
255
271
  },
@@ -0,0 +1,147 @@
1
+ import path from 'node:path';
2
+ import { dataSizeDetailOf, isEmptyDataSize } from './cleanup.js';
3
+ import { errorCode, isObject } from './machine.js';
4
+ import { context, json } from './model.js';
5
+ import { BRAND, describeInspection, platformSummary, PROBLEM_MARK, UNCONFIRMED } from './render.js';
6
+ import { INSTALL_SCRATCH_PREFIX, disabledDirectory, logsDirectory, readLastRun, replacedDirectory, sourcesFile, } from './storage.js';
7
+ import { knownTitle } from './titles.js';
8
+ /** 路径折叠:配置根 → <claude>,主目录 → ~;先长后短,且仅折叠后继为分隔符或结尾的完整前缀 */
9
+ export function foldText(ctx, text) {
10
+ let folded = text;
11
+ for (const directory of [ctx.claudeRoot, ctx.home]) {
12
+ const token = directory === ctx.claudeRoot ? '<claude>' : '~';
13
+ for (const separator of ['\\', '/']) {
14
+ const prefix = directory.replaceAll('\\', separator).replaceAll('/', separator);
15
+ if (prefix)
16
+ folded = folded.replace(new RegExp(`${prefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?=[\\\\/]|$)`, 'g'), token);
17
+ }
18
+ }
19
+ return folded;
20
+ }
21
+ /** 凭据打码:常见令牌形态只保留前缀提示 */
22
+ export function redactText(text) {
23
+ return text
24
+ .replace(/(Authorization:\s*\S+\s+)\S+/gi, '$1<redacted>')
25
+ .replace(/\b(sk-ant-[A-Za-z0-9_-]{4})[A-Za-z0-9_-]+/g, '$1…<redacted>')
26
+ .replace(/\b(ghp_[A-Za-z0-9]{4})[A-Za-z0-9]+/g, '$1…<redacted>')
27
+ .replace(/\b(sk-[A-Za-z0-9]{4})[A-Za-z0-9]{8,}\b/g, '$1…<redacted>');
28
+ }
29
+ async function directoryCount(ctx, directory) {
30
+ try {
31
+ return (await ctx.machine.entries(directory)).length;
32
+ }
33
+ catch (error) {
34
+ return errorCode(error) === 'ENOENT' ? 0 : null;
35
+ }
36
+ }
37
+ /** 收集诊断日志:只读本地事实,生成一个脱敏报告文件;不上传、不做网络请求 */
38
+ export async function collectLogs(ccw, options) {
39
+ const ctx = context(options);
40
+ // 展示层兜底词:读取未知不用空串或「无」代替
41
+ const UNKNOWN = '未知';
42
+ // 两路检查顺序执行(各 5 秒预算)
43
+ const view = await ccw.inspect('contents');
44
+ const data = await ccw.inspect('data');
45
+ const problems = [
46
+ ...view.problems.map(problem => problem.code),
47
+ ...view.items.flatMap(item => (item.problem ? [item.problem] : [])),
48
+ ];
49
+ const sources = await json(ctx.machine, sourcesFile(ctx)).catch(() => null);
50
+ // 记录不可读时保留未知(不以"无历史"代替查无):读取对缺失文件返回空对象,抛错即为损坏或不可读
51
+ let lastRun = {};
52
+ let lastRunReadable = true;
53
+ try {
54
+ lastRun = await readLastRun(ctx);
55
+ }
56
+ catch {
57
+ lastRunReadable = false;
58
+ }
59
+ const runItems = Array.isArray(lastRun.items)
60
+ ? lastRun.items.filter(isObject).map(entry => ({
61
+ title: typeof entry.title === 'string' ? entry.title : typeof entry.id === 'string' ? entry.id : UNKNOWN,
62
+ state: typeof entry.state === 'string' ? entry.state : UNKNOWN,
63
+ }))
64
+ : [];
65
+ const runAt = typeof lastRun.finishedAt === 'string' ? lastRun.finishedAt : undefined;
66
+ const runState = typeof lastRun.state === 'string' ? lastRun.state : undefined;
67
+ const replaced = await directoryCount(ctx, replacedDirectory(ctx));
68
+ const disabled = await directoryCount(ctx, disabledDirectory(ctx));
69
+ const storageEntries = await ctx.machine.entries(ctx.storage).catch(() => null);
70
+ const installLeftovers = storageEntries?.filter(entry => entry.name.startsWith(INSTALL_SCRATCH_PREFIX)).length ?? null;
71
+ const customConfigRoot = ctx.claudeRoot !== path.join(ctx.home, '.claude');
72
+ const stamp = new Date();
73
+ const environment = [
74
+ `生成时间:${stamp.toISOString()}`,
75
+ `版本:CCW ${BRAND.versionNumber}`,
76
+ `环境:${platformSummary(ctx.platform, ctx.arch ?? process.arch)}${ctx.libc ? ` · ${ctx.libc}` : ''} · Node ${process.version}`,
77
+ `配置根:${customConfigRoot ? '自定义(CLAUDE_CONFIG_DIR)' : '默认'} · 状态文件与存储见下方折叠路径`,
78
+ ];
79
+ const dataLines = data.items.map(item => {
80
+ const size = dataSizeDetailOf(item);
81
+ return `- ${knownTitle(item.id)}:${size ?? '无数据'}${item.problem ? ` · ${UNCONFIRMED}(${item.problem})` : ''}`;
82
+ });
83
+ const report = [
84
+ '# CCW 诊断报告',
85
+ '',
86
+ ...environment,
87
+ `存储位置:${path.join(ctx.storage, '')}(来源记录 ${sources === null ? '不可读' : `${Object.keys(sources).length} 条`},替换备份 ${replaced ?? UNKNOWN} 份,停用备份 ${disabled ?? UNKNOWN} 份,安装残留 ${installLeftovers ?? UNKNOWN} 项)`,
88
+ '',
89
+ '## 检查结果(完整明细)',
90
+ '',
91
+ describeInspection(view, true) || '(无条目)',
92
+ '',
93
+ '## 最近一次执行',
94
+ '',
95
+ ...(lastRunReadable
96
+ ? runItems.length || runState !== undefined
97
+ ? [
98
+ `时间:${runAt ?? UNKNOWN} · 状态:${runState ?? UNKNOWN}`,
99
+ ...runItems.map(entry => `- ${entry.title}:${entry.state}`),
100
+ ]
101
+ : ['(无执行历史)']
102
+ : ['(最近执行状态未知:记录不可读)']),
103
+ '',
104
+ '## 运行数据体量',
105
+ '',
106
+ ...(dataLines.length ? dataLines : ['(无数据)']),
107
+ ...data.problems.map(problem => `- ${PROBLEM_MARK}${problem.code}${problem.detail ? `:${problem.detail}` : ''}`),
108
+ '',
109
+ '## 隐私声明',
110
+ '',
111
+ '- 本报告只在本地生成;CCW 不会自动上传任何内容,是否提供给他人由你决定',
112
+ '- 报告中的主目录与配置根路径已折叠,常见凭据形态已打码',
113
+ '- 检查过程会读取 settings.json 与 .claude.json 以派生状态;报告只收录派生事实码,不收录原文与凭据值',
114
+ '- 未读取任何日志文件的内容,仅统计存在性与体量',
115
+ '',
116
+ ].join('\n');
117
+ const directory = logsDirectory(ctx);
118
+ const base = `ccw-collect-${stamp.toISOString().replace(/[-:]/g, '').replace('T', '').slice(0, 14)}`;
119
+ const text = redactText(foldText(ctx, report));
120
+ let file = path.join(directory, `${base}.md`);
121
+ let attempt = 0;
122
+ while (!(await ctx.machine.initialize(file, text))) {
123
+ if (++attempt >= 100)
124
+ throw new Error('report-name-conflict');
125
+ file = path.join(directory, `${base}-${attempt}.md`);
126
+ }
127
+ const summary = [
128
+ 'CCW 诊断摘要',
129
+ `版本:CCW ${BRAND.versionNumber} · ${platformSummary(ctx.platform, ctx.arch ?? process.arch)} · Node ${process.version}`,
130
+ `检查:${view.items.length} 项,${problems.length} 个问题${problems.length ? `(${[...new Set(problems)].join('、')})` : ''}`,
131
+ ...(lastRunReadable && runState !== undefined ? [`最近执行:${runState}`] : []),
132
+ ...(data.items.length
133
+ ? [
134
+ `数据:${data.items
135
+ .map(item => {
136
+ const size = dataSizeDetailOf(item);
137
+ return size !== undefined && !isEmptyDataSize(size) ? `${knownTitle(item.id)} ${size}` : '';
138
+ })
139
+ .filter(Boolean)
140
+ .join(' · ')}`,
141
+ ]
142
+ : []),
143
+ `完整报告:${file}`,
144
+ '报障时请把上面的完整报告文件一并附上',
145
+ ].join('\n');
146
+ return { file, summary };
147
+ }
package/dist/errors.js CHANGED
@@ -96,13 +96,14 @@ export const ERROR_MESSAGES = {
96
96
  'channel-change-required': { brief: '需要重新接入', detail: '接入服务失败:启动渠道不同;需重新接入' },
97
97
  'serena-initialization-failed': { brief: '服务初始化失败', detail: '初始化 Serena 失败' },
98
98
  'marketplace-source-conflict': { brief: '市场来源不符', detail: '保留同名市场:来源不同' },
99
- 'overlapping-selection': { brief: '选择范围重复', detail: '选择内容失败:入口已包含在 OfficeCLI 操作' },
99
+ 'overlapping-selection': { brief: '选择范围重复', detail: '选择内容失败:与同批另一项的操作范围重叠' },
100
100
  'installer-unavailable': { brief: '安装未执行', detail: '安装程序失败:官方来源返回网页;未执行安装' },
101
101
  'selected-item-unavailable': { brief: '所选内容失效', detail: '选择内容失败:内容不在检查结果' },
102
102
  'integration-source-conflict': { brief: '接入来源待确认', detail: '接入内容失败:同名入口与程序关系未知' },
103
103
  'claude-running': { brief: '请先退出程序', detail: '执行 Claude 操作失败:Claude 正在运行' },
104
104
  'process-state-unconfirmed': { brief: '进程待确认', detail: '确认 Claude 进程失败:状态未知' },
105
105
  'backup-exists': { brief: '备份目标已存在', detail: '保存备份失败:目标已存在' },
106
+ 'report-name-conflict': { brief: '报告文件冲突', detail: '保存诊断报告失败:同名报告过多' },
106
107
  'connection-not-applied': { brief: '接入未生效', detail: '确认接入失败:配置未生效' },
107
108
  'inspection-failed': { brief: '检查失败', detail: '检查内容失败' },
108
109
  'installer-conflict': { brief: '安装目标冲突', detail: '启动安装器失败:临时目标已存在' },
@@ -127,7 +128,7 @@ export const ERROR_MESSAGES = {
127
128
  'unknown-selection': { brief: '选择无效', detail: '准备操作失败:所选内容不受支持' },
128
129
  'unknown-argument': {
129
130
  brief: '参数无效',
130
- detail: '只接受一个模式:--help、--version 或 --inspect;可附加一次 --details;不接受其他参数',
131
+ detail: '只接受一个模式:--help、--version、--inspect 或 --collect-logs;可附加一次 --details;不接受其他参数',
131
132
  },
132
133
  'interactive-terminal-required': { brief: '需要交互终端', detail: '启动界面失败:需要交互终端' },
133
134
  'unsupported-platform': { brief: '系统暂不支持', detail: '启动 CCW 失败:系统不支持' },
@@ -1,4 +1,4 @@
1
- import { cancelled, json, object, removeFields, sequence, unchanged } from './model.js';
1
+ import { cancelled, json, MCP_SERVERS_KEY, object, readMcpServers, removeFields, sequence, unchanged, } from './model.js';
2
2
  const OWNED_RULES = ['mcp__amirc__organize_papers', 'mcp__amirc__search_papers', 'mcp__amirc__get_papers'];
3
3
  function allowedTools(settings) {
4
4
  const allow = object(settings.permissions).allow;
@@ -13,7 +13,7 @@ export async function hasLegacyAmircPermissions(ctx) {
13
13
  }
14
14
  /** 退役迁移只解除明确选择的旧注册与精确允许规则,保留技能与用户材料 */
15
15
  export async function prepareLegacyAmircDetach(ctx) {
16
- const before = object((await json(ctx.machine, ctx.stateFile)).mcpServers);
16
+ const before = await readMcpServers(ctx);
17
17
  const allowBefore = allowedTools(await json(ctx.machine, ctx.settingsFile));
18
18
  if (before.amirc === undefined && !allowBefore.some(rule => OWNED_RULES.includes(rule)))
19
19
  throw new Error('no-connection');
@@ -54,7 +54,7 @@ export async function prepareLegacyAmircDetach(ctx) {
54
54
  verify,
55
55
  };
56
56
  return sequence([
57
- removeFields(ctx, ctx.stateFile, { amirc: before.amirc }, [{ code: 'mcp-remove-registration', detail: 'amirc' }, { code: 'mcp-keep-runtime' }], { state: 'done', code: 'registration-removed', detail: 'amirc' }, 'mcpServers'),
57
+ removeFields(ctx, ctx.stateFile, { amirc: before.amirc }, [{ code: 'mcp-remove-registration', detail: 'amirc' }, { code: 'mcp-keep-runtime' }], { state: 'done', code: 'registration-removed', detail: 'amirc' }, MCP_SERVERS_KEY),
58
58
  permissions,
59
59
  ]);
60
60
  }
package/dist/machine.js CHANGED
@@ -12,6 +12,8 @@ export const GIT_COMMAND_TIMEOUT_MS = 15_000;
12
12
  export const FETCH_TEXT_TIMEOUT_MS = 30_000;
13
13
  export const FETCH_BYTES_TIMEOUT_MS = 120_000;
14
14
  export const SOURCE_TIMEOUT_MS = 120_000;
15
+ /** git 提交号形状:40 位十六进制小写 */
16
+ export const isGitRevision = (value) => /^[a-f0-9]{40}$/.test(value);
15
17
  /** 限制整读内容的内存占用 */
16
18
  const FILE_LIMIT_BYTES = 2 * 1024 * 1024;
17
19
  const OUTPUT_LIMIT_BYTES = 1024 * 1024;
@@ -252,7 +254,7 @@ async function run(executable, args, environment, cwd, options = {}) {
252
254
  }
253
255
  }
254
256
  return new Promise(resolve => {
255
- const child = spawn(executable, [...args], {
257
+ const child = spawn(executable, args, {
256
258
  cwd,
257
259
  env: environment,
258
260
  windowsHide: true,
@@ -609,7 +611,7 @@ export function createMachine(environment = process.env, cwd = process.cwd(), ha
609
611
  },
610
612
  async source(repository, revision, subdirectory, options = {}) {
611
613
  return remoteRead(options, SOURCE_TIMEOUT_MS, async (reading) => {
612
- if (!/^https:\/\/github\.com\/[\w.-]+\/[\w.-]+(?:\.git)?$/.test(repository) || !/^[a-f0-9]{40}$/.test(revision))
614
+ if (!/^https:\/\/github\.com\/[\w.-]+\/[\w.-]+(?:\.git)?$/.test(repository) || !isGitRevision(revision))
613
615
  throw new Error('invalid-source');
614
616
  const temporary = await fs.mkdtemp(path.join(os.tmpdir(), 'ccw-source-'));
615
617
  const git = async (args) => {