sillyspec 3.20.2 → 3.20.4

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 (133) hide show
  1. package/.claude/skills/sillyspec-archive/SKILL.md +21 -21
  2. package/.claude/skills/sillyspec-auto/SKILL.md +83 -83
  3. package/.claude/skills/sillyspec-brainstorm/SKILL.md +44 -44
  4. package/.claude/skills/sillyspec-commit/SKILL.md +106 -106
  5. package/.claude/skills/sillyspec-continue/SKILL.md +45 -45
  6. package/.claude/skills/sillyspec-doctor/SKILL.md +31 -31
  7. package/.claude/skills/sillyspec-execute/SKILL.md +30 -30
  8. package/.claude/skills/sillyspec-explore/SKILL.md +109 -109
  9. package/.claude/skills/sillyspec-knowledge/SKILL.md +269 -269
  10. package/.claude/skills/sillyspec-plan/SKILL.md +21 -21
  11. package/.claude/skills/sillyspec-propose/SKILL.md +21 -21
  12. package/.claude/skills/sillyspec-quick/SKILL.md +21 -21
  13. package/.claude/skills/sillyspec-resume/SKILL.md +68 -68
  14. package/.claude/skills/sillyspec-scan/SKILL.md +21 -21
  15. package/.claude/skills/sillyspec-state/SKILL.md +54 -54
  16. package/.claude/skills/sillyspec-status/SKILL.md +21 -21
  17. package/.claude/skills/sillyspec-verify/SKILL.md +21 -21
  18. package/.claude/skills/sillyspec-workspace/SKILL.md +157 -157
  19. package/.husky/pre-push +13 -13
  20. package/CLAUDE.md +18 -18
  21. package/README.md +198 -188
  22. package/SKILL.md +90 -91
  23. package/bin/sillyspec.js +2 -2
  24. package/docs/brainstorm-plan-contract.md +64 -64
  25. package/docs/plan-execute-contract.md +123 -123
  26. package/docs/platform-scan-protocol.md +298 -298
  27. package/docs/revision-mode.md +115 -115
  28. package/docs/sillyspec/file-lifecycle/known-implementation-gaps.md +99 -99
  29. package/docs/sillyspec/file-lifecycle/platform-workflows-sync.md +218 -218
  30. package/docs/sillyspec/file-lifecycle/stage-artifacts.md +167 -167
  31. package/docs/sillyspec/file-lifecycle/storage-and-state.md +148 -148
  32. package/docs/sillyspec/file-lifecycle/worktree-and-guard.md +211 -193
  33. package/docs/sillyspec/file-lifecycle.md +125 -125
  34. package/docs/workflow-contract-regression.md +106 -106
  35. package/docs/worktree-isolation.md +252 -252
  36. package/package.json +40 -40
  37. package/packages/dashboard/dist/assets/index-Bq_Z2hne.js +7446 -7446
  38. package/packages/dashboard/dist/assets/index-O2W5RV4z.css +1 -1
  39. package/packages/dashboard/dist/index.html +16 -16
  40. package/packages/dashboard/index.html +15 -15
  41. package/packages/dashboard/package-lock.json +2384 -2384
  42. package/packages/dashboard/package.json +25 -25
  43. package/packages/dashboard/server/executor.js +86 -86
  44. package/packages/dashboard/server/index.js +588 -588
  45. package/packages/dashboard/server/parser.js +526 -526
  46. package/packages/dashboard/server/watcher.js +344 -344
  47. package/packages/dashboard/src/App.vue +558 -558
  48. package/packages/dashboard/src/components/ActionBar.vue +93 -93
  49. package/packages/dashboard/src/components/CommandPalette.vue +96 -96
  50. package/packages/dashboard/src/components/DetailPanel.vue +137 -137
  51. package/packages/dashboard/src/components/LogStream.vue +65 -65
  52. package/packages/dashboard/src/components/PipelineStage.vue +95 -95
  53. package/packages/dashboard/src/components/PipelineView.vue +156 -156
  54. package/packages/dashboard/src/components/ProjectList.vue +210 -210
  55. package/packages/dashboard/src/components/StageBadge.vue +67 -67
  56. package/packages/dashboard/src/components/StepCard.vue +94 -94
  57. package/packages/dashboard/src/components/detail/DocsDetail.vue +48 -48
  58. package/packages/dashboard/src/components/detail/GitDetail.vue +61 -61
  59. package/packages/dashboard/src/components/detail/TechDetail.vue +43 -43
  60. package/packages/dashboard/src/composables/useDashboard.js +170 -170
  61. package/packages/dashboard/src/composables/useKeyboard.js +119 -119
  62. package/packages/dashboard/src/composables/useWebSocket.js +129 -129
  63. package/packages/dashboard/src/main.js +8 -8
  64. package/packages/dashboard/src/style.css +132 -132
  65. package/packages/dashboard/vite.config.js +18 -18
  66. package/src/brainstorm-postcheck.js +158 -158
  67. package/src/change-list.js +52 -52
  68. package/src/change-risk-profile.js +352 -352
  69. package/src/classify-change.js +73 -73
  70. package/src/constants.js +70 -70
  71. package/src/contract-matrix.js +278 -278
  72. package/src/db.js +201 -201
  73. package/src/endpoint-extractor.js +315 -315
  74. package/src/hooks/claude-pre-tool-use.cjs +125 -125
  75. package/src/hooks/worktree-guard.js +653 -653
  76. package/src/index.js +922 -900
  77. package/src/init.js +431 -431
  78. package/src/knowledge-match.js +130 -130
  79. package/src/migrate.js +117 -117
  80. package/src/modules.js +482 -482
  81. package/src/progress.js +1734 -1734
  82. package/src/run.js +3465 -3358
  83. package/src/scan-postcheck.js +387 -383
  84. package/src/setup.js +398 -398
  85. package/src/stage-contract.js +700 -700
  86. package/src/stages/archive.js +160 -160
  87. package/src/stages/brainstorm-auto.js +229 -229
  88. package/src/stages/brainstorm.js +645 -645
  89. package/src/stages/doctor.js +365 -365
  90. package/src/stages/execute.js +625 -625
  91. package/src/stages/explore.js +34 -34
  92. package/src/stages/index.js +29 -29
  93. package/src/stages/knowledge.js +498 -498
  94. package/src/stages/plan-postcheck.js +511 -513
  95. package/src/stages/plan.js +582 -582
  96. package/src/stages/propose.js +174 -174
  97. package/src/stages/quick.js +82 -82
  98. package/src/stages/scan.js +558 -558
  99. package/src/stages/status.js +65 -65
  100. package/src/stages/verify.js +322 -322
  101. package/src/sync.js +497 -497
  102. package/src/task-review.js +346 -346
  103. package/src/workflow.js +785 -785
  104. package/src/worktree-apply.js +549 -549
  105. package/src/worktree-deps.js +185 -0
  106. package/src/worktree.js +982 -932
  107. package/templates/workflows/archive-impact.yaml +79 -79
  108. package/templates/workflows/scan-docs.yaml +132 -132
  109. package/test/brainstorm-plan-contract.test.mjs +273 -273
  110. package/test/check-syntax.mjs +26 -26
  111. package/test/contract-artifacts.test.mjs +323 -323
  112. package/test/decision-supersede.test.mjs +277 -277
  113. package/test/knowledge-match.test.mjs +231 -231
  114. package/test/plan-execute-contract.test.mjs +330 -330
  115. package/test/plan-optimization.test.mjs +572 -572
  116. package/test/platform-artifacts.test.mjs +166 -166
  117. package/test/platform-failure-samples.test.mjs +199 -199
  118. package/test/platform-recovery-chain.test.mjs +167 -167
  119. package/test/platform-recovery.test.mjs +136 -136
  120. package/test/platform-scan-p0.test.mjs +168 -168
  121. package/test/revision-v1.test.mjs +1145 -1145
  122. package/test/run-scan-project-parse.test.mjs +200 -200
  123. package/test/run-tests.mjs +48 -48
  124. package/test/scan-knowledge.test.mjs +175 -175
  125. package/test/scan-paths.test.mjs +68 -68
  126. package/test/scan-postcheck.test.mjs +197 -197
  127. package/test/spec-dir.test.mjs +206 -206
  128. package/test/stage-contract.test.mjs +299 -299
  129. package/test/stage-definitions.test.mjs +39 -39
  130. package/test/wait-gates.test.mjs +496 -496
  131. package/test/worktree-deps-provision.test.mjs +148 -0
  132. package/test/worktree-guard.test.mjs +71 -71
  133. package/test/worktree-native-overlay.test.mjs +188 -188
@@ -1,352 +1,352 @@
1
- /**
2
- * change-risk-profile.js — 变更风险分级检测
3
- *
4
- * 根据变更涉及的文件类型、关键词、git diff、brainstorm 产物,
5
- * 自动判定 P0/P1/P2 风险等级,产出结构化 risk-profile.json。
6
- *
7
- * P0 = 阻塞确认(必须用户确认)
8
- * P1 = 自动推进但记录
9
- * P2 = 自动通过
10
- */
11
-
12
- // ============ P0 触发规则 ============
13
-
14
- const P0_FILE_PATTERNS = [
15
- { id: 'R-002', pattern: /(?:^|\/)(?:migrations?|migration)\/(?:.+)/i, desc: '数据库 migration' },
16
- { id: 'R-002', pattern: /(?:^|\/)schema\.(?:sql|prisma|ts|js)$/i, desc: '数据库 schema' },
17
- { id: 'R-003', pattern: /(?:^|\/)(?:auth|permission|role|login|token)\b/i, desc: '鉴权/权限' },
18
- { id: 'R-004', pattern: /(?:^|\/)(?:payment|billing|stripe|paypal)\b/i, desc: '支付/资金' },
19
- { id: 'R-005', pattern: /\.(?:env|env\.\w+)$/, desc: '环境配置' },
20
- { id: 'R-005', pattern: /(?:^|\/)(?:Dockerfile|docker-compose\.\w+)$/i, desc: '部署配置' },
21
- { id: 'R-005', pattern: /(?:^|\/)config\.(?:yaml|yml|json|toml)$/i, desc: '生产配置' },
22
- ]
23
-
24
- const P0_CONTENT_PATTERNS = [
25
- { id: 'R-001', pattern: /\b(?:DROP\s+TABLE|TRUNCATE\s+TABLE|DELETE\s+FROM\s+\w+\s+(?!WHERE\s+.+\s+LIMIT))/i, desc: '删除数据' },
26
- { id: 'R-002', pattern: /\b(?:CREATE\s+TABLE|ALTER\s+TABLE|ADD\s+COLUMN|DROP\s+COLUMN|CREATE\s+INDEX)/i, desc: '数据库 migration' },
27
- ]
28
-
29
- // ============ P1 触发规则 ============
30
-
31
- const P1_FILE_PATTERNS = [
32
- { id: 'R-101', pattern: /(?:^|\/)(?:routes|controllers?|handlers?)\//i, desc: 'API 层' },
33
- { id: 'R-102', pattern: /(?:^|\/)(?:models|entities)\//i, desc: '数据模型层' },
34
- { id: 'R-104', pattern: /(?:^|\/)(?:services)\//i, desc: '业务逻辑层(跨模块)' },
35
- { id: 'R-106', pattern: /(?:^|\/)index\.(?:ts|js)$/i, desc: 're-export 入口' },
36
- ]
37
-
38
- const P1_CONTENT_PATTERNS = [
39
- { id: 'R-101', pattern: /\b(?:daemon|backend|grpc|websocket|cross.?process|ipc|message.?queue)\b/i, desc: '跨进程通信' },
40
- { id: 'R-101', pattern: /\b(?:session|lease|agent.?run|lifecycle|state.?transition|claim|heartbeat)\b/i, desc: '状态机/生命周期' },
41
- { id: 'R-102', pattern: /\b(?:api|client|contract|dto)\b/i, desc: 'API contract' },
42
- { id: 'R-105', pattern: /(?:^|\/)(?:workflow|daemon|session|lifecycle|state-machine)\b/i, desc: '核心模块' },
43
- ]
44
-
45
- // ============ P0/P1 命中文件名关键词(用于 git diff 检测) ============
46
-
47
- const PROTECTED_FILE_NAMES = [
48
- '.env', 'package.json', 'tsconfig.json', 'vite.config.ts', 'vite.config.js',
49
- 'prisma/schema.prisma', 'docker-compose.yml', 'docker-compose.yaml',
50
- ]
51
-
52
- // ============ 向后兼容:旧的 INTEGRATION_CRITICAL_PATTERNS ============
53
-
54
- export const INTEGRATION_CRITICAL_PATTERNS = [
55
- /\bdaemon\b/i,
56
- /\bbackend\b/i,
57
- /\bclient.*api\b/i,
58
- /\bgrpc\b/i,
59
- /\bwebsocket\b/i,
60
- /\bhttp.*client\b/i,
61
- /\bsession\b/i,
62
- /\blease\b/i,
63
- /\bagent.?run\b/i,
64
- /\blifecycle\b/i,
65
- /\bstate.?transition\b/i,
66
- /\bclaim\b/i,
67
- /\bheartbeat\b/i,
68
- /\bcross.?process\b/i,
69
- /\bipc\b/i,
70
- /\bmessage.?queue\b/i,
71
- /\bpub.?sub\b/i,
72
- /\bcli\.ts\b/i,
73
- /\bmain\.ts\b/i,
74
- /\bentrypoint\b/i,
75
- /\bserver\.(js|ts)\b/i,
76
- /\bbootstrap\b/i,
77
- /\bdockerfile\b/i,
78
- /\bdocker.?compose\b/i,
79
- ]
80
-
81
- export const INTEGRATION_FILE_PATTERNS = [
82
- /daemon/i,
83
- /session.?manager/i,
84
- /agent.?run/i,
85
- /lifecycle/i,
86
- /state.?machine/i,
87
- /lease/i,
88
- /cli\.(js|ts)$/,
89
- /main\.(js|ts)$/,
90
- /server\.(js|ts)$/,
91
- /bootstrap/i,
92
- /startup/i,
93
- ]
94
-
95
- // ============ 核心检测函数 ============
96
-
97
- /**
98
- * 三级风险检测:P0 / P1 / P2
99
- * @param {object} opts
100
- * @param {string} [opts.designContent] - design.md 内容
101
- * @param {string} [opts.planContent] - plan.md 内容
102
- * @param {string[]} [opts.changedFiles] - 变更文件列表
103
- * @param {string} [opts.diffContent] - git diff 内容(可选,用于更精确检测)
104
- * @param {object} [opts.nextAction] - next-action.json 解析后的对象(可选)
105
- * @param {string[]} [opts.protectedFiles] - 项目自定义 protected files 列表
106
- * @returns {RiskProfile}
107
- *
108
- * @typedef {object} RiskProfile
109
- * @property {string} level - 'P0' | 'P1' | 'P2'
110
- * @property {string[]} triggers - 触发的规则 ID 列表
111
- * @property {object[]} assessedFrom - 评估依据
112
- * @property {string[]} applyBlockers - apply 阻塞原因
113
- * @property {boolean} canAutoApply - 是否可自动 apply
114
- * @property {string} applyReason - apply 决策原因
115
- */
116
- export function detectRiskProfile({ designContent = '', planContent = '', changedFiles = [], diffContent = '', nextAction = null, protectedFiles = [] } = {}) {
117
- const triggers = []
118
- const assessedFrom = []
119
-
120
- const combined = [designContent, planContent].join('\n')
121
-
122
- // ── P0 检测(最高优先级)──
123
-
124
- // 基于文件路径
125
- for (const rule of P0_FILE_PATTERNS) {
126
- for (const file of changedFiles) {
127
- if (rule.pattern.test(file)) {
128
- rule.pattern.lastIndex = 0
129
- if (!triggers.includes(rule.id)) {
130
- triggers.push(rule.id)
131
- assessedFrom.push({ source: 'file_path', pattern: rule.desc, matchedFiles: [file] })
132
- }
133
- }
134
- }
135
- }
136
-
137
- // 基于 diff 内容(P0 关键词)
138
- const diffText = diffContent || combined
139
- for (const rule of P0_CONTENT_PATTERNS) {
140
- if (rule.pattern.test(diffText)) {
141
- rule.pattern.lastIndex = 0
142
- if (!triggers.includes(rule.id)) {
143
- triggers.push(rule.id)
144
- assessedFrom.push({ source: 'content', pattern: rule.desc })
145
- }
146
- }
147
- }
148
-
149
- // protected files
150
- for (const file of changedFiles) {
151
- if (PROTECTED_FILE_NAMES.some(p => file === p || file.endsWith('/' + p))) {
152
- const id = 'R-005'
153
- if (!triggers.includes(id)) {
154
- triggers.push(id)
155
- assessedFrom.push({ source: 'protected_file', pattern: file })
156
- }
157
- }
158
- // 用户自定义 protected files
159
- if (protectedFiles.includes(file)) {
160
- const id = 'R-005'
161
- if (!triggers.includes(id)) {
162
- triggers.push(id)
163
- assessedFrom.push({ source: 'protected_file', pattern: file })
164
- }
165
- }
166
- }
167
-
168
- // next-action.json 有 blocking questions
169
- if (nextAction && nextAction.has_blocking_questions === true) {
170
- const id = 'R-009'
171
- if (!triggers.includes(id)) {
172
- triggers.push(id)
173
- assessedFrom.push({ source: 'brainstorm', pattern: 'has_blocking_questions === true' })
174
- }
175
- }
176
-
177
- // ── P1 检测(只在无 P0 时检测)──
178
- if (!triggers.some(t => t.startsWith('R-00'))) {
179
- // 基于文件路径
180
- for (const rule of P1_FILE_PATTERNS) {
181
- for (const file of changedFiles) {
182
- if (rule.pattern.test(file)) {
183
- rule.pattern.lastIndex = 0
184
- if (!triggers.includes(rule.id)) {
185
- triggers.push(rule.id)
186
- assessedFrom.push({ source: 'file_path', pattern: rule.desc, matchedFiles: [file] })
187
- }
188
- }
189
- }
190
- }
191
-
192
- // 基于内容关键词
193
- for (const rule of P1_CONTENT_PATTERNS) {
194
- if (rule.pattern.test(combined)) {
195
- rule.pattern.lastIndex = 0
196
- if (!triggers.includes(rule.id)) {
197
- triggers.push(rule.id)
198
- assessedFrom.push({ source: 'content', pattern: rule.desc })
199
- }
200
- }
201
- }
202
-
203
- // 跨模块检测(> 3 个文件的变更)
204
- if (changedFiles.length > 10) {
205
- const id = 'R-101'
206
- if (!triggers.includes(id)) {
207
- triggers.push(id)
208
- assessedFrom.push({ source: 'file_count', pattern: `${changedFiles.length} files changed` })
209
- }
210
- }
211
-
212
- // next-action.json 有 NEEDS_REVIEW 决策
213
- if (nextAction && Array.isArray(nextAction.auto_decisions)) {
214
- for (const d of nextAction.auto_decisions) {
215
- if (d.status === 'NEEDS_REVIEW') {
216
- const id = 'R-102'
217
- if (!triggers.includes(id)) {
218
- triggers.push(id)
219
- assessedFrom.push({ source: 'brainstorm', pattern: `NEEDS_REVIEW: ${d.decision}` })
220
- }
221
- }
222
- }
223
- }
224
- }
225
-
226
- // ── 判定等级 ──
227
- let level = 'P2'
228
- if (triggers.some(t => t.match(/^R-0\d+$/))) {
229
- level = 'P0'
230
- } else if (triggers.some(t => t.match(/^R-1\d+$/))) {
231
- level = 'P1'
232
- }
233
-
234
- // ── apply 决策 ──
235
- const applyBlockers = []
236
- if (level === 'P0') {
237
- applyBlockers.push('风险等级 P0:需要用户确认后才能 apply')
238
- }
239
-
240
- const canAutoApply = level !== 'P0' && applyBlockers.length === 0
241
- const applyReason = canAutoApply
242
- ? `风险等级 ${level},无 P0 触发,无 protected files 修改`
243
- : applyBlockers.join('; ')
244
-
245
- return { level, triggers, assessedFrom, applyBlockers, canAutoApply, applyReason }
246
- }
247
-
248
- // ============ 向后兼容 ============
249
-
250
- /**
251
- * 旧的 detectChangeRisk 接口保持向后兼容
252
- * @returns {{ level: string, triggers: string[], requiredVerification: string[] }}
253
- */
254
- export function detectChangeRisk({ designContent = '', planContent = '', changedFiles = [] } = {}) {
255
- const triggers = []
256
- const combined = [designContent, planContent].join('\n')
257
-
258
- for (const pattern of INTEGRATION_CRITICAL_PATTERNS) {
259
- if (pattern.test(combined)) {
260
- pattern.lastIndex = 0
261
- const match = combined.match(pattern)
262
- if (match && !triggers.includes(match[0])) triggers.push(match[0])
263
- }
264
- }
265
-
266
- for (const file of changedFiles) {
267
- for (const pattern of INTEGRATION_FILE_PATTERNS) {
268
- if (pattern.test(file)) {
269
- pattern.lastIndex = 0
270
- const match = file.match(pattern)
271
- if (match && !triggers.includes(match[0])) triggers.push(match[0])
272
- }
273
- }
274
- }
275
-
276
- if (triggers.length === 0) {
277
- return { level: 'doc-only', triggers: [], requiredVerification: ['static_check'] }
278
- }
279
-
280
- const deploymentTrigger = triggers.some(t => /cli\.ts|main\.ts|server\.(js|ts)|bootstrap|entrypoint/i.test(t))
281
- const lifecycleTrigger = triggers.some(t => /session|lease|agent.?run|lifecycle|state.?transition|claim|heartbeat/i.test(t))
282
- const crossProcessTrigger = triggers.some(t => /daemon|backend|client.*api|grpc|websocket|cross.?process|ipc|message.?queue/i.test(t))
283
-
284
- let level
285
- const requiredVerification = ['unit_tests']
286
-
287
- if (deploymentTrigger) {
288
- level = 'deployment-critical'
289
- requiredVerification.push('contract_tests', 'real_daemon_backend_integration', 'runtime_log_evidence', 'real_startup_once')
290
- } else if (lifecycleTrigger || crossProcessTrigger) {
291
- level = 'integration-critical'
292
- requiredVerification.push('contract_tests', 'real_daemon_backend_integration', 'runtime_log_evidence', 'terminal_state_assertion')
293
- } else if (triggers.some(t => /api|client|contract|dto/i.test(t))) {
294
- level = 'contract-required'
295
- requiredVerification.push('contract_tests')
296
- } else {
297
- level = 'unit-sufficient'
298
- }
299
-
300
- return { level, triggers, requiredVerification }
301
- }
302
-
303
- /**
304
- * 检查 verify-result.md 是否包含集成验证证据
305
- */
306
- export function checkIntegrationEvidence(verifyContent, requiredVerification) {
307
- const errors = []
308
- const warnings = []
309
- const lower = verifyContent.toLowerCase()
310
-
311
- const needsIntegration = requiredVerification.includes('real_daemon_backend_integration')
312
- const needsLogEvidence = requiredVerification.includes('runtime_log_evidence')
313
- const needsTerminalState = requiredVerification.includes('terminal_state_assertion')
314
- const needsRealStartup = requiredVerification.includes('real_startup_once')
315
-
316
- if (needsIntegration) {
317
- const hasMockOnly = /mock.*test.*passed|unit.*test.*passed/i.test(lower)
318
- const hasIntegrationEvidence =
319
- /集成测试|integration.*test|e2e.*test|端到端/i.test(lower) ||
320
- /daemon.*backend|backend.*daemon|真实.*集成|real.*integration/i.test(lower) ||
321
- /runtime.*evidence|运行时.*证据/i.test(lower)
322
-
323
- if (!hasIntegrationEvidence && hasMockOnly) {
324
- errors.push('integration-critical 变更只提供了 mock 单测证据,缺少真实 daemon↔backend 集成验证')
325
- } else if (!hasIntegrationEvidence) {
326
- errors.push('integration-critical 变更缺少集成验证证据 — 需要真实 daemon↔backend 测试结果或运行时日志')
327
- }
328
- }
329
-
330
- if (needsLogEvidence) {
331
- const hasRuntimeSection = /runtime.*evidence|运行时.*证据|daemon.*log|日志.*片段/i.test(lower)
332
- if (!hasRuntimeSection) {
333
- errors.push('integration-critical 变更的 verify-result.md 缺少 Runtime Evidence section')
334
- }
335
- }
336
-
337
- if (needsTerminalState) {
338
- const hasTerminalState = /terminal.*state|终态|running.*completed|completed.*failed|session.*end|lease.*end/i.test(lower)
339
- if (!hasTerminalState) {
340
- warnings.push('建议检查终态断言:AgentRun running→completed/failed、session end 状态同步')
341
- }
342
- }
343
-
344
- if (needsRealStartup) {
345
- const hasStartupEvidence = /启动.*一次|real.*startup|实际.*启动|docker.*up|npm.*start|node.*server/i.test(lower)
346
- if (!hasStartupEvidence) {
347
- errors.push('deployment-critical 变更需要真实启动验证证据')
348
- }
349
- }
350
-
351
- return { ok: errors.length === 0, errors, warnings }
352
- }
1
+ /**
2
+ * change-risk-profile.js — 变更风险分级检测
3
+ *
4
+ * 根据变更涉及的文件类型、关键词、git diff、brainstorm 产物,
5
+ * 自动判定 P0/P1/P2 风险等级,产出结构化 risk-profile.json。
6
+ *
7
+ * P0 = 阻塞确认(必须用户确认)
8
+ * P1 = 自动推进但记录
9
+ * P2 = 自动通过
10
+ */
11
+
12
+ // ============ P0 触发规则 ============
13
+
14
+ const P0_FILE_PATTERNS = [
15
+ { id: 'R-002', pattern: /(?:^|\/)(?:migrations?|migration)\/(?:.+)/i, desc: '数据库 migration' },
16
+ { id: 'R-002', pattern: /(?:^|\/)schema\.(?:sql|prisma|ts|js)$/i, desc: '数据库 schema' },
17
+ { id: 'R-003', pattern: /(?:^|\/)(?:auth|permission|role|login|token)\b/i, desc: '鉴权/权限' },
18
+ { id: 'R-004', pattern: /(?:^|\/)(?:payment|billing|stripe|paypal)\b/i, desc: '支付/资金' },
19
+ { id: 'R-005', pattern: /\.(?:env|env\.\w+)$/, desc: '环境配置' },
20
+ { id: 'R-005', pattern: /(?:^|\/)(?:Dockerfile|docker-compose\.\w+)$/i, desc: '部署配置' },
21
+ { id: 'R-005', pattern: /(?:^|\/)config\.(?:yaml|yml|json|toml)$/i, desc: '生产配置' },
22
+ ]
23
+
24
+ const P0_CONTENT_PATTERNS = [
25
+ { id: 'R-001', pattern: /\b(?:DROP\s+TABLE|TRUNCATE\s+TABLE|DELETE\s+FROM\s+\w+\s+(?!WHERE\s+.+\s+LIMIT))/i, desc: '删除数据' },
26
+ { id: 'R-002', pattern: /\b(?:CREATE\s+TABLE|ALTER\s+TABLE|ADD\s+COLUMN|DROP\s+COLUMN|CREATE\s+INDEX)/i, desc: '数据库 migration' },
27
+ ]
28
+
29
+ // ============ P1 触发规则 ============
30
+
31
+ const P1_FILE_PATTERNS = [
32
+ { id: 'R-101', pattern: /(?:^|\/)(?:routes|controllers?|handlers?)\//i, desc: 'API 层' },
33
+ { id: 'R-102', pattern: /(?:^|\/)(?:models|entities)\//i, desc: '数据模型层' },
34
+ { id: 'R-104', pattern: /(?:^|\/)(?:services)\//i, desc: '业务逻辑层(跨模块)' },
35
+ { id: 'R-106', pattern: /(?:^|\/)index\.(?:ts|js)$/i, desc: 're-export 入口' },
36
+ ]
37
+
38
+ const P1_CONTENT_PATTERNS = [
39
+ { id: 'R-101', pattern: /\b(?:daemon|backend|grpc|websocket|cross.?process|ipc|message.?queue)\b/i, desc: '跨进程通信' },
40
+ { id: 'R-101', pattern: /\b(?:session|lease|agent.?run|lifecycle|state.?transition|claim|heartbeat)\b/i, desc: '状态机/生命周期' },
41
+ { id: 'R-102', pattern: /\b(?:api|client|contract|dto)\b/i, desc: 'API contract' },
42
+ { id: 'R-105', pattern: /(?:^|\/)(?:workflow|daemon|session|lifecycle|state-machine)\b/i, desc: '核心模块' },
43
+ ]
44
+
45
+ // ============ P0/P1 命中文件名关键词(用于 git diff 检测) ============
46
+
47
+ const PROTECTED_FILE_NAMES = [
48
+ '.env', 'package.json', 'tsconfig.json', 'vite.config.ts', 'vite.config.js',
49
+ 'prisma/schema.prisma', 'docker-compose.yml', 'docker-compose.yaml',
50
+ ]
51
+
52
+ // ============ 向后兼容:旧的 INTEGRATION_CRITICAL_PATTERNS ============
53
+
54
+ export const INTEGRATION_CRITICAL_PATTERNS = [
55
+ /\bdaemon\b/i,
56
+ /\bbackend\b/i,
57
+ /\bclient.*api\b/i,
58
+ /\bgrpc\b/i,
59
+ /\bwebsocket\b/i,
60
+ /\bhttp.*client\b/i,
61
+ /\bsession\b/i,
62
+ /\blease\b/i,
63
+ /\bagent.?run\b/i,
64
+ /\blifecycle\b/i,
65
+ /\bstate.?transition\b/i,
66
+ /\bclaim\b/i,
67
+ /\bheartbeat\b/i,
68
+ /\bcross.?process\b/i,
69
+ /\bipc\b/i,
70
+ /\bmessage.?queue\b/i,
71
+ /\bpub.?sub\b/i,
72
+ /\bcli\.ts\b/i,
73
+ /\bmain\.ts\b/i,
74
+ /\bentrypoint\b/i,
75
+ /\bserver\.(js|ts)\b/i,
76
+ /\bbootstrap\b/i,
77
+ /\bdockerfile\b/i,
78
+ /\bdocker.?compose\b/i,
79
+ ]
80
+
81
+ export const INTEGRATION_FILE_PATTERNS = [
82
+ /daemon/i,
83
+ /session.?manager/i,
84
+ /agent.?run/i,
85
+ /lifecycle/i,
86
+ /state.?machine/i,
87
+ /lease/i,
88
+ /cli\.(js|ts)$/,
89
+ /main\.(js|ts)$/,
90
+ /server\.(js|ts)$/,
91
+ /bootstrap/i,
92
+ /startup/i,
93
+ ]
94
+
95
+ // ============ 核心检测函数 ============
96
+
97
+ /**
98
+ * 三级风险检测:P0 / P1 / P2
99
+ * @param {object} opts
100
+ * @param {string} [opts.designContent] - design.md 内容
101
+ * @param {string} [opts.planContent] - plan.md 内容
102
+ * @param {string[]} [opts.changedFiles] - 变更文件列表
103
+ * @param {string} [opts.diffContent] - git diff 内容(可选,用于更精确检测)
104
+ * @param {object} [opts.nextAction] - next-action.json 解析后的对象(可选)
105
+ * @param {string[]} [opts.protectedFiles] - 项目自定义 protected files 列表
106
+ * @returns {RiskProfile}
107
+ *
108
+ * @typedef {object} RiskProfile
109
+ * @property {string} level - 'P0' | 'P1' | 'P2'
110
+ * @property {string[]} triggers - 触发的规则 ID 列表
111
+ * @property {object[]} assessedFrom - 评估依据
112
+ * @property {string[]} applyBlockers - apply 阻塞原因
113
+ * @property {boolean} canAutoApply - 是否可自动 apply
114
+ * @property {string} applyReason - apply 决策原因
115
+ */
116
+ export function detectRiskProfile({ designContent = '', planContent = '', changedFiles = [], diffContent = '', nextAction = null, protectedFiles = [] } = {}) {
117
+ const triggers = []
118
+ const assessedFrom = []
119
+
120
+ const combined = [designContent, planContent].join('\n')
121
+
122
+ // ── P0 检测(最高优先级)──
123
+
124
+ // 基于文件路径
125
+ for (const rule of P0_FILE_PATTERNS) {
126
+ for (const file of changedFiles) {
127
+ if (rule.pattern.test(file)) {
128
+ rule.pattern.lastIndex = 0
129
+ if (!triggers.includes(rule.id)) {
130
+ triggers.push(rule.id)
131
+ assessedFrom.push({ source: 'file_path', pattern: rule.desc, matchedFiles: [file] })
132
+ }
133
+ }
134
+ }
135
+ }
136
+
137
+ // 基于 diff 内容(P0 关键词)
138
+ const diffText = diffContent || combined
139
+ for (const rule of P0_CONTENT_PATTERNS) {
140
+ if (rule.pattern.test(diffText)) {
141
+ rule.pattern.lastIndex = 0
142
+ if (!triggers.includes(rule.id)) {
143
+ triggers.push(rule.id)
144
+ assessedFrom.push({ source: 'content', pattern: rule.desc })
145
+ }
146
+ }
147
+ }
148
+
149
+ // protected files
150
+ for (const file of changedFiles) {
151
+ if (PROTECTED_FILE_NAMES.some(p => file === p || file.endsWith('/' + p))) {
152
+ const id = 'R-005'
153
+ if (!triggers.includes(id)) {
154
+ triggers.push(id)
155
+ assessedFrom.push({ source: 'protected_file', pattern: file })
156
+ }
157
+ }
158
+ // 用户自定义 protected files
159
+ if (protectedFiles.includes(file)) {
160
+ const id = 'R-005'
161
+ if (!triggers.includes(id)) {
162
+ triggers.push(id)
163
+ assessedFrom.push({ source: 'protected_file', pattern: file })
164
+ }
165
+ }
166
+ }
167
+
168
+ // next-action.json 有 blocking questions
169
+ if (nextAction && nextAction.has_blocking_questions === true) {
170
+ const id = 'R-009'
171
+ if (!triggers.includes(id)) {
172
+ triggers.push(id)
173
+ assessedFrom.push({ source: 'brainstorm', pattern: 'has_blocking_questions === true' })
174
+ }
175
+ }
176
+
177
+ // ── P1 检测(只在无 P0 时检测)──
178
+ if (!triggers.some(t => t.startsWith('R-00'))) {
179
+ // 基于文件路径
180
+ for (const rule of P1_FILE_PATTERNS) {
181
+ for (const file of changedFiles) {
182
+ if (rule.pattern.test(file)) {
183
+ rule.pattern.lastIndex = 0
184
+ if (!triggers.includes(rule.id)) {
185
+ triggers.push(rule.id)
186
+ assessedFrom.push({ source: 'file_path', pattern: rule.desc, matchedFiles: [file] })
187
+ }
188
+ }
189
+ }
190
+ }
191
+
192
+ // 基于内容关键词
193
+ for (const rule of P1_CONTENT_PATTERNS) {
194
+ if (rule.pattern.test(combined)) {
195
+ rule.pattern.lastIndex = 0
196
+ if (!triggers.includes(rule.id)) {
197
+ triggers.push(rule.id)
198
+ assessedFrom.push({ source: 'content', pattern: rule.desc })
199
+ }
200
+ }
201
+ }
202
+
203
+ // 跨模块检测(> 3 个文件的变更)
204
+ if (changedFiles.length > 10) {
205
+ const id = 'R-101'
206
+ if (!triggers.includes(id)) {
207
+ triggers.push(id)
208
+ assessedFrom.push({ source: 'file_count', pattern: `${changedFiles.length} files changed` })
209
+ }
210
+ }
211
+
212
+ // next-action.json 有 NEEDS_REVIEW 决策
213
+ if (nextAction && Array.isArray(nextAction.auto_decisions)) {
214
+ for (const d of nextAction.auto_decisions) {
215
+ if (d.status === 'NEEDS_REVIEW') {
216
+ const id = 'R-102'
217
+ if (!triggers.includes(id)) {
218
+ triggers.push(id)
219
+ assessedFrom.push({ source: 'brainstorm', pattern: `NEEDS_REVIEW: ${d.decision}` })
220
+ }
221
+ }
222
+ }
223
+ }
224
+ }
225
+
226
+ // ── 判定等级 ──
227
+ let level = 'P2'
228
+ if (triggers.some(t => t.match(/^R-0\d+$/))) {
229
+ level = 'P0'
230
+ } else if (triggers.some(t => t.match(/^R-1\d+$/))) {
231
+ level = 'P1'
232
+ }
233
+
234
+ // ── apply 决策 ──
235
+ const applyBlockers = []
236
+ if (level === 'P0') {
237
+ applyBlockers.push('风险等级 P0:需要用户确认后才能 apply')
238
+ }
239
+
240
+ const canAutoApply = level !== 'P0' && applyBlockers.length === 0
241
+ const applyReason = canAutoApply
242
+ ? `风险等级 ${level},无 P0 触发,无 protected files 修改`
243
+ : applyBlockers.join('; ')
244
+
245
+ return { level, triggers, assessedFrom, applyBlockers, canAutoApply, applyReason }
246
+ }
247
+
248
+ // ============ 向后兼容 ============
249
+
250
+ /**
251
+ * 旧的 detectChangeRisk 接口保持向后兼容
252
+ * @returns {{ level: string, triggers: string[], requiredVerification: string[] }}
253
+ */
254
+ export function detectChangeRisk({ designContent = '', planContent = '', changedFiles = [] } = {}) {
255
+ const triggers = []
256
+ const combined = [designContent, planContent].join('\n')
257
+
258
+ for (const pattern of INTEGRATION_CRITICAL_PATTERNS) {
259
+ if (pattern.test(combined)) {
260
+ pattern.lastIndex = 0
261
+ const match = combined.match(pattern)
262
+ if (match && !triggers.includes(match[0])) triggers.push(match[0])
263
+ }
264
+ }
265
+
266
+ for (const file of changedFiles) {
267
+ for (const pattern of INTEGRATION_FILE_PATTERNS) {
268
+ if (pattern.test(file)) {
269
+ pattern.lastIndex = 0
270
+ const match = file.match(pattern)
271
+ if (match && !triggers.includes(match[0])) triggers.push(match[0])
272
+ }
273
+ }
274
+ }
275
+
276
+ if (triggers.length === 0) {
277
+ return { level: 'doc-only', triggers: [], requiredVerification: ['static_check'] }
278
+ }
279
+
280
+ const deploymentTrigger = triggers.some(t => /cli\.ts|main\.ts|server\.(js|ts)|bootstrap|entrypoint/i.test(t))
281
+ const lifecycleTrigger = triggers.some(t => /session|lease|agent.?run|lifecycle|state.?transition|claim|heartbeat/i.test(t))
282
+ const crossProcessTrigger = triggers.some(t => /daemon|backend|client.*api|grpc|websocket|cross.?process|ipc|message.?queue/i.test(t))
283
+
284
+ let level
285
+ const requiredVerification = ['unit_tests']
286
+
287
+ if (deploymentTrigger) {
288
+ level = 'deployment-critical'
289
+ requiredVerification.push('contract_tests', 'real_daemon_backend_integration', 'runtime_log_evidence', 'real_startup_once')
290
+ } else if (lifecycleTrigger || crossProcessTrigger) {
291
+ level = 'integration-critical'
292
+ requiredVerification.push('contract_tests', 'real_daemon_backend_integration', 'runtime_log_evidence', 'terminal_state_assertion')
293
+ } else if (triggers.some(t => /api|client|contract|dto/i.test(t))) {
294
+ level = 'contract-required'
295
+ requiredVerification.push('contract_tests')
296
+ } else {
297
+ level = 'unit-sufficient'
298
+ }
299
+
300
+ return { level, triggers, requiredVerification }
301
+ }
302
+
303
+ /**
304
+ * 检查 verify-result.md 是否包含集成验证证据
305
+ */
306
+ export function checkIntegrationEvidence(verifyContent, requiredVerification) {
307
+ const errors = []
308
+ const warnings = []
309
+ const lower = verifyContent.toLowerCase()
310
+
311
+ const needsIntegration = requiredVerification.includes('real_daemon_backend_integration')
312
+ const needsLogEvidence = requiredVerification.includes('runtime_log_evidence')
313
+ const needsTerminalState = requiredVerification.includes('terminal_state_assertion')
314
+ const needsRealStartup = requiredVerification.includes('real_startup_once')
315
+
316
+ if (needsIntegration) {
317
+ const hasMockOnly = /mock.*test.*passed|unit.*test.*passed/i.test(lower)
318
+ const hasIntegrationEvidence =
319
+ /集成测试|integration.*test|e2e.*test|端到端/i.test(lower) ||
320
+ /daemon.*backend|backend.*daemon|真实.*集成|real.*integration/i.test(lower) ||
321
+ /runtime.*evidence|运行时.*证据/i.test(lower)
322
+
323
+ if (!hasIntegrationEvidence && hasMockOnly) {
324
+ errors.push('integration-critical 变更只提供了 mock 单测证据,缺少真实 daemon↔backend 集成验证')
325
+ } else if (!hasIntegrationEvidence) {
326
+ errors.push('integration-critical 变更缺少集成验证证据 — 需要真实 daemon↔backend 测试结果或运行时日志')
327
+ }
328
+ }
329
+
330
+ if (needsLogEvidence) {
331
+ const hasRuntimeSection = /runtime.*evidence|运行时.*证据|daemon.*log|日志.*片段/i.test(lower)
332
+ if (!hasRuntimeSection) {
333
+ errors.push('integration-critical 变更的 verify-result.md 缺少 Runtime Evidence section')
334
+ }
335
+ }
336
+
337
+ if (needsTerminalState) {
338
+ const hasTerminalState = /terminal.*state|终态|running.*completed|completed.*failed|session.*end|lease.*end/i.test(lower)
339
+ if (!hasTerminalState) {
340
+ warnings.push('建议检查终态断言:AgentRun running→completed/failed、session end 状态同步')
341
+ }
342
+ }
343
+
344
+ if (needsRealStartup) {
345
+ const hasStartupEvidence = /启动.*一次|real.*startup|实际.*启动|docker.*up|npm.*start|node.*server/i.test(lower)
346
+ if (!hasStartupEvidence) {
347
+ errors.push('deployment-critical 变更需要真实启动验证证据')
348
+ }
349
+ }
350
+
351
+ return { ok: errors.length === 0, errors, warnings }
352
+ }