dsh-project-flow 0.8.3 → 0.9.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.
Files changed (75) hide show
  1. package/CHANGELOG.md +0 -0
  2. package/README.md +166 -358
  3. package/bench/corpus/qa-fail-3-issues.md +33 -0
  4. package/bench/corpus/qa-fail-assertion.md +20 -0
  5. package/bench/corpus/qa-fail-missing-detect.md +21 -0
  6. package/bench/corpus/qa-pass.md +9 -0
  7. package/bench/corpus/qa-reverify-partial.md +30 -0
  8. package/bench/corpus/qa-unverified-only.md +15 -0
  9. package/bench/corpus/requirement-no-check.md +8 -0
  10. package/bench/corpus/requirement-with-check.md +16 -0
  11. package/bench/corpus/reverify-table-not-defects.md +18 -0
  12. package/bench/run.mjs +142 -0
  13. package/client.js +195 -9
  14. package/cordis.patch.yml +29 -9
  15. package/docs/CHECKS.md +100 -0
  16. package/docs/DETAIL.md +6 -6
  17. package/docs/FEATURES.md +12 -5
  18. package/docs/ISSUES.md +75 -0
  19. package/docs/LAUNCH.md +3 -3
  20. package/docs/LEDGER.md +46 -0
  21. package/docs/MOMENTS.md +4 -4
  22. package/docs/USAGE.md +2 -2
  23. package/docs/adr/0001-four-stage-isolation.md +25 -0
  24. package/docs/adr/0002-file-handoff-not-context.md +27 -0
  25. package/docs/adr/0003-diff-over-self-report.md +27 -0
  26. package/docs/adr/0004-issue-level-rework.md +30 -0
  27. package/docs/adr/0005-assertion-over-prose.md +30 -0
  28. package/docs/anchors/assertion-exec.md +39 -0
  29. package/docs/anchors/cost-accounting.md +44 -0
  30. package/docs/anchors/diff-reconciliation.md +35 -0
  31. package/docs/anchors/file-whitelist.md +29 -0
  32. package/docs/anchors/intent-gate.md +41 -0
  33. package/docs/anchors/issue-loop.md +40 -0
  34. package/docs/anchors/patch-ledger.md +38 -0
  35. package/docs/anchors/watchdog.md +30 -0
  36. package/domains.mjs +1 -1
  37. package/evidence.mjs +19 -3
  38. package/flow.schema.mjs +600 -0
  39. package/gate.mjs +49 -23
  40. package/index.js +2800 -134
  41. package/locale/en.json +15 -4
  42. package/locale/zh.json +17 -6
  43. package/package.json +11 -2
  44. package/tests/_heartbeat-regression.test.mjs +124 -0
  45. package/tests/_wd_sandbox/.project-flow/demo/run.log +1 -0
  46. package/tests/_wd_sandbox/a.txt +1 -0
  47. package/tests/aesthetic.test.mjs +534 -0
  48. package/tests/assertions-e2e.mjs +234 -0
  49. package/tests/bench-check.mjs +32 -0
  50. package/tests/client-bundle.test.mjs +707 -0
  51. package/tests/contract.test.mjs +137 -0
  52. package/tests/desktop.test.mjs +130 -0
  53. package/tests/domains.test.mjs +220 -0
  54. package/tests/e2e.mjs +300 -0
  55. package/tests/evidence.test.mjs +408 -0
  56. package/tests/extra-phase.test.mjs +133 -0
  57. package/tests/feedback.test.mjs +187 -0
  58. package/tests/flow-create.test.mjs +168 -0
  59. package/tests/flow-gate.test.mjs +232 -0
  60. package/tests/flow-schema.test.mjs +213 -0
  61. package/tests/gate.test.mjs +246 -0
  62. package/tests/issue-loop.test.mjs +254 -0
  63. package/tests/issues-e2e.mjs +246 -0
  64. package/tests/panel-independence.test.mjs +78 -0
  65. package/tests/panel-report.test.mjs +129 -0
  66. package/tests/patch-ledger.test.mjs +280 -0
  67. package/tests/paths.mjs +94 -0
  68. package/tests/preview-path.test.mjs +69 -0
  69. package/tests/qa-assertions.test.mjs +352 -0
  70. package/tests/run-all.mjs +90 -0
  71. package/tests/stage-model.test.mjs +120 -0
  72. package/tests/stop-resume.test.mjs +260 -0
  73. package/tests/watch-root.test.mjs +167 -0
  74. package/tests/watchdog-tokens.test.mjs +49 -0
  75. package/tests/watchdog.test.mjs +301 -0
package/index.js CHANGED
@@ -20,12 +20,14 @@
20
20
  * 授权流程见 docs/COMMERCIAL.md。
21
21
  */
22
22
  import { mkdir, readFile, writeFile, readdir, appendFile, rename, rm, stat } from 'node:fs/promises'
23
- import { readFileSync, existsSync } from 'node:fs'
23
+ import { readFileSync, existsSync, appendFileSync, writeFileSync, rmSync } from 'node:fs'
24
24
  import { join, isAbsolute, dirname, resolve, relative, basename, sep } from 'node:path'
25
25
  import { fileURLToPath } from 'node:url'
26
26
  import { homedir, tmpdir } from 'node:os'
27
27
  import { execFile } from 'node:child_process'
28
+ import { createHash } from 'node:crypto'
28
29
  import z from '@deepseek-ai/schemastery'
30
+ import { loadFlow, describeFlowProblems, BUILTIN_FLOW } from './flow.schema.mjs'
29
31
  import {
30
32
  Watchdog,
31
33
  WatchdogFault,
@@ -89,8 +91,12 @@ import {
89
91
  guardToolCall,
90
92
  extractReadiness,
91
93
  buttonState,
94
+ blindspotGaps,
95
+ dimensionLabel,
96
+ DIMENSIONS,
92
97
  DIMENSION_KEYS,
93
98
  MIN_CONCLUSION_LENGTH,
99
+ SCORE_FLOOR,
94
100
  } from './gate.mjs'
95
101
 
96
102
  /** Shown by project_models, /flow-models, and every plugin surface that reports identity. */
@@ -174,19 +180,40 @@ export const Config = z.object({
174
180
  // runs and simply reports that rollback is unavailable.
175
181
  snapshotEnabled: z.boolean().default(true),
176
182
  snapshotExcludes: z.string().default(''),
183
+ /**
184
+ * 快照保留张数。每次实施前后各打一张,跑十几轮返工就上百张,只增不删会一直涨。
185
+ * 默认留最近 40 张,更老的截掉。设 0 = 不截断(老行为)。
186
+ */
187
+ snapshotKeep: z.natural().default(40),
177
188
  // 工作模式只在这个目录里开。留空就认「当前工作区下的 工作流 目录」,
178
189
  // 填绝对路径就把整台机器的工作流固定到一个地方。
179
190
  flowRoot: z.string().default(''),
180
191
  /**
181
- * 目录门控。auto(默认)不拦,装完就能用;strict 只认「工作流」目录;
182
- * off 不拦也不看名字。想回到早期那道边界就设 strict。
192
+ * 目录门控。三种值:
193
+ *
194
+ * off(默认)—— 不拦,装完就能用,在哪个目录都能开工作模式。这是默认值:
195
+ * 一个要装了就用的工具,不该先让人去建目录再切工作区。
196
+ * auto —— 能识别「工作流」目录就认它,识别不出来也不拦(与 off 的
197
+ * 区别只在「该去哪」这句提示上)。
198
+ * strict —— 只认「工作流」目录,别处直接拒绝。想让目录边界硬一点再开。
199
+ *
200
+ * 以前默认值是 strict 而注释写着「auto 默认不拦」,两句话互相矛盾;
201
+ * 'auto' 这一档甚至不在合法值里,写了会被悄悄归一成 strict。
183
202
  */
184
- flowGate: z.string().default('strict'),
203
+ flowGate: z.string().default('off'),
185
204
  /**
186
205
  * 第一次在普通目录开工时,自动把「工作流」目录建出来。
187
- * 关掉就退回老行为:不在工作流目录里直接拒绝,让人自己去建。
206
+ * 只有 flowGate 为 strict 时才起作用:off / auto 下根本不会走到这一步。
188
207
  */
189
208
  autoCreateFlowDir: z.boolean().default(true),
209
+ /**
210
+ * 意图门控的前置拦截强度。
211
+ *
212
+ * off(默认)—— 只由 project_run 自己检查,别处不拦。装上即可用。
213
+ * enforce —— 注册 ctx.tools.guard,任何推进类工具在自查表没过之前一律拦。
214
+ * 模型想靠换个工具绕开第 1 阶,靠这个堵。
215
+ */
216
+ intentGate: z.string().default('off'),
190
217
  /**
191
218
  * 桌面工具(agent-desktop 那类插件提供的 desktop_* 工具)怎么用。
192
219
  * auto:有视觉产出、或者行当本来就要在软件里核对时才提;on:一律提;off:不提。
@@ -229,7 +256,10 @@ export const Config = z.object({
229
256
  silentMsPlan: z.natural().default(300000),
230
257
  silentMsBuild: z.natural().default(900000),
231
258
  silentMsCheck: z.natural().default(900000),
232
- budgetUsd: z.natural().default(10),
259
+ // 预算上限。用 z.number 而不是 z.natural:z.natural 只收整数,
260
+ // 想设 2.5 美元会被 schema 挡掉并报 "expected number multiple of 1"——
261
+ // 一个按字符估的花费上限,粒度卡在 1 美元太粗了。
262
+ budgetUsd: z.number().min(0).default(10),
233
263
  // 价目表:JSON 字符串,键是模型名,值是 { input, output } 的每百万 token 美元价。
234
264
  priceTable: z.string().default(''),
235
265
  // 完成证据包:外部测试命令的 exit code 决定 requirement_met,
@@ -239,6 +269,24 @@ export const Config = z.object({
239
269
  testCommand: z.string().default('auto'),
240
270
  testTimeoutMs: z.natural().default(600000),
241
271
  cnyRate: z.number().min(0.0001).default(7),
272
+ // ── 断言执行器 ──────────────────────────────────────────────
273
+ /**
274
+ * 额外放行的命令,逗号或空格分隔。默认那 9 类写死在代码里,这一项只能往上加:
275
+ * 白名单一旦可以被配置删空,「判据」就又回到模型嘴里了。
276
+ */
277
+ checkAllowedCommands: z.string().default(''),
278
+ /**
279
+ * 严格判据模式:连 `node -e` / `python -c` 这类「把代码当参数」的调用也拒。
280
+ *
281
+ * 默认 false。这几个开关是写轻量判据的常见写法(`node -e "require('assert')..."`),
282
+ * 默认拦住等于把正常用法砍了。它挡的是手滑,不是刻意;想再紧一点再开。
283
+ * 注意:开了之后那些判据会记成 denied 而不是 pass,别一装上就开。
284
+ */
285
+ checkStrictEval: z.boolean().default(false),
286
+ /** 单条 check 的超时。不是一轮总和:一轮里每条各自计时。 */
287
+ checkTimeoutMs: z.natural().default(120000),
288
+ /** stdout / stderr 留多少字符的尾巴。超长只留尾部——报错基本写在最后几行。 */
289
+ checkStdoutTailChars: z.natural().default(8000),
242
290
  })
243
291
 
244
292
  const STAGE_LABEL = {
@@ -274,6 +322,321 @@ const ARTIFACT = {
274
322
  log: 'Execution_Log.md',
275
323
  qa: 'QA_Report.md',
276
324
  nextStep: 'Next_Step.md',
325
+ // 判据指纹:Requirement.md 里 check 字段的 sha256。第 2 阶入口算一次,
326
+ // 第 4 阶复算一次,对不上就停机——中途改判据等于自己给自己放水。
327
+ requirementHash: 'requirement.sha',
328
+ }
329
+
330
+ // ── 补丁台账 ──────────────────────────────────────────────────
331
+ //
332
+ // 回滚以前靠 git 快照整棵还原。问题是 precise 模式只还原 attempts 里记的文件,
333
+ // 而 attempts 的文件清单来自实施段的自述——自述可以说假话。
334
+ //
335
+ // 台账记的是「插件自己看到的每次写入」:beforeSha / afterSha 都是插件算的,
336
+ // 不靠自述。回滚按台账走,只动 agent 真的写过的路径,不卷走用户手改的东西。
337
+
338
+ /** 台账目录:.project-flow/<project>/ledger/ */
339
+ function ledgerDir(cwd, project) {
340
+ return join(stateDir(cwd, project), 'ledger')
341
+ }
342
+
343
+ /** 台账文件:patch-ledger.jsonl,逐行 JSON 追加写,不覆盖。 */
344
+ function ledgerPath(cwd, project) {
345
+ return join(ledgerDir(cwd, project), 'patch-ledger.jsonl')
346
+ }
347
+
348
+ /**
349
+ * 把路径里的反斜杠统一成正斜杠。
350
+ *
351
+ * Windows 上同一个文件可能以 `src\a.ts` 和 `src/a.ts` 两种面貌出现,
352
+ * 不归一的话台账里会有两个 key,回滚只还原其中一个。
353
+ */
354
+ export function normalizedPatchPath(path) {
355
+ const text = typeof path === 'string' ? path : String(path ?? '')
356
+ return text.replace(/\\/gu, '/').replace(/^\.\//u, '').trim()
357
+ }
358
+
359
+ /** 文件的 sha256,不存在返回 null。 */
360
+ async function fileSha256(path) {
361
+ try {
362
+ const data = await readFile(path)
363
+ return createHash('sha256').update(data).digest('hex')
364
+ } catch {
365
+ return null
366
+ }
367
+ }
368
+
369
+ /** 同步版:用于追加写时的 beforeSha(此时文件还没被改)。 */
370
+ function fileSha256Sync(path) {
371
+ try {
372
+ const data = readFileSync(path)
373
+ return createHash('sha256').update(data).digest('hex')
374
+ } catch {
375
+ return null
376
+ }
377
+ }
378
+
379
+ /**
380
+ * 往台账追加一行。
381
+ *
382
+ * 用 appendFileSync 同步写:实施段写文件和台账追加必须原子,
383
+ * 中间不能被中断——否则文件改了但台账没记,那条改动就丢了。
384
+ */
385
+ export function appendLedgerEntry(cwd, project, entry) {
386
+ const path = ledgerPath(cwd, project)
387
+ try {
388
+ mkdirSync(ledgerDir(cwd, project), { recursive: true })
389
+ const line = JSON.stringify(entry) + '\n'
390
+ appendFileSync(path, line, 'utf8')
391
+ } catch {
392
+ // 台账写失败不该中断实施段——但要在日志里留痕。
393
+ }
394
+ }
395
+
396
+ /** mkdirSync 的引入(appendLedgerEntry 用)。 */
397
+ import { mkdirSync } from 'node:fs'
398
+
399
+ /**
400
+ * 读台账,返回条目数组。坏 JSON 行不静默跳过:报错并列出行号。
401
+ */
402
+ export function readLedger(cwd, project) {
403
+ const path = ledgerPath(cwd, project)
404
+ let text
405
+ try {
406
+ text = readFileSync(path, 'utf8')
407
+ } catch {
408
+ return []
409
+ }
410
+ const lines = text.split(/\r?\n/u).filter(line => line.trim() !== '')
411
+ const entries = []
412
+ const bad = []
413
+ for (let i = 0; i < lines.length; i += 1) {
414
+ try {
415
+ const obj = JSON.parse(lines[i])
416
+ if (obj !== null && typeof obj === 'object' && !Array.isArray(obj)) {
417
+ entries.push(obj)
418
+ } else {
419
+ bad.push({ line: i + 1, text: lines[i].slice(0, 100) })
420
+ }
421
+ } catch {
422
+ bad.push({ line: i + 1, text: lines[i].slice(0, 100) })
423
+ }
424
+ }
425
+ if (bad.length > 0) {
426
+ const msg = `台账有 ${bad.length} 行坏 JSON:` + bad.map(b => `第 ${b.line} 行(${b.text})`).join('、')
427
+ throw new Error(msg)
428
+ }
429
+ return entries
430
+ }
431
+
432
+ /**
433
+ * 记录实施段的一次文件写入。
434
+ *
435
+ * 关键在 `beforeCommit`:这是实施开始前那张快照的 commit。
436
+ *
437
+ * 以前这里只算 beforeSha(文件内容的哈希),回滚时拿着一个哈希毫无用处——
438
+ * 哈希不是 git object,没法 checkout,于是「回滚」只能比对「当前内容是不是
439
+ * 和写入前一模一样」,是就报「已一致」,不是就报「已被手改,不能还原」。
440
+ * 也就是说它从来没真正还原过任何文件,却每次都追加一条 reverted 记录。
441
+ *
442
+ * 现在台账记的是「这一批写入之前工作区长什么样」(commit),回滚直接
443
+ * `git checkout <beforeCommit> -- <path>`,内容来源是快照仓库,可靠。
444
+ *
445
+ * @param beforeCommit 实施前那张快照的 commit;为空时回滚会明确报「没有内容来源」
446
+ */
447
+ export async function recordFileWrite(cwd, project, filePath, batchId, stage, index, beforeCommit = '') {
448
+ const abs = isAbsolute(filePath) ? filePath : join(cwd, filePath)
449
+ const rel = normalizedPatchPath(isAbsolute(filePath) ? relative(cwd, filePath) : filePath)
450
+ const beforeSha = await fileSha256(abs)
451
+ return {
452
+ index,
453
+ batchId,
454
+ stage,
455
+ path: rel,
456
+ beforeSha,
457
+ beforeCommit: typeof beforeCommit === 'string' ? beforeCommit : '',
458
+ afterSha: null,
459
+ status: 'pending',
460
+ ts: nowIso(),
461
+ }
462
+ }
463
+
464
+ /** 写完文件后补上 afterSha 并追加到台账。 */
465
+ export function commitLedgerEntry(cwd, project, entry, afterSha) {
466
+ const committed = { ...entry, afterSha, status: 'applied', ts: nowIso() }
467
+ appendLedgerEntry(cwd, project, committed)
468
+ return committed
469
+ }
470
+
471
+ /**
472
+ * 按最后一批 applied 条目还原。
473
+ *
474
+ * 只动台账里的 path,不在台账里的文件原样保留。
475
+ *
476
+ * 内容来源是 `beforeCommit`(实施前那张快照)。三件事必须分清:
477
+ *
478
+ * plan 这批要还原哪些文件,各自能还原到什么程度——纯计算,不动磁盘
479
+ * apply 真去 checkout,只有 dryRun=false 才走
480
+ *
481
+ * 以前这两件事揉在一起,dryRun 在 ledger 分支根本没被读,于是「先看看会动什么」
482
+ * 和「真动」是同一条路径。现在 dryRun 走 plan,一条文件都不写。
483
+ *
484
+ * @param dryRun 默认 true——和 project_rollback 的工具默认值对齐。
485
+ * 要真回滚必须显式传 false,不能靠「忘了传」触发写操作。
486
+ */
487
+ export async function rollbackByLedger(cwd, project, { dryRun = true } = {}) {
488
+ const entries = readLedger(cwd, project)
489
+ if (entries.length === 0) {
490
+ return { ok: false, reason: '台账为空,没有可回滚的条目' }
491
+ }
492
+ const applied = entries.filter(e => e.status === 'applied')
493
+ if (applied.length === 0) {
494
+ return { ok: false, reason: '台账里没有 applied 条目' }
495
+ }
496
+ // 按 batchId 分组,取最后那个 batch
497
+ const batchIds = [...new Set(applied.map(e => e.batchId))]
498
+ const lastBatch = batchIds[batchIds.length - 1]
499
+ const batchEntries = applied.filter(e => e.batchId === lastBatch)
500
+
501
+ // ── plan:算这一批每个文件会怎么动 ──
502
+ //
503
+ // 判断「要不要还原」不看 beforeSha:那个字段在实施后才写,值其实是写入后的。
504
+ // 唯一可信的旧内容来源是 beforeCommit 那张快照。
505
+ //
506
+ // 比「当前 == 快照」用 git 自己的 blob 哈希(`git hash-object` 算的是同一种
507
+ // sha1),不走 cat-file 二进制管道——那条路会被编码转换弄坏内容。
508
+ const plans = []
509
+ for (const entry of batchEntries) {
510
+ const abs = join(cwd, entry.path)
511
+ const currentSha = await fileSha256(abs).catch(() => null)
512
+ const hasCommit = typeof entry.beforeCommit === 'string' && entry.beforeCommit !== ''
513
+
514
+ if (!hasCommit) {
515
+ // 老条目,没记快照:没有内容来源,明确说还原不了,不假装成功
516
+ if (currentSha === null) {
517
+ plans.push({ entry, action: 'unchanged', note: '文件已不在,且台账没记快照' })
518
+ } else {
519
+ plans.push({
520
+ entry,
521
+ action: 'blocked',
522
+ note: '台账没记实施前的快照(老版本写的条目),没有内容来源,不能自动还原',
523
+ })
524
+ }
525
+ continue
526
+ }
527
+
528
+ // 快照里有没有这个文件
529
+ const inTree = await snapshotCommand(cwd, project, ['rev-parse', '--verify', '--quiet', `${entry.beforeCommit}:${entry.path}`])
530
+ if (!inTree.ok) {
531
+ // 快照里没有 = 写入前它不存在 → 还原就是删掉
532
+ plans.push({
533
+ entry,
534
+ action: currentSha === null ? 'unchanged' : 'delete',
535
+ note: currentSha === null ? '文件已不在,无需处理' : '删除(写入前不存在)',
536
+ })
537
+ continue
538
+ }
539
+
540
+ if (currentSha === null) {
541
+ plans.push({ entry, action: 'restore', note: `文件已删,从 ${entry.beforeCommit.slice(0, 8)} 重建` })
542
+ continue
543
+ }
544
+
545
+ // 当前文件内容的 git sha1,跟快照里那个 blob 直接比
546
+ const currentGitSha = await snapshotCommand(cwd, project, ['hash-object', entry.path])
547
+ if (currentGitSha.ok && currentGitSha.stdout.trim() === inTree.stdout.trim()) {
548
+ plans.push({ entry, action: 'unchanged', note: '已与写入前一致' })
549
+ continue
550
+ }
551
+ plans.push({ entry, action: 'restore', note: `还原到 ${entry.beforeCommit.slice(0, 8)}` })
552
+ }
553
+
554
+ // ── 干跑:到此为止 ──
555
+ if (dryRun) {
556
+ return {
557
+ ok: true,
558
+ dryRun: true,
559
+ batchId: lastBatch,
560
+ count: batchEntries.length,
561
+ restored: plans.filter(p => p.action === 'restore' || p.action === 'delete').map(p => `${p.entry.path}(${p.note})`),
562
+ failed: plans.filter(p => p.action === 'blocked').map(p => `${p.entry.path}(${p.note})`),
563
+ plan: plans.map(p => ({ path: p.entry.path, action: p.action, note: p.note })),
564
+ }
565
+ }
566
+
567
+ // ── apply:真动磁盘 ──
568
+ const restored = []
569
+ const failed = []
570
+ for (const item of plans) {
571
+ const { entry } = item
572
+ const abs = join(cwd, entry.path)
573
+ if (item.action === 'unchanged') {
574
+ restored.push(`${entry.path}(已一致)`)
575
+ continue
576
+ }
577
+ if (item.action === 'blocked') {
578
+ failed.push(`${entry.path}(${item.note})`)
579
+ continue
580
+ }
581
+ try {
582
+ if (item.action === 'delete') {
583
+ await rm(abs, { force: true })
584
+ restored.push(`${entry.path}(删除)`)
585
+ } else {
586
+ // 从实施前那张快照把这个文件 checkout 回来
587
+ const result = await snapshotCommand(cwd, project, ['checkout', entry.beforeCommit, '--', entry.path], { timeoutMs: 300000 })
588
+ if (!result.ok) {
589
+ failed.push(`${entry.path}(快照里 checkout 失败:${(result.stderr || result.message || '').trim().slice(0, 80)})`)
590
+ continue
591
+ }
592
+ restored.push(`${entry.path}(还原到 ${entry.beforeCommit.slice(0, 8)})`)
593
+ }
594
+ // 只有真动过文件的才记 reverted
595
+ appendLedgerEntry(cwd, project, {
596
+ index: entry.index,
597
+ batchId: entry.batchId,
598
+ stage: entry.stage,
599
+ path: entry.path,
600
+ beforeSha: entry.afterSha,
601
+ afterSha: entry.beforeSha,
602
+ beforeCommit: entry.beforeCommit,
603
+ status: 'reverted',
604
+ rollbackOf: entry.index,
605
+ ts: nowIso(),
606
+ })
607
+ } catch (error) {
608
+ failed.push(`${entry.path}(${messageOf(error)})`)
609
+ }
610
+ }
611
+ return {
612
+ ok: failed.length === 0,
613
+ dryRun: false,
614
+ batchId: lastBatch,
615
+ count: batchEntries.length,
616
+ restored,
617
+ failed,
618
+ plan: plans.map(p => ({ path: p.entry.path, action: p.action, note: p.note })),
619
+ }
620
+ }
621
+
622
+ /**
623
+ * 检查 diff 里改的文件是否都在台账里。
624
+ * 不在台账里的算「越界改动」——不是实施段写的,是别的来源改的。
625
+ */
626
+ export function checkLedgerCoverage(cwd, project, diffPaths) {
627
+ const entries = readLedger(cwd, project)
628
+ const ledgerPaths = new Set(entries
629
+ .filter(e => e.status === 'applied')
630
+ .map(e => normalizedPatchPath(e.path)))
631
+ const diff = Array.isArray(diffPaths) ? diffPaths : []
632
+ const outOfBounds = diff
633
+ .map(p => normalizedPatchPath(p))
634
+ .filter(p => !ledgerPaths.has(p))
635
+ return {
636
+ total: diff.length,
637
+ inLedger: diff.length - outOfBounds.length,
638
+ outOfBounds,
639
+ }
277
640
  }
278
641
 
279
642
  /**
@@ -374,11 +737,21 @@ async function attemptDiff(cwd, project, attempts, limitChars = DIFF_LIMIT_CHARS
374
737
  * 按 STAGE_IO 拼出某一阶该看到的全部上下文。
375
738
  * extraKeys 只给返工用(实施阶额外读上一轮的 QA_Report)。
376
739
  * 读不到的文件直接跳过,不报错——缺产物由调用方按各自的规则处理。
740
+ *
741
+ * 传了 flow 就按 flow.yaml 里声明的 reads 读;不传走内置四阶。两条路
742
+ * 拿到的都是 ARTIFACT 的 key,下游 readArtifact 不用改。
377
743
  */
378
- async function stageContext(cwd, project, stage, extraKeys = []) {
379
- const spec = STAGE_IO[stage]
380
- const keys = [...spec.reads, ...extraKeys]
744
+ async function stageContext(cwd, project, stage, extraKeys = [], flow = undefined, contractText = undefined) {
745
+ const keys = flow === undefined
746
+ ? [...(STAGE_IO[stage]?.reads ?? []), ...extraKeys]
747
+ : [...phaseReadKeys(flow.phases?.[stage - 1]), ...extraKeys]
381
748
  const parts = []
749
+ // 契约排在最前面:它是这一阶的前提,不是附录。
750
+ // 放最前还有一个实际好处——上下文被截断时,截掉的是后面的产物,不是约定。
751
+ //
752
+ // 收参数而不是自己读:这个函数是纯拼装,读盘交给调用方。自己读的话它就跟
753
+ // 契约那套(哈希、上限)绑死了,单测也抠不出来单独跑。
754
+ if (typeof contractText === 'string' && contractText !== '') parts.push(contractText)
382
755
  for (const key of keys) {
383
756
  let text = await readArtifact(cwd, project, ARTIFACT[key])
384
757
  if (text === undefined) continue
@@ -440,24 +813,28 @@ class StopRequested extends Error {
440
813
  }
441
814
 
442
815
  /** Resolve the parent conversation's working directory without a hard dependency. */
443
- function cwdOf(ctx, agent) {
816
+ export function cwdOf(ctx, agent) {
444
817
  const candidates = []
445
818
  if (agent !== undefined) {
819
+ // 会话自己记的 cwd 排第一:那才是用户在左边工作区里选的那个文件夹。
820
+ //
821
+ // workingDirectory 服务排在后面当兜底——它有时候给的是「进程启动目录」,
822
+ // 不是会话目录。照它算,用户在左边切到 D:\我的项目,插件拿到的还是
823
+ // C:\...\default-workspace,于是工作流建在默认工作区、状态栏也显示那儿。
824
+ // 用户报的「只有默认工作区」就是这个。
825
+ const recorded = agent.session?.header?.cwd
826
+ if (typeof recorded === 'string' && isAbsolute(recorded)) candidates.push(recorded)
446
827
  const workingDirectory = ctx.get('workingDirectory')
447
828
  if (workingDirectory !== undefined) {
448
829
  try {
449
830
  candidates.push(workingDirectory.get(agent.session))
450
831
  } catch {
451
- // 拿不到就靠下面那个来源
832
+ // 拿不到就靠上面那个来源
452
833
  }
453
834
  }
454
- const recorded = agent.session?.header?.cwd
455
- if (typeof recorded === 'string' && isAbsolute(recorded)) candidates.push(recorded)
456
835
  }
457
836
  const valid = candidates.filter(item => typeof item === 'string' && item !== '')
458
- // 两个来源打架时,优先选那个真在「工作流」里的。
459
- // workingDirectory 有时给的是进程启动目录而不是会话目录,照它算就会得出
460
- // 「工作流目录也算不在工作流里」——用户看到的状态栏永远是「未启用」。
837
+ // 两个来源打架时,优先选那个真在「工作流」里的——那是明确的意图信号。
461
838
  const inFlow = valid.find(item => item.split(/[\\/]+/u).includes(FLOW_DIR_NAME))
462
839
  return inFlow ?? valid[0] ?? process.cwd()
463
840
  }
@@ -475,16 +852,20 @@ function cwdOf(ctx, agent) {
475
852
  * turn); stages 2-4 are not (three child agents, three models, snapshots), and a
476
853
  * plan built on a guessed intent multiplies the guess across every stage.
477
854
  */
478
- const INTENT_CONFIDENCE_FLOOR = 95
855
+ /**
856
+ * 门槛只有一个数,来自 gate.mjs 的 SCORE_FLOOR。
857
+ *
858
+ * 以前这里另写了一个 95,两处同时改的时候总会漏一处——门控一处放行、一处拦,
859
+ * 用户看到的是「有时候问得出来,有时候问不出来」。
860
+ */
861
+ const INTENT_CONFIDENCE_FLOOR = SCORE_FLOOR
479
862
 
480
- /** 五个硬性维度,顺序即提示词和 UI 的展示顺序。 */
481
- const BLINDSPOT_LABELS = {
482
- permissions: '权限',
483
- concurrency: '并发',
484
- edge_cases: '异常边界',
485
- stack: '技术栈',
486
- data_flow: '数据流向',
487
- }
863
+ /**
864
+ * 五个硬性维度,顺序即提示词和 UI 的展示顺序。
865
+ *
866
+ * 名字同样只有一份定义(gate.DIMENSIONS),这里只是摊平成一张查表。
867
+ */
868
+ const BLINDSPOT_LABELS = Object.fromEntries(DIMENSIONS.map(dim => [dim.key, dim.label]))
488
869
 
489
870
  /**
490
871
  * 盲区清单的硬门槛:五个维度都要给出够具体的结论,空一个或写一句空话就一票否决。
@@ -492,38 +873,50 @@ const BLINDSPOT_LABELS = {
492
873
  * 这一条排在 override 前面,是刻意的:用户说「就按这个做」放开的是
493
874
  * 「把握够不够」,不是「盲区有没有问」。两件事混在一起,override 就成了
494
875
  * 绕过一切的万能钥匙,这正是要堵的漏洞。
876
+ *
877
+ * 判定本身走 gate.blindspotGaps——那是全插件唯一一份五维判定。
878
+ * 这里只负责把结果翻译成一句人话并抛出去。
495
879
  */
496
880
  function assertNoEmptyBlindspots(blindspots) {
497
- const record = blindspots !== null && typeof blindspots === 'object' && !Array.isArray(blindspots)
498
- ? blindspots
499
- : {}
500
- const empty = []
501
- const vague = []
502
- for (const key of DIMENSION_KEYS) {
503
- const value = record[key]
504
- const line = typeof value === 'string' ? value.trim() : ''
505
- if (line === '') {
506
- empty.push(key)
507
- continue
508
- }
509
- // 「已确认」「OK」这类凑数的结论,去掉标点后不够长,也算没写。
510
- if (line.replace(/[\s\p{P}]/gu, '').length < MIN_CONCLUSION_LENGTH) vague.push(key)
511
- }
512
- if (empty.length > 0 || vague.length > 0) {
513
- const parts = []
514
- if (empty.length > 0) parts.push(`还没结论:${empty.map(key => BLINDSPOT_LABELS[key]).join('、')}`)
515
- if (vague.length > 0) parts.push(`写得太笼统,要说具体:${vague.map(key => BLINDSPOT_LABELS[key]).join('、')}`)
516
- throw new Error(
517
- [
518
- `盲区清单没过门控——${parts.join(';')}`,
519
- '',
520
- '下一步只有两条路:',
521
- '· 用 ask_user_question 一个一个问掉,问一个填一条,每条写成一句真结论;',
522
- '· 确实问不出来、且做错也能承受的,写进 assumptions 并写清验收时怎么核。',
523
- 'override 只管「把握够不够」,管不了「盲区有没有问」——这两件事分开判。',
524
- ].join('\n'),
525
- )
881
+ const gap = blindspotGaps(blindspots)
882
+ if (gap.gaps === 0) return
883
+ const parts = []
884
+ if (gap.empty.length > 0) parts.push(`还没结论:${gap.empty.map(dimensionLabel).join('、')}`)
885
+ if (gap.vague.length > 0) {
886
+ parts.push(`写得太笼统,要说具体:${gap.vague.map(key => `${dimensionLabel(key)}(「${gap.lines[key]}」)`).join('、')}`)
526
887
  }
888
+ throw new Error(
889
+ [
890
+ `盲区清单没过门控——${parts.join(';')}`,
891
+ '',
892
+ '下一步只有两条路:',
893
+ '· 用 ask_user_question 一个一个问掉,问一个填一条,每条写成一句真结论;',
894
+ '· 确实问不出来、且做错也能承受的,写进 assumptions 并写清验收时怎么核。',
895
+ 'override 只管「把握够不够」,管不了「盲区有没有问」——这两件事分开判。',
896
+ ].join('\n'),
897
+ )
898
+ }
899
+
900
+ /**
901
+ * 每个会话最近一次交上来的自查表。
902
+ *
903
+ * 前置门控(ctx.tools.guard)在工具调用前跑,拿不到 project_run 的参数,
904
+ * 只能从这里取。按 agent 对象做 WeakMap 键:会话销毁它自己就没了,不用管清理。
905
+ *
906
+ * 只有 project_run 真的收到自查表时才写一条;没写过的会话读出来是 undefined,
907
+ * evaluateReadiness 会判 missing——那是「还没开始问」,不是「问错了」。
908
+ */
909
+ const readinessByAgent = new WeakMap()
910
+
911
+ function rememberReadiness(agent, readiness) {
912
+ if (agent === undefined || agent === null || typeof agent !== 'object') return
913
+ readinessByAgent.set(agent, readiness)
914
+ }
915
+
916
+ function lastReadinessOf(exec) {
917
+ const agent = exec?.agent
918
+ if (agent === undefined || agent === null || typeof agent !== 'object') return undefined
919
+ return readinessByAgent.get(agent)
527
920
  }
528
921
 
529
922
  /** Reject an intent that has not converged, with a message that says what to do. */
@@ -604,10 +997,222 @@ function assertIntentConverged(confirmation) {
604
997
  }
605
998
  }
606
999
 
1000
+ /** 面板顶栏要显示版本号。读一次就够,装好之后不会变。 */
1001
+ const PKG_VERSION = (() => {
1002
+ try {
1003
+ const pkg = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8'))
1004
+ return typeof pkg.version === 'string' ? pkg.version : ''
1005
+ } catch {
1006
+ return ''
1007
+ }
1008
+ })()
1009
+
607
1010
  function stateDir(cwd, project) {
608
1011
  return join(cwd, '.project-flow', project)
609
1012
  }
610
1013
 
1014
+ // ── 完成契约 ────────────────────────────────────────────────────
1015
+ //
1016
+ // 长任务跨压缩之后,模型容易忘掉第 1 阶确认过的要求和禁改范围,后半段
1017
+ // 开始自由发挥。这里把「要做什么、不许碰什么、什么算做完」存成一份文件,
1018
+ // 每一阶都重新塞进 prompt——压缩带走的是对话,带不走磁盘。
1019
+ //
1020
+ // 长度上限 1200 字符是硬的:这段要进每一阶的 prompt,太长就把真正的内容挤掉了。
1021
+
1022
+ const CONTRACT_FILE = 'contract.json'
1023
+ const CONTRACT_MAX_CHARS = 1200
1024
+
1025
+ const filled = value => typeof value === 'string' && value.trim() !== ''
1026
+
1027
+ /**
1028
+ * 契约指纹。
1029
+ *
1030
+ * 只覆盖三份内容,不含创建时间之类的噪音——同内容必须同指纹,
1031
+ * 否则「契约被换了」会天天误报。
1032
+ */
1033
+ export function contractSha(contract) {
1034
+ const basis = JSON.stringify({
1035
+ requirements: Array.isArray(contract?.requirements) ? contract.requirements : [],
1036
+ forbidden: Array.isArray(contract?.forbidden) ? contract.forbidden : [],
1037
+ doneWhen: Array.isArray(contract?.doneWhen) ? contract.doneWhen : [],
1038
+ })
1039
+ return createHash('sha256').update(basis, 'utf8').digest('hex')
1040
+ }
1041
+
1042
+ export async function readContract(cwd, project) {
1043
+ try {
1044
+ const parsed = JSON.parse(await readFile(join(stateDir(cwd, project), CONTRACT_FILE), 'utf8'))
1045
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return undefined
1046
+ return parsed
1047
+ } catch {
1048
+ return undefined
1049
+ }
1050
+ }
1051
+
1052
+ export async function writeContract(cwd, project, input) {
1053
+ const dir = stateDir(cwd, project)
1054
+ await mkdir(dir, { recursive: true })
1055
+ const next = {
1056
+ requirements: Array.isArray(input?.requirements) ? input.requirements.filter(filled).map(item => item.trim()) : [],
1057
+ forbidden: Array.isArray(input?.forbidden) ? input.forbidden.filter(filled).map(item => item.trim()) : [],
1058
+ doneWhen: Array.isArray(input?.doneWhen) ? input.doneWhen.filter(filled).map(item => item.trim()) : [],
1059
+ }
1060
+ next.sha = contractSha(next)
1061
+ await writeFileAtomic(join(dir, CONTRACT_FILE), `${JSON.stringify(next, null, 2)}\n`)
1062
+ return next
1063
+ }
1064
+
1065
+ /**
1066
+ * 把契约压成一段 prompt。
1067
+ *
1068
+ * 超长时的砍法有顺序:先砍「算做完」,再砍要求(从最后一条往前砍),
1069
+ * 禁改项最后砍。理由是禁改项一旦被砍掉,越界就没人拦得住——那是这份契约
1070
+ * 唯一能造成实际损失的地方,宁可少讲两条要求。
1071
+ */
1072
+ export function contractBlock(contract) {
1073
+ if (contract === undefined || contract === null) return ''
1074
+ const reqs = Array.isArray(contract.requirements) ? contract.requirements : []
1075
+ const forbidden = Array.isArray(contract.forbidden) ? contract.forbidden : []
1076
+ const done = Array.isArray(contract.doneWhen) ? contract.doneWhen : []
1077
+ if (reqs.length === 0 && forbidden.length === 0 && done.length === 0) return ''
1078
+
1079
+ const build = (r, f, d) => [
1080
+ '## 这次任务的约定(每阶都重贴,压缩后也还在)',
1081
+ ...(r.length === 0 ? [] : ['要求:', ...r.map((line, index) => `${index + 1}. ${line}`)]),
1082
+ ...(d.length === 0 ? [] : ['算做完:', ...d.map(line => `- ${line}`)]),
1083
+ ...(f.length === 0 ? [] : ['不许碰(碰了要回滚):', ...f.map(line => `- ${line}`)]),
1084
+ ].join('\n')
1085
+
1086
+ let text = build(reqs, forbidden, done)
1087
+ if (text.length <= CONTRACT_MAX_CHARS) return text
1088
+
1089
+ text = build(reqs, forbidden, [])
1090
+ if (text.length <= CONTRACT_MAX_CHARS) return text
1091
+
1092
+ let keep = reqs.length
1093
+ while (keep > 0 && build(reqs.slice(0, keep), forbidden, []).length > CONTRACT_MAX_CHARS) keep -= 1
1094
+ text = build(reqs.slice(0, keep), forbidden, [])
1095
+ if (text.length <= CONTRACT_MAX_CHARS) return text
1096
+
1097
+ // 要求砍光还超,就只剩禁改项。这条再长也不砍——它是底线。
1098
+ text = ['## 这次任务的约定', '不许碰(碰了要回滚):', ...forbidden.map(line => `- ${line}`)].join('\n')
1099
+ return text.length <= CONTRACT_MAX_CHARS ? text : text.slice(0, CONTRACT_MAX_CHARS)
1100
+ }
1101
+
1102
+ /**
1103
+ * 判断一个路径有没有踩到禁改项。
1104
+ *
1105
+ * 比的是「规范化之后的前缀或相等」——用户写 `src/legacy`,那 `src/legacy/a.ts`
1106
+ * 也算踩。反过来写 `src/legacy/a.ts` 不该把整个目录判进来。
1107
+ * 反斜杠统一成正斜杠,不然同一个路径在 Windows 上会有两种写法。
1108
+ */
1109
+ export function hitsForbidden(filePath, forbidden) {
1110
+ if (typeof filePath !== 'string' || filePath === '') return ''
1111
+ const norm = value => value.replace(/\\+/gu, '/').replace(/\/+$/u, '').toLowerCase()
1112
+ const target = norm(filePath)
1113
+ for (const entry of Array.isArray(forbidden) ? forbidden : []) {
1114
+ const rule = norm(String(entry))
1115
+ if (rule === '') continue
1116
+ if (target === rule || target.startsWith(`${rule}/`)) return String(entry)
1117
+ }
1118
+ return ''
1119
+ }
1120
+
1121
+ // ── 声明式流程 ──────────────────────────────────────────────────
1122
+ //
1123
+ // 四阶以前是写死的:想加一个「安全评审」阶,或者换某一阶读哪些文件,
1124
+ // 得改 index.js。现在项目目录里放一份 flow.yaml 就能改,代码只负责校验和执行。
1125
+ //
1126
+ // 向后兼容是硬要求:没有 flow.yaml 时走 BUILTIN_FLOW,行为和 0.8.x 逐条一致。
1127
+ // 所以 STAGE_IO 留着不动——它是内置四阶的「不装 flow.yaml 时的那份」,
1128
+ // 也是解析不出 flow.yaml 时的退路。
1129
+
1130
+ /** 项目自己的 flow.yaml。和 Requirement.md 放一起,一个项目一份。 */
1131
+ function flowPath(cwd, project) {
1132
+ return join(stateDir(cwd, project), 'flow.yaml')
1133
+ }
1134
+
1135
+ /** 产物文件名 → ARTIFACT 的 key。flow.yaml 里写文件名,内部认 key。 */
1136
+ const ARTIFACT_KEY_BY_FILE = new Map(
1137
+ Object.entries(ARTIFACT).map(([key, fileName]) => [fileName, key]),
1138
+ )
1139
+
1140
+ /**
1141
+ * 读某个项目生效的流程。
1142
+ *
1143
+ * 三种结果:
1144
+ * - 没有 flow.yaml:返回内置四阶,`configured=false`
1145
+ * - 有且合法:返回它,`configured=true`
1146
+ * - 有但不合法:返回内置四阶并带上 errors——调用方决定是拒跑还是照跑。
1147
+ * 只在 project_run 入口拒,别的路径(状态栏、诊断)不该因为配置写错就整个不可用。
1148
+ */
1149
+ async function resolveFlow(cwd, project) {
1150
+ const file = flowPath(cwd, project)
1151
+ let text
1152
+ try {
1153
+ text = await readFile(file, 'utf8')
1154
+ } catch {
1155
+ return { flow: BUILTIN_FLOW, configured: false, errors: [], warnings: [] }
1156
+ }
1157
+ const result = loadFlow(text)
1158
+ if (!result.ok) {
1159
+ return { flow: BUILTIN_FLOW, configured: true, errors: result.errors, warnings: result.warnings }
1160
+ }
1161
+ return {
1162
+ flow: { process: result.doc.process, phases: result.phases },
1163
+ configured: true,
1164
+ errors: [],
1165
+ warnings: result.warnings,
1166
+ }
1167
+ }
1168
+
1169
+ /**
1170
+ * 把 flow.yaml 里写的文件名换算成 ARTIFACT 的 key。
1171
+ *
1172
+ * 认不出来的是 glob(比如 `src/**`)——那不是产物,不参与「这一阶该读到什么」,
1173
+ * 直接跳过。跳过不是错误:flow.yaml 允许声明它读取代码目录,只是这一层喂不了。
1174
+ */
1175
+ function phaseReadKeys(phase) {
1176
+ if (phase === undefined || phase === null || !Array.isArray(phase.reads)) return []
1177
+ const keys = []
1178
+ for (const entry of phase.reads) {
1179
+ if (typeof entry !== 'string') continue
1180
+ const key = ARTIFACT_KEY_BY_FILE.get(entry) ?? ARTIFACT_KEY_BY_FILE.get(basename(entry))
1181
+ if (key !== undefined) keys.push(key)
1182
+ }
1183
+ return keys
1184
+ }
1185
+
1186
+ /**
1187
+ * 某一阶到底用哪个模型。
1188
+ *
1189
+ * 优先级:flow.yaml 里 phase 的 `model` > project-flow.json 里的 > 继承主对话。
1190
+ * 三者都空就是「跟主对话走」——空串在这个插件里一直是这个意思,不是「没设」。
1191
+ *
1192
+ * 只在调用点算,不缓存到模块变量:两个项目可以同时跑(maxConcurrentProjects=2),
1193
+ * 一个项目级的状态放在模块上就会串。
1194
+ */
1195
+ export function stageModelOf(settings, flow, stageNo, fallback) {
1196
+ const phase = flow?.phases?.[stageNo - 1]
1197
+ const configured = phase !== undefined && phase !== null && typeof phase.model === 'object' && phase.model !== null
1198
+ ? phase.model
1199
+ : null
1200
+ const fromPhase = key => {
1201
+ if (configured === null) return ''
1202
+ const value = configured[key]
1203
+ return typeof value === 'string' ? value.trim() : ''
1204
+ }
1205
+ const phaseProvider = fromPhase('provider')
1206
+ const phaseModel = fromPhase('model')
1207
+ return {
1208
+ provider: settings.provider,
1209
+ llmProvider: phaseProvider !== '' ? phaseProvider : fallback.llmProvider,
1210
+ model: phaseModel !== '' ? phaseModel : fallback.model,
1211
+ // 这个模型是 flow.yaml 指定的,还是配置里来的——回退日志要说清是谁的锅。
1212
+ source: phaseModel !== '' ? 'flow.yaml' : fallback.llmProvider === '' && fallback.model === '' ? 'inherit' : 'config',
1213
+ }
1214
+ }
1215
+
611
1216
  /**
612
1217
  * Reject a project name that would escape `.project-flow`.
613
1218
  *
@@ -706,23 +1311,66 @@ const FLOW_DIR_NAME = '工作流'
706
1311
  * 第一次在普通目录开工时,插件自己把「工作流」建出来,然后到里面干活——
707
1312
  * 边界还在,但那一步手工操作没了。
708
1313
  */
709
- const FLOW_GATE_MODES = ['strict', 'off']
1314
+ const FLOW_GATE_MODES = ['off', 'auto', 'strict']
710
1315
 
711
- function flowModeOf(settings) {
1316
+ export function flowModeOf(settings) {
712
1317
  const raw = typeof settings?.flowGate === 'string' ? settings.flowGate.trim().toLowerCase() : ''
713
- return FLOW_GATE_MODES.includes(raw) ? raw : 'strict'
1318
+ return FLOW_GATE_MODES.includes(raw) ? raw : 'off'
1319
+ }
1320
+
1321
+ /**
1322
+ * 这个路径是不是落在系统盘上。
1323
+ *
1324
+ * Windows 上系统盘就是 `%SystemDrive%`(通常 C:)。别的平台没这个概念,
1325
+ * 一律返回 false——这条规则是给 Windows 用户省系统盘用的。
1326
+ */
1327
+ export function onSystemDrive(target) {
1328
+ if (process.platform !== 'win32') return false
1329
+ const system = (process.env.SystemDrive ?? 'C:').replace(/[\\/]+$/u, '').toLowerCase()
1330
+ const normalized = String(target ?? '').replace(/\\+/gu, '/').toLowerCase()
1331
+ return normalized === system.toLowerCase() || normalized.startsWith(`${system.toLowerCase()}/`)
1332
+ }
1333
+
1334
+ /**
1335
+ * 找一个能放数据的盘。
1336
+ *
1337
+ * 从 D 往后试:C 装系统和缓存,项目数据不该放那儿。都没有就返回 undefined,
1338
+ * 调用方据此留在原地——单盘机器上没得选,报错也没用。
1339
+ */
1340
+ export function pickDataDrive() {
1341
+ if (process.platform !== 'win32') return undefined
1342
+ for (const letter of ['D', 'E', 'F', 'G']) {
1343
+ try {
1344
+ if (existsSync(`${letter}:\\`)) return `${letter}:`
1345
+ } catch {
1346
+ // 这个盘符不可访问,试下一个
1347
+ }
1348
+ }
1349
+ return undefined
714
1350
  }
715
1351
 
716
1352
  /**
717
1353
  * 工作模式的地盘在哪(只有 strict 模式用它算「应该在的目录」)。
718
1354
  *
719
- * `flowRoot` 配了绝对路径就只认那个路径及其子目录;没配就认 cwd 里
720
- * 名为「工作流」的那一段(cwd 本身叫工作流,或者在某个 …/工作流/ 之下)。
1355
+ * `flowRoot` 配了绝对路径就只认那个路径及其子目录;没配就看 cwd 落在哪个盘——
1356
+ * 系统盘上不建,见下面的说明。
721
1357
  */
722
- function flowRootOf(cwd, settings) {
1358
+ export function flowRootOf(cwd, settings) {
723
1359
  const configured = typeof settings.flowRoot === 'string' ? settings.flowRoot.trim() : ''
724
1360
  if (configured !== '' && isAbsolute(configured)) return resolve(configured)
725
- return join(resolve(cwd), configured === '' ? FLOW_DIR_NAME : configured)
1361
+ const base = resolve(cwd)
1362
+ // 不往系统盘上建工作流。
1363
+ //
1364
+ // 用户的默认工作区就在 C 盘(DSH 装在 C,默认工作区跟着走),于是
1365
+ // 「谁的工作区就在谁下面建」等于把项目数据全塞进系统盘。他明确说了
1366
+ // 「默认不要在此盘」——那就是别在 C 盘上建。
1367
+ //
1368
+ // 有别的盘就挪过去(<盘>:\工作流),单盘机器上留在原地。
1369
+ if (onSystemDrive(base)) {
1370
+ const data = pickDataDrive()
1371
+ if (data !== undefined) return join(`${data}${sep}`, FLOW_DIR_NAME)
1372
+ }
1373
+ return join(base, configured === '' ? FLOW_DIR_NAME : configured)
726
1374
  }
727
1375
 
728
1376
  /**
@@ -747,7 +1395,7 @@ function flowRootConfigured(settings) {
747
1395
  * 所以:配置根下面如果真有一个「工作流」且里面已经有 .project-flow,
748
1396
  * 就指到那一层;否则才用配置根本身。
749
1397
  */
750
- function flowRootTargetOf(cwd, settings) {
1398
+ export function flowRootTargetOf(cwd, settings) {
751
1399
  const root = flowRootOf(cwd, settings)
752
1400
  try {
753
1401
  const nested = join(root, FLOW_DIR_NAME)
@@ -761,22 +1409,25 @@ function flowRootTargetOf(cwd, settings) {
761
1409
  /**
762
1410
  * 这个目录能不能开工作模式。
763
1411
  *
764
- * 默认能。只有两种情况会说不:
765
- * 1. flowRoot 配了绝对路径 —— 这是明确表态「只在这个子树里用」,那就守它
766
- * 2. flowGate=strict —— 用户主动要那道边界
1412
+ * 由 flowGate 一个开关说了算:
1413
+ * off(默认)/ auto —— 任何目录都能开
1414
+ * strict —— 只认「工作流」目录
1415
+ *
1416
+ * 配了 flowRoot 绝对路径只影响「该去哪」这句提示和目录自动创建的位置,
1417
+ * 不再顺带把门关死。以前配了路径就等于强制 strict,于是「换个目录先试试」
1418
+ * 这件事变得做不到——用户得先去改配置才能试,这正是要去的门槛。
767
1419
  */
768
- function insideFlow(cwd, settings) {
1420
+ export function insideFlow(cwd, settings) {
1421
+ if (flowModeOf(settings) !== 'strict') return true
769
1422
  const configured = typeof settings.flowRoot === 'string' ? settings.flowRoot.trim() : ''
770
1423
  const here = resolve(cwd)
771
- // 配了绝对路径:就是那个目录的子树,别处一律不算。这条不看 flowGate,
772
- // 因为配了绝对路径本身就是比开关更强的表态。
1424
+ // strict 下配了绝对路径:只认那个子树的,别处一律不算。
773
1425
  if (configured !== '' && isAbsolute(configured)) {
774
1426
  const root = resolve(configured)
775
1427
  const rel = relative(root, here)
776
1428
  return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))
777
1429
  }
778
- if (flowModeOf(settings) !== 'strict') return true
779
- // strict:认路径里有没有这一段。
1430
+ // strict 且没配绝对路径:认路径里有没有这一段。
780
1431
  // cwd 本身叫这个名字(把工作流目录直接当工作区开),或者它在某个同名目录下面。
781
1432
  const name = (configured === '' ? FLOW_DIR_NAME : configured).replace(/[\\/]+$/u, '')
782
1433
  return here.split(/[\\/]/u).includes(name)
@@ -810,20 +1461,29 @@ function flowGateMessage(cwd, settings) {
810
1461
  * @returns {{ root: string, created: boolean, moved: boolean }}
811
1462
  * root 这次该用的工作目录;created 表示这次新建了目录;moved 表示 base 从 cwd 换成了 root
812
1463
  */
813
- async function ensureFlowRoot(cwd, settings) {
1464
+ export async function ensureFlowRoot(cwd, settings) {
814
1465
  if (insideFlow(cwd, settings)) {
815
1466
  return { root: cwd, created: false, moved: false }
816
1467
  }
817
- const root = flowRootOf(cwd, settings)
818
- let created = false
1468
+ // 用 flowRootTargetOf 而不是 flowRootOf:配了绝对路径时,真正的项目数据
1469
+ // 常常在它下面那层「工作流」里(用户配 D:\某个目录,项目在 D:\某个目录\工作流)。
1470
+ // 用外层的话,工作目录会指到没有 .project-flow 的地方,项目一个都看不见。
1471
+ const root = flowRootTargetOf(cwd, settings)
1472
+ // mkdir recursive 对已存在的目录不报错,所以「建成功了」和「这次新建了」
1473
+ // 是两件事,得分开判。以前把两者混成一个 created,于是每次调用都报
1474
+ // 「新建了」——状态栏和日志里都会说一句假话。
1475
+ const existed = existsSync(root)
819
1476
  try {
820
1477
  await mkdir(root, { recursive: true })
821
- created = true
822
- } catch {
823
- // 建不出来(权限、只读盘)就退回原目录,让调用方按老规矩拒绝并说清
824
- return { root: cwd, created: false, moved: false }
1478
+ } catch (error) {
1479
+ // 建不出来就说清是哪条路走不通。
1480
+ //
1481
+ // 以前这里静默退回,用户看到的只有一句「不在工作流目录里」——他完全
1482
+ // 不知道该干什么:是权限问题?盘只读?还是路径本身不合法?
1483
+ // 一句「建不出来」比一句「不行」有用得多。
1484
+ return { root: cwd, created: false, moved: false, error: messageOf(error), attempted: root }
825
1485
  }
826
- return { root, created: true, moved: true }
1486
+ return { root, created: !existed, moved: true }
827
1487
  }
828
1488
 
829
1489
  /** 上次在这个工作流目录里确认过的盲区与假设,放在工作流根下的一个文件里。 */
@@ -879,15 +1539,31 @@ async function readState(cwd, project) {
879
1539
  }
880
1540
  }
881
1541
 
1542
+ /**
1543
+ * 产物落盘。走 writeFileAtomic:进程在写一半被杀时最坏只是丢掉这次更新,
1544
+ * 不会留下半截 Requirement.md 让后面每一阶都读到坏文件。
1545
+ *
1546
+ * 以前这里是裸 writeFile。state.json 和 run.lock 早就原子化了,但真正被
1547
+ * 三个子会话反复读的那几个 .md 一直没有——「断电也不会留下要人修的东西」
1548
+ * 这句话当时说得过头了。
1549
+ */
882
1550
  async function saveArtifact(cwd, project, fileName, content) {
883
1551
  const dir = stateDir(cwd, project)
884
1552
  await mkdir(dir, { recursive: true })
885
- await writeFile(join(dir, fileName), `${content}\n`, 'utf8')
1553
+ await writeFileAtomic(join(dir, fileName), `${content}\n`)
886
1554
  }
887
1555
 
888
1556
  /**
889
1557
  * 追加写。Execution_Log.md 用这个:返工几轮就有几条记录,
890
1558
  * 覆盖掉的话上一轮做过什么就查不到了。
1559
+ *
1560
+ * 追加写没有「原子替换」这回事——目标文件本来就是不断变长的。
1561
+ * 能做的是两件:
1562
+ * 1. 先确保父目录在(第一次写时)
1563
+ * 2. 一次 write 写完整段,而不是分多次小写;O_APPEND 保证单次写入不交错
1564
+ *
1565
+ * 真被在写到一半杀掉时,最坏结果是最后一行不完整。读取侧用
1566
+ * `readArtifactTolerant` 兜住:解析时容忍末行截断,不让一条残行毁掉整份日志。
891
1567
  */
892
1568
  async function appendArtifact(cwd, project, fileName, content) {
893
1569
  const dir = stateDir(cwd, project)
@@ -895,6 +1571,22 @@ async function appendArtifact(cwd, project, fileName, content) {
895
1571
  await appendFile(join(dir, fileName), `${content}\n`, 'utf8')
896
1572
  }
897
1573
 
1574
+ /**
1575
+ * 读产物,容忍末行被截断。
1576
+ *
1577
+ * 追加写被杀时最后一行可能只有半句。JSONL 类的文件(台账)直接跳过坏行并
1578
+ * 报行号;Markdown 类的文件没法判断「半句」是不是正常内容,所以只做一件事:
1579
+ * 文件读不出来时退回空串,并且不把异常抛给上层——一阶产物坏了不该让整个
1580
+ * 流水崩在这里,让质检去判「产物不完整」更接近事实。
1581
+ */
1582
+ async function readArtifactTolerant(cwd, project, fileName) {
1583
+ try {
1584
+ return await readFile(join(stateDir(cwd, project), fileName), 'utf8')
1585
+ } catch {
1586
+ return ''
1587
+ }
1588
+ }
1589
+
898
1590
  /** Concatenate the text blocks of a settled child result. */
899
1591
  function textOf(output) {
900
1592
  if (!Array.isArray(output)) return ''
@@ -1128,23 +1820,28 @@ async function runStage(ctx, options) {
1128
1820
  try {
1129
1821
  let activation
1130
1822
  let used = routes[0]
1131
- let firstError
1823
+ // 每级失败都留一条,不只是第一个:三级都试过之后,用户要知道是哪一级
1824
+ // 顶住了。只记 firstError 的话,「配置那个起不来」会把「继承主对话也起不来」
1825
+ // 吞掉,日志上看着像一次成功回退。
1826
+ const failures = []
1132
1827
  for (const route of routes) {
1133
1828
  try {
1134
1829
  activation = await start(route)
1135
1830
  used = route
1136
1831
  break
1137
1832
  } catch (error) {
1138
- firstError ??= error
1833
+ failures.push({ route, error })
1139
1834
  }
1140
1835
  }
1141
- if (activation === undefined) throw firstError ?? new Error('所有路由都起不来')
1836
+ if (activation === undefined) throw failures[0]?.error ?? new Error('所有路由都起不来')
1142
1837
  const describe = route => route.model === ''
1143
1838
  ? '主对话模型'
1144
1839
  : `${route.llmProvider === '' ? route.provider : route.llmProvider}/${route.model}`
1145
1840
  if (used !== routes[0]) {
1146
- routeNote = `${label}:${describe(routes[0])} 起不来`
1147
- + `(${messageOf(firstError).slice(0, 160)}),已改走 ${describe(used)}`
1841
+ routeNote = `${label}|` + failures
1842
+ .map(item => `tried=${describe(item.route)} reason=${messageOf(item.error).slice(0, 120)}`)
1843
+ .join(';')
1844
+ + `|fellBackTo=${describe(used)}`
1148
1845
  }
1149
1846
 
1150
1847
  let outcome = await settle(activation)
@@ -1633,6 +2330,1110 @@ async function readArtifact(cwd, project, fileName) {
1633
2330
  }
1634
2331
  }
1635
2332
 
2333
+ // ── 断言执行器 ──────────────────────────────────────────────────
2334
+ //
2335
+ // 质检以前只说「我核过了」。这一节让它自己跑命令:Requirement.md 的 YAML
2336
+ // 前置块里,每条要求可以带一条 check,退出码就是判据。
2337
+ //
2338
+ // 分工定死:模型解释结果,命令产出结果。命令说不过,模型说过了也不算数;
2339
+ // 要求没写 check,那一条就只能记 unverified,不能算 PASS——这是这一节存在的
2340
+ // 全部理由,破了这条就等于回到原来那套。
2341
+
2342
+ /** 默认白名单。配置只能往上加:能删的话「判据」就又能被配置关掉了。 */
2343
+ const DEFAULT_ALLOWED_COMMANDS = ['node', 'npm', 'pnpm', 'python', 'pytest', 'git', 'cargo', 'go', 'dotnet']
2344
+
2345
+ /** 单条 check 的默认超时,以及断言输出留多长的尾巴。 */
2346
+ const DEFAULT_CHECK_TIMEOUT_MS = 120000
2347
+ const DEFAULT_CHECK_TAIL_CHARS = 8000
2348
+
2349
+ /**
2350
+ * 「命令不存在」超过这个条数就整组退成 unverified。
2351
+ * 连着五条都 ENOENT,说明这台机器没装那套工具链,不是这次实现写错了;
2352
+ * 硬判 FAIL 会把环境问题记成代码问题,返工几轮也修不好。
2353
+ */
2354
+ const CHECK_MISSING_BINARY_LIMIT = 5
2355
+
2356
+ /**
2357
+ * 拆文件头那段 YAML 前置块。
2358
+ *
2359
+ * 手写行解析,不引 YAML 库:这一块只放 checks,格式由我们自己定,
2360
+ * 引一个库换来的「通用」在这里没有用。
2361
+ */
2362
+ function splitFrontMatter(text) {
2363
+ if (typeof text !== 'string') return { front: '', body: '' }
2364
+ const trimmed = text.replace(/^\uFEFF/u, '')
2365
+ if (!trimmed.startsWith('---')) return { front: '', body: trimmed }
2366
+ const firstBreak = trimmed.indexOf('\n')
2367
+ if (firstBreak === -1) return { front: '', body: trimmed }
2368
+ const end = trimmed.indexOf('\n---', firstBreak)
2369
+ if (end === -1) return { front: '', body: trimmed }
2370
+ return {
2371
+ front: trimmed.slice(firstBreak + 1, end),
2372
+ body: trimmed.slice(end + 4).replace(/^\n+/u, ''),
2373
+ }
2374
+ }
2375
+
2376
+ /** YAML 标量还原:双引号走 JSON 转义,单引号按 YAML 规矩去掉一层。 */
2377
+ function unquoteScalar(value) {
2378
+ const text = typeof value === 'string' ? value.trim() : ''
2379
+ if (text.length >= 2 && text.startsWith('"') && text.endsWith('"')) {
2380
+ try {
2381
+ return String(JSON.parse(text))
2382
+ } catch {
2383
+ return text.slice(1, -1)
2384
+ }
2385
+ }
2386
+ if (text.length >= 2 && text.startsWith("'") && text.endsWith("'")) return text.slice(1, -1)
2387
+ return text
2388
+ }
2389
+
2390
+ /** 写回去时的标量引法。空串写成 '',其余一律 JSON 双引号——YAML 认这一套。 */
2391
+ function quoteScalar(value) {
2392
+ const text = typeof value === 'string' ? value : String(value ?? '')
2393
+ return text === '' ? "''" : JSON.stringify(text)
2394
+ }
2395
+
2396
+ /**
2397
+ * 把 Requirement.md 的前置块读成 [{ req, cmd, expectExit }]。
2398
+ *
2399
+ * 只认 checks: 下面那几行,别的一概不碰:前置块以后还要放别的东西,
2400
+ * 见什么认什么都收进来,迟早会把散文当成命令跑。
2401
+ */
2402
+ export function parseRequirementChecks(text) {
2403
+ const { front } = splitFrontMatter(text)
2404
+ if (front === '') return []
2405
+ const entries = []
2406
+ let inChecks = false
2407
+ let current
2408
+ for (const rawLine of front.split(/\r?\n/u)) {
2409
+ const line = rawLine.replace(/\s+$/u, '')
2410
+ if (/^checks\s*:\s*$/u.test(line)) {
2411
+ inChecks = true
2412
+ continue
2413
+ }
2414
+ // 顶格的非空行意味着 checks 这一段结束了。
2415
+ if (inChecks && /^\S/u.test(line)) {
2416
+ inChecks = false
2417
+ current = undefined
2418
+ }
2419
+ if (!inChecks) continue
2420
+ const reqMatch = /^\s*-\s*req\s*:\s*(\d+)\s*$/u.exec(line)
2421
+ if (reqMatch !== null) {
2422
+ current = { req: Number(reqMatch[1]), cmd: '', expectExit: 0 }
2423
+ entries.push(current)
2424
+ continue
2425
+ }
2426
+ if (current === undefined) continue
2427
+ const cmdMatch = /^\s+cmd\s*:\s*(.*)$/u.exec(line)
2428
+ if (cmdMatch !== null) {
2429
+ current.cmd = unquoteScalar(cmdMatch[1])
2430
+ continue
2431
+ }
2432
+ const exitMatch = /^\s+exit\s*:\s*(-?\d+)\s*$/u.exec(line)
2433
+ if (exitMatch !== null) current.expectExit = Number(exitMatch[1])
2434
+ }
2435
+ return entries
2436
+ }
2437
+
2438
+ /** 反过来:把断言表写成一段前置块。cmd 为空表示这条要求没定义判据。 */
2439
+ export function renderRequirementChecks(entries) {
2440
+ if (!Array.isArray(entries) || entries.length === 0) return ''
2441
+ const lines = ['---', 'checks:']
2442
+ for (const entry of entries) {
2443
+ lines.push(` - req: ${entry.req}`)
2444
+ lines.push(` cmd: ${quoteScalar(entry.cmd ?? '')}`)
2445
+ lines.push(` exit: ${Number.isInteger(entry.expectExit) ? entry.expectExit : 0}`)
2446
+ }
2447
+ lines.push('---')
2448
+ return lines.join('\n')
2449
+ }
2450
+
2451
+ /**
2452
+ * 判据指纹:req / 命令 / 期望退出码三样的 sha256。
2453
+ *
2454
+ * 只覆盖判据本身,不覆盖要求正文——文案改写不是作弊,改判据才是。
2455
+ * 顺序也算在内:把两条命令对调,跑起来结果就变了。
2456
+ *
2457
+ * 使用固定字段顺序的 JSON(req、cmd、expectedExit,按原顺序排列)作为输入,
2458
+ * sha256 输出小写十六进制。
2459
+ */
2460
+ export function requirementFingerprint(entries) {
2461
+ const list = Array.isArray(entries) ? entries : []
2462
+ const canonical = JSON.stringify(
2463
+ list.map(entry => ({
2464
+ req: Number.isInteger(entry.req) ? entry.req : 0,
2465
+ cmd: typeof entry.cmd === 'string' ? entry.cmd : '',
2466
+ expectedExit: Number.isInteger(entry.expectExit) ? entry.expectExit : 0,
2467
+ })),
2468
+ )
2469
+ return createHash('sha256').update(canonical, 'utf8').digest('hex')
2470
+ }
2471
+
2472
+ /** 命令名归一:取 basename、小写、去掉 Windows 的扩展名。 */
2473
+ function commandNameOf(token) {
2474
+ const base = basename(String(token ?? '').trim()).toLowerCase()
2475
+ return base.replace(/\.(exe|cmd|bat|ps1)$/u, '')
2476
+ }
2477
+
2478
+ /**
2479
+ * 解释器「按代码跑」的开关。
2480
+ *
2481
+ * 这条界线要划清楚,别把它当安全沙箱——它不是。
2482
+ *
2483
+ * 白名单能挡的是**手滑**:`rm -rf`、`curl ... | sh`、`ssh` 这种东西
2484
+ * 不该出现在一条「验证我这次改动」的判据里,看见就拦,让人回来改。
2485
+ *
2486
+ * 白名单挡不住的是**刻意**:`node -e`、`python -c` 是写轻量判据的常见写法
2487
+ * (`node -e "require('assert')..."`),一律拦掉等于把正常用法砍了。
2488
+ * 想刻意做坏事的人另有的是工具,不会特意绕经判据这条路。
2489
+ *
2490
+ * 所以默认放行 eval 类开关,`checkStrictEval: true` 时才拦。
2491
+ */
2492
+ const CODE_ESCAPE_FLAGS = {
2493
+ node: ['-e', '--eval', '-p', '--print', '--experimental-loader', '--loader'],
2494
+ python: ['-c'],
2495
+ python3: ['-c'],
2496
+ // 包运行器后面跟的是另一条命令,本身就是「绕过白名单去跑别的包」
2497
+ npm: ['exec', 'x'],
2498
+ pnpm: ['exec', 'dlx'],
2499
+ }
2500
+
2501
+ /**
2502
+ * 严格模式下才拦的那几个(默认放行)。
2503
+ *
2504
+ * 分开放是为了让 checkStrictEval 只影响这些:包运行器和 git 挂命令
2505
+ * 不管严格不严格都该拦,那是真的绕过白名单,不是正常用法。
2506
+ */
2507
+ const STRICT_ONLY_FLAGS = new Set(['node', 'python', 'python3'])
2508
+
2509
+ /**
2510
+ * npm / pnpm 的子命令里,哪几个本质上是「再起一个任意解释器」。
2511
+ *
2512
+ * `npm exec -- node -e "..."` 和直接 `node -e` 没有区别,所以 subshell 也要看。
2513
+ */
2514
+ const PACKAGE_RUNNERS = new Set(['exec', 'x', 'dlx'])
2515
+
2516
+ /**
2517
+ * git 的 `-c` 里,哪些键能把任意命令挂到 git 上执行。
2518
+ *
2519
+ * `git -c core.autocrlf=false status` 是日常写法,不该拦;
2520
+ * `git -c core.pager=sh` 则等于让 git 替你起 shell。只拦后者这类。
2521
+ */
2522
+ const GIT_DANGEROUS_CONFIG = /^(core\.(pager|editor|hooksPath|sshCommand|askpass|fsmonitor)|diff\.(external|textconv)|credential\.helper|filter\.|.*\.command$)/iu
2523
+
2524
+ /**
2525
+ * 这条命令有没有借解释器开关逃出白名单。
2526
+ *
2527
+ * @param strictEval true 时连 node -e / python -c 一起拦
2528
+ * @returns {{escaped:false} | {escaped:true, reason:string}}
2529
+ */
2530
+ export function checkCodeEscape(name, args, strictEval = false) {
2531
+ const direct = CODE_ESCAPE_FLAGS[name]
2532
+ if (Array.isArray(direct) && direct.length > 0) {
2533
+ // 严格模式下才管 eval 类开关;包运行器不受这个开关影响。
2534
+ const enforced = strictEval || !STRICT_ONLY_FLAGS.has(name)
2535
+ if (enforced) {
2536
+ for (const arg of args) {
2537
+ // `--eval=code` 这样的写法也要认
2538
+ const head = arg.split('=')[0]
2539
+ if (direct.includes(arg) || direct.includes(head)) {
2540
+ return {
2541
+ escaped: true,
2542
+ reason: strictEval
2543
+ ? `${name} ${head} 等于直接执行一段代码(checkStrictEval 已开启,这类调用一律拒)`
2544
+ : `${name} ${head} 会再起一个解释器,等于绕过白名单`,
2545
+ }
2546
+ }
2547
+ }
2548
+ }
2549
+ }
2550
+ // git -c key=value:只有那几个能把命令挂上去的键才拦。
2551
+ if (name === 'git') {
2552
+ for (let i = 0; i < args.length; i += 1) {
2553
+ if (args[i] !== '-c') continue
2554
+ const assignment = args[i + 1] ?? ''
2555
+ const key = assignment.split('=')[0].trim()
2556
+ if (GIT_DANGEROUS_CONFIG.test(key)) {
2557
+ return { escaped: true, reason: `git -c ${key} 会把任意命令挂到 git 上执行,换成不带这条配置的写法` }
2558
+ }
2559
+ }
2560
+ }
2561
+ // 包运行器:npm exec / pnpm dlx 后面跟的其实是另一条命令,递归看一眼。
2562
+ if (PACKAGE_RUNNERS.has(name) && args.length > 0) {
2563
+ const sub = args.find(arg => !arg.startsWith('-'))
2564
+ if (sub !== undefined) {
2565
+ const subName = commandNameOf(sub)
2566
+ if (PACKAGE_RUNNERS.has(subName) || (CODE_ESCAPE_FLAGS[subName] ?? []).length > 0) {
2567
+ return { escaped: true, reason: `${name} ${sub} 会再起一个解释器,等于绕过白名单` }
2568
+ }
2569
+ }
2570
+ }
2571
+ return { escaped: false }
2572
+ }
2573
+
2574
+ /** 生效的白名单 = 写死的 9 类 + 配置里加的,去掉空串和重复。 */
2575
+ export function allowedCommandsOf(settings) {
2576
+ const extra = typeof settings?.checkAllowedCommands === 'string' ? settings.checkAllowedCommands : ''
2577
+ const names = [...DEFAULT_ALLOWED_COMMANDS, ...extra.split(/[,\s]+/u)]
2578
+ .map(commandNameOf)
2579
+ .filter(name => name !== '')
2580
+ return [...new Set(names)]
2581
+ }
2582
+
2583
+ /**
2584
+ * 按 shell 的习惯切命令,但不交给 shell 执行。
2585
+ *
2586
+ * 切是为了拿首 token 去比白名单、把剩下的当参数传给 execFile。
2587
+ * execFile 不走 shell,所以 `;` `|` `&&` 都不会被解释——它们只会变成
2588
+ * 传给程序的普通字符串参数。这是「白名单」能立得住的物理前提。
2589
+ */
2590
+ export function tokenizeCommand(cmd) {
2591
+ const text = typeof cmd === 'string' ? cmd : ''
2592
+ const tokens = []
2593
+ let current = ''
2594
+ let quote = ''
2595
+ let started = false
2596
+ for (const ch of text) {
2597
+ if (quote !== '') {
2598
+ if (ch === quote) {
2599
+ quote = ''
2600
+ continue
2601
+ }
2602
+ current += ch
2603
+ continue
2604
+ }
2605
+ if (ch === '"' || ch === "'") {
2606
+ quote = ch
2607
+ started = true
2608
+ continue
2609
+ }
2610
+ if (/\s/u.test(ch)) {
2611
+ if (started) {
2612
+ tokens.push(current)
2613
+ current = ''
2614
+ started = false
2615
+ }
2616
+ continue
2617
+ }
2618
+ current += ch
2619
+ started = true
2620
+ }
2621
+ if (started) tokens.push(current)
2622
+ return tokens
2623
+ }
2624
+
2625
+ /**
2626
+ * 一条命令能不能跑。拒绝理由要写清楚是哪一条规则拦的,否则人只看到一句
2627
+ * 「没跑」,会以为插件坏了。
2628
+ */
2629
+ export function checkDenial(cmd, allowed, options = {}) {
2630
+ const list = Array.isArray(allowed) ? allowed : DEFAULT_ALLOWED_COMMANDS
2631
+ if (typeof cmd !== 'string' || cmd.trim() === '') return { denied: true, reason: 'check 是空的' }
2632
+ const tokens = tokenizeCommand(cmd)
2633
+ const name = commandNameOf(tokens[0] ?? '')
2634
+ if (name === '') return { denied: true, reason: '认不出命令名' }
2635
+ if (!list.includes(name)) {
2636
+ return { denied: true, reason: `命令 ${name} 不在白名单里(只放行 ${list.join(' / ')})` }
2637
+ }
2638
+ const args = tokens.slice(1)
2639
+ // 名字在白名单里还有几种绕过路子(npm exec / pnpm dlx / git -c 挂命令)。
2640
+ // eval 类开关默认放行——那是写轻量判据的正常写法,见 CODE_ESCAPE_FLAGS 的说明。
2641
+ const escape = checkCodeEscape(name, args, options.strictEval === true)
2642
+ if (escape.escaped) return { denied: true, reason: escape.reason }
2643
+ return { denied: false, name, file: tokens[0], args }
2644
+ }
2645
+
2646
+ /** 输出只留尾巴。stdout 大的时候前面几千行是噪音,报错在最后几行。 */
2647
+ function tailOf(text, limit) {
2648
+ const value = typeof text === 'string' ? text : ''
2649
+ const max = Number.isFinite(limit) && limit > 0 ? Math.floor(limit) : DEFAULT_CHECK_TAIL_CHARS
2650
+ return value.length <= max ? value : value.slice(value.length - max)
2651
+ }
2652
+
2653
+ /**
2654
+ * 在 Windows 上把 `npm` / `pnpm` / `npx` 这类名字解析成能真正被 execFile 启动的东西。
2655
+ *
2656
+ * 问题:Windows 上 npm 装的是一个 `npm.cmd`(批处理垫片),没有 `npm.exe`。
2657
+ * `execFile('npm', ...)` 不会做 PATHEXT 扩展,直接 ENOENT——于是 `npm test`
2658
+ * 这种最常见的判据被记成「命令不存在」,而不是「测试没过」。这两件事在
2659
+ * 质检里的含义完全不同:一个该改代码,一个该改环境。
2660
+ *
2661
+ * 解法:`.cmd` / `.bat` 必须先经 cmd.exe 才能执行(Node 自 18.20 起出于安全
2662
+ * 默认拒绝直接 spawn 批处理)。
2663
+ *
2664
+ * **引号这条路走不通**:试过 `cmd /c "路径" "参数"`,路径里带中文或空格时
2665
+ * cmd 的引号剥离规则会把整串拆坏(实测 "D:\新建文件夹 (4)\npm.cmd" 被拆成
2666
+ * 两段报「不是内部或外部命令」)。所以改成「写一个临时 .bat,把命令原样放进去,
2667
+ * 再执行那个 bat」——批处理文件内部不经过 cmd 的命令行解析,中文路径和参数
2668
+ * 都能原样保留,跑完删掉。
2669
+ *
2670
+ * 只对 Windows 生效,别的平台原样返回。
2671
+ *
2672
+ * @returns {{file:string, args:string[], viaCmd:boolean, resolved:string, cleanup?:()=>void}}
2673
+ */
2674
+ export function resolveWindowsCommand(file, args) {
2675
+ const list = Array.isArray(args) ? args : []
2676
+ if (process.platform !== 'win32') return { file, args: list, viaCmd: false, resolved: file }
2677
+
2678
+ const lower = String(file).toLowerCase()
2679
+ const isBatch = lower.endsWith('.cmd') || lower.endsWith('.bat')
2680
+
2681
+ let resolved = file
2682
+ if (!isBatch) {
2683
+ const found = whichSync(file)
2684
+ if (found === undefined) return { file, args: list, viaCmd: false, resolved: file }
2685
+ resolved = found
2686
+ const foundLower = found.toLowerCase()
2687
+ if (!foundLower.endsWith('.cmd') && !foundLower.endsWith('.bat')) {
2688
+ // 找到的是 .exe,直接跑,不用过 cmd
2689
+ return { file: found, args: list, viaCmd: false, resolved: found }
2690
+ }
2691
+ }
2692
+
2693
+ // 写一个临时 bat:把路径和参数原样写进去。
2694
+ //
2695
+ // 编码是个坑:cmd.exe 默认按系统 ANSI 代码页(简中 Windows 是 GBK/936)读
2696
+ // 批处理,写 UTF-8 会让中文路径变成乱码,写 ascii 会丢字。这里用
2697
+ // `chcp 65001` 把控制台切到 UTF-8,再以 UTF-8 写文件——这样中文、emoji
2698
+ // 路径都不受系统代码页影响。切代码页只影响这个 bat 自己的进程,不外溢。
2699
+ let batPath
2700
+ try {
2701
+ batPath = join(tmpdir(), `pf-run-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.bat`)
2702
+ const quotedArgs = list.map(part => `"${String(part).replace(/"/gu, '""')}"`).join(' ')
2703
+ const body = [
2704
+ '@echo off',
2705
+ 'chcp 65001 >nul 2>&1',
2706
+ `"${resolved}"${quotedArgs === '' ? '' : ` ${quotedArgs}`}`,
2707
+ 'exit /b %ERRORLEVEL%',
2708
+ ].join('\r\n')
2709
+ writeFileSync(batPath, `${body}\r\n`, 'utf8')
2710
+ } catch {
2711
+ // 写不出临时文件就退回直连,至少 exe 类命令不受影响
2712
+ return { file: resolved, args: list, viaCmd: false, resolved }
2713
+ }
2714
+
2715
+ return {
2716
+ file: process.env.ComSpec ?? 'cmd.exe',
2717
+ args: ['/d', '/s', '/c', batPath],
2718
+ viaCmd: true,
2719
+ resolved,
2720
+ cleanup: () => {
2721
+ try { rmSync(batPath, { force: true }) } catch { /* 删不掉就算了,在系统临时目录里 */ }
2722
+ },
2723
+ }
2724
+ }
2725
+
2726
+ /**
2727
+ * 按 PATHEXT 找可执行文件。只用 node:path / node:fs,不引依赖。
2728
+ *
2729
+ * Windows 的查找顺序和 cmd 一致:当前目录 → PATH 每一项,每个目录里试
2730
+ * .COM/.EXE/.BAT/.CMD(PATHEXT 的顺序)。
2731
+ */
2732
+ function whichSync(name) {
2733
+ if (typeof name !== 'string' || name === '') return undefined
2734
+ if (isAbsolute(name)) return existsSync(name) ? name : undefined
2735
+
2736
+ const exts = (process.env.PATHEXT ?? '.COM;.EXE;.BAT;.CMD').split(';').filter(e => e !== '')
2737
+ // 名字本身已经带扩展名就只试那一个
2738
+ const hasExt = exts.some(ext => name.toLowerCase().endsWith(ext.toLowerCase()))
2739
+ const candidates = hasExt ? [name] : exts.map(ext => `${name}${ext.toLowerCase()}`)
2740
+
2741
+ const dirs = [process.cwd(), ...(process.env.PATH ?? '').split(';').filter(d => d !== '')]
2742
+ for (const dir of dirs) {
2743
+ for (const candidate of candidates) {
2744
+ const full = join(dir, candidate)
2745
+ try {
2746
+ if (existsSync(full)) return full
2747
+ } catch {
2748
+ // 这个目录不可访问,试下一个
2749
+ }
2750
+ }
2751
+ }
2752
+ return undefined
2753
+ }
2754
+
2755
+ /**
2756
+ * 真正起进程。默认实现走 execFile:不走 shell,超时用 SIGKILL 收掉,
2757
+ * 拿不到可执行文件时按 127 记(和 shell 的规矩一致)。
2758
+ *
2759
+ * Windows 上的 npm/pnpm/npx 是 .cmd 垫片,要经 cmd.exe——见 resolveWindowsCommand。
2760
+ * 那条路径仍然只执行白名单放行的那一条命令:参数在进 cmd 之前已经被逐条
2761
+ * 引号包住,而白名单在更早的 checkDenial 里已经卡过命令名。
2762
+ */
2763
+ function defaultSpawnCheck({ file, args, cwd, timeoutMs, env }) {
2764
+ const resolved = resolveWindowsCommand(file, args)
2765
+ return new Promise(resolve => {
2766
+ execFile(resolved.file, resolved.args, {
2767
+ cwd,
2768
+ timeout: timeoutMs,
2769
+ killSignal: 'SIGKILL',
2770
+ windowsHide: true,
2771
+ maxBuffer: 8 * 1024 * 1024,
2772
+ ...(env === undefined ? {} : { env }),
2773
+ }, (error, stdout, stderr) => {
2774
+ // 临时 bat 用完就删,别在系统临时目录里攒
2775
+ if (typeof resolved.cleanup === 'function') resolved.cleanup()
2776
+ const output = `${stdout ?? ''}${stderr ?? ''}`
2777
+ if (error === null || error === undefined) {
2778
+ resolve({ exit: 0, output })
2779
+ return
2780
+ }
2781
+ if (error.code === 'ENOENT') {
2782
+ // 说清「找的是哪个文件」:Windows 上常见的坑是 npm 装成了 npm.cmd,
2783
+ // 只报一句「命令不存在」会让人去重装,实际是路径没解析到。
2784
+ resolve({
2785
+ exit: 127,
2786
+ output: `${output}${error.message}`,
2787
+ missing: true,
2788
+ ...(resolved.resolved !== file ? { triedPath: resolved.resolved } : {}),
2789
+ })
2790
+ return
2791
+ }
2792
+ const timedOut = error.killed === true || (error.signal !== undefined && error.signal !== null)
2793
+ // 超时一律记 124(和 shell timeout 命令一致),不用内核信号码。
2794
+ if (timedOut) {
2795
+ resolve({ exit: 124, output, timedOut: true })
2796
+ return
2797
+ }
2798
+ if (typeof error.code === 'number') {
2799
+ resolve({ exit: error.code, output })
2800
+ return
2801
+ }
2802
+ resolve({ exit: 1, output: `${output}${error.message}` })
2803
+ })
2804
+ })
2805
+ }
2806
+
2807
+ /**
2808
+ * 串行跑全部 check,返回 assertions[]。
2809
+ *
2810
+ * 串行是有意的:同一项目不会同时跑两轮,但这些命令可能抢同一个端口、
2811
+ * 同一份构建产物,并发跑等于自己给自己制造不确定性。
2812
+ */
2813
+ export async function runRequirementChecks(options) {
2814
+ const {
2815
+ entries = [],
2816
+ cwd,
2817
+ allowed = DEFAULT_ALLOWED_COMMANDS,
2818
+ strictEval = false,
2819
+ timeoutMs = DEFAULT_CHECK_TIMEOUT_MS,
2820
+ tailChars = DEFAULT_CHECK_TAIL_CHARS,
2821
+ env,
2822
+ spawnCheck = defaultSpawnCheck,
2823
+ } = options ?? {}
2824
+ const assertions = []
2825
+ for (const entry of Array.isArray(entries) ? entries : []) {
2826
+ const req = Number.isInteger(entry?.req) ? entry.req : assertions.length + 1
2827
+ const cmd = typeof entry?.cmd === 'string' ? entry.cmd.trim() : ''
2828
+ if (cmd === '') {
2829
+ assertions.push({ req, cmd: null, exit: null, durationMs: 0, stdoutTail: '', status: 'unverified' })
2830
+ continue
2831
+ }
2832
+ const denial = checkDenial(cmd, allowed, { strictEval })
2833
+ if (denial.denied === true) {
2834
+ assertions.push({
2835
+ req,
2836
+ cmd,
2837
+ exit: 126,
2838
+ durationMs: 0,
2839
+ stdoutTail: `白名单拒绝:${denial.reason}`,
2840
+ status: 'denied',
2841
+ denied: true,
2842
+ })
2843
+ continue
2844
+ }
2845
+ const startedAt = Date.now()
2846
+ let run
2847
+ try {
2848
+ run = await spawnCheck({ file: denial.file, args: denial.args, cwd, timeoutMs, env })
2849
+ } catch (error) {
2850
+ run = { exit: 1, output: messageOf(error) }
2851
+ }
2852
+ const durationMs = Date.now() - startedAt
2853
+ const expectExit = Number.isInteger(entry?.expectExit) ? entry.expectExit : 0
2854
+ const status = run.timedOut === true
2855
+ ? 'fail'
2856
+ : run.missing === true
2857
+ ? 'missing'
2858
+ : run.exit === expectExit ? 'pass' : 'fail'
2859
+ assertions.push({
2860
+ req,
2861
+ cmd,
2862
+ exit: run.exit ?? null,
2863
+ durationMs,
2864
+ stdoutTail: tailOf(run.output ?? '', tailChars),
2865
+ status,
2866
+ ...(run.timedOut === true ? { timeout: true } : {}),
2867
+ ...(expectExit === 0 ? {} : { expectExit }),
2868
+ })
2869
+ }
2870
+ const missing = assertions.filter(item => item.status === 'missing')
2871
+ const degrade = missing.length > CHECK_MISSING_BINARY_LIMIT
2872
+ for (const item of assertions) {
2873
+ if (item.status !== 'missing') continue
2874
+ // 环境里没有这条命令:少数几条按 FAIL 记(应该是这次实现要用的工具),
2875
+ // 成片缺失按 unverified 记(更像是这台机器没装)。
2876
+ item.status = degrade ? 'unverified' : 'fail'
2877
+ }
2878
+ return assertions
2879
+ }
2880
+
2881
+ /**
2882
+ * 判据到底有没有启用:至少有一条要求真写了 check。
2883
+ *
2884
+ * 一条都没有的时候走老路——不能因为「第 1 阶没给判据」就把每个项目都判死,
2885
+ * 那等于把流程关了。混着写(有的有 check、有的没有)才算启用,那种情况下
2886
+ * 没 check 的那几条是 unverified,不能跟着一起 PASS。
2887
+ */
2888
+ export function criteriaInPlay(assertions) {
2889
+ const list = Array.isArray(assertions) ? assertions : []
2890
+ return list.some(item => item.status !== 'unverified')
2891
+ }
2892
+
2893
+ /**
2894
+ * 把 assertions 折成一个判据结论。
2895
+ *
2896
+ * FAIL —— 有命令跑了但没过,或者被白名单拒了。这一轮不许 PASS。
2897
+ * UNVERIFIED —— 有要求压根没有 check。也不许 PASS:判不了不等于判过了。
2898
+ * PASS —— 每条要求都有 check 且都过了。
2899
+ */
2900
+ export function gateAssertions(assertions, requirementCount) {
2901
+ const list = Array.isArray(assertions) ? assertions : []
2902
+ const failed = list.filter(item => item.status === 'fail' || item.status === 'denied')
2903
+ const unverified = list.filter(item => item.status === 'unverified')
2904
+ const passed = list.filter(item => item.status === 'pass')
2905
+ const covered = new Set(list.map(item => item.req))
2906
+ const total = Number.isInteger(requirementCount) && requirementCount > 0 ? requirementCount : covered.size
2907
+ const uncovered = []
2908
+ for (let index = 1; index <= total; index += 1) if (!covered.has(index)) uncovered.push(index)
2909
+ const verdict = failed.length > 0 ? 'FAIL' : (unverified.length > 0 || uncovered.length > 0) ? 'UNVERIFIED' : 'PASS'
2910
+ return {
2911
+ verdict,
2912
+ failed,
2913
+ unverified,
2914
+ passed,
2915
+ uncovered,
2916
+ total,
2917
+ checked: list.length,
2918
+ }
2919
+ }
2920
+
2921
+ /** 给质检看的断言摘要:跑过什么、退出码多少、尾巴里写了什么。 */
2922
+ export function describeAssertions(gate) {
2923
+ if (gate === undefined || gate === null) return ''
2924
+ const lines = [
2925
+ '## 插件自己跑过的断言(这部分不是模型判断,是命令的退出码)',
2926
+ '',
2927
+ `结论:${gate.verdict}|共 ${gate.total} 条要求,有判据 ${gate.checked} 条,过 ${gate.passed.length} 条,`
2928
+ + `未过 ${gate.failed.length} 条,判不了 ${gate.unverified.length + gate.uncovered.length} 条`,
2929
+ ]
2930
+ if (gate.checked === 0) {
2931
+ lines.push('', '这次一条 check 都没有:所有要求都是 unverified,按规矩不能算 PASS。')
2932
+ return lines.join('\n')
2933
+ }
2934
+ for (const item of gate.failed) {
2935
+ lines.push('', `- 第 ${item.req} 条:${item.cmd}`, ` 退出码 ${item.exit ?? '?'},用时 ${item.durationMs}ms`)
2936
+ if (item.timeout === true) lines.push(' 超时被收掉(timeout: true)')
2937
+ const tail = String(item.stdoutTail ?? '').trim()
2938
+ if (tail !== '') lines.push(' 输出的尾巴:', ' ```', ...tail.split(/\r?\n/u).slice(-15).map(line => ` ${line}`), ' ```')
2939
+ }
2940
+ for (const item of gate.unverified) {
2941
+ lines.push('', `- 第 ${item.req} 条:没有 check,判不了(unverified)`)
2942
+ }
2943
+ return lines.join('\n')
2944
+ }
2945
+
2946
+ /**
2947
+ * 把 assertions 写成 QA_Report.md 的前置块。
2948
+ *
2949
+ * 正文还是给人看的散文,机器要的这几个字段进前置块:
2950
+ * 报告以后要被第 3 阶、被证据包、被状态栏读,各读各的,别互相猜格式。
2951
+ */
2952
+ export function renderAssertionsBlock(assertions, meta = {}) {
2953
+ const lines = ['---']
2954
+ if (typeof meta.verdict === 'string' && meta.verdict !== '') lines.push(`verdict: ${quoteScalar(meta.verdict)}`)
2955
+ if (Number.isInteger(meta.round)) lines.push(`round: ${meta.round}`)
2956
+ lines.push(...assertionFrontLines(assertions))
2957
+ lines.push('---')
2958
+ return lines.join('\n')
2959
+ }
2960
+
2961
+ /**
2962
+ * 报告的前置块:verdict / round / issues / assertions 四段。
2963
+ *
2964
+ * issues 放前面是有意的:返工看的是它,质检报告的第一屏就该是待办。
2965
+ * assertions 是命令跑出来的事实,排在后面当证据。
2966
+ */
2967
+ export function renderQaFrontMatter(meta = {}) {
2968
+ const lines = ['---']
2969
+ if (typeof meta.verdict === 'string' && meta.verdict !== '') lines.push(`verdict: ${quoteScalar(meta.verdict)}`)
2970
+ if (Number.isInteger(meta.round)) lines.push(`round: ${meta.round}`)
2971
+ const issues = Array.isArray(meta.issues) ? meta.issues : []
2972
+ if (issues.length === 0) {
2973
+ lines.push('issues: []')
2974
+ } else {
2975
+ lines.push('issues:')
2976
+ for (const issue of issues) lines.push(...issueLines(issue))
2977
+ }
2978
+ lines.push(...assertionFrontLines(meta.assertions))
2979
+ lines.push('---')
2980
+ return lines.join('\n')
2981
+ }
2982
+
2983
+ /** 断言那一段的 YAML 行,两处写报告共用一个实现。 */
2984
+ function assertionFrontLines(assertions) {
2985
+ const list = Array.isArray(assertions) ? assertions : []
2986
+ if (list.length === 0) return ['assertions: []']
2987
+ const lines = ['assertions:']
2988
+ for (const item of list) {
2989
+ lines.push(` - req: ${Number.isInteger(item.req) ? item.req : 0}`)
2990
+ lines.push(` cmd: ${!item.cmd && item.cmd !== 0 ? "''" : quoteScalar(String(item.cmd))}`)
2991
+ lines.push(` exit: ${typeof item.exit === 'number' ? item.exit : 'null'}`)
2992
+ lines.push(` durationMs: ${Number.isInteger(item.durationMs) ? item.durationMs : 0}`)
2993
+ lines.push(` status: ${item.status ?? 'unknown'}`)
2994
+ if (item.timeout === true) lines.push(' timeout: true')
2995
+ if (item.denied === true) lines.push(' denied: true')
2996
+ const tail = String(item.stdoutTail ?? '')
2997
+ if (tail === '') {
2998
+ lines.push(" stdoutTail: ''")
2999
+ } else {
3000
+ lines.push(' stdoutTail: |')
3001
+ for (const line of tail.split(/\r?\n/u)) lines.push(` ${line}`)
3002
+ }
3003
+ }
3004
+ return lines
3005
+ }
3006
+
3007
+ /**
3008
+ * 从 requirements 生成断言表:一条要求一行,cmd 为空就是「没定义判据」。
3009
+ *
3010
+ * check 可以从两个地方来:
3011
+ * 1. project_run 的 checks 参数(更结构化,req 用 1 起的序号)
3012
+ * 2. 要求文本里自带的一行 `check: ...`(人或后来的模型直接改 Requirement.md)
3013
+ */
3014
+ export function buildCheckEntries(requirements, checks) {
3015
+ const list = Array.isArray(requirements) ? requirements : []
3016
+ const extra = Array.isArray(checks) ? checks : []
3017
+ return list.map((line, index) => {
3018
+ const text = typeof line === 'string' ? line : String(line ?? '')
3019
+ const inline = /(?:\r?\n|\s*\|\|\s*)\s*check\s*:\s*([\s\S]+)$/u.exec(text)
3020
+ const fromList = extra.find(item => item !== null && typeof item === 'object' && Number(item.req) === index + 1)
3021
+ const listed = fromList !== undefined && typeof fromList.check === 'string' && fromList.check.trim() !== ''
3022
+ ? fromList.check.trim()
3023
+ : ''
3024
+ const cmd = listed !== '' ? listed : inline === null ? '' : inline[1].trim()
3025
+ // checks 列表中 exit 等价于 checkExit:两个字段都接收,checkExit 优先,缺省均为 0
3026
+ const rawExit = fromList !== undefined
3027
+ ? (Number.isInteger(Number(fromList.checkExit)) ? fromList.checkExit : (Number.isInteger(Number(fromList.exit)) ? fromList.exit : undefined))
3028
+ : undefined
3029
+ const expectExit = Number.isInteger(Number(rawExit)) ? Number(rawExit) : 0
3030
+ return { req: index + 1, cmd, expectExit }
3031
+ })
3032
+ }
3033
+
3034
+ /** 要求正文里那行 `check:` 去掉,正文只留人看的话。 */
3035
+ export function stripInlineCheck(line) {
3036
+ const text = typeof line === 'string' ? line : String(line ?? '')
3037
+ return text.replace(/(?:\r?\n|\s*\|\|\s*)\s*check\s*:\s*[\s\S]+$/u, '').trim()
3038
+ }
3039
+
3040
+ /**
3041
+ * 把当前判据的指纹落盘。
3042
+ *
3043
+ * 只在第 2 阶入口调一次——写在这儿而不是第 4 阶开头,是因为这里才是
3044
+ * 「判据定稿」的那一刻:规划还没跑,实施还没动,任何人都还没机会改它。
3045
+ */
3046
+ async function saveRequirementFingerprint(cwd, project) {
3047
+ const text = await readArtifact(cwd, project, ARTIFACT.requirement) ?? ''
3048
+ const digest = requirementFingerprint(parseRequirementChecks(text))
3049
+ await saveArtifact(cwd, project, ARTIFACT.requirementHash, digest)
3050
+ return digest
3051
+ }
3052
+
3053
+ /** 读回第 2 阶记下的指纹。没有就是空串:老项目、或者第 2 阶没跑过。 */
3054
+ async function readRequirementFingerprint(cwd, project) {
3055
+ const text = await readArtifact(cwd, project, ARTIFACT.requirementHash)
3056
+ return typeof text === 'string' ? text.trim() : ''
3057
+ }
3058
+
3059
+ // ── 问题级闭环 ──────────────────────────────────────────────────
3060
+ //
3061
+ // 返工的旧判据是「质检判了 FAIL 就再来一轮」。它有两个毛病:一是一条模糊的
3062
+ // FAIL 也能烧掉一整轮,二是第二轮没人记得第一轮那几条到底修了没有——报告
3063
+ // 每轮重写,问题没有身份。
3064
+ //
3065
+ // 这一节给问题发编号:Q-001 一旦发出去,跨轮就是它。返工只看「还有几条没闭环」,
3066
+ // 不看模型那句话是 PASS 还是 FAIL。
3067
+
3068
+ const SEVERITIES = ['P0', 'P1', 'P2']
3069
+
3070
+ /** 一轮最多认真处理这么多条。超出来的先搁着,别让一次报告把返工预算用光。 */
3071
+ const ISSUE_LIMIT = 50
3072
+
3073
+ /** 一处空白差异不该让同一条问题换个身份。 */
3074
+ function normalizeIssueText(value) {
3075
+ return String(value ?? '').replace(/\s+/gu, ' ').trim()
3076
+ }
3077
+
3078
+ /**
3079
+ * 认「同一条问题」用的键:位置 + 说法。
3080
+ *
3081
+ * 不含严重级——模型这轮写 P1、下轮写 P0 是常事,那不该变成两个问题;
3082
+ * 也不含证据和检测方式——那些是随轮次变的描述,不是身份。
3083
+ */
3084
+ export function issueKeyOf(issue) {
3085
+ const loc = normalizeIssueText(issue?.location).toLowerCase().replace(/^\.\//u, '')
3086
+ const claim = normalizeIssueText(issue?.claim).toLowerCase()
3087
+ .replace(/[,。;:、,.;:!?!?"'“”‘’()()]/gu, '')
3088
+ return `${loc}\u0000${claim}`
3089
+ }
3090
+
3091
+ /** 前端模型交上来的东西可能是任何形状,先规整成固定的八个字段里的六个。 */
3092
+ export function normalizeIncomingIssues(raw) {
3093
+ const list = Array.isArray(raw) ? raw : []
3094
+ const out = []
3095
+ for (const item of list) {
3096
+ if (item === null || typeof item !== 'object' || Array.isArray(item)) continue
3097
+ const severity = normalizeIssueText(item.severity).toUpperCase()
3098
+ const issue = {
3099
+ severity: SEVERITIES.includes(severity) ? severity : 'P1',
3100
+ location: normalizeIssueText(item.location),
3101
+ claim: normalizeIssueText(item.claim),
3102
+ evidence: normalizeIssueText(item.evidence),
3103
+ detect: normalizeIssueText(item.detect),
3104
+ pass: normalizeIssueText(item.pass),
3105
+ resolved: item.resolved === true,
3106
+ }
3107
+ if (issue.claim === '' && issue.location === '') continue
3108
+ out.push(issue)
3109
+ }
3110
+ return out
3111
+ }
3112
+
3113
+ /**
3114
+ * 从 QA_Report.md 的前置块里把 assertions 读回来。
3115
+ *
3116
+ * 和 parseIssueBlock 一个路子:只认 assertions: 那一段,别的不碰。
3117
+ * 面板要显示「哪条命令挂了、退出码多少」,光一个 fail 计数说不出事。
3118
+ *
3119
+ * stdoutTail 是 `|` 块,可能是好几行,这里不读内容——面板只显示有没有输出、
3120
+ * 失败时给个入口让人去看原文件。把整段 stdout 塞进面板反而没法看。
3121
+ */
3122
+ export function parseAssertionBlock(text) {
3123
+ const { front } = splitFrontMatter(text)
3124
+ if (front === '') return []
3125
+ const rows = []
3126
+ let inBlock = false
3127
+ let current
3128
+ for (const rawLine of front.split(/\r?\n/u)) {
3129
+ const line = rawLine.replace(/\s+$/u, '')
3130
+ if (/^assertions\s*:\s*(\[\])?\s*$/u.test(line)) {
3131
+ inBlock = true
3132
+ continue
3133
+ }
3134
+ // 顶格的非空行意味着这一段结束了。
3135
+ if (inBlock && /^[A-Za-z_]\w*\s*:/u.test(line)) {
3136
+ inBlock = false
3137
+ current = undefined
3138
+ }
3139
+ if (!inBlock) continue
3140
+ const start = /^\s*-\s*req\s*:\s*(.+)$/u.exec(line)
3141
+ if (start !== null) {
3142
+ const req = Number.parseInt(unquoteScalar(start[1]), 10)
3143
+ current = { req: Number.isInteger(req) ? req : rows.length + 1 }
3144
+ rows.push(current)
3145
+ continue
3146
+ }
3147
+ if (current === undefined) continue
3148
+ const field = /^\s+(cmd|exit|durationMs|status)\s*:\s*(.*)$/u.exec(line)
3149
+ if (field === null) continue
3150
+ const [, key, rawValue] = field
3151
+ const value = unquoteScalar(rawValue)
3152
+ if (key === 'cmd') current.cmd = value
3153
+ else if (key === 'status') current.status = value
3154
+ else {
3155
+ const num = Number.parseInt(value, 10)
3156
+ current[key] = Number.isInteger(num) ? num : null
3157
+ }
3158
+ }
3159
+ return rows
3160
+ }
3161
+
3162
+ /**
3163
+ * 从 QA_Report.md 的前置块里把 issues 读回来。
3164
+ *
3165
+ * 读回来是为了「上一轮那条」还认得出来:跨轮的 id、closed 不许复活、
3166
+ * 同区段重开,全都建立在这份读得回来的基础上。
3167
+ */
3168
+ export function parseIssueBlock(text) {
3169
+ const { front } = splitFrontMatter(text)
3170
+ if (front === '') return []
3171
+ const issues = []
3172
+ let inIssues = false
3173
+ let current
3174
+ for (const rawLine of front.split(/\r?\n/u)) {
3175
+ const line = rawLine.replace(/\s+$/u, '')
3176
+ if (/^issues\s*:\s*(\[\])?\s*$/u.test(line)) {
3177
+ inIssues = true
3178
+ continue
3179
+ }
3180
+ if (inIssues && /^[A-Za-z_]\w*\s*:/u.test(line)) {
3181
+ inIssues = false
3182
+ current = undefined
3183
+ }
3184
+ if (!inIssues) continue
3185
+ const start = /^\s*-\s*id\s*:\s*(.*)$/u.exec(line)
3186
+ if (start !== null) {
3187
+ current = { id: unquoteScalar(start[1]) }
3188
+ issues.push(current)
3189
+ continue
3190
+ }
3191
+ if (current === undefined) continue
3192
+ const field = /^\s+(severity|location|claim|evidence|detect|pass|status|note)\s*:\s*(.*)$/u.exec(line)
3193
+ if (field === null) {
3194
+ const rounds = /^\s+rounds\s*:\s*(\d+)\s*$/u.exec(line)
3195
+ if (rounds !== null && current !== undefined) current.roundsOpen = Number(rounds[1])
3196
+ continue
3197
+ }
3198
+ current[field[1]] = unquoteScalar(field[2])
3199
+ }
3200
+ return issues.filter(item => typeof item.id === 'string' && item.id !== '')
3201
+ }
3202
+
3203
+ /** 一条 issue 写成 YAML 行。文字里的换行交给 JSON 转义,读回来还是原文。 */
3204
+ function issueLines(issue) {
3205
+ const lines = [
3206
+ ` - id: ${quoteScalar(issue.id)}`,
3207
+ ` severity: ${quoteScalar(issue.severity)}`,
3208
+ ` location: ${quoteScalar(issue.location)}`,
3209
+ ` claim: ${quoteScalar(issue.claim)}`,
3210
+ ` evidence: ${quoteScalar(issue.evidence)}`,
3211
+ ` detect: ${quoteScalar(issue.detect)}`,
3212
+ ` pass: ${quoteScalar(issue.pass)}`,
3213
+ ` status: ${quoteScalar(issue.status)}`,
3214
+ ]
3215
+ if (typeof issue.note === 'string' && issue.note !== '') lines.push(` note: ${quoteScalar(issue.note)}`)
3216
+ // 连续几轮没闭环。用来触发「别再无脑返工了」的那道闸,
3217
+ // 和 maxRework 不是一回事:maxRework 数的是整轮,这个数的是同一条问题。
3218
+ if (Number.isInteger(issue.roundsOpen) && issue.roundsOpen > 0) lines.push(` rounds: ${issue.roundsOpen}`)
3219
+ return lines
3220
+ }
3221
+
3222
+ /**
3223
+ * 把这一轮的模型意见并进上一轮的台账。
3224
+ *
3225
+ * 规则(每一条都对应一个具体的翻车现场):
3226
+ * - 认得出是同一条 → 沿用原 id,不新发号
3227
+ * - 上一轮 closed 的,模型这轮又提,只有在 diff 真碰了同一文件同一区段时
3228
+ * 才算 reopened;否则忽略——不然「修好的」会被一句模糊重述反复翻案
3229
+ * - 上一轮 open 的,这轮模型没提到 → 保持 open。没提到不等于修好了
3230
+ * - detect / pass 缺一个 → invalid:这条问题没法验,整轮按 FAIL 处理
3231
+ * - 模型明写 resolved: true → closed
3232
+ */
3233
+ export function mergeIssueRounds(previous, incoming, diffText) {
3234
+ const prev = Array.isArray(previous) ? previous : []
3235
+ const next = Array.isArray(incoming) ? incoming : []
3236
+ let maxIndex = 0
3237
+ for (const item of prev) {
3238
+ const match = /^Q-(\d+)$/u.exec(String(item?.id ?? ''))
3239
+ if (match !== null) maxIndex = Math.max(maxIndex, Number(match[1]))
3240
+ }
3241
+ const byKey = new Map()
3242
+ for (const item of prev) byKey.set(issueKeyOf(item), item)
3243
+ const touched = new Set()
3244
+ const issues = []
3245
+ const reopened = []
3246
+ const invalid = []
3247
+
3248
+ for (const item of next) {
3249
+ const key = issueKeyOf(item)
3250
+ const old = byKey.get(key)
3251
+ const missing = normalizeIssueText(item.detect) === '' || normalizeIssueText(item.pass) === ''
3252
+ if (old !== undefined && touched.has(old.id) !== true) {
3253
+ touched.add(old.id)
3254
+ const sameFile = diffTouches(diffText, item.location)
3255
+ if (old.status === 'closed') {
3256
+ if (item.resolved === true) continue
3257
+ if (sameFile !== true) continue
3258
+ const revived = { ...old, ...item, id: old.id, status: 'reopened', note: '上一轮判 closed,这一轮 diff 又动了同一处' }
3259
+ issues.push(revived)
3260
+ reopened.push(revived)
3261
+ continue
3262
+ }
3263
+ const status = item.resolved === true ? 'closed' : missing ? 'invalid' : 'open'
3264
+ const roundsOpen = status === 'closed' ? 0 : (Number.isInteger(old.roundsOpen) ? old.roundsOpen : 0) + 1
3265
+ const merged = {
3266
+ ...old,
3267
+ ...item,
3268
+ id: old.id,
3269
+ status,
3270
+ roundsOpen,
3271
+ ...(missing ? { note: '缺少 detect 或 pass,验不了' } : {}),
3272
+ }
3273
+ issues.push(merged)
3274
+ if (status === 'invalid') invalid.push(merged)
3275
+ continue
3276
+ }
3277
+ // 新问题:发新号。同一轮里重复描述的,认第一个。
3278
+ if ([...issues, ...prev].some(candidate => issueKeyOf(candidate) === key)) continue
3279
+ maxIndex += 1
3280
+ const id = `Q-${String(maxIndex).padStart(3, '0')}`
3281
+ const status = missing ? 'invalid' : item.resolved === true ? 'closed' : 'open'
3282
+ const created = { ...item, id, status, ...(missing ? { note: '缺少 detect 或 pass,验不了' } : {}) }
3283
+ issues.push(created)
3284
+ if (status === 'invalid') invalid.push(created)
3285
+ }
3286
+
3287
+ // 模型没提到的上轮问题:原样留下。不提到不等于修好,这条是闭环能不能信的关键。
3288
+ for (const item of prev) {
3289
+ if (touched.has(item.id)) continue
3290
+ if (item.status === 'closed') continue
3291
+ issues.push({
3292
+ ...item,
3293
+ roundsOpen: (Number.isInteger(item.roundsOpen) ? item.roundsOpen : 0) + 1,
3294
+ })
3295
+ }
3296
+
3297
+ // 条数超限:先保 P0/P1,其余标 deferred,不参与返工判据。
3298
+ const processed = []
3299
+ const deferred = []
3300
+ for (const item of issues) {
3301
+ const counts = item.status === 'open' || item.status === 'reopened' || item.status === 'invalid'
3302
+ if (counts && item.severity === 'P2' && issues.length > ISSUE_LIMIT) {
3303
+ deferred.push({ ...item, status: 'deferred' })
3304
+ continue
3305
+ }
3306
+ processed.push(item)
3307
+ }
3308
+ const finalList = processed.concat(deferred)
3309
+ const open = finalList.filter(item => item.status === 'open' || item.status === 'reopened')
3310
+ // 同一条问题连着三轮没闭环:再多返工也是原地打转,这道闸比 maxRework 更早响。
3311
+ const stuck = open.filter(item => (Number.isInteger(item.roundsOpen) ? item.roundsOpen : 0) >= 3)
3312
+ return {
3313
+ issues: finalList,
3314
+ open,
3315
+ openCount: open.length,
3316
+ openP0P1: open.filter(item => item.severity === 'P0' || item.severity === 'P1').length,
3317
+ reopened,
3318
+ invalid,
3319
+ deferred,
3320
+ stuck,
3321
+ }
3322
+ }
3323
+
3324
+ /** 这一轮的 diff 有没有碰这条问题指的那处。文件对上、行号落在 hunk 里才算。 */
3325
+ export function diffTouches(diffText, location) {
3326
+ const text = typeof diffText === 'string' ? diffText : ''
3327
+ const loc = normalizeIssueText(location)
3328
+ if (text === '' || loc === '') return false
3329
+ const filePart = loc.split(':')[0].trim().replace(/^\.\//u, '').replace(/^[ab]\//u, '')
3330
+ if (filePart === '') return false
3331
+ const lineMatch = /:(\d+)/u.exec(loc)
3332
+ const line = lineMatch === null ? undefined : Number(lineMatch[1])
3333
+ let currentFile = ''
3334
+ let range
3335
+ for (const rawLine of text.split(/\r?\n/u)) {
3336
+ const header = /^\+\+\+ b\/(.+)$/u.exec(rawLine)
3337
+ if (header !== null) {
3338
+ currentFile = header[1].trim()
3339
+ range = undefined
3340
+ continue
3341
+ }
3342
+ const hunk = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/u.exec(rawLine)
3343
+ if (hunk !== null) {
3344
+ range = { start: Number(hunk[1]), count: hunk[2] === undefined ? 1 : Number(hunk[2]) }
3345
+ continue
3346
+ }
3347
+ if (currentFile === '' || range === undefined) continue
3348
+ if (currentFile !== filePart && currentFile.endsWith(`/${filePart}`) !== true) continue
3349
+ if (line === undefined) return true
3350
+ const end = range.start + Math.max(range.count, 1) - 1
3351
+ if (line >= range.start && line <= end) return true
3352
+ }
3353
+ return false
3354
+ }
3355
+
3356
+ /**
3357
+ * 模型没按 JSON 回、改交了一张表时的兜底。
3358
+ *
3359
+ * 只有表头里明写严重级那一列才认;没有那一列的表格整张跳过。
3360
+ * 早期版本的规则是「第 2 格长得像 P0-P3 就当缺陷」——那不是解析,那是猜。
3361
+ */
3362
+ export function parseIssueTables(text) {
3363
+ const source = typeof text === 'string' ? text : ''
3364
+ const lines = source.split(/\r?\n/u)
3365
+ const issues = []
3366
+ for (let index = 0; index < lines.length; index += 1) {
3367
+ const header = lines[index].trim()
3368
+ if (header.startsWith('|') !== true || /^\|[\s:-]+\|/u.test(header)) continue
3369
+ const cells = header.split('|').map(cell => cell.trim()).filter((cell, at, all) => at > 0 && at < all.length - 1)
3370
+ const severityAt = cells.findIndex(cell => /^(严重级|严重程度|severity|优先级|级别)$/iu.test(cell))
3371
+ if (severityAt === -1) {
3372
+ // 整张跳过:没有声明严重级的表,说什么都不算缺陷清单。
3373
+ while (index < lines.length && lines[index].trim().startsWith('|')) index += 1
3374
+ continue
3375
+ }
3376
+ const pick = names => cells.findIndex(cell => names.some(name => new RegExp(name, 'iu').test(cell)))
3377
+ const locationAt = pick(['位置', 'location', '文件'])
3378
+ const claimAt = pick(['问题', 'claim', '描述', '缺陷'])
3379
+ const evidenceAt = pick(['证据', 'evidence'])
3380
+ const detectAt = pick(['检测', 'detect', '复现', '怎么验'])
3381
+ const passAt = pick(['通过', 'pass', '验收', '标准'])
3382
+ let row = index + 1
3383
+ if (row < lines.length && /^\|[\s:|-]+\|$/u.test(lines[row].trim())) row += 1
3384
+ for (; row < lines.length; row += 1) {
3385
+ const line = lines[row].trim()
3386
+ if (line.startsWith('|') !== true) break
3387
+ const cellsOfRow = line.split('|').map(cell => cell.trim()).filter((cell, at, all) => at > 0 && at < all.length - 1)
3388
+ const severity = (cellsOfRow[severityAt] ?? '').toUpperCase()
3389
+ if (SEVERITIES.includes(severity) !== true) continue
3390
+ issues.push({
3391
+ severity,
3392
+ location: locationAt === -1 ? '' : cellsOfRow[locationAt] ?? '',
3393
+ claim: claimAt === -1 ? '' : cellsOfRow[claimAt] ?? '',
3394
+ evidence: evidenceAt === -1 ? '' : cellsOfRow[evidenceAt] ?? '',
3395
+ detect: detectAt === -1 ? '' : cellsOfRow[detectAt] ?? '',
3396
+ pass: passAt === -1 ? '' : cellsOfRow[passAt] ?? '',
3397
+ })
3398
+ }
3399
+ index = row - 1
3400
+ }
3401
+ return issues
3402
+ }
3403
+
3404
+ /** 实施段交上来的修复清单,写成 Execution_Log.md 里那一节。 */
3405
+ export function renderFixLog(fixes, round) {
3406
+ const list = Array.isArray(fixes) ? fixes : []
3407
+ if (list.length === 0) return ''
3408
+ const lines = [`## 本轮修复(R${round})`, '']
3409
+ for (const item of list) {
3410
+ const id = normalizeIssueText(item?.id) || 'Q-???'
3411
+ const change = normalizeIssueText(item?.change) || '(没写改了什么)'
3412
+ const command = normalizeIssueText(item?.command)
3413
+ const result = normalizeIssueText(item?.result)
3414
+ lines.push(`- ${id} → ${change}${command === '' ? '' : ` → \`${command}\``} → ${result === '' ? '(没写结果)' : result}`)
3415
+ }
3416
+ return lines.join('\n')
3417
+ }
3418
+
3419
+ /** 给质检看的上一轮台账:让它逐条回答修没修,而不是重新写一份新的。 */
3420
+ export function renderKnownIssues(issues) {
3421
+ const list = Array.isArray(issues) ? issues : []
3422
+ const open = list.filter(item => item.status === 'open' || item.status === 'reopened')
3423
+ if (open.length === 0) return ''
3424
+ const lines = [
3425
+ '## 上一轮还没闭环的问题(逐条回答,别重新编号)',
3426
+ '',
3427
+ ]
3428
+ for (const item of open) {
3429
+ lines.push(`- ${item.id}|${item.severity}|${item.location || '(没写位置)'}|${item.claim}`)
3430
+ if (item.pass !== '') lines.push(` 通过标准:${item.pass}`)
3431
+ if (item.detect !== '') lines.push(` 检测方式:${item.detect}`)
3432
+ }
3433
+ lines.push('', '修好了就在这一轮的 issues 里带上同一个 id 并写 "resolved": true;没修就照原样再列一遍。')
3434
+ return lines.join('\n')
3435
+ }
3436
+
1636
3437
  /** Every project under `.project-flow` as a status line, sorted by name. */
1637
3438
  async function listProjectLines(cwd) {
1638
3439
  let names = []
@@ -1863,7 +3664,7 @@ function snapshotLabel(label) {
1863
3664
  * no changes reuses the previous commit instead of piling up empty ones.
1864
3665
  */
1865
3666
  async function takeSnapshot(cwd, project, label, options = {}) {
1866
- const { excludes = DEFAULT_SNAPSHOT_EXCLUDES, allowEmpty = false } = options
3667
+ const { excludes = DEFAULT_SNAPSHOT_EXCLUDES, allowEmpty = false, keep } = options
1867
3668
  if (await gitAvailable() !== true) {
1868
3669
  return { ok: false, reason: '这台机器上没有可用的 git,快照与回滚不可用' }
1869
3670
  }
@@ -1894,12 +3695,12 @@ async function takeSnapshot(cwd, project, label, options = {}) {
1894
3695
  // after removing it; the operation is idempotent, so a retry is safe.
1895
3696
  if (/index\.lock/iu.test(add.stderr) && await clearStaleIndexLock(cwd, project)) {
1896
3697
  const retried = await snapshotCommand(cwd, project, ['add', '-A'], { timeoutMs: 600000 })
1897
- if (retried.ok) return finishSnapshot(cwd, project, label, { allowEmpty })
3698
+ if (retried.ok) return finishSnapshot(cwd, project, label, { allowEmpty, keep })
1898
3699
  return { ok: false, reason: `暂存工作区失败:${retried.stderr.trim() || retried.message}` }
1899
3700
  }
1900
3701
  return { ok: false, reason: `暂存工作区失败:${add.stderr.trim() || add.message}` }
1901
3702
  }
1902
- return finishSnapshot(cwd, project, label, { allowEmpty })
3703
+ return finishSnapshot(cwd, project, label, { allowEmpty, keep })
1903
3704
  }
1904
3705
 
1905
3706
  /**
@@ -1918,9 +3719,72 @@ async function clearStaleIndexLock(cwd, project) {
1918
3719
  }
1919
3720
  }
1920
3721
 
3722
+ /**
3723
+ * 快照保留上限:只留最近 keep 张,更老的截掉。
3724
+ *
3725
+ * snap.git 只增不删的话,跑十几轮返工的项目体积会一直涨——每次实施前后各一张,
3726
+ * 一个正常项目跑完轻松上百张。这里在每次提交后顺手截一次。
3727
+ *
3728
+ * 用的是「造一个新根,把最近 keep 个提交接上去」的办法,不走 rebase:
3729
+ * rebase 会重放每个 commit,快照仓库里几百个 commit 重放一次就是几百次写盘,
3730
+ * 而且中途失败还得回滚。commit-tree 造根是一次性的,失败了也不动 HEAD。
3731
+ *
3732
+ * 一句实话:截掉的那段历史就真的没了(用户本来也只能看最近几十张)。
3733
+ * 保留上限由 snapshotKeep 配,设 0 关掉。
3734
+ */
3735
+ export async function pruneSnapshots(cwd, project, keep) {
3736
+ if (await gitAvailable() !== true) return { ok: false, reason: '没有可用的 git' }
3737
+ if (!Number.isInteger(keep) || keep <= 0) return { ok: true, pruned: 0, count: undefined }
3738
+
3739
+ const total = await snapshotCommand(cwd, project, ['rev-list', '--count', 'HEAD'])
3740
+ if (!total.ok) return { ok: false, reason: '读不到快照数量' }
3741
+ const count = Number(total.stdout.trim())
3742
+ if (!Number.isFinite(count) || count <= keep) return { ok: true, pruned: 0, count }
3743
+
3744
+ const head = await snapshotCommand(cwd, project, ['rev-parse', 'HEAD'])
3745
+ if (!head.ok) return { ok: false, reason: '读不到 HEAD' }
3746
+
3747
+ // 第 keep 个提交(从 1 数):它将成为新的「最早那一张」。
3748
+ const boundary = await snapshotCommand(cwd, project, ['rev-list', `--max-count=1`, `--skip=${keep - 1}`, 'HEAD'])
3749
+ if (!boundary.ok || boundary.stdout.trim() === '') return { ok: true, pruned: 0, count }
3750
+ const boundarySha = boundary.stdout.trim()
3751
+
3752
+ // 用 boundary 那棵树造一个没有父提交的新根,再把边界点之后的提交接到它上面。
3753
+ const tree = await snapshotCommand(cwd, project, ['rev-parse', `${boundarySha}^{tree}`])
3754
+ if (!tree.ok) return { ok: false, reason: '读不到边界提交的树' }
3755
+ const root = await snapshotCommand(cwd, project, ['commit-tree', tree.stdout.trim(), '-m', snapshotLabel('更早的快照已截断')])
3756
+ if (!root.ok) return { ok: false, reason: '造新根失败' }
3757
+
3758
+ // cherry-pick 的形态太重,这里用最朴素的办法:只保留最近 keep 个 commit 的
3759
+ // 树内容,把它们逐个接到新根上。数量不大(keep 默认 40),够用且可回退。
3760
+ const recent = await snapshotCommand(cwd, project, ['rev-list', `--max-count=${keep - 1}`, boundarySha])
3761
+ if (!recent.ok) return { ok: false, reason: '读不到要保留的提交' }
3762
+ let parent = root.stdout.trim()
3763
+ for (const sha of recent.stdout.trim().split('\n').filter(line => line !== '').reverse()) {
3764
+ const t = await snapshotCommand(cwd, project, ['rev-parse', `${sha}^{tree}`])
3765
+ if (!t.ok) continue
3766
+ const subject = await snapshotCommand(cwd, project, ['log', '-1', '--pretty=format:%s', sha])
3767
+ const next = await snapshotCommand(cwd, project, [
3768
+ 'commit-tree', t.stdout.trim(), '-p', parent, '-m', subject.ok ? subject.stdout.trim() : '快照',
3769
+ ])
3770
+ if (!next.ok) continue
3771
+ parent = next.stdout.trim()
3772
+ }
3773
+
3774
+ const moved = await snapshotCommand(cwd, project, ['reset', '--soft', parent])
3775
+ if (!moved.ok) {
3776
+ // 没动过 HEAD 的话这里根本不会失败;真失败了就把 HEAD 拉回原处。
3777
+ await snapshotCommand(cwd, project, ['reset', '--soft', head.stdout.trim()])
3778
+ return { ok: false, reason: '接新根失败,已回到截断前' }
3779
+ }
3780
+ await snapshotCommand(cwd, project, ['gc', '--prune=now', '--quiet'], { timeoutMs: 300000 })
3781
+ const after = await snapshotCommand(cwd, project, ['rev-list', '--count', 'HEAD'])
3782
+ return { ok: true, pruned: count - keep, count: after.ok ? Number(after.stdout.trim()) : undefined }
3783
+ }
3784
+
1921
3785
  /** Commit the staged snapshot, reusing HEAD when nothing changed. */
1922
3786
  async function finishSnapshot(cwd, project, label, options = {}) {
1923
- const { allowEmpty = false } = options
3787
+ const { allowEmpty = false, keep } = options
1924
3788
  const head = await snapshotCommand(cwd, project, ['rev-parse', 'HEAD'])
1925
3789
  const diff = await snapshotCommand(cwd, project, ['diff', '--cached', '--quiet'])
1926
3790
  const dirty = !diff.ok // `--quiet` exits 1 when there are staged changes
@@ -1932,7 +3796,12 @@ async function finishSnapshot(cwd, project, label, options = {}) {
1932
3796
  return { ok: false, reason: `建立快照失败:${commit.stderr.trim() || commit.message}` }
1933
3797
  }
1934
3798
  const after = await snapshotCommand(cwd, project, ['rev-parse', 'HEAD'])
1935
- return { ok: true, commit: after.stdout.trim(), reused: false }
3799
+ // 顺手压一次历史:失败不影响这次快照已经建好这件事。
3800
+ let pruned
3801
+ if (Number.isInteger(keep) && keep > 0) {
3802
+ pruned = await pruneSnapshots(cwd, project, keep).catch(() => undefined)
3803
+ }
3804
+ return { ok: true, commit: after.stdout.trim(), reused: false, ...(pruned === undefined ? {} : { pruned }) }
1936
3805
  }
1937
3806
 
1938
3807
  /** Every snapshot, newest first. */
@@ -2070,10 +3939,16 @@ ${rework ? `这次是返工。上一轮质检判了 FAIL,意见在 ${ARTIFACT.
2070
3939
  {
2071
3940
  "summary": "你实际做了什么,逐条对应任务书",
2072
3941
  "files": ["改动的文件路径"],
3942
+ "fixes": [
3943
+ { "id": "Q-002", "change": "改了什么", "command": "你为这一条跑过的验证命令", "result": "通过 / 还是没过" }
3944
+ ],
2073
3945
  "deviations": ["与任务书不一致的地方;没有就空数组"],
2074
3946
  "unresolved": ["没做完或做不到的;没有就空数组"]
2075
3947
  }
2076
3948
  \`\`\`
3949
+
3950
+ \`fixes\` 只在返工时写:一条对应 ${ARTIFACT.qa} 里的一个编号,每行只说「改了什么、跑了哪条命令、结果如何」,
3951
+ 不要写散文,也不要漏——漏掉的那条下一轮还是 open。
2077
3952
  `
2078
3953
 
2079
3954
  /** 载体 id → 中文名,给采集环节的 prompt 用。认不出来的 id 原样带出。 */
@@ -2150,12 +4025,35 @@ diff 里改了、任务书里没要求的,算做多了。diff 拿不到的时
2150
4025
  输出必须是一个 JSON 代码块,verdict 只允许 PASS 或 FAIL 两个值:
2151
4026
  \`\`\`json
2152
4027
  {
2153
- "verdict": "PASS",
4028
+ "verdict": "FAIL",
4029
+ "issues": [
4030
+ {
4031
+ "severity": "P1",
4032
+ "location": "src/a.ts:12",
4033
+ "claim": "空数组会走到 reduce 里抛 TypeError",
4034
+ "evidence": "diff 第 12 行直接 reduce,没有 length 判断",
4035
+ "detect": "node -e \\"const f=require('./src/a'); f([])\\"",
4036
+ "pass": "f([]) 返回 [] 而不是抛错",
4037
+ "resolved": false
4038
+ }
4039
+ ],
2154
4040
  "reasons": ["判 PASS 时写你核过哪几条;判 FAIL 时写具体哪里不达标,最多 5 条,每条要能被下一轮照着改"],
2155
4041
  "acceptable_risks": ["判 PASS 时列你知道但没有解决、且判断可以接受的风险;没有就空数组"]
2156
4042
  }
2157
4043
  \`\`\`
2158
4044
 
4045
+ ## 问题清单的三条硬规矩
4046
+
4047
+ 1. **每条都要有 \`detect\` 和 \`pass\`。** \`detect\` 是一条能跑的命令、或者一步能照着做的检查;
4048
+ \`pass\` 是「做到什么算过」。缺一个,这条问题就不成立,整轮按「问题缺少可执行定义」判 FAIL
4049
+ ——没有验法的意见,下一轮改不改都说不清。
4050
+ 2. **\`severity\` 只认 \`P0\` \`P1\` \`P2\`。** P0 = 交不了,P1 = 明显不对,P2 = 可以留到以后。
4051
+ 3. **上一轮的问题要给答复。** 见了 id 就在同一份 issues 里带上那个 id:修好了写 \`"resolved": true\`,
4052
+ 没修就照原样再列一遍(可以不重复描述)。不要换个说法另开一条——那会变成两个问题。
4053
+
4054
+ 要交表格也行,但表头必须有「严重级」这一列(位置 / 问题 / 证据 / 检测 / 通过标准 也按这个顺序列)。
4055
+ 没有严重级那一列的表会被整张跳过,等于没写。
4056
+
2159
4057
  \`acceptable_risks\` 是给验收报告用的:这些风险会被原样写进完成证据包,
2160
4058
  所以每条都要写成人能看懂的一句话——「没做并发测试,单机场景够用」这种,
2161
4059
  不要写「可能存在风险」这种谁都能说的话。
@@ -2165,7 +4063,7 @@ diff 里改了、任务书里没要求的,算做多了。diff 拿不到的时
2165
4063
 
2166
4064
  不要写建议、不要写评价、不要写「基本通过」。只有 PASS 和 FAIL 两个词。`
2167
4065
 
2168
- const QA_PROMPT = (requirement, plan, log, diff) => {
4066
+ const QA_PROMPT = (requirement, plan, log, diff, known = '') => {
2169
4067
 
2170
4068
  const diffSection = diff?.ok === true
2171
4069
  ? (diff.text.trim() === ''
@@ -2191,7 +4089,7 @@ ${log}
2191
4089
  ## 改动(从快照仓库两端算出来的 git diff)
2192
4090
 
2193
4091
  ${diffSection}
2194
- `
4092
+ ${known === '' ? '' : `\n${known}\n`}`
2195
4093
  }
2196
4094
 
2197
4095
  /**
@@ -2616,6 +4514,57 @@ async function watchRootOf(cwd, settings) {
2616
4514
  * 客户端自己也能从 .project-flow 里读,但这个函数让模型和命令也能问
2617
4515
  * 「现在什么状态」,两边口径一致。
2618
4516
  */
4517
+ /**
4518
+ * 面板要的那一小份报告摘要。
4519
+ *
4520
+ * 不返回全文:面板一屏放不下,QA_Report.md 本身是给人读的散文。
4521
+ * 只留三样——还开着的问题、断言的分类计数、挂掉的那几条命令。
4522
+ *
4523
+ * 读不到就返回空结构,不报错:没跑过质检的项目本来就没有这份报告。
4524
+ */
4525
+ async function panelReportOf(watch, name) {
4526
+ let text
4527
+ try {
4528
+ text = await readArtifact(watch, name, ARTIFACT.qa)
4529
+ } catch {
4530
+ text = undefined
4531
+ }
4532
+ const empty = { issues: [], assertions: { total: 0, pass: 0, fail: 0, unverified: 0 }, failed: [] }
4533
+ if (typeof text !== 'string' || text.trim() === '') return empty
4534
+
4535
+ const all = parseIssueBlock(text)
4536
+ const assertions = parseAssertionBlock(text)
4537
+ const count = status => assertions.filter(item => item.status === status).length
4538
+ return {
4539
+ issues: all
4540
+ .filter(item => item.status === 'open' || item.status === 'reopened')
4541
+ .map(item => ({
4542
+ id: typeof item.id === 'string' ? item.id : '',
4543
+ severity: typeof item.severity === 'string' ? item.severity : '',
4544
+ location: typeof item.location === 'string' ? item.location.slice(0, 120) : '',
4545
+ claim: typeof item.claim === 'string' ? item.claim.slice(0, 160) : '',
4546
+ detect: typeof item.detect === 'string' ? item.detect.slice(0, 160) : '',
4547
+ status: item.status,
4548
+ })),
4549
+ assertions: {
4550
+ total: assertions.length,
4551
+ pass: count('pass'),
4552
+ fail: count('fail'),
4553
+ unverified: count('unverified'),
4554
+ },
4555
+ // 挂掉的命令单独拎出来。面板上要显示「哪一条、退出码多少」——
4556
+ // 只说「失败 1 条」等于让人再去翻文件。
4557
+ failed: assertions
4558
+ .filter(item => item.status === 'fail' || item.status === 'timeout' || item.status === 'denied')
4559
+ .map(item => ({
4560
+ req: item.req,
4561
+ cmd: typeof item.cmd === 'string' ? item.cmd.slice(0, 160) : '',
4562
+ exit: Number.isInteger(item.exit) ? item.exit : null,
4563
+ status: item.status,
4564
+ })),
4565
+ }
4566
+ }
4567
+
2619
4568
  export async function panelSnapshot(cwd, settings, onlyProject, sessionId) {
2620
4569
  const watch = await watchRootOf(cwd, settings)
2621
4570
  const inside = insideFlow(cwd, settings)
@@ -2647,6 +4596,9 @@ export async function panelSnapshot(cwd, settings, onlyProject, sessionId) {
2647
4596
  status: typeof state.status === 'string' ? state.status : '',
2648
4597
  rework: typeof state.rework === 'number' ? state.rework : 0,
2649
4598
  maxRework: typeof state.maxRework === 'number' ? state.maxRework : settings.maxRework,
4599
+ // 未闭环问题数(P0+P1 的 open+reopened 数):阶段灯旁那个 open: N。
4600
+ // 它和 rework 是两件事——一个是「还剩几件事」,一个是「花了几轮」。
4601
+ open: typeof state.openCritical === 'number' ? state.openCritical : (typeof state.openIssues === 'number' ? state.openIssues : 0),
2650
4602
  running: runningEntry !== undefined,
2651
4603
  /**
2652
4604
  * 这个项目是不是「你这个会话」开的。
@@ -2658,6 +4610,21 @@ export async function panelSnapshot(cwd, settings, onlyProject, sessionId) {
2658
4610
  mine: runningEntry !== undefined
2659
4611
  && sessionId !== undefined
2660
4612
  && runningEntry.sessionId === sessionId,
4613
+ /**
4614
+ * 这个项目是不是「你这个对话」碰过的——跑完之后也算。
4615
+ *
4616
+ * mine 只覆盖「正在跑」,跑完就假了;状态栏靠这一条才能一个对话一个,
4617
+ * 而不是所有对话都退回显示同一个项目。
4618
+ *
4619
+ * 三种值,缺一不可:
4620
+ * true 归我
4621
+ * false 不归我(这个项目有归属记录,但里面没有我这个会话)
4622
+ * null 未知归属——升级之前跑的老项目没有 ownerSessions,
4623
+ * 不能judge成「不是我的」,否则升级当天所有老项目一起消失
4624
+ */
4625
+ owned: sessionId !== undefined && Array.isArray(state.ownerSessions)
4626
+ ? state.ownerSessions.includes(sessionId)
4627
+ : null,
2661
4628
  // 已花掉的钱:每阶结束都会落盘,状态栏直接读,不用再算
2662
4629
  cost: state.cost === undefined ? undefined : {
2663
4630
  cny: state.cost.spentCny,
@@ -2665,10 +4632,20 @@ export async function panelSnapshot(cwd, settings, onlyProject, sessionId) {
2665
4632
  },
2666
4633
  interruptedAt: state.interruptedAt ?? null,
2667
4634
  updatedAt: state.updatedAt ?? null,
4635
+ // 开工时间。面板要显示「这一轮跑了多久」——只有 updatedAt 算不出时长,
4636
+ // 而 state 里本来就有这一项,不用另存。
4637
+ startedAt: state.startedAt ?? null,
2668
4638
  verdict: typeof state.verdict === 'string' ? state.verdict : '',
4639
+ // 面板要能看到「还差哪几条」「哪条命令没过」。光有一个 open 数字
4640
+ // 说不出事,用户还得去翻 QA_Report.md——那正是这个面板想省掉的一步。
4641
+ //
4642
+ // 读不到就返回空数组,不报错:没跑过质检的项目本来就没有这份报告。
4643
+ report: await panelReportOf(watch, name),
2669
4644
  })
2670
4645
  }
2671
4646
  const snapshot = {
4647
+ // 面板顶栏那一行要显示插件版本。宿主自己读 package.json,不靠客户端猜。
4648
+ version: PKG_VERSION,
2672
4649
  // 算出来的时间。客户端靠它判断这份是不是自己刚触发的那一次——
2673
4650
  // 缓存是全进程共用的,不校验时间就会读到别的栏(工作流/默认工作区)的数据。
2674
4651
  at: nowIso(),
@@ -2765,9 +4742,13 @@ export function apply(ctx, config) {
2765
4742
  staleLockMs: config.staleLockMs ?? 1800000,
2766
4743
  snapshotEnabled: config.snapshotEnabled === undefined ? true : config.snapshotEnabled,
2767
4744
  snapshotExcludes: config.snapshotExcludes ?? '',
4745
+ snapshotKeep: Number.isInteger(config.snapshotKeep) ? config.snapshotKeep : 40,
2768
4746
  flowRoot: config.flowRoot ?? '',
2769
- flowGate: config.flowGate ?? 'strict',
4747
+ flowGate: config.flowGate ?? 'off',
2770
4748
  autoCreateFlowDir: config.autoCreateFlowDir === undefined ? true : config.autoCreateFlowDir,
4749
+ // 意图门控强度:off(默认,只由 project_run 自查)/ enforce(注册前置拦截)。
4750
+ // 少这一行的时候配置里写什么都没用——settingsOf() 会读成 undefined。
4751
+ intentGate: config.intentGate ?? 'off',
2771
4752
  desktopTools: config.desktopTools ?? 'auto',
2772
4753
  aesthetic: config.aesthetic ?? 'auto',
2773
4754
  aestheticImages: config.aestheticImages === undefined ? true : config.aestheticImages,
@@ -2788,6 +4769,11 @@ export function apply(ctx, config) {
2788
4769
  testCommand: config.testCommand ?? 'auto',
2789
4770
  testTimeoutMs: config.testTimeoutMs ?? 600000,
2790
4771
  cnyRate: config.cnyRate ?? 7,
4772
+ // 断言执行器:白名单、单条超时、输出留尾的长度。
4773
+ checkAllowedCommands: config.checkAllowedCommands ?? '',
4774
+ checkStrictEval: config.checkStrictEval === true,
4775
+ checkTimeoutMs: config.checkTimeoutMs ?? 120000,
4776
+ checkStdoutTailChars: config.checkStdoutTailChars ?? 8000,
2791
4777
  }
2792
4778
 
2793
4779
  const overridePaths = () => {
@@ -2932,12 +4918,36 @@ function splitRoute(value) {
2932
4918
  type: 'array',
2933
4919
  required: true,
2934
4920
  items: { type: 'string' },
2935
- description: '用户的要求,一条一行,要能逐条核对。质检环节会照着这些逐项验。',
4921
+ description: '用户的要求,一条一行,要能逐条核对。质检环节会照着这些逐项验。要带断言就在这一条里加一行 `check: <命令>`,或者改用 checks 参数。',
4922
+ },
4923
+ checks: {
4924
+ type: 'array',
4925
+ items: {
4926
+ type: 'object',
4927
+ additionalProperties: false,
4928
+ required: ['req', 'check'],
4929
+ properties: {
4930
+ req: { type: 'integer', description: 'requirements 里第几条,1 起。' },
4931
+ check: { type: 'string', description: '一条命令,退出码等于 checkExit(默认 0)才算过。' },
4932
+ checkExit: { type: 'integer', description: '期望退出码,默认 0。' },
4933
+ },
4934
+ },
4935
+ description: '每条要求的可执行判据:写进 Requirement.md 的前置块,第 4 阶由插件自己跑,不看模型怎么说。',
2936
4936
  },
2937
4937
  constraints: {
2938
4938
  type: 'string',
2939
4939
  description: '边界:不能碰的文件、不要用的技术、预算或风格限制。',
2940
4940
  },
4941
+ forbidden: {
4942
+ type: 'array',
4943
+ items: { type: 'string' },
4944
+ description: '不许碰的路径(目录或文件,相对绝对都行)。实施段跑完会拿它比对台账,碰到就判 FAIL 并要求回滚。',
4945
+ },
4946
+ doneWhen: {
4947
+ type: 'array',
4948
+ items: { type: 'string' },
4949
+ description: '算做完的判据,一句话一条。和 requirements 一起写进 contract.json,每一阶都会重贴。',
4950
+ },
2941
4951
  intentConfidence: {
2942
4952
  type: 'integer',
2943
4953
  required: true,
@@ -3034,6 +5044,12 @@ function splitRoute(value) {
3034
5044
  overridden: args.override,
3035
5045
  overrideReason: args.overrideReason,
3036
5046
  })
5047
+ // 存一份给前置门控用:这次过了,下一个会推进的工具就不该再被同一道门拦。
5048
+ rememberReadiness(parent, {
5049
+ score: confirmation.confidence,
5050
+ blindspots: confirmation.blindspots,
5051
+ assumptions: confirmation.assumptions,
5052
+ })
3037
5053
  const settings = settingsOf()
3038
5054
  if (running.has(args.project)) throw new Error(`项目 ${args.project} 正在运行,等这一轮结束`)
3039
5055
  if (running.size >= settings.maxConcurrentProjects) {
@@ -3047,12 +5063,17 @@ function splitRoute(value) {
3047
5063
  // 但**配了绝对 flowRoot 就不许挪**:那代表用户明确表态「只在那儿用」。
3048
5064
  // 擅自把活挪过去,会在用户工程目录旁边另起一个 .project-flow,
3049
5065
  // 项目就散了——用户的原话是「默认工作区里不可以跑工作流」。
5066
+ let createError
5067
+ let createAttempt
3050
5068
  if (!flowRootConfigured(settings)
3051
5069
  && settings.autoCreateFlowDir === true
3052
5070
  && flowModeOf(settings) === 'strict'
3053
5071
  && !insideFlow(cwd, settings)) {
3054
5072
  const ensured = await ensureFlowRoot(cwd, settings)
3055
5073
  if (ensured.created === true) cwd = ensured.root
5074
+ // 建不出来要留话:后面那句拒绝只说「不在工作流目录里」,看不出是权限问题。
5075
+ createError = ensured.error
5076
+ createAttempt = ensured.attempted
3056
5077
  }
3057
5078
  // 在这儿开过工就记下来:下次在别的目录打开会话,状态栏照样知道该看哪儿。
3058
5079
  // 不记的话,人一换目录,那边就只剩一句「未启用」——正是用户报的那个问题。
@@ -3068,7 +5089,7 @@ function splitRoute(value) {
3068
5089
  verdict: `不在「${FLOW_DIR_NAME}」目录里`,
3069
5090
  issues: [],
3070
5091
  artifacts: stateDir(cwd, args.project),
3071
- note: flowGateMessage(cwd, settings),
5092
+ note: flowGateMessage(cwd, settings) + (createError === undefined ? '' : `\n\n工作流目录本来该自动建出来的,但建失败了:${createAttempt}\n${createError}\n换个能写的盘,或者把 flowRoot 配成你确定有权限的绝对路径。`),
3072
5093
  }
3073
5094
  }
3074
5095
  // 门控过了就记下来:下次在同一个目录开工,五格能直接沿用,不用再问用户一遍。
@@ -3102,7 +5123,10 @@ function splitRoute(value) {
3102
5123
  project: args.project,
3103
5124
  intent: args.intent,
3104
5125
  requirements: args.requirements,
5126
+ checks: args.checks,
3105
5127
  constraints: args.constraints ?? '',
5128
+ forbidden: args.forbidden,
5129
+ doneWhen: args.doneWhen,
3106
5130
  confirmation,
3107
5131
  maxRework: args.maxRework ?? settings.maxRework,
3108
5132
  parent,
@@ -3290,6 +5314,46 @@ function splitRoute(value) {
3290
5314
  // here, so one check covers them all.
3291
5315
  assertProjectName(project)
3292
5316
  const settings = settingsOf()
5317
+ // 契约落盘:要求 + 不许碰 + 算做完。
5318
+ //
5319
+ // 每一阶的 prompt 都会把这份重贴一遍,所以上下文压缩带走的东西它带不走。
5320
+ // 只写一次、每轮复用,不在这里覆盖用户的既定约定——resume 时 options 里
5321
+ // 没有 requirements,那就读回原来那份继续用。
5322
+ const contractBefore = await readContract(cwd, project)
5323
+ let contract = contractBefore
5324
+ if (Array.isArray(options.requirements) && options.requirements.length > 0) {
5325
+ contract = await writeContract(cwd, project, {
5326
+ requirements: options.requirements,
5327
+ forbidden: options.forbidden,
5328
+ doneWhen: options.doneWhen,
5329
+ })
5330
+ // 契约换了要说一声:判据被换过而没人提,比判据写错更糟。
5331
+ if (contractBefore !== undefined && contractBefore.sha !== contract.sha) {
5332
+ await logLine(
5333
+ cwd,
5334
+ project,
5335
+ `契约变了(${String(contractBefore.sha ?? '').slice(0, 8)} → ${contract.sha.slice(0, 8)}),这一轮按新的算`,
5336
+ )
5337
+ }
5338
+ }
5339
+ // flow.yaml 写错了就别开跑:跑到一半才发现配置不对,钱已经花出去了。
5340
+ // 没有 flow.yaml 时 configured=false,这一段整段跳过,行为和 0.8.x 逐条一致。
5341
+ const flowResolution = await resolveFlow(cwd, project)
5342
+ if (flowResolution.configured) {
5343
+ if (flowResolution.errors.length > 0) {
5344
+ throw new Error(`项目 ${project} 的 flow.yaml 有问题,先改好再跑:\n${describeFlowProblems(flowResolution)}`)
5345
+ }
5346
+ // 执行器的顺序语义是「按位置认」:第 1 个=需求、第 2 个=规划、第 3 个=
5347
+ // 实施、最后 1 个=质检,中间那些是插在实施和质检之间的额外阶段。
5348
+ // 少于四个就没法凑出这四件事,直接拒。
5349
+ if (flowResolution.flow.phases.length < 4) {
5350
+ throw new Error(
5351
+ `项目 ${project} 的 flow.yaml 只有 ${flowResolution.flow.phases.length} 个环节,至少要四个:`
5352
+ + '需求、规划、实施、质检。顺序按位置认,中间多出来的会插在实施和质检之间跑。',
5353
+ )
5354
+ }
5355
+ }
5356
+ const activeFlow = flowResolution.flow
3293
5357
  // 顺手把模型配置落一份给状态栏:它只读文件,不调命令
3294
5358
  void writePanelFile(cwd, settings)
3295
5359
  // 状态栏的停止按钮要有东西可停。这一轮自己的开关,和外面传进来的信号合成一份,
@@ -3302,6 +5366,26 @@ function splitRoute(value) {
3302
5366
  controller: stop,
3303
5367
  sessionId: options.parent?.id ?? options.parent?.session?.id,
3304
5368
  })
5369
+
5370
+ // 记下「这个项目被哪些会话碰过」,落盘。
5371
+ //
5372
+ // 上面那个 panelStops 只在本轮运行期间有效——跑完就清掉,于是 mine 变假,
5373
+ // 状态栏退回「全表第一个项目」,所有对话看到的都是同一个。用户说的
5374
+ // 「所有工作区对话共用一条状态栏」就是这条退路造成的。
5375
+ // 落盘之后,跑完、重启、隔天回来都还认得出来。
5376
+ //
5377
+ // 存数组不是单个值:A 对话开的项目,B 对话可以接着 resume,两边都该看得见。
5378
+ // 只留最近 8 个,防止长年累月越攒越长。
5379
+ const panelSessionId = options.parent?.id ?? options.parent?.session?.id
5380
+ if (typeof panelSessionId === 'string' && panelSessionId !== '') {
5381
+ const before = await readState(cwd, project)
5382
+ const owners = Array.isArray(before?.ownerSessions)
5383
+ ? before.ownerSessions.filter(item => typeof item === 'string' && item !== '')
5384
+ : []
5385
+ if (!owners.includes(panelSessionId)) {
5386
+ await writeState(cwd, project, { ownerSessions: [...owners, panelSessionId].slice(-8) })
5387
+ }
5388
+ }
3305
5389
  const signal = mergeSignals(options.signal, stop.signal)
3306
5390
  const claim = await acquireLock(cwd, project, settings)
3307
5391
  if (claim.ok !== true) {
@@ -3453,7 +5537,7 @@ function splitRoute(value) {
3453
5537
  * count, and says which stage to start from.
3454
5538
  */
3455
5539
  const runPipeline = async options => {
3456
- const { cwd, project, intent, requirements, constraints, confirmation, maxRework, parent, signal, seed, settings, healed, mode, watchdog } = options
5540
+ const { cwd, project, intent, requirements, checks, constraints, confirmation, maxRework, parent, signal, seed, settings, healed, mode, watchdog } = options
3457
5541
  const artifacts = stateDir(cwd, project)
3458
5542
  const routeNotes = []
3459
5543
  const noteRoute = note => {
@@ -3476,9 +5560,11 @@ function splitRoute(value) {
3476
5560
  // the time anyone asks. A missing git downgrades to a warning, never a stop.
3477
5561
  const excludes = snapshotExcludesOf(settings)
3478
5562
  const snapshotsOn = settings.snapshotEnabled === true
5563
+ // 快照保留上限:0 表示不截断,只增不删(老行为)。
5564
+ const snapshotKeep = Number.isInteger(settings.snapshotKeep) ? settings.snapshotKeep : 40
3479
5565
  const snap = async label => {
3480
5566
  if (!snapshotsOn) return ''
3481
- const result = await takeSnapshot(cwd, project, label, { excludes })
5567
+ const result = await takeSnapshot(cwd, project, label, { excludes, keep: snapshotKeep })
3482
5568
  if (result.ok !== true) {
3483
5569
  if (snapshotNote === '') snapshotNote = `快照不可用:${result.reason}`
3484
5570
  await logLine(cwd, project, `快照失败(${label}):${result.reason}`)
@@ -3725,11 +5811,20 @@ function splitRoute(value) {
3725
5811
  // 意图确认那段弄丢,第 4 阶质检就没得核了。所以只有真开跑(有 confirmation)
3726
5812
  // 或者文件根本不在的时候才写。
3727
5813
  if (confirmation !== undefined || existingRequirement === undefined || existingRequirement.trim() === '') {
3728
- await saveArtifact(cwd, project, ARTIFACT.requirement, ticketBlock(
5814
+ // 判据(check)和陈旧的散文一样,是这一阶写的,不是第 2 阶现编的:
5815
+ // 它进 Requirement.md 的前置块,从这里开始就是「用户的判据」,
5816
+ // 后面谁改它,第 4 阶的指纹都会认出来。
5817
+ const checkEntries = buildCheckEntries(requirements, checks)
5818
+ const front = renderRequirementChecks(checkEntries)
5819
+ const body = ticketBlock(
3729
5820
  '需求',
3730
- `${intent}\n\n## 用户要求\n\n${requirements.map((line, index) => `${index + 1}. ${line}`).join('\n')}${convergence}`,
3731
- ))
5821
+ `${intent}\n\n## 用户要求\n\n${requirements.map((line, index) => `${index + 1}. ${stripInlineCheck(line)}`).join('\n')}${convergence}`,
5822
+ )
5823
+ await saveArtifact(cwd, project, ARTIFACT.requirement, front === '' ? body : `${front}\n\n${body}`)
3732
5824
  }
5825
+ // 指纹每次进第 2 阶都落一份(包括续跑):旧项目没有这个文件的时候,
5826
+ // 第 4 阶不能因为「没有基线」就跳过比对——那样等于谁都能事后补一条 check。
5827
+ await saveRequirementFingerprint(cwd, project)
3733
5828
  await writeState(cwd, project, { stage: 2, status: 'planning' })
3734
5829
  // ── 审美采集:去网上找骨架,攒进库 ──────────────────
3735
5830
  //
@@ -3785,13 +5880,21 @@ function splitRoute(value) {
3785
5880
  // 规划不再从内存拿 intent 变量,而是读刚落的 Requirement.md——
3786
5881
  // 这样它和用户之间就只剩这一个文件。
3787
5882
  const requirementText = await readArtifact(cwd, project, ARTIFACT.requirement)
3788
- const planned = await runStage(ctx, stageOptions({
3789
- provider: settings.provider,
5883
+ // flow.yaml 里 plan 环节写了 model 就用它,没写就用配置里的。
5884
+ const planRoute = stageModelOf(settings, (await resolveFlow(cwd, project)).flow, 2, {
3790
5885
  llmProvider: settings.planProvider,
3791
5886
  model: settings.planModel,
5887
+ })
5888
+ // 契约现场读一次,不引用外层变量——规划段和写契约那段不在同一个函数作用域里,
5889
+ // 之前 activeFlow 就是这么踩的:看着在同一个函数,实际不是。
5890
+ const plannerContract = contractBlock(await readContract(cwd, project))
5891
+ const planned = await runStage(ctx, stageOptions({
5892
+ provider: planRoute.provider,
5893
+ llmProvider: planRoute.llmProvider,
5894
+ model: planRoute.model,
3792
5895
  label: `${project} 规划`,
3793
5896
  stageKey: 'plan',
3794
- prompt: PLANNER_PROMPT(requirementText, constraints, (await listFiles(cwd)).join('\n'))
5897
+ prompt: `${plannerContract}${plannerContract === '' ? '' : '\n\n'}${PLANNER_PROMPT(requirementText, constraints, (await listFiles(cwd)).join('\n'))}`
3795
5898
  + (aesthetic.enabled === true ? `${planNote(aesthetic.carriers)}\n${ceilingPlanNote(aesthetic.carriers)}\n${describePatterns(patterns)}` : '')
3796
5899
  + domainPlanNote(domain),
3797
5900
  }))
@@ -3864,10 +5967,16 @@ function splitRoute(value) {
3864
5967
  })
3865
5968
  // The pre-build snapshot is what "roll this attempt back" means later.
3866
5969
  const before = await snap(`实施前 R${rework + 1}`)
3867
- const built = await runStage(ctx, stageOptions({
3868
- provider: settings.provider,
5970
+ // 返工循环里每轮都算一次:flow.yaml 里的 model 是这一轮的真相,
5971
+ // 不在循环外缓存——中途改了配置,下一轮就该按新的来。
5972
+ const buildRoute = stageModelOf(settings, (await resolveFlow(cwd, project)).flow, 3, {
3869
5973
  llmProvider: settings.buildProvider,
3870
5974
  model: settings.buildModel,
5975
+ })
5976
+ const built = await runStage(ctx, stageOptions({
5977
+ provider: buildRoute.provider,
5978
+ llmProvider: buildRoute.llmProvider,
5979
+ model: buildRoute.model,
3871
5980
  // 轮次用 rework+1:rework 是「已经返工过几次」,返工 1 次说明这是第 2 轮。
3872
5981
  // 之前写成 R${rework},结果快照说「实施前 R2」、日志标签说「实施 R1」,
3873
5982
  // 对着日志数轮次会数错。
@@ -3875,7 +5984,7 @@ function splitRoute(value) {
3875
5984
  stageKey: 'build',
3876
5985
  // 实施只读 Plan.md;返工时额外读上一轮的 QA_Report.md。
3877
5986
  // 读什么由 STAGE_IO 决定,不在这里手工拼内存变量。
3878
- prompt: `${BUILDER_RULES(rework)}${aesthetic.enabled === true ? `\n${buildRules(aesthetic.carriers)}\n${describePatterns(patterns)}` : ''}${domainBuildRules(domain)}${useDesktop ? desktopBuildNote() : ''}\n\n${await stageContext(cwd, project, 3, rework > 0 ? ['qa'] : [])}`,
5987
+ prompt: `${BUILDER_RULES(rework)}${aesthetic.enabled === true ? `\n${buildRules(aesthetic.carriers)}\n${describePatterns(patterns)}` : ''}${domainBuildRules(domain)}${useDesktop ? desktopBuildNote() : ''}\n\n${await stageContext(cwd, project, 3, rework > 0 ? ['qa'] : [], (await resolveFlow(cwd, project)).flow, contractBlock(await readContract(cwd, project)))}`,
3879
5988
  }))
3880
5989
  noteRoute(built.routeNote)
3881
5990
  await watchdog?.afterStage(built)
@@ -3910,6 +6019,11 @@ function splitRoute(value) {
3910
6019
  const build = parseJsonBlock(built.text, 'summary')
3911
6020
  buildSummary = typeof build?.summary === 'string' ? build.summary : built.text.slice(0, 800)
3912
6021
  await appendArtifact(cwd, project, ARTIFACT.log, ticketBlock(`实施 R${rework + 1}`, buildSummary))
6022
+ // 返工的修复台账:一条一行,只写「编号 → 改了什么 → 跑了哪条命令 → 结果」。
6023
+ // 这一节存在的意义是把「这轮到底修了哪几条」固定成事实,
6024
+ // 免得下一轮质检只能靠 diff 猜。
6025
+ const fixLog = renderFixLog(build?.fixes, rework + 1)
6026
+ if (fixLog !== '') await appendArtifact(cwd, project, ARTIFACT.log, fixLog)
3913
6027
  // Record what this attempt touched, so a precise rollback knows which
3914
6028
  // files to put back without needing the builder to be honest later.
3915
6029
  const claimed = normalizePaths(build?.files)
@@ -3917,6 +6031,28 @@ function splitRoute(value) {
3917
6031
  if (touched.length === 0 && before !== '') {
3918
6032
  touched = (await snapshotDiff(cwd, project, before)).map(entry => entry.path)
3919
6033
  }
6034
+ // ── 补丁台账:记录这一轮实施段真的写了哪些文件 ──
6035
+ // attempts 的文件清单来自实施段自述,可以说假话;台账记的是
6036
+ // 插件通过快照 diff 看到的实际改动。
6037
+ //
6038
+ // 每条都带上 `beforeCommit`(实施前那张快照):执行到这里时工作区
6039
+ // 已经被改过了,唯一的旧内容来源就是那张快照。以前这里只存 beforeSha,
6040
+ // 回滚拿着一个哈希毫无办法,只能报「已被手改」,等于回滚从来没生效过。
6041
+ const batchId = `${project}-R${rework + 1}`
6042
+ if (touched.length > 0) {
6043
+ const ledgerEntries = []
6044
+ for (let i = 0; i < touched.length; i += 1) {
6045
+ const entry = await recordFileWrite(cwd, project, touched[i], batchId, 3, i + 1, before)
6046
+ ledgerEntries.push(entry)
6047
+ }
6048
+ // 写完之后再算 afterSha:此时文件已经是实施段改过的版本
6049
+ for (const entry of ledgerEntries) {
6050
+ const abs = join(cwd, entry.path)
6051
+ const afterSha = await fileSha256(abs)
6052
+ commitLedgerEntry(cwd, project, entry, afterSha)
6053
+ }
6054
+ await logLine(cwd, project, `补丁台账:${ledgerEntries.length} 条写入(batchId=${batchId}${before === '' ? ',无快照,回滚将不可用' : `,回滚点 ${before.slice(0, 8)}`})`)
6055
+ }
3920
6056
  const after = await snap(`实施后 R${rework + 1}`)
3921
6057
  attempts.push({
3922
6058
  round: rework + 1,
@@ -3928,22 +6064,268 @@ function splitRoute(value) {
3928
6064
  at: nowIso(),
3929
6065
  })
3930
6066
  await writeState(cwd, project, { attempts })
6067
+
6068
+ // ── 越界检查 ──────────────────────────────────────────
6069
+ //
6070
+ // 契约里的「不许碰」在这里兑现。只能写在写完文件之后:插件没有
6071
+ // 「工具调用前」那个钩子,拦不住第一次写,但能保证它跑不掉——
6072
+ // 判 FAIL、把契约原文贴回去、让人用台账把这批改动撤掉。
6073
+ //
6074
+ // touched 来自快照 diff,不是实施段自述,所以它说不说谎都一样。
6075
+ const guard = await readContract(cwd, project)
6076
+ const violated = touched
6077
+ .map(file => ({ file, rule: hitsForbidden(file, guard?.forbidden) }))
6078
+ .filter(item => item.rule !== '')
6079
+ if (violated.length > 0) {
6080
+ const detail = violated.map(item => `${item.file}(踩到「${item.rule}」)`).join(';')
6081
+ await writeState(cwd, project, {
6082
+ stage: 3,
6083
+ status: 'forbidden-touched',
6084
+ rework,
6085
+ lastError: detail,
6086
+ })
6087
+ await logLine(cwd, project, `越界:${detail}`)
6088
+ return craft({
6089
+ outcome: 'blocked',
6090
+ stage: 3,
6091
+ rework,
6092
+ plan: planText,
6093
+ buildSummary,
6094
+ verdict: `改了不许碰的地方:${detail}`,
6095
+ issues: [
6096
+ `越界改动:${detail}`,
6097
+ ...(Array.isArray(guard?.forbidden) ? guard.forbidden.map(line => `不许碰:${line}`) : []),
6098
+ ],
6099
+ note: await writeNextStep(cwd, project, explainStop({
6100
+ stage: 3,
6101
+ verdict: '越界',
6102
+ reason: `实施段改了契约里写着不许碰的路径:${detail}。`,
6103
+ resumable: true,
6104
+ next: '先 project_rollback mode="ledger" 把这批撤掉,再让实施段重做。契约原文在 .project-flow/<项目>/contract.json。',
6105
+ })),
6106
+ })
6107
+ }
3931
6108
  needBuild = false
3932
6109
  }
3933
6110
 
6111
+ // ── 中间阶段 ──────────────────────────────────────────────
6112
+ //
6113
+ // flow.yaml 允许在实施和质检之间插阶段(任务书举的例子是安全评审)。
6114
+ // 位置语义:前三个是需求/规划/实施,最后一个是质检,中间那些才是额外阶段。
6115
+ // 所以是 slice(3, -1) 而不是 slice(2, -1)——内置四阶下它切出空数组,
6116
+ // 一个都不跑,「没有 flow.yaml 时行为完全不变」就是在这一句兑现的。
6117
+ //
6118
+ // 中间阶段用通用子会话:读它声明的文件,按 instructions 干活。四阶各有
6119
+ // 专用 prompt,但未知阶段没法预先写专用 prompt,所以只能通用。没写
6120
+ // instructions 的直接跳过并记日志,不猜它想干什么——猜错了是白花钱。
6121
+ const middleFlow = (await resolveFlow(cwd, project)).flow
6122
+ const middlePhases = middleFlow.phases.slice(3, -1)
6123
+ for (const phase of middlePhases) {
6124
+ cancelled()
6125
+ const instruction = typeof phase.instructions === 'string' ? phase.instructions.trim() : ''
6126
+ if (instruction === '') {
6127
+ await logLine(cwd, project, `中间阶段 ${phase.id} 没写 instructions,跳过`)
6128
+ continue
6129
+ }
6130
+ await writeState(cwd, project, { stage: 3, status: `extra:${phase.id}`, rework })
6131
+ const inputs = []
6132
+ for (const file of phase.reads) {
6133
+ // 只喂产物文件。src/** 这类 glob 指的是代码目录,喂不进上下文,跳过。
6134
+ const text = await readArtifact(cwd, project, basename(file))
6135
+ if (text !== undefined) inputs.push(`## ${file}\n\n${text.trim()}`)
6136
+ }
6137
+ const extra = await runStage(ctx, stageOptions({
6138
+ provider: settings.provider,
6139
+ llmProvider: settings.planProvider,
6140
+ model: settings.planModel,
6141
+ label: `${project} ${phase.id}${rework === 0 ? '' : ` R${rework + 1}`}`,
6142
+ stageKey: phase.id,
6143
+ prompt: `${instruction}${inputs.length === 0 ? '' : `\n\n${inputs.join('\n\n')}`}`,
6144
+ }))
6145
+ noteRoute(extra.routeNote)
6146
+ await watchdog?.afterStage(extra)
6147
+ await recordCost()
6148
+ cancelled()
6149
+ if (!extra.ok) {
6150
+ const why = diagnoseEmptyError(extra.stopReason, extra.diagnostic)
6151
+ await writeState(cwd, project, {
6152
+ stage: 3,
6153
+ status: `中间阶段 ${phase.id} 失败`,
6154
+ rework,
6155
+ lastError: why,
6156
+ })
6157
+ await logLine(cwd, project, `中间阶段 ${phase.id} 失败:${extra.stopReason}|${why}`)
6158
+ return craft({
6159
+ outcome: 'blocked',
6160
+ stage: 3,
6161
+ rework,
6162
+ plan: planText,
6163
+ buildSummary,
6164
+ verdict: `中间阶段 ${phase.id} 没跑完`,
6165
+ issues: [why],
6166
+ note: await writeNextStep(cwd, project, explainStop({
6167
+ stage: 3,
6168
+ verdict: `${phase.id} 没跑完`,
6169
+ reason: `中间阶段 ${phase.id} 试了 ${settings.maxStageRetries + 1} 次都没正常结束:${why}。`,
6170
+ resumable: true,
6171
+ next: '「继续」会从这个中间阶段接着跑,前面几阶不重做。',
6172
+ })),
6173
+ })
6174
+ }
6175
+ // 门禁只认「产物在不在」。intent 要问用户、verdict 属于质检那一段的
6176
+ // 职责、assertions 要跑命令——这些在这里重复一遍就是两套判定。
6177
+ const gateOfMiddle = phase.gate !== null && typeof phase.gate === 'object' ? phase.gate : {}
6178
+ if (gateOfMiddle.kind === 'artifact_present') {
6179
+ const produced = []
6180
+ for (const file of phase.writes) {
6181
+ const text = await readArtifact(cwd, project, basename(file))
6182
+ if (text !== undefined && text.trim() !== '') produced.push(file)
6183
+ }
6184
+ if (produced.length === 0) {
6185
+ const why = `中间阶段 ${phase.id} 跑完了,但没产出它声明的任何文件(${phase.writes.join('、') || 'writes 是空的'})`
6186
+ await writeState(cwd, project, { stage: 3, status: `extra-missing:${phase.id}`, rework, lastError: why })
6187
+ await logLine(cwd, project, why)
6188
+ return craft({
6189
+ outcome: 'blocked',
6190
+ stage: 3,
6191
+ rework,
6192
+ plan: planText,
6193
+ buildSummary,
6194
+ verdict: why,
6195
+ issues: [why],
6196
+ note: await writeNextStep(cwd, project, explainStop({
6197
+ stage: 3,
6198
+ verdict: `中间阶段 ${phase.id} 没产出`,
6199
+ reason: why,
6200
+ resumable: true,
6201
+ next: '「继续」会重跑这个中间阶段,前面几阶不重做。',
6202
+ })),
6203
+ })
6204
+ }
6205
+ }
6206
+ await appendArtifact(
6207
+ cwd,
6208
+ project,
6209
+ ARTIFACT.log,
6210
+ ticketBlock(`${phase.id} R${rework + 1}`, typeof extra.text === 'string' ? extra.text.slice(0, 800) : ''),
6211
+ )
6212
+ }
6213
+
3934
6214
  await writeState(cwd, project, {
3935
6215
  stage: 4,
3936
6216
  status: rework === 0 ? 'checking' : `checking R${rework}`,
3937
6217
  rework,
3938
6218
  })
3939
6219
 
6220
+ // ── 判据先跑,模型后判 ──────────────────────────────────
6221
+ //
6222
+ // 顺序很重要:命令先跑完,结果原样塞进质检的输入里。模型看到的不是
6223
+ // 「请你自己判断」,而是「这些命令的退出码在这里,照着解释」。它说 PASS
6224
+ // 也翻不了命令的案。
6225
+ const requirementForQa = await readArtifact(cwd, project, ARTIFACT.requirement) ?? ''
6226
+ const storedFingerprint = await readRequirementFingerprint(cwd, project)
6227
+ const checkEntries = parseRequirementChecks(requirementForQa)
6228
+ const liveFingerprint = requirementFingerprint(checkEntries)
6229
+ const fingerprintMissing = storedFingerprint === ''
6230
+ const fingerprintInvalid = !fingerprintMissing && !/^[0-9a-fA-F]{64}$/u.test(storedFingerprint)
6231
+ const fingerprintMismatch = !fingerprintMissing && !fingerprintInvalid && liveFingerprint !== storedFingerprint
6232
+ if (fingerprintMissing || fingerprintInvalid || fingerprintMismatch) {
6233
+ // 判据被改:第 2 阶定过的 check 现在和磁盘上的不一样,或者根本就没
6234
+ // 记过指纹(requirement.sha 缺失/非法)。考题被换过的那种情况下,
6235
+ // 跑出来的任何结论都不作数。
6236
+ const detail = fingerprintMissing
6237
+ ? 'requirement.sha 缺失(第 2 阶没跑或产物被删)'
6238
+ : fingerprintInvalid
6239
+ ? `requirement.sha 内容非法:不是 64 位十六进制(${storedFingerprint.slice(0, 20)}…)`
6240
+ : `指纹 ${storedFingerprint.slice(0, 12)} → ${liveFingerprint.slice(0, 12)}`
6241
+ await writeState(cwd, project, {
6242
+ stage: 4,
6243
+ status: 'criteria-tampered',
6244
+ rework,
6245
+ lastError: `判据被改:${detail}`,
6246
+ })
6247
+ await logLine(cwd, project, `判据被改:${detail},停机`)
6248
+ return craft({
6249
+ outcome: 'blocked',
6250
+ stage: 4,
6251
+ rework,
6252
+ plan: planText,
6253
+ buildSummary,
6254
+ verdict: '判据被改',
6255
+ issues: [
6256
+ fingerprintMissing
6257
+ ? 'requirement.sha 缺失:第 2 阶没跑或产物被删,判据指纹没有基线,这一轮不跑命令。'
6258
+ : fingerprintInvalid
6259
+ ? `requirement.sha 内容非法(${storedFingerprint.slice(0, 24)}…),不是合法指纹,这一轮不跑命令。`
6260
+ : `Requirement.md 里 check 的指纹变了:第 2 阶记的是 ${storedFingerprint.slice(0, 16)}…,现在是 ${liveFingerprint.slice(0, 16)}…`,
6261
+ '这一轮不跑任何 check、也不出结论:考题的状态不对,跑出来的结果说明不了任何事。',
6262
+ ],
6263
+ note: await writeNextStep(cwd, project, explainStop({
6264
+ stage: 4,
6265
+ verdict: '判据被改',
6266
+ reason: fingerprintMissing
6267
+ ? 'requirement.sha 不存在:第 2 阶没跑,或者这个项目的 check 从来没被定稿过。'
6268
+ : fingerprintInvalid
6269
+ ? `requirement.sha 坏了:${storedFingerprint.slice(0, 24)}… 不是 64 位十六进制。`
6270
+ : `${ARTIFACT.requirement} 的 check 字段和第 2 阶定稿时算的 sha256 对不上:中途有人改了判据。`,
6271
+ resumable: true,
6272
+ next: fingerprintMissing || fingerprintInvalid
6273
+ ? '用 project_run 重开这个项目(会重新记指纹),不要手动补一个 sha 文件。'
6274
+ : `把 check 改回第 2 阶那一版,或者用 project_run 重开这个项目(会重新定稿并记新指纹)。`,
6275
+ })),
6276
+ })
6277
+ }
6278
+ const assertions = await runRequirementChecks({
6279
+ entries: checkEntries,
6280
+ cwd,
6281
+ allowed: allowedCommandsOf(settings),
6282
+ strictEval: settings.checkStrictEval === true,
6283
+ timeoutMs: settings.checkTimeoutMs,
6284
+ tailChars: settings.checkStdoutTailChars,
6285
+ })
6286
+ const gate = gateAssertions(assertions)
6287
+ if (Array.isArray(assertions) && assertions.length > 0) {
6288
+ await logLine(cwd, project, criteriaInPlay(assertions)
6289
+ ? `断言:${gate.verdict}|过 ${gate.passed.length} / 未过 ${gate.failed.length} / 判不了 ${gate.unverified.length + gate.uncovered.length}`
6290
+ : `断言:这次一条 check 都没有(${assertions.length} 条要求全 unverified),结论只来自模型`)
6291
+ }
6292
+
3940
6293
  // 先把质检要看的东西准备好:三个文件 + diff,视觉类任务再加预览图。
3941
- const qaText = `${QA_PROMPT(
3942
- await readArtifact(cwd, project, ARTIFACT.requirement) ?? '',
6294
+ //
6295
+ // diff 单独拿一次:它既要喂给质检,也要用来判断「上一轮判 closed 的问题
6296
+ // 是不是又被这轮改回去了」。同一个东西读两遍会漂。
6297
+ const diffForQa = await attemptDiff(cwd, project, attempts)
6298
+ // ── 越界检测:diff 里改的文件是否都在台账里 ──
6299
+ // 不在台账里的算「越界改动」——不是实施段写的,是别的来源改的。
6300
+ // 这种情况写进日志,但不阻断流程:用户手改的文件不该挡住质检。
6301
+ let outOfBoundsNote = ''
6302
+ try {
6303
+ const diffPaths = diffForQa?.ok === true
6304
+ ? diffForQa.text.split(/\r?\n/u)
6305
+ .filter(line => /^diff --git a\//u.test(line))
6306
+ .map(line => /^diff --git a\/(.+?) b\//u.exec(line)?.[1] ?? '')
6307
+ .filter(p => p !== '')
6308
+ : []
6309
+ if (diffPaths.length > 0) {
6310
+ const coverage = checkLedgerCoverage(cwd, project, diffPaths)
6311
+ if (coverage.outOfBounds.length > 0) {
6312
+ outOfBoundsNote = `越界改动 ${coverage.outOfBounds.length} 个文件(不在台账里):${coverage.outOfBounds.slice(0, 5).join('、')}`
6313
+ await logLine(cwd, project, outOfBoundsNote)
6314
+ }
6315
+ }
6316
+ } catch {
6317
+ // 台账读不了就跳过越界检测,不阻断质检
6318
+ }
6319
+ // 上一轮的账本在这一轮报告覆盖之前读回来,否则跨轮就断了。
6320
+ const previousReport = await readArtifact(cwd, project, ARTIFACT.qa) ?? ''
6321
+ const previousIssues = parseIssueBlock(previousReport)
6322
+ const qaText = `${contractBlock(await readContract(cwd, project))}${QA_PROMPT(
6323
+ requirementForQa,
3943
6324
  await readArtifact(cwd, project, ARTIFACT.plan) ?? '',
3944
6325
  await readArtifact(cwd, project, ARTIFACT.log) ?? '',
3945
- await attemptDiff(cwd, project, attempts),
3946
- )}${aesthetic.enabled === true ? checkRules(aesthetic.carriers) : ''}${domainQaChecks(domain)}${useDesktop ? desktopQaNote() : ''}`
6326
+ diffForQa,
6327
+ renderKnownIssues(previousIssues),
6328
+ )}${describeAssertions(gate)}${aesthetic.enabled === true ? checkRules(aesthetic.carriers) : ''}${domainQaChecks(domain)}${useDesktop ? desktopQaNote() : ''}`
3947
6329
 
3948
6330
  // 有预览图就喂进去。喂不了(模型不支持看图)也有退路:prompt 里已经写了
3949
6331
  // 「没有预览图就写审美未核」,不会静默放行。
@@ -3957,10 +6339,14 @@ function splitRoute(value) {
3957
6339
  await logLine(cwd, project, `质检输入:${preview.note}`)
3958
6340
  }
3959
6341
 
3960
- const checked = await runStage(ctx, stageOptions({
3961
- provider: settings.provider,
6342
+ const checkRoute = stageModelOf(settings, (await resolveFlow(cwd, project)).flow, 4, {
3962
6343
  llmProvider: settings.checkProvider,
3963
6344
  model: settings.checkModel,
6345
+ })
6346
+ const checked = await runStage(ctx, stageOptions({
6347
+ provider: checkRoute.provider,
6348
+ llmProvider: checkRoute.llmProvider,
6349
+ model: checkRoute.model,
3964
6350
  label: `${project} 质检${rework === 0 ? '' : ` R${rework}`}`,
3965
6351
  stageKey: 'check',
3966
6352
  // 质检只读三个文件加一份 diff,不碰内存里的 intent / planText / buildSummary。
@@ -4022,8 +6408,39 @@ function splitRoute(value) {
4022
6408
  ? `质检既没 JSON 也没判词,正文 ${text.length} 字:${text.slice(0, 200).replace(/\s+/gu, ' ')}`
4023
6409
  : `质检没按 JSON 回,从正文里认出结论 ${rawVerdict}(正文 ${text.length} 字)`)
4024
6410
  }
4025
- const passed = rawVerdict === 'PASS'
6411
+ // 命令的结论压过模型的结论。只在「这一项目真写了判据」时生效:
6412
+ // 一条 check 都没有的项目(老的、纯文档的)照老路走,否则升级之后
6413
+ // 每个项目都会被判死,那不是加判据,那是把流程关了。
6414
+ const gateActive = criteriaInPlay(assertions)
6415
+ let passed = rawVerdict === 'PASS'
4026
6416
  verdict = rawVerdict === '' ? '质检没给出 PASS/FAIL' : rawVerdict
6417
+ if (gateActive && gate.verdict === 'FAIL') {
6418
+ passed = false
6419
+ verdict = `FAIL(断言未过 ${gate.failed.length} 条)`
6420
+ } else if (gateActive && gate.verdict === 'UNVERIFIED' && passed) {
6421
+ // 判不了不等于判过了。
6422
+ passed = false
6423
+ verdict = 'FAIL(有要求没有 check,判不了)'
6424
+ }
6425
+
6426
+ // ── 问题台账:这一轮到底还剩几条没闭环 ──────────────────
6427
+ //
6428
+ // 模型给 JSON 就走 JSON;没给 JSON 才退回解析表格(表头必须声明严重级)。
6429
+ // 两条路都不通,这一轮就没有可执行的意见,按「没法照着改」停机。
6430
+ const incomingIssues = normalizeIncomingIssues(
6431
+ Array.isArray(check?.issues) && check.issues.length > 0 ? check.issues : parseIssueTables(typeof checked.text === 'string' ? checked.text : ''),
6432
+ )
6433
+ const ledger = mergeIssueRounds(previousIssues, incomingIssues, typeof diffForQa?.text === 'string' ? diffForQa.text : '')
6434
+ if (ledger.invalid.length > 0) {
6435
+ // detect / pass 缺一条,这条问题就没法验;整轮按 FAIL,别指望返工能补。
6436
+ passed = false
6437
+ verdict = 'FAIL(问题缺少可执行定义)'
6438
+ } else if (ledger.openCount > 0) {
6439
+ // 还有没闭环的问题,就不许算过——哪怕模型说 PASS。
6440
+ // 判词直接写「几条没闭环」:返工看的是这个数,不是 PASS/FAIL 两个词。
6441
+ passed = false
6442
+ verdict = `FAIL(${ledger.openCount} 条没闭环)`
6443
+ }
4027
6444
 
4028
6445
  // 骨架的反馈:这一轮用过的那几条,质检过了加分,没过减分。
4029
6446
  // 没有这个闭环,库只会越来越多,不会越来越准。
@@ -4050,25 +6467,123 @@ function splitRoute(value) {
4050
6467
  const issues = parsedIssues.length > 0 || rawText === ''
4051
6468
  ? parsedIssues
4052
6469
  : [`质检没按 JSON 回,以下是它的原文(前 1200 字):\n${rawText.slice(0, 1200)}`]
6470
+ // 断言没过的条目必须进 issues:第 3 阶返工只按这份清单改,
6471
+ // 命令的退出码不写进去,它就只改模型顺嘴提的那几条。
6472
+ if (gateActive && gate.verdict !== 'PASS') {
6473
+ for (const item of gate.failed) {
6474
+ const why = item.denied === true
6475
+ ? '被白名单拒了'
6476
+ : item.timeout === true
6477
+ ? '超时被收掉'
6478
+ : `退出码 ${item.exit ?? '?'}(期望 ${item.expectExit ?? 0})`
6479
+ const tail = String(item.stdoutTail ?? '').trim().split(/\r?\n/u).slice(-6).join(' / ')
6480
+ issues.push(`第 ${item.req} 条判据没过:${item.cmd} ${why}${tail === '' ? '' : `|输出尾巴:${tail}`}`)
6481
+ }
6482
+ for (const item of gate.unverified) {
6483
+ issues.push(`第 ${item.req} 条没有 check,判不了:这一条不能算过,得先在 Requirement.md 里给它写一条可执行的判据`)
6484
+ }
6485
+ }
4053
6486
  // 质检自己说「知道但接受」的风险,进证据包的 remaining_risks
4054
6487
  const acceptableRisks = Array.isArray(check?.acceptable_risks)
4055
6488
  ? check.acceptable_risks.filter(item => typeof item === 'string' && item.trim() !== '').slice(0, 8)
4056
6489
  : []
4057
- await saveArtifact(cwd, project, ARTIFACT.qa, ticketBlock(
6490
+
6491
+ // ── 问题台账:这一轮到底还剩几条没闭环 ──────────────────
6492
+ if (ledger.open.length > 0) {
6493
+ for (const item of ledger.open) {
6494
+ issues.push(`${item.id}|${item.severity}|${item.location || '(没写位置)'}|${item.claim}`)
6495
+ }
6496
+ }
6497
+ await writeState(cwd, project, {
6498
+ openIssues: ledger.openCount,
6499
+ openCritical: ledger.openP0P1,
6500
+ })
6501
+ // 报告分两半:前置块给机器读(verdict + assertions),正文给人读。
6502
+ // 以前只有正文,第 3 阶返工时得靠模型再解释一遍「哪条没过」——那一遍解释
6503
+ // 就是二手信息,现在退出码直接躺着,谁读都一样。
6504
+ const assertionLine = (item) => {
6505
+ const tail = String(item.stdoutTail ?? '').trim().split(/\r?\n/u).slice(-3).join(' / ')
6506
+ return `- 第 ${item.req} 条:${item.status}|${item.cmd === null || item.cmd === undefined ? '(没有 check)' : item.cmd}`
6507
+ + `|exit ${typeof item.exit === 'number' ? item.exit : '-'}|${item.durationMs}ms`
6508
+ + `${item.timeout === true ? '|timeout' : ''}${item.denied === true ? '|白名单拒绝' : ''}`
6509
+ + `${tail === '' ? '' : `|${tail}`}`
6510
+ }
6511
+ const issueLedgerLine = (item) => {
6512
+ const head = `- ${item.id}|${item.severity}|${item.status}|${item.location || '(没写位置)'}|${item.claim}`
6513
+ const more = []
6514
+ if (item.detect !== '') more.push(` 检测:\`${item.detect}\``)
6515
+ if (item.pass !== '') more.push(` 通过标准:${item.pass}`)
6516
+ if (typeof item.note === 'string' && item.note !== '') more.push(` 备注:${item.note}`)
6517
+ return [head, ...more].join('\n')
6518
+ }
6519
+ const reportFront = renderQaFrontMatter({ verdict, round: rework, issues: ledger.issues, assertions })
6520
+ await saveArtifact(cwd, project, ARTIFACT.qa, `${reportFront}\n\n${ticketBlock(
4058
6521
  `质检结论:${verdict}`,
4059
6522
  [
4060
6523
  verdict,
4061
6524
  issues.length === 0 ? '' : `## 核过 / 不达标\n\n${issues.map(line => `- ${line}`).join('\n')}`,
6525
+ `## 问题台账\n\n${ledger.issues.length === 0
6526
+ ? '(这一轮没有提出具体问题)'
6527
+ : ledger.issues.map(issueLedgerLine).join('\n')}`,
6528
+ `## 断言\n\n${assertions.length === 0
6529
+ ? '(这次没有一条 check,结论只来自模型)'
6530
+ : assertions.map(assertionLine).join('\n')}`,
4062
6531
  // 单列一节,格式固定,证据包按标题抠条目
4063
6532
  `## 可接受的风险\n\n${acceptableRisks.length === 0
4064
6533
  ? '(无)'
4065
6534
  : acceptableRisks.map(line => `- ${line}`).join('\n')}`,
4066
6535
  ].filter(part => part !== '').join('\n\n'),
4067
- ))
6536
+ )}`)
6537
+
6538
+ // 判据没定义导致的 FAIL,返工修不了:命令是第 1 阶定的,第 3 阶改不了考题。
6539
+ // 这种情况直接停,说清要补什么,别让它白跑一轮返工。
6540
+ if (gateActive && gate.verdict === 'UNVERIFIED' && gate.failed.length === 0) {
6541
+ await writeState(cwd, project, { stage: 4, status: 'qa-unverified', rework, verdict })
6542
+ await logLine(cwd, project, `质检:${gate.unverified.length + gate.uncovered.length} 条要求没有 check,判不了 PASS,停机等补判据`)
6543
+ return craft({
6544
+ outcome: 'blocked',
6545
+ stage: 4,
6546
+ rework,
6547
+ plan: planText,
6548
+ buildSummary,
6549
+ verdict,
6550
+ issues,
6551
+ note: await writeNextStep(cwd, project, explainStop({
6552
+ stage: 4,
6553
+ verdict: '有要求没有 check,判不了',
6554
+ reason: `第 ${gate.unverified.length + gate.uncovered.length} 条要求没写 check,没有可执行的判据,按规矩不能算 PASS。返工也补不上——判据是第 1 阶定的,第 3 阶改不了。`,
6555
+ resumable: true,
6556
+ next: `在 ${ARTIFACT.requirement} 的 checks 前置块里给这几条补上 check(或者下次 project_run 时用 checks 参数),再「继续」。`,
6557
+ })),
6558
+ })
6559
+ }
6560
+
6561
+ // 问题缺少可执行定义:detect / pass 缺一条,这条意见就没法验。
6562
+ // 这不是实现的问题,返工照着一句模糊的话改只会越改越散,所以停机。
6563
+ if (ledger.invalid.length > 0) {
6564
+ await writeState(cwd, project, { stage: 4, status: 'qa-issues-undefined', rework, verdict })
6565
+ await logLine(cwd, project, `质检报告有 ${ledger.invalid.length} 条问题没写全 detect/pass,整轮 FAIL`)
6566
+ return craft({
6567
+ outcome: 'blocked',
6568
+ stage: 4,
6569
+ rework,
6570
+ plan: planText,
6571
+ buildSummary,
6572
+ verdict,
6573
+ issues,
6574
+ note: await writeNextStep(cwd, project, explainStop({
6575
+ stage: 4,
6576
+ verdict: '问题缺少可执行定义',
6577
+ reason: `${ledger.invalid.map(item => item.id).join('、')} 没有写全 detect / pass。没有验法的问题,下一轮改没改都说不清,返工也是瞎改。`,
6578
+ resumable: true,
6579
+ next: '「继续」会让质检重出一轮意见。要是每次都这样,说明任务书里那条要求本身没法验,先把要求写具体。',
6580
+ })),
6581
+ })
6582
+ }
4068
6583
 
4069
6584
  if (passed) {
4070
- await writeState(cwd, project, { stage: 4, status: 'passed', rework, verdict })
4071
- await logLine(cwd, project, `质检通过(返工 ${rework} 次)`)
6585
+ await writeState(cwd, project, { stage: 4, status: 'passed', rework, verdict, openIssues: 0, openCritical: 0 })
6586
+ await logLine(cwd, project, `质检通过(返工 ${rework} 次,问题全部闭环)`)
4072
6587
 
4073
6588
  // 验收的最后一步:跑外部测试拿 exit code,再把整轮的事实写成 JSON。
4074
6589
  // 质检说 PASS 只代表「按需求做的」,测试才是「能不能跑」——两件事分开记。
@@ -4100,11 +6615,38 @@ function splitRoute(value) {
4100
6615
  })
4101
6616
  }
4102
6617
 
4103
- // 质检只给 PASS/FAIL。一条 reason 都没有的 FAIL 没法照着改,
4104
- // 按规则停机,不盲目返工。
4105
- if (issues.length === 0) {
4106
- await writeState(cwd, project, { stage: 4, status: 'qa-failed-no-reasons', rework })
4107
- await logLine(cwd, project, '质检判 FAIL 但没给原因')
6618
+ // 同一条问题连着三轮没闭环:停,别再空转。report 已经写明卡在哪几条。
6619
+ if (ledger.stuck.length > 0) {
6620
+ verdict = `${ledger.stuck.length} 条问题连续 3 轮没闭环`
6621
+ await writeState(cwd, project, { stage: 4, status: 'stuck-open-issues', rework, verdict })
6622
+ await logLine(cwd, project, `连续 3 轮没闭环:${ledger.stuck.map(item => item.id).join('、')},停机`)
6623
+ return craft({
6624
+ outcome: 'stopped',
6625
+ stage: 4,
6626
+ rework,
6627
+ plan: planText,
6628
+ buildSummary,
6629
+ verdict,
6630
+ issues,
6631
+ note: await writeNextStep(cwd, project, explainStop({
6632
+ stage: 4,
6633
+ verdict: `${ledger.stuck.length} 条问题连续 3 轮没闭环`,
6634
+ reason: `卡在这几条:${ledger.stuck.map(item => `${item.id} ${item.claim}`).join(';')}。同样的意见返第三遍还是没过,说明不是没看见,是做不到或者判据本身有问题。`,
6635
+ resumable: true,
6636
+ next: '要么你自己动手改这几处,要么把这条要求放宽(改 Requirement.md)再「继续」。原样再来一轮只会再停一次。',
6637
+ })),
6638
+ })
6639
+ }
6640
+
6641
+ // 返工判据从「判了 FAIL 就返工」改成「还有没闭环的问题才返工」。
6642
+ // 一条待办都没有的 FAIL 去返工,等于让实施段自己猜哪里不对。
6643
+ //
6644
+ // 例外:判据(check)自己没过。那不是「没问题」,是有一条明确的可执行判据
6645
+ // 在报错——报告里的断言那节就是待办,照它改得动。
6646
+ const assertionActionable = gateActive && gate.verdict === 'FAIL'
6647
+ if (ledger.openCount === 0 && assertionActionable !== true) {
6648
+ await writeState(cwd, project, { stage: 4, status: 'qa-failed-no-issues', rework, openIssues: 0 })
6649
+ await logLine(cwd, project, `质检判 FAIL 但没有未闭环问题(${ledger.issues.length} 条台账)`)
4108
6650
  return craft({
4109
6651
  outcome: 'blocked',
4110
6652
  stage: 4,
@@ -4112,20 +6654,21 @@ function splitRoute(value) {
4112
6654
  plan: planText,
4113
6655
  buildSummary,
4114
6656
  verdict,
4115
- issues: [],
6657
+ issues,
4116
6658
  note: await writeNextStep(cwd, project, explainStop({
4117
6659
  stage: 4,
4118
- verdict: '质检判 FAIL 但没给理由',
4119
- reason: `质检判了 FAIL,但 ${ARTIFACT.qa} 里一条能照着改的修改点都没有。没有修改点的返工只能瞎改,所以不返。`,
6660
+ verdict: '质检判 FAIL 但没有可返工的问题',
6661
+ reason: `${ARTIFACT.qa} 里没有一条 open 的问题,返工没有目标。`
6662
+ + `(这轮台账 ${ledger.issues.length} 条:${ledger.issues.map(item => `${item.id}=${item.status}`).join('、') || '空的'})`,
4120
6663
  resumable: true,
4121
- next: '「继续」会让它重跑质检,通常能拿到具体理由;要是老这样,说明任务书里的要求太抽象,得先把要求写具体。',
6664
+ next: '「继续」会让它重跑质检,通常能给出一份带 detect / pass 的问题清单;老这样说明任务书里的要求太抽象,得先把要求写具体。',
4122
6665
  })),
4123
6666
  })
4124
6667
  }
4125
6668
  rework += 1
4126
6669
  if (rework > maxRework) {
4127
6670
  await writeState(cwd, project, { stage: 4, status: 'stopped-after-rework-limit', rework: rework - 1 })
4128
- await logLine(cwd, project, `返工上限 ${maxRework} 次用完,停机`)
6671
+ await logLine(cwd, project, `返工上限 ${maxRework} 次用完,停机;未闭环 ${ledger.openCount} 条`)
4129
6672
  return craft({
4130
6673
  outcome: 'stopped',
4131
6674
  stage: 4,
@@ -4136,16 +6679,15 @@ function splitRoute(value) {
4136
6679
  issues,
4137
6680
  note: await writeNextStep(cwd, project, explainStop({
4138
6681
  stage: 4,
4139
- verdict: `返工 ${rework - 1} 次仍未通过`,
4140
- reason: issues.length === 0
4141
- ? `返工上限 ${maxRework} 次用完了,最后一次是「${verdict}」但没留下具体修改点。`
4142
- : `返工上限 ${maxRework} 次用完了,最后一次仍卡在:${issues.slice(0, 3).join(';')}`,
6682
+ verdict: `返工 ${rework - 1} 次仍有 ${ledger.openCount} 条没闭环`,
6683
+ reason: `返工上限 ${maxRework} 次用完了,还卡在这几条:${ledger.open.slice(0, 3).map(item => `${item.id} ${item.claim}`).join(';')}`,
4143
6684
  resumable: true,
4144
6685
  next: '三条路:你自己动手改;把要求放宽(改 Requirement.md)再「继续」;或者放弃这个项目。继续循环下去只会空烧钱,所以故意停在这里。',
4145
6686
  })),
4146
6687
  })
4147
6688
  }
4148
6689
  // 修正任务书不再生成:第三阶返工时读的是 QA_Report.md 本身。
6690
+ await logLine(cwd, project, `R${rework} 返工:未闭环 ${ledger.openCount} 条(${ledger.open.map(item => item.id).join('、')})`)
4149
6691
  needBuild = true
4150
6692
  }
4151
6693
  }
@@ -4222,7 +6764,7 @@ function splitRoute(value) {
4222
6764
 
4223
6765
  const rollbackTool = defineTool({
4224
6766
  name: 'project_rollback',
4225
- description: '把工作区回滚到某个快照。mode=full 整棵恢复到目标快照(连新增文件一起清掉);mode=precise 只还原指定那次实施动过的文件,不碰你手改的其他东西。默认先干跑给 diff,dryRun=false 才真回滚;真回滚前会自动再打一张 pre-rollback 快照,回错了还能再回来。',
6767
+ description: '把工作区回滚到某个快照。mode=full 整棵恢复到目标快照(连新增文件一起清掉);mode=precise 只还原指定那次实施动过的文件,不碰你手改的其他东西;mode=ledger 按补丁台账还原最后一批写入,只动 agent 真的写过的路径。默认先干跑给 diff,dryRun=false 才真回滚;真回滚前会自动再打一张 pre-rollback 快照,回错了还能再回来。',
4226
6768
  parameters: {
4227
6769
  project: {
4228
6770
  type: 'string',
@@ -4235,7 +6777,7 @@ function splitRoute(value) {
4235
6777
  },
4236
6778
  mode: {
4237
6779
  type: 'string',
4238
- description: 'full=整棵恢复(默认);precise=只还原那一次实施动过的文件。',
6780
+ description: 'full=整棵恢复(默认);precise=只还原那一次实施动过的文件;ledger=按补丁台账还原最后一批写入。',
4239
6781
  },
4240
6782
  dryRun: {
4241
6783
  type: 'boolean',
@@ -4273,11 +6815,84 @@ function splitRoute(value) {
4273
6815
  const cwd = args.cwd !== undefined && isAbsolute(args.cwd) ? args.cwd : cwdOf(ctx, exec.agent)
4274
6816
  const project = assertProjectName(args.project)
4275
6817
  const dryRun = args.dryRun !== false
4276
- const mode = args.mode === 'precise' ? 'precise' : 'full'
6818
+ // ledger 模式不走 git 快照,走台账。
6819
+ const isLedger = args.mode === 'ledger'
6820
+ const mode = isLedger ? 'ledger' : (args.mode === 'precise' ? 'precise' : 'full')
4277
6821
  const fail = (line, details = '') => ({
4278
6822
  ok: false, dryRun, target: '', line, changes: [], details,
4279
6823
  })
4280
6824
 
6825
+ // ── ledger 模式:按补丁台账回滚 ──
6826
+ if (isLedger) {
6827
+ // state 必须在这里读:下面写 rollbacks 记录要用它。
6828
+ // 以前它在 ledger 分支之后才声明,走这条路一律 ReferenceError,
6829
+ // 而错误被外层 catch 吞成一句「台账回滚失败」——看着像台账坏了。
6830
+ const state = await readState(cwd, project)
6831
+
6832
+ // 台账不存在时报错,不静默回滚全部
6833
+ const ledgerFile = ledgerPath(cwd, project)
6834
+ if (!existsSync(ledgerFile)) {
6835
+ return fail(
6836
+ `项目 ${project}:没有补丁台账(${ledgerFile} 不存在),mode=ledger 没法回滚。`,
6837
+ '台账在实施段每次写文件时自动追加。如果这个项目是在台账功能加上之前跑的,就没有台账。',
6838
+ )
6839
+ }
6840
+
6841
+ // 干跑只算差异:不打快照、不写盘、不追加台账。
6842
+ // 以前这里不读 dryRun,默认 true 一进来就直接真回滚了。
6843
+ let ledgerResult
6844
+ try {
6845
+ ledgerResult = await rollbackByLedger(cwd, project, { dryRun })
6846
+ } catch (error) {
6847
+ return fail(`台账回滚失败:${messageOf(error)}`, '台账里有坏 JSON 行,一个文件都不会动。')
6848
+ }
6849
+ if (ledgerResult.ok !== true && ledgerResult.reason !== undefined) {
6850
+ return fail(`台账回滚失败:${ledgerResult.reason}`)
6851
+ }
6852
+
6853
+ const restored = ledgerResult.restored ?? []
6854
+ const failed = ledgerResult.failed ?? []
6855
+
6856
+ if (dryRun) {
6857
+ return {
6858
+ ok: true,
6859
+ dryRun: true,
6860
+ target: `ledger:${ledgerResult.batchId}`,
6861
+ line: `台账回滚 · 干跑(batchId=${ledgerResult.batchId},共 ${ledgerResult.count} 条):会还原 ${restored.length} 个,${failed.length} 个还原不了。没动磁盘。`,
6862
+ changes: [...restored, ...failed],
6863
+ details: (ledgerResult.plan ?? []).map(p => ` ${p.action.padEnd(9)} ${p.path} — ${p.note}`).join('\n'),
6864
+ }
6865
+ }
6866
+
6867
+ // 真回滚之前才打这张保险快照:干跑不在快照仓库里留垃圾。
6868
+ if (await gitAvailable() === true) {
6869
+ const guard = await takeSnapshot(cwd, project, `pre-rollback-ledger ${nowIso().slice(0, 19)}`, {
6870
+ excludes: snapshotExcludesOf(settingsOf()),
6871
+ })
6872
+ if (guard.ok === true) {
6873
+ await logLine(cwd, project, `台账回滚前快照 → ${guard.commit.slice(0, 8)}`)
6874
+ }
6875
+ }
6876
+
6877
+ await logLine(cwd, project, `台账回滚:还原 ${restored.length} 个文件${failed.length > 0 ? `,${failed.length} 个失败` : ''}(batchId=${ledgerResult.batchId})`)
6878
+ await writeState(cwd, project, {
6879
+ rollbacks: [
6880
+ ...(Array.isArray(state?.rollbacks) ? state.rollbacks : []),
6881
+ { to: 'ledger', mode, at: nowIso(), batchId: ledgerResult.batchId, remaining: failed.length },
6882
+ ],
6883
+ })
6884
+ return {
6885
+ ok: failed.length === 0,
6886
+ dryRun: false,
6887
+ target: `ledger:${ledgerResult.batchId}`,
6888
+ line: `台账回滚(batchId=${ledgerResult.batchId}):还原 ${restored.length} 个文件${failed.length > 0 ? `,${failed.length} 个失败` : ''}。`,
6889
+ changes: [...restored, ...failed],
6890
+ details: failed.length === 0
6891
+ ? '只动了台账里记录的文件,其他文件原样保留。'
6892
+ : `失败:\n${failed.map(f => ` ${f}`).join('\n')}`,
6893
+ }
6894
+ }
6895
+
4281
6896
  if (await gitAvailable() !== true) {
4282
6897
  return fail(`项目 ${project}:这台机器上没有可用的 git,回滚做不了。`)
4283
6898
  }
@@ -4727,6 +7342,9 @@ async function decorateCost(result, settings, requirements, cwd) {
4727
7342
  return { ok: false, line: `不认识的阶段「${args.stage}」。用 规划 / 实施 / 质检。` }
4728
7343
  }
4729
7344
  const value = (args.model ?? '').trim()
7345
+ // 写错名字当场拒,别等跑起来才在回退日志里看见。
7346
+ const unknown = await unknownModelMessage(value)
7347
+ if (unknown !== undefined) return { ok: false, line: unknown }
4730
7348
  if (value === '' || value === '清空' || value === 'reset') {
4731
7349
  await writeOverride({ [key]: '' })
4732
7350
  return { ok: true, line: `已把「${args.stage}」恢复成继承当前模型,立即生效。` }
@@ -4752,6 +7370,25 @@ async function decorateCost(result, settings, requirements, cwd) {
4752
7370
  const offEstimate = ctx.tools.register(estimateTool)
4753
7371
  const offModels = ctx.tools.register(modelsTool)
4754
7372
  const offSet = ctx.tools.register(setTool)
7373
+
7374
+ // 意图门控的前置拦截。
7375
+ //
7376
+ // 以前 gate.guardToolCall 写好了却从没接上来:只有 project_run 自己在
7377
+ // execute 里检查 intentConfidence,模型想绕过就换个工具(比如先
7378
+ // project_rollback 把工作区搅一遍再开跑)。接上 ctx.tools.guard 之后
7379
+ // 任何工具调用都会先过这一关。
7380
+ //
7381
+ // 默认不开:装上就该能用,不该先被一道门拦住。要开就在配置里写
7382
+ // intentGate: 'enforce'——那时才注册,注册了才拦。
7383
+ const gated = settingsOf().intentGate === 'enforce'
7384
+ const offGuard = gated
7385
+ ? ctx.tools.guard(exec => {
7386
+ const verdict = guardToolCall({ toolName: exec.name, readiness: lastReadinessOf(exec) })
7387
+ if (verdict.allow) return undefined
7388
+ return { reason: verdict.message }
7389
+ })
7390
+ : undefined
7391
+
4755
7392
  return () => {
4756
7393
  offRun()
4757
7394
  offResume()
@@ -4763,6 +7400,7 @@ async function decorateCost(result, settings, requirements, cwd) {
4763
7400
  offEstimate()
4764
7401
  offModels()
4765
7402
  offSet()
7403
+ if (offGuard !== undefined) offGuard()
4766
7404
  }
4767
7405
  })
4768
7406
 
@@ -4834,6 +7472,34 @@ async function decorateCost(result, settings, requirements, cwd) {
4834
7472
  return { providers: groups.filter(group => group.models.length > 0 || group.failed === true) }
4835
7473
  }
4836
7474
 
7475
+ /**
7476
+ * 模型名写错要在保存时拦住,不能等跑起来才在回退日志里看见。
7477
+ *
7478
+ * 只有真探到列表时才校验。一个都探不出来(llm 服务没起、profile 里没配模型)
7479
+ * 就放行——那种情况下拦人等于把人锁死在配置界面外面,而错名字本来也有
7480
+ * 三级回退兜着。
7481
+ *
7482
+ * 三种写法都认:`kimi`、`workbuddy/kimi`、`workbuddy kimi`。用户记不清
7483
+ * 该带不带 provider 前缀,不该因为写法差异被判「模型不存在」。
7484
+ */
7485
+ const unknownModelMessage = async model => {
7486
+ if (typeof model !== 'string' || model.trim() === '') return undefined
7487
+ const wanted = model.trim()
7488
+ const catalog = await listModelCatalog()
7489
+ const known = []
7490
+ for (const group of catalog.providers ?? []) {
7491
+ for (const item of group.models ?? []) {
7492
+ if (typeof item.id !== 'string' || item.id === '') continue
7493
+ known.push(item.id, `${group.id}/${item.id}`, `${group.id} ${item.id}`)
7494
+ }
7495
+ }
7496
+ if (known.length === 0) return undefined
7497
+ const lower = wanted.toLowerCase()
7498
+ if (known.some(id => id.toLowerCase() === lower)) return undefined
7499
+ const unique = [...new Set(known)]
7500
+ return `模型「${wanted}」不在本机可用列表里,没有写入。可用的有:\n${unique.map(id => ` ${id}`).join('\n')}`
7501
+ }
7502
+
4837
7503
  /**
4838
7504
  * 刷新「本机有哪些模型」这份缓存。
4839
7505
  *