sillyspec 3.26.10 → 3.26.13

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 (101) hide show
  1. package/.claude/skills/sillyspec-archive/SKILL.md +85 -85
  2. package/.claude/skills/sillyspec-brainstorm/SKILL.md +114 -114
  3. package/.claude/skills/sillyspec-commit/SKILL.md +109 -109
  4. package/.claude/skills/sillyspec-continue/SKILL.md +45 -45
  5. package/.claude/skills/sillyspec-doctor/SKILL.md +76 -76
  6. package/.claude/skills/sillyspec-execute/SKILL.md +200 -200
  7. package/.claude/skills/sillyspec-explore/SKILL.md +95 -95
  8. package/.claude/skills/sillyspec-knowledge/SKILL.md +269 -269
  9. package/.claude/skills/sillyspec-plan/SKILL.md +148 -148
  10. package/.claude/skills/sillyspec-quick/SKILL.md +115 -111
  11. package/.claude/skills/sillyspec-resume/SKILL.md +68 -68
  12. package/.claude/skills/sillyspec-scan/SKILL.md +79 -79
  13. package/.claude/skills/sillyspec-state/SKILL.md +64 -64
  14. package/.claude/skills/sillyspec-status/SKILL.md +54 -54
  15. package/.claude/skills/sillyspec-verify/SKILL.md +83 -83
  16. package/.claude/skills/sillyspec-workspace/SKILL.md +169 -169
  17. package/.gitattributes +2 -0
  18. package/.husky/pre-push +20 -20
  19. package/README.md +203 -201
  20. package/SKILL.md +91 -90
  21. package/package.json +39 -39
  22. package/packages/dashboard/dist/assets/index-Bq_Z2hne.js +7446 -7446
  23. package/packages/dashboard/dist/assets/index-O2W5RV4z.css +1 -1
  24. package/packages/dashboard/dist/index.html +16 -16
  25. package/packages/dashboard/package.json +25 -25
  26. package/packages/dashboard/server/executor.js +95 -86
  27. package/packages/dashboard/server/index.js +663 -601
  28. package/packages/dashboard/server/parser.js +526 -526
  29. package/src/change-risk-profile.js +254 -254
  30. package/src/classify-change.js +109 -109
  31. package/src/config-schema.js +313 -310
  32. package/src/contract-matrix.js +388 -379
  33. package/src/db.js +370 -350
  34. package/src/dispatch/backends/local-agent.js +155 -155
  35. package/src/dispatch/backends/sillyhub-mcp.js +245 -245
  36. package/src/dispatch/probe.js +246 -210
  37. package/src/dispatch/strategy.js +121 -121
  38. package/src/docs-check.js +188 -16
  39. package/src/docs-debt.js +6 -2
  40. package/src/docs-gate.js +1 -0
  41. package/src/doctor-diagnostics.js +898 -711
  42. package/src/endpoint-extractor.js +401 -401
  43. package/src/fs-atomic.js +71 -69
  44. package/src/git-helper.js +82 -79
  45. package/src/hooks/claude-pre-tool-use.cjs +125 -125
  46. package/src/hooks/worktree-guard.js +854 -848
  47. package/src/index.js +251 -20
  48. package/src/init.js +624 -623
  49. package/src/knowledge-match.js +130 -130
  50. package/src/local-detect.js +128 -120
  51. package/src/machine-interface.js +543 -543
  52. package/src/migrate.js +127 -127
  53. package/src/modules.js +7 -5
  54. package/src/progress/change-registry.js +297 -260
  55. package/src/progress/consistency-doctor.js +355 -355
  56. package/src/progress/shared.js +36 -36
  57. package/src/progress/stage-machine.js +589 -550
  58. package/src/progress/step-store.js +261 -261
  59. package/src/progress.js +1285 -1127
  60. package/src/quicklog.js +724 -693
  61. package/src/review-tier.js +77 -77
  62. package/src/run/command.js +1408 -1364
  63. package/src/run/complete-handlers.js +1450 -1399
  64. package/src/run/complete.js +1181 -920
  65. package/src/run/gates.js +878 -755
  66. package/src/run/prompt.js +765 -761
  67. package/src/run/quick-audit.js +155 -146
  68. package/src/run/shared.js +1348 -1215
  69. package/src/run/stage.js +527 -479
  70. package/src/scan-postcheck.js +371 -371
  71. package/src/setup.js +414 -416
  72. package/src/sillyhub-mcp/client.js +597 -529
  73. package/src/spec-dir-typo.js +3 -24
  74. package/src/spec-sync.js +358 -319
  75. package/src/stage-contract.js +871 -897
  76. package/src/stage-review.js +549 -549
  77. package/src/stages/archive.js +156 -155
  78. package/src/stages/brainstorm-auto.js +236 -236
  79. package/src/stages/brainstorm.js +597 -597
  80. package/src/stages/cmd-existence.js +145 -145
  81. package/src/stages/doctor.js +386 -371
  82. package/src/stages/execute.js +1014 -1003
  83. package/src/stages/explore.js +34 -34
  84. package/src/stages/index.js +29 -29
  85. package/src/stages/knowledge.js +498 -498
  86. package/src/stages/plan-postcheck.js +1323 -1302
  87. package/src/stages/plan.js +642 -623
  88. package/src/stages/quick.js +153 -151
  89. package/src/stages/scan.js +607 -607
  90. package/src/stages/status.js +64 -64
  91. package/src/stages/verify.js +264 -264
  92. package/src/sync.js +1325 -1135
  93. package/src/task-review.js +1204 -1019
  94. package/src/taskcard.js +178 -0
  95. package/src/verify-postcheck.js +1199 -1186
  96. package/src/workflow.js +600 -600
  97. package/src/worktree-apply.js +1237 -1136
  98. package/src/worktree-deps.js +453 -353
  99. package/src/worktree.js +1527 -1481
  100. package/templates/workflows/archive-impact.yaml +79 -79
  101. package/templates/workflows/scan-docs.yaml +132 -132
@@ -1,401 +1,401 @@
1
- /**
2
- * endpoint-extractor.js — 从代码中提取 HTTP 端点定义和调用
3
- *
4
- * provider 端:扫描 router 文件,提取注册的 API 路径
5
- * consumer 端:扫描前端文件,提取 apiFetch/request 调用路径
6
- *
7
- * 契约对账时:provider 产出 ≠ consumer 消费 → gap
8
- */
9
-
10
- import { existsSync, readFileSync, readdirSync, statSync } from 'fs'
11
- import { join, extname, basename, dirname, resolve } from 'path'
12
- import { execSync } from 'child_process'
13
-
14
- // ─── Provider: 扫描后端 router 注册的端点 ───────────────────────────────
15
-
16
- /**
17
- * 从单个文件提取 FastAPI router 端点
18
- * 支持 APIRouter(prefix=...) 和 @router.get/post/put/delete/patch("/path")
19
- *
20
- * @param {string} filePath - 文件绝对路径
21
- * @returns {Array<{ method: string, path: string, source: string, line: number }>}
22
- */
23
- export function extractFastApiEndpoints(filePath) {
24
- const content = readFileSync(filePath, 'utf8')
25
- const lines = content.split('\n')
26
- const endpoints = []
27
-
28
- // 1. 提取 router prefix
29
- let routerPrefix = ''
30
- for (const line of lines) {
31
- const prefixMatch = line.match(/(?:APIRouter|router)\s*\(\s*(?:prefix\s*=\s*)?["'`]([^"'`]+)["'`]/)
32
- || line.match(/\.include_router\s*\([^)]*prefix\s*=\s*["'`]([^"'`]+)["'`]/)
33
- if (prefixMatch) {
34
- routerPrefix = prefixMatch[1]
35
- }
36
- }
37
-
38
- // 2. 提取 @router.method("/path") 或分散式定义
39
- // FastAPI 支持两种写法:
40
- // a) @router.get("/path", ...) 下一行 def func():
41
- // b) @router.get 下一行 ("/path", ...)
42
- for (let i = 0; i < lines.length; i++) {
43
- const line = lines[i]
44
- const decoratorMatch = line.match(
45
- /@(?:router|api_router)\.(get|post|put|delete|patch)\s*\(\s*["'`]([^"'`]+)["'`]/
46
- )
47
- if (decoratorMatch) {
48
- const method = decoratorMatch[1].toUpperCase()
49
- const rawPath = decoratorMatch[2]
50
- endpoints.push({
51
- method,
52
- path: routerPrefix + rawPath,
53
- source: filePath,
54
- line: i + 1,
55
- })
56
- continue
57
- }
58
- // 分散式: @router.get\n ("/path",
59
- const splitMatch = line.match(/@(?:router|api_router)\.(get|post|put|delete|patch)\s*$/)
60
- if (splitMatch && i + 1 < lines.length) {
61
- const nextLine = lines[i + 1]
62
- const pathMatch = nextLine.match(/\(\s*["'`]([^"'`]+)["'`]/)
63
- if (pathMatch) {
64
- endpoints.push({
65
- method: splitMatch[1].toUpperCase(),
66
- path: routerPrefix + pathMatch[1],
67
- source: filePath,
68
- line: i + 1,
69
- })
70
- }
71
- }
72
- }
73
-
74
- return endpoints
75
- }
76
-
77
- /**
78
- * 从单个文件提取 Express(Node)路由端点。
79
- * 支持 router/app.get|post|put|delete|patch("path") 与链式 router.route("path").<method>()。
80
- * app.use("prefix", router) 的前缀只做同文件近似(跨文件追踪不在首版范围)。
81
- *
82
- * @param {string} filePath - 文件绝对路径
83
- * @returns {Array<{ method: string, path: string, source: string, line: number }>}
84
- */
85
- export function extractExpressEndpoints(filePath) {
86
- const content = readFileSync(filePath, 'utf8')
87
- const lines = content.split('\n')
88
- const endpoints = []
89
-
90
- // 同文件内最后一个 app.use("prefix", ...) 作为前缀近似
91
- let routerPrefix = ''
92
- for (const line of lines) {
93
- const useMatch = line.match(/\bapp\.use\s*\(\s*["'`]([^"'`]+)["'`]/)
94
- if (useMatch) routerPrefix = useMatch[1]
95
- }
96
-
97
- for (let i = 0; i < lines.length; i++) {
98
- const line = lines[i]
99
- const m = line.match(/\b(?:app|router)\.(get|post|put|delete|patch)\s*\(\s*["'`]([^"'`]+)["'`]/i)
100
- if (m) {
101
- endpoints.push({ method: m[1].toUpperCase(), path: routerPrefix + m[2], source: filePath, line: i + 1 })
102
- continue
103
- }
104
- const routeChain = line.match(/\.route\s*\(\s*["'`]([^"'`]+)["'`]/)
105
- if (routeChain) {
106
- // 链式 .route(path).get(h).put(h) —— 同行所有 method 配上 path
107
- const chainPath = routerPrefix + routeChain[1]
108
- for (const mm of line.matchAll(/\.(get|post|put|delete|patch)\s*\(/gi)) {
109
- endpoints.push({ method: mm[1].toUpperCase(), path: chainPath, source: filePath, line: i + 1 })
110
- }
111
- }
112
- }
113
-
114
- return endpoints
115
- }
116
-
117
- /**
118
- * 从单个文件提取 Spring(Java)端点。
119
- * 支持 @GetMapping/@PostMapping/.../@PatchMapping 与旧式 @RequestMapping(value="path", method=RequestMethod.X);
120
- * 类级 @RequestMapping("api") 前缀合并(取文件内第一个作类前缀,近似)。
121
- *
122
- * @param {string} filePath - 文件绝对路径
123
- * @returns {Array<{ method: string, path: string, source: string, line: number }>}
124
- */
125
- export function extractSpringEndpoints(filePath) {
126
- const content = readFileSync(filePath, 'utf8')
127
- const lines = content.split('\n')
128
- const endpoints = []
129
-
130
- let classPrefix = ''
131
- for (const line of lines) {
132
- const cm = line.match(/@RequestMapping\s*\(\s*(?:value\s*=\s*)?["'`]([^"'`]+)["'`]/)
133
- if (cm) { classPrefix = cm[1]; break }
134
- }
135
-
136
- const methodMap = { get: 'GET', post: 'POST', put: 'PUT', delete: 'DELETE', patch: 'PATCH' }
137
-
138
- for (let i = 0; i < lines.length; i++) {
139
- const line = lines[i]
140
- const shortMatch = line.match(/@(Get|Post|Put|Delete|Patch)Mapping\s*\(\s*(?:value\s*=\s*)?["'`]([^"'`]+)["'`]/i)
141
- if (shortMatch) {
142
- endpoints.push({ method: methodMap[shortMatch[1].toLowerCase()], path: classPrefix + shortMatch[2], source: filePath, line: i + 1 })
143
- continue
144
- }
145
- const oldMatch = line.match(/@RequestMapping\s*\(\s*(?:value\s*=\s*)?["'`]([^"'`]+)["'`][^)]*?method\s*=\s*RequestMethod\.(\w+)/i)
146
- if (oldMatch) {
147
- endpoints.push({ method: oldMatch[2].toUpperCase(), path: classPrefix + oldMatch[1], source: filePath, line: i + 1 })
148
- }
149
- }
150
-
151
- return endpoints
152
- }
153
-
154
- /**
155
- * 从目录递归扫描后端端点(多框架)。
156
- * 按扩展名分派:.py→FastAPI / .js,.ts→Express / .java→Spring。
157
- * 保留 excludePatterns(向后兼容 opts);filePattern 在多框架分派下不再适用。
158
- * @param {string} dir
159
- * @param {{ excludePatterns?: RegExp[] }} opts
160
- * @returns {Array<{ method: string, path: string, source: string, line: number }>}
161
- */
162
- export function scanBackendEndpoints(dir, opts = {}) {
163
- const excludePatterns = opts.excludePatterns || [
164
- /^__pycache__$/, /^node_modules$/, /^\.venv$/, /^\.git$/, /^\.gradle$/,
165
- /^(dist|build|target|out)$/i,
166
- /test/i,
167
- ]
168
-
169
- const results = []
170
- if (!existsSync(dir)) return results
171
-
172
- function walk(d) {
173
- for (const entry of readdirSync(d, { withFileTypes: true })) {
174
- const full = join(d, entry.name)
175
- if (entry.isDirectory()) {
176
- if (excludePatterns.some(p => p.test(entry.name))) continue
177
- walk(full)
178
- } else if (entry.isFile()) {
179
- const ext = extname(entry.name).toLowerCase()
180
- try {
181
- if (ext === '.py') results.push(...extractFastApiEndpoints(full))
182
- else if (ext === '.js' || ext === '.ts') results.push(...extractExpressEndpoints(full))
183
- else if (ext === '.java') results.push(...extractSpringEndpoints(full))
184
- } catch {}
185
- }
186
- }
187
- }
188
- walk(dir)
189
- return results
190
- }
191
-
192
- // ─── Consumer: 扫描前端 API 调用路径 ─────────────────────────────────────
193
-
194
- /**
195
- * 从前端文件提取 API 调用路径
196
- * 支持:
197
- * apiFetch("/api/xxx")
198
- * request("/api/xxx")
199
- * axios.get("/api/xxx")
200
- * axios.post("/api/xxx")
201
- * fetch("/api/xxx")
202
- *
203
- * @param {string} filePath
204
- * @returns {Array<{ method: string, path: string, source: string, line: number, raw: string }>}
205
- */
206
- export function extractFrontendApiCalls(filePath) {
207
- const content = readFileSync(filePath, 'utf8')
208
- const lines = content.split('\n')
209
- const results = []
210
-
211
- for (let i = 0; i < lines.length; i++) {
212
- const line = lines[i]
213
-
214
- // Pattern 1: apiFetch<T>("/path", { method: "POST" }) — default GET
215
- const apiFetchMatch = line.match(/apiFetch\s*(?:<[^>]*>)?\s*\(\s*["'`]([^"'`]+)["'`]/)
216
- if (apiFetchMatch) {
217
- // 检查是否有 method 字段(在后续行或同一行)
218
- let method = 'GET'
219
- const snippet = lines.slice(i, Math.min(i + 3, lines.length)).join(' ')
220
- const methodMatch = snippet.match(/method\s*:\s*["'`](GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS)["'`]/i)
221
- if (methodMatch) method = methodMatch[1].toUpperCase()
222
-
223
- results.push({
224
- method,
225
- path: normalizePath(apiFetchMatch[1]),
226
- source: filePath,
227
- line: i + 1,
228
- raw: apiFetchMatch[1],
229
- })
230
- continue
231
- }
232
-
233
- // Pattern 2: axios.get/post/put/delete("/path")
234
- const axiosMatch = line.match(/axios\.(get|post|put|delete|patch)\s*\(\s*["'`]([^"'`]+)["'`]/i)
235
- if (axiosMatch) {
236
- results.push({
237
- method: axiosMatch[1].toUpperCase(),
238
- path: normalizePath(axiosMatch[2]),
239
- source: filePath,
240
- line: i + 1,
241
- raw: axiosMatch[2],
242
- })
243
- continue
244
- }
245
-
246
- // Pattern 3: fetch("/api/xxx", { method: "POST" })
247
- const fetchMatch = line.match(/(?:api_?)?fetch\s*\(\s*["'`]([^"'`]+)["'`]/)
248
- if (fetchMatch && !apiFetchMatch) {
249
- let method = 'GET'
250
- const snippet = lines.slice(i, Math.min(i + 3, lines.length)).join(' ')
251
- const methodMatch = snippet.match(/method\s*:\s*["'`](GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS)["'`]/i)
252
- if (methodMatch) method = methodMatch[1].toUpperCase()
253
-
254
- results.push({
255
- method,
256
- path: normalizePath(fetchMatch[1]),
257
- source: filePath,
258
- line: i + 1,
259
- raw: fetchMatch[1],
260
- })
261
- continue
262
- }
263
- }
264
-
265
- return results
266
- }
267
-
268
- /**
269
- * 递归扫描前端目录的 API 调用
270
- * @param {string} dir
271
- * @param {{ filePattern?: RegExp, excludePatterns?: RegExp[] }} opts
272
- * @returns {Array<{ method: string, path: string, source: string, line: number, raw: string }>}
273
- */
274
- export function scanFrontendApiCalls(dir, opts = {}) {
275
- const filePattern = opts.filePattern || /\.(ts|tsx|js|jsx)$/
276
- const excludePatterns = opts.excludePatterns || [/node_modules/, /\.next/, /dist/, /__tests__/, /\.d\.ts$/]
277
-
278
- const results = []
279
- if (!existsSync(dir)) return results
280
-
281
- function walk(d) {
282
- for (const entry of readdirSync(d, { withFileTypes: true })) {
283
- const full = join(d, entry.name)
284
- if (entry.isDirectory()) {
285
- if (excludePatterns.some(p => p.test(entry.name))) continue
286
- walk(full)
287
- } else if (entry.isFile() && filePattern.test(entry.name)) {
288
- try {
289
- results.push(...extractFrontendApiCalls(full))
290
- } catch {}
291
- }
292
- }
293
- }
294
- walk(dir)
295
- return results
296
- }
297
-
298
- // ─── 路径归一化 ─────────────────────────────────────────────────────────
299
-
300
- /**
301
- * 将动态路径归一化为参数占位符
302
- * /api/ppm/project-plan/${id}/plan-nodes → /api/ppm/project-plan/{param}/plan-nodes
303
- * /api/ppm/project-plan/:planId/plan-nodes → /api/ppm/project-plan/{param}/plan-nodes
304
- * @param {string} rawPath
305
- * @returns {string}
306
- */
307
- export function normalizePath(rawPath) {
308
- return rawPath
309
- .replace(/\$\{[^}]+\}/g, '{param}')
310
- .replace(/:\w+/g, '{param}')
311
- .replace(/\$\w+/g, '{param}')
312
- .replace(/\{[^}]+\}/g, '{param}') // Spring {planId} / FastAPI {plan_id} → {param}
313
- }
314
-
315
- // ─── 对账 ───────────────────────────────────────────────────────────────
316
-
317
- /**
318
- * 比较前端调用的路径和后端注册的端点,返回差异
319
- *
320
- * @param {Array<{ path: string, method: string, source: string }>} frontendCalls
321
- * @param {Array<{ path: string, method: string, source: string }>} backendEndpoints
322
- * @returns {{
323
- * missingBackend: Array<{ path: string, method: string, consumerFile: string, consumerLine: number }>,
324
- * unusedBackend: Array<{ path: string, method: string, providerFile: string }>
325
- * }}
326
- */
327
- export function diffApiParity(frontendCalls, backendEndpoints) {
328
- // 构建 backend 注册表:归一化 path + method → endpoint
329
- const backendMap = new Map()
330
- for (const ep of backendEndpoints) {
331
- const key = `${ep.method}:${normalizePath(ep.path)}`
332
- if (!backendMap.has(key)) backendMap.set(key, ep)
333
- }
334
-
335
- const missingBackend = []
336
- for (const call of frontendCalls) {
337
- const key = `${call.method}:${normalizePath(call.path)}`
338
- if (!backendMap.has(key)) {
339
- missingBackend.push({
340
- path: normalizePath(call.path),
341
- method: call.method,
342
- consumerFile: call.source,
343
- consumerLine: call.line,
344
- })
345
- }
346
- }
347
-
348
- // 构建 frontend 调用表
349
- const frontendSet = new Set(
350
- frontendCalls.map(c => `${c.method}:${normalizePath(c.path)}`)
351
- )
352
-
353
- const unusedBackend = []
354
- for (const ep of backendEndpoints) {
355
- const key = `${ep.method}:${normalizePath(ep.path)}`
356
- if (!frontendSet.has(key)) {
357
- unusedBackend.push({
358
- path: normalizePath(ep.path),
359
- method: ep.method,
360
- providerFile: ep.source,
361
- })
362
- }
363
- }
364
-
365
- return { missingBackend, unusedBackend, ok: missingBackend.length === 0 }
366
- }
367
-
368
- // ─── CLI 入口 ────────────────────────────────────────────────────────────
369
-
370
- /**
371
- * CLI 子命令入口:sillyspec contract scan [--backend dir] [--frontend dir]
372
- * 输出 JSON 格式的端点清单和对账结果
373
- */
374
- export async function contractScan(args, cwd) {
375
- const backendIdx = args.indexOf('--backend')
376
- const frontendIdx = args.indexOf('--frontend')
377
- const backendDir = backendIdx !== -1 && args[backendIdx + 1]
378
- ? resolve(cwd, args[backendIdx + 1])
379
- : resolve(cwd, 'backend')
380
- const frontendDir = frontendIdx !== -1 && args[frontendIdx + 1]
381
- ? resolve(cwd, args[frontendIdx + 1])
382
- : resolve(cwd, 'frontend')
383
-
384
- const backendEndpoints = scanBackendEndpoints(backendDir)
385
- const frontendCalls = scanFrontendApiCalls(frontendDir)
386
- const { missingBackend, unusedBackend } = diffApiParity(frontendCalls, backendEndpoints)
387
-
388
- return {
389
- backend: backendEndpoints.map(e => ({ method: e.method, path: normalizePath(e.path), file: e.source })),
390
- frontend: frontendCalls.map(c => ({ method: c.method, path: normalizePath(c.path), file: c.source })),
391
- missingBackend,
392
- unusedBackend,
393
- summary: {
394
- backendEndpointCount: backendEndpoints.length,
395
- frontendCallCount: frontendCalls.length,
396
- missingBackendCount: missingBackend.length,
397
- unusedBackendCount: unusedBackend.length,
398
- ok: missingBackend.length === 0,
399
- },
400
- }
401
- }
1
+ /**
2
+ * endpoint-extractor.js — 从代码中提取 HTTP 端点定义和调用
3
+ *
4
+ * provider 端:扫描 router 文件,提取注册的 API 路径
5
+ * consumer 端:扫描前端文件,提取 apiFetch/request 调用路径
6
+ *
7
+ * 契约对账时:provider 产出 ≠ consumer 消费 → gap
8
+ */
9
+
10
+ import { existsSync, readFileSync, readdirSync, statSync } from 'fs'
11
+ import { join, extname, basename, dirname, resolve } from 'path'
12
+ import { execSync } from 'child_process'
13
+
14
+ // ─── Provider: 扫描后端 router 注册的端点 ───────────────────────────────
15
+
16
+ /**
17
+ * 从单个文件提取 FastAPI router 端点
18
+ * 支持 APIRouter(prefix=...) 和 @router.get/post/put/delete/patch("/path")
19
+ *
20
+ * @param {string} filePath - 文件绝对路径
21
+ * @returns {Array<{ method: string, path: string, source: string, line: number }>}
22
+ */
23
+ export function extractFastApiEndpoints(filePath) {
24
+ const content = readFileSync(filePath, 'utf8')
25
+ const lines = content.split('\n')
26
+ const endpoints = []
27
+
28
+ // 1. 提取 router prefix
29
+ let routerPrefix = ''
30
+ for (const line of lines) {
31
+ const prefixMatch = line.match(/(?:APIRouter|router)\s*\(\s*(?:prefix\s*=\s*)?["'`]([^"'`]+)["'`]/)
32
+ || line.match(/\.include_router\s*\([^)]*prefix\s*=\s*["'`]([^"'`]+)["'`]/)
33
+ if (prefixMatch) {
34
+ routerPrefix = prefixMatch[1]
35
+ }
36
+ }
37
+
38
+ // 2. 提取 @router.method("/path") 或分散式定义
39
+ // FastAPI 支持两种写法:
40
+ // a) @router.get("/path", ...) 下一行 def func():
41
+ // b) @router.get 下一行 ("/path", ...)
42
+ for (let i = 0; i < lines.length; i++) {
43
+ const line = lines[i]
44
+ const decoratorMatch = line.match(
45
+ /@(?:router|api_router)\.(get|post|put|delete|patch)\s*\(\s*["'`]([^"'`]+)["'`]/
46
+ )
47
+ if (decoratorMatch) {
48
+ const method = decoratorMatch[1].toUpperCase()
49
+ const rawPath = decoratorMatch[2]
50
+ endpoints.push({
51
+ method,
52
+ path: routerPrefix + rawPath,
53
+ source: filePath,
54
+ line: i + 1,
55
+ })
56
+ continue
57
+ }
58
+ // 分散式: @router.get\n ("/path",
59
+ const splitMatch = line.match(/@(?:router|api_router)\.(get|post|put|delete|patch)\s*$/)
60
+ if (splitMatch && i + 1 < lines.length) {
61
+ const nextLine = lines[i + 1]
62
+ const pathMatch = nextLine.match(/\(\s*["'`]([^"'`]+)["'`]/)
63
+ if (pathMatch) {
64
+ endpoints.push({
65
+ method: splitMatch[1].toUpperCase(),
66
+ path: routerPrefix + pathMatch[1],
67
+ source: filePath,
68
+ line: i + 1,
69
+ })
70
+ }
71
+ }
72
+ }
73
+
74
+ return endpoints
75
+ }
76
+
77
+ /**
78
+ * 从单个文件提取 Express(Node)路由端点。
79
+ * 支持 router/app.get|post|put|delete|patch("path") 与链式 router.route("path").<method>()。
80
+ * app.use("prefix", router) 的前缀只做同文件近似(跨文件追踪不在首版范围)。
81
+ *
82
+ * @param {string} filePath - 文件绝对路径
83
+ * @returns {Array<{ method: string, path: string, source: string, line: number }>}
84
+ */
85
+ export function extractExpressEndpoints(filePath) {
86
+ const content = readFileSync(filePath, 'utf8')
87
+ const lines = content.split('\n')
88
+ const endpoints = []
89
+
90
+ // 同文件内最后一个 app.use("prefix", ...) 作为前缀近似
91
+ let routerPrefix = ''
92
+ for (const line of lines) {
93
+ const useMatch = line.match(/\bapp\.use\s*\(\s*["'`]([^"'`]+)["'`]/)
94
+ if (useMatch) routerPrefix = useMatch[1]
95
+ }
96
+
97
+ for (let i = 0; i < lines.length; i++) {
98
+ const line = lines[i]
99
+ const m = line.match(/\b(?:app|router)\.(get|post|put|delete|patch)\s*\(\s*["'`]([^"'`]+)["'`]/i)
100
+ if (m) {
101
+ endpoints.push({ method: m[1].toUpperCase(), path: routerPrefix + m[2], source: filePath, line: i + 1 })
102
+ continue
103
+ }
104
+ const routeChain = line.match(/\.route\s*\(\s*["'`]([^"'`]+)["'`]/)
105
+ if (routeChain) {
106
+ // 链式 .route(path).get(h).put(h) —— 同行所有 method 配上 path
107
+ const chainPath = routerPrefix + routeChain[1]
108
+ for (const mm of line.matchAll(/\.(get|post|put|delete|patch)\s*\(/gi)) {
109
+ endpoints.push({ method: mm[1].toUpperCase(), path: chainPath, source: filePath, line: i + 1 })
110
+ }
111
+ }
112
+ }
113
+
114
+ return endpoints
115
+ }
116
+
117
+ /**
118
+ * 从单个文件提取 Spring(Java)端点。
119
+ * 支持 @GetMapping/@PostMapping/.../@PatchMapping 与旧式 @RequestMapping(value="path", method=RequestMethod.X);
120
+ * 类级 @RequestMapping("api") 前缀合并(取文件内第一个作类前缀,近似)。
121
+ *
122
+ * @param {string} filePath - 文件绝对路径
123
+ * @returns {Array<{ method: string, path: string, source: string, line: number }>}
124
+ */
125
+ export function extractSpringEndpoints(filePath) {
126
+ const content = readFileSync(filePath, 'utf8')
127
+ const lines = content.split('\n')
128
+ const endpoints = []
129
+
130
+ let classPrefix = ''
131
+ for (const line of lines) {
132
+ const cm = line.match(/@RequestMapping\s*\(\s*(?:value\s*=\s*)?["'`]([^"'`]+)["'`]/)
133
+ if (cm) { classPrefix = cm[1]; break }
134
+ }
135
+
136
+ const methodMap = { get: 'GET', post: 'POST', put: 'PUT', delete: 'DELETE', patch: 'PATCH' }
137
+
138
+ for (let i = 0; i < lines.length; i++) {
139
+ const line = lines[i]
140
+ const shortMatch = line.match(/@(Get|Post|Put|Delete|Patch)Mapping\s*\(\s*(?:value\s*=\s*)?["'`]([^"'`]+)["'`]/i)
141
+ if (shortMatch) {
142
+ endpoints.push({ method: methodMap[shortMatch[1].toLowerCase()], path: classPrefix + shortMatch[2], source: filePath, line: i + 1 })
143
+ continue
144
+ }
145
+ const oldMatch = line.match(/@RequestMapping\s*\(\s*(?:value\s*=\s*)?["'`]([^"'`]+)["'`][^)]*?method\s*=\s*RequestMethod\.(\w+)/i)
146
+ if (oldMatch) {
147
+ endpoints.push({ method: oldMatch[2].toUpperCase(), path: classPrefix + oldMatch[1], source: filePath, line: i + 1 })
148
+ }
149
+ }
150
+
151
+ return endpoints
152
+ }
153
+
154
+ /**
155
+ * 从目录递归扫描后端端点(多框架)。
156
+ * 按扩展名分派:.py→FastAPI / .js,.ts→Express / .java→Spring。
157
+ * 保留 excludePatterns(向后兼容 opts);filePattern 在多框架分派下不再适用。
158
+ * @param {string} dir
159
+ * @param {{ excludePatterns?: RegExp[] }} opts
160
+ * @returns {Array<{ method: string, path: string, source: string, line: number }>}
161
+ */
162
+ export function scanBackendEndpoints(dir, opts = {}) {
163
+ const excludePatterns = opts.excludePatterns || [
164
+ /^__pycache__$/, /^node_modules$/, /^\.venv$/, /^\.git$/, /^\.gradle$/,
165
+ /^(dist|build|target|out)$/i,
166
+ /test/i,
167
+ ]
168
+
169
+ const results = []
170
+ if (!existsSync(dir)) return results
171
+
172
+ function walk(d) {
173
+ for (const entry of readdirSync(d, { withFileTypes: true })) {
174
+ const full = join(d, entry.name)
175
+ if (entry.isDirectory()) {
176
+ if (excludePatterns.some(p => p.test(entry.name))) continue
177
+ walk(full)
178
+ } else if (entry.isFile()) {
179
+ const ext = extname(entry.name).toLowerCase()
180
+ try {
181
+ if (ext === '.py') results.push(...extractFastApiEndpoints(full))
182
+ else if (ext === '.js' || ext === '.ts') results.push(...extractExpressEndpoints(full))
183
+ else if (ext === '.java') results.push(...extractSpringEndpoints(full))
184
+ } catch {}
185
+ }
186
+ }
187
+ }
188
+ walk(dir)
189
+ return results
190
+ }
191
+
192
+ // ─── Consumer: 扫描前端 API 调用路径 ─────────────────────────────────────
193
+
194
+ /**
195
+ * 从前端文件提取 API 调用路径
196
+ * 支持:
197
+ * apiFetch("/api/xxx")
198
+ * request("/api/xxx")
199
+ * axios.get("/api/xxx")
200
+ * axios.post("/api/xxx")
201
+ * fetch("/api/xxx")
202
+ *
203
+ * @param {string} filePath
204
+ * @returns {Array<{ method: string, path: string, source: string, line: number, raw: string }>}
205
+ */
206
+ export function extractFrontendApiCalls(filePath) {
207
+ const content = readFileSync(filePath, 'utf8')
208
+ const lines = content.split('\n')
209
+ const results = []
210
+
211
+ for (let i = 0; i < lines.length; i++) {
212
+ const line = lines[i]
213
+
214
+ // Pattern 1: apiFetch<T>("/path", { method: "POST" }) — default GET
215
+ const apiFetchMatch = line.match(/apiFetch\s*(?:<[^>]*>)?\s*\(\s*["'`]([^"'`]+)["'`]/)
216
+ if (apiFetchMatch) {
217
+ // 检查是否有 method 字段(在后续行或同一行)
218
+ let method = 'GET'
219
+ const snippet = lines.slice(i, Math.min(i + 3, lines.length)).join(' ')
220
+ const methodMatch = snippet.match(/method\s*:\s*["'`](GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS)["'`]/i)
221
+ if (methodMatch) method = methodMatch[1].toUpperCase()
222
+
223
+ results.push({
224
+ method,
225
+ path: normalizePath(apiFetchMatch[1]),
226
+ source: filePath,
227
+ line: i + 1,
228
+ raw: apiFetchMatch[1],
229
+ })
230
+ continue
231
+ }
232
+
233
+ // Pattern 2: axios.get/post/put/delete("/path")
234
+ const axiosMatch = line.match(/axios\.(get|post|put|delete|patch)\s*\(\s*["'`]([^"'`]+)["'`]/i)
235
+ if (axiosMatch) {
236
+ results.push({
237
+ method: axiosMatch[1].toUpperCase(),
238
+ path: normalizePath(axiosMatch[2]),
239
+ source: filePath,
240
+ line: i + 1,
241
+ raw: axiosMatch[2],
242
+ })
243
+ continue
244
+ }
245
+
246
+ // Pattern 3: fetch("/api/xxx", { method: "POST" })
247
+ const fetchMatch = line.match(/(?:api_?)?fetch\s*\(\s*["'`]([^"'`]+)["'`]/)
248
+ if (fetchMatch && !apiFetchMatch) {
249
+ let method = 'GET'
250
+ const snippet = lines.slice(i, Math.min(i + 3, lines.length)).join(' ')
251
+ const methodMatch = snippet.match(/method\s*:\s*["'`](GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS)["'`]/i)
252
+ if (methodMatch) method = methodMatch[1].toUpperCase()
253
+
254
+ results.push({
255
+ method,
256
+ path: normalizePath(fetchMatch[1]),
257
+ source: filePath,
258
+ line: i + 1,
259
+ raw: fetchMatch[1],
260
+ })
261
+ continue
262
+ }
263
+ }
264
+
265
+ return results
266
+ }
267
+
268
+ /**
269
+ * 递归扫描前端目录的 API 调用
270
+ * @param {string} dir
271
+ * @param {{ filePattern?: RegExp, excludePatterns?: RegExp[] }} opts
272
+ * @returns {Array<{ method: string, path: string, source: string, line: number, raw: string }>}
273
+ */
274
+ export function scanFrontendApiCalls(dir, opts = {}) {
275
+ const filePattern = opts.filePattern || /\.(ts|tsx|js|jsx)$/
276
+ const excludePatterns = opts.excludePatterns || [/node_modules/, /\.next/, /dist/, /__tests__/, /\.d\.ts$/]
277
+
278
+ const results = []
279
+ if (!existsSync(dir)) return results
280
+
281
+ function walk(d) {
282
+ for (const entry of readdirSync(d, { withFileTypes: true })) {
283
+ const full = join(d, entry.name)
284
+ if (entry.isDirectory()) {
285
+ if (excludePatterns.some(p => p.test(entry.name))) continue
286
+ walk(full)
287
+ } else if (entry.isFile() && filePattern.test(entry.name)) {
288
+ try {
289
+ results.push(...extractFrontendApiCalls(full))
290
+ } catch {}
291
+ }
292
+ }
293
+ }
294
+ walk(dir)
295
+ return results
296
+ }
297
+
298
+ // ─── 路径归一化 ─────────────────────────────────────────────────────────
299
+
300
+ /**
301
+ * 将动态路径归一化为参数占位符
302
+ * /api/ppm/project-plan/${id}/plan-nodes → /api/ppm/project-plan/{param}/plan-nodes
303
+ * /api/ppm/project-plan/:planId/plan-nodes → /api/ppm/project-plan/{param}/plan-nodes
304
+ * @param {string} rawPath
305
+ * @returns {string}
306
+ */
307
+ export function normalizePath(rawPath) {
308
+ return rawPath
309
+ .replace(/\$\{[^}]+\}/g, '{param}')
310
+ .replace(/:\w+/g, '{param}')
311
+ .replace(/\$\w+/g, '{param}')
312
+ .replace(/\{[^}]+\}/g, '{param}') // Spring {planId} / FastAPI {plan_id} → {param}
313
+ }
314
+
315
+ // ─── 对账 ───────────────────────────────────────────────────────────────
316
+
317
+ /**
318
+ * 比较前端调用的路径和后端注册的端点,返回差异
319
+ *
320
+ * @param {Array<{ path: string, method: string, source: string }>} frontendCalls
321
+ * @param {Array<{ path: string, method: string, source: string }>} backendEndpoints
322
+ * @returns {{
323
+ * missingBackend: Array<{ path: string, method: string, consumerFile: string, consumerLine: number }>,
324
+ * unusedBackend: Array<{ path: string, method: string, providerFile: string }>
325
+ * }}
326
+ */
327
+ export function diffApiParity(frontendCalls, backendEndpoints) {
328
+ // 构建 backend 注册表:归一化 path + method → endpoint
329
+ const backendMap = new Map()
330
+ for (const ep of backendEndpoints) {
331
+ const key = `${ep.method}:${normalizePath(ep.path)}`
332
+ if (!backendMap.has(key)) backendMap.set(key, ep)
333
+ }
334
+
335
+ const missingBackend = []
336
+ for (const call of frontendCalls) {
337
+ const key = `${call.method}:${normalizePath(call.path)}`
338
+ if (!backendMap.has(key)) {
339
+ missingBackend.push({
340
+ path: normalizePath(call.path),
341
+ method: call.method,
342
+ consumerFile: call.source,
343
+ consumerLine: call.line,
344
+ })
345
+ }
346
+ }
347
+
348
+ // 构建 frontend 调用表
349
+ const frontendSet = new Set(
350
+ frontendCalls.map(c => `${c.method}:${normalizePath(c.path)}`)
351
+ )
352
+
353
+ const unusedBackend = []
354
+ for (const ep of backendEndpoints) {
355
+ const key = `${ep.method}:${normalizePath(ep.path)}`
356
+ if (!frontendSet.has(key)) {
357
+ unusedBackend.push({
358
+ path: normalizePath(ep.path),
359
+ method: ep.method,
360
+ providerFile: ep.source,
361
+ })
362
+ }
363
+ }
364
+
365
+ return { missingBackend, unusedBackend, ok: missingBackend.length === 0 }
366
+ }
367
+
368
+ // ─── CLI 入口 ────────────────────────────────────────────────────────────
369
+
370
+ /**
371
+ * CLI 子命令入口:sillyspec contract scan [--backend dir] [--frontend dir]
372
+ * 输出 JSON 格式的端点清单和对账结果
373
+ */
374
+ export async function contractScan(args, cwd) {
375
+ const backendIdx = args.indexOf('--backend')
376
+ const frontendIdx = args.indexOf('--frontend')
377
+ const backendDir = backendIdx !== -1 && args[backendIdx + 1]
378
+ ? resolve(cwd, args[backendIdx + 1])
379
+ : resolve(cwd, 'backend')
380
+ const frontendDir = frontendIdx !== -1 && args[frontendIdx + 1]
381
+ ? resolve(cwd, args[frontendIdx + 1])
382
+ : resolve(cwd, 'frontend')
383
+
384
+ const backendEndpoints = scanBackendEndpoints(backendDir)
385
+ const frontendCalls = scanFrontendApiCalls(frontendDir)
386
+ const { missingBackend, unusedBackend } = diffApiParity(frontendCalls, backendEndpoints)
387
+
388
+ return {
389
+ backend: backendEndpoints.map(e => ({ method: e.method, path: normalizePath(e.path), file: e.source })),
390
+ frontend: frontendCalls.map(c => ({ method: c.method, path: normalizePath(c.path), file: c.source })),
391
+ missingBackend,
392
+ unusedBackend,
393
+ summary: {
394
+ backendEndpointCount: backendEndpoints.length,
395
+ frontendCallCount: frontendCalls.length,
396
+ missingBackendCount: missingBackend.length,
397
+ unusedBackendCount: unusedBackend.length,
398
+ ok: missingBackend.length === 0,
399
+ },
400
+ }
401
+ }