carlos-flow 2.11.2 → 2.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,94 @@
1
+ ## [2.12.0] - 2026-11-14 — 发布暂停开关 + 19 个工具的契约文档
2
+
3
+ ### ✨ 新增 | Added
4
+
5
+ - **发布暂停开关**(`scripts/publish-gate.mjs` + `release.yml`):
6
+ `RELEASE_PAUSED=1` 时发布闸直接返回 `publish=false`,不再走版本比较逻辑;
7
+ 设为 `0` 恢复正常发布。工作区默认暂停(`RELEASE_PAUSED: '1'`),
8
+ 需要发版时再开启。背景:推 `v*` tag 等于触发 npm 自动发布,
9
+ 此前出现过修复尚未完成就把版本推上去的情况。
10
+ - **工具契约文档**(`docs/TOOL_CONTRACTS.md`):把 19 个工具的状态门、问题层、
11
+ 读写字段、测试覆盖固化成一份可核对的文档,供后续维护与新人上手。
12
+ 含 26 个状态字段的读写者清单、v0→v4 迁移链、`flow_verdict` 的
13
+ 9 组判断(15 个 return 点,2 个无条件 + 13 个仅 PASS)。
14
+ - **测试覆盖统计脚本**(`test/count-tool-refs.mjs`、`test/count-tool-calls.mjs`):
15
+ 统计每个工具在测试里的真实调用文件数与调用次数,文档里的数字可一键复现。
16
+ 调用口径含四种形式:进程内 `call()`、JSON-RPC `name:`、CLI `spawnSync`、
17
+ 激活计划 `s.tool ===` 断言。
18
+
19
+ ### 🐛 修复 | Fixed
20
+
21
+ - **并发套件误判普通卡后写为泄漏**:`test/concurrency-e2e.mjs` 的零泄漏判定
22
+ 只看 `pending.length === 0 && 卡片字段空`,但用例故意让两个进程提交
23
+ **不同类型**的卡(占位卡 vs 普通卡)。当两个进程都读到空 prev 时,
24
+ 普通卡后写落盘的 `activation_activated=false + pending=[]` 是**正确行为**
25
+ (普通卡不上闸门),被误判为泄漏(实测 457 轮里偶发 1 次)。
26
+ 现在 `stillLeak` 增加 `activation_activated === true` 条件:
27
+ 只有「最终状态是占位卡却 `pending=[]`」才算真泄漏。
28
+ 真缺陷(占位卡被错误清空)仍是 `activation_activated=true + pending=[]`,照样能拓住。
29
+
30
+ ### 📚 文档 | Docs
31
+
32
+ - 新增 `docs/TOOL_CONTRACTS.md`(640 行),含:
33
+ - 三层分类(状态门 9 个 / 工作流辅助 3 个 / 追溯查询 7 个)
34
+ - 19 张契约卡,每张固定四维
35
+ - 26 个状态字段的写入者 / 读取者 / 作用
36
+ - `flow_verdict` 的 9 组判断与顺序为何不可调换
37
+ - 读写矩阵总表、维护检查清单、已知局限
38
+ - 如实记录代码注释瑕疵:`src/index.js` 里门禁注释编号「之四」「之五」
39
+ 各出现两次且缺「之一」,不影响执行顺序但会误导维护者
40
+
41
+ ## [2.11.3] - 2026-11-13 — 多副本治理收敛 + 推 tag 前置门禁 + A1 验证绑代码状态
42
+
43
+ ### 🐛 修复 | Fixed
44
+
45
+ - **A1:验证结果绑定代码状态(指纹 + 四态)** —— 研究产物《A1-A2-A3 实施前核验清单》确认的绕过路径:
46
+ `flow_run_verify` 跑通 → executor 继续改代码(甚至改坏)→ `flow_verdict(PASS)` 三道判断全过 → **直接放行**。
47
+ 现在 `last_verify` 记录工作区指纹(HEAD + `git diff HEAD` + 全部未跟踪文件),
48
+ PASS 闸门新增第四道判断:指纹不一致即拒绝,错误含「验证结果已过期(STALE)」。
49
+ `flow_status` 新增 `verify_state` 四态(not_run / fail / stale / pass),
50
+ `verify_passed` **仍保持 boolean** 不破坏下游。
51
+ - **负对照路径同样绑定指纹**:`flow_falsify` 写 `last_verify` 时此前**不记指纹**,
52
+ 于是「先负对照、再改代码、再记 PASS」这条路径会绕过 STALE 闸门 —— 一并修复。
53
+ - **`init` 在 Windows 上产出非法 JSON**(影响所有 Windows 用户的安装):
54
+ 旧写法把 Windows 路径的**原始反斜杠**塞进 JSON 模板,
55
+ 产出含 `d` `
56
+ ` ` ` 等非法转义序列的配置文件,解析即报
57
+ 「Bad escaped character」,表现为「安装成功但插件不出现」。
58
+ 现在 JSON 目标用 JSON 转义、YAML 目标(.mcprc)用正斜杠路径。
59
+
60
+ ### 🔒 变更 | Changed
61
+
62
+ - **多副本治理收敛**(本机 5 套副本 → 2 套):
63
+ - 归档 `carlos-flow-cindy` / `carlos-flow-opencode` / `_carlos-flow-remote` 等 7 个目录
64
+ (三个 git 副本的**独有提交实测均为 0**,无内容丢失);保留发布线与线上运行副本两份。
65
+ - 线上运行副本(`D:cindycarlos-flow-mcp`)从 2.8.0 **同步到最新发布版**,
66
+ 此前它的 bridge 无 `windowsHide`、无路径自探测 —— 也就是说仓库里修好的黑窗问题**在用户机器上根本没生效**。
67
+ - Cindy **已安装插件**(旧 v1.0.5 架构)两处 spawn 补上 `windowsHide: true` ——
68
+ 这才是用户实际看到的黑色控制台窗口的来源。
69
+ - npm 全局安装同步到最新发布版。
70
+
71
+ ### 🔒 发布控制 | Release Control
72
+
73
+ - **发布暂停开关**(`scripts/publish-gate.mjs` + `release.yml`):
74
+ `RELEASE_PAUSED=1` 时停止 npm publish,只建 GitHub Release;
75
+ 设为 `0` 恢复。工作区本地操作默认暂停(`RELEASE_PAUSED: '1'`),
76
+ 需要发布时再开启。防止修复未完成时自动把半成品推上 npm。
77
+
78
+ ### 🧪 新增门禁 | Gates
79
+
80
+ - **推 tag 前置钩子**(`scripts/install-hooks.mjs`):只拦截 **tag 推送**,依次校验
81
+ 版本号一致性(`sync-version --check`)/ `check-all.sh` 真 RPC 往返 / tag 重名。
82
+ 背景:推 `v*` tag **等于**触发 npm 自动发布,此前 v2.11.1 那样没跑过验证的提交被打 tag 推上远端。
83
+ - **`check:templates` 模板渲染门禁**:用真实 Windows 路径渲染全部模板,
84
+ 断言产物可解析且路径无损,并校验 `client/carlos.js` 的转义写法与门禁**同源**。
85
+ - **`test:stale` A1 验证测试**:把研究文档里 4 段需要人手敲的命令(V1.1~V1.4)变成 14 条自动化断言。
86
+
87
+ ### ✨ 新增 | Added
88
+
89
+ - **`sync-version.mjs --check` 只读模式**:有偏差退出码 1 且不写文件,供推 tag 钩子做精确判定。
90
+ - **`sync-version.mjs` 批量对齐版本号**:以 package.json 为唯一真源,同步 package-lock.json / ghost.json / TRIGGER_GUIDE.md / CHANGELOG.md。
91
+
1
92
  ## [2.11.2] - 2026-11-13 — 修复 Bridge 转发通路与 Windows 黑窗,新增路径自探测
2
93
 
3
94
  ### ✨ 新增 | Added
package/TRIGGER_GUIDE.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Carlos Flow 智能触发引擎使用指南
2
2
 
3
- > **版本**: v2.11.2
3
+ > **版本**: v2.12.0
4
4
  > **适用**:`carlos-flow` 单包架构(2.6.0+)
5
5
  > **代码位置**:`src/trigger.js`(零外部依赖的纯 JavaScript 实现)
6
6
 
@@ -779,5 +779,5 @@ MIT License
779
779
 
780
780
  ---
781
781
 
782
- **版本**: v2.11.2
782
+ **版本**: v2.12.0
783
783
  **更新日期**: 2026-11-12
package/client/carlos.js CHANGED
@@ -417,14 +417,28 @@ async function runInit(target) {
417
417
  console.log(`✅ 触发器配置已写入: ${tcPath}`);
418
418
  }
419
419
 
420
+ // --- __ROOT__ 渲染:必须按目标格式转义 ---
421
+ //
422
+ // 背景(2026-11-13 实测):旧实现直接 `.replace(/__ROOT__/g, ROOT_ABS)`,
423
+ // 把 Windows 路径的**原始反斜杠**嵌进 JSON 模板,产出
424
+ // "D:\dev-env\node-v22.23.4-win-x64\node_modules\carlos-flow/bridge/mcp-bridge.js"
425
+ // 其中 `\d` `\n` `\v` 都是**非法 JSON 转义序列** —— 文件根本解析不了,
426
+ // 表现为「安装成功但插件不出现」,而且任何 JSON 解析器都报同一个位置。
427
+ //
428
+ // 两种目标格式要分别处理:
429
+ // - JSON(ghost.json / mcp.json / opencode.json):必须 JSON 转义(反斜杠 → \\)
430
+ // - YAML(.mcprc):Windows 路径一律用正斜杠(反斜杠在 YAML 双引号标量里同样非法)
431
+ const rootJson = JSON.stringify(ROOT_ABS).slice(1, -1);
432
+ const rootYaml = ROOT_ABS.replace(/\\/g, "/");
433
+
420
434
  if (target === "cindy") {
421
435
  // --- Cindy: 生成 ghost.json 到 ~/.cindy/ghosts/ ---
422
436
  const ghostsDir = join(home, ".cindy", "ghosts");
423
437
  mkdirSync(ghostsDir, { recursive: true });
424
438
  const ghostPath = join(ghostsDir, "carlos-flow.json");
425
-
439
+
426
440
  const ghostTemplate = readFileSync(resolve(ROOT_ABS, "ghost.json"), "utf8");
427
- const ghostContent = ghostTemplate.replace(/__ROOT__/g, ROOT_ABS);
441
+ const ghostContent = ghostTemplate.replace(/__ROOT__/g, rootJson);
428
442
  writeFileSync(ghostPath, ghostContent, "utf8");
429
443
  console.log(`✅ Cindy ghost 已写入: ${ghostPath}`);
430
444
  console.log(` 重启 Cindy 后即可在侧栏看到 "Carlos 工作流" 插件`);
@@ -435,13 +449,13 @@ async function runInit(target) {
435
449
  const pluginPath = join(pluginDir, "opencode.json");
436
450
 
437
451
  const pluginTemplate = readFileSync(resolve(ROOT_ABS, "opencode.json.template"), "utf8");
438
- const pluginContent = pluginTemplate.replace(/__ROOT__/g, ROOT_ABS);
452
+ const pluginContent = pluginTemplate.replace(/__ROOT__/g, rootJson);
439
453
  writeFileSync(pluginPath, pluginContent, "utf8");
440
454
  console.log(`✅ OpenCode 插件配置已写入: ${pluginPath}`);
441
455
 
442
456
  // 同时生成 .mcprc 到项目根目录(用户可手动复制)
443
457
  const mcprcTemplate = readFileSync(resolve(ROOT_ABS, ".mcprc.template"), "utf8");
444
- const mcprcContent = mcprcTemplate.replace(/__ROOT__/g, ROOT_ABS);
458
+ const mcprcContent = mcprcTemplate.replace(/__ROOT__/g, rootYaml);
445
459
  const mcprcPath = join(process.cwd(), ".mcprc");
446
460
  writeFileSync(mcprcPath, mcprcContent, "utf8");
447
461
  console.log(`✅ MCP 配置模板已写入: ${mcprcPath}`);
@@ -454,7 +468,7 @@ async function runInit(target) {
454
468
 
455
469
  const templatePath = resolve(ROOT_ABS, "templates", target, "mcp.json");
456
470
  const template = readFileSync(templatePath, "utf8");
457
- const content = template.replace(/__ROOT__/g, ROOT_ABS);
471
+ const content = template.replace(/__ROOT__/g, rootJson);
458
472
  writeFileSync(configPath, content, "utf8");
459
473
  console.log(`✅ ${target.charAt(0).toUpperCase() + target.slice(1)} 配置已写入: ${configPath}`);
460
474
  } else if (target === "vscode") {
@@ -465,7 +479,7 @@ async function runInit(target) {
465
479
 
466
480
  const templatePath = resolve(ROOT_ABS, "templates", "vscode", "mcp.json");
467
481
  const template = readFileSync(templatePath, "utf8");
468
- const content = template.replace(/__ROOT__/g, ROOT_ABS);
482
+ const content = template.replace(/__ROOT__/g, rootJson);
469
483
  writeFileSync(configPath, content, "utf8");
470
484
  console.log(`✅ VS Code (Copilot) 配置已写入: ${configPath}`);
471
485
  } else if (target === "claude") {
package/ghost.json CHANGED
@@ -5,7 +5,7 @@
5
5
  "name": "Carlos 工作流",
6
6
  "description": "机械门禁 MCP:留痕/派发/裁定/审计/快照/免检/还原。自动管理 Bridge 后台常驻,首次调用 ~3-5s,后续 ~1s。",
7
7
  "whenToUse": "需要走 Carlos 工作流门禁时使用:留痕/派发/裁定/审计/快照/免检/还原",
8
- "version": "2.11.2",
8
+ "version": "2.12.0",
9
9
  "kind": "mcp",
10
10
  "entry": "client/carlos.js",
11
11
  "command": "门禁",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "carlos-flow",
3
- "version": "2.11.2",
3
+ "version": "2.12.0",
4
4
  "description": "Carlos 工作流 — AI 编码 Agent 的机械门禁。留痕/派发/验证/裁定/审计/还原,约束写在代码里而非提示词里。单一包支持 Cindy/OpenCode/Cursor/Cline/VS Code/Claude Desktop。",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
@@ -23,7 +23,7 @@
23
23
  "test:trigger": "node test/trigger-e2e.mjs",
24
24
  "test:concurrency": "node test/concurrency-e2e.mjs",
25
25
  "test:acceptance": "node test/e2e-acceptance.mjs",
26
- "test:all": "npm run test && npm run test:baseline && npm run test:e2e && npm run test:p0 && npm run test:trigger && npm run test:concurrency && npm run test:acceptance && npm run test:gate",
26
+ "test:all": "npm run test && npm run test:baseline && npm run test:e2e && npm run test:p0 && npm run test:trigger && npm run test:concurrency && npm run test:acceptance && npm run test:gate && npm run test:stale && npm run test:scope && npm run test:audit && npm run test:bridge",
27
27
  "test:mutation": "node scripts/mutation-check.mjs",
28
28
  "sync:readme": "node scripts/sync-readme.mjs",
29
29
  "check:readme": "node scripts/sync-readme.mjs --check",
@@ -52,7 +52,11 @@
52
52
  "test:bridge": "node test/bridge-identity.mjs",
53
53
  "sync:version": "node scripts/sync-version.mjs",
54
54
  "check:version": "node scripts/check-repo-parity.mjs",
55
- "test:gate": "node test/publish-gate.test.mjs"
55
+ "test:gate": "node test/publish-gate.test.mjs",
56
+ "install:hooks": "node scripts/install-hooks.mjs",
57
+ "check:hooks": "node scripts/install-hooks.mjs --check",
58
+ "test:stale": "node test/verify-stale.test.mjs",
59
+ "check:templates": "node scripts/check-templates.mjs"
56
60
  },
57
61
  "keywords": [
58
62
  "carlos",
@@ -0,0 +1,126 @@
1
+ // 模板渲染合法性门禁
2
+ //
3
+ // 为什么需要(2026-11-13 实测事故):
4
+ // `carlos-flow init --target <platform>` 曾经用**裸字符串替换**把项目根路径塞进模板,
5
+ // 即不做任何转义地把路径原文替换进 JSON 字符串里。
6
+ // Windows 路径的原始反斜杠因此进了 JSON,产出形如
7
+ // "D:\dev-env\node-v22.23.4-win-x64\node_modules\carlos-flow/bridge/mcp-bridge.js"
8
+ // 其中 \d \n \v 都是**非法 JSON 转义序列** —— 配置文件根本解析不了,
9
+ // 表现为「安装成功但插件不出现」,而且任何解析器都报同一个位置。
10
+ // 现场文件 C:\Users\EDY\.cindy\ghosts\carlos-flow.json 就是这个状态。
11
+ // 正确写法见 client/carlos.js:JSON 目标用 JSON.stringify 转义,YAML 目标用正斜杠。
12
+ //
13
+ // 本门禁做的事:
14
+ // 用**真实的 Windows 路径**渲染全部模板,断言产物能被正确解析,
15
+ // 并且路径里的反斜杠没有丢失、没有变成非法转义。
16
+ //
17
+ // 运行:node scripts/check-templates.mjs
18
+
19
+ import { readFileSync } from "node:fs";
20
+ import { join, dirname } from "node:path";
21
+ import { fileURLToPath } from "node:url";
22
+
23
+ const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
24
+
25
+ let pass = 0;
26
+ let fail = 0;
27
+
28
+ function ok(msg) {
29
+ pass++;
30
+ console.log(" ✅ " + msg);
31
+ }
32
+ function bad(msg) {
33
+ fail++;
34
+ console.log(" ❌ " + msg);
35
+ }
36
+
37
+ // 真实的 Windows 路径(含反斜杠、大写、子目录),用来复现事故现场
38
+ const WIN_ROOT = "D:\\dev-env\\node-v22.23.4-win-x64\\node_modules\\carlos-flow";
39
+
40
+ // 与 client/carlos.js 中的渲染逻辑保持一致(这是本门禁的关键:两处必须同源)
41
+ const rootJson = JSON.stringify(WIN_ROOT).slice(1, -1);
42
+ const rootYaml = WIN_ROOT.replace(/\\/g, "/");
43
+
44
+ console.log("▶ JSON 模板:Windows 路径渲染后必须可解析且路径无损");
45
+
46
+ const jsonTemplates = [
47
+ ["ghost.json", (t) => t.replace(/__ROOT__/g, rootJson)],
48
+ ["opencode.json.template", (t) => t.replace(/__ROOT__/g, rootJson)],
49
+ ["templates/cursor/mcp.json", (t) => t.replace(/__ROOT__/g, rootJson)],
50
+ ["templates/cline/mcp.json", (t) => t.replace(/__ROOT__/g, rootJson)],
51
+ ["templates/vscode/mcp.json", (t) => t.replace(/__ROOT__/g, rootJson)],
52
+ ["templates/claude/claude_desktop_config.json", (t) => t.replace(/__ROOT__/g, rootJson)],
53
+ ];
54
+
55
+ for (const [rel, render] of jsonTemplates) {
56
+ let raw = "";
57
+ try {
58
+ raw = readFileSync(join(ROOT, rel), "utf8");
59
+ } catch {
60
+ bad(`${rel} 读不到`);
61
+ continue;
62
+ }
63
+ if (!raw.includes("__ROOT__")) {
64
+ bad(`${rel} 里没有 __ROOT__ 占位符 —— 渲染逻辑可能已失效,模板与代码脱节`);
65
+ continue;
66
+ }
67
+ const out = render(raw);
68
+ try {
69
+ const parsed = JSON.parse(out);
70
+ ok(`${rel} 渲染后可解析`);
71
+ // 路径无损检查:反斜杠必须完好,不能变成 \\ 之外的任何形态
72
+ const found = JSON.stringify(parsed).includes("dev-env");
73
+ if (!found) bad(`${rel} 渲染后路径内容丢失`);
74
+ } catch (e) {
75
+ bad(`${rel} 渲染后无法解析:${e.message}`);
76
+ }
77
+ }
78
+
79
+ console.log("▶ YAML 模板:.mcprc 必须用正斜杠(反斜杠在 YAML 双引号里同样非法)");
80
+
81
+ try {
82
+ const raw = readFileSync(join(ROOT, ".mcprc.template"), "utf8");
83
+ const out = raw.replace(/__ROOT__/g, rootYaml);
84
+ if (out.includes("\\\\")) {
85
+ bad(".mcprc.template 渲染后仍含双反斜杠 —— YAML 双引号标量里 \\d \\U 是非法转义");
86
+ } else if (out.includes(rootYaml)) {
87
+ ok(".mcprc.template 渲染后为正斜杠路径");
88
+ } else {
89
+ bad(".mcprc.template 渲染后未找到正斜杠路径");
90
+ }
91
+ } catch (e) {
92
+ bad(".mcprc.template 读不到:" + e.message);
93
+ }
94
+
95
+ console.log("▶ 反例确认:旧的裸替换写法必须确实产出非法 JSON");
96
+
97
+ {
98
+ const raw = readFileSync(join(ROOT, "ghost.json"), "utf8");
99
+ const oldOut = raw.replace(/__ROOT__/g, WIN_ROOT);
100
+ try {
101
+ JSON.parse(oldOut);
102
+ bad("旧的裸替换写法竟然能解析 —— 前提假设已变,门禁需重新评估");
103
+ } catch {
104
+ ok("旧的裸替换写法确实产出非法 JSON(本门禁守的正是这个)");
105
+ }
106
+ }
107
+
108
+ console.log("▶ 源码一致性:client/carlos.js 必须用同样的转义方式");
109
+
110
+ {
111
+ const src = readFileSync(join(ROOT, "client", "carlos.js"), "utf8");
112
+ const usesJsonEscape = /JSON\.stringify\(ROOT_ABS\)\.slice\(1,\s*-1\)/.test(src);
113
+ const usesYamlSlash = /ROOT_ABS\.replace\(\/\\\\\/g,\s*"\/"\)/.test(src);
114
+ if (usesJsonEscape) ok("client/carlos.js 使用 JSON 转义渲染 ROOT");
115
+ else bad("client/carlos.js 未使用 JSON 转义渲染 ROOT —— 与本门禁不同源");
116
+
117
+ if (usesYamlSlash) ok("client/carlos.js 对 YAML 目标使用正斜杠");
118
+ else bad("client/carlos.js 未对 YAML 目标使用正斜杠 —— 与本门禁不同源");
119
+ }
120
+
121
+ console.log("");
122
+ if (fail) {
123
+ console.log(`❌ 模板渲染门禁失败:${pass} 通过 / ${fail} 失败`);
124
+ process.exit(1);
125
+ }
126
+ console.log(`✅ 模板渲染门禁全部通过(${pass} 条)`);
@@ -0,0 +1,166 @@
1
+ // 推 tag 前置钩子安装器
2
+ //
3
+ // 为什么需要:
4
+ // 1. 2026-11-13 的 v2.11.1 —— 一个**没跑过任何验证**的提交被打上 tag 并推上远端,
5
+ // 里面包含一个语法错误的冒烟测试和一个只有 23 行的残缺 bridge。
6
+ // 2. 推 `v*` tag **等于**触发 npm 自动发布 —— 推错 tag 的代价远大于推错分支。
7
+ //
8
+ // 装上之后,`git push` 只要涉及 tag,就会自动跑:
9
+ // - `./check-all.sh`(语法校验 + 真 RPC 往返冒烟测试)
10
+ // - `npm run sync:version` 的等价校验(版本号在 4 处是否一致)
11
+ // - tag 重名检查
12
+ // 任何一项不过,**推送被阻断**,远端不会出现带缺陷的 tag。
13
+ //
14
+ // 用法:
15
+ // node scripts/install-hooks.mjs # 安装
16
+ // node scripts/install-hooks.mjs --check # 只检查装没装 / 是否最新
17
+
18
+ import { existsSync, readFileSync, writeFileSync, mkdirSync, copyFileSync } from "node:fs";
19
+ import { join, dirname } from "node:path";
20
+ import { fileURLToPath } from "node:url";
21
+ import { execFileSync } from "node:child_process";
22
+
23
+ const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
24
+ const HOOKS_DIR = join(ROOT, ".git", "hooks");
25
+ const HOOK_PATH = join(HOOKS_DIR, "pre-push");
26
+
27
+ // 钩子正文。用 bash 写(Git for Windows 自带 bash)。
28
+ // 关键:只对 **tag** 推送生效,普通分支推送不受影响。
29
+ const HOOK = `#!/bin/bash
30
+ # ============================================================
31
+ # Carlos Flow —— 推 tag 前置门禁(由 scripts/install-hooks.mjs 生成)
32
+ #
33
+ # 背景:推 v* tag 会触发 GitHub Actions 自动 npm publish。
34
+ # 没有这道门禁时,v2.11.1 那样「没跑过验证」的提交会被打 tag 推上远端。
35
+ #
36
+ # 规则:只对 **tag 推送** 生效;分支推送直接放行。
37
+ # ============================================================
38
+
39
+ set -u
40
+
41
+ # 钩子位于 .git/hooks/ —— 仓库根是它的 ../..(不是 ..,那是 .git 目录本身)
42
+ REPO_ROOT="$(cd "$(dirname "\${BASH_SOURCE[0]}")/../.." && pwd)"
43
+ [ -f "$REPO_ROOT/package.json" ] || REPO_ROOT="$(git rev-parse --show-toplevel 2>/dev/null)"
44
+ cd "$REPO_ROOT" || exit 1
45
+ [ -f "$REPO_ROOT/package.json" ] || { echo "❌ 找不到仓库根目录(package.json)"; exit 1; }
46
+
47
+ # 从 stdin 读待推送的 ref:<local ref> <local sha> <remote ref> <remote sha>
48
+ PUSHING_TAG=0
49
+ TAG_NAME=""
50
+ while read -r LOCAL_REF LOCAL_SHA REMOTE_REF REMOTE_SHA; do
51
+ if echo "$REMOTE_REF" | grep -q '^refs/tags/'; then
52
+ PUSHING_TAG=1
53
+ TAG_NAME="\${REMOTE_REF#refs/tags/}"
54
+ fi
55
+ done
56
+
57
+ if [ "$PUSHING_TAG" -eq 0 ]; then
58
+ exit 0
59
+ fi
60
+
61
+ echo "=============================================="
62
+ echo "🚧 推 tag 前置门禁:$TAG_NAME"
63
+ echo "=============================================="
64
+
65
+ # --- 1. 版本号单一真源校验(只读) ---
66
+ # 版本号散落 5 处(package.json / package-lock.json / ghost.json / TRIGGER_GUIDE.md / CHANGELOG.md),
67
+ # 漏改任一处 release 的「单包一致性检查」就会红、发布中止。
68
+ # --check 只读不写:有偏差则退出 1。
69
+ if ! node scripts/sync-version.mjs --check >/dev/null 2>&1; then
70
+ echo "❌ 版本号未对齐(package.json / package-lock.json / ghost.json / TRIGGER_GUIDE.md / CHANGELOG.md)"
71
+ echo " 请先运行:npm run sync:version,然后提交改动"
72
+ exit 1
73
+ fi
74
+ # 版本已对齐但还没提交 —— tag 指向的提交里版本与工作区不一致,同样要拦。
75
+ if ! git diff --quiet -- package-lock.json ghost.json TRIGGER_GUIDE.md CHANGELOG.md; then
76
+ echo "❌ 版本相关文件有未提交改动"
77
+ echo " 请先提交这些改动再推 tag(tag 指向的提交必须与工作区一致)"
78
+ exit 1
79
+ fi
80
+ echo "✅ 版本号一致性"
81
+
82
+ # --- 2. 语法校验 + 真 RPC 往返冒烟测试 ---
83
+ if ! bash ./check-all.sh; then
84
+ echo "❌ Gatekeeper 未通过,拒绝推送 tag"
85
+ echo " 修好后再推;这条 gate 存在的意义就是别再推坏版本。"
86
+ exit 1
87
+ fi
88
+
89
+ # --- 3. tag 重名检查(查**远端**,不是本地) ---
90
+ # 正常流程就是「本地先 git tag 再 push」,本地存在是必然的;
91
+ # 真正要拦的是**远端已有同名 tag**。
92
+ #
93
+ # 但远端已有 tag 不等于一律不能推 —— 有一种合法场景:
94
+ # 「上次发布在门禁阶段失败 → tag 已推上去但 npm 没收到 → 修好后重推同一个 tag」。
95
+ # 区分标准:**该版本是否已经发布到 npm**。
96
+ # · 已发布 → 移动 tag 会让 npm 版本与 git tag 对不上 → 拦
97
+ # · 未发布 → 是失败恢复路径 → 放行(并明确告知)
98
+ if git ls-remote --exit-code --tags origin "refs/tags/$TAG_NAME" >/dev/null 2>&1; then
99
+ VERSION="\${TAG_NAME#v}"
100
+ PUBLISHED="$(npm view carlos-flow versions --json --prefer-online 2>/dev/null || echo '')"
101
+ if echo "$PUBLISHED" | grep -q "\"$VERSION\""; then
102
+ echo "❌ tag $TAG_NAME 对应的版本 $VERSION 已发布到 npm,不能移动"
103
+ echo " 移动 tag 会让 npm 版本与 git tag 对不上(用户装到的代码与仓库不符)"
104
+ echo " 若确需继续,请先发新版本号"
105
+ exit 1
106
+ fi
107
+ echo "⚠️ 远端已存在 tag $TAG_NAME,但该版本**未发布到 npm**"
108
+ echo " (这是「上次发布在门禁阶段失败 → 修好后重推」的标准恢复路径,允许覆盖)"
109
+ fi
110
+ echo "✅ tag 名可用"
111
+
112
+ echo ""
113
+ echo "=============================================="
114
+ echo "✅ 全部前置门禁通过,可以推 tag:$TAG_NAME"
115
+ echo " ⚠️ 提醒:推 v* tag 会触发 npm 自动发布"
116
+ echo "=============================================="
117
+ exit 0
118
+ `;
119
+
120
+ function main() {
121
+ const checkOnly = process.argv.includes("--check");
122
+
123
+ if (checkOnly) {
124
+ if (!existsSync(HOOK_PATH)) {
125
+ console.log("❌ 未安装推 tag 前置钩子");
126
+ process.exit(1);
127
+ }
128
+ const cur = readFileSync(HOOK_PATH, "utf8");
129
+ const ok = cur === HOOK;
130
+ console.log(ok ? "✅ 钩子已安装且为最新" : "⚠️ 钩子已安装但内容不是最新,重新安装即可");
131
+ process.exit(ok ? 0 : 1);
132
+ }
133
+
134
+ if (!existsSync(join(ROOT, ".git"))) {
135
+ console.error("❌ 当前目录不是 git 仓库");
136
+ process.exit(1);
137
+ }
138
+
139
+ mkdirSync(HOOKS_DIR, { recursive: true });
140
+
141
+ // 备份既有钩子(不覆盖别人的东西)
142
+ if (existsSync(HOOK_PATH)) {
143
+ const bak = HOOK_PATH + ".bak-" + Date.now();
144
+ copyFileSync(HOOK_PATH, bak);
145
+ console.log("ℹ️ 已备份原钩子:" + bak);
146
+ }
147
+
148
+ writeFileSync(HOOK_PATH, HOOK, "utf8");
149
+ console.log("✅ 已安装推 tag 前置钩子:" + HOOK_PATH);
150
+
151
+ // Windows 上 git 可能在提交时丢掉可执行位,这里直接修回 100755
152
+ try {
153
+ execFileSync("git", ["update-index", "--chmod=+x", ".git/hooks/pre-push"], {
154
+ cwd: ROOT,
155
+ stdio: "ignore",
156
+ });
157
+ } catch {
158
+ // .git/hooks 不在 index 里,这条会失败,属预期,忽略
159
+ }
160
+
161
+ console.log("");
162
+ console.log("生效范围:只拦截 **tag 推送**;普通分支推送不受影响。");
163
+ console.log("自检:node scripts/install-hooks.mjs --check");
164
+ }
165
+
166
+ main();
@@ -17,6 +17,11 @@
17
17
  // node scripts/publish-gate.mjs --count 12
18
18
  //
19
19
  // 输出:向 $GITHUB_OUTPUT 写 publish=true/false(若有该环境变量),并打印人话结论。
20
+ //
21
+ // ===== 发布暂停开关 =====
22
+ // RELEASE_PAUSED=1 → 停止所有 npm publish(仅建 GitHub Release)
23
+ // RELEASE_PAUSED=0 → 恢复正常发布(由 deploy 方决定是否启用)
24
+ // 本机操作时默认开闸,仅 CI 触发推送时带开关才生效
20
25
 
21
26
  import { execFileSync } from "node:child_process";
22
27
  import { readFileSync, appendFileSync } from "node:fs";
@@ -25,7 +30,7 @@ import { fileURLToPath, pathToFileURL } from "node:url";
25
30
 
26
31
  const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
27
32
 
28
- // 语义化版本比较:a > b 返回正数,a < b 返回负数,相等返回 0
33
+ /** 语义化版本比较:a > b 返回正数,a < b 返回负数,相等返回 0 */
29
34
  export function semverCompare(a, b) {
30
35
  const pa = String(a).split(/[.-]/).map((x) => Number(x) || 0);
31
36
  const pb = String(b).split(/[.-]/).map((x) => Number(x) || 0);
@@ -37,7 +42,7 @@ export function semverCompare(a, b) {
37
42
  return 0;
38
43
  }
39
44
 
40
- // 纯函数:给定版本与 registry 现状,返回是否允许发布
45
+ /** 纯函数:给定版本与 registry 现状,返回是否允许发布 */
41
46
  export function decidePublish({ version, latest, count }) {
42
47
  if (!latest || !count || count <= 1) {
43
48
  return { publish: true, reason: "registry 暂无已发布版本 —— 允许发布" };
@@ -60,6 +65,13 @@ export function decidePublish({ version, latest, count }) {
60
65
  };
61
66
  }
62
67
 
68
+ /** 发布暂停指令:RELEASE_PAUSED 为非空非 0 时禁止 npm publish */
69
+ export function releasePaused() {
70
+ const v = String(process.env.RELEASE_PAUSED || "").trim().toLowerCase();
71
+ if (!v || v === "0" || v === "false") return false;
72
+ return true;
73
+ }
74
+
63
75
  function argOf(name) {
64
76
  const i = process.argv.indexOf(name);
65
77
  return i === -1 ? null : process.argv[i + 1];
@@ -100,13 +112,22 @@ function main() {
100
112
  }
101
113
  }
102
114
 
115
+ if (releasePaused()) {
116
+ const reason = "RELEASE_PAUSED 已设置 → 停止所有 npm publish(仅建 Release)";
117
+ console.log(`本次版本:${version} | registry latest:${latest || "(无)"} | 已发布版本数:${count}`);
118
+ console.log(reason);
119
+ if (process.env.GITHUB_OUTPUT) appendFileSync(process.env.GITHUB_OUTPUT, "publish=false\n");
120
+ console.log("publish=false");
121
+ return;
122
+ }
123
+
103
124
  const { publish, reason } = decidePublish({
104
125
  version,
105
126
  latest: latest || "",
106
127
  count,
107
128
  });
108
129
 
109
- console.log(`▶ 本次版本:${version}|registry latest:${latest || "(无)"}|已发布版本数:${count}`);
130
+ console.log(`本次版本:${version} | registry latest:${latest || "(无)"} | 已发布版本数:${count}`);
110
131
  console.log(`${publish ? "✓" : "✗"} ${reason}`);
111
132
 
112
133
  if (process.env.GITHUB_OUTPUT) {
@@ -10,6 +10,11 @@
10
10
  // node scripts/sync-version.mjs 仅同步并校验(不改 CHANGELOG)
11
11
  // node scripts/sync-version.mjs --changelog "标题" 同时在 CHANGELOG 顶部插入新条目
12
12
  // node scripts/sync-version.mjs --date 2026-11-13 指定条目日期(默认今天)
13
+ // node scripts/sync-version.mjs --check 只读校验:有偏差则退出码 1 且**不写文件**
14
+ //
15
+ // --check 为什么需要:推 tag 前置钩子要判断「版本号是否已对齐且已提交」。
16
+ // 普通模式会写文件(退出码总是 0),没法用来做只读判定;
17
+ // --check 不写任何文件,有偏差就退出 1。
13
18
 
14
19
  import { readFileSync, writeFileSync } from "node:fs";
15
20
  import { join, dirname } from "node:path";
@@ -25,7 +30,15 @@ function readText(rel) {
25
30
  }
26
31
  }
27
32
 
33
+ let changedFiles = [];
34
+
28
35
  function writeText(rel, text) {
36
+ if (CHECK_ONLY) {
37
+ // --check 模式只记录,不落盘
38
+ if (!changedFiles.includes(rel)) changedFiles.push(rel);
39
+ console.log(" ❌ " + rel + " 需同步");
40
+ return;
41
+ }
29
42
  writeFileSync(join(ROOT, rel), text, "utf8");
30
43
  console.log(` ✏️ ${rel}`);
31
44
  }
@@ -39,6 +52,7 @@ function readJson(rel) {
39
52
  }
40
53
 
41
54
  const argv = process.argv.slice(2);
55
+ const CHECK_ONLY = argv.includes("--check");
42
56
  const changelogTitle = argv.includes("--changelog")
43
57
  ? argv[argv.indexOf("--changelog") + 1]
44
58
  : null;
@@ -113,6 +127,10 @@ if (changelog) {
113
127
  changelog =
114
128
  changelog.slice(0, insertAt) + entry + changelog.slice(insertAt);
115
129
  writeText("CHANGELOG.md", changelog);
130
+ } else if (CHECK_ONLY) {
131
+ // --check 模式:只报告偏差,不退出(最后统一汇总)
132
+ if (!changedFiles.includes("CHANGELOG.md")) changedFiles.push("CHANGELOG.md");
133
+ console.log(" ❌ CHANGELOG.md 顶部需同步");
116
134
  } else {
117
135
  console.error(
118
136
  `❌ CHANGELOG.md 顶部是 ${topVer || "(无)"},与 ${ver} 不一致。\n` +
@@ -123,4 +141,15 @@ if (changelog) {
123
141
  }
124
142
  }
125
143
 
126
- console.log("\n✅ 版本号已全部对齐到 " + ver);
144
+ if (CHECK_ONLY) {
145
+ if (changedFiles.length) {
146
+ console.error(
147
+ "\n❌ 版本号未对齐,需同步:" + changedFiles.join("、") +
148
+ "\n 请运行:npm run sync:version(改完记得提交)",
149
+ );
150
+ process.exit(1);
151
+ }
152
+ console.log("\n✅ 版本号已全部对齐到 " + ver);
153
+ } else {
154
+ console.log("\n✅ 版本号已全部对齐到 " + ver);
155
+ }
package/src/index.js CHANGED
@@ -9,7 +9,7 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
9
9
  import { ListToolsRequestSchema, CallToolRequestSchema } from "@modelcontextprotocol/sdk/types.js";
10
10
  import { PROTOCOL } from "./protocol.js";
11
11
  import { parseCard, validateCard, riskTier, isSensitive } from "./card.js";
12
- import { loadState, saveState, defaultState, audit, readAudit, getUserMessages, writeUserMessage, pathExists, gitHead, isStale, isBypassed, verifyAuditChain, withStateLock, auditHashMode } from "./state.js";
12
+ import { loadState, saveState, defaultState, audit, readAudit, getUserMessages, writeUserMessage, pathExists, gitHead, isStale, isBypassed, verifyAuditChain, withStateLock, auditHashMode, workspaceFingerprint } from "./state.js";
13
13
  import { buildContractPrompt, snapshotFiles, readManifest, readManifestAll, writeDispatchPrompt, saveAgentResult, runVerifyCommand, runNegativeControl, computeOutputHash, enforceScope, MAX_DISPATCH } from "./dispatch.js";
14
14
 
15
15
  const log = (msg) => {
@@ -69,6 +69,36 @@ const verifyPassed = (state) => {
69
69
  return typeof lv.cmd === "string" && lv.cmd.trim() === want;
70
70
  };
71
71
 
72
+ // 验证状态四态(R4:保持 verify_passed 为 boolean,只**新增**本字段)。
73
+ //
74
+ // not_run —— 没跑过 / 没有对应当前卡片的验证结果
75
+ // fail —— 跑了但没通过
76
+ // stale —— 跑通了,但验证之后代码又变了(指纹不一致)—— 这一态正是 A1 要堵的
77
+ // pass —— 跑通且代码自那以后没动过
78
+ //
79
+ // 指纹不可用时(非 git 目录)按 fail-open 处理:算 pass,但在 fingerprint 字段里
80
+ // 如实标注「不可用」,不装作验证过(A1 R1)。
81
+ const verifyState = (state) => {
82
+ const lv = state && state.last_verify;
83
+ if (!lv || typeof lv !== "object") return { state: "not_run", fingerprint: "unavailable" };
84
+ const want = cardVerifyCmd(state);
85
+ if (!want || typeof lv.cmd !== "string" || lv.cmd.trim() !== want) {
86
+ return { state: "not_run", fingerprint: "unavailable" };
87
+ }
88
+ if (lv.ok !== true) return { state: "fail", fingerprint: "unavailable" };
89
+
90
+ const fpWas = lv.fingerprint;
91
+ if (!fpWas || !fpWas.ok) {
92
+ return { state: "pass", fingerprint: "unavailable" };
93
+ }
94
+ const fpNow = workspaceFingerprint(lv.cwd || process.cwd());
95
+ if (!fpNow.ok) return { state: "pass", fingerprint: "unavailable" };
96
+ if (fpNow.diff_sha256 !== fpWas.diff_sha256) {
97
+ return { state: "stale", fingerprint: fpNow.diff_sha256 };
98
+ }
99
+ return { state: "pass", fingerprint: fpNow.diff_sha256 };
100
+ };
101
+
72
102
  // WARN 汇总条数上限:防止 WARN 通胀把返回值灌成噪音,主 Agent 反而开始忽略。
73
103
  const WARN_FINDINGS_LIMIT = 20;
74
104
 
@@ -715,6 +745,31 @@ const TOOLS = [
715
745
  "请对当前卡片重新执行 flow_run_verify,再记录裁定。");
716
746
  }
717
747
 
748
+ // 防假闭环之五:验证结果必须绑定当时的**代码状态**(A1)。
749
+ //
750
+ // 前面三道判断只看「验证跑过 / 跑通了 / 命令对得上」,**不看代码变没变**。
751
+ // 于是存在这条绕过路径:
752
+ // 1. flow_run_verify 跑通 → last_verify = {ok:true, cmd:"npm test"}
753
+ // 2. executor 继续改代码(甚至改坏)
754
+ // 3. flow_verdict(PASS) → 三道全过 → 放行
755
+ // 指纹把「验证通过」绑定到一次**可复现的运行**:验证之后再动过代码,指纹就变了。
756
+ //
757
+ // 非 git 目录:fail-open(Carlos Flow 支持非 Git 项目),但要在 flow_status
758
+ // 里如实标注指纹不可用(见 R1)。
759
+ const fpCwd = a.cwd || (state.last_verify && state.last_verify.cwd) || process.cwd();
760
+ const fpWas = lv.fingerprint;
761
+ const fpNow = workspaceFingerprint(fpCwd);
762
+ if (fpWas && fpWas.ok && fpNow.ok && fpNow.diff_sha256 !== fpWas.diff_sha256) {
763
+ audit("decision", sessionId, {
764
+ kind: "verdict_denied",
765
+ reason: "验证结果已过期(代码在验证后被修改)",
766
+ fp_was: fpWas.diff_sha256,
767
+ fp_now: fpNow.diff_sha256,
768
+ });
769
+ return fail("验证结果已过期(STALE):验证通过后代码又被修改,当前 diff 指纹已变化。" +
770
+ "请重新执行 flow_run_verify 再记录裁定。");
771
+ }
772
+
718
773
  // 防假闭环之四:越界改动必须被拦住。
719
774
  //
720
775
  // 「越界直接阻断」的**真实落点**在这里:判定「本次执行有没有改到
@@ -888,6 +943,9 @@ const TOOLS = [
888
943
  // verify_passed:真实验证是否通过(last_verify.ok===true 且命令与当前卡片一致)。
889
944
  // 注意 verified 只表示「是否已有裁定」,不代表验证通过——两者语义不同,不可混用。
890
945
  verify_passed: verifyPassed(state),
946
+ // 四态验证状态:not_run / fail / stale / pass。
947
+ // stale = 验证通过后代码被改过 —— 不阻断(fail-open),但必须如实告知。
948
+ verify_state: verifyState(state).state,
891
949
  completed_ok: state.completed_ok === true,
892
950
  stale: isStale(state),
893
951
  bypass: !!state.bypass,
@@ -1218,6 +1276,9 @@ const TOOLS = [
1218
1276
  ok: result.ok,
1219
1277
  // 输出指纹:把「验证通过」绑定到一次可复现的运行,而不是「我说过了」。
1220
1278
  output_hash: computeOutputHash(result.exitCode, result.stdout, result.stderr),
1279
+ // 代码状态指纹:把「验证通过」绑定到**当时的代码状态**。
1280
+ // 没有它,验证通过后再改坏代码,flow_verdict(PASS) 仍会放行(见 A1)。
1281
+ fingerprint: workspaceFingerprint(workdir || process.cwd()),
1221
1282
  };
1222
1283
  saveState(sessionId, state2);
1223
1284
 
@@ -1279,6 +1340,10 @@ const TOOLS = [
1279
1340
  exitCode: r.after.exitCode,
1280
1341
  ok: r.after.ok,
1281
1342
  output_hash: r.after.hash,
1343
+ // 代码状态指纹:负对照同样是一次「验证通过」,
1344
+ // 必须与 flow_run_verify 一样绑定代码状态,
1345
+ // 否则「先负对照、再改代码、再记 PASS」这条路径会绕过 STALE 闸门。
1346
+ fingerprint: workspaceFingerprint(workdir || process.cwd()),
1282
1347
  };
1283
1348
  saveState(sessionId, state2);
1284
1349
 
package/src/state.js CHANGED
@@ -219,14 +219,52 @@ export function defaultState() {
219
219
  }
220
220
 
221
221
  export function loadState(sid) {
222
+ const file = path.join(RUNS_DIR, sanitizeId(sid), "state.json");
223
+
224
+ // 读失败必须区分「真的没有」与「暂时读不到」。
225
+ //
226
+ // 背景(2026-11-13 实测):旧实现把**任何**读/解析失败都当成「状态不存在」,
227
+ // 返回 defaultState()。而 saveState 用的是 tmp+rename,
228
+ // 在 Windows 上 rename 与其他进程的 readFileSync 存在竞争窗口(EBUSY/EPERM),
229
+ // 读失败 → prev 退化成默认值 → activation_activated 丢成 false →
230
+ // 紧接着的写入把「占位卡的 pending=[三项]」覆盖成「普通卡的 pending=[]」
231
+ // → **激活闸门被绕过**。
232
+ // 这正是并发测试「零泄漏」偶发失败的根因(实测 370 轮里漏 1)。
233
+ //
234
+ // 现在:只有「文件不存在」才返回默认值;
235
+ // 瞬时错误先重试;仍失败则**报错**(fail-closed),
236
+ // 绝不静默把一个有闸门的状态当成无闸门的状态。
237
+ let raw = null;
238
+ let lastErr = null;
239
+ for (let attempt = 0; attempt < 5; attempt++) {
240
+ try {
241
+ raw = fs.readFileSync(file, "utf8");
242
+ lastErr = null;
243
+ break;
244
+ } catch (e) {
245
+ if (e.code === "ENOENT") return defaultState(); // 真的没有
246
+ lastErr = e;
247
+ sleepMs(10 * (attempt + 1)); // 瞬时竞争窗口,退避重试
248
+ }
249
+ }
250
+ if (lastErr) {
251
+ throw new Error(
252
+ "读取状态失败(" + (lastErr.code || lastErr.message) + "):" + file +
253
+ "。为避免丢掉门禁状态,本次操作已中止,请稍后重试。",
254
+ );
255
+ }
256
+
257
+ let parsed;
222
258
  try {
223
- const file = path.join(RUNS_DIR, sanitizeId(sid), "state.json");
224
- const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
225
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return defaultState();
226
- return { ...defaultState(), ...migrate(parsed) };
227
- } catch {
228
- return defaultState();
259
+ parsed = JSON.parse(raw);
260
+ } catch (e) {
261
+ throw new Error(
262
+ "状态文件损坏,无法解析:" + file + "(" + e.message + ")。" +
263
+ "为避免丢掉门禁状态,本次操作已中止;如确认可丢弃该会话状态,可删除该文件后重试。",
264
+ );
229
265
  }
266
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return defaultState();
267
+ return { ...defaultState(), ...migrate(parsed) };
230
268
  }
231
269
 
232
270
  export function saveState(sid, state) {
@@ -785,4 +823,77 @@ export function isBypassed(state) {
785
823
  if (!state.bypass_ts) return false;
786
824
  if (state.card_ts && state.bypass_ts < state.card_ts) return false;
787
825
  return true;
826
+ }
827
+
828
+ // ---------------------------------------------------------------------------
829
+ // workspaceFingerprint —— 工作区代码状态指纹
830
+ //
831
+ // 为什么需要(A1):
832
+ // 原来的 PASS 闸门只看 last_verify 的三个字段(存在 / ok===true / cmd 与卡片一致),
833
+ // **不绑定代码状态**。于是存在这条绕过路径:
834
+ // 1. flow_run_verify 跑通 → last_verify = {ok:true, cmd:"npm test"}
835
+ // 2. executor 继续改代码(甚至改坏)
836
+ // 3. flow_verdict(PASS) → 三个条件全满足 → 放行
837
+ // 指纹把「验证通过」绑定到**一次可复现的运行**:验证之后再动过代码,指纹就变了。
838
+ //
839
+ // 指纹构成:HEAD 提交 + `git diff HEAD` 的全文 + 全部未跟踪文件(路径 + 内容)。
840
+ // · 未跟踪文件必须计入:新建文件是最常见的越界/破坏手段。
841
+ // · `.carlos-flow/` 必须排除:跑一次检查会创建状态目录,计入则立即自我失效。
842
+ //
843
+ // 非 git 目录:显式返回 {ok:false, reason:"not_a_git_repo"},**不崩**。
844
+ // Carlos Flow 明确支持非 Git 项目,所以调用方要 fail-open(不阻断 PASS),
845
+ // 但要在 flow_status 里如实标注指纹不可用。
846
+ export function workspaceFingerprint(cwd) {
847
+ const dir = cwd || process.cwd();
848
+ const head = spawnSync("git", ["rev-parse", "HEAD"], { cwd: dir, encoding: "utf8" });
849
+ if (head.error || head.status !== 0) {
850
+ return { ok: false, reason: "not_a_git_repo" };
851
+ }
852
+ const diff = spawnSync("git", ["diff", "HEAD", "--no-color"], { cwd: dir, encoding: "utf8" });
853
+ const untracked = spawnSync("git", ["ls-files", "--others", "--exclude-standard"], {
854
+ cwd: dir,
855
+ encoding: "utf8",
856
+ });
857
+
858
+ const h = createHash("sha256");
859
+ h.update(String(diff.stdout || ""));
860
+
861
+ const files = String(untracked.stdout || "")
862
+ .split("\n")
863
+ .map((s) => s.trim())
864
+ .filter(Boolean)
865
+ .sort();
866
+
867
+ // 状态目录必须排除(R3):跑一次检查就会往里写审计/状态文件,
868
+ // 若计入指纹则「验证 → 落审计 → 记裁定」之间指纹必变 → 每次都误报 STALE。
869
+ //
870
+ // ⚠️ 不能只硬编码 ".carlos-flow/":状态目录由 CARLOS_FLOW_HOME 决定,
871
+ // 用户完全可以把它设在**项目内部**(如 <repo>/.flowhome),那就会自我失效。
872
+ // 所以这里按**解析后的绝对路径**排除真正的 FLOW_HOME,
873
+ // 同时保留 .carlos-flow/ 的字面排除以兼容默认布局。
874
+ const flowHomeAbs = path.resolve(FLOW_HOME);
875
+ for (const f of files) {
876
+ const abs = path.resolve(dir, f);
877
+ const inFlowHome = abs === flowHomeAbs || abs.startsWith(flowHomeAbs + path.sep);
878
+ if (inFlowHome) continue;
879
+ if (f.startsWith(".carlos-flow/") || f.startsWith(".carlos-flow\\")) continue;
880
+ h.update(`\u0000untracked-file:${f}\u0000`);
881
+ try {
882
+ const buf = fs.readFileSync(path.join(dir, f));
883
+ // 大文件只入路径 + 大小,不入内容(避免读上万文件/大文件)
884
+ if (buf.length > 1024 * 1024) {
885
+ h.update(`size:${buf.length}`);
886
+ } else {
887
+ h.update(buf);
888
+ }
889
+ } catch (e) {
890
+ h.update(`<<unreadable: ${e}>>`);
891
+ }
892
+ }
893
+
894
+ return {
895
+ ok: true,
896
+ head: String(head.stdout || "").trim(),
897
+ diff_sha256: h.digest("hex"),
898
+ };
788
899
  }