sillyspec 3.16.2 → 3.17.1

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/run.js CHANGED
@@ -4,9 +4,21 @@
4
4
  * CLI 成为流程引擎,AI 变成步骤执行器。
5
5
  * 支持多变更并行:每个变更状态存储在 sillyspec.db 中。
6
6
  */
7
- import { basename, join } from 'path'
7
+ import { basename, join, resolve } from 'path'
8
8
  import { existsSync, readdirSync, mkdirSync, writeFileSync, appendFileSync, readFileSync, statSync } from 'fs'
9
9
  import { ProgressManager } from './progress.js'
10
+
11
+ /**
12
+ * 解析规范目录路径
13
+ * @param {string} cwd - 项目根目录
14
+ * @param {object} [opts]
15
+ * @param {string} [opts.specDir] - 用户指定的 specDir(通过 --spec-dir 或 --spec-root)
16
+ * @returns {string} 规范目录的绝对路径
17
+ */
18
+ function resolveSpecDir(cwd, opts = {}) {
19
+ if (opts.specDir) return resolve(opts.specDir)
20
+ return join(cwd, '.sillyspec')
21
+ }
10
22
  import { stageRegistry, auxiliaryStages } from './stages/index.js'
11
23
  import { checkTransition, runValidators } from './stage-contract.js'
12
24
  import { buildExecuteSteps } from './stages/execute.js'
@@ -155,8 +167,8 @@ async function checkApproval(cwd, changeName) {
155
167
  /**
156
168
  * 统一查找变更目录(与 progress.js 的变更检测逻辑一致)
157
169
  */
158
- function resolveChangeDir(cwd, progress) {
159
- const changesDir = join(cwd, '.sillyspec', 'changes')
170
+ function resolveChangeDir(cwd, progress, specDir = null) {
171
+ const changesDir = join(specDir || resolveSpecDir(cwd), 'changes')
160
172
  if (!existsSync(changesDir)) return null
161
173
 
162
174
  // 1. 优先用 currentChange
@@ -177,9 +189,9 @@ function resolveChangeDir(cwd, progress) {
177
189
  * 自动探测并设置 currentChange(唯一变更目录时)
178
190
  * @returns {boolean} 是否设置了 currentChange
179
191
  */
180
- function autoDetectChange(progress, cwd) {
192
+ function autoDetectChange(progress, cwd, specDir = null) {
181
193
  if (progress.currentChange) return false
182
- const changesDir = join(cwd, '.sillyspec', 'changes')
194
+ const changesDir = join(specDir || resolveSpecDir(cwd), 'changes')
183
195
  if (!existsSync(changesDir)) return false
184
196
  const entries = readdirSync(changesDir, { withFileTypes: true })
185
197
  .filter(e => e.isDirectory() && e.name !== 'archive')
@@ -193,9 +205,9 @@ function autoDetectChange(progress, cwd) {
193
205
  /**
194
206
  * 从 progress 或变更目录推导变更名
195
207
  */
196
- function resolveChangeName(cwd, progress) {
208
+ function resolveChangeName(cwd, progress, specDir = null) {
197
209
  if (progress.currentChange) return progress.currentChange
198
- const changesDir = join(cwd, '.sillyspec', 'changes')
210
+ const changesDir = join(specDir || resolveSpecDir(cwd), 'changes')
199
211
  if (!existsSync(changesDir)) return null
200
212
  const entries = readdirSync(changesDir, { withFileTypes: true })
201
213
  .filter(e => e.isDirectory() && e.name !== 'archive')
@@ -206,9 +218,9 @@ function resolveChangeName(cwd, progress) {
206
218
  /**
207
219
  * 获取阶段的步骤定义(execute 需要动态构建)
208
220
  */
209
- async function getStageSteps(stageName, cwd, progress) {
221
+ async function getStageSteps(stageName, cwd, progress, specDir = null) {
210
222
  if (stageName === 'execute') {
211
- const changeDir = resolveChangeDir(cwd, progress)
223
+ const changeDir = resolveChangeDir(cwd, progress, specDir)
212
224
  let planFile = null
213
225
  if (changeDir) {
214
226
  const p = join(changeDir, 'plan.md')
@@ -217,7 +229,7 @@ async function getStageSteps(stageName, cwd, progress) {
217
229
  return buildExecuteSteps(planFile)
218
230
  }
219
231
  if (stageName === 'plan') {
220
- const changeDir = resolveChangeDir(cwd, progress)
232
+ const changeDir = resolveChangeDir(cwd, progress, specDir)
221
233
  return buildPlanSteps(changeDir)
222
234
  }
223
235
  const def = stageRegistry[stageName]
@@ -227,10 +239,10 @@ async function getStageSteps(stageName, cwd, progress) {
227
239
  /**
228
240
  * 确保阶段的 steps 已初始化到 progress
229
241
  */
230
- async function ensureStageSteps(progress, stageName, cwd) {
242
+ async function ensureStageSteps(progress, stageName, cwd, specDir = null) {
231
243
  if (!progress.stages) progress.stages = {}
232
244
 
233
- const steps = await getStageSteps(stageName, cwd, progress)
245
+ const steps = await getStageSteps(stageName, cwd, progress, specDir)
234
246
  if (!steps) return false
235
247
 
236
248
  if (!progress.stages[stageName] || !progress.stages[stageName].steps || progress.stages[stageName].steps.length === 0) {
@@ -287,7 +299,9 @@ async function outputStep(stageName, stepIndex, steps, cwd, changeName, dbProjec
287
299
  console.log(`project: ${projectName}`)
288
300
  if (changeName) {
289
301
  console.log(`change: ${changeName}`)
290
- const changeDir = join('.sillyspec', 'changes', changeName)
302
+ const isPlatform = platformOpts?.specRoot || platformOpts?.runtimeRoot
303
+ const changeDirBase = isPlatform ? platformOpts.specRoot : '.sillyspec'
304
+ const changeDir = join(changeDirBase, 'changes', changeName)
291
305
  console.log(`changeDir: ${changeDir}`)
292
306
  }
293
307
  console.log(`---\n`)
@@ -331,40 +345,59 @@ async function outputStep(stageName, stepIndex, steps, cwd, changeName, dbProjec
331
345
  if (changeName && promptText.includes('<change-name>')) {
332
346
  promptText = promptText.replace(/<change-name>/g, changeName)
333
347
  }
334
- // 平台模式:注入路径覆盖指令(仅 scan 阶段)
335
- if (stageName === 'scan') {
348
+ // 平台模式:注入路径覆盖指令
349
+ if (platformOpts?.specRoot || platformOpts?.runtimeRoot) {
336
350
  const projectName = dbProjectName || basename(cwd)
337
- const specSillyspec = platformOpts?.specRoot
338
- ? join(platformOpts.specRoot, '.sillyspec')
339
- : join(cwd, '.sillyspec')
351
+ // platformOpts.specRoot 现在指向 specDir 本身(可能是 cwd/.sillyspec 或外部路径)
352
+ const specSillyspec = platformOpts.specRoot || join(cwd, '.sillyspec')
340
353
  const docsRoot = join(specSillyspec, 'docs', projectName)
341
354
  const projectsRoot = join(specSillyspec, 'projects')
355
+ const changesRoot = join(specSillyspec, 'changes')
342
356
 
343
357
  promptText = promptText.replace(/\{DOCS_ROOT\}/g, docsRoot)
344
358
  promptText = promptText.replace(/\{PROJECTS_ROOT\}/g, projectsRoot)
345
359
 
346
- // 平台模式附加指令
347
- if (platformOpts?.specRoot || platformOpts?.runtimeRoot) {
348
- const platformDirectives = []
349
- if (platformOpts.specRoot) {
350
- platformDirectives.push(
351
- `## ⚠️ 平台模式\n` +
352
- `文档路径已参数化:\n` +
353
- `- 文档根目录: \`${docsRoot}/\`\n` +
354
- `- 项目注册表: \`${projectsRoot}/\`\n` +
355
- `创建目录: \`mkdir -p ${docsRoot}/{scan,modules,flows} ${projectsRoot}\`\n`
356
- )
357
- }
358
- if (platformOpts.runtimeRoot) {
359
- const scanRunId = platformOpts.scanRunId || 'scan-' + new Date().toISOString().slice(0, 19).replace(/[T:]/g, '-')
360
- platformDirectives.push(
361
- `运行时产物写入: \`${platformOpts.runtimeRoot}/scan-runs/${scanRunId}/\`\n`
362
- )
363
- }
364
- if (platformOpts.workspaceId) {
365
- platformDirectives.push(`workspace_id: ${platformOpts.workspaceId}`)
366
- }
367
- promptText = platformDirectives.join('\n') + '\n\n' + promptText
360
+ const platformDirectives = []
361
+ platformDirectives.push(
362
+ `## ⚠️ 平台模式 — 写入路径约束(必须严格遵守)\n` +
363
+ `\n` +
364
+ `规范目录(specDir): \`${specSillyspec}\`\n` +
365
+ `- 文档根目录: \`${docsRoot}/\`\n` +
366
+ `- 项目注册表: \`${projectsRoot}/\`\n` +
367
+ `- 变更目录: \`${changesRoot}/\`\n` +
368
+ `\n` +
369
+ `### 写入规则\n` +
370
+ `1. **所有文档、配置、产物只能写入上述路径**。严禁写入源码目录或相对路径 \`.sillyspec/\`。\n` +
371
+ `2. **不允许**从 cwd 推导文档路径,必须使用上面列出的绝对路径。\n` +
372
+ `3. **源码扫描范围**必须排除:.sillyspec/、.claude/、.git/、node_modules/、dist/、build/、__pycache__/\n` +
373
+ `4. **local.yaml 校验**:commands 中引用的命令必须在 package.json scripts 中存在,不存在的标记为 unavailable,不能写 "配置良好"\n` +
374
+ `\n` +
375
+ `### ⛔ Write 工具规则\n` +
376
+ `1. 如果 Write 返回 \"File has not been read yet\",正确动作是:先 Read 目标文件 → 再 Write 覆盖。\n` +
377
+ `2. **不允许**用 cat >、tee、heredoc 等 Bash 方式绕过 Write 工具。\n` +
378
+ `3. 如果 Write 和 Read 均失败,记录失败并停止当前 step。\n` +
379
+ `\n` +
380
+ `创建目录: \`mkdir -p ${docsRoot}/{scan,modules,flows} ${projectsRoot} ${changesRoot}\`\n`
381
+ )
382
+ if (platformOpts.runtimeRoot) {
383
+ const scanRunId = platformOpts.scanRunId || 'scan-' + new Date().toISOString().slice(0, 19).replace(/[T:]/g, '-')
384
+ platformDirectives.push(
385
+ `运行时产物写入: \`${platformOpts.runtimeRoot}/scan-runs/${scanRunId}/\`\n`
386
+ )
387
+ }
388
+ if (platformOpts.workspaceId) {
389
+ platformDirectives.push(`workspace_id: ${platformOpts.workspaceId}`)
390
+ }
391
+ promptText = platformDirectives.join('\n') + '\n\n' + promptText
392
+ } else {
393
+ // 非 platform 模式也要替换占位符
394
+ if (stageName === 'scan') {
395
+ const projectName = dbProjectName || basename(cwd)
396
+ const specSillyspec = join(cwd, '.sillyspec')
397
+ const docsRoot = join(specSillyspec, 'docs', projectName)
398
+ const projectsRoot = join(specSillyspec, 'projects')
399
+ promptText = promptText.replace(/\{DOCS_ROOT\}/g, docsRoot)
400
+ promptText = promptText.replace(/\{PROJECTS_ROOT\}/g, projectsRoot)
368
401
  }
369
402
  }
370
403
 
@@ -378,9 +411,18 @@ async function outputStep(stageName, stepIndex, steps, cwd, changeName, dbProjec
378
411
  console.log('- 不要用 mv/rename 重命名变更目录,必须用 `sillyspec change-rename <旧名> <新名>`')
379
412
  console.log('- 文档类型文件(.md/.yaml/.json 等)头部必须包含 author(git 用户名)和 created_at(精确到秒)')
380
413
  console.log('- 执行构建/测试前必须先读 local.yaml,优先使用其中配置的命令、路径和环境变量;未配置时才使用默认值')
414
+ // 平台模式额外铁律
415
+ if (platformOpts?.specRoot || platformOpts?.runtimeRoot) {
416
+ const specSillyspec = platformOpts.specRoot || join(cwd, '.sillyspec')
417
+ console.log(`- **平台模式:所有文件只能写入 \`${specSillyspec}/\` 下的对应子目录,严禁写入源码目录。**`)
418
+ console.log('- **平台模式:Write 工具失败时,不允许用 cat > / tee / heredoc 等方式绕过。先 Read 再 Write,仍失败则记录并停止。**')
419
+ console.log('- **平台模式:local.yaml 中的 commands 必须在 package.json scripts 中真实存在,不存在的标记 unavailable。**')
420
+ }
381
421
  // 路径安全规则:防止 AI 拼错变更目录
382
422
  if (changeName) {
383
- const changeDir = join('.sillyspec', 'changes', changeName)
423
+ const isPlatform = platformOpts?.specRoot || platformOpts?.runtimeRoot
424
+ const changeDirBase = isPlatform ? platformOpts.specRoot : '.sillyspec'
425
+ const changeDir = join(changeDirBase, 'changes', changeName)
384
426
  console.log(`- **文件路径规则:所有变更文件必须写入 \`${changeDir}/\` 目录下。不要自己拼接路径,直接使用 changeDir 值。示例:\`${changeDir}/proposal.md\`**`)
385
427
  }
386
428
  const changeFlag = changeName ? ` --change ${changeName}` : ''
@@ -391,7 +433,7 @@ async function outputStep(stageName, stepIndex, steps, cwd, changeName, dbProjec
391
433
  /**
392
434
  * sillyspec run <stage> 主命令
393
435
  */
394
- export async function runCommand(args, cwd) {
436
+ export async function runCommand(args, cwd, specDir = null) {
395
437
  // 解析参数
396
438
  const stageName = args[0]
397
439
  const flags = args.slice(1)
@@ -416,20 +458,36 @@ export async function runCommand(args, cwd) {
416
458
  const isSkipApproval = flags.includes('--skip-approval')
417
459
 
418
460
  // 平台模式参数(供 SillyHub 等平台调用)
461
+ // --spec-dir 是统一参数名,--spec-root 保留为向后兼容别名
419
462
  const getFlagValue = (name) => {
420
463
  const idx = flags.indexOf(name)
421
464
  return idx !== -1 && flags[idx + 1] ? flags[idx + 1] : null
422
465
  }
466
+ const resolvedSpecDir = specDir || getFlagValue('--spec-dir') || getFlagValue('--spec-root');
423
467
  const platformOpts = {
424
- specRoot: getFlagValue('--spec-root'),
425
- runtimeRoot: getFlagValue('--runtime-root'),
468
+ specRoot: resolvedSpecDir ? resolve(resolvedSpecDir) : null,
469
+ runtimeRoot: getFlagValue('--runtime-root') ? resolve(getFlagValue('--runtime-root')) : null,
426
470
  workspaceId: getFlagValue('--workspace-id'),
427
471
  scanRunId: getFlagValue('--scan-run-id'),
428
472
  }
429
473
 
430
474
  // 跨 --done 生命周期:从 metadata 文件恢复 platformOpts
431
475
  // 首次 scan 时写入,所有后续调用(包括 run、--done、--skip)都读取
432
- const platformOptsFile = join(cwd, '.sillyspec', '.runtime', 'platform-scan.json')
476
+ // 优先在 specDir 下查找,否则回退到 cwd/.sillyspec/.runtime/
477
+ const specRoot = platformOpts.specRoot || resolveSpecDir(cwd)
478
+ // platform-scan.json 搜索策略(多路径兼容):
479
+ // 平台模式首次 scan 写入 specRoot/.runtime/,但后续 --done 可能不带 --spec-root
480
+ // 需要在多个候选位置搜索
481
+ const candidatePaths = []
482
+ if (platformOpts.specRoot) {
483
+ candidatePaths.push(join(platformOpts.specRoot, '.runtime', 'platform-scan.json'))
484
+ }
485
+ if (resolvedSpecDir) {
486
+ candidatePaths.push(join(resolve(resolvedSpecDir), '.runtime', 'platform-scan.json'))
487
+ }
488
+ candidatePaths.push(join(specRoot, '.runtime', 'platform-scan.json')) // cwd/.sillyspec/.runtime/
489
+
490
+ let platformOptsFile = candidatePaths.find(p => existsSync(p)) || candidatePaths[0]
433
491
  let platformFileExists = existsSync(platformOptsFile)
434
492
  // 如果命令行没传 spec-root,尝试从持久化文件恢复
435
493
  if (!platformOpts.specRoot && !platformOpts.runtimeRoot) {
@@ -457,11 +515,12 @@ export async function runCommand(args, cwd) {
457
515
  }
458
516
  }
459
517
  }
460
- // 持久化 platformOpts(命令行传入或已恢复的都持久化)
518
+ // 持久化 platformOpts
519
+ // 在 specRoot/.runtime/ 写主文件,同时在 cwd/.sillyspec/.runtime/ 写恢复指针
461
520
  if (platformOpts.specRoot || platformOpts.runtimeRoot) {
462
521
  try {
463
522
  const { mkdirSync, writeFileSync } = await import('fs')
464
- mkdirSync(join(cwd, '.sillyspec', '.runtime'), { recursive: true })
523
+ mkdirSync(join(specRoot, '.runtime'), { recursive: true })
465
524
  writeFileSync(platformOptsFile, JSON.stringify({
466
525
  specRoot: platformOpts.specRoot,
467
526
  runtimeRoot: platformOpts.runtimeRoot,
@@ -469,6 +528,16 @@ export async function runCommand(args, cwd) {
469
528
  scanRunId: platformOpts.scanRunId,
470
529
  savedAt: new Date().toISOString(),
471
530
  }, null, 2) + '\n')
531
+ // 恢复指针:在 cwd/.sillyspec/.runtime/ 也写一份,供后续 --done(不带 --spec-root)找到
532
+ const cwdRuntimeDir = join(cwd, '.sillyspec', '.runtime')
533
+ mkdirSync(cwdRuntimeDir, { recursive: true })
534
+ writeFileSync(join(cwdRuntimeDir, 'platform-scan.json'), JSON.stringify({
535
+ specRoot: platformOpts.specRoot,
536
+ runtimeRoot: platformOpts.runtimeRoot,
537
+ workspaceId: platformOpts.workspaceId,
538
+ scanRunId: platformOpts.scanRunId,
539
+ savedAt: new Date().toISOString(),
540
+ }, null, 2) + '\n')
472
541
  } catch {
473
542
  // 静默失败,不影响主流程
474
543
  }
@@ -509,7 +578,7 @@ export async function runCommand(args, cwd) {
509
578
  const knownFlags = new Set([
510
579
  '--done', '--skip', '--status', '--reset', '--confirm', '--skip-approval',
511
580
  '--output', '--input', '--change',
512
- '--spec-root', '--runtime-root', '--workspace-id', '--scan-run-id',
581
+ '--spec-dir', '--spec-root', '--runtime-root', '--workspace-id', '--scan-run-id',
513
582
  '--files', '--allow-new', '--force-baseline',
514
583
  '--json', '--dir', '--help',
515
584
  ])
@@ -528,17 +597,17 @@ export async function runCommand(args, cwd) {
528
597
 
529
598
  const isAuxiliary = auxiliaryStages.includes(stageName)
530
599
 
531
- const pm = new ProgressManager()
600
+ const pm = new ProgressManager({ specDir: specRoot })
532
601
  let progress = await pm.read(cwd, changeName)
533
602
 
534
603
  if (!progress) {
535
604
  // 如果指定了变更名或有变更目录,自动初始化变更的 progress
536
- const autoChange = changeName || resolveChangeNameAuto(cwd)
605
+ const autoChange = changeName || resolveChangeNameAuto(cwd, specRoot)
537
606
  if (autoChange) {
538
607
  progress = await pm.initChange(cwd, autoChange)
539
608
  } else if (isAuxiliary) {
540
609
  // 辅助阶段(scan/explore/quick/doctor/status)自动使用默认变更名
541
- const autoName = changeName || resolveChangeNameAuto(cwd) || 'default'
610
+ const autoName = changeName || resolveChangeNameAuto(cwd, specRoot) || 'default'
542
611
  changeName = autoName
543
612
  progress = await pm.initChange(cwd, autoName)
544
613
  // initChange 可能因 project 表为空返回 null
@@ -563,7 +632,7 @@ export async function runCommand(args, cwd) {
563
632
  }
564
633
 
565
634
  // 确保 progress 有 currentChange
566
- const effectiveChange = changeName || progress.currentChange || resolveChangeName(cwd, progress)
635
+ const effectiveChange = changeName || progress.currentChange || resolveChangeName(cwd, progress, specRoot)
567
636
 
568
637
  // -- auto 模式:自动推进所有流程阶段
569
638
  if (stageName === 'auto') {
@@ -582,7 +651,7 @@ export async function runCommand(args, cwd) {
582
651
  }
583
652
 
584
653
  // 确保步骤已初始化
585
- const changed = await ensureStageSteps(progress, stageName, cwd)
654
+ const changed = await ensureStageSteps(progress, stageName, cwd, specRoot)
586
655
  if (changed && effectiveChange) {
587
656
  await pm._write(cwd, progress, effectiveChange)
588
657
  triggerSync(cwd, effectiveChange)
@@ -605,14 +674,14 @@ export async function runCommand(args, cwd) {
605
674
  }
606
675
 
607
676
  // 默认:输出当前步骤
608
- return await runStage(pm, progress, stageName, cwd, effectiveChange, isSkipApproval, platformOpts)
677
+ return await runStage(pm, progress, stageName, cwd, effectiveChange, isSkipApproval, platformOpts, { quickFiles, isAllowNew, isForceBaseline })
609
678
  }
610
679
 
611
680
  /**
612
681
  * 自动推导变更名(不依赖 progress)
613
682
  */
614
- function resolveChangeNameAuto(cwd) {
615
- const changesDir = join(cwd, '.sillyspec', 'changes')
683
+ function resolveChangeNameAuto(cwd, specDir = null) {
684
+ const changesDir = join(specDir || resolveSpecDir(cwd), 'changes')
616
685
  if (!existsSync(changesDir)) return null
617
686
  const entries = readdirSync(changesDir, { withFileTypes: true })
618
687
  .filter(e => e.isDirectory() && e.name !== 'archive')
@@ -620,7 +689,7 @@ function resolveChangeNameAuto(cwd) {
620
689
  return null
621
690
  }
622
691
 
623
- async function runStage(pm, progress, stageName, cwd, changeName, skipApproval = false, platformOpts = {}) {
692
+ async function runStage(pm, progress, stageName, cwd, changeName, skipApproval = false, platformOpts = {}, quickOpts = {}) {
624
693
  // 状态转换校验
625
694
  const prevStage = progress.currentStage || ''
626
695
  const transition = checkTransition(prevStage, stageName)
@@ -696,9 +765,9 @@ async function runStage(pm, progress, stageName, cwd, changeName, skipApproval =
696
765
  .trim().split('\n').filter(Boolean)
697
766
  .map(line => line.slice(3).trim())
698
767
  .filter(f => !f.startsWith('.sillyspec/'))
699
- const allowedFiles = quickFiles || []
700
- const allowNew = isAllowNew || false
701
- const forceBaseline = isForceBaseline || false
768
+ const allowedFiles = quickOpts?.quickFiles || []
769
+ const allowNew = quickOpts?.isAllowNew || false
770
+ const forceBaseline = quickOpts?.isForceBaseline || false
702
771
  progress.quickGuard = {
703
772
  baselineCommit: execSync('git rev-parse HEAD', { cwd, encoding: 'utf8', timeout: 5000 }).trim(),
704
773
  baselineFiles,
@@ -1034,8 +1103,8 @@ async function completeStep(pm, progress, stageName, cwd, outputText, inputText
1034
1103
  appendFileSync(inputsPath, entry)
1035
1104
  }
1036
1105
 
1037
- // 平台模式:scan 完成后生成 manifest.json
1038
- if (stageName === 'scan' && platformOpts.specRoot) {
1106
+ // 平台模式:scan 完成后生成 manifest.json + post-check
1107
+ if (stageName === 'scan' && (platformOpts.specRoot || platformOpts.runtimeRoot)) {
1039
1108
  try {
1040
1109
  const { mkdirSync, writeFileSync } = await import('fs')
1041
1110
  const { join } = await import('path')
@@ -1061,29 +1130,52 @@ async function completeStep(pm, progress, stageName, cwd, outputText, inputText
1061
1130
  }
1062
1131
  // 清理平台参数临时文件
1063
1132
  const { unlinkSync } = await import('fs')
1064
- const platformOptsFile = join(cwd, '.sillyspec', '.runtime', 'platform-scan.json')
1133
+ const platformOptsFile = join(specRoot, '.runtime', 'platform-scan.json')
1065
1134
  try { unlinkSync(platformOptsFile) } catch {}
1066
1135
 
1067
- // 平台模式后置校验:检查 source_root 是否被污染
1068
- if (platformOpts.specRoot) {
1069
- const { readdirSync } = await import('fs')
1070
- const localDocsDir = join(cwd, '.sillyspec', 'docs')
1071
- try {
1072
- if (existsSync(localDocsDir)) {
1073
- const entries = readdirSync(localDocsDir, { recursive: true }).filter(e => e.endsWith('.md'))
1074
- if (entries.length > 0) {
1075
- console.warn(`⚠️ 平台模式后置校验:source_root 下存在 ${entries.length} 个文档文件:`)
1076
- console.warn(` 路径:${localDocsDir}/`)
1077
- console.warn(` 可能原因:agent 未遵守路径覆盖,将文档写入到了 cwd 而非 spec-root`)
1078
- }
1079
- }
1080
- } catch {}
1136
+ // CLI post-check(替代旧的简单检查)
1137
+ const { runScanPostCheck, printScanPostCheckResult } = await import('./scan-postcheck.js')
1138
+ const postResult = runScanPostCheck({
1139
+ cwd,
1140
+ specDir: platformOpts.specRoot,
1141
+ outputText,
1142
+ })
1143
+ printScanPostCheckResult(postResult)
1144
+
1145
+ // 将 post-check 结果写入 manifest
1146
+ manifest.scan_post_check = {
1147
+ status: postResult.status,
1148
+ checks: postResult.checks,
1149
+ }
1150
+ // 更新 manifest
1151
+ writeFileSync(manifestPath, JSON.stringify(manifest, null, 2) + '\n')
1152
+ console.log(`📄 manifest.json 已更新(含 post-check 结果)`)
1153
+
1154
+ // failed_post_check 时强制阻止 clean success
1155
+ if (postResult.status === 'failed_post_check') {
1156
+ stageData.status = 'failed_post_check'
1157
+ stageData.completedAt = new Date().toLocaleString('zh-CN',{hour12:false})
1158
+ await pm._write(cwd, progress, changeName)
1159
+ console.error(`\n❌ scan post-check 失败,状态设为 failed_post_check。不允许 clean success。`)
1160
+ console.error(` 请检查上方错误信息并修复后重新 scan。`)
1161
+ } else if (postResult.status === 'completed_with_warnings') {
1162
+ // 警告不阻止完成,但记录
1163
+ stageData.status = 'completed'
1164
+ stageData.completedAt = new Date().toLocaleString('zh-CN',{hour12:false})
1165
+ await pm._write(cwd, progress, changeName)
1081
1166
  }
1082
1167
  } catch (e) {
1083
1168
  console.warn(`⚠️ manifest.json 写入失败: ${e.message}`)
1084
1169
  }
1085
1170
  }
1086
1171
 
1172
+ // 非 platform 模式 scan 也做轻量 post-check
1173
+ if (stageName === 'scan' && !platformOpts.specRoot && !platformOpts.runtimeRoot) {
1174
+ const { runScanPostCheck, printScanPostCheckResult } = await import('./scan-postcheck.js')
1175
+ const postResult = runScanPostCheck({ cwd, specDir: null, outputText })
1176
+ printScanPostCheckResult(postResult)
1177
+ }
1178
+
1087
1179
  validateMetadata(cwd, stageName)
1088
1180
 
1089
1181
  // 验证关键文件是否在正确的变更目录下
@@ -0,0 +1,179 @@
1
+ /**
2
+ * scan-postcheck.js — CLI 层 scan 完成后强制校验
3
+ *
4
+ * 不依赖 AI agent 的自检报告,由 CLI 代码直接检查文件系统。
5
+ * 平台模式下必须通过所有 check 才能 success,否则降级。
6
+ */
7
+
8
+ import { existsSync, readdirSync, readFileSync } from 'fs'
9
+ import { join, basename } from 'path'
10
+
11
+ const REQUIRED_SCAN_DOCS = [
12
+ 'ARCHITECTURE.md',
13
+ 'CONVENTIONS.md',
14
+ 'STRUCTURE.md',
15
+ 'INTEGRATIONS.md',
16
+ 'TESTING.md',
17
+ 'CONCERNS.md',
18
+ 'PROJECT.md',
19
+ ]
20
+
21
+ /**
22
+ * @param {object} opts
23
+ * @param {string} opts.cwd - 源码项目根目录 (source_root)
24
+ * @param {string} opts.specDir - 规范目录 (spec-root),null 时为非平台模式
25
+ * @param {string} [opts.outputText] - 最后一步(自检)的 AI 输出文本
26
+ * @returns {{ status: 'success'|'completed_with_warnings'|'failed_post_check', checks: Array<{name, severity, detail}> }}
27
+ */
28
+ export function runScanPostCheck({ cwd, specDir, outputText = '' }) {
29
+ const isPlatform = !!specDir
30
+ const checks = []
31
+
32
+ if (!isPlatform) {
33
+ // 非平台模式:只做轻量检查
34
+ const localSpec = join(cwd, '.sillyspec')
35
+ const scanDir = join(localSpec, 'docs', basename(cwd), 'scan')
36
+
37
+ // 检查 7 份文档是否存在
38
+ const missing = REQUIRED_SCAN_DOCS.filter(f => !existsSync(join(scanDir, f)))
39
+ if (missing.length > 0) {
40
+ checks.push({ name: 'missing_docs', severity: 'warning', detail: `缺少 ${missing.length} 份 scan 文档: ${missing.join(', ')}` })
41
+ }
42
+
43
+ const hasWarning = checks.some(c => c.severity === 'warning')
44
+ return { status: hasWarning ? 'completed_with_warnings' : 'success', checks }
45
+ }
46
+
47
+ // ── 平台模式:严格检查 ──
48
+
49
+ const projectName = basename(cwd)
50
+
51
+ // 1. source_root 污染检查
52
+ const localDocsDir = join(cwd, '.sillyspec', 'docs')
53
+ if (existsSync(localDocsDir)) {
54
+ try {
55
+ const leaked = readdirSync(localDocsDir, { recursive: true }).filter(e => String(e).endsWith('.md'))
56
+ if (leaked.length > 0) {
57
+ checks.push({
58
+ name: 'source_root_docs_leak',
59
+ severity: 'failed',
60
+ detail: `source_root 下存在 ${leaked.length} 个文档文件(${localDocsDir}/),agent 可能写入到了错误路径`
61
+ })
62
+ }
63
+ } catch {}
64
+ }
65
+
66
+ // 2. spec_root 检查 7 份必需文档
67
+ const specScanDir = join(specDir, 'docs', projectName, 'scan')
68
+ const missingDocs = REQUIRED_SCAN_DOCS.filter(f => !existsSync(join(specScanDir, f)))
69
+ if (missingDocs.length > 0) {
70
+ checks.push({
71
+ name: missingDocs.length === REQUIRED_SCAN_DOCS.length ? 'all_docs_missing' : 'partial_docs_missing',
72
+ severity: 'failed',
73
+ detail: missingDocs.length === REQUIRED_SCAN_DOCS.length
74
+ ? `spec_root 下无任何 scan 文档(${specScanDir}/),扫描可能未执行`
75
+ : `spec_root 缺少必需文档: ${missingDocs.join(', ')}(7 份 scan 文档均为 required)`
76
+ })
77
+ }
78
+
79
+ // 3. 检查文档 header(author / created_at)
80
+ const existingDocs = REQUIRED_SCAN_DOCS.filter(f => existsSync(join(specScanDir, f)))
81
+ const docsMissingHeader = []
82
+ for (const doc of existingDocs) {
83
+ const content = readFileSync(join(specScanDir, doc), 'utf8')
84
+ if (!content.includes('author') || !content.includes('created_at')) {
85
+ docsMissingHeader.push(doc)
86
+ }
87
+ }
88
+ if (docsMissingHeader.length > 0) {
89
+ checks.push({
90
+ name: 'docs_missing_header',
91
+ severity: 'warning',
92
+ detail: `${docsMissingHeader.length} 份文档缺少 author/created_at: ${docsMissingHeader.join(', ')}`
93
+ })
94
+ }
95
+
96
+ // 4. local.yaml 校验
97
+ const localYamlPath = join(specDir, 'local.yaml')
98
+ if (existsSync(localYamlPath)) {
99
+ const yamlContent = readFileSync(localYamlPath, 'utf8')
100
+ const packageJsonPath = join(cwd, 'package.json')
101
+ const invalidCommands = []
102
+
103
+ // 简单提取 local.yaml 中的 commands
104
+ const commandMatch = yamlContent.match(/build:\s*"([^"]+)"/) ||
105
+ yamlContent.match(/test:\s*"([^"]+)"/) ||
106
+ yamlContent.match(/lint:\s*"([^"]+)"/)
107
+
108
+ if (commandMatch) {
109
+ // 提取所有 npm run <script> 形式的命令
110
+ const npmRunCommands = yamlContent.match(/npm run (\S+)/g) || []
111
+ if (npmRunCommands.length > 0 && existsSync(packageJsonPath)) {
112
+ try {
113
+ const pkg = JSON.parse(readFileSync(packageJsonPath, 'utf8'))
114
+ const scripts = pkg.scripts || {}
115
+ for (const cmd of npmRunCommands) {
116
+ const scriptName = cmd.replace('npm run ', '')
117
+ if (!scripts[scriptName]) {
118
+ invalidCommands.push(`${cmd} (package.json 无 ${scriptName} script)`)
119
+ }
120
+ }
121
+ } catch {}
122
+ }
123
+ }
124
+
125
+ if (invalidCommands.length > 0) {
126
+ checks.push({
127
+ name: 'local_config_invalid',
128
+ severity: 'warning',
129
+ detail: `local.yaml 引用不存在的命令: ${invalidCommands.join('; ')}`
130
+ })
131
+ }
132
+ }
133
+
134
+ // 5. 检查 AI 输出中的错误标记
135
+ if (outputText) {
136
+ const errorPatterns = [
137
+ { pattern: /tool_use_error/i, name: 'tool_use_error', detail: 'AI 输出中包含 tool_use_error' },
138
+ { pattern: /API Error.*529/i, name: 'api_error_529', detail: 'AI 输出中包含 API Error 529' },
139
+ { pattern: /rate.?limit.*exhausted/i, name: 'rate_limit_exhausted', detail: 'AI 输出中包含 rate_limit exhausted' },
140
+ { pattern: /fallback|retry.*failed|skipped.*validat/i, name: 'fallback_or_skip', detail: 'AI 输出中出现 fallback/retry failed/skipped validation' },
141
+ ]
142
+ for (const ep of errorPatterns) {
143
+ if (ep.pattern.test(outputText)) {
144
+ checks.push({ name: ep.name, severity: 'warning', detail: ep.detail })
145
+ }
146
+ }
147
+ }
148
+
149
+ // 6. 计算 finalStatus
150
+ const hasFailed = checks.some(c => c.severity === 'failed')
151
+ const hasWarning = checks.some(c => c.severity === 'warning')
152
+
153
+ let status
154
+ if (hasFailed) {
155
+ status = 'failed_post_check'
156
+ } else if (hasWarning) {
157
+ status = 'completed_with_warnings'
158
+ } else {
159
+ status = 'success'
160
+ }
161
+
162
+ return { status, checks }
163
+ }
164
+
165
+ /**
166
+ * 打印 post-check 结果到 stdout
167
+ */
168
+ export function printScanPostCheckResult(result) {
169
+ if (result.checks.length === 0) {
170
+ console.log(' ✅ CLI post-check: 全部通过')
171
+ return
172
+ }
173
+
174
+ for (const check of result.checks) {
175
+ const icon = check.severity === 'failed' ? '❌' : '⚠️'
176
+ console.log(` ${icon} CLI post-check [${check.name}]: ${check.detail}`)
177
+ }
178
+ console.log(` 📋 最终状态: ${result.status}`)
179
+ }