@hit-sudomaker/ccw 0.4.0 → 0.5.0

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