dsh-project-flow 0.9.0 → 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 (48) hide show
  1. package/CHANGELOG.md +0 -0
  2. package/README.md +58 -11
  3. package/cordis.patch.yml +30 -11
  4. package/docs/DETAIL.md +6 -6
  5. package/docs/FEATURES.md +12 -5
  6. package/docs/LAUNCH.md +3 -3
  7. package/docs/MOMENTS.md +4 -4
  8. package/docs/USAGE.md +2 -2
  9. package/domains.mjs +1 -1
  10. package/evidence.mjs +19 -3
  11. package/flow.schema.mjs +192 -35
  12. package/gate.mjs +49 -23
  13. package/index.js +639 -120
  14. package/locale/en.json +15 -4
  15. package/locale/zh.json +17 -6
  16. package/package.json +5 -3
  17. package/tests/_heartbeat-regression.test.mjs +124 -0
  18. package/tests/_wd_sandbox/.project-flow/demo/run.log +1 -0
  19. package/tests/_wd_sandbox/a.txt +1 -0
  20. package/tests/aesthetic.test.mjs +534 -0
  21. package/tests/assertions-e2e.mjs +234 -0
  22. package/tests/bench-check.mjs +32 -0
  23. package/tests/client-bundle.test.mjs +707 -0
  24. package/tests/contract.test.mjs +137 -0
  25. package/tests/desktop.test.mjs +130 -0
  26. package/tests/domains.test.mjs +220 -0
  27. package/tests/e2e.mjs +300 -0
  28. package/tests/evidence.test.mjs +408 -0
  29. package/tests/extra-phase.test.mjs +133 -0
  30. package/tests/feedback.test.mjs +187 -0
  31. package/tests/flow-create.test.mjs +168 -0
  32. package/tests/flow-gate.test.mjs +232 -0
  33. package/tests/flow-schema.test.mjs +213 -0
  34. package/tests/gate.test.mjs +246 -0
  35. package/tests/issue-loop.test.mjs +254 -0
  36. package/tests/issues-e2e.mjs +246 -0
  37. package/tests/panel-independence.test.mjs +78 -0
  38. package/tests/panel-report.test.mjs +129 -0
  39. package/tests/patch-ledger.test.mjs +280 -0
  40. package/tests/paths.mjs +94 -0
  41. package/tests/preview-path.test.mjs +69 -0
  42. package/tests/qa-assertions.test.mjs +352 -0
  43. package/tests/run-all.mjs +90 -0
  44. package/tests/stage-model.test.mjs +120 -0
  45. package/tests/stop-resume.test.mjs +260 -0
  46. package/tests/watch-root.test.mjs +167 -0
  47. package/tests/watchdog-tokens.test.mjs +49 -0
  48. package/tests/watchdog.test.mjs +301 -0
package/index.js CHANGED
@@ -20,7 +20,7 @@
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, appendFileSync } 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'
@@ -91,8 +91,12 @@ import {
91
91
  guardToolCall,
92
92
  extractReadiness,
93
93
  buttonState,
94
+ blindspotGaps,
95
+ dimensionLabel,
96
+ DIMENSIONS,
94
97
  DIMENSION_KEYS,
95
98
  MIN_CONCLUSION_LENGTH,
99
+ SCORE_FLOOR,
96
100
  } from './gate.mjs'
97
101
 
98
102
  /** Shown by project_models, /flow-models, and every plugin surface that reports identity. */
@@ -176,19 +180,40 @@ export const Config = z.object({
176
180
  // runs and simply reports that rollback is unavailable.
177
181
  snapshotEnabled: z.boolean().default(true),
178
182
  snapshotExcludes: z.string().default(''),
183
+ /**
184
+ * 快照保留张数。每次实施前后各打一张,跑十几轮返工就上百张,只增不删会一直涨。
185
+ * 默认留最近 40 张,更老的截掉。设 0 = 不截断(老行为)。
186
+ */
187
+ snapshotKeep: z.natural().default(40),
179
188
  // 工作模式只在这个目录里开。留空就认「当前工作区下的 工作流 目录」,
180
189
  // 填绝对路径就把整台机器的工作流固定到一个地方。
181
190
  flowRoot: z.string().default(''),
182
191
  /**
183
- * 目录门控。auto(默认)不拦,装完就能用;strict 只认「工作流」目录;
184
- * off 不拦也不看名字。想回到早期那道边界就设 strict。
192
+ * 目录门控。三种值:
193
+ *
194
+ * off(默认)—— 不拦,装完就能用,在哪个目录都能开工作模式。这是默认值:
195
+ * 一个要装了就用的工具,不该先让人去建目录再切工作区。
196
+ * auto —— 能识别「工作流」目录就认它,识别不出来也不拦(与 off 的
197
+ * 区别只在「该去哪」这句提示上)。
198
+ * strict —— 只认「工作流」目录,别处直接拒绝。想让目录边界硬一点再开。
199
+ *
200
+ * 以前默认值是 strict 而注释写着「auto 默认不拦」,两句话互相矛盾;
201
+ * 'auto' 这一档甚至不在合法值里,写了会被悄悄归一成 strict。
185
202
  */
186
- flowGate: z.string().default('strict'),
203
+ flowGate: z.string().default('off'),
187
204
  /**
188
205
  * 第一次在普通目录开工时,自动把「工作流」目录建出来。
189
- * 关掉就退回老行为:不在工作流目录里直接拒绝,让人自己去建。
206
+ * 只有 flowGate 为 strict 时才起作用:off / auto 下根本不会走到这一步。
190
207
  */
191
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'),
192
217
  /**
193
218
  * 桌面工具(agent-desktop 那类插件提供的 desktop_* 工具)怎么用。
194
219
  * auto:有视觉产出、或者行当本来就要在软件里核对时才提;on:一律提;off:不提。
@@ -231,7 +256,10 @@ export const Config = z.object({
231
256
  silentMsPlan: z.natural().default(300000),
232
257
  silentMsBuild: z.natural().default(900000),
233
258
  silentMsCheck: z.natural().default(900000),
234
- 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),
235
263
  // 价目表:JSON 字符串,键是模型名,值是 { input, output } 的每百万 token 美元价。
236
264
  priceTable: z.string().default(''),
237
265
  // 完成证据包:外部测试命令的 exit code 决定 requirement_met,
@@ -247,6 +275,14 @@ export const Config = z.object({
247
275
  * 白名单一旦可以被配置删空,「判据」就又回到模型嘴里了。
248
276
  */
249
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),
250
286
  /** 单条 check 的超时。不是一轮总和:一轮里每条各自计时。 */
251
287
  checkTimeoutMs: z.natural().default(120000),
252
288
  /** stdout / stderr 留多少字符的尾巴。超长只留尾部——报错基本写在最后几行。 */
@@ -396,11 +432,19 @@ export function readLedger(cwd, project) {
396
432
  /**
397
433
  * 记录实施段的一次文件写入。
398
434
  *
399
- * 在实施段真正写文件之前调 recordBefore,拿到 beforeSha;
400
- * 写完之后调 recordAfter,拿到 afterSha 并追加台账。
401
- * 两步分开是因为「写之前」和「写之后」的文件状态都要记。
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;为空时回滚会明确报「没有内容来源」
402
446
  */
403
- export async function recordFileWrite(cwd, project, filePath, batchId, stage, index) {
447
+ export async function recordFileWrite(cwd, project, filePath, batchId, stage, index, beforeCommit = '') {
404
448
  const abs = isAbsolute(filePath) ? filePath : join(cwd, filePath)
405
449
  const rel = normalizedPatchPath(isAbsolute(filePath) ? relative(cwd, filePath) : filePath)
406
450
  const beforeSha = await fileSha256(abs)
@@ -410,6 +454,7 @@ export async function recordFileWrite(cwd, project, filePath, batchId, stage, in
410
454
  stage,
411
455
  path: rel,
412
456
  beforeSha,
457
+ beforeCommit: typeof beforeCommit === 'string' ? beforeCommit : '',
413
458
  afterSha: null,
414
459
  status: 'pending',
415
460
  ts: nowIso(),
@@ -427,14 +472,23 @@ export function commitLedgerEntry(cwd, project, entry, afterSha) {
427
472
  * 按最后一批 applied 条目还原。
428
473
  *
429
474
  * 只动台账里的 path,不在台账里的文件原样保留。
430
- * 还原后追加一条 reverted 记录,指回原条目 index。
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,不能靠「忘了传」触发写操作。
431
486
  */
432
- export async function rollbackByLedger(cwd, project) {
487
+ export async function rollbackByLedger(cwd, project, { dryRun = true } = {}) {
433
488
  const entries = readLedger(cwd, project)
434
489
  if (entries.length === 0) {
435
490
  return { ok: false, reason: '台账为空,没有可回滚的条目' }
436
491
  }
437
- // 找最后一批 applied:从末尾往前,连续的 applied 条目是同一批。
438
492
  const applied = entries.filter(e => e.status === 'applied')
439
493
  if (applied.length === 0) {
440
494
  return { ok: false, reason: '台账里没有 applied 条目' }
@@ -444,54 +498,124 @@ export async function rollbackByLedger(cwd, project) {
444
498
  const lastBatch = batchIds[batchIds.length - 1]
445
499
  const batchEntries = applied.filter(e => e.batchId === lastBatch)
446
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:真动磁盘 ──
447
568
  const restored = []
448
569
  const failed = []
449
- for (const entry of batchEntries) {
570
+ for (const item of plans) {
571
+ const { entry } = item
450
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
+ }
451
581
  try {
452
- if (entry.beforeSha === null) {
453
- // 文件原来不存在,回滚就是删掉它
582
+ if (item.action === 'delete') {
454
583
  await rm(abs, { force: true })
455
584
  restored.push(`${entry.path}(删除)`)
456
585
  } else {
457
- // 从快照仓库 checkout 这个文件到 beforeSha 对应的版本
458
- // 但 beforeSha 是哈希不是 git object——只能靠快照的 commit 来 checkout。
459
- // 台账回滚的语义是「还原到这一批写入之前」,不是「还原到某个 git commit」。
460
- // 所以这里走的是:如果文件当前哈希 !== beforeSha,就报「内容已被手改,不能自动还原」。
461
- const currentSha = await fileSha256(abs)
462
- if (currentSha === entry.beforeSha) {
463
- // 已经和写入前一样了,不用动
464
- restored.push(`${entry.path}(已一致)`)
465
- } else if (currentSha === null) {
466
- // 文件被删了,需要重建——但没有内容来源。报告这个情况。
467
- failed.push(`${entry.path}(文件已被删除,无法重建)`)
468
- } else {
469
- // 文件被手改了,不能盲目覆盖
470
- failed.push(`${entry.path}(已被手改,当前 ${currentSha?.slice(0, 8)} ≠ 写入前 ${entry.beforeSha?.slice(0, 8)})`)
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
471
591
  }
592
+ restored.push(`${entry.path}(还原到 ${entry.beforeCommit.slice(0, 8)})`)
472
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
+ })
473
607
  } catch (error) {
474
608
  failed.push(`${entry.path}(${messageOf(error)})`)
475
609
  }
476
- // 记 reverted 条目
477
- appendLedgerEntry(cwd, project, {
478
- index: entry.index,
479
- batchId: entry.batchId,
480
- stage: entry.stage,
481
- path: entry.path,
482
- beforeSha: entry.afterSha,
483
- afterSha: entry.beforeSha,
484
- status: 'reverted',
485
- rollbackOf: entry.index,
486
- ts: nowIso(),
487
- })
488
610
  }
489
611
  return {
490
612
  ok: failed.length === 0,
491
- restored,
492
- failed,
613
+ dryRun: false,
493
614
  batchId: lastBatch,
494
615
  count: batchEntries.length,
616
+ restored,
617
+ failed,
618
+ plan: plans.map(p => ({ path: p.entry.path, action: p.action, note: p.note })),
495
619
  }
496
620
  }
497
621
 
@@ -728,16 +852,20 @@ export function cwdOf(ctx, agent) {
728
852
  * turn); stages 2-4 are not (three child agents, three models, snapshots), and a
729
853
  * plan built on a guessed intent multiplies the guess across every stage.
730
854
  */
731
- const INTENT_CONFIDENCE_FLOOR = 95
855
+ /**
856
+ * 门槛只有一个数,来自 gate.mjs 的 SCORE_FLOOR。
857
+ *
858
+ * 以前这里另写了一个 95,两处同时改的时候总会漏一处——门控一处放行、一处拦,
859
+ * 用户看到的是「有时候问得出来,有时候问不出来」。
860
+ */
861
+ const INTENT_CONFIDENCE_FLOOR = SCORE_FLOOR
732
862
 
733
- /** 五个硬性维度,顺序即提示词和 UI 的展示顺序。 */
734
- const BLINDSPOT_LABELS = {
735
- permissions: '权限',
736
- concurrency: '并发',
737
- edge_cases: '异常边界',
738
- stack: '技术栈',
739
- data_flow: '数据流向',
740
- }
863
+ /**
864
+ * 五个硬性维度,顺序即提示词和 UI 的展示顺序。
865
+ *
866
+ * 名字同样只有一份定义(gate.DIMENSIONS),这里只是摊平成一张查表。
867
+ */
868
+ const BLINDSPOT_LABELS = Object.fromEntries(DIMENSIONS.map(dim => [dim.key, dim.label]))
741
869
 
742
870
  /**
743
871
  * 盲区清单的硬门槛:五个维度都要给出够具体的结论,空一个或写一句空话就一票否决。
@@ -745,38 +873,50 @@ const BLINDSPOT_LABELS = {
745
873
  * 这一条排在 override 前面,是刻意的:用户说「就按这个做」放开的是
746
874
  * 「把握够不够」,不是「盲区有没有问」。两件事混在一起,override 就成了
747
875
  * 绕过一切的万能钥匙,这正是要堵的漏洞。
876
+ *
877
+ * 判定本身走 gate.blindspotGaps——那是全插件唯一一份五维判定。
878
+ * 这里只负责把结果翻译成一句人话并抛出去。
748
879
  */
749
880
  function assertNoEmptyBlindspots(blindspots) {
750
- const record = blindspots !== null && typeof blindspots === 'object' && !Array.isArray(blindspots)
751
- ? blindspots
752
- : {}
753
- const empty = []
754
- const vague = []
755
- for (const key of DIMENSION_KEYS) {
756
- const value = record[key]
757
- const line = typeof value === 'string' ? value.trim() : ''
758
- if (line === '') {
759
- empty.push(key)
760
- continue
761
- }
762
- // 「已确认」「OK」这类凑数的结论,去掉标点后不够长,也算没写。
763
- if (line.replace(/[\s\p{P}]/gu, '').length < MIN_CONCLUSION_LENGTH) vague.push(key)
764
- }
765
- if (empty.length > 0 || vague.length > 0) {
766
- const parts = []
767
- if (empty.length > 0) parts.push(`还没结论:${empty.map(key => BLINDSPOT_LABELS[key]).join('、')}`)
768
- if (vague.length > 0) parts.push(`写得太笼统,要说具体:${vague.map(key => BLINDSPOT_LABELS[key]).join('、')}`)
769
- throw new Error(
770
- [
771
- `盲区清单没过门控——${parts.join(';')}`,
772
- '',
773
- '下一步只有两条路:',
774
- '· 用 ask_user_question 一个一个问掉,问一个填一条,每条写成一句真结论;',
775
- '· 确实问不出来、且做错也能承受的,写进 assumptions 并写清验收时怎么核。',
776
- 'override 只管「把握够不够」,管不了「盲区有没有问」——这两件事分开判。',
777
- ].join('\n'),
778
- )
779
- }
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('、')}`)
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)
780
920
  }
781
921
 
782
922
  /** Reject an intent that has not converged, with a message that says what to do. */
@@ -1171,11 +1311,11 @@ const FLOW_DIR_NAME = '工作流'
1171
1311
  * 第一次在普通目录开工时,插件自己把「工作流」建出来,然后到里面干活——
1172
1312
  * 边界还在,但那一步手工操作没了。
1173
1313
  */
1174
- const FLOW_GATE_MODES = ['strict', 'off']
1314
+ const FLOW_GATE_MODES = ['off', 'auto', 'strict']
1175
1315
 
1176
1316
  export function flowModeOf(settings) {
1177
1317
  const raw = typeof settings?.flowGate === 'string' ? settings.flowGate.trim().toLowerCase() : ''
1178
- return FLOW_GATE_MODES.includes(raw) ? raw : 'strict'
1318
+ return FLOW_GATE_MODES.includes(raw) ? raw : 'off'
1179
1319
  }
1180
1320
 
1181
1321
  /**
@@ -1269,22 +1409,25 @@ export function flowRootTargetOf(cwd, settings) {
1269
1409
  /**
1270
1410
  * 这个目录能不能开工作模式。
1271
1411
  *
1272
- * 默认能。只有两种情况会说不:
1273
- * 1. flowRoot 配了绝对路径 —— 这是明确表态「只在这个子树里用」,那就守它
1274
- * 2. flowGate=strict —— 用户主动要那道边界
1412
+ * 由 flowGate 一个开关说了算:
1413
+ * off(默认)/ auto —— 任何目录都能开
1414
+ * strict —— 只认「工作流」目录
1415
+ *
1416
+ * 配了 flowRoot 绝对路径只影响「该去哪」这句提示和目录自动创建的位置,
1417
+ * 不再顺带把门关死。以前配了路径就等于强制 strict,于是「换个目录先试试」
1418
+ * 这件事变得做不到——用户得先去改配置才能试,这正是要去的门槛。
1275
1419
  */
1276
1420
  export function insideFlow(cwd, settings) {
1421
+ if (flowModeOf(settings) !== 'strict') return true
1277
1422
  const configured = typeof settings.flowRoot === 'string' ? settings.flowRoot.trim() : ''
1278
1423
  const here = resolve(cwd)
1279
- // 配了绝对路径:就是那个目录的子树,别处一律不算。这条不看 flowGate,
1280
- // 因为配了绝对路径本身就是比开关更强的表态。
1424
+ // strict 下配了绝对路径:只认那个子树的,别处一律不算。
1281
1425
  if (configured !== '' && isAbsolute(configured)) {
1282
1426
  const root = resolve(configured)
1283
1427
  const rel = relative(root, here)
1284
1428
  return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))
1285
1429
  }
1286
- if (flowModeOf(settings) !== 'strict') return true
1287
- // strict:认路径里有没有这一段。
1430
+ // strict 且没配绝对路径:认路径里有没有这一段。
1288
1431
  // cwd 本身叫这个名字(把工作流目录直接当工作区开),或者它在某个同名目录下面。
1289
1432
  const name = (configured === '' ? FLOW_DIR_NAME : configured).replace(/[\\/]+$/u, '')
1290
1433
  return here.split(/[\\/]/u).includes(name)
@@ -1396,15 +1539,31 @@ async function readState(cwd, project) {
1396
1539
  }
1397
1540
  }
1398
1541
 
1542
+ /**
1543
+ * 产物落盘。走 writeFileAtomic:进程在写一半被杀时最坏只是丢掉这次更新,
1544
+ * 不会留下半截 Requirement.md 让后面每一阶都读到坏文件。
1545
+ *
1546
+ * 以前这里是裸 writeFile。state.json 和 run.lock 早就原子化了,但真正被
1547
+ * 三个子会话反复读的那几个 .md 一直没有——「断电也不会留下要人修的东西」
1548
+ * 这句话当时说得过头了。
1549
+ */
1399
1550
  async function saveArtifact(cwd, project, fileName, content) {
1400
1551
  const dir = stateDir(cwd, project)
1401
1552
  await mkdir(dir, { recursive: true })
1402
- await writeFile(join(dir, fileName), `${content}\n`, 'utf8')
1553
+ await writeFileAtomic(join(dir, fileName), `${content}\n`)
1403
1554
  }
1404
1555
 
1405
1556
  /**
1406
1557
  * 追加写。Execution_Log.md 用这个:返工几轮就有几条记录,
1407
1558
  * 覆盖掉的话上一轮做过什么就查不到了。
1559
+ *
1560
+ * 追加写没有「原子替换」这回事——目标文件本来就是不断变长的。
1561
+ * 能做的是两件:
1562
+ * 1. 先确保父目录在(第一次写时)
1563
+ * 2. 一次 write 写完整段,而不是分多次小写;O_APPEND 保证单次写入不交错
1564
+ *
1565
+ * 真被在写到一半杀掉时,最坏结果是最后一行不完整。读取侧用
1566
+ * `readArtifactTolerant` 兜住:解析时容忍末行截断,不让一条残行毁掉整份日志。
1408
1567
  */
1409
1568
  async function appendArtifact(cwd, project, fileName, content) {
1410
1569
  const dir = stateDir(cwd, project)
@@ -1412,6 +1571,22 @@ async function appendArtifact(cwd, project, fileName, content) {
1412
1571
  await appendFile(join(dir, fileName), `${content}\n`, 'utf8')
1413
1572
  }
1414
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
+
1415
1590
  /** Concatenate the text blocks of a settled child result. */
1416
1591
  function textOf(output) {
1417
1592
  if (!Array.isArray(output)) return ''
@@ -2300,6 +2475,102 @@ function commandNameOf(token) {
2300
2475
  return base.replace(/\.(exe|cmd|bat|ps1)$/u, '')
2301
2476
  }
2302
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
+
2303
2574
  /** 生效的白名单 = 写死的 9 类 + 配置里加的,去掉空串和重复。 */
2304
2575
  export function allowedCommandsOf(settings) {
2305
2576
  const extra = typeof settings?.checkAllowedCommands === 'string' ? settings.checkAllowedCommands : ''
@@ -2355,7 +2626,7 @@ export function tokenizeCommand(cmd) {
2355
2626
  * 一条命令能不能跑。拒绝理由要写清楚是哪一条规则拦的,否则人只看到一句
2356
2627
  * 「没跑」,会以为插件坏了。
2357
2628
  */
2358
- export function checkDenial(cmd, allowed) {
2629
+ export function checkDenial(cmd, allowed, options = {}) {
2359
2630
  const list = Array.isArray(allowed) ? allowed : DEFAULT_ALLOWED_COMMANDS
2360
2631
  if (typeof cmd !== 'string' || cmd.trim() === '') return { denied: true, reason: 'check 是空的' }
2361
2632
  const tokens = tokenizeCommand(cmd)
@@ -2364,7 +2635,12 @@ export function checkDenial(cmd, allowed) {
2364
2635
  if (!list.includes(name)) {
2365
2636
  return { denied: true, reason: `命令 ${name} 不在白名单里(只放行 ${list.join(' / ')})` }
2366
2637
  }
2367
- return { denied: false, name, file: tokens[0], args: tokens.slice(1) }
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 }
2368
2644
  }
2369
2645
 
2370
2646
  /** 输出只留尾巴。stdout 大的时候前面几千行是噪音,报错在最后几行。 */
@@ -2374,13 +2650,120 @@ function tailOf(text, limit) {
2374
2650
  return value.length <= max ? value : value.slice(value.length - max)
2375
2651
  }
2376
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
+
2377
2755
  /**
2378
2756
  * 真正起进程。默认实现走 execFile:不走 shell,超时用 SIGKILL 收掉,
2379
2757
  * 拿不到可执行文件时按 127 记(和 shell 的规矩一致)。
2758
+ *
2759
+ * Windows 上的 npm/pnpm/npx 是 .cmd 垫片,要经 cmd.exe——见 resolveWindowsCommand。
2760
+ * 那条路径仍然只执行白名单放行的那一条命令:参数在进 cmd 之前已经被逐条
2761
+ * 引号包住,而白名单在更早的 checkDenial 里已经卡过命令名。
2380
2762
  */
2381
2763
  function defaultSpawnCheck({ file, args, cwd, timeoutMs, env }) {
2764
+ const resolved = resolveWindowsCommand(file, args)
2382
2765
  return new Promise(resolve => {
2383
- execFile(file, args, {
2766
+ execFile(resolved.file, resolved.args, {
2384
2767
  cwd,
2385
2768
  timeout: timeoutMs,
2386
2769
  killSignal: 'SIGKILL',
@@ -2388,13 +2771,22 @@ function defaultSpawnCheck({ file, args, cwd, timeoutMs, env }) {
2388
2771
  maxBuffer: 8 * 1024 * 1024,
2389
2772
  ...(env === undefined ? {} : { env }),
2390
2773
  }, (error, stdout, stderr) => {
2774
+ // 临时 bat 用完就删,别在系统临时目录里攒
2775
+ if (typeof resolved.cleanup === 'function') resolved.cleanup()
2391
2776
  const output = `${stdout ?? ''}${stderr ?? ''}`
2392
2777
  if (error === null || error === undefined) {
2393
2778
  resolve({ exit: 0, output })
2394
2779
  return
2395
2780
  }
2396
2781
  if (error.code === 'ENOENT') {
2397
- resolve({ exit: 127, output: `${output}${error.message}`, missing: true })
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
+ })
2398
2790
  return
2399
2791
  }
2400
2792
  const timedOut = error.killed === true || (error.signal !== undefined && error.signal !== null)
@@ -2423,6 +2815,7 @@ export async function runRequirementChecks(options) {
2423
2815
  entries = [],
2424
2816
  cwd,
2425
2817
  allowed = DEFAULT_ALLOWED_COMMANDS,
2818
+ strictEval = false,
2426
2819
  timeoutMs = DEFAULT_CHECK_TIMEOUT_MS,
2427
2820
  tailChars = DEFAULT_CHECK_TAIL_CHARS,
2428
2821
  env,
@@ -2436,7 +2829,7 @@ export async function runRequirementChecks(options) {
2436
2829
  assertions.push({ req, cmd: null, exit: null, durationMs: 0, stdoutTail: '', status: 'unverified' })
2437
2830
  continue
2438
2831
  }
2439
- const denial = checkDenial(cmd, allowed)
2832
+ const denial = checkDenial(cmd, allowed, { strictEval })
2440
2833
  if (denial.denied === true) {
2441
2834
  assertions.push({
2442
2835
  req,
@@ -3271,7 +3664,7 @@ function snapshotLabel(label) {
3271
3664
  * no changes reuses the previous commit instead of piling up empty ones.
3272
3665
  */
3273
3666
  async function takeSnapshot(cwd, project, label, options = {}) {
3274
- const { excludes = DEFAULT_SNAPSHOT_EXCLUDES, allowEmpty = false } = options
3667
+ const { excludes = DEFAULT_SNAPSHOT_EXCLUDES, allowEmpty = false, keep } = options
3275
3668
  if (await gitAvailable() !== true) {
3276
3669
  return { ok: false, reason: '这台机器上没有可用的 git,快照与回滚不可用' }
3277
3670
  }
@@ -3302,12 +3695,12 @@ async function takeSnapshot(cwd, project, label, options = {}) {
3302
3695
  // after removing it; the operation is idempotent, so a retry is safe.
3303
3696
  if (/index\.lock/iu.test(add.stderr) && await clearStaleIndexLock(cwd, project)) {
3304
3697
  const retried = await snapshotCommand(cwd, project, ['add', '-A'], { timeoutMs: 600000 })
3305
- if (retried.ok) return finishSnapshot(cwd, project, label, { allowEmpty })
3698
+ if (retried.ok) return finishSnapshot(cwd, project, label, { allowEmpty, keep })
3306
3699
  return { ok: false, reason: `暂存工作区失败:${retried.stderr.trim() || retried.message}` }
3307
3700
  }
3308
3701
  return { ok: false, reason: `暂存工作区失败:${add.stderr.trim() || add.message}` }
3309
3702
  }
3310
- return finishSnapshot(cwd, project, label, { allowEmpty })
3703
+ return finishSnapshot(cwd, project, label, { allowEmpty, keep })
3311
3704
  }
3312
3705
 
3313
3706
  /**
@@ -3326,9 +3719,72 @@ async function clearStaleIndexLock(cwd, project) {
3326
3719
  }
3327
3720
  }
3328
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
+
3329
3785
  /** Commit the staged snapshot, reusing HEAD when nothing changed. */
3330
3786
  async function finishSnapshot(cwd, project, label, options = {}) {
3331
- const { allowEmpty = false } = options
3787
+ const { allowEmpty = false, keep } = options
3332
3788
  const head = await snapshotCommand(cwd, project, ['rev-parse', 'HEAD'])
3333
3789
  const diff = await snapshotCommand(cwd, project, ['diff', '--cached', '--quiet'])
3334
3790
  const dirty = !diff.ok // `--quiet` exits 1 when there are staged changes
@@ -3340,7 +3796,12 @@ async function finishSnapshot(cwd, project, label, options = {}) {
3340
3796
  return { ok: false, reason: `建立快照失败:${commit.stderr.trim() || commit.message}` }
3341
3797
  }
3342
3798
  const after = await snapshotCommand(cwd, project, ['rev-parse', 'HEAD'])
3343
- 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 }) }
3344
3805
  }
3345
3806
 
3346
3807
  /** Every snapshot, newest first. */
@@ -4281,9 +4742,13 @@ export function apply(ctx, config) {
4281
4742
  staleLockMs: config.staleLockMs ?? 1800000,
4282
4743
  snapshotEnabled: config.snapshotEnabled === undefined ? true : config.snapshotEnabled,
4283
4744
  snapshotExcludes: config.snapshotExcludes ?? '',
4745
+ snapshotKeep: Number.isInteger(config.snapshotKeep) ? config.snapshotKeep : 40,
4284
4746
  flowRoot: config.flowRoot ?? '',
4285
- flowGate: config.flowGate ?? 'strict',
4747
+ flowGate: config.flowGate ?? 'off',
4286
4748
  autoCreateFlowDir: config.autoCreateFlowDir === undefined ? true : config.autoCreateFlowDir,
4749
+ // 意图门控强度:off(默认,只由 project_run 自查)/ enforce(注册前置拦截)。
4750
+ // 少这一行的时候配置里写什么都没用——settingsOf() 会读成 undefined。
4751
+ intentGate: config.intentGate ?? 'off',
4287
4752
  desktopTools: config.desktopTools ?? 'auto',
4288
4753
  aesthetic: config.aesthetic ?? 'auto',
4289
4754
  aestheticImages: config.aestheticImages === undefined ? true : config.aestheticImages,
@@ -4306,6 +4771,7 @@ export function apply(ctx, config) {
4306
4771
  cnyRate: config.cnyRate ?? 7,
4307
4772
  // 断言执行器:白名单、单条超时、输出留尾的长度。
4308
4773
  checkAllowedCommands: config.checkAllowedCommands ?? '',
4774
+ checkStrictEval: config.checkStrictEval === true,
4309
4775
  checkTimeoutMs: config.checkTimeoutMs ?? 120000,
4310
4776
  checkStdoutTailChars: config.checkStdoutTailChars ?? 8000,
4311
4777
  }
@@ -4578,6 +5044,12 @@ function splitRoute(value) {
4578
5044
  overridden: args.override,
4579
5045
  overrideReason: args.overrideReason,
4580
5046
  })
5047
+ // 存一份给前置门控用:这次过了,下一个会推进的工具就不该再被同一道门拦。
5048
+ rememberReadiness(parent, {
5049
+ score: confirmation.confidence,
5050
+ blindspots: confirmation.blindspots,
5051
+ assumptions: confirmation.assumptions,
5052
+ })
4581
5053
  const settings = settingsOf()
4582
5054
  if (running.has(args.project)) throw new Error(`项目 ${args.project} 正在运行,等这一轮结束`)
4583
5055
  if (running.size >= settings.maxConcurrentProjects) {
@@ -5088,9 +5560,11 @@ function splitRoute(value) {
5088
5560
  // the time anyone asks. A missing git downgrades to a warning, never a stop.
5089
5561
  const excludes = snapshotExcludesOf(settings)
5090
5562
  const snapshotsOn = settings.snapshotEnabled === true
5563
+ // 快照保留上限:0 表示不截断,只增不删(老行为)。
5564
+ const snapshotKeep = Number.isInteger(settings.snapshotKeep) ? settings.snapshotKeep : 40
5091
5565
  const snap = async label => {
5092
5566
  if (!snapshotsOn) return ''
5093
- const result = await takeSnapshot(cwd, project, label, { excludes })
5567
+ const result = await takeSnapshot(cwd, project, label, { excludes, keep: snapshotKeep })
5094
5568
  if (result.ok !== true) {
5095
5569
  if (snapshotNote === '') snapshotNote = `快照不可用:${result.reason}`
5096
5570
  await logLine(cwd, project, `快照失败(${label}):${result.reason}`)
@@ -5559,12 +6033,16 @@ function splitRoute(value) {
5559
6033
  }
5560
6034
  // ── 补丁台账:记录这一轮实施段真的写了哪些文件 ──
5561
6035
  // attempts 的文件清单来自实施段自述,可以说假话;台账记的是
5562
- // 插件通过快照 diff 看到的实际改动,beforeSha/afterSha 都是插件算的。
6036
+ // 插件通过快照 diff 看到的实际改动。
6037
+ //
6038
+ // 每条都带上 `beforeCommit`(实施前那张快照):执行到这里时工作区
6039
+ // 已经被改过了,唯一的旧内容来源就是那张快照。以前这里只存 beforeSha,
6040
+ // 回滚拿着一个哈希毫无办法,只能报「已被手改」,等于回滚从来没生效过。
5563
6041
  const batchId = `${project}-R${rework + 1}`
5564
6042
  if (touched.length > 0) {
5565
6043
  const ledgerEntries = []
5566
6044
  for (let i = 0; i < touched.length; i += 1) {
5567
- const entry = await recordFileWrite(cwd, project, touched[i], batchId, 3, i + 1)
6045
+ const entry = await recordFileWrite(cwd, project, touched[i], batchId, 3, i + 1, before)
5568
6046
  ledgerEntries.push(entry)
5569
6047
  }
5570
6048
  // 写完之后再算 afterSha:此时文件已经是实施段改过的版本
@@ -5573,7 +6051,7 @@ function splitRoute(value) {
5573
6051
  const afterSha = await fileSha256(abs)
5574
6052
  commitLedgerEntry(cwd, project, entry, afterSha)
5575
6053
  }
5576
- await logLine(cwd, project, `补丁台账:${ledgerEntries.length} 条写入(batchId=${batchId})`)
6054
+ await logLine(cwd, project, `补丁台账:${ledgerEntries.length} 条写入(batchId=${batchId}${before === '' ? ',无快照,回滚将不可用' : `,回滚点 ${before.slice(0, 8)}`})`)
5577
6055
  }
5578
6056
  const after = await snap(`实施后 R${rework + 1}`)
5579
6057
  attempts.push({
@@ -5801,6 +6279,7 @@ function splitRoute(value) {
5801
6279
  entries: checkEntries,
5802
6280
  cwd,
5803
6281
  allowed: allowedCommandsOf(settings),
6282
+ strictEval: settings.checkStrictEval === true,
5804
6283
  timeoutMs: settings.checkTimeoutMs,
5805
6284
  tailChars: settings.checkStdoutTailChars,
5806
6285
  })
@@ -6345,16 +6824,11 @@ function splitRoute(value) {
6345
6824
 
6346
6825
  // ── ledger 模式:按补丁台账回滚 ──
6347
6826
  if (isLedger) {
6348
- // 先写 pre-rollback 快照(如果 git 可用),回错了还能再回去
6349
- if (await gitAvailable() === true) {
6350
- const settings0 = settingsOf()
6351
- const guard = await takeSnapshot(cwd, project, `pre-rollback-ledger ${nowIso().slice(0, 19)}`, {
6352
- excludes: snapshotExcludesOf(settings0),
6353
- })
6354
- if (guard.ok === true) {
6355
- await logLine(cwd, project, `台账回滚前快照 → ${guard.commit.slice(0, 8)}`)
6356
- }
6357
- }
6827
+ // state 必须在这里读:下面写 rollbacks 记录要用它。
6828
+ // 以前它在 ledger 分支之后才声明,走这条路一律 ReferenceError,
6829
+ // 而错误被外层 catch 吞成一句「台账回滚失败」——看着像台账坏了。
6830
+ const state = await readState(cwd, project)
6831
+
6358
6832
  // 台账不存在时报错,不静默回滚全部
6359
6833
  const ledgerFile = ledgerPath(cwd, project)
6360
6834
  if (!existsSync(ledgerFile)) {
@@ -6363,18 +6837,43 @@ function splitRoute(value) {
6363
6837
  '台账在实施段每次写文件时自动追加。如果这个项目是在台账功能加上之前跑的,就没有台账。',
6364
6838
  )
6365
6839
  }
6366
- // 坏 JSON 行报错,不静默跳过
6840
+
6841
+ // 干跑只算差异:不打快照、不写盘、不追加台账。
6842
+ // 以前这里不读 dryRun,默认 true 一进来就直接真回滚了。
6367
6843
  let ledgerResult
6368
6844
  try {
6369
- ledgerResult = await rollbackByLedger(cwd, project)
6845
+ ledgerResult = await rollbackByLedger(cwd, project, { dryRun })
6370
6846
  } catch (error) {
6371
6847
  return fail(`台账回滚失败:${messageOf(error)}`, '台账里有坏 JSON 行,一个文件都不会动。')
6372
6848
  }
6373
6849
  if (ledgerResult.ok !== true && ledgerResult.reason !== undefined) {
6374
6850
  return fail(`台账回滚失败:${ledgerResult.reason}`)
6375
6851
  }
6852
+
6376
6853
  const restored = ledgerResult.restored ?? []
6377
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
+
6378
6877
  await logLine(cwd, project, `台账回滚:还原 ${restored.length} 个文件${failed.length > 0 ? `,${failed.length} 个失败` : ''}(batchId=${ledgerResult.batchId})`)
6379
6878
  await writeState(cwd, project, {
6380
6879
  rollbacks: [
@@ -6871,6 +7370,25 @@ async function decorateCost(result, settings, requirements, cwd) {
6871
7370
  const offEstimate = ctx.tools.register(estimateTool)
6872
7371
  const offModels = ctx.tools.register(modelsTool)
6873
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
+
6874
7392
  return () => {
6875
7393
  offRun()
6876
7394
  offResume()
@@ -6882,6 +7400,7 @@ async function decorateCost(result, settings, requirements, cwd) {
6882
7400
  offEstimate()
6883
7401
  offModels()
6884
7402
  offSet()
7403
+ if (offGuard !== undefined) offGuard()
6885
7404
  }
6886
7405
  })
6887
7406