sillyspec 3.19.2 → 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.
@@ -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)