clawt 3.10.4 → 3.10.6

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.
Files changed (48) hide show
  1. package/AGENTS.md +16 -0
  2. package/dist/index.js +228 -86
  3. package/dist/postinstall.js +27 -0
  4. package/docs/create.md +1 -0
  5. package/docs/list.md +21 -10
  6. package/docs/merge.md +1 -0
  7. package/docs/remove.md +2 -0
  8. package/docs/spec.md +4 -1
  9. package/docs/status.md +9 -1
  10. package/docs/superpowers/findings/2026-06-01-sync-validate-diverged-findings.md +203 -0
  11. package/docs/superpowers/findings/2026-06-09-worktree-base-branch-findings.md +58 -0
  12. package/docs/superpowers/plans/2026-06-01-validate-ignored-files-conflict.md +412 -0
  13. package/docs/superpowers/plans/2026-06-09-worktree-base-branch.md +386 -0
  14. package/docs/superpowers/specs/2026-06-01-validate-ignored-files-conflict-design.md +76 -0
  15. package/docs/superpowers/specs/2026-06-09-worktree-base-branch-design.md +169 -0
  16. package/docs/validate.md +42 -5
  17. package/package.json +1 -1
  18. package/src/commands/list.ts +5 -3
  19. package/src/commands/merge.ts +1 -1
  20. package/src/commands/remove.ts +3 -0
  21. package/src/commands/status.ts +5 -0
  22. package/src/constants/messages/validate.ts +17 -0
  23. package/src/types/status.ts +2 -0
  24. package/src/types/worktree.ts +12 -0
  25. package/src/utils/formatter.ts +22 -0
  26. package/src/utils/git-core.ts +23 -0
  27. package/src/utils/index.ts +4 -2
  28. package/src/utils/interactive-panel-render.ts +6 -3
  29. package/src/utils/validate-core.ts +52 -0
  30. package/src/utils/worktree-metadata.ts +82 -0
  31. package/src/utils/worktree.ts +29 -10
  32. package/tests/helpers/fixtures.ts +1 -0
  33. package/tests/unit/commands/cover-validate.test.ts +4 -4
  34. package/tests/unit/commands/create.test.ts +3 -3
  35. package/tests/unit/commands/list.test.ts +66 -3
  36. package/tests/unit/commands/merge.test.ts +1 -1
  37. package/tests/unit/commands/remove.test.ts +24 -18
  38. package/tests/unit/commands/resume.test.ts +21 -21
  39. package/tests/unit/commands/run.test.ts +17 -17
  40. package/tests/unit/commands/status.test.ts +85 -10
  41. package/tests/unit/commands/sync.test.ts +4 -4
  42. package/tests/unit/commands/validate.test.ts +1 -1
  43. package/tests/unit/utils/git-core.test.ts +43 -0
  44. package/tests/unit/utils/interactive-panel-render.test.ts +124 -0
  45. package/tests/unit/utils/validate-core.test.ts +60 -0
  46. package/tests/unit/utils/worktree-matcher.test.ts +2 -2
  47. package/tests/unit/utils/worktree-metadata.test.ts +91 -0
  48. package/tests/unit/utils/worktree.test.ts +65 -0
@@ -33,6 +33,14 @@ vi.mock('../../../src/constants/index.js', async (importOriginal) => {
33
33
  };
34
34
  });
35
35
 
36
+ vi.mock('../../../src/utils/i18n.js', async (importOriginal) => {
37
+ const actual = await importOriginal<typeof import('../../../src/utils/i18n.js')>();
38
+ return {
39
+ ...actual,
40
+ getCurrentLanguage: vi.fn(() => 'zh'),
41
+ };
42
+ });
43
+
36
44
  vi.mock('../../../src/utils/index.js', () => ({
37
45
  runPreChecks: vi.fn(),
38
46
  getProjectName: vi.fn(),
@@ -52,6 +60,7 @@ vi.mock('../../../src/utils/index.js', () => ({
52
60
  printSeparator: vi.fn(),
53
61
  loadProjectConfig: vi.fn().mockReturnValue(null),
54
62
  checkBranchExists: vi.fn().mockReturnValue(true),
63
+ formatBaseBranchLine: vi.fn((baseBranch: string | null | undefined) => `来源分支: ${baseBranch ?? '未记录'}`),
55
64
  }));
56
65
 
57
66
  import { registerStatusCommand } from '../../../src/commands/status.js';
@@ -122,7 +131,7 @@ describe('handleStatus', () => {
122
131
 
123
132
  it('--json 输出完整 JSON 结构', async () => {
124
133
  mockedGetProjectWorktrees.mockReturnValue([
125
- { path: '/path/feature', branch: 'feature' },
134
+ { path: '/path/feature', branch: 'feature', baseBranch: null },
126
135
  ]);
127
136
  mockedGetCommitDivergenceAsync.mockResolvedValue({ ahead: 2, behind: 0 });
128
137
  mockedGetDiffStatAsync.mockResolvedValue({ insertions: 10, deletions: 5 });
@@ -148,7 +157,7 @@ describe('handleStatus', () => {
148
157
 
149
158
  it('有 worktree 时收集正确的变更状态', async () => {
150
159
  mockedGetProjectWorktrees.mockReturnValue([
151
- { path: '/path/feature', branch: 'feature' },
160
+ { path: '/path/feature', branch: 'feature', baseBranch: null },
152
161
  ]);
153
162
  // 模拟冲突状态:porcelain 输出包含 UU 前缀的行
154
163
  mockedGetStatusPorcelainAsync.mockResolvedValue('UU src/conflict-file.ts');
@@ -187,7 +196,7 @@ describe('handleStatus', () => {
187
196
  it('快照摘要包含总数和孤立数', async () => {
188
197
  mockedGetProjectSnapshotBranches.mockReturnValue(['feature', 'deleted-branch']);
189
198
  mockedGetProjectWorktrees.mockReturnValue([
190
- { path: '/path/feature', branch: 'feature' },
199
+ { path: '/path/feature', branch: 'feature', baseBranch: null },
191
200
  ]);
192
201
 
193
202
  const consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
@@ -207,7 +216,7 @@ describe('handleStatus', () => {
207
216
 
208
217
  it('uncommitted 变更状态正确检测', async () => {
209
218
  mockedGetProjectWorktrees.mockReturnValue([
210
- { path: '/path/feature', branch: 'feature' },
219
+ { path: '/path/feature', branch: 'feature', baseBranch: null },
211
220
  ]);
212
221
  // 模拟未提交修改:porcelain 输出包含修改但非冲突的行
213
222
  mockedGetStatusPorcelainAsync.mockResolvedValue(' M src/file.ts'); // 目标 worktree 有未提交修改
@@ -228,7 +237,7 @@ describe('handleStatus', () => {
228
237
 
229
238
  it('createdAt 字段包含在 JSON 输出中', async () => {
230
239
  mockedGetProjectWorktrees.mockReturnValue([
231
- { path: '/path/feature', branch: 'feature' },
240
+ { path: '/path/feature', branch: 'feature', baseBranch: null },
232
241
  ]);
233
242
  mockedGetWorktreeCreatedTime.mockReturnValue('2026-02-20T14:30:00+08:00');
234
243
 
@@ -248,7 +257,7 @@ describe('handleStatus', () => {
248
257
 
249
258
  it('snapshotTime 字段包含在 JSON 输出中', async () => {
250
259
  mockedGetProjectWorktrees.mockReturnValue([
251
- { path: '/path/feature', branch: 'feature' },
260
+ { path: '/path/feature', branch: 'feature', baseBranch: null },
252
261
  ]);
253
262
  mockedGetSnapshotModifiedTime.mockReturnValue('2026-02-22T10:00:00.000Z');
254
263
 
@@ -268,7 +277,7 @@ describe('handleStatus', () => {
268
277
 
269
278
  it('文本模式显示分支创建时间', async () => {
270
279
  mockedGetProjectWorktrees.mockReturnValue([
271
- { path: '/path/feature', branch: 'feature' },
280
+ { path: '/path/feature', branch: 'feature', baseBranch: null },
272
281
  ]);
273
282
  mockedGetWorktreeCreatedTime.mockReturnValue('2026-02-20T14:30:00+08:00');
274
283
  mockedFormatRelativeTime.mockReturnValue('2 天前');
@@ -285,7 +294,7 @@ describe('handleStatus', () => {
285
294
 
286
295
  it('文本模式 createdAt 为 null 时不显示创建时间', async () => {
287
296
  mockedGetProjectWorktrees.mockReturnValue([
288
- { path: '/path/feature', branch: 'feature' },
297
+ { path: '/path/feature', branch: 'feature', baseBranch: null },
289
298
  ]);
290
299
  mockedGetWorktreeCreatedTime.mockReturnValue(null);
291
300
 
@@ -301,7 +310,7 @@ describe('handleStatus', () => {
301
310
 
302
311
  it('文本模式无快照时显示未验证警示', async () => {
303
312
  mockedGetProjectWorktrees.mockReturnValue([
304
- { path: '/path/feature', branch: 'feature' },
313
+ { path: '/path/feature', branch: 'feature', baseBranch: null },
305
314
  ]);
306
315
  mockedGetSnapshotModifiedTime.mockReturnValue(null);
307
316
 
@@ -317,7 +326,7 @@ describe('handleStatus', () => {
317
326
 
318
327
  it('文本模式有快照时显示上次验证时间', async () => {
319
328
  mockedGetProjectWorktrees.mockReturnValue([
320
- { path: '/path/feature', branch: 'feature' },
329
+ { path: '/path/feature', branch: 'feature', baseBranch: null },
321
330
  ]);
322
331
  mockedGetSnapshotModifiedTime.mockReturnValue('2026-02-22T10:00:00.000Z');
323
332
  mockedFormatRelativeTime.mockReturnValue('5 小时前');
@@ -370,4 +379,70 @@ describe('handleStatus', () => {
370
379
  expect(parsed.main.insertions).toBe(0);
371
380
  expect(parsed.main.deletions).toBe(0);
372
381
  });
382
+
383
+ it('--json 输出包含 baseBranch 字段', async () => {
384
+ mockedGetProjectWorktrees.mockReturnValue([
385
+ { path: '/path/feature', branch: 'feature', baseBranch: 'test' },
386
+ ]);
387
+
388
+ const consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
389
+
390
+ const program = new Command();
391
+ program.exitOverride();
392
+ registerStatusCommand(program);
393
+ await program.parseAsync(['status', '--json'], { from: 'user' });
394
+
395
+ const jsonCall = consoleSpy.mock.calls.find((call) => {
396
+ try { JSON.parse(call[0]); return true; } catch { return false; }
397
+ });
398
+ expect(jsonCall).toBeDefined();
399
+ const parsed = JSON.parse(jsonCall![0]);
400
+ expect(parsed.worktrees[0].baseBranch).toBe('test');
401
+ });
402
+
403
+ it('--json 输出 baseBranch 为 null 时字段值为 null', async () => {
404
+ mockedGetProjectWorktrees.mockReturnValue([
405
+ { path: '/path/feature', branch: 'feature', baseBranch: null },
406
+ ]);
407
+
408
+ const consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
409
+
410
+ const program = new Command();
411
+ program.exitOverride();
412
+ registerStatusCommand(program);
413
+ await program.parseAsync(['status', '--json'], { from: 'user' });
414
+
415
+ const jsonCall = consoleSpy.mock.calls.find((call) => {
416
+ try { JSON.parse(call[0]); return true; } catch { return false; }
417
+ });
418
+ expect(jsonCall).toBeDefined();
419
+ const parsed = JSON.parse(jsonCall![0]);
420
+ expect(parsed.worktrees[0].baseBranch).toBeNull();
421
+ });
422
+
423
+ it('文本模式显示来源分支行', async () => {
424
+ mockedGetProjectWorktrees.mockReturnValue([
425
+ { path: '/path/feature', branch: 'feature', baseBranch: 'test' },
426
+ ]);
427
+
428
+ const program = new Command();
429
+ program.exitOverride();
430
+ registerStatusCommand(program);
431
+ await program.parseAsync(['status'], { from: 'user' });
432
+
433
+ expect(mockedPrintInfo).toHaveBeenCalledWith(expect.stringContaining('来源分支: test'));
434
+ });
435
+
436
+ it('文本模式 baseBranch 为 null 时显示未记录', async () => {
437
+ mockedGetProjectWorktrees.mockReturnValue([
438
+ { path: '/path/feature', branch: 'feature', baseBranch: null },
439
+ ]);
440
+
441
+ const program = new Command();
442
+ program.exitOverride();
443
+ registerStatusCommand(program);
444
+ await program.parseAsync(['status'], { from: 'user' });
445
+
446
+ expect(mockedPrintInfo).toHaveBeenCalledWith(expect.stringContaining('来源分支: 未记录'));
447
+ });
373
448
  });
@@ -110,7 +110,7 @@ describe('registerSyncCommand', () => {
110
110
 
111
111
  describe('handleSync', () => {
112
112
  it('目标 worktree 干净时直接合并', async () => {
113
- const worktree = { path: '/path/feature', branch: 'feature' };
113
+ const worktree = { path: '/path/feature', branch: 'feature', baseBranch: null };
114
114
  mockedGetProjectWorktrees.mockReturnValue([worktree]);
115
115
  mockedResolveTargetWorktree.mockResolvedValue(worktree);
116
116
  mockedIsWorkingDirClean.mockReturnValue(true);
@@ -126,7 +126,7 @@ describe('handleSync', () => {
126
126
  });
127
127
 
128
128
  it('目标 worktree 有未提交变更时自动保存后合并', async () => {
129
- const worktree = { path: '/path/feature', branch: 'feature' };
129
+ const worktree = { path: '/path/feature', branch: 'feature', baseBranch: null };
130
130
  mockedGetProjectWorktrees.mockReturnValue([worktree]);
131
131
  mockedResolveTargetWorktree.mockResolvedValue(worktree);
132
132
  mockedIsWorkingDirClean.mockReturnValue(false);
@@ -145,7 +145,7 @@ describe('handleSync', () => {
145
145
  });
146
146
 
147
147
  it('合并冲突时输出警告并返回', async () => {
148
- const worktree = { path: '/path/feature', branch: 'feature' };
148
+ const worktree = { path: '/path/feature', branch: 'feature', baseBranch: null };
149
149
  mockedGetProjectWorktrees.mockReturnValue([worktree]);
150
150
  mockedResolveTargetWorktree.mockResolvedValue(worktree);
151
151
  mockedIsWorkingDirClean.mockReturnValue(true);
@@ -162,7 +162,7 @@ describe('handleSync', () => {
162
162
  });
163
163
 
164
164
  it('合并失败(非冲突错误)时向上抛出', async () => {
165
- const worktree = { path: '/path/feature', branch: 'feature' };
165
+ const worktree = { path: '/path/feature', branch: 'feature', baseBranch: null };
166
166
  mockedGetProjectWorktrees.mockReturnValue([worktree]);
167
167
  mockedResolveTargetWorktree.mockResolvedValue(worktree);
168
168
  mockedIsWorkingDirClean.mockReturnValue(true);
@@ -155,7 +155,7 @@ const mockedSwitchToValidateBranch = vi.mocked(switchToValidateBranch);
155
155
  const mockedExecuteRunCommand = vi.mocked(executeRunCommand);
156
156
  const mockedGetValidateRunCommand = vi.mocked(getValidateRunCommand);
157
157
 
158
- const worktree = { path: '/path/feature', branch: 'feature' };
158
+ const worktree = { path: '/path/feature', branch: 'feature', baseBranch: null };
159
159
 
160
160
  beforeEach(() => {
161
161
  mockedGetGitTopLevel.mockReturnValue('/repo');
@@ -0,0 +1,43 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+ import { gitCheckIgnored } from '../../../src/utils/git-core.js';
3
+
4
+ // mock child_process
5
+ vi.mock('node:child_process', () => ({
6
+ execSync: vi.fn(),
7
+ execFileSync: vi.fn(),
8
+ exec: vi.fn(),
9
+ }));
10
+
11
+ import { execFileSync } from 'node:child_process';
12
+ const mockExecFileSync = vi.mocked(execFileSync);
13
+
14
+ describe('gitCheckIgnored', () => {
15
+ beforeEach(() => {
16
+ vi.clearAllMocks();
17
+ });
18
+
19
+ it('空数组输入时返回空数组', () => {
20
+ const result = gitCheckIgnored([]);
21
+ expect(result).toEqual([]);
22
+ expect(mockExecFileSync).not.toHaveBeenCalled();
23
+ });
24
+
25
+ it('全部被忽略时返回全部路径', () => {
26
+ mockExecFileSync.mockReturnValue('docs/superpowers/a.md\ndocs/superpowers/b.md\n');
27
+ const result = gitCheckIgnored(['docs/superpowers/a.md', 'docs/superpowers/b.md']);
28
+ expect(result).toEqual(['docs/superpowers/a.md', 'docs/superpowers/b.md']);
29
+ });
30
+
31
+ it('全部不被忽略时返回空数组', () => {
32
+ // git check-ignore 无匹配时退出码为 1,execFileSync 抛出异常
33
+ mockExecFileSync.mockImplementation(() => { throw new Error('exit code 1'); });
34
+ const result = gitCheckIgnored(['src/index.ts']);
35
+ expect(result).toEqual([]);
36
+ });
37
+
38
+ it('混合场景时仅返回被忽略的路径', () => {
39
+ mockExecFileSync.mockReturnValue('docs/superpowers/a.md\n');
40
+ const result = gitCheckIgnored(['docs/superpowers/a.md', 'src/index.ts']);
41
+ expect(result).toEqual(['docs/superpowers/a.md']);
42
+ });
43
+ });
@@ -0,0 +1,124 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+
3
+ // mock 常量模块
4
+ vi.mock('../../../src/constants/index.js', () => ({
5
+ SELECTED_INDICATOR: '▶',
6
+ UNSELECTED_INDICATOR: ' ',
7
+ PANEL_DATE_SEPARATOR_PREFIX: '─',
8
+ PANEL_SEPARATOR_MAX_WIDTH: 60,
9
+ PANEL_DATE_COLOR: '#FF8C00',
10
+ UNKNOWN_DATE_GROUP: 'UNKNOWN',
11
+ VALIDATE_BRANCH_PREFIX: 'clawt-validate-',
12
+ MESSAGES: {
13
+ STATUS_CHANGE_COMMITTED: '已提交',
14
+ STATUS_CHANGE_UNCOMMITTED: '未提交',
15
+ STATUS_CHANGE_CONFLICT: '冲突',
16
+ STATUS_CHANGE_CLEAN: '干净',
17
+ STATUS_CREATED_AT: (relativeTime: string) => `创建于 ${relativeTime}`,
18
+ STATUS_LAST_VALIDATED: (relativeTime: string) => `上次验证: ${relativeTime}`,
19
+ STATUS_NOT_VALIDATED: '✗ 未验证',
20
+ },
21
+ }));
22
+
23
+ // mock i18n 模块
24
+ vi.mock('../../../src/utils/i18n.js', () => ({
25
+ getCurrentLanguage: vi.fn(() => 'zh'),
26
+ }));
27
+
28
+ // mock 消息常量
29
+ vi.mock('../../../src/constants/messages/index.js', () => ({
30
+ PANEL_COMMITS_AHEAD: (count: number) => `${count} 个本地提交`,
31
+ PANEL_COMMITS_BEHIND: (count: number) => `落后主分支 ${count} 个提交`,
32
+ PANEL_SYNCED_WITH_MAIN: '与主分支同步',
33
+ PANEL_FOOTER_SHORTCUTS: 'footer shortcuts',
34
+ PANEL_FOOTER_COUNTDOWN: (s: number) => `${s}s`,
35
+ PANEL_OVERFLOW_DOWN_HINT: '↓ more',
36
+ PANEL_OVERFLOW_UP_HINT: '↑ more',
37
+ PANEL_SNAPSHOT_SUMMARY: (total: number, orphaned: number) => `快照 ${total}/${orphaned}`,
38
+ PANEL_NO_WORKTREES_MSG: 'no worktrees',
39
+ PANEL_TITLE: (name: string) => `Title: ${name}`,
40
+ PANEL_CONFIGURED_BRANCH: (branch: string) => `配置分支: ${branch}`,
41
+ PANEL_CONFIGURED_BRANCH_DELETED: (branch: string) => `配置分支已删除: ${branch}`,
42
+ PANEL_CONFIGURED_BRANCH_MISMATCH: (branch: string) => `配置分支不匹配: ${branch}`,
43
+ PANEL_NOT_INITIALIZED: '未初始化',
44
+ PANEL_UNKNOWN_DATE: '未知日期',
45
+ }));
46
+
47
+ // mock utils/index.js(仅 mock renderWorktreeBlock 用到的函数)
48
+ vi.mock('../../../src/utils/index.js', () => ({
49
+ formatRelativeTime: vi.fn((iso: string) => iso ? '3 天前' : null),
50
+ groupWorktreesByDate: vi.fn(() => new Map()),
51
+ formatRelativeDate: vi.fn(() => '3 天前'),
52
+ formatBaseBranchLine: vi.fn((baseBranch: string | null | undefined) => `来源分支: ${baseBranch ?? '未记录'}`),
53
+ }));
54
+
55
+ import { renderWorktreeBlock } from '../../../src/utils/interactive-panel-render.js';
56
+ import type { WorktreeDetailedStatus } from '../../../src/types/index.js';
57
+
58
+ describe('renderWorktreeBlock', () => {
59
+ it('渲染包含来源分支行(baseBranch 有值)', () => {
60
+ const wt: WorktreeDetailedStatus = {
61
+ path: '/path/feature',
62
+ branch: 'feature',
63
+ baseBranch: 'test',
64
+ changeStatus: 'clean',
65
+ commitsAhead: 0,
66
+ commitsBehind: 0,
67
+ snapshotTime: null,
68
+ insertions: 0,
69
+ deletions: 0,
70
+ createdAt: null,
71
+ };
72
+
73
+ const lines = renderWorktreeBlock(wt, false);
74
+ const joined = lines.join('\n');
75
+ expect(joined).toContain('来源分支: test');
76
+ });
77
+
78
+ it('渲染包含来源分支行(baseBranch 为 null 时显示未记录)', () => {
79
+ const wt: WorktreeDetailedStatus = {
80
+ path: '/path/feature',
81
+ branch: 'feature',
82
+ baseBranch: null,
83
+ changeStatus: 'clean',
84
+ commitsAhead: 0,
85
+ commitsBehind: 0,
86
+ snapshotTime: null,
87
+ insertions: 0,
88
+ deletions: 0,
89
+ createdAt: null,
90
+ };
91
+
92
+ const lines = renderWorktreeBlock(wt, false);
93
+ const joined = lines.join('\n');
94
+ expect(joined).toContain('来源分支: 未记录');
95
+ });
96
+
97
+ it('来源分支行位于同步状态行之后、创建时间行之前', () => {
98
+ const wt: WorktreeDetailedStatus = {
99
+ path: '/path/feature',
100
+ branch: 'feature',
101
+ baseBranch: 'main',
102
+ changeStatus: 'clean',
103
+ commitsAhead: 0,
104
+ commitsBehind: 0,
105
+ snapshotTime: null,
106
+ insertions: 0,
107
+ deletions: 0,
108
+ createdAt: '2026-02-20T14:30:00+08:00',
109
+ };
110
+
111
+ const lines = renderWorktreeBlock(wt, false);
112
+ const joined = lines.join('\n');
113
+
114
+ // 来源分支在同步状态之后
115
+ const syncIdx = joined.indexOf('与主分支同步');
116
+ const baseBranchIdx = joined.indexOf('来源分支: main');
117
+ expect(syncIdx).toBeGreaterThanOrEqual(0);
118
+ expect(baseBranchIdx).toBeGreaterThan(syncIdx);
119
+
120
+ // 来源分支在创建时间之前
121
+ const createdAtIdx = joined.indexOf('创建于');
122
+ expect(createdAtIdx).toBeGreaterThan(baseBranchIdx);
123
+ });
124
+ });
@@ -0,0 +1,60 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+
3
+ vi.mock('../../../src/utils/git-core.js', async () => {
4
+ const actual = await vi.importActual('../../../src/utils/git-core.js');
5
+ return { ...actual, gitCheckIgnored: vi.fn() };
6
+ });
7
+
8
+ vi.mock('node:fs', () => ({
9
+ existsSync: vi.fn(),
10
+ mkdirSync: vi.fn(),
11
+ }));
12
+
13
+ vi.mock('../../../src/utils/shell.js', async () => {
14
+ const actual = await vi.importActual('../../../src/utils/shell.js');
15
+ return { ...actual, execCommand: vi.fn() };
16
+ });
17
+
18
+ import { detectIgnoredFilesInPatch } from '../../../src/utils/validate-core.js';
19
+ import { gitCheckIgnored } from '../../../src/utils/git-core.js';
20
+ import { existsSync } from 'node:fs';
21
+ import { execCommand } from '../../../src/utils/shell.js';
22
+
23
+ const mockGitCheckIgnored = vi.mocked(gitCheckIgnored);
24
+ const mockExistsSync = vi.mocked(existsSync);
25
+ const mockExecCommand = vi.mocked(execCommand);
26
+
27
+ describe('detectIgnoredFilesInPatch', () => {
28
+ beforeEach(() => {
29
+ vi.clearAllMocks();
30
+ });
31
+
32
+ it('无幽灵文件时返回空数组', () => {
33
+ mockExecCommand.mockReturnValue('src/a.ts\nsrc/b.ts');
34
+ mockGitCheckIgnored.mockReturnValue([]);
35
+ const result = detectIgnoredFilesInPatch('feature', '/main');
36
+ expect(result).toEqual([]);
37
+ });
38
+
39
+ it('检测到幽灵文件时返回文件列表', () => {
40
+ mockExecCommand.mockReturnValue('docs/superpowers/a.md\nsrc/b.ts');
41
+ mockGitCheckIgnored.mockReturnValue(['docs/superpowers/a.md']);
42
+ mockExistsSync.mockImplementation((p: string) => p === '/main/docs/superpowers/a.md');
43
+ const result = detectIgnoredFilesInPatch('feature', '/main');
44
+ expect(result).toEqual(['docs/superpowers/a.md']);
45
+ });
46
+
47
+ it('被忽略但物理不存在的文件不包含在结果中', () => {
48
+ mockExecCommand.mockReturnValue('docs/superpowers/a.md');
49
+ mockGitCheckIgnored.mockReturnValue(['docs/superpowers/a.md']);
50
+ mockExistsSync.mockReturnValue(false);
51
+ const result = detectIgnoredFilesInPatch('feature', '/main');
52
+ expect(result).toEqual([]);
53
+ });
54
+
55
+ it('git diff --name-only 失败时返回空数组(降级)', () => {
56
+ mockExecCommand.mockImplementation(() => { throw new Error('fatal'); });
57
+ const result = detectIgnoredFilesInPatch('feature', '/main');
58
+ expect(result).toEqual([]);
59
+ });
60
+ });
@@ -272,7 +272,7 @@ describe('groupWorktreesByDate', () => {
272
272
 
273
273
  describe('buildGroupedChoices', () => {
274
274
  it('构建的 choices 包含全局全选、分隔线、组全选和分支', () => {
275
- const groups = new Map<string, Array<{ path: string; branch: string }>>([
275
+ const groups = new Map<string, Array<{ path: string; branch: string; baseBranch: string | null }>>([
276
276
  ['2026-02-26', [
277
277
  createWorktreeInfo({ branch: 'feature-auth' }),
278
278
  createWorktreeInfo({ branch: 'feature-login' }),
@@ -317,7 +317,7 @@ describe('buildGroupedChoices', () => {
317
317
 
318
318
  describe('buildGroupMembershipMap', () => {
319
319
  it('构建组全选 name 到分支 name 列表的正确映射', () => {
320
- const groups = new Map<string, Array<{ path: string; branch: string }>>([
320
+ const groups = new Map<string, Array<{ path: string; branch: string; baseBranch: string | null }>>([
321
321
  ['2026-02-26', [
322
322
  createWorktreeInfo({ branch: 'feature-auth' }),
323
323
  createWorktreeInfo({ branch: 'feature-login' }),
@@ -0,0 +1,91 @@
1
+ import { describe, expect, it, vi, beforeEach } from 'vitest';
2
+
3
+ vi.mock('node:fs', () => ({
4
+ existsSync: vi.fn(),
5
+ mkdirSync: vi.fn(),
6
+ readFileSync: vi.fn(),
7
+ rmSync: vi.fn(),
8
+ writeFileSync: vi.fn(),
9
+ }));
10
+
11
+ vi.mock('../../../src/constants/index.js', async (importOriginal) => {
12
+ const actual = await importOriginal<typeof import('../../../src/constants/index.js')>();
13
+ return {
14
+ ...actual,
15
+ PROJECTS_CONFIG_DIR: '/tmp/clawt-projects',
16
+ };
17
+ });
18
+
19
+ import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
20
+ import {
21
+ getWorktreeMetadataPath,
22
+ loadWorktreeMetadata,
23
+ removeWorktreeMetadata,
24
+ saveWorktreeMetadata,
25
+ } from '../../../src/utils/worktree-metadata.js';
26
+
27
+ beforeEach(() => {
28
+ vi.clearAllMocks();
29
+ });
30
+
31
+ describe('worktree metadata', () => {
32
+ it('生成项目 worktree 元数据路径', () => {
33
+ expect(getWorktreeMetadataPath('demo', 'feature')).toBe('/tmp/clawt-projects/demo/worktrees/feature.json');
34
+ });
35
+
36
+ it('保存并读取来源分支元数据', () => {
37
+ vi.mocked(existsSync).mockReturnValue(true);
38
+ vi.mocked(readFileSync).mockReturnValue(JSON.stringify({
39
+ branch: 'feature',
40
+ baseBranch: 'test',
41
+ createdAt: '2026-06-09T10:30:00.000Z',
42
+ }));
43
+
44
+ saveWorktreeMetadata('demo', {
45
+ branch: 'feature',
46
+ baseBranch: 'test',
47
+ createdAt: '2026-06-09T10:30:00.000Z',
48
+ });
49
+
50
+ expect(writeFileSync).toHaveBeenCalledWith(
51
+ '/tmp/clawt-projects/demo/worktrees/feature.json',
52
+ expect.stringContaining('"baseBranch": "test"'),
53
+ 'utf-8',
54
+ );
55
+ expect(loadWorktreeMetadata('demo', 'feature')?.baseBranch).toBe('test');
56
+ });
57
+
58
+ it('元数据不存在时返回 null', () => {
59
+ vi.mocked(existsSync).mockReturnValue(false);
60
+ expect(loadWorktreeMetadata('demo', 'missing')).toBeNull();
61
+ });
62
+
63
+ it('removeWorktreeMetadata 正常删除文件', () => {
64
+ vi.mocked(existsSync).mockReturnValue(true);
65
+ removeWorktreeMetadata('demo', 'feature');
66
+ expect(rmSync).toHaveBeenCalledWith('/tmp/clawt-projects/demo/worktrees/feature.json');
67
+ });
68
+
69
+ it('removeWorktreeMetadata 文件不存在时不报错且不调用 rmSync', () => {
70
+ vi.mocked(existsSync).mockReturnValue(false);
71
+ // 不应抛出异常
72
+ expect(() => removeWorktreeMetadata('demo', 'missing')).not.toThrow();
73
+ expect(rmSync).not.toHaveBeenCalled();
74
+ });
75
+
76
+ it('loadWorktreeMetadata JSON 损坏时返回 null', () => {
77
+ vi.mocked(existsSync).mockReturnValue(true);
78
+ vi.mocked(readFileSync).mockReturnValue('{ invalid json !!!');
79
+ expect(loadWorktreeMetadata('demo', 'corrupt')).toBeNull();
80
+ });
81
+
82
+ it('loadWorktreeMetadata 元数据格式无效(缺少 baseBranch)时返回 null', () => {
83
+ vi.mocked(existsSync).mockReturnValue(true);
84
+ vi.mocked(readFileSync).mockReturnValue(JSON.stringify({
85
+ branch: 'feature',
86
+ // 缺少 baseBranch 字段
87
+ createdAt: '2026-06-09T10:30:00.000Z',
88
+ }));
89
+ expect(loadWorktreeMetadata('demo', 'feature')).toBeNull();
90
+ });
91
+ });
@@ -54,6 +54,18 @@ vi.mock('../../../src/utils/validate-branch.js', () => ({
54
54
  deleteValidateBranch: vi.fn(),
55
55
  }));
56
56
 
57
+ // mock git-branch
58
+ vi.mock('../../../src/utils/git-branch.js', () => ({
59
+ getCurrentBranch: vi.fn().mockReturnValue('main'),
60
+ }));
61
+
62
+ // mock worktree-metadata
63
+ vi.mock('../../../src/utils/worktree-metadata.js', () => ({
64
+ saveWorktreeMetadata: vi.fn(),
65
+ loadWorktreeMetadata: vi.fn().mockReturnValue(null),
66
+ removeWorktreeMetadata: vi.fn(),
67
+ }));
68
+
57
69
  import { existsSync, readdirSync } from 'node:fs';
58
70
  import {
59
71
  getProjectName,
@@ -68,6 +80,8 @@ import {
68
80
  } from '../../../src/utils/git.js';
69
81
  import { sanitizeBranchName, validateBranchesNotExist } from '../../../src/utils/branch.js';
70
82
  import { ensureDir, removeEmptyDir } from '../../../src/utils/fs.js';
83
+ import { getCurrentBranch } from '../../../src/utils/git-branch.js';
84
+ import { saveWorktreeMetadata, loadWorktreeMetadata, removeWorktreeMetadata } from '../../../src/utils/worktree-metadata.js';
71
85
  import { createWorktrees, createWorktreesByBranches, getProjectWorktrees, cleanupWorktrees, getWorktreeStatus } from '../../../src/utils/worktree.js';
72
86
  import { createWorktreeInfo } from '../../helpers/fixtures.js';
73
87
 
@@ -80,6 +94,10 @@ const mockedDeleteBranch = vi.mocked(deleteBranch);
80
94
  const mockedGetCommitCountAhead = vi.mocked(getCommitCountAhead);
81
95
  const mockedGetDiffStat = vi.mocked(getDiffStat);
82
96
  const mockedIsWorkingDirClean = vi.mocked(isWorkingDirClean);
97
+ const mockedGetCurrentBranch = vi.mocked(getCurrentBranch);
98
+ const mockedSaveWorktreeMetadata = vi.mocked(saveWorktreeMetadata);
99
+ const mockedLoadWorktreeMetadata = vi.mocked(loadWorktreeMetadata);
100
+ const mockedRemoveWorktreeMetadata = vi.mocked(removeWorktreeMetadata);
83
101
 
84
102
  describe('createWorktrees', () => {
85
103
  it('单个 worktree 创建', () => {
@@ -105,6 +123,17 @@ describe('createWorktrees', () => {
105
123
  expect(validateBranchesNotExist).toHaveBeenCalled();
106
124
  expect(ensureDir).toHaveBeenCalled();
107
125
  });
126
+
127
+ it('创建 worktree 时记录当前分支为来源分支', () => {
128
+ mockedGetCurrentBranch.mockReturnValue('test');
129
+ const result = createWorktrees('feature', 1);
130
+ expect(result[0].baseBranch).toBe('test');
131
+ expect(mockedSaveWorktreeMetadata).toHaveBeenCalledWith('my-project', {
132
+ branch: 'feature',
133
+ baseBranch: 'test',
134
+ createdAt: expect.any(String),
135
+ });
136
+ });
108
137
  });
109
138
 
110
139
  describe('createWorktreesByBranches', () => {
@@ -152,6 +181,36 @@ describe('getProjectWorktrees', () => {
152
181
  expect(result).toHaveLength(1);
153
182
  expect(result[0].branch).toBe('feature');
154
183
  });
184
+
185
+ it('获取 worktree 时读取来源分支', () => {
186
+ mockedExistsSync.mockReturnValue(true);
187
+ mockedGitWorktreeList.mockReturnValue(
188
+ '/repo abc [main]\n/tmp/test-worktrees/my-project/feature def [feature]',
189
+ );
190
+ mockedReaddirSync.mockReturnValue([
191
+ { name: 'feature', isDirectory: () => true },
192
+ ] as any);
193
+ mockedLoadWorktreeMetadata.mockReturnValue({
194
+ branch: 'feature',
195
+ baseBranch: 'test',
196
+ createdAt: '2026-06-09T10:30:00.000Z',
197
+ });
198
+ const result = getProjectWorktrees();
199
+ expect(result[0].baseBranch).toBe('test');
200
+ });
201
+
202
+ it('获取 worktree 时无元数据则 baseBranch 为 null', () => {
203
+ mockedExistsSync.mockReturnValue(true);
204
+ mockedGitWorktreeList.mockReturnValue(
205
+ '/repo abc [main]\n/tmp/test-worktrees/my-project/feature def [feature]',
206
+ );
207
+ mockedReaddirSync.mockReturnValue([
208
+ { name: 'feature', isDirectory: () => true },
209
+ ] as any);
210
+ mockedLoadWorktreeMetadata.mockReturnValue(null);
211
+ const result = getProjectWorktrees();
212
+ expect(result[0].baseBranch).toBeNull();
213
+ });
155
214
  });
156
215
 
157
216
  describe('cleanupWorktrees', () => {
@@ -176,6 +235,12 @@ describe('cleanupWorktrees', () => {
176
235
  // 不应抛出异常
177
236
  expect(() => cleanupWorktrees(worktrees)).not.toThrow();
178
237
  });
238
+
239
+ it('清理 worktree 时删除元数据', () => {
240
+ const worktrees = [createWorktreeInfo({ branch: 'a', path: '/path/a' })];
241
+ cleanupWorktrees(worktrees);
242
+ expect(mockedRemoveWorktreeMetadata).toHaveBeenCalledWith('my-project', 'a');
243
+ });
179
244
  });
180
245
 
181
246
  describe('getWorktreeStatus', () => {