carlos-flow 2.13.0 → 2.14.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/AGENTS.md CHANGED
@@ -13,6 +13,9 @@
13
13
  | `src/index.js` 的参数校验 | `scripts/check-params.mjs` 的判定口径 | 工具的 `inputSchema` |
14
14
  | `src/state.js` 的状态字段 | `src/state.js` 的 `defaultState()` + `schemaVersion` | 迁移函数 `migrate()` |
15
15
  | `src/state.js` 的审计链 | `docs/AUDIT_REVIEW.md` 的威胁模型 | `test/audit-chain.mjs` |
16
+ | `src/state.js` 的 `withStateLock` | `docs/TOOL_CONTRACTS.md` §4.5(排他/回收/退避口径) | `test/state-lock.mjs`、`test/concurrency-e2e.mjs` |
17
+ | `src/protocol.js` 的敏感名单 | `docs/TOOL_CONTRACTS.md` §4.4(只能追加,不许放宽) | `test/sensitive-config.mjs` |
18
+ | `src/dispatch.js` 的负对照还原 | `docs/TOOL_CONTRACTS.md` 的 `flow_falsify` 关键约束 | `test/falsify-restore.mjs` |
16
19
  | `src/dispatch.js` 的 scope 判定 | `test/scope-enforcement.mjs` 的用例 | `README.md` 的能力矩阵 |
17
20
  | 门禁逻辑(claim / dispatch / verdict) | `test/e2e-carlos.mjs` 的第 15~26 组用例 | 变异体 M1~M6 |
18
21
  | `src/trigger.js` 触发引擎 | `TRIGGER_GUIDE.md` + `test/trigger-e2e.mjs` | 触发器配置模板 |
@@ -41,6 +44,14 @@
41
44
  4. **激活占位卡未补齐时不得派发 / 不得裁定**
42
45
  - `activation_pending` 非空 → `flow_claim` / `flow_dispatch` / `flow_verdict` 全部拒绝。
43
46
 
47
+ 4.1 **敏感规则只许追加(v2.14.0)**
48
+ - `.carlos.json` 的 `sensitive` 只能**加**规则;`!x` / `-x` 否定式必须被忽略。
49
+ - 配置损坏时退回内置基线,不许因为「配置读不到」而放宽。
50
+
51
+ 4.2 **负对照不得让工作区停在改动前(v2.14.0)**
52
+ - 进入临界区前必须写 `journal.json`;`finally` 里还原后必须逐文件核对摘要。
53
+ - 还原失败时**保留备份目录**(下一次调用靠它恢复),不许删了当没事。
54
+
44
55
  5. **审计链的 legacy 记录不得重置链起点**
45
56
  - 旧格式记录(无 hash)只计入 `legacy` 计数,**保持 `prev` 不变**。
46
57
  - 重置会让 v2.5 升级上来的用户审计链长期报红 —— 误报比漏报更伤信任。
@@ -62,6 +73,9 @@ npm run test:all # 主测试套件(smoke + e2e + p0 + trigger + con
62
73
  npm run test:scope # 越界拦截真实验证(真实 git 仓库 + 真实改动)
63
74
  npm run test:audit # 审计链篡改检测验证(HMAC / plain / legacy / date)
64
75
  npm run test:bridge # Bridge 身份隔离(端口上是别人的 bridge 不得复用)
76
+ npm run test:sensitive # 项目级敏感规则:只能追加、否定式无效、坏配置退回基线
77
+ npm run test:lock # 状态锁:退避 / 死锁回收 / fail-closed
78
+ npm run test:falsify # 负对照:还原核对 + 崩溃恢复
65
79
  npm run test:lang # 产物语言体检的自检
66
80
  npm run test:package # 包级端到端(真实 tarball + 干净安装 + 真实 MCP 握手)
67
81
  npm run check:full # 对外产物全面体检
@@ -75,7 +89,7 @@ npm run check:readme # 双语 README 未漂移
75
89
  变异测试(耗时较长,发布前跑):
76
90
 
77
91
  ```bash
78
- npm run test:mutation # 17 类变异体必须 17/17 全部被抓住
92
+ npm run test:mutation # 20 类变异体必须 20/20 全部被抓住
79
93
  ```
80
94
 
81
95
  ---
package/CHANGELOG.md CHANGED
@@ -1,3 +1,20 @@
1
+ ## [2.14.0] - 2026-11-17
2
+ - 项目级敏感路径扩展:仓库根 `.carlos.json` 可追加 `sensitive.names/segments/extensions/prefixes`(只能追加,否定式 `!` `-` 一律忽略;配置损坏自动退回内置基线)
3
+ - 负对照安全性:`flow_falsify` 进入前写还原日志、还原后逐文件核对摘要;被强杀留下的 pending 日志会在下一次调用时先把工作区救回来(返回值如实报告 `restore` / `recovered`)
4
+ - 状态锁:指数退避 + 抖动(固定 15ms 会让多进程同步撞锁),持有者 pid 已死即时回收,超时错误点明持有者 pid
5
+ - 向导模式:占位卡未补齐时直接给出可复制的 `flow_submit_requirement` 补齐骨架(pro 模式行为不变)
6
+ - 裁定闸门注释按 docs/TOOL_CONTRACTS.md 的 9 组对齐(2 无条件 + 7 仅 PASS),修掉「之四/之五各出现两次」的历史错乱
7
+ - bridge:启动时清理 pid 已死的僵尸工牌(只删死进程的),`/health` 增补 `idle_ms` / `idle_for_ms` / `active_sockets`
8
+ - 回归新增:test:sensitive / test:lock / test:falsify 三套真实验证,e2e 第 31 组覆盖占位卡补齐骨架
9
+
10
+ ## [2.13.1] - 2026-11-17
11
+ - 轻量化:bridge 空闲退出(默认 30 分钟,CARLOS_BRIDGE_IDLE_MS 可调,0 关闭)+ 子进程死则 bridge 跟退;实测进程 14→5、私有内存 430→95MB
12
+ - 止住测试污染:测试端口改为向系统申请真空闲端口 + /health 校验 flow_home 身份;实测再跑 e2e+p0 向真实目录新增会话 0 个
13
+ - 降门槛:scope 校验统一到 git 仓库根(与 git diff 同基准),不传 cwd 也不再误报「路径不存在」;显式 cwd 仍作为验证执行目录
14
+ - 报错解释层:pro 模式附「为什么被拦」机制说明,guide 模式只留人话(不叠两层)
15
+ - 运维入口:新增 carlos clean(默认只列不删,只动测试前缀会话,永不删审计链);客户端启动自动回收失效 pid 文件
16
+ - 装机清单修正:flow_mode 工具此前在装机清单中缺失,版本号 2.12.0→2.13.1
17
+
1
18
  ## [2.13.0]
2
19
  - CI 全绿:修复 3 个漂移的变异锚点(M2/M3 claim/verdict 闸门、M15 审计链校验),check:anchors 恢复 17/17
3
20
  - 工具清单对齐:ghost.json 与 src/index.js 统一为 20 个工具(移除空名称残留)
package/README.en.md CHANGED
@@ -224,6 +224,30 @@ One package, six platforms. The init command generates the right config file for
224
224
 
225
225
  ---
226
226
 
227
+ ## 🔧 Per-project configuration (optional)
228
+
229
+ Drop a `.carlos.json` at your repo root to teach the gate about **your own** sensitive
230
+ files (anything beyond the built-in list):
231
+
232
+ ```json
233
+ {
234
+ "sensitive": {
235
+ "names": ["pay_api_key.txt"],
236
+ "segments": ["ledger"],
237
+ "extensions": [".vault"],
238
+ "prefixes": ["billing/ledger/"]
239
+ }
240
+ }
241
+ ```
242
+
243
+ - **Append-only, never relax**: entries starting with `!` or `-` are ignored; the built-in
244
+ list (`.env`, private keys, lock files, `migrations/`, …) always applies.
245
+ - **A broken config cannot loosen the gate**: on parse failure the built-in list is used.
246
+ - The engine walks up from the working directory (max 12 levels) to the nearest `.carlos.json`.
247
+ - Matched paths are treated as sensitive when submitting a task card, so they require `confirmed: true`.
248
+
249
+ ---
250
+
227
251
  ## 📦 Version Consistency Convention (Dev Environment)
228
252
 
229
253
  When you configure Carlos Flow for your AI, there are three conventions worth knowing:
@@ -486,8 +510,9 @@ npm pack
486
510
  | [TRIGGER_GUIDE.md](./TRIGGER_GUIDE.md) | Deep guide to the Smart Trigger Engine (config, scoring, activation, feedback learning) |
487
511
  | [CHANGELOG.md](./CHANGELOG.md) | Version history (Keep a Changelog + SemVer) |
488
512
  | [MIGRATION.md](./MIGRATION.md) | Migrating from `carlos-flow-cindy` / `carlos-flow-opencode` |
489
- | [QA Report](./docs/QA_REPORT_v2.5.5.md) | Third-party read-only audit (13/13 mutants caught) |
490
- | [Mutation Report](./docs/MUTATION_REPORT_v2.5.5.md) | Mutation injection details and results |
513
+ | [Release Notes v2.13.0](./docs/RELEASE_v2.13.0.md) | Latest release status, CI results and regression numbers |
514
+ | [QA Report (historical snapshot)](./docs/QA_REPORT_v2.5.5.md) | Third-party read-only audit, valid for v2.5.5 only |
515
+ | [Mutation Report (historical snapshot)](./docs/MUTATION_REPORT_v2.5.5.md) | Mutation injection details, valid for v2.5.5 only |
491
516
 
492
517
  ---
493
518
 
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # Carlos 工作流 (Carlos-Flow)
2
2
 
3
3
  [![Build Status](https://img.shields.io/badge/build-passing-brightgreen)](https://github.com/skyer-now/carlos-flow)
4
- [![Version](https://img.shields.io/badge/version-2.12.2-blue)](https://www.npmjs.com/package/carlos-flow)
4
+ [![Version](https://img.shields.io/badge/version-2.14.0-blue)](https://www.npmjs.com/package/carlos-flow)
5
5
  [![License](https://img.shields.io/badge/license-MIT-green)](LICENSE)
6
6
 
7
7
  [中文](README.zh.md) | [English Version](README.en.md)
@@ -39,6 +39,28 @@ Carlos 工作流的核心逻辑是“闭环质检”:
39
39
 
40
40
  ---
41
41
 
42
+ ## 🔧 项目级配置(可选)
43
+
44
+ 在仓库根放一个 `.carlos.json`,就能让门禁认识**你项目自己**的敏感文件(内置名单之外的):
45
+
46
+ ```json
47
+ {
48
+ "sensitive": {
49
+ "names": ["pay_api_key.txt"],
50
+ "segments": ["ledger"],
51
+ "extensions": [".vault"],
52
+ "prefixes": ["billing/ledger/"]
53
+ }
54
+ }
55
+ ```
56
+
57
+ - **只能追加,不能放宽**:以 `!` 或 `-` 开头的条目一律被忽略;内置名单(`.env`、私钥、锁文件、`migrations` 目录等)永远生效。
58
+ - **写坏了也不会放宽**:配置解析失败时自动退回内置名单,不会静默放行。
59
+ - 引擎从调用的工作目录向上找最近的 `.carlos.json`(最多 12 层),所以在大仓的子目录里调用也能命中。
60
+ - 命中的路径在提交任务卡时会被判为敏感路径,需要 `confirmed: true` 才能继续。
61
+
62
+ ---
63
+
42
64
  ## ❓ 常见问题 (FAQ)
43
65
 
44
66
  **Q:我用的是 OpenCode / Claude Code,能装吗?**
@@ -88,8 +110,9 @@ git log --oneline origin/main -1
88
110
  | [TRIGGER_GUIDE.md](./TRIGGER_GUIDE.md) | 智能触发引擎深度指南(配置、评分、激活、反馈学习) |
89
111
  | [CHANGELOG.md](./CHANGELOG.md) | 版本历史(遵循 Keep a Changelog + SemVer) |
90
112
  | [MIGRATION.md](./MIGRATION.md) | 从 `carlos-flow-cindy` / `carlos-flow-opencode` 迁移 |
91
- | [QA 报告](./docs/QA_REPORT_v2.5.5.md) | 第三方只读审计(13/13 变异体检测通过) |
92
- | [变异报告](./docs/MUTATION_REPORT_v2.5.5.md) | 变异注入详情与结果 |
113
+ | [发布说明 v2.13.0](./docs/RELEASE_v2.13.0.md) | 最新发布状态、CI 结论与回归数字 |
114
+ | [QA 报告(历史快照)](./docs/QA_REPORT_v2.5.5.md) | 第三方只读审计,仅对 v2.5.5 负责 |
115
+ | [变异报告(历史快照)](./docs/MUTATION_REPORT_v2.5.5.md) | 变异注入详情,仅对 v2.5.5 负责 |
93
116
 
94
117
  ## 🚀 准备好开始了吗?
95
118
  只需几行命令,为你的 AI 加上这层保护罩。
package/README.zh.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # Carlos 工作流 (Carlos-Flow)
2
2
 
3
3
  [![Build Status](https://img.shields.io/badge/build-passing-brightgreen)](https://github.com/skyer-now/carlos-flow)
4
- [![Version](https://img.shields.io/badge/version-2.12.2-blue)](https://www.npmjs.com/package/carlos-flow)
4
+ [![Version](https://img.shields.io/badge/version-2.14.0-blue)](https://www.npmjs.com/package/carlos-flow)
5
5
  [![License](https://img.shields.io/badge/license-MIT-green)](LICENSE)
6
6
 
7
7
  [中文](README.zh.md) | [English Version](README.en.md)
@@ -39,6 +39,28 @@ Carlos 工作流的核心逻辑是“闭环质检”:
39
39
 
40
40
  ---
41
41
 
42
+ ## 🔧 项目级配置(可选)
43
+
44
+ 在仓库根放一个 `.carlos.json`,就能让门禁认识**你项目自己**的敏感文件(内置名单之外的):
45
+
46
+ ```json
47
+ {
48
+ "sensitive": {
49
+ "names": ["pay_api_key.txt"],
50
+ "segments": ["ledger"],
51
+ "extensions": [".vault"],
52
+ "prefixes": ["billing/ledger/"]
53
+ }
54
+ }
55
+ ```
56
+
57
+ - **只能追加,不能放宽**:以 `!` 或 `-` 开头的条目一律被忽略;内置名单(`.env`、私钥、锁文件、`migrations` 目录等)永远生效。
58
+ - **写坏了也不会放宽**:配置解析失败时自动退回内置名单,不会静默放行。
59
+ - 引擎从调用的工作目录向上找最近的 `.carlos.json`(最多 12 层),所以在大仓的子目录里调用也能命中。
60
+ - 命中的路径在提交任务卡时会被判为敏感路径,需要 `confirmed: true` 才能继续。
61
+
62
+ ---
63
+
42
64
  ## ❓ 常见问题 (FAQ)
43
65
 
44
66
  **Q:我用的是 OpenCode / Claude Code,能装吗?**
@@ -88,8 +110,9 @@ git log --oneline origin/main -1
88
110
  | [TRIGGER_GUIDE.md](./TRIGGER_GUIDE.md) | 智能触发引擎深度指南(配置、评分、激活、反馈学习) |
89
111
  | [CHANGELOG.md](./CHANGELOG.md) | 版本历史(遵循 Keep a Changelog + SemVer) |
90
112
  | [MIGRATION.md](./MIGRATION.md) | 从 `carlos-flow-cindy` / `carlos-flow-opencode` 迁移 |
91
- | [QA 报告](./docs/QA_REPORT_v2.5.5.md) | 第三方只读审计(13/13 变异体检测通过) |
92
- | [变异报告](./docs/MUTATION_REPORT_v2.5.5.md) | 变异注入详情与结果 |
113
+ | [发布说明 v2.13.0](./docs/RELEASE_v2.13.0.md) | 最新发布状态、CI 结论与回归数字 |
114
+ | [QA 报告(历史快照)](./docs/QA_REPORT_v2.5.5.md) | 第三方只读审计,仅对 v2.5.5 负责 |
115
+ | [变异报告(历史快照)](./docs/MUTATION_REPORT_v2.5.5.md) | 变异注入详情,仅对 v2.5.5 负责 |
93
116
 
94
117
  ## 🚀 准备好开始了吗?
95
118
  只需几行命令,为你的 AI 加上这层保护罩。
package/TRIGGER_GUIDE.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Carlos Flow 智能触发引擎使用指南
2
2
 
3
- > **版本**: v2.13.0
3
+ > **版本**: v2.14.0
4
4
  > **适用**:`carlos-flow` 单包架构(2.6.0+)
5
5
  > **代码位置**:`src/trigger.js`(零外部依赖的纯 JavaScript 实现)
6
6
 
@@ -766,7 +766,7 @@ node client/carlos.js flow_status '{"sessionId":"my-task"}'
766
766
  ## 📚 相关资源
767
767
 
768
768
  - [测试脚本](test/trigger-e2e.mjs) - E2E 测试套件(29 项,含 10 项回归用例)
769
- - [变异测试](scripts/mutation-check.mjs) - 注入退化验证测试套件真的能抓住(13 类变异)
769
+ - [变异测试](scripts/mutation-check.mjs) - 注入退化验证测试套件真的能抓住(20 类变异)
770
770
  - [核心代码](src/trigger.js) - 触发引擎实现
771
771
  - [集成示例](client/carlos.js) - 客户端集成代码
772
772
  - [完整 README](./README.md) - 项目总览与能力矩阵
@@ -779,5 +779,5 @@ MIT License
779
779
 
780
780
  ---
781
781
 
782
- **版本**: v2.13.0
782
+ **版本**: v2.14.0
783
783
  **更新日期**: 2026-11-12
@@ -6,6 +6,7 @@
6
6
  import { spawn } from "node:child_process";
7
7
  import { createServer } from "node:net";
8
8
  import { createHash } from "node:crypto";
9
+ import { readFileSync, readdirSync, unlinkSync } from "node:fs";
9
10
  import { fileURLToPath } from "node:url";
10
11
  import path from "node:path";
11
12
 
@@ -29,6 +30,57 @@ const RATE_LIMIT = 10; // 每秒最多请求数
29
30
  // 现在默认 180s(> 服务端 120s 上限),可用 CARLOS_BRIDGE_TIMEOUT_MS 覆盖。
30
31
  const REQUEST_TIMEOUT = Number(process.env.CARLOS_BRIDGE_TIMEOUT_MS) || 180000; // 180s
31
32
 
33
+ // ---- 空闲退出(idle reaper)----
34
+ //
35
+ // 为什么必须有:ghost.json 一直声明着 `"idleTimeoutSeconds": 300` 与
36
+ // `"lifecycle": "on-demand"`,但本文件从来没有任何空闲退出实现。
37
+ // 结果实测(2026-11-17):机器上常驻 14 个进程、私有内存 430MB,
38
+ // 仓库里还堆着 40 个 bridge-*.pid(36 个指向已死进程)。
39
+ //
40
+ // 代价很低:实测 bridge 从启动到 /health 就绪只要 118ms(server 155ms),
41
+ // 所以「用的时候起、闲了就退」几乎无感。默认 30 分钟(不是 5 分钟),
42
+ // 避免短暂休息就触发冷启动。
43
+ // CARLOS_BRIDGE_IDLE_MS=0 可关闭本机制(常驻场景)。
44
+ const IDLE_MS = (() => {
45
+ const raw = process.env.CARLOS_BRIDGE_IDLE_MS;
46
+ if (raw === undefined || raw === "") return 30 * 60 * 1000;
47
+ const n = Number(raw);
48
+ if (!Number.isFinite(n) || n < 0) return 30 * 60 * 1000;
49
+ return n;
50
+ })();
51
+ let lastActivity = Date.now();
52
+ let activeSockets = 0;
53
+ const touch = () => { lastActivity = Date.now(); };
54
+
55
+ // ---- 启动时清理僵尸工牌 ----
56
+ //
57
+ // 背景(2026-11-17 实测):仓库根堆了 40 个 bridge-*.pid,其中 36 个指向已不存在的进程。
58
+ // 这些文件没有任何用处,却会让人「以为 bridge 还在跑」,也让排查端口占用时判断失真。
59
+ // 只删 **pid 已死** 的工牌:活着的一律不动(pid 可能被别的进程复用,误删会掩盖真实占用)。
60
+ function sweepStalePidFiles() {
61
+ let names = [];
62
+ try { names = readdirSync(MCP_ROOT); } catch { return { removed: 0, kept: 0 }; }
63
+ let removed = 0;
64
+ let kept = 0;
65
+ for (const name of names) {
66
+ if (!/^bridge-\d+\.pid$/.test(name)) continue;
67
+ const file = path.join(MCP_ROOT, name);
68
+ let pid = 0;
69
+ try { pid = parseInt(readFileSync(file, "utf8").trim(), 10); } catch { continue; }
70
+ if (!Number.isInteger(pid) || pid <= 0 || pid === process.pid) { kept++; continue; }
71
+ let alive = true;
72
+ try {
73
+ process.kill(pid, 0);
74
+ } catch (e) {
75
+ // ESRCH = 进程不存在;EPERM = 存在但无权发信号 → 按活着处理
76
+ if (e && e.code === "ESRCH") alive = false;
77
+ }
78
+ if (alive) { kept++; continue; }
79
+ try { unlinkSync(file); removed++; } catch { /* 被别的进程删了 */ }
80
+ }
81
+ return { removed, kept };
82
+ }
83
+
32
84
  if (!TOKEN) {
33
85
  process.stderr.write("[bridge] ❌ CARLOS_BRIDGE_TOKEN 未设置(fail-closed)\n");
34
86
  process.exit(1);
@@ -87,6 +139,10 @@ child.on("exit", (code) => {
87
139
  try { c.socket.end(); } catch {}
88
140
  }
89
141
  pendingClients.clear();
142
+ // 子进程没了,这个 bridge 已经没用了:必须跟着退出。
143
+ // 否则会留下「端口活着、服务死了」的僵尸 —— 调用方连得上却永远等不到回包,
144
+ // 只能等到 180s 超时(比进程根本不存要难查得多)。
145
+ shutdown(code === 0 ? 0 : 1);
90
146
  });
91
147
 
92
148
  // 速率限制(per-connection sliding window)
@@ -108,7 +164,13 @@ const server = createServer((socket) => {
108
164
  let buf = "";
109
165
  let size = 0;
110
166
 
167
+ // 活跃连接计数:只要还有连接就不算空闲(客户端可能正在等长调用)
168
+ activeSockets++;
169
+ touch();
170
+ socket.on("close", () => { activeSockets = Math.max(0, activeSockets - 1); touch(); });
171
+
111
172
  socket.on("data", (data) => {
173
+ touch();
112
174
  size += data.length;
113
175
  if (size > MAX_REQUEST_SIZE) {
114
176
  socket.write(JSON.stringify({ error: "413 Payload Too Large" }) + "\n");
@@ -144,6 +206,11 @@ const server = createServer((socket) => {
144
206
  flow_home: process.env.CARLOS_FLOW_HOME || "",
145
207
  pid: process.pid,
146
208
  port: PORT,
209
+ // 空闲策略可观测:排查「为什么它退了 / 为什么它不退」时不用猜配置。
210
+ // 恒为附加字段,客户端只比对 root / flow_home,不受影响。
211
+ idle_ms: IDLE_MS,
212
+ idle_for_ms: Date.now() - lastActivity,
213
+ active_sockets: activeSockets,
147
214
  };
148
215
  socket.write(JSON.stringify(health) + "\n");
149
216
  continue;
@@ -193,12 +260,45 @@ server.on("error", (e) => {
193
260
 
194
261
  server.listen(PORT, "127.0.0.1", () => {
195
262
  process.stderr.write(`[bridge] Carlos MCP Bridge listening on 127.0.0.1:${PORT}\n`);
263
+ const swept = sweepStalePidFiles();
264
+ if (swept.removed > 0) {
265
+ process.stderr.write(`[bridge] 已清理 ${swept.removed} 个僵尸 pid 工牌(保留 ${swept.kept} 个活进程的)\n`);
266
+ }
196
267
  });
197
268
 
269
+ let shuttingDown = false;
270
+ function shutdown(code) {
271
+ if (shuttingDown) return;
272
+ shuttingDown = true;
273
+ // 自己把自己的工牌拆下来 —— 否则仓库里会继续堆死 pid 文件
274
+ // (实测 40 个,其中 36 个指向已不存在的进程)。
275
+ // 只删「内容是本进程 pid」的那个,避免两个桥互删工牌。
276
+ try {
277
+ const pidFile = path.join(MCP_ROOT, `bridge-${PORT}.pid`);
278
+ if (parseInt(readFileSync(pidFile, "utf8").trim(), 10) === process.pid) {
279
+ unlinkSync(pidFile);
280
+ }
281
+ } catch { /* 文件不存在 / 已属于别人:忽略 */ }
282
+ try { child.stdin.end(); } catch {}
283
+ try { child.kill("SIGTERM"); } catch {}
284
+ try { server.close(); } catch {}
285
+ setTimeout(() => process.exit(code), 150).unref?.();
286
+ }
287
+
288
+ // 空闲巡检:只有「无活跃连接 + 无待回包请求」才算真空闲
289
+ if (IDLE_MS > 0) {
290
+ const tickMs = Math.min(15000, Math.max(500, Math.floor(IDLE_MS / 4)));
291
+ const timer = setInterval(() => {
292
+ if (activeSockets > 0 || pendingClients.size > 0) { touch(); return; }
293
+ const idleFor = Date.now() - lastActivity;
294
+ if (idleFor < IDLE_MS) return;
295
+ process.stderr.write(`[bridge] 已空闲 ${Math.round(idleFor / 1000)}s,按空闲策略退出(CARLOS_BRIDGE_IDLE_MS=${IDLE_MS})\n`);
296
+ shutdown(0);
297
+ }, tickMs);
298
+ // 定时器本身不能让进程活着(否则空闲退出永远等不到)
299
+ timer.unref?.();
300
+ }
301
+
198
302
  // 优雅退出
199
- process.on("SIGTERM", () => {
200
- child.stdin.end();
201
- child.kill("SIGTERM");
202
- server.close();
203
- process.exit(0);
204
- });
303
+ process.on("SIGTERM", () => shutdown(0));
304
+ process.on("SIGINT", () => shutdown(0));
package/client/carlos.js CHANGED
@@ -6,7 +6,7 @@
6
6
 
7
7
  import { createConnection, createServer } from "node:net";
8
8
  import { spawn } from "node:child_process";
9
- import { existsSync, readFileSync, writeFileSync, unlinkSync, mkdirSync } from "node:fs";
9
+ import { existsSync, readFileSync, writeFileSync, unlinkSync, mkdirSync, readdirSync, statSync, rmSync } from "node:fs";
10
10
  import { randomBytes } from "node:crypto";
11
11
  import { resolve, join, dirname } from "node:path";
12
12
  import { fileURLToPath, pathToFileURL } from "node:url";
@@ -85,6 +85,95 @@ try {
85
85
  const toolName = process.argv[2];
86
86
  const argsJson = process.argv[3] || "{}";
87
87
 
88
+ // 测试会自动生成大量会话。这些前缀是「机器造的」,与真实使用可可靠区分,
89
+ // clean 命令默认只动它们。
90
+ const TEST_SESSION_PREFIXES = ["e2e-", "p0-", "probe-", "guide-", "test-", "smoke-", "unknown"];
91
+
92
+ function dirSize(p) {
93
+ let total = 0;
94
+ const walk = (d) => {
95
+ let ents = [];
96
+ try { ents = readdirSync(d, { withFileTypes: true }); } catch { return; }
97
+ for (const e of ents) {
98
+ const full = join(d, e.name);
99
+ if (e.isDirectory()) walk(full);
100
+ else { try { total += statSync(full).size; } catch {} }
101
+ }
102
+ };
103
+ walk(p);
104
+ return total;
105
+ }
106
+
107
+ /**
108
+ * 清理测试残留会话(gate-state/runs/<sid>)。
109
+ *
110
+ * 绝不删除 gate-audit:审计是逐日哈希链,删一天就断链,
111
+ * 「谁在什么时候批了什么」就永久查不回来了 —— 这不是磁盘占用问题,是可信度问题。
112
+ */
113
+ function runClean(opts) {
114
+ const runsDir = join(process.env.CARLOS_FLOW_HOME || DEFAULT_FLOW_HOME, "gate-state", "runs");
115
+ if (!existsSync(runsDir)) {
116
+ console.log("没有需要清理的会话目录(" + runsDir + " 不存在)");
117
+ return { ok: true };
118
+ }
119
+ const now = Date.now();
120
+ const cutoff = opts.olderThanDays > 0 ? now - opts.olderThanDays * 86400_000 : 0;
121
+ const isTest = (name) => (opts.prefixes ? opts.prefixes.some((p) => name === p || name.startsWith(p)) : true);
122
+
123
+ let names = [];
124
+ try {
125
+ names = readdirSync(runsDir, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name);
126
+ } catch (e) {
127
+ console.error("读取会话目录失败:" + e.message);
128
+ return { ok: false };
129
+ }
130
+
131
+ const targets = [];
132
+ const kept = [];
133
+ for (const n of names) {
134
+ const full = join(runsDir, n);
135
+ let mtimeMs = 0;
136
+ try { mtimeMs = statSync(full).mtimeMs; } catch {}
137
+ const oldEnough = !cutoff || mtimeMs < cutoff;
138
+ if (isTest(n) && oldEnough) targets.push({ name: n, full, size: dirSize(full) });
139
+ else kept.push(n);
140
+ }
141
+
142
+ const totalBytes = targets.reduce((s, t) => s + t.size, 0);
143
+ const mb = (n) => (n / 1048576).toFixed(1) + " MB";
144
+
145
+ console.log("════ 会话清理" + (opts.apply ? "(执行模式)" : "(预览模式,不会删任何东西)") + " ════");
146
+ console.log(" 会话目录: " + runsDir);
147
+ console.log(" 总会话数: " + names.length);
148
+ console.log(" 待清理 : " + targets.length + " 个测试残留,共 " + mb(totalBytes));
149
+ console.log(" 保留 : " + kept.length + " 个(真实会话 + 不匹配前缀的)");
150
+ if (targets.length > 0) {
151
+ const sample = targets.slice(0, 5).map((t) => t.name).join(", ");
152
+ console.log(" 样例 : " + sample + (targets.length > 5 ? " …" : ""));
153
+ }
154
+ console.log(" 注意 : 审计流水(gate-audit)永远不会被删 —— 它是哈希链,断一天就查不回去了");
155
+
156
+ if (!opts.apply) {
157
+ console.log("\n确认无误后加 --apply 真正执行:");
158
+ console.log(" node carlos.js clean --apply");
159
+ console.log("只清更早的: node carlos.js clean --apply --older-than 7");
160
+ return { ok: true };
161
+ }
162
+
163
+ let removed = 0, reclaimed = 0, failed = 0;
164
+ for (const t of targets) {
165
+ try {
166
+ rmSync(t.full, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 });
167
+ removed++; reclaimed += t.size;
168
+ } catch {
169
+ failed++;
170
+ }
171
+ }
172
+ console.log("\n✅ 已删除 " + removed + " 个会话,释放 " + mb(reclaimed) + (failed ? ";失败 " + failed + " 个(可能被占用)" : ""));
173
+ if (failed) console.log(" 补充:关闭占用这些目录的进程后重跑即可。");
174
+ return { ok: failed === 0 };
175
+ }
176
+
88
177
  // ===== init 命令:一键生成宿主配置 =====
89
178
  if (toolName === "init") {
90
179
  const target = process.argv.includes("--target")
@@ -100,10 +189,38 @@ if (toolName === "init") {
100
189
  process.exit(0);
101
190
  }
102
191
 
192
+ if (toolName === "clean") {
193
+ // 清理命令(不需要 bridge / MCP):轻量化的运维入口。
194
+ //
195
+ // 背景(2026-11-17 实测):840 个会话目录里 587 个是测试残留,18MB。
196
+ // 以前没有任何清理手段,只能人工进目录删。
197
+ //
198
+ // 安全口径:
199
+ // · 默认**只列不删**(dry-run),必须显式 --apply 才真的删
200
+ // · 默认只动**测试前缀**的会话(e2e-/p0-/probe-/guide-/test-/smoke-),
201
+ // 真实会话(root-/maint-/audit-/用户自起名)一律不碰
202
+ // · **绝不删除 gate-audit**:审计是哈希链,删一天就断链,追溯能力就没了
203
+ const opts = { apply: false, prefixes: TEST_SESSION_PREFIXES, olderThanDays: 0 };
204
+ for (let i = 3; i < process.argv.length; i++) {
205
+ const a = process.argv[i];
206
+ if (a === "--apply") opts.apply = true;
207
+ else if (a === "--all") opts.prefixes = null; // 危险:连真实会话一起列(仍默认不删)
208
+ else if (a === "--older-than") opts.olderThanDays = Number(process.argv[++i]) || 0;
209
+ else if (a === "--prefix") opts.prefixes = [String(process.argv[++i] || "").trim()].filter(Boolean);
210
+ }
211
+ const r = runClean(opts);
212
+ process.exit(r.ok ? 0 : 1);
213
+ }
214
+
103
215
  if (!toolName) {
104
- console.error("用法: node carlos.js <tool_name> [json_args]");
216
+ console.error("用法: node carlos.js <工具名> [json参数]");
217
+ console.error(" node carlos.js clean [--apply] [--older-than 7] 清理测试残留会话(默认只列不删)");
105
218
  console.error(" node carlos.js init --target cindy|opencode|cursor|cline|vscode|claude");
106
- console.error("工具: flow_protocol flow_submit_requirement flow_claim flow_dispatch flow_run_verify flow_check_scope flow_verdict flow_status flow_audit flow_diff_hunks flow_bypass flow_add_user_msg flow_save_result flow_revert_plan");
219
+ console.error("");
220
+ console.error("最常用的三个工具(其余见 flow_protocol):");
221
+ console.error(" flow_status 看当前进度:有没有任务卡、走到哪一步、下一步该做什么");
222
+ console.error(" flow_trigger_check 判断这句话该不该启动工作流(智能激活)");
223
+ console.error(" flow_bypass 临时跳过审查(需 confirmed:true)");
107
224
  process.exit(1);
108
225
  }
109
226
 
@@ -522,7 +639,44 @@ async function runInit(target) {
522
639
  console.log(` 提示: 设置环境变量 CARLOS_FLOW_HOME 可自定义状态目录(默认 ~/.carlos-flow)`);
523
640
  }
524
641
 
642
+ // 清理「指向已死进程」的 bridge-*.pid。
643
+ //
644
+ // 背景:bridge 以前从不退出,pid 文件也没人回收,实测仓库根里积了 40 个,
645
+ // 36 个指向早已不存在的进程。那些文件除了干扰人工排查,还会让新启动的
646
+ // 客户端误以为「某个端口上有 bridge」。
647
+ // 只删**确认已死**的,活着的一个不动。返回删掉的个数。
648
+ function sweepStalePidFiles() {
649
+ try {
650
+ const names = readdirSync(ROOT_ABS).filter((f) => /^bridge-\d+\.pid$/.test(f));
651
+ let removed = 0;
652
+ for (const n of names) {
653
+ const full = join(ROOT_ABS, n);
654
+ let pid = 0;
655
+ try { pid = parseInt(readFileSync(full, "utf8").trim(), 10); } catch { continue; }
656
+ if (!pid) {
657
+ // 内容坏了:直接删,它已经提供不了任何信息
658
+ try { unlinkSync(full); removed++; } catch {}
659
+ continue;
660
+ }
661
+ if (pid === process.pid) continue;
662
+ let alive = true;
663
+ try { process.kill(pid, 0); } catch { alive = false; }
664
+ if (!alive) {
665
+ try { unlinkSync(full); removed++; } catch {}
666
+ }
667
+ }
668
+ if (removed > 0) process.stderr.write(`[carlos] 已清理 ${removed} 个失效的 bridge pid 文件\n`);
669
+ return removed;
670
+ } catch {
671
+ return 0;
672
+ }
673
+ }
674
+
525
675
  async function main() {
676
+ // 启动前先扫一遍死工牌:bridge 现在会空闲自退,历史遗留的 pid 文件
677
+ // 必须自动回收,不能越积越多。
678
+ sweepStalePidFiles();
679
+
526
680
  // 确保 bridge 运行(带重试)
527
681
  let lastErr = null;
528
682
  for (let attempt = 0; attempt < 3; attempt++) {
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.13.0",
8
+ "version": "2.14.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.13.0",
3
+ "version": "2.14.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",
@@ -24,7 +24,7 @@
24
24
  "test:concurrency": "node test/concurrency-e2e.mjs",
25
25
  "test:ui": "node test/verify-ui.mjs",
26
26
  "test:acceptance": "node test/e2e-acceptance.mjs",
27
- "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 && npm run test:ui",
27
+ "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 && npm run test:clean && npm run test:ui && npm run test:sensitive && npm run test:lock && npm run test:falsify",
28
28
  "test:mutation": "node scripts/mutation-check.mjs",
29
29
  "sync:readme": "node scripts/sync-readme.mjs",
30
30
  "check:readme": "node scripts/sync-readme.mjs --check",
@@ -50,14 +50,18 @@
50
50
  "check:no-dead-handler": "node scripts/check-no-dead-handler.mjs",
51
51
  "test:scope": "node test/scope-enforcement.mjs",
52
52
  "test:audit": "node test/audit-chain.mjs",
53
- "test:bridge": "node test/bridge-identity.mjs",
53
+ "test:bridge": "node test/bridge-identity.mjs && node test/bridge-idle.mjs",
54
54
  "sync:version": "node scripts/sync-version.mjs",
55
55
  "check:version": "node scripts/check-repo-parity.mjs",
56
56
  "test:gate": "node test/publish-gate.test.mjs",
57
57
  "install:hooks": "node scripts/install-hooks.mjs",
58
58
  "check:hooks": "node scripts/install-hooks.mjs --check",
59
59
  "test:stale": "node test/verify-stale.test.mjs",
60
- "check:templates": "node scripts/check-templates.mjs"
60
+ "test:sensitive": "node test/sensitive-config.mjs",
61
+ "test:lock": "node test/state-lock.mjs",
62
+ "test:falsify": "node test/falsify-restore.mjs",
63
+ "check:templates": "node scripts/check-templates.mjs",
64
+ "test:clean": "node test/clean-command.mjs"
61
65
  },
62
66
  "keywords": [
63
67
  "carlos",
@@ -15,7 +15,7 @@ const PURE_DOC_TOOLS = new Set(["flow_protocol"]);
15
15
 
16
16
  // 真实副作用词表(含本项目实际使用的封装函数与 fs 操作)
17
17
  const REAL_WORK =
18
- /\b(await|async|loadState|saveState|readManifest|saveAgentResult|buildRevertPlan|revertPlan|audit|spawn|spawnSync|execFileSync|execSync|readFileSync|writeFileSync|appendFileSync|mkdirSync|unlinkSync|rmSync|renameSync|copyFileSync|withStateLock|gitHead|verifyAuditChain|computeFingerprint|checkScope|enforceScope|parseCard|validateCard|sanitizeSid)\b/;
18
+ /\b(await|async|loadState|saveState|writeUserMessage|getUserMessages|readManifest|saveAgentResult|buildRevertPlan|revertPlan|audit|spawn|spawnSync|execFileSync|execSync|readFileSync|writeFileSync|appendFileSync|mkdirSync|unlinkSync|rmSync|renameSync|copyFileSync|withStateLock|gitHead|verifyAuditChain|computeFingerprint|checkScope|enforceScope|parseCard|validateCard|sanitizeSid)\b/;
19
19
 
20
20
  // 常量返回特征:整段函数体只有一个 return ok({...}) / return {...},无任何其它语句
21
21
  function isConstantReturn(body) {
@@ -59,7 +59,9 @@ const walk = (dir, depth = 0) => {
59
59
  let entries = [];
60
60
  try { entries = readdirSync(dir); } catch { return; }
61
61
  for (const e of entries) {
62
- if (e === "node_modules" || e === ".git" || e === "docs") continue;
62
+ // .mutation-report.md 是 mutation-check 跑完写的**生成产物**(已 gitignore),
63
+ // 它的表头本来就会讲「旧包名」这件事 —— 扫进来只会产生假红。
64
+ if (e === "node_modules" || e === ".git" || e === "docs" || e === ".mutation-report.md") continue;
63
65
  const full = join(dir, e);
64
66
  let st;
65
67
  try { st = statSync(full); } catch { continue; }