carlos-flow 2.6.3 → 2.7.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/client/carlos.js CHANGED
@@ -7,6 +7,7 @@
7
7
  import { createConnection, createServer } from "node:net";
8
8
  import { spawn } from "node:child_process";
9
9
  import { existsSync, readFileSync, writeFileSync, unlinkSync, mkdirSync } from "node:fs";
10
+ import { randomBytes } from "node:crypto";
10
11
  import { resolve, join, dirname } from "node:path";
11
12
  import { fileURLToPath, pathToFileURL } from "node:url";
12
13
  import os from "node:os";
@@ -27,7 +28,49 @@ const BRIDGE_SCRIPT = [
27
28
  const MCP_SERVER = ROOT_ABS + "/src/index.js";
28
29
  // PID 文件按端口区分:多 Bridge 并存(测试用独立端口)时不会互相覆盖
29
30
  const PID_FILE = ROOT_ABS + "/bridge-" + BRIDGE_PORT + ".pid";
30
- const BRIDGE_TOKEN = process.env.CARLOS_BRIDGE_TOKEN || "carlos-local-token-2026";
31
+ // 实际使用的 bridge 端口:pickBridgePort 选定后写入,后续 callMCP 一律用它。
32
+ // 早先 callMCP 写死 BRIDGE_PORT,而 bridge 可能起在别的端口 → 连不上。
33
+ let ACTIVE_PORT = BRIDGE_PORT;
34
+ const BRIDGE_TOKEN_FILE = () => join(DEFAULT_FLOW_HOME, "bridge-token");
35
+
36
+ // 读取或生成 Bridge token。
37
+ //
38
+ // 早先这里是 `process.env.CARLOS_BRIDGE_TOKEN || "carlos-local-token-2026"` ——
39
+ // 一个**硬编码的默认值**。任何本机进程都知道这个字符串,都能连上本机 bridge
40
+ // (虽然只监听 127.0.0.1,但「本机任意进程可连」本身就是一道没关的门),
41
+ // 而且它与 bridge 侧的 fail-closed 行为不一致(bridge 没设环境变量就拒绕)。
42
+ //
43
+ // 现在:
44
+ // 1) 优先用环境变量 CARLOS_BRIDGE_TOKEN;
45
+ // 2) 没有则首次运行生成随机 token 落到 $CARLOS_FLOW_HOME/bridge-token(0600),
46
+ // 之后跨进程复用同一个(client 与 bridge 必须用同一把钥匙);
47
+ // 3) 文件权限设 0600(POSIX);Windows 上靠 ACL 默认保护。
48
+ //
49
+ // 这样既没有硬编码默认值,也不需要用户手工配置环境变量。
50
+ function resolveBridgeToken() {
51
+ const fromEnv = process.env.CARLOS_BRIDGE_TOKEN;
52
+ if (fromEnv && String(fromEnv).trim()) return String(fromEnv).trim();
53
+
54
+ const file = BRIDGE_TOKEN_FILE();
55
+ try {
56
+ if (existsSync(file)) {
57
+ const t = readFileSync(file, "utf8").trim();
58
+ if (t.length >= 32) return t;
59
+ }
60
+ } catch { /* 读不到 → 重新生成 */ }
61
+
62
+ const token = randomBytes(32).toString("hex");
63
+ try {
64
+ mkdirSync(dirname(file), { recursive: true });
65
+ writeFileSync(file, token + "\n", { encoding: "utf8", mode: 0o600 });
66
+ } catch {
67
+ // 落盘失败(只读 HOME 等)→ 退化为进程级临时 token:
68
+ // 本进程内 client 与 bridge 仍然一致,只是重启后失效。
69
+ }
70
+ return token;
71
+ }
72
+
73
+ const BRIDGE_TOKEN = resolveBridgeToken();
31
74
 
32
75
  // 智能触发引擎(本文件是 ESM,必须用动态 import;require 在 ESM 中不存在)
33
76
  // 加载失败时降级为「不触发」,不影响主流程
@@ -154,8 +197,27 @@ async function checkTrigger(message = '') {
154
197
  }
155
198
  }
156
199
 
200
+ // 路径归一化比较:判断两个路径是否指向同一个目录。
201
+ // 为什么要归一化:同一个目录在不同环境下可能是 POSIX 形式(Git Bash 的 /tmp/x)、
202
+ // Windows 形式、带不带尾斜杠、大小写差异 —— 直接字符串比较会把
203
+ // 「同一个目录」判成「不同身份」,于是永远不复用、每次都另起一个 bridge。
204
+ function samePath(a, b) {
205
+ if (!a || !b) return true; // 对方没报 → 不以此为拒理由
206
+ const norm = (p) => {
207
+ try {
208
+ let s = resolve(String(p));
209
+ // 去掉尾分隔符(根目录除外)
210
+ if (s.length > 1) s = s.replace(/[\\/]+$/, "");
211
+ return process.platform === "win32" ? s.toLowerCase() : s;
212
+ } catch {
213
+ return String(p);
214
+ }
215
+ };
216
+ return norm(a) === norm(b);
217
+ }
218
+
157
219
  // 检查 bridge 是否已在运行(先读 PID,再 TCP 探测)
158
- function isBridgeRunning() {
220
+ function isBridgeRunning(port = BRIDGE_PORT) {
159
221
  return new Promise((resolve) => {
160
222
  // 先检查 PID 文件
161
223
  if (existsSync(PID_FILE)) {
@@ -172,7 +234,7 @@ function isBridgeRunning() {
172
234
  }
173
235
 
174
236
  // TCP 探测
175
- const s = createConnection(BRIDGE_PORT, "127.0.0.1");
237
+ const s = createConnection(port, "127.0.0.1");
176
238
  s.on("connect", () => {
177
239
  // 发送健康检查
178
240
  s.write("GET /health\n");
@@ -181,7 +243,31 @@ function isBridgeRunning() {
181
243
  const resp = data.toString().trim();
182
244
  try {
183
245
  const json = JSON.parse(resp);
184
- if (json.status === "ok") { s.end(); resolve(true); return; }
246
+ if (json.status !== "ok") { s.end(); resolve(false); return; }
247
+ // ⚠️ 身份校验:端口上跑的 bridge 必须是**我这份代码 + 我这个 HOME**。
248
+ //
249
+ // 早先只判 status==ok 就复用 —— 于是端口上是**另一个 ROOT** 的 bridge 时
250
+ // (比如开发机上的旧仓库那份),本进程会静默连过去:
251
+ // · 它启动时的 CARLOS_FLOW_HOME 生效 → 本次传入的 HOME 完全失效,
252
+ // 状态/审计写到**别人的目录**(测试污染生产状态的真凶);
253
+ // · 协议/版本可能不匹配 → 调用挂死。
254
+ // 现在比对 root 与 flow_home,不符就当“未运行”,另起一个自己的 bridge。
255
+ //
256
+ // 路径必须**归一化**后再比:同一个目录在不同环境下可能是
257
+ // POSIX 形式(Git Bash:/tmp/x)、Windows 形式(D:\\x)、带不带尾斜杠、
258
+ // 大小写差异 —— 直接字符串比较会把「同一个目录」判成「不同身份」,
259
+ // 于是永远不复用、每次都另起一个 bridge。
260
+ const sameRoot = samePath(json.root, ROOT_ABS);
261
+ const wantHome = process.env.CARLOS_FLOW_HOME || DEFAULT_FLOW_HOME;
262
+ const sameHome = samePath(json.flow_home, wantHome);
263
+ if (!sameRoot || !sameHome) {
264
+ s.end();
265
+ resolve(false);
266
+ return;
267
+ }
268
+ s.end();
269
+ resolve(true);
270
+ return;
185
271
  } catch {}
186
272
  s.end();
187
273
  // 健康检查失败但端口存活,也算运行中
@@ -192,10 +278,32 @@ function isBridgeRunning() {
192
278
  });
193
279
  }
194
280
 
281
+ // 找一个能用的端口。
282
+ //
283
+ // 首选 BRIDGE_PORT;若该端口已被**另一个身份的 bridge** 占用,
284
+ // 则向上探测若干个端口另起一个 —— 不能硬挤同一端口:
285
+ // 挤不进去时 spawn 会失败或挂死(实测客户端因此超时挂死 30s)。
286
+ async function pickBridgePort() {
287
+ for (let i = 0; i < 20; i++) {
288
+ const port = BRIDGE_PORT + i;
289
+ // 端口空闲 → 直接用
290
+ const busy = await new Promise((res) => {
291
+ const s = createConnection(port, "127.0.0.1");
292
+ s.on("connect", () => { s.end(); res(true); });
293
+ s.on("error", () => res(false));
294
+ setTimeout(() => { s.destroy(); res(false); }, 800);
295
+ });
296
+ if (!busy) return port;
297
+ // 端口被占 → 若是**同身份**的 bridge,直接复用
298
+ if (await isBridgeRunning(port)) return port;
299
+ }
300
+ return BRIDGE_PORT;
301
+ }
302
+
195
303
  // 自动启动 bridge(后台常驻)
196
- function startBridge() {
304
+ function startBridge(port = BRIDGE_PORT) {
197
305
  return new Promise((resolve, reject) => {
198
- const child = spawn(process.execPath, [BRIDGE_SCRIPT, String(BRIDGE_PORT)], {
306
+ const child = spawn(process.execPath, [BRIDGE_SCRIPT, String(port)], {
199
307
  stdio: ["ignore", "ignore", "pipe"],
200
308
  detached: true,
201
309
  windowsHide: true,
@@ -212,14 +320,14 @@ function startBridge() {
212
320
  // stderr 管道会挂住父进程的事件循环(bridge 常驻,管道永不关闭)→ 必须 unref
213
321
  try { child.stderr?.unref?.(); } catch {}
214
322
 
215
- // 写入 PID 文件
216
- try { writeFileSync(PID_FILE, String(child.pid), "utf8"); } catch {}
323
+ // 写入 PID 文件(按**实际使用的端口**命名,避免多实例互相覆盖)
324
+ try { writeFileSync(join(ROOT_ABS, `bridge-${port}.pid`), String(child.pid), "utf8"); } catch {}
217
325
 
218
326
  // 等待 bridge 就绪:用轻量健康检查端点,不占用 MCP 的 initialize 握手
219
327
  // (否则同一 MCP server 会被握手两次,导致首次调用挂起)
220
328
  const check = setInterval(async () => {
221
329
  const ready = await new Promise((res) => {
222
- const s = createConnection(BRIDGE_PORT, "127.0.0.1");
330
+ const s = createConnection(port, "127.0.0.1");
223
331
  let buf = "";
224
332
  s.on("connect", () => { s.write("GET /health\n"); });
225
333
  s.on("data", (data) => {
@@ -250,7 +358,7 @@ function startBridge() {
250
358
  // 通过 bridge 调用 MCP
251
359
  function callMCP(method, params) {
252
360
  return new Promise((resolve, reject) => {
253
- const socket = createConnection(BRIDGE_PORT, "127.0.0.1");
361
+ const socket = createConnection(ACTIVE_PORT, "127.0.0.1");
254
362
  let buf = "";
255
363
  const reqId = Math.floor(Math.random() * 100000000) + 2;
256
364
  let resolved = false;
@@ -406,7 +514,10 @@ async function main() {
406
514
  for (let attempt = 0; attempt < 3; attempt++) {
407
515
  if (await isBridgeRunning()) break;
408
516
  try {
409
- await startBridge();
517
+ // 选端口:首选 BRIDGE_PORT;若被**别的身份的 bridge** 占用则向上另选
518
+ const port = await pickBridgePort();
519
+ ACTIVE_PORT = port;
520
+ await startBridge(port);
410
521
  break;
411
522
  } catch (e) {
412
523
  lastErr = e;
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.6.3",
8
+ "version": "2.7.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.6.3",
3
+ "version": "2.7.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",
@@ -42,7 +42,13 @@
42
42
  "check:lang": "node scripts/lang-audit.mjs",
43
43
  "test:lang": "node test/lang-audit.test.mjs",
44
44
  "check:full": "node scripts/full-audit.mjs",
45
- "test:package": "node test/package-e2e.mjs"
45
+ "test:package": "node test/package-e2e.mjs",
46
+ "check:claims": "node scripts/check-claims.mjs",
47
+ "check:params": "node scripts/check-params.mjs",
48
+ "check:no-dead-handler": "node scripts/check-no-dead-handler.mjs",
49
+ "test:scope": "node test/scope-enforcement.mjs",
50
+ "test:audit": "node test/audit-chain.mjs",
51
+ "test:bridge": "node test/bridge-identity.mjs"
46
52
  },
47
53
  "keywords": [
48
54
  "carlos",
@@ -89,6 +95,7 @@
89
95
  "TRIGGER_GUIDE.md",
90
96
  "MIGRATION.md",
91
97
  "CHANGELOG.md",
92
- "LICENSE"
98
+ "LICENSE",
99
+ "AGENTS.md"
93
100
  ]
94
101
  }
@@ -0,0 +1,188 @@
1
+ #!/usr/bin/env node
2
+ // check-claims.mjs — 「承诺兑现度」门禁
3
+ //
4
+ // 为什么要它:
5
+ // 现有的门禁(check:full / check:identity)查的是**静态一致性**
6
+ // ——「文档里写的版本号 == package.json 的版本号」「文档链接的文件存在」。
7
+ // 但 2026-11-07 的第三方审查发现的三个真问题,静态检查**一个都查不到**:
8
+ //
9
+ // · enforceScope 从不自己跑 git diff,且 flow_dispatch 里零 scope 校验
10
+ // → README 承诺的「越界直接阻断派发」根本不成立
11
+ // · flow_audit 的 date 参数算出来了却没用 → 承诺的「按日期过滤」不成立
12
+ // · CallTool handler 注册了两次 → 参数校验靠注册顺序维持,是死代码
13
+ //
14
+ // 共同点:**文档/描述承诺了 A,代码里实际做的是 B**。
15
+ // 所以本门禁直接检查「承诺 ↔ 代码路径」:
16
+ //
17
+ // 1. 工具描述里声明的能力,必须在 handler 里有对应实现
18
+ // 2. README 里点名的关键能力,必须在代码里有对应调用
19
+ // 3. 关键不变量(fail-closed / 真实验证 / 链式审计)必须在源码里出现
20
+ //
21
+ // 退出码:0 = 承诺全部兑现;1 = 有承诺未兑现(逐条打印)
22
+ import { readFileSync, existsSync } from "node:fs";
23
+ import { resolve, dirname, join } from "node:path";
24
+ import { fileURLToPath } from "node:url";
25
+
26
+ const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
27
+ const read = (p) => { try { return readFileSync(join(ROOT, p), "utf8"); } catch { return null; } };
28
+
29
+ let failed = 0;
30
+ const pass = (m) => console.log(` ✅ ${m}`);
31
+ const fail = (m) => { console.log(` ❌ ${m}`); failed++; };
32
+ const section = (t) => console.log(`\n▶ ${t}`);
33
+
34
+ console.log("=".repeat(72));
35
+ console.log("Carlos Flow · 承诺兑现度门禁(文档/描述 ↔ 代码路径)");
36
+ console.log("=".repeat(72));
37
+
38
+ const indexSrc = read("src/index.js") || "";
39
+ const dispatchSrc = read("src/dispatch.js") || "";
40
+ const stateSrc = read("src/state.js") || "";
41
+ const readme = read("README.md") || "";
42
+
43
+ // ---- 1. README 承诺的关键能力必须在代码里有对应实现 ----
44
+ section("README 承诺 ↔ 代码实现");
45
+
46
+ const CLAIMS = [
47
+ {
48
+ claim: "越界改动会阻断(README:「越界直接阻断派发」)",
49
+ // 判定:enforceScope 必须自己跑 git diff(不能只信调用方传的 paths),
50
+ // 且 flow_verdict 必须调用它 —— 没有这一步,承诺就是空的。
51
+ ok: () => /git["'\s,]+diff|--name-only/.test(dispatchSrc) &&
52
+ /enforceScope/.test(dispatchSrc) &&
53
+ /enforceScope/.test(indexSrc),
54
+ hint: "enforceScope 需自己跑 git diff,且 flow_verdict 需调用它做增量比对",
55
+ },
56
+ {
57
+ claim: "真实验证(README:真实 spawn 执行 verify.cmd)",
58
+ ok: () => /runVerifyCommand/.test(indexSrc) && /spawn/.test(dispatchSrc),
59
+ hint: "flow_run_verify 必须调用真实 spawn 的 runVerifyCommand",
60
+ },
61
+ {
62
+ claim: "链式审计(README:SHA-256 链式哈希)",
63
+ ok: () => /prevHash/.test(stateSrc) && /createHash|createHmac/.test(stateSrc),
64
+ hint: "state.js 需实现 prevHash → hash 的链式结构",
65
+ },
66
+ {
67
+ claim: "审计链防篡改(README:改一条全链断裂)",
68
+ // 诚实要求:要么有密钥(HMAC,能发现有意篡改),
69
+ // 要么 verify 结果里显式标注 mode(plain 只是弱保证,不能继续宣称防篡改)。
70
+ ok: () => /createHmac/.test(stateSrc) && /mode/.test(stateSrc),
71
+ hint: "需支持 HMAC(CARLOS_FLOW_AUDIT_KEY),并在 verify 结果里标注 mode",
72
+ },
73
+ {
74
+ claim: "智能触发(README:flow_trigger_check 可实际激活)",
75
+ ok: () => /flow_trigger_check/.test(indexSrc) && /activated/.test(indexSrc),
76
+ hint: "flow_trigger_check 需真实执行激活步骤",
77
+ },
78
+ {
79
+ claim: "独立复核角色(README:auditor 角色)",
80
+ ok: () => /auditor/.test(indexSrc) && /auditor/.test(dispatchSrc),
81
+ hint: "需存在 auditor 角色与对应合同",
82
+ },
83
+ {
84
+ claim: "快照 + 还原(README:flow_revert_plan 生成原子还原计划)",
85
+ ok: () => /snapshotFiles/.test(indexSrc) && /flow_revert_plan/.test(indexSrc),
86
+ hint: "需实现快照与还原计划",
87
+ },
88
+ {
89
+ claim: "派发配额(README:dispatch_count 只在派发时 +1)",
90
+ ok: () => /dispatch_count/.test(indexSrc) && /MAX_DISPATCH/.test(indexSrc),
91
+ hint: "需有 dispatch_count 与 MAX_DISPATCH 约束",
92
+ },
93
+ {
94
+ claim: "免检自动清零(README:每次派发自动清零)",
95
+ ok: () => /bypass_auto_reset/.test(indexSrc),
96
+ hint: "派发后需清零 bypass 并记 bypass_auto_reset 审计",
97
+ },
98
+ {
99
+ claim: "跨平台验证(README:Linux/macOS 也能跑)",
100
+ ok: () => /\/bin\/sh/.test(dispatchSrc) || /COMSPEC/.test(dispatchSrc),
101
+ hint: "runVerifyCommand 需按平台选 shell,不能硬编码 cmd.exe",
102
+ },
103
+ ];
104
+
105
+ for (const c of CLAIMS) {
106
+ const ok = c.ok();
107
+ if (ok) pass(c.claim);
108
+ else fail(`${c.claim}\n → ${c.hint}`);
109
+ }
110
+
111
+ // ---- 2. 工具描述里声明的参数必须真的被 handler 读取 ----
112
+ section("工具描述 ↔ handler 实现");
113
+
114
+ // 抽取每个工具的 description 与 handler 体
115
+ const toolBlocks = indexSrc.split(/\n \{\n/).slice(1);
116
+ let paramIssues = 0;
117
+ for (const block of toolBlocks) {
118
+ const nameM = block.match(/name:\s*"(flow_[a-z_]+)"/);
119
+ if (!nameM) continue;
120
+ const name = nameM[1];
121
+ // 描述里点名的参数(中文或英文)→ 必须在 handler 里出现
122
+ const descM = block.match(/description:\s*([\s\S]*?),\s*\n\s*inputSchema:/);
123
+ const desc = descM ? descM[1] : "";
124
+ const handlerM = block.match(/handler:\s*async\s*\(args\)\s*=>\s*\{([\s\S]*?)\n \},\n \},/);
125
+ const handler = handlerM ? handlerM[1] : block;
126
+
127
+ // 描述里提到「按日期过滤」→ handler/下游必须真的用 date
128
+ if (/日期|date/i.test(desc) && /按.*date|date.*过滤/i.test(desc)) {
129
+ if (!/a\.date|opts\.date|\bdate\b/.test(handler)) {
130
+ fail(`工具 ${name} 的描述承诺支持 date 参数,但 handler 里没用到`);
131
+ paramIssues++;
132
+ }
133
+ }
134
+ // 描述里提到 scope 检查 → 必须调用 enforceScope
135
+ if (/scope/.test(desc) && /检查|越界|范围/.test(desc)) {
136
+ if (!/enforceScope/.test(handler) && !/enforceScope/.test(indexSrc.split(`name: "${name}"`)[1]?.slice(0, 4000) || "")) {
137
+ fail(`工具 ${name} 的描述承诺做 scope 检查,但实现里没调用 enforceScope`);
138
+ paramIssues++;
139
+ }
140
+ }
141
+ }
142
+ if (!paramIssues) pass("所有工具描述承诺的能力都有对应实现");
143
+
144
+ // ---- 3. 关键不变量必须在源码里出现 ----
145
+ section("关键不变量");
146
+
147
+ const INVARIANTS = [
148
+ {
149
+ name: "空 scope 必须 fail-closed(不能「白名单为空=随便改」)",
150
+ ok: () => /scope\.length === 0[\s\S]{0,400}ok:\s*false/.test(dispatchSrc) ||
151
+ /不允许修改任何文件/.test(dispatchSrc),
152
+ },
153
+ {
154
+ name: "记 PASS 必须要求验证通过",
155
+ ok: () => /lv\.ok !== true/.test(indexSrc) && /尚未执行验证/.test(indexSrc),
156
+ },
157
+ {
158
+ name: "记 PASS 必须要求确实派发过",
159
+ ok: () => /dispatch_count\) > 0/.test(indexSrc),
160
+ },
161
+ {
162
+ name: "激活占位卡未补齐时不得派发/裁定",
163
+ ok: () => /activation_pending/.test(indexSrc) &&
164
+ /activation_pending/.test(indexSrc.split("flow_dispatch")[1]?.slice(0, 4000) || ""),
165
+ },
166
+ {
167
+ name: "审计链必须含 prevHash 链接",
168
+ ok: () => /rec\.prevHash = prev/.test(stateSrc),
169
+ },
170
+ {
171
+ name: "状态目录不得写到仓库里(必须走 CARLOS_FLOW_HOME)",
172
+ ok: () => /CARLOS_FLOW_HOME/.test(stateSrc) && !/FLOW_HOME\s*=\s*["']\.\//.test(stateSrc),
173
+ },
174
+ ];
175
+ for (const inv of INVARIANTS) {
176
+ if (inv.ok()) pass(inv.name);
177
+ else fail(inv.name);
178
+ }
179
+
180
+ console.log("\n" + "=".repeat(72));
181
+ if (failed) {
182
+ console.log(`❌ 承诺兑现度检查失败:${failed} 项未兑现`);
183
+ console.log("=".repeat(72));
184
+ process.exit(1);
185
+ }
186
+ console.log("✅ 承诺兑现度检查全部通过");
187
+ console.log("=".repeat(72));
188
+ process.exit(0);
@@ -0,0 +1,88 @@
1
+ #!/usr/bin/env node
2
+ // check-no-dead-handler.mjs — 禁止重复注册同一 request schema
3
+ //
4
+ // 为什么要它:
5
+ // 2026-11-07 的第三方审查发现 src/index.js 里 CallToolRequestSchema
6
+ // **注册了两次**(1132 行与 1213 行)。
7
+ //
8
+ // MCP SDK 的 setRequestHandler 内部是 Map.set → 后注册的覆盖先注册的,
9
+ // 于是先注册的那个(含约 17 行)**永远不会执行** —— 是一段死代码。
10
+ //
11
+ // 当前行为之所以正确,只是因为「带参数校验的那个恰好注册在后面」:
12
+ // · 谁先谁后是一种**隐式约定**,没有任何东西守着它;
13
+ // · 任何一次重排、插入、合并都会静默丢掉参数校验
14
+ // (required 字段 / 类型 / enum 全部失效)—— 而且测试**不会**变红。
15
+ //
16
+ // 所以本门禁把「同一 schema 只能注册一次」变成硬约束。
17
+ //
18
+ // 退出码:0 = 无重复注册;1 = 发现重复(打印位置)
19
+ import { readFileSync } from "node:fs";
20
+ import { resolve, dirname, join } from "node:path";
21
+ import { fileURLToPath } from "node:url";
22
+
23
+ const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
24
+
25
+ let failed = 0;
26
+ const pass = (m) => console.log(` ✅ ${m}`);
27
+ const fail = (m) => { console.log(` ❌ ${m}`); failed++; };
28
+
29
+ console.log("=".repeat(72));
30
+ console.log("Carlos Flow · 重复注册门禁(同一 request schema 只能注册一次)");
31
+ console.log("=".repeat(72));
32
+
33
+ const files = ["src/index.js"];
34
+ for (const f of files) {
35
+ let src = "";
36
+ try { src = readFileSync(join(ROOT, f), "utf8"); } catch { continue; }
37
+
38
+ // 统计 setRequestHandler(X, ...) 的出现,按 schema 分组
39
+ const bySchema = new Map();
40
+ const re = /setRequestHandler\(\s*([A-Za-z_][A-Za-z0-9_]*)/g;
41
+ let m;
42
+ while ((m = re.exec(src)) !== null) {
43
+ const schema = m[1];
44
+ const line = src.slice(0, m.index).split("\n").length;
45
+ if (!bySchema.has(schema)) bySchema.set(schema, []);
46
+ bySchema.get(schema).push(line);
47
+ }
48
+
49
+ console.log(`\n▶ ${f}`);
50
+ for (const [schema, lines] of bySchema) {
51
+ if (lines.length > 1) {
52
+ fail(`${schema} 被注册了 ${lines.length} 次(第 ${lines.join(", ")} 行)—— ` +
53
+ `后注册的会覆盖先注册的,先注册的是永不执行的死代码`);
54
+ } else {
55
+ pass(`${schema} 只注册一次(第 ${lines[0]} 行)`);
56
+ }
57
+ }
58
+ }
59
+
60
+ // ---- 额外:MCP server 装配段的 handler 与工具实现必须对得上 ----
61
+ console.log("\n▶ 工具实现 ↔ handler 装配");
62
+ try {
63
+ const src = readFileSync(join(ROOT, "src/index.js"), "utf8");
64
+ const toolsM = src.match(/const TOOLS = \[([\s\S]*?)\n\];/);
65
+ const declared = toolsM
66
+ ? [...toolsM[1].matchAll(/name:\s*"(flow_[a-z_]+)"/g)].map((x) => x[1])
67
+ : [];
68
+ const hasDispatchLookup = /TOOLS\.find\([\s\S]{0,80}?\.name\s*===/.test(src);
69
+ if (hasDispatchLookup) pass("CallTool handler 通过 TOOLS.find 分发到工具实现");
70
+ else fail("CallTool handler 找不到按 name 分发到工具实现的逻辑");
71
+ const hasValidation = /validateToolArgs\(/.test(src);
72
+ if (hasValidation) pass("CallTool handler 调用了 validateToolArgs(参数校验未丢失)");
73
+ else fail("CallTool handler 没有调用 validateToolArgs —— 参数校验可能已丢失");
74
+ if (declared.length === 15) pass(`TOOLS 声明 ${declared.length} 个工具`);
75
+ else fail(`TOOLS 声明了 ${declared.length} 个工具(期望 15)`);
76
+ } catch (e) {
77
+ fail(`读取 src/index.js 失败:${e.message}`);
78
+ }
79
+
80
+ console.log("\n" + "=".repeat(72));
81
+ if (failed) {
82
+ console.log(`❌ 重复注册检查失败:${failed} 项问题`);
83
+ console.log("=".repeat(72));
84
+ process.exit(1);
85
+ }
86
+ console.log("✅ 重复注册检查全部通过");
87
+ console.log("=".repeat(72));
88
+ process.exit(0);