sillyspec 3.19.0 → 3.19.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sillyspec",
3
- "version": "3.19.0",
3
+ "version": "3.19.1",
4
4
  "description": "SillySpec CLI — 流程状态机,让 AI 严格按步骤来",
5
5
  "icon": "logo.jpg",
6
6
  "homepage": "https://sillyspec.ppdmq.top/",
package/src/worktree.js CHANGED
@@ -9,7 +9,7 @@
9
9
  */
10
10
 
11
11
  import { execSync } from 'child_process';
12
- import { existsSync, mkdirSync, readFileSync, writeFileSync, rmSync, readdirSync } from 'fs';
12
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, rmSync, readdirSync, statSync } from 'fs';
13
13
  import { join, resolve, dirname } from 'path';
14
14
  import { createHash } from 'crypto';
15
15
 
@@ -120,7 +120,43 @@ export function isGitWorktreeSupported(cwd = process.cwd()) {
120
120
  export class WorktreeManager {
121
121
  constructor({ cwd, worktreeDir } = {}) {
122
122
  this.cwd = cwd || process.cwd();
123
- this.worktreeBase = worktreeDir || resolve(this.cwd, WORKTREES_REL);
123
+
124
+ // worktreeBase 必须固定到主仓库路径,不能跟着 cwd 变化。
125
+ // native-worktree 模式下 cwd 是 worktree 子目录,用 cwd 推导 worktreeBase
126
+ // 会导致 meta 写入 worktree 内部路径,worktree 内再次执行时找不到。
127
+ // 解决:用 git rev-parse --git-common-dir 反推主仓库路径。
128
+ if (worktreeDir) {
129
+ this.worktreeBase = worktreeDir;
130
+ } else {
131
+ this.worktreeBase = resolve(this._resolveMainRepoRoot(), WORKTREES_REL);
132
+ }
133
+ }
134
+
135
+ /**
136
+ * 解析当前 git 环境对应的主仓库根目录
137
+ * 在主仓库内执行:返回 cwd 自身
138
+ * 在 linked worktree 内执行:返回 git-common-dir 的父目录(即主仓库 .git 所在地)
139
+ * @private
140
+ */
141
+ _resolveMainRepoRoot() {
142
+ try {
143
+ // git-common-dir 在主仓库内 = <main>/.git
144
+ // 在 linked worktree 内 = <main>/.git(git 共享 .git 目录)
145
+ const commonDir = gitQuiet(this.cwd, 'rev-parse --git-common-dir');
146
+ if (!commonDir) return this.cwd;
147
+
148
+ // commonDir 应该是 <main-repo>/.git
149
+ // dirname(commonDir) = <main-repo>
150
+ if (existsSync(commonDir)) {
151
+ const st = statSync(commonDir);
152
+ if (st.isDirectory()) {
153
+ return dirname(commonDir);
154
+ }
155
+ }
156
+ } catch (e) {
157
+ // 静默 fallback:主仓库内执行或 git 异常
158
+ }
159
+ return this.cwd;
124
160
  }
125
161
 
126
162
  /**
@@ -167,11 +203,19 @@ export class WorktreeManager {
167
203
  if (isolation.inWorktree) {
168
204
  // 已在 linked worktree 中,复用当前目录作为 worktree 路径
169
205
  console.log(`ℹ️ 已在 linked worktree 中(git-dir: ${isolation.gitDir}),复用当前隔离环境。`);
170
- return this._createInPlaceMeta(name, {
206
+
207
+ // 幂等守卫:meta 已存在时不重新 overlay baseline
208
+ const existingMeta = this.getMeta(name)
209
+ if (existingMeta) {
210
+ return { branch: existingMeta.branch, worktreePath: existingMeta.worktreePath, baseHash: existingMeta.baseHash, mode: existingMeta.mode }
211
+ }
212
+
213
+ // meta 不存在但已在 worktree 内:可能是 meta 被损坏/误删。
214
+ // 绝对禁止 overlay baseline(source === target 会冲突),
215
+ // 只恢复 meta 引用,不触碰文件系统。
216
+ return this._recoverNativeWorktreeMeta(name, {
171
217
  worktreePath: this.cwd,
172
218
  branch: gitQuiet(this.cwd, 'symbolic-ref --short HEAD') || 'detached',
173
- mode: 'native-worktree',
174
- base,
175
219
  });
176
220
  }
177
221
 
@@ -304,12 +348,76 @@ export class WorktreeManager {
304
348
  return { branch, worktreePath, baseHash, mode: meta.mode };
305
349
  }
306
350
 
351
+ /**
352
+ * native-worktree 模式下恢复 meta 引用
353
+ * 当 meta.json 被损坏/误删时,只重建 meta 文件,不触碰文件系统(不 overlay)
354
+ * @private
355
+ */
356
+ _recoverNativeWorktreeMeta(name, { worktreePath, branch }) {
357
+ const baseHash = gitQuiet(worktreePath, 'rev-parse HEAD') || null
358
+ const meta = {
359
+ changeName: name,
360
+ branch: branch || BRANCH_PREFIX + name,
361
+ baseBranch: branch,
362
+ baseHash,
363
+ actualBaseHash: baseHash,
364
+ createdAt: new Date().toISOString(),
365
+ worktreePath,
366
+ mode: 'native-worktree',
367
+ baselineFiles: [],
368
+ baselineCommit: null,
369
+ baselineHash: null,
370
+ recoveredAt: new Date().toISOString(),
371
+ recoveryNote: 'meta was missing in native-worktree; recovered without baseline overlay',
372
+ }
373
+ if (!existsSync(this.worktreeBase)) mkdirSync(this.worktreeBase, { recursive: true })
374
+ const metaDir = join(this.worktreeBase, name)
375
+ if (!existsSync(metaDir)) mkdirSync(metaDir, { recursive: true })
376
+ writeFileSync(join(metaDir, META_FILE), JSON.stringify(meta, null, 2) + '\n')
377
+ console.log(`🔗 native-worktree meta 已恢复: ${metaDir}/meta.json`)
378
+ return { branch: meta.branch, worktreePath, baseHash, mode: meta.mode }
379
+ }
380
+
307
381
  /**
308
382
  * 创建 in-place 模式的 meta.json(降级路径)
309
383
  * 不创建 git worktree,直接在当前目录记录 baseline 并写入 meta
310
384
  * @private
311
385
  */
312
386
  _createInPlaceMeta(name, { worktreePath, branch, baseBranch, baseHash, mode } = {}) {
387
+ // 幂等守卫:meta 已存在时不重新创建(避免 overlay baseline 和已有改动冲突)
388
+ const existingMeta = this.getMeta(name)
389
+ if (existingMeta) {
390
+ return { branch: existingMeta.branch, worktreePath: existingMeta.worktreePath, baseHash: existingMeta.baseHash, mode: existingMeta.mode }
391
+ }
392
+
393
+ // 硬规则:禁止 self-overlay(source 和 target 相同时 overlay 必然冲突)
394
+ const resolvedSource = resolve(this.cwd)
395
+ const resolvedTarget = resolve(worktreePath)
396
+ if (resolvedSource === resolvedTarget) {
397
+ console.warn('⚠️ 跳过 baseline overlay:当前目录与目标目录相同(native-worktree 或 in-place 模式)')
398
+ // 写 meta 但不 overlay
399
+ baseBranch = baseBranch || gitQuiet(this.cwd, 'symbolic-ref --short HEAD') || gitQuiet(this.cwd, 'rev-parse HEAD')
400
+ baseHash = baseHash || git(this.cwd, 'rev-parse HEAD')
401
+ const meta = {
402
+ changeName: name,
403
+ branch: branch || BRANCH_PREFIX + name,
404
+ baseBranch,
405
+ baseHash,
406
+ actualBaseHash: gitQuiet(worktreePath, 'rev-parse HEAD') || baseHash,
407
+ createdAt: new Date().toISOString(),
408
+ worktreePath,
409
+ mode: mode || 'in-place-fallback',
410
+ baselineFiles: [],
411
+ baselineCommit: null,
412
+ baselineHash: null,
413
+ }
414
+ if (!existsSync(this.worktreeBase)) mkdirSync(this.worktreeBase, { recursive: true })
415
+ const metaDir = join(this.worktreeBase, name)
416
+ if (!existsSync(metaDir)) mkdirSync(metaDir, { recursive: true })
417
+ writeFileSync(join(metaDir, META_FILE), JSON.stringify(meta, null, 2) + '\n')
418
+ return { branch: meta.branch, worktreePath, baseHash, mode: meta.mode }
419
+ }
420
+
313
421
  // 解析 base
314
422
  if (!baseHash) {
315
423
  baseBranch = baseBranch || gitQuiet(this.cwd, 'symbolic-ref --short HEAD') || gitQuiet(this.cwd, 'rev-parse HEAD');
@@ -0,0 +1,188 @@
1
+ /**
2
+ * worktree native-worktree overlay regression tests
3
+ *
4
+ * 验证 Bug 1 + Bug 2 修复:
5
+ * 1. worktreeBase 固定到主仓库路径,不跟着 cwd 变化
6
+ * 2. 禁止 self-overlay(source === target 时)
7
+ * 3. native-worktree meta 缺失时 recover,不 overlay
8
+ * 4. meta 已存在时幂等返回,不重建
9
+ */
10
+
11
+ import fs from 'fs'
12
+ import path from 'path'
13
+ import os from 'os'
14
+ import { execSync } from 'child_process'
15
+
16
+ // ── Test 1: _resolveMainRepoRoot 在主仓库内返回 cwd ──
17
+
18
+ async function test1_mainRepoRoot() {
19
+ const d = fs.mkdtempSync(path.join(os.tmpdir(), 'wt-'))
20
+ execSync('git init', { cwd: d, stdio: 'pipe' })
21
+ execSync('git config user.email "test@test.com"', { cwd: d, stdio: 'pipe' })
22
+ execSync('git config user.name "test"', { cwd: d, stdio: 'pipe' })
23
+ execSync('git commit --allow-empty -m "init"', { cwd: d, stdio: 'pipe' })
24
+
25
+ // Add .gitignore to allow worktreeBase path
26
+ fs.mkdirSync(path.join(d, '.sillyspec'), { recursive: true })
27
+ fs.writeFileSync(path.join(d, '.gitignore'), '.sillyspec/\n')
28
+
29
+ const { WorktreeManager } = await import('../src/worktree.js')
30
+ const wm = new WorktreeManager({ cwd: d })
31
+ const root = wm._resolveMainRepoRoot()
32
+ console.assert(root === d, `Test 1 FAIL: expected ${d}, got ${root}`)
33
+ console.log('✅ Test 1: main repo root resolves to cwd')
34
+
35
+ fs.rmSync(d, { recursive: true })
36
+ }
37
+
38
+ // ── Test 2: native-worktree 检测 + 幂等守卫 ──
39
+
40
+ async function test2_nativeWorktreeIdempotent() {
41
+ const d = fs.mkdtempSync(path.join(os.tmpdir(), 'wt-'))
42
+ execSync('git init', { cwd: d, stdio: 'pipe' })
43
+ execSync('git config user.email "test@test.com"', { cwd: d, stdio: 'pipe' })
44
+ execSync('git config user.name "test"', { cwd: d, stdio: 'pipe' })
45
+ execSync('git commit --allow-empty -m "init"', { cwd: d, stdio: 'pipe' })
46
+
47
+ const wtDir = path.join(d, 'wt')
48
+ execSync(`git worktree add ${wtDir} -b test-branch`, { cwd: d, stdio: 'pipe' })
49
+
50
+ // wtDir is a linked worktree
51
+ const { WorktreeManager } = await import('../src/worktree.js')
52
+
53
+ // First: create meta from inside worktree (simulating native-worktree mode)
54
+ const wm1 = new WorktreeManager({ cwd: wtDir })
55
+ // This simulates what happens when Claude Code runs in the worktree
56
+ // and SillySpec calls create() — detectIsolation should return inWorktree=true
57
+ // and meta should be written to main repo's worktreeBase, not worktree's
58
+
59
+ // Verify worktreeBase points to main repo
60
+ const expectedBase = path.join(d, '.sillyspec', '.runtime', 'worktrees')
61
+ console.assert(wm1.worktreeBase === expectedBase, `Test 2 FAIL: worktreeBase=${wm1.worktreeBase}, expected=${expectedBase}`)
62
+ console.log('✅ Test 2: worktreeBase fixed to main repo path')
63
+
64
+ fs.rmSync(d, { recursive: true })
65
+ }
66
+
67
+ // ── Test 3: self-overlay 禁止 ──
68
+
69
+ async function test3_selfOverlayBlocked() {
70
+ const d = fs.mkdtempSync(path.join(os.tmpdir(), 'wt-'))
71
+ execSync('git init', { cwd: d, stdio: 'pipe' })
72
+ execSync('git config user.email "test@test.com"', { cwd: d, stdio: 'pipe' })
73
+ execSync('git config user.name "test"', { cwd: d, stdio: 'pipe' })
74
+ execSync('git commit --allow-empty -m "init"', { cwd: d, stdio: 'pipe' })
75
+ fs.mkdirSync(path.join(d, '.sillyspec'), { recursive: true })
76
+ fs.writeFileSync(path.join(d, '.gitignore'), '.sillyspec/\n')
77
+
78
+ const { WorktreeManager } = await import('../src/worktree.js')
79
+ const wm = new WorktreeManager({ cwd: d })
80
+
81
+ // Create with in-place-fallback mode (source === target)
82
+ const result = wm._createInPlaceMeta('test-change', {
83
+ worktreePath: d,
84
+ branch: 'test-branch',
85
+ mode: 'in-place-fallback',
86
+ })
87
+
88
+ console.assert(result.mode === 'in-place-fallback', `Test 3 FAIL: mode=${result.mode}`)
89
+ // 返回值不包含 baselineFiles(是简化的返回结构),验证 meta 文件本身
90
+ const meta3 = wm.getMeta('test-change')
91
+ console.assert(meta3 && meta3.baselineFiles.length === 0, `Test 3 FAIL: meta baselineFiles should be empty`)
92
+ console.log('✅ Test 3: self-overlay blocked, baselineFiles empty')
93
+
94
+ fs.rmSync(d, { recursive: true })
95
+ }
96
+
97
+ // ── Test 4: meta 幂等,不重复 overlay ──
98
+
99
+ async function test4_metaIdempotent() {
100
+ const d = fs.mkdtempSync(path.join(os.tmpdir(), 'wt-'))
101
+ execSync('git init', { cwd: d, stdio: 'pipe' })
102
+ execSync('git config user.email "test@test.com"', { cwd: d, stdio: 'pipe' })
103
+ execSync('git config user.name "test"', { cwd: d, stdio: 'pipe' })
104
+ execSync('git commit --allow-empty -m "init"', { cwd: d, stdio: 'pipe' })
105
+ fs.mkdirSync(path.join(d, '.sillyspec'), { recursive: true })
106
+ fs.writeFileSync(path.join(d, '.gitignore'), '.sillyspec/\n')
107
+
108
+ const { WorktreeManager } = await import('../src/worktree.js')
109
+ const wm = new WorktreeManager({ cwd: d })
110
+
111
+ // First create
112
+ const r1 = wm._createInPlaceMeta('test-change', {
113
+ worktreePath: d,
114
+ branch: 'test-branch',
115
+ mode: 'in-place-fallback',
116
+ })
117
+
118
+ // Second create (should return existing, not re-overlay)
119
+ const r2 = wm._createInPlaceMeta('test-change', {
120
+ worktreePath: d,
121
+ branch: 'test-branch',
122
+ mode: 'in-place-fallback',
123
+ })
124
+
125
+ console.assert(r1.baseHash === r2.baseHash, `Test 4 FAIL: hashes differ`)
126
+ console.log('✅ Test 4: _createInPlaceMeta idempotent')
127
+
128
+ fs.rmSync(d, { recursive: true })
129
+ }
130
+
131
+ // ── Test 5: native-worktree meta 恢复 ──
132
+
133
+ async function test5_nativeRecovery() {
134
+ const d = fs.mkdtempSync(path.join(os.tmpdir(), 'wt-'))
135
+ execSync('git init', { cwd: d, stdio: 'pipe' })
136
+ execSync('git config user.email "test@test.com"', { cwd: d, stdio: 'pipe' })
137
+ execSync('git config user.name "test"', { cwd: d, stdio: 'pipe' })
138
+ execSync('git commit --allow-empty -m "init"', { cwd: d, stdio: 'pipe' })
139
+
140
+ const wtDir = path.join(d, 'wt')
141
+ execSync(`git worktree add ${wtDir} -b test-branch`, { cwd: d, stdio: 'pipe' })
142
+
143
+ const { WorktreeManager } = await import('../src/worktree.js')
144
+ const wm = new WorktreeManager({ cwd: wtDir })
145
+
146
+ // Simulate meta missing in native-worktree (should recover, not overlay)
147
+ const result = wm._recoverNativeWorktreeMeta('test-change', {
148
+ worktreePath: wtDir,
149
+ branch: 'test-branch',
150
+ })
151
+
152
+ console.assert(result.mode === 'native-worktree', `Test 5 FAIL: mode=${result.mode}`)
153
+ // 返回值不包含 baselineFiles,验证 meta 文件本身
154
+ const meta5 = wm.getMeta('test-change')
155
+ console.assert(meta5 && meta5.baselineFiles.length === 0, `Test 5 FAIL: meta baselineFiles should be empty`)
156
+
157
+ // Verify meta is readable now
158
+ const meta = wm.getMeta('test-change')
159
+ console.assert(meta !== null, `Test 5 FAIL: meta should exist after recovery`)
160
+ console.assert(meta.mode === 'native-worktree', `Test 5 FAIL: meta.mode=${meta.mode}`)
161
+ console.log('✅ Test 5: native-worktree meta recovery without overlay')
162
+
163
+ fs.rmSync(d, { recursive: true })
164
+ }
165
+
166
+ // ── Run all ──
167
+
168
+ const tests = [
169
+ ['main repo root', test1_mainRepoRoot],
170
+ ['native worktree worktreeBase', test2_nativeWorktreeIdempotent],
171
+ ['self-overlay blocked', test3_selfOverlayBlocked],
172
+ ['meta idempotent', test4_metaIdempotent],
173
+ ['native recovery', test5_nativeRecovery],
174
+ ]
175
+
176
+ let passed = 0, failed = 0
177
+ for (const [name, fn] of tests) {
178
+ try {
179
+ await fn()
180
+ passed++
181
+ } catch (e) {
182
+ console.log(`❌ ${name}: ${e.message}`)
183
+ failed++
184
+ }
185
+ }
186
+
187
+ console.log(`\n${passed}/${tests.length} passed`)
188
+ if (failed) process.exit(1)