sillyspec 3.19.1 → 3.20.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/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
 
@@ -305,6 +305,147 @@ export function applyWorktree(changeName, { cwd, checkOnly = false } = {}) {
305
305
  return result;
306
306
  }
307
307
 
308
+ /**
309
+ * 风险审计:评估 worktree 变更是否可以安全自动 apply
310
+ *
311
+ * 检查项:
312
+ * 1. patch --check 通过
313
+ * 2. 所有变更在 allowed_paths 内
314
+ * 3. 主工作区 baseline 未变化
315
+ * 4. 没有删除/重命名关键文件
316
+ * 5. 没有改高风险文件(lockfile/migration/配置/入口)除非任务显式允许
317
+ * 6. diff 规模没有异常膨胀
318
+ *
319
+ * @param {string} changeName
320
+ * @param {{ cwd?: string }} opts
321
+ * @returns {{
322
+ * decision: 'SAFE' | 'WARNING' | 'BLOCKED',
323
+ * changedFiles: string[],
324
+ * reasons: string[],
325
+ * warnings: string[],
326
+ * stats: { additions: number, deletions: number }
327
+ * }}
328
+ */
329
+ export function assessApplyRisk(changeName, { cwd } = {}) {
330
+ const projectRoot = cwd || process.cwd();
331
+ const reasons = [];
332
+ const warnings = [];
333
+
334
+ // 先跑 --check-only 模式的 applyWorktree 获取变更文件列表
335
+ const checkResult = applyWorktree(changeName, { cwd: projectRoot, checkOnly: true });
336
+
337
+ if (checkResult.errors.length > 0) {
338
+ return {
339
+ decision: 'BLOCKED',
340
+ changedFiles: checkResult.changedFiles,
341
+ reasons: checkResult.errors,
342
+ warnings: [],
343
+ stats: { additions: 0, deletions: 0 }
344
+ };
345
+ }
346
+
347
+ const changedFiles = checkResult.changedFiles;
348
+
349
+ if (changedFiles.length === 0) {
350
+ return {
351
+ decision: 'SAFE',
352
+ changedFiles: [],
353
+ reasons: ['无变更需要应用'],
354
+ warnings: [],
355
+ stats: { additions: 0, deletions: 0 }
356
+ };
357
+ }
358
+
359
+ // 解析 TaskCard allowed_paths
360
+ const wm = new WorktreeManager({ cwd: projectRoot });
361
+ const meta = wm.getMeta(changeName);
362
+ const tasksDir = join(projectRoot, CHANGES_REL, changeName, 'tasks');
363
+ const allowedPaths = new Set();
364
+ if (existsSync(tasksDir)) {
365
+ const { readdirSync, readFileSync } = require('fs');
366
+ for (const tf of readdirSync(tasksDir).filter(f => /^task-\d+\.md$/.test(f))) {
367
+ const content = readFileSync(join(tasksDir, tf), 'utf8');
368
+ const fmMatch = content.match(/^---\n([\s\S]*?)\n---/);
369
+ if (!fmMatch) continue;
370
+ const fm = fmMatch[1];
371
+ const inline = fm.match(/allowed_paths:\s*\[([^\]]*)\]/);
372
+ if (inline) {
373
+ inline[1].split(',').forEach(s => { const v = s.trim().replace(/['"]/g, ''); if (v) allowedPaths.add(v); });
374
+ }
375
+ const block = fm.match(/allowed_paths:\s*\n((?:\s+-\s+.+\n?)+)/);
376
+ if (block) {
377
+ block[1].match(/-\s+(.+)/g)?.forEach(s => { const v = s.replace(/^-\s+/, '').trim().replace(/['"]/g, ''); if (v) allowedPaths.add(v); });
378
+ }
379
+ }
380
+ }
381
+
382
+ // 检查 2: 变更在 allowed_paths 内(仅在 TaskCard 存在时)
383
+ if (allowedPaths.size > 0) {
384
+ const outsidePaths = changedFiles.filter(f => !
385
+ [...allowedPaths].some(allowed => f === allowed || f.startsWith(allowed.replace(/\*$/, '')))
386
+ );
387
+ if (outsidePaths.length > 0) {
388
+ reasons.push(`变更文件超出 allowed_paths:\n ${outsidePaths.join('\n ')}`);
389
+ }
390
+ }
391
+
392
+ // 检查 4+5: 高风险文件模式
393
+ const HIGH_RISK_PATTERNS = [
394
+ /(^|\/)package-lock\.json$/,
395
+ /(^|\/)pnpm-lock\.yaml$/,
396
+ /(^|\/)yarn\.lock$/,
397
+ /(^|\/)\.env($|\.)/,
398
+ /(^|\/)docker-compose.*\.ya?ml$/,
399
+ /(^|\/)Dockerfile$/,
400
+ /migration[\w.-]*\.(sql|js|ts)$/i,
401
+ /(^|\/).*entry.*\.(js|ts)$/i,
402
+ /(^|\/)main\.(js|ts)$/i,
403
+ /(^|\/)index\.(js|ts)$/i,
404
+ /(^|\/)app\.(js|ts)$/i,
405
+ ];
406
+ const riskyFiles = changedFiles.filter(f => HIGH_RISK_PATTERNS.some(p => p.test(f)));
407
+ if (riskyFiles.length > 0) {
408
+ // 高风险文件只有在 allowedPaths 显式包含时才放行
409
+ const trulyRisky = riskyFiles.filter(f => !
410
+ [...allowedPaths].some(allowed => f === allowed)
411
+ );
412
+ if (trulyRisky.length > 0) {
413
+ reasons.push(`高风险文件变更(未在 allowed_paths 中显式声明):\n ${trulyRisky.join('\n ')}`);
414
+ } else {
415
+ warnings.push(`高风险文件变更(已在 allowed_paths 中声明):${riskyFiles.join(', ')}`);
416
+ }
417
+ }
418
+
419
+ // 检查 6: diff 规模异常(>2000 行变更视为异常)
420
+ const wtPath = meta?.worktreePath;
421
+ const diffBase = meta?.baselineCommit || meta?.baseHash;
422
+ let additions = 0, deletions = 0;
423
+ if (wtPath && diffBase) {
424
+ try {
425
+ const shortstat = gitQuiet(wtPath, `diff --shortstat ${diffBase}`);
426
+ const insMatch = shortstat?.match(/(\d+) insertion/);
427
+ const delMatch = shortstat?.match(/(\d+) deletion/);
428
+ additions = insMatch ? parseInt(insMatch[1]) : 0;
429
+ deletions = delMatch ? parseInt(delMatch[1]) : 0;
430
+ if (additions + deletions > 2000) {
431
+ reasons.push(`diff 规模异常(${additions} additions + ${deletions} deletions = ${additions + deletions} 行)`);
432
+ }
433
+ } catch {}
434
+ }
435
+
436
+ // 判定
437
+ let decision;
438
+ if (reasons.length > 0) {
439
+ decision = 'BLOCKED';
440
+ } else if (warnings.length > 0) {
441
+ decision = 'WARNING';
442
+ } else {
443
+ decision = 'SAFE';
444
+ }
445
+
446
+ return { decision, changedFiles, reasons, warnings, stats: { additions, deletions } };
447
+ }
448
+
308
449
  /**
309
450
  * 格式化 execute run summary(人类可读)
310
451
  *
@@ -0,0 +1,277 @@
1
+ /**
2
+ * Stage Contract: decisions.md supersede 关系测试
3
+ *
4
+ * 验证被 supersede 的旧版本不再被要求引用
5
+ */
6
+ import { readFileSync } from 'fs'
7
+ import { join } from 'path'
8
+
9
+ // 直接测试 extractCurrentDecisionIds 的行为
10
+ // 由于它不是 exported,我们通过 validateBrainstormOutputs 间接测试
11
+
12
+ let failed = 0
13
+ const failures = []
14
+
15
+ function assert(condition, msg) {
16
+ if (!condition) {
17
+ failed++
18
+ failures.push(msg)
19
+ console.log(` ❌ FAIL: ${msg}`)
20
+ } else {
21
+ console.log(` ✅ PASS: ${msg}`)
22
+ }
23
+ }
24
+
25
+ console.log('=== decisions.md supersede 关系测试 ===\n')
26
+
27
+ // 动态导入 stage-contract.js 的内部函数
28
+ // 由于 extractCurrentDecisionIds 不是 exported,我们用 validateBrainstormOutputs 来间接验证
29
+ const contractPath = join(import.meta.dirname, '..', 'src', 'stage-contract.js')
30
+ const contractSource = readFileSync(contractPath, 'utf8')
31
+
32
+ // 提取并 eval 需要的函数
33
+ // 通过创建临时模块来测试
34
+ const { existsSync, mkdirSync, writeFileSync, mkdtempSync, rmSync } = await import('fs')
35
+ const { join: pJoin } = await import('path')
36
+ const { tmpdir } = await import('os')
37
+
38
+ // 我们通过 validateBrainstormOutputs 来端到端测试
39
+ const mod = await import(pJoin(import.meta.dirname, '..', 'src', 'stage-contract.js'))
40
+
41
+ // ─────────────────────────────────────────
42
+ // Test 1: 被 supersede 的旧版本不警告
43
+ // ─────────────────────────────────────────
44
+ console.log('--- Test 1: 被 supersede 的旧版本不警告 ---')
45
+ {
46
+ const tmpDir = mkdtempSync(join(tmpdir(), 'sillyspec-supersede-'))
47
+ // 模拟 .sillyspec/changes 结构
48
+ const changeDir = pJoin(tmpDir, '.sillyspec', 'changes', '2026-06-25-test')
49
+ mkdirSync(changeDir, { recursive: true })
50
+
51
+ // decisions.md: D-004@v2 supersedes D-004@v1
52
+ writeFileSync(pJoin(changeDir, 'decisions.md'), `# Decisions
53
+
54
+ ## D-004@v1
55
+ - status: accepted
56
+ - priority: P1
57
+
58
+ ## D-004@v2
59
+ - status: accepted
60
+ - priority: P1
61
+ - supersedes: D-004@v1
62
+ `)
63
+
64
+ // design.md 只引用 D-004@v2(不引用 v1)
65
+ writeFileSync(pJoin(changeDir, 'design.md'), `# Design
66
+
67
+ ## 目标
68
+ 修复 bug。
69
+
70
+ ## 方案
71
+ 用方案 B。
72
+
73
+ ## 决策
74
+ D-004@v2: 选择方案 B
75
+ `)
76
+
77
+ writeFileSync(pJoin(changeDir, 'requirements.md'), `# Requirements
78
+
79
+ ## FR-01
80
+ 需求 A。
81
+
82
+ ## 决策覆盖
83
+ - D-004@v2 → FR-01
84
+ `)
85
+
86
+ writeFileSync(pJoin(changeDir, 'tasks.md'), `# Tasks
87
+ - task-01: 实现
88
+ `)
89
+
90
+ // 用 validateBrainstormOutputs 验证
91
+ const result = mod.runValidators("brainstorm", tmpDir, '2026-06-25-test')
92
+
93
+ // 不应有关于 D-004@v1 的未引用警告
94
+ const v1Warnings = result.warnings.filter(w => w.includes('D-004@V1'))
95
+ assert(v1Warnings.length === 0, `不应有 D-004@V1 未引用警告,实际 warnings: ${JSON.stringify(v1Warnings)}`)
96
+
97
+ rmSync(tmpDir, { recursive: true, force: true })
98
+ }
99
+
100
+ // ─────────────────────────────────────────
101
+ // Test 2: 没有 supersede 关系时,旧版本仍被校验
102
+ // ─────────────────────────────────────────
103
+ console.log('\n--- Test 2: 无 supersede 关系时旧版本仍校验 ---')
104
+ {
105
+ const tmpDir = mkdtempSync(join(tmpdir(), 'sillyspec-nosupersede-'))
106
+ const changeDir = pJoin(tmpDir, '.sillyspec', 'changes', '2026-06-25-test')
107
+ mkdirSync(changeDir, { recursive: true })
108
+
109
+ // decisions.md: 两个独立决策,无 supersede 关系
110
+ writeFileSync(pJoin(changeDir, 'decisions.md'), `# Decisions
111
+
112
+ ## D-004@v1
113
+ - status: accepted
114
+ - priority: P1
115
+
116
+ ## D-005@v1
117
+ - status: accepted
118
+ - priority: P1
119
+ `)
120
+
121
+ // design.md 只引用 D-004@v1,不引用 D-005@v1
122
+ writeFileSync(pJoin(changeDir, 'design.md'), `# Design
123
+
124
+ ## 目标
125
+ 修复 bug。
126
+
127
+ ## 方案
128
+ 用方案 B。
129
+
130
+ ## 决策
131
+ D-004@v1: 选择方案 B
132
+ ## 文件变更清单
133
+ | 操作 | 文件 | 说明 |
134
+ ## 风险登记
135
+ - 风险 A
136
+ ## 自审
137
+ - 已检查
138
+ `)
139
+
140
+ writeFileSync(pJoin(changeDir, 'requirements.md'), `# Requirements
141
+ ## FR-01
142
+ 需求 A。
143
+ `)
144
+
145
+ writeFileSync(pJoin(changeDir, 'proposal.md'), `# Proposal
146
+ ## 不在范围内
147
+ - 无
148
+ `)
149
+ writeFileSync(pJoin(changeDir, 'tasks.md'), `# Tasks
150
+ - task-01: 实现
151
+ `)
152
+
153
+ const result = mod.runValidators("brainstorm", tmpDir, '2026-06-25-test')
154
+
155
+ // D-005@v1 应该有未引用警告
156
+ const v5Warnings = result.warnings.filter(w => w.includes('D-005@V1'))
157
+ assert(v5Warnings.length > 0, `应有 D-005@V1 未引用警告`)
158
+
159
+ rmSync(tmpDir, { recursive: true, force: true })
160
+ }
161
+
162
+ // ─────────────────────────────────────────
163
+ // Test 3: status=superseded 的旧版本不警告(原有行为,回归测试)
164
+ // ─────────────────────────────────────────
165
+ console.log('\n--- Test 3: status=superseded 的旧版本不警告(回归) ---')
166
+ {
167
+ const tmpDir = mkdtempSync(join(tmpdir(), 'sillyspec-status-'))
168
+ const changeDir = pJoin(tmpDir, '.sillyspec', 'changes', '2026-06-25-test')
169
+ mkdirSync(changeDir, { recursive: true })
170
+
171
+ writeFileSync(pJoin(changeDir, 'decisions.md'), `# Decisions
172
+
173
+ ## D-004@v1
174
+ - status: superseded
175
+ - priority: P1
176
+
177
+ ## D-004@v2
178
+ - status: accepted
179
+ - priority: P1
180
+ `)
181
+
182
+ writeFileSync(pJoin(changeDir, 'design.md'), `# Design
183
+
184
+ ## 目标
185
+ 修复 bug。
186
+
187
+ ## 方案
188
+ 用方案 B。
189
+
190
+ ## 决策
191
+ D-004@v2: 选择方案 B
192
+ `)
193
+
194
+ writeFileSync(pJoin(changeDir, 'requirements.md'), `# Requirements
195
+ ## FR-01
196
+ 需求 A。
197
+ `)
198
+
199
+ writeFileSync(pJoin(changeDir, 'tasks.md'), `# Tasks
200
+ - task-01: 实现
201
+ `)
202
+
203
+ const result = mod.runValidators("brainstorm", tmpDir, '2026-06-25-test')
204
+
205
+ const v1Warnings = result.warnings.filter(w => w.includes('D-004@V1'))
206
+ assert(v1Warnings.length === 0, `status=superseded 的 D-004@V1 不应警告`)
207
+
208
+ rmSync(tmpDir, { recursive: true, force: true })
209
+ }
210
+
211
+ // ─────────────────────────────────────────
212
+ // Test 4: 多级 supersede 链(v1 ← v2 ← v3)
213
+ // ─────────────────────────────────────────
214
+ console.log('\n--- Test 4: 多级 supersede 链 ---')
215
+ {
216
+ const tmpDir = mkdtempSync(join(tmpdir(), 'sillyspec-chain-'))
217
+ const changeDir = pJoin(tmpDir, '.sillyspec', 'changes', '2026-06-25-test')
218
+ mkdirSync(changeDir, { recursive: true })
219
+
220
+ writeFileSync(pJoin(changeDir, 'decisions.md'), `# Decisions
221
+
222
+ ## D-004@v1
223
+ - status: accepted
224
+ - priority: P1
225
+
226
+ ## D-004@v2
227
+ - status: accepted
228
+ - priority: P1
229
+ - supersedes: D-004@v1
230
+
231
+ ## D-004@v3
232
+ - status: accepted
233
+ - priority: P1
234
+ - supersedes: D-004@v2
235
+ `)
236
+
237
+ // design.md 只引用 D-004@v3
238
+ writeFileSync(pJoin(changeDir, 'design.md'), `# Design
239
+
240
+ ## 目标
241
+ 修复 bug。
242
+
243
+ ## 方案
244
+ 用方案 C。
245
+
246
+ ## 决策
247
+ D-004@v3: 选择方案 C
248
+ `)
249
+
250
+ writeFileSync(pJoin(changeDir, 'requirements.md'), `# Requirements
251
+ ## FR-01
252
+ 需求 A。
253
+ - D-004@v3 → FR-01
254
+ `)
255
+
256
+ writeFileSync(pJoin(changeDir, 'tasks.md'), `# Tasks
257
+ - task-01: 实现
258
+ `)
259
+
260
+ const result = mod.runValidators("brainstorm", tmpDir, '2026-06-25-test')
261
+
262
+ const oldWarnings = result.warnings.filter(w => w.includes('D-004@V1') || w.includes('D-004@V2'))
263
+ assert(oldWarnings.length === 0, `多级 supersede 链中 v1/v2 不应警告,实际: ${JSON.stringify(oldWarnings)}`)
264
+
265
+ rmSync(tmpDir, { recursive: true, force: true })
266
+ }
267
+
268
+ // ── 结果 ──
269
+ console.log(`\n${'='.repeat(50)}`)
270
+ console.log(`✅ 通过: ${4 - failed} ❌ 失败: ${failed}`)
271
+ if (failures.length > 0) {
272
+ console.log(`失败项:`)
273
+ failures.forEach(f => console.log(` - ${f}`))
274
+ }
275
+ console.log(`${'='.repeat(50)}`)
276
+
277
+ if (failed > 0) process.exit(1)