@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/ccw.js CHANGED
@@ -1,137 +1,33 @@
1
1
  import { AsyncLocalStorage } from 'node:async_hooks';
2
- import { randomUUID } from 'node:crypto';
3
- import { knownTitle, programCopySuffix } from './titles.js';
4
- import { createCcline } from './ccline.js';
5
- import { createClaudeDomain, createSettingsDomain } from './claude-config.js';
6
- import { createCleanupDomain, prepareClaudeDataRemoval } from './cleanup.js';
7
- import { createMcpDomain } from './mcp.js';
8
- import { createPluginsDomain } from './plugins.js';
9
- import { createSkillsDomain } from './skills.js';
10
2
  import { errorCode } from './machine.js';
11
- import { CLAUDE_DATA_ID, cancelled, context, defaultInstallAction, kindOf, normalizePath, restOf } from './model.js';
12
- import { createOfficecli, OFFICECLI_ENTRY_IDS } from './officecli.js';
3
+ import { cancelled, context } from './model.js';
13
4
  import { createReadMachine } from './read-machine.js';
14
- import { writeLastRun } from './storage.js';
15
- const INVALID_PROGRAM_PLAN_REASONS = new Set([
16
- 'program-changed',
17
- 'program-scope-unconfirmed',
18
- 'program-installation-unconfirmed',
19
- 'npm-changed',
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
- ];
31
- /** 约束观察器:回调失败即自失效,绝不打断流程 */
32
- function progressGuard(callback) {
33
- let observer = callback;
34
- return (event) => {
35
- if (observer === undefined)
36
- return;
37
- try {
38
- void Promise.resolve(observer(event)).catch(() => {
39
- observer = undefined;
40
- });
41
- }
42
- catch {
43
- observer = undefined;
44
- }
45
- };
46
- }
47
- /** 构造失败的 RunResult:problem 项失败、无 problem 项跳过 */
48
- function planFailure(items) {
49
- return {
50
- state: 'failed',
51
- items: items.map(item => ({
52
- id: item.id,
53
- title: item.title,
54
- state: 'failed',
55
- effects: [
56
- {
57
- state: item.problem ? 'failed' : 'skipped',
58
- code: item.problem ?? 'changes-not-started',
59
- },
60
- ],
61
- })),
62
- };
63
- }
64
- /** 生成准备前的纯描述;需要来源证据的标题由领域准备步骤用同一份事实补全 */
65
- function planDisplayTitle(id, selected) {
66
- const kind = kindOf(id);
67
- const key = restOf(id) ?? '';
68
- if (kind === 'mcp' || kind === 'plugin' || kind === 'skill' || kind === 'command')
69
- return key || id;
70
- if (kind === 'claude' || kind === 'officecli')
71
- return `${knownTitle(kind)}${programCopySuffix(id, selected.map(other => other.id))}`;
72
- return knownTitle(id);
73
- }
74
- /** 只并发解除操作;同一配置文件独占,独立入口最多同时处理四项 */
75
- async function detachBatch(ctx, items, work, run) {
76
- const waiting = items.map((item, index) => ({
77
- item,
78
- index,
79
- files: (work.get(item.id)?.writes ?? []).map(file => normalizePath(ctx.platform, file)),
80
- }));
81
- const occupied = new Set();
82
- const running = new Set();
83
- const results = [];
84
- try {
85
- while (waiting.length || running.size) {
86
- while (running.size < 4) {
87
- const next = waiting.findIndex(entry => entry.files.every(file => !occupied.has(file)));
88
- if (next < 0)
89
- break;
90
- const entry = waiting.splice(next, 1)[0];
91
- if (!entry)
92
- break;
93
- for (const file of entry.files)
94
- occupied.add(file);
95
- const task = run(entry.item)
96
- .then(result => {
97
- results[entry.index] = result;
98
- })
99
- .finally(() => {
100
- for (const file of entry.files)
101
- occupied.delete(file);
102
- running.delete(task);
103
- });
104
- running.add(task);
105
- }
106
- if (running.size)
107
- await Promise.race(running);
108
- }
109
- }
110
- finally {
111
- await Promise.allSettled(running);
112
- }
113
- return results;
114
- }
115
- /** 统一管理当前用户的内容;检查不消费计划,执行逐项报告已发生的效果 */
5
+ import { createEffectMachine, createEffectScope } from './effect-machine.js';
6
+ import { inspectClaudeData } from './cleanup.js';
7
+ import { CONTENT_DOMAINS, createPlanner } from './planning.js';
8
+ const INSPECTION_TIMEOUT_MS = 5_000;
9
+ const VERIFICATION_TIMEOUT_MS = 30_000;
10
+ /**
11
+ * 创建独立持有计划和操作锁的 CCW 实例
12
+ *
13
+ * @throws Error - 用户目录或配置根不是有效的绝对非根路径
14
+ * @remarks 创建时不安装工具,读写由实例方法触发
15
+ */
116
16
  export function createCcw(options) {
117
17
  const ctx = context(options);
118
- const preparation = new AsyncLocalStorage();
119
- const preparationContext = { ...ctx, machine: createReadMachine(ctx.machine, () => preparation.getStore()) };
120
- /** 登记 prepare 域:随 preparationContext 一次建成;inspect 域每次内联新建以吃当次读取预算 */
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));
128
- let lifecycle = { phase: 'idle' };
129
- let remaining;
130
- async function inspect(scope = 'contents', signal) {
18
+ let busy = false;
19
+ let approved;
20
+ const effectScope = createEffectScope(options.machine);
21
+ const effects = effectScope.machine;
22
+ const readScope = new AsyncLocalStorage();
23
+ const preparationContext = { ...ctx, effects, machine: createReadMachine(ctx.machine, () => readScope.getStore()) };
24
+ const plan = createPlanner(preparationContext, readScope);
25
+ async function inspect(signal, scope = 'contents') {
131
26
  cancelled(signal);
132
- const deadlineMs = performance.now() + 5_000;
27
+ const deadlineMs = performance.now() + INSPECTION_TIMEOUT_MS;
133
28
  const reading = {
134
29
  ...ctx,
30
+ effects: createEffectMachine(options.machine, () => false),
135
31
  machine: createReadMachine(ctx.machine, () => ({ deadlineMs, ...(signal ? { signal } : {}) }), {
136
32
  shouldShareReads: true,
137
33
  }),
@@ -146,275 +42,164 @@ export function createCcw(options) {
146
42
  }
147
43
  };
148
44
  const results = scope === 'data'
149
- ? [await guard('data', createCleanupDomain(reading))]
45
+ ? [await inspectClaudeData(reading)]
150
46
  : await Promise.all(CONTENT_DOMAINS.map(([, label, factory]) => guard(label, factory(reading))));
151
47
  cancelled(signal);
152
- const grouped = new Set(results.flatMap(result => result.grouped ?? []));
153
- return {
154
- items: results.flatMap(result => result.items).filter(item => !grouped.has(item.id)),
155
- problems: results.flatMap(result => result.problems),
156
- };
157
- }
158
- async function prepare(selection, describe) {
159
- const domain = prepareDomains.get(kindOf(selection.id));
160
- if (!domain)
161
- throw new Error('unknown-selection');
162
- return domain.prepare(selection, describe);
48
+ return { items: results.flatMap(result => result.items), problems: results.flatMap(result => result.problems) };
163
49
  }
164
- return {
165
- inspect,
166
- async plan(input, signal, progress) {
167
- cancelled(signal);
168
- if (lifecycle.phase === 'preparing' || lifecycle.phase === 'applying')
169
- throw new Error('operation-in-progress');
170
- lifecycle = { phase: 'preparing' };
171
- const emit = progressGuard(progress);
172
- const observe = (id, title) => ({
173
- ...(signal ? { signal } : {}),
174
- report(stage) {
175
- emit({ id, title, stage });
176
- },
177
- });
178
- try {
179
- if ('resume' in input) {
180
- const saved = remaining;
181
- remaining = undefined;
182
- if (!saved || saved.id !== input.resume)
183
- throw new Error('plan-unavailable');
184
- const plan = { id: randomUUID(), items: saved.items, problem: null };
185
- lifecycle = { phase: 'ready', plan, work: saved.work };
186
- return structuredClone(plan);
50
+ async function apply(planId, signal, progress) {
51
+ if (busy)
52
+ return failedRun('operation-in-progress');
53
+ const current = approved;
54
+ if (!current || current.plan.id !== planId)
55
+ return failedRun('plan-unavailable');
56
+ approved = undefined;
57
+ busy = true;
58
+ const notify = progressGuard(progress);
59
+ const problems = new Map();
60
+ const finished = new Set();
61
+ let wasCancelled = false;
62
+ const verify = (read) => readScope.run({
63
+ deadlineMs: performance.now() + VERIFICATION_TIMEOUT_MS,
64
+ commandTimeoutMs: VERIFICATION_TIMEOUT_MS,
65
+ timeoutCode: 'verification-timeout',
66
+ }, read);
67
+ const resultFor = (item) => {
68
+ const outcome = current.work.get(item.id)?.result();
69
+ const failure = problems.get(item.id);
70
+ const done = !!outcome?.complete && !item.problem && failure === undefined;
71
+ const effects = [...(outcome?.effects ?? [])];
72
+ const causes = new Set([
73
+ ...(item.problem ? [item.problem] : []),
74
+ ...(failure === undefined ? [] : [failure]),
75
+ ...(outcome?.problems ?? []),
76
+ ]);
77
+ if (!done && wasCancelled && !finished.has(item.id) && !item.problem)
78
+ causes.add('cancelled');
79
+ for (const problem of causes)
80
+ if (!effects.some(effect => effect.code === problem))
81
+ effects.push({
82
+ state: problem === 'cancelled' || problem === 'dependency-not-ready' ? 'skipped' : 'failed',
83
+ code: problem,
84
+ });
85
+ const hasEffect = effects.some(effect => effect.state === 'done' || effect.state === 'kept');
86
+ const failed = effects.some(effect => effect.state === 'failed');
87
+ const result = {
88
+ id: item.id,
89
+ title: item.title,
90
+ state: done
91
+ ? 'done'
92
+ : hasEffect
93
+ ? 'partial'
94
+ : failed
95
+ ? 'failed'
96
+ : causes.has('cancelled')
97
+ ? 'cancelled'
98
+ : causes.has('dependency-not-ready')
99
+ ? 'skipped'
100
+ : 'failed',
101
+ effects,
102
+ };
103
+ return result;
104
+ };
105
+ try {
106
+ for (const item of current.plan.items) {
107
+ const job = current.work.get(item.id);
108
+ if (!job || item.problem) {
109
+ notify({ kind: 'checked', id: item.id, result: resultFor(item) });
110
+ continue;
187
111
  }
188
- remaining = undefined;
189
- const snapshot = structuredClone(input);
190
- if (!['install', 'detach', 'uninstall', 'clean'].includes(snapshot.task))
191
- throw new Error('action-unavailable');
192
- if ('removeData' in snapshot && (snapshot.task !== 'uninstall' || typeof snapshot.removeData !== 'boolean'))
193
- throw new Error('action-unavailable');
194
- const shouldRemoveData = snapshot.task === 'uninstall' && snapshot.removeData === true;
195
- const request = snapshot.selected.map(pick => {
196
- if (pick.maintenance !== undefined &&
197
- (snapshot.task !== 'install' || !['update', 'reinstall', 'login'].includes(pick.maintenance)))
198
- throw new Error('action-unavailable');
199
- if (pick.removal !== undefined && (snapshot.task !== 'uninstall' || pick.removal !== 'detach'))
200
- throw new Error('action-unavailable');
201
- const isProgram = ['claude', 'officecli', 'ccline'].includes(kindOf(pick.id));
202
- const action = snapshot.task === 'install'
203
- ? (pick.maintenance ?? defaultInstallAction(pick.id))
204
- : snapshot.task === 'uninstall'
205
- ? pick.removal === 'detach' || !isProgram
206
- ? 'detach'
207
- : 'uninstall'
208
- : snapshot.task;
209
- return {
210
- id: pick.id,
211
- action,
212
- ...(pick.fields ? { fields: pick.fields } : {}),
213
- ...(shouldRemoveData && kindOf(pick.id) === 'claude' ? { removeData: true } : {}),
214
- };
215
- });
216
- const claudeRemovals = request.filter(selection => selection.action === 'uninstall' && kindOf(selection.id) === 'claude');
217
- if (shouldRemoveData && !claudeRemovals.length)
218
- throw new Error('claude-removal-required');
219
- const work = new Map();
220
- const items = [];
221
- const seen = new Set();
222
- const sorted = [...request].sort((a, b) => snapshot.task === 'uninstall'
223
- ? Number(kindOf(a.id) === 'claude') - Number(kindOf(b.id) === 'claude')
224
- : Number(kindOf(a.id) !== 'claude') - Number(kindOf(b.id) !== 'claude'));
225
- const hasOfficeConnectionChange = sorted.some(selection => kindOf(selection.id) === 'officecli' && selection.action !== 'update');
226
- /** 装配单项计划:成功记入 work 并取 changes,失败收敛为 problem 码 */
227
- const attach = async (id, prepareOperation) => {
228
- let problem = null;
229
- let changes = [];
230
- try {
231
- const operation = await prepareOperation();
232
- changes = operation.changes;
233
- work.set(id, operation);
234
- }
235
- catch (error) {
236
- problem = errorCode(error);
237
- }
238
- return { changes, problem };
239
- };
240
- const prepareItem = async (selection) => {
112
+ try {
241
113
  cancelled(signal);
242
- let title = planDisplayTitle(selection.id, sorted);
243
- let observer = observe(selection.id, title);
244
- return preparation.run({ ...observer, report: stage => observer.report(stage) }, async () => {
245
- observer.report('inspect');
246
- const { changes, problem } = await attach(selection.id, async () => {
247
- if (seen.has(selection.id))
248
- throw new Error('duplicate-selection');
249
- seen.add(selection.id);
250
- if (hasOfficeConnectionChange && OFFICECLI_ENTRY_IDS.includes(selection.id))
251
- throw new Error('overlapping-selection');
252
- return prepare(selection, resolved => {
253
- cancelled(signal);
254
- if (title === resolved)
255
- return;
256
- title = resolved;
257
- observer = observe(selection.id, title);
258
- observer.report('inspect');
259
- });
260
- });
261
- cancelled(signal);
262
- return { id: selection.id, title, action: selection.action, changes, problem };
114
+ await job.run({
115
+ ...(signal ? { signal } : {}),
116
+ perform: action => effectScope.run(action, signal),
117
+ verify,
118
+ started: () => notify({ kind: 'started', id: item.id }),
119
+ report: effect => notify({ kind: 'effect', id: item.id, effect }),
263
120
  });
264
- };
265
- let next = 0;
266
- const workers = await Promise.allSettled(Array.from({ length: Math.min(2, sorted.length) }, async () => {
267
- while (next < sorted.length) {
268
- const index = next++;
269
- const selection = sorted[index];
270
- if (selection)
271
- items[index] = await prepareItem(selection);
121
+ finished.add(item.id);
122
+ }
123
+ catch (error) {
124
+ if (errorCode(error) === 'cancelled') {
125
+ wasCancelled = true;
272
126
  }
273
- }));
274
- for (const result of workers)
275
- if (result.status === 'rejected')
276
- throw result.reason;
277
- if (shouldRemoveData) {
278
- await preparation.run(observe(CLAUDE_DATA_ID, knownTitle(CLAUDE_DATA_ID)), async () => {
279
- preparation.getStore()?.report('inspect');
280
- const { changes, problem } = await attach(CLAUDE_DATA_ID, () => prepareClaudeDataRemoval(preparationContext, async () => {
281
- for (const selection of claudeRemovals) {
282
- const program = work.get(selection.id);
283
- if (!program?.verify)
284
- throw new Error('dependency-not-ready');
285
- await program.verify();
286
- }
287
- }));
288
- items.push({
289
- id: CLAUDE_DATA_ID,
290
- title: knownTitle(CLAUDE_DATA_ID),
291
- action: 'uninstall',
292
- changes,
293
- problem,
294
- });
295
- });
127
+ else
128
+ problems.set(item.id, errorCode(error));
296
129
  }
297
- const plan = { id: randomUUID(), items, problem: items.length === 0 ? 'empty-selection' : null };
298
- cancelled(signal);
299
- lifecycle = { phase: 'ready', plan, work };
300
- return structuredClone(plan);
301
- }
302
- catch (error) {
303
- lifecycle = { phase: 'idle' };
304
- throw error;
305
- }
306
- finally {
307
- preparation.disable();
130
+ notify({ kind: 'checked', id: item.id, result: resultFor(item) });
131
+ if (wasCancelled)
132
+ break;
308
133
  }
309
- },
310
- async apply(planId, signal, progress) {
311
- if (lifecycle.phase !== 'ready' || lifecycle.plan.id !== planId)
312
- return planFailure([
313
- {
314
- id: 'plan',
315
- title: knownTitle('plan'),
316
- problem: lifecycle.phase === 'preparing' || lifecycle.phase === 'applying'
317
- ? 'operation-in-progress'
318
- : 'plan-unavailable',
319
- },
320
- ]);
321
- const current = lifecycle;
322
- lifecycle = { phase: 'applying' };
323
- if (current.plan.items.some(item => item.problem !== null)) {
324
- lifecycle = { phase: 'idle' };
325
- return planFailure(current.plan.items);
134
+ wasCancelled ||= signal?.aborted === true;
135
+ for (const [id, job] of current.work) {
136
+ try {
137
+ await verify(() => job.verify());
138
+ }
139
+ catch (error) {
140
+ problems.set(id, errorCode(error));
141
+ }
326
142
  }
327
- const guard = progressGuard(progress);
328
- const notify = (event) => guard(structuredClone(event));
329
- try {
330
- let hasClaudeFailure = false;
331
- let isClaudePlanInvalidated = false;
332
- const unfinished = new Map();
333
- const unfinishedItems = [];
334
- const runItem = async (item) => {
335
- const effects = [];
336
- const report = (effect) => {
337
- effects.push(effect);
338
- notify({ kind: 'effect', id: item.id, effect });
339
- };
340
- let state = 'done';
341
- let isPlanInvalidated = false;
342
- notify({ kind: 'started', id: item.id });
343
- try {
344
- cancelled(signal);
345
- if (hasClaudeFailure &&
346
- item.action !== 'detach' &&
347
- (kindOf(item.id) === 'plugin' || item.action === 'login' || item.id === CLAUDE_DATA_ID))
348
- throw new Error('dependency-not-ready');
349
- const operation = current.work.get(item.id);
350
- if (operation === undefined)
351
- throw new Error('plan-unavailable');
352
- await operation.run(report, signal);
353
- }
354
- catch (error) {
355
- const code = errorCode(error);
356
- isPlanInvalidated =
357
- INVALID_PROGRAM_PLAN_REASONS.has(code) || (code === 'dependency-not-ready' && isClaudePlanInvalidated);
358
- if (!effects.some(effect => effect.code === code && (effect.state === 'failed' || effect.state === 'skipped')))
359
- report({ state: code === 'cancelled' || code === 'dependency-not-ready' ? 'skipped' : 'failed', code });
360
- state =
361
- code === 'cancelled'
362
- ? 'cancelled'
363
- : effects.some(effect => effect.state === 'done')
364
- ? 'partial'
365
- : 'failed';
366
- if (kindOf(item.id) === 'claude' && !effects.some(effect => effect.code === 'program-ready')) {
367
- hasClaudeFailure = true;
368
- isClaudePlanInvalidated ||= isPlanInvalidated;
369
- }
370
- }
371
- let isPending = false;
372
- if (state !== 'done' && !isPlanInvalidated) {
373
- const operation = current.work.get(item.id);
374
- const rest = operation?.remaining ? operation.remaining() : operation;
375
- if (rest) {
376
- isPending = true;
377
- unfinished.set(item.id, rest);
378
- unfinishedItems.push({ ...item, changes: rest.changes });
379
- }
380
- }
381
- const result = { id: item.id, title: item.title, state, effects, isPending };
382
- notify({ kind: 'finished', id: item.id, result });
383
- return result;
384
- };
385
- const results = [];
386
- if (current.plan.items.every(item => item.action === 'detach' && current.work.get(item.id)?.writes !== undefined))
387
- results.push(...(await detachBatch(ctx, current.plan.items, current.work, runItem)));
388
- else
389
- for (const item of current.plan.items)
390
- results.push(await runItem(item));
391
- const token = unfinished.size ? randomUUID() : undefined;
392
- if (token)
393
- remaining = {
394
- id: token,
395
- items: current.plan.items
396
- .filter(item => unfinished.has(item.id))
397
- .map(item => unfinishedItems.find(value => value.id === item.id) ?? item),
398
- work: unfinished,
399
- };
400
- const result = {
401
- state: results.some(item => item.state === 'cancelled')
402
- ? 'cancelled'
403
- : results.every(item => item.state === 'done') && current.plan.problem === null
404
- ? 'done'
405
- : results.some(item => item.state === 'done' || item.state === 'partial')
406
- ? 'partial'
407
- : 'failed',
408
- items: results,
409
- ...(token ? { remaining: token } : {}),
410
- };
411
- // 最近执行落盘供诊断收集读取,尽力而为
412
- await writeLastRun(ctx, current.plan, result, token);
143
+ const results = current.plan.items.map(item => {
144
+ const result = resultFor(item);
145
+ notify({ kind: 'finished', id: item.id, result });
413
146
  return result;
147
+ });
148
+ const result = {
149
+ state: results.every(item => item.state === 'done')
150
+ ? 'done'
151
+ : wasCancelled
152
+ ? 'cancelled'
153
+ : results.some(item => item.state === 'done' || item.state === 'partial')
154
+ ? 'partial'
155
+ : 'failed',
156
+ items: results,
157
+ };
158
+ return result;
159
+ }
160
+ catch (error) {
161
+ return failedRun(errorCode(error));
162
+ }
163
+ finally {
164
+ busy = false;
165
+ }
166
+ }
167
+ return {
168
+ inspect,
169
+ async plan(input, signal, progress) {
170
+ if (busy)
171
+ throw new Error('operation-in-progress');
172
+ approved = undefined;
173
+ busy = true;
174
+ try {
175
+ const current = await plan(input, signal, progressGuard(progress));
176
+ approved = current;
177
+ return structuredClone(current.plan);
414
178
  }
415
179
  finally {
416
- lifecycle = { phase: 'idle' };
180
+ busy = false;
417
181
  }
418
182
  },
183
+ apply: (id, signal, progress) => readScope.run({ ...(signal ? { signal } : {}) }, () => apply(id, signal, progress)),
184
+ };
185
+ }
186
+ const failedRun = (problem) => ({
187
+ state: 'failed',
188
+ items: [{ id: 'plan', title: '操作计划', state: 'failed', effects: [{ state: 'failed', code: problem }] }],
189
+ });
190
+ /** 复制公开进度并隔离接收器异常 */
191
+ function progressGuard(callback) {
192
+ let observer = callback;
193
+ return (event) => {
194
+ if (!observer)
195
+ return;
196
+ try {
197
+ void Promise.resolve(observer(structuredClone(event))).catch(() => {
198
+ observer = undefined;
199
+ });
200
+ }
201
+ catch {
202
+ observer = undefined;
203
+ }
419
204
  };
420
205
  }