sillyspec 3.19.0 → 3.19.2

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/.npmrc-tmp ADDED
@@ -0,0 +1 @@
1
+ //registry.npmjs.org/:_authToken=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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sillyspec",
3
- "version": "3.19.0",
3
+ "version": "3.19.2",
4
4
  "description": "SillySpec CLI — 流程状态机,让 AI 严格按步骤来",
5
5
  "icon": "logo.jpg",
6
6
  "homepage": "https://sillyspec.ppdmq.top/",
@@ -143,14 +143,13 @@ function warnMissingIds(warnings, ids, targetContent, targetName, sourceName) {
143
143
  */
144
144
  function validateScanOutputs(cwd, changeName, context = {}) {
145
145
  const { projectName, specRoot } = context
146
- // 平台模式使用 specRoot,本地模式使用 cwd
147
- const base = specRoot || cwd
148
- // 如果 base 已经是 specDir(有 docs/ 子目录),直接用 base/docs/
149
- // 否则按传统模式拼接 .sillyspec/docs/
150
- const isSpecDir = existsSync(join(base, 'docs'))
146
+ // 平台模式:specRoot 直接是规范目录(含 docs/)
147
+ // 本地模式:规范目录是 cwd/.sillyspec
148
+ // 不用 isSpecDir 启发式猜测——很多项目根目录有自己的 docs/,会误判
149
+ const specBase = specRoot || join(cwd, '.sillyspec')
151
150
  const docsRoot = projectName
152
- ? join(base, isSpecDir ? 'docs' : '.sillyspec/docs', projectName, 'scan')
153
- : join(base, isSpecDir ? 'docs' : '.sillyspec/docs', 'scan')
151
+ ? join(specBase, 'docs', projectName, 'scan')
152
+ : join(specBase, 'docs', 'scan')
154
153
 
155
154
  const requiredDocs = [
156
155
  'ARCHITECTURE.md',
@@ -173,8 +172,8 @@ function validateScanOutputs(cwd, changeName, context = {}) {
173
172
 
174
173
  // 检查 modules 目录
175
174
  const modulesRoot = projectName
176
- ? join(base, isSpecDir ? 'docs' : '.sillyspec/docs', projectName, 'modules')
177
- : join(base, isSpecDir ? 'docs' : '.sillyspec/docs', 'modules')
175
+ ? join(specBase, 'docs', projectName, 'modules')
176
+ : join(specBase, 'docs', 'modules')
178
177
  if (!existsSync(modulesRoot)) {
179
178
  warnings.push('modules 目录不存在')
180
179
  } else {
package/src/workflow.js CHANGED
@@ -154,7 +154,12 @@ function checkOutput(outputDef, projectName, cwd, specBase) {
154
154
  // 未传时回退 join(cwd, '.sillyspec'),等价于旧行为 resolve(cwd, '.sillyspec/...')
155
155
  const effectiveBase = specBase || join(cwd, '.sillyspec')
156
156
  // 将 <project> 替换为实际项目名
157
- const rawPath = (outputDef.path || '').replace(/<project>/g, projectName)
157
+ let rawPath = (outputDef.path || '').replace(/<project>/g, projectName)
158
+ // 旧版兼容:如果 path 以 .sillyspec/ 开头(相对路径),strip 前缀避免双拼接
159
+ // 新版 yaml 用 {SPEC_ROOT} 已在 runPostCheck 中替换为绝对路径,不会走这里
160
+ if (rawPath.startsWith('.sillyspec/')) {
161
+ rawPath = rawPath.slice('.sillyspec/'.length)
162
+ }
158
163
  const fullPath = resolve(effectiveBase, rawPath)
159
164
  const checks = outputDef.checks || []
160
165
  const results = []
@@ -204,7 +209,7 @@ function checkOutput(outputDef, projectName, cwd, specBase) {
204
209
  const patterns = check.patterns || ['待补充', 'TODO', 'TBD', '未分析', '根据项目情况', '根据实际情况', '按需填写']
205
210
  // 只匹配独立成行的占位文本,不匹配行内引用
206
211
  const lineMatches = patterns.filter(p => {
207
- const regex = new RegExp(`^\s*[-*]?\s*${p}\s*$`, 'm')
212
+ const regex = new RegExp(`^\\s*[-*]?\\s*${p}\\s*$`, 'm')
208
213
  return regex.test(content)
209
214
  })
210
215
  results.push({ passed: lineMatches.length === 0, check: 'no_placeholder', detail: lineMatches.length > 0 ? `包含占位文本: ${lineMatches.map(m => `"${m}"`).join(', ')} — ${rawPath}` : '' })
@@ -246,13 +251,20 @@ function checkOutput(outputDef, projectName, cwd, specBase) {
246
251
  */
247
252
  export function runPostCheck(wf, cwd, projectName, placeholders = {}, specBase) {
248
253
  let resolved = replaceProjectPlaceholder(wf, projectName)
249
- if (Object.keys(placeholders).length > 0) {
250
- let json = JSON.stringify(resolved)
251
- for (const [key, value] of Object.entries(placeholders)) {
252
- json = json.replace(new RegExp(`<${key}>`, 'g'), value)
253
- }
254
- resolved = JSON.parse(json)
254
+
255
+ // 自动注入 {SPEC_ROOT} 占位符(yaml 模板用 {SPEC_ROOT} 表示规范根目录)
256
+ // effectiveBase _checkWorkflow 内部一致:specBase || join(cwd, '.sillyspec')
257
+ const effectiveBase = specBase || join(cwd, '.sillyspec')
258
+ const allPlaceholders = { SPEC_ROOT: effectiveBase, ...placeholders }
259
+
260
+ let json = JSON.stringify(resolved)
261
+ for (const [key, value] of Object.entries(allPlaceholders)) {
262
+ // 支持 {key} 和 <key> 两种占位符语法
263
+ json = json.replace(new RegExp(`\{${key}\}`, 'g'), value)
264
+ json = json.replace(new RegExp(`<${key}>`, 'g'), value)
255
265
  }
266
+ resolved = JSON.parse(json)
267
+
256
268
  return _checkWorkflow(resolved, cwd, projectName, specBase)
257
269
  }
258
270
 
@@ -261,6 +273,7 @@ function _checkWorkflow(wf, cwd, projectName, specBase) {
261
273
  const workflowName = wf.name || 'unknown'
262
274
  const specVersion = wf.spec_version || wf.version || 0
263
275
  const workflowChecks = wf.checks?.workflow_level || []
276
+ const roleLevelChecks = wf.checks?.role_level || []
264
277
  const roles = []
265
278
  const failures = []
266
279
  const workflowCheckResults = []
@@ -274,7 +287,11 @@ function _checkWorkflow(wf, cwd, projectName, specBase) {
274
287
 
275
288
  for (const outputDef of outputDefs) {
276
289
  const rawPath = (outputDef.path || '').replace(/<project>/g, projectName)
277
- const checkResults = checkOutput(outputDef, projectName, cwd, effectiveBase)
290
+ // role_level checks: 全局施加到每个 output(与 output 自身的 checks 合并)
291
+ const mergedOutputDef = roleLevelChecks.length > 0
292
+ ? { ...outputDef, checks: [...(outputDef.checks || []), ...roleLevelChecks] }
293
+ : outputDef
294
+ const checkResults = checkOutput(mergedOutputDef, projectName, cwd, effectiveBase)
278
295
  const outputPassed = checkResults.every(c => c.passed)
279
296
 
280
297
  outputs.push({
@@ -355,8 +372,97 @@ function _checkWorkflow(wf, cwd, projectName, specBase) {
355
372
  }
356
373
  break
357
374
  }
375
+ case 'file_exists': {
376
+ // workflow_level file_exists: check.path 可以是目录或文件,相对 effectiveBase
377
+ let checkPath = check.path || ''
378
+ // 兼容 .sillyspec/ 前缀
379
+ if (checkPath.startsWith('.sillyspec/')) checkPath = checkPath.slice('.sillyspec/'.length)
380
+ // 替换 <change-name> 占位符(archive-impact 用)
381
+ checkPath = checkPath.replace(/<change-name>/g, wf._changeName || '')
382
+ const fullPath = join(effectiveBase, checkPath)
383
+ if (!existsSync(fullPath)) {
384
+ const detail = `文件不存在: ${checkPath}`
385
+ workflowCheckResults.push({ type: 'file_exists', status: 'fail', detail })
386
+ failures.push({ level: 'workflow', check: 'file_exists', message: detail })
387
+ } else {
388
+ workflowCheckResults.push({ type: 'file_exists', status: 'pass', detail: '' })
389
+ }
390
+ break
391
+ }
392
+ case 'min_lines': {
393
+ let checkPath = check.path || ''
394
+ if (checkPath.startsWith('.sillyspec/')) checkPath = checkPath.slice('.sillyspec/'.length)
395
+ checkPath = checkPath.replace(/<change-name>/g, wf._changeName || '')
396
+ const fullPath = join(effectiveBase, checkPath)
397
+ if (existsSync(fullPath)) {
398
+ const content = readFileSync(fullPath, 'utf8')
399
+ const lines = content.split('\n').length
400
+ const min = check.min || 1
401
+ if (lines < min) {
402
+ const detail = `文件只有 ${lines} 行,要求至少 ${min} 行: ${checkPath}`
403
+ workflowCheckResults.push({ type: 'min_lines', status: 'fail', detail })
404
+ failures.push({ level: 'workflow', check: 'min_lines', message: detail })
405
+ } else {
406
+ workflowCheckResults.push({ type: 'min_lines', status: 'pass', detail: '' })
407
+ }
408
+ } else {
409
+ const detail = `文件不存在: ${checkPath}`
410
+ workflowCheckResults.push({ type: 'min_lines', status: 'fail', detail })
411
+ failures.push({ level: 'workflow', check: 'min_lines', message: detail })
412
+ }
413
+ break
414
+ }
415
+ case 'contains_sections': {
416
+ let checkPath = check.path || ''
417
+ if (checkPath.startsWith('.sillyspec/')) checkPath = checkPath.slice('.sillyspec/'.length)
418
+ checkPath = checkPath.replace(/<change-name>/g, wf._changeName || '')
419
+ const fullPath = join(effectiveBase, checkPath)
420
+ if (existsSync(fullPath)) {
421
+ const content = readFileSync(fullPath, 'utf8')
422
+ const sections = check.sections || []
423
+ const missing = sections.filter(s => !content.includes(`## ${s}`))
424
+ if (missing.length > 0) {
425
+ const detail = `缺少章节: ${missing.join(', ')} — ${checkPath}`
426
+ workflowCheckResults.push({ type: 'contains_sections', status: 'fail', detail })
427
+ failures.push({ level: 'workflow', check: 'contains_sections', message: detail })
428
+ } else {
429
+ workflowCheckResults.push({ type: 'contains_sections', status: 'pass', detail: '' })
430
+ }
431
+ } else {
432
+ const detail = `文件不存在: ${checkPath}`
433
+ workflowCheckResults.push({ type: 'contains_sections', status: 'fail', detail })
434
+ failures.push({ level: 'workflow', check: 'contains_sections', message: detail })
435
+ }
436
+ break
437
+ }
438
+ case 'no_placeholder': {
439
+ let checkPath = check.path || ''
440
+ if (checkPath.startsWith('.sillyspec/')) checkPath = checkPath.slice('.sillyspec/'.length)
441
+ checkPath = checkPath.replace(/<change-name>/g, wf._changeName || '')
442
+ const fullPath = join(effectiveBase, checkPath)
443
+ if (existsSync(fullPath)) {
444
+ const content = readFileSync(fullPath, 'utf8')
445
+ const patterns = check.patterns || ['待补充', 'TODO', 'TBD', '未分析', '根据项目情况', '根据实际情况', '按需填写']
446
+ const lineMatches = patterns.filter(p => {
447
+ const regex = new RegExp(`^\\s*[-*]?\\s*${p}\\s*$`, 'm')
448
+ return regex.test(content)
449
+ })
450
+ if (lineMatches.length > 0) {
451
+ const detail = `包含占位文本: ${lineMatches.map(m => `"${m}"`).join(', ')} — ${checkPath}`
452
+ workflowCheckResults.push({ type: 'no_placeholder', status: 'fail', detail })
453
+ failures.push({ level: 'workflow', check: 'no_placeholder', message: detail })
454
+ } else {
455
+ workflowCheckResults.push({ type: 'no_placeholder', status: 'pass', detail: '' })
456
+ }
457
+ } else {
458
+ const detail = `文件不存在: ${checkPath}`
459
+ workflowCheckResults.push({ type: 'no_placeholder', status: 'fail', detail })
460
+ failures.push({ level: 'workflow', check: 'no_placeholder', message: detail })
461
+ }
462
+ break
463
+ }
358
464
  default:
359
- workflowCheckResults.push({ type: check.type, status: 'pass', detail: '' })
465
+ workflowCheckResults.push({ type: check.type, status: 'pass', detail: `未知检查类型,跳过: ${check.type}` })
360
466
  }
361
467
  }
362
468
 
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');
@@ -108,14 +108,15 @@ const specRoot = mkdtempSync(join(tmpdir(), 'sillyspec-test-'))
108
108
  const sourceRoot = mkdtempSync(join(tmpdir(), 'sillyspec-source-'))
109
109
  const projectName = 'myaaa'
110
110
 
111
- // specRoot 下创建正确的 scan 文档
112
- const specDocsDir = join(specRoot, '.sillyspec', 'docs', projectName, 'scan')
111
+ // specRoot 在实际代码中等价于 .sillyspec 目录本身(run.js: join(specRoot, 'docs', ...))
112
+ // 所以 scan 文档路径为 specRoot/docs/<project>/scan/,不需要额外的 .sillyspec/ 前缀
113
+ const specDocsDir = join(specRoot, 'docs', projectName, 'scan')
113
114
  mkdirSync(specDocsDir, { recursive: true })
114
115
  for (const doc of ['ARCHITECTURE.md', 'CONVENTIONS.md', 'STRUCTURE.md', 'INTEGRATIONS.md', 'TESTING.md', 'CONCERNS.md', 'PROJECT.md']) {
115
116
  writeFileSync(join(specDocsDir, doc), '# ' + doc)
116
117
  }
117
- mkdirSync(join(specRoot, '.sillyspec', 'docs', projectName, 'modules'), { recursive: true })
118
- writeFileSync(join(specRoot, '.sillyspec', 'docs', projectName, 'modules', 'app.md'), '# app')
118
+ mkdirSync(join(specRoot, 'docs', projectName, 'modules'), { recursive: true })
119
+ writeFileSync(join(specRoot, 'docs', projectName, 'modules', 'app.md'), '# app')
119
120
 
120
121
  // 测试1:使用 specRoot 校验成功
121
122
  const specResult = runValidators('scan', sourceRoot, 'test', { projectName, specRoot })
@@ -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)