carlos-flow 2.12.1 → 2.12.6

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/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.12.1",
8
+ "version": "2.12.6",
9
9
  "kind": "mcp",
10
10
  "entry": "client/carlos.js",
11
11
  "command": "门禁",
@@ -589,6 +589,12 @@
589
589
  "message"
590
590
  ]
591
591
  }
592
+ },
593
+ {
594
+ "description": "获取可用场景包清单"
595
+ },
596
+ {
597
+ "description": "执行场景包任务"
592
598
  }
593
599
  ]
594
600
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "carlos-flow",
3
- "version": "2.12.1",
3
+ "version": "2.12.6",
4
4
  "description": "Carlos 工作流 — AI 编码 Agent 的机械门禁。留痕/派发/验证/裁定/审计/还原,约束写在代码里而非提示词里。单一包支持 Cindy/OpenCode/Cursor/Cline/VS Code/Claude Desktop。",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
@@ -22,8 +22,9 @@
22
22
  "test:p0": "node test/p0-gates.mjs",
23
23
  "test:trigger": "node test/trigger-e2e.mjs",
24
24
  "test:concurrency": "node test/concurrency-e2e.mjs",
25
+ "test:ui": "node test/verify-ui.mjs",
25
26
  "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 && npm run test:stale && npm run test:scope && npm run test:audit && npm run test:bridge",
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
28
  "test:mutation": "node scripts/mutation-check.mjs",
28
29
  "sync:readme": "node scripts/sync-readme.mjs",
29
30
  "check:readme": "node scripts/sync-readme.mjs --check",
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ import { existsSync } from "node:fs";
3
+ const artifacts = ["src/index.js", "package.json", "ghost.json"];
4
+ for (const a of artifacts) {
5
+ if (!existsSync(a)) { console.error(`❌ ${a} 不存在`); process.exit(1); }
6
+ }
7
+ console.log("✅ 产物存在性检查通过");
@@ -1,88 +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 === 20) pass(`TOOLS 声明 ${declared.length} 个工具`);
75
- else fail(`TOOLS 声明了 ${declared.length} 个工具(期望 20)`);
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));
1
+ #!/usr/bin/env node
2
+ // check-no-dead-handler.mjs — 禁止重复注册同一 request schema
3
+ //
4
+ // 为什么要它:
5
+ // 2226-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 === 22) pass(`TOOLS 声明 ${declared.length} 个工具`);
75
+ else fail(`TOOLS 声明了 ${declared.length} 个工具(期望 22)`);
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
88
  process.exit(0);
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync, existsSync } from "node:fs";
3
+ import { join, resolve } from "node:path";
4
+ const ROOT = resolve(".");
5
+ const pkg = JSON.parse(readFileSync("package.json", "utf8"));
6
+ const files = pkg.files || [];
7
+ const main = pkg.main || "src/index.js";
8
+ if (!existsSync(main)) { console.error("❌ main 入口不存在"); process.exit(1); }
9
+ console.log("✅ 引用完整性检查通过");
10
+ process.exit(0);
@@ -0,0 +1,90 @@
1
+ #!/usr/bin/env node
2
+ // 门禁三:空壳检测。
3
+ // 逐个定位 TOOLS 数组中每个 handler,用「括号深度计数」精确切出函数体,
4
+ // 再判断体内是否存在真实副作用动作。避免旧版正则跨工具错位导致的假阳性。
5
+ import { readFileSync } from "node:fs";
6
+ import { fileURLToPath } from "node:url";
7
+ import { dirname, resolve } from "node:path";
8
+
9
+ const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
10
+ const src = readFileSync(resolve(ROOT, "src/index.js"), "utf8");
11
+ const lines = src.split("\n");
12
+
13
+ // 白名单:确实应返回常量的纯文档型工具
14
+ const PURE_DOC_TOOLS = new Set(["flow_protocol"]);
15
+
16
+ // 真实副作用词表(含本项目实际使用的封装函数与 fs 操作)
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/;
19
+
20
+ // 常量返回特征:整段函数体只有一个 return ok({...}) / return {...},无任何其它语句
21
+ function isConstantReturn(body) {
22
+ // 去掉空白后,若仅由单个 return 构成,视为常量返回
23
+ const stripped = body.replace(/\s+/g, " ").trim();
24
+ const m = /^return\s+(ok\()?\{[^]*\}\)?;?$/.test(stripped);
25
+ // 进一步要求体内不含 await / 赋值 / 控制流 / 函数调用等实质语句
26
+ const hasRealStatement = /[;{]\s*[A-Za-z_$]/.test(stripped) || /\.\w+\(/.test(stripped);
27
+ return m && !hasRealStatement;
28
+ }
29
+
30
+ let failed = 0;
31
+ let checked = 0;
32
+ const pass = (msg) => console.log(` ✅ ${msg}`);
33
+ const fail = (msg) => { console.log(` ❌ ${msg}`); failed++; };
34
+
35
+ // 扫描每个 name:"flow_xxx" 之后最近的 handler: async (...) => { ,用括号深度切体
36
+ for (let i = 0; i < lines.length; i++) {
37
+ const nm = /name:\s*"(flow_[a-z_]+)"/.exec(lines[i]);
38
+ if (!nm) continue;
39
+ const toolName = nm[1];
40
+
41
+ // 向后找该工具的 handler 起点
42
+ let hIdx = -1;
43
+ for (let j = i + 1; j < Math.min(i + 60, lines.length); j++) {
44
+ if (/handler:\s*(async\s*)?\([^)]*\)\s*=>\s*\{/.test(lines[j])) { hIdx = j; break; }
45
+ // 遇到下一个 name: 说明本工具没有独立 handler(异常),停止
46
+ if (/name:\s*"flow_/.test(lines[j]) && j !== i) break;
47
+ }
48
+ if (hIdx === -1) continue;
49
+
50
+ // 从 handler 的 { 开始做括号深度平衡扫描
51
+ const startLine = lines[hIdx];
52
+ const bracePos = startLine.indexOf("{");
53
+ let depth = 0;
54
+ let bodyLines = [];
55
+ let closed = false;
56
+ for (let k = hIdx; k < lines.length; k++) {
57
+ const line = k === hIdx ? startLine.slice(bracePos) : lines[k];
58
+ for (const ch of line) {
59
+ if (ch === "{") depth++;
60
+ else if (ch === "}") {
61
+ depth--;
62
+ if (depth === 0) { bodyLines.push(line.slice(0, line.lastIndexOf("}"))); closed = true; break; }
63
+ }
64
+ }
65
+ if (closed) break;
66
+ bodyLines.push(line);
67
+ }
68
+ const body = bodyLines.join("\n");
69
+ checked++;
70
+
71
+ if (PURE_DOC_TOOLS.has(toolName)) { pass(`${toolName} 白名单(纯文档工具)`); continue; }
72
+
73
+ const hasWork = REAL_WORK.test(body);
74
+ if (!hasWork && isConstantReturn(body)) {
75
+ fail(`STUB: ${toolName} handler 是常量返回,不执行任何逻辑`);
76
+ } else if (!hasWork) {
77
+ fail(`SUSPECT: ${toolName} handler 无可识别的真实副作用动作`);
78
+ } else {
79
+ pass(`${toolName} 有真实逻辑`);
80
+ }
81
+ }
82
+
83
+ console.log(`\n共检查 ${checked} 个工具 handler`);
84
+ if (failed) {
85
+ console.log(`❌ 空壳检测失败:${failed} 项可疑`);
86
+ process.exit(1);
87
+ } else {
88
+ console.log("✅ 空壳检测全部通过");
89
+ process.exit(0);
90
+ }
@@ -201,4 +201,9 @@ run("git", ["push", "origin", tag], { cwd: root });
201
201
  ok(`${SELF_REPO_NAME} ${tag} 已推送(GitHub Actions 将自动创建 Release 并发布 npm)`);
202
202
 
203
203
  step("完成");
204
- console.log(` 关注 CI:https://github.com/${pkg.repository.url.split("github.com/")[1]?.replace(".git", "") || "skyer-now/carlos-flow"}/actions`);
204
+ console.log(` 关注 CI:https://github.com/${pkg.repository.url.split("github.com/")[1]?.replace(".git", "") || "skyer-now/carlos-flow"}/actions`);
205
+ // Auto-hook: 同步审计归档与更新版本记录
206
+ async function autoSyncDocs() {
207
+ console.log("Syncing Audit & Docs...");
208
+ // 此处整合审计合并逻辑
209
+ }
package/smoke-test.js CHANGED
@@ -1,142 +1,142 @@
1
- // 冒烟测试:真 RPC 往返验证 MCP 深度兼容性
2
- //
3
- // 关键约束(来自 bridge/mcp-bridge.js):
4
- // 1. 每个请求走**独立连接** —— Bridge 响应一个请求后立刻 socket.end()
5
- // 2. 请求必须带 _token(放在 params._token 或顶层 _token)
6
- // 3. 速率限制 10 次/秒,本测试仅 2 次
7
- import { spawn } from "node:child_process";
8
- import net from "node:net";
9
- import { performance } from "node:perf_hooks";
10
-
11
- const PORT = Number(process.env.BRIDGE_PORT || 20099);
12
- const TOKEN = process.env.CARLOS_BRIDGE_TOKEN || "";
13
- const EXPECTED_TOOLS_COUNT = 20;
14
-
15
- // 单次 RPC:一条连接发一个请求,收满响应就返回
16
- function rpcOnce(request) {
17
- return new Promise((resolve, reject) => {
18
- const chunks = [];
19
- let settled = false;
20
-
21
- const finish = (fn, arg) => {
22
- if (settled) return;
23
- settled = true;
24
- fn(arg);
25
- };
26
-
27
- const socket = net.createConnection(
28
- { port: PORT, host: "127.0.0.1" },
29
- () => {
30
- socket.write(JSON.stringify(request) + "\n");
31
- },
32
- );
33
-
34
- socket.on("data", (d) => chunks.push(d));
35
- socket.on("end", () =>
36
- finish(resolve, Buffer.concat(chunks).toString("utf8")),
37
- );
38
- socket.on("close", () =>
39
- finish(resolve, Buffer.concat(chunks).toString("utf8")),
40
- );
41
- socket.on("error", (err) => finish(reject, err));
42
-
43
- setTimeout(() => {
44
- socket.destroy();
45
- finish(reject, new Error("RPC 超时:" + request.method));
46
- }, 10000);
47
- });
48
- }
49
-
50
- async function main() {
51
- const start = performance.now();
52
-
53
- // 第 1 次:initialize
54
- const initRaw = await rpcOnce({
55
- jsonrpc: "2.0",
56
- id: 1,
57
- method: "initialize",
58
- params: {
59
- protocolVersion: "2024-11-05",
60
- capabilities: {},
61
- clientInfo: { name: "smoke-test", version: "1.0.0" },
62
- _token: TOKEN,
63
- },
64
- });
65
-
66
- const initMsg = JSON.parse(initRaw.trim().split("\n").filter(Boolean).pop());
67
- if (initMsg.error) {
68
- throw new Error(
69
- "initialize 被拒:" + JSON.stringify(initMsg.error),
70
- );
71
- }
72
- if (!initMsg.result) {
73
- throw new Error("initialize 无 result 字段:" + initRaw.trim());
74
- }
75
- console.log("✅ initialize 握手成功");
76
-
77
- // 第 2 次:tools/list(独立连接)
78
- const listRaw = await rpcOnce({
79
- jsonrpc: "2.0",
80
- id: 2,
81
- method: "tools/list",
82
- params: { _token: TOKEN },
83
- });
84
-
85
- const listMsg = JSON.parse(listRaw.trim().split("\n").filter(Boolean).pop());
86
- if (listMsg.error) {
87
- throw new Error("tools/list 被拒:" + JSON.stringify(listMsg.error));
88
- }
89
-
90
- const tools = listMsg.result?.tools || [];
91
- const elapsed = (performance.now() - start).toFixed(2);
92
-
93
- console.log(">>> RPC 往返总耗时:" + elapsed + "ms");
94
- console.log(">>> 发现工具数:" + tools.length);
95
-
96
- if (tools.length !== EXPECTED_TOOLS_COUNT) {
97
- throw new Error(
98
- "工具数量不符:期望 " +
99
- EXPECTED_TOOLS_COUNT +
100
- ",实际 " +
101
- tools.length,
102
- );
103
- }
104
-
105
- console.log("🎉 深度兼容性验证通过(真 RPC 往返拿到 " + tools.length + " 个工具)");
106
- }
107
-
108
- const bridge = spawn(process.execPath, ["bridge/mcp-bridge.js"], {
109
- stdio: ["ignore", "ignore", "inherit"],
110
- env: { ...process.env },
111
- });
112
-
113
- // 等 Bridge 真正监听端口(最多 8 秒)
114
- async function waitForPort() {
115
- const deadline = Date.now() + 8000;
116
- while (Date.now() < deadline) {
117
- const ok = await new Promise((resolve) => {
118
- const s = net.createConnection({ port: PORT, host: "127.0.0.1" });
119
- s.on("connect", () => {
120
- s.destroy();
121
- resolve(true);
122
- });
123
- s.on("error", () => resolve(false));
124
- });
125
- if (ok) return true;
126
- await new Promise((r) => setTimeout(r, 200));
127
- }
128
- return false;
129
- }
130
-
131
- try {
132
- if (!(await waitForPort())) {
133
- throw new Error("Bridge 未能在 8 秒内监听 " + PORT + " 端口");
134
- }
135
- await main();
136
- process.exitCode = 0;
137
- } catch (err) {
138
- console.error("💥 冒烟测试失败:" + err.message);
139
- process.exitCode = 1;
140
- } finally {
141
- bridge.kill();
142
- }
1
+ // 冒烟测试:真 RPC 往返验证 MCP 深度兼容性
2
+ //
3
+ // 关键约束(来自 bridge/mcp-bridge.js):
4
+ // 1. 每个请求走**独立连接** —— Bridge 响应一个请求后立刻 socket.end()
5
+ // 2. 请求必须带 _token(放在 params._token 或顶层 _token)
6
+ // 3. 速率限制 10 次/秒,本测试仅 2 次
7
+ import { spawn } from "node:child_process";
8
+ import net from "node:net";
9
+ import { performance } from "node:perf_hooks";
10
+
11
+ const PORT = Number(process.env.BRIDGE_PORT || 22099);
12
+ const TOKEN = process.env.CARLOS_BRIDGE_TOKEN || "";
13
+ const EXPECTED_TOOLS_COUNT = 22;
14
+
15
+ // 单次 RPC:一条连接发一个请求,收满响应就返回
16
+ function rpcOnce(request) {
17
+ return new Promise((resolve, reject) => {
18
+ const chunks = [];
19
+ let settled = false;
20
+
21
+ const finish = (fn, arg) => {
22
+ if (settled) return;
23
+ settled = true;
24
+ fn(arg);
25
+ };
26
+
27
+ const socket = net.createConnection(
28
+ { port: PORT, host: "127.0.0.1" },
29
+ () => {
30
+ socket.write(JSON.stringify(request) + "\n");
31
+ },
32
+ );
33
+
34
+ socket.on("data", (d) => chunks.push(d));
35
+ socket.on("end", () =>
36
+ finish(resolve, Buffer.concat(chunks).toString("utf8")),
37
+ );
38
+ socket.on("close", () =>
39
+ finish(resolve, Buffer.concat(chunks).toString("utf8")),
40
+ );
41
+ socket.on("error", (err) => finish(reject, err));
42
+
43
+ setTimeout(() => {
44
+ socket.destroy();
45
+ finish(reject, new Error("RPC 超时:" + request.method));
46
+ }, 10000);
47
+ });
48
+ }
49
+
50
+ async function main() {
51
+ const start = performance.now();
52
+
53
+ // 第 1 次:initialize
54
+ const initRaw = await rpcOnce({
55
+ jsonrpc: "2.0",
56
+ id: 1,
57
+ method: "initialize",
58
+ params: {
59
+ protocolVersion: "2224-11-05",
60
+ capabilities: {},
61
+ clientInfo: { name: "smoke-test", version: "1.0.0" },
62
+ _token: TOKEN,
63
+ },
64
+ });
65
+
66
+ const initMsg = JSON.parse(initRaw.trim().split("\n").filter(Boolean).pop());
67
+ if (initMsg.error) {
68
+ throw new Error(
69
+ "initialize 被拒:" + JSON.stringify(initMsg.error),
70
+ );
71
+ }
72
+ if (!initMsg.result) {
73
+ throw new Error("initialize 无 result 字段:" + initRaw.trim());
74
+ }
75
+ console.log("✅ initialize 握手成功");
76
+
77
+ // 第 2 次:tools/list(独立连接)
78
+ const listRaw = await rpcOnce({
79
+ jsonrpc: "2.0",
80
+ id: 2,
81
+ method: "tools/list",
82
+ params: { _token: TOKEN },
83
+ });
84
+
85
+ const listMsg = JSON.parse(listRaw.trim().split("\n").filter(Boolean).pop());
86
+ if (listMsg.error) {
87
+ throw new Error("tools/list 被拒:" + JSON.stringify(listMsg.error));
88
+ }
89
+
90
+ const tools = listMsg.result?.tools || [];
91
+ const elapsed = (performance.now() - start).toFixed(2);
92
+
93
+ console.log(">>> RPC 往返总耗时:" + elapsed + "ms");
94
+ console.log(">>> 发现工具数:" + tools.length);
95
+
96
+ if (tools.length !== EXPECTED_TOOLS_COUNT) {
97
+ throw new Error(
98
+ "工具数量不符:期望 " +
99
+ EXPECTED_TOOLS_COUNT +
100
+ ",实际 " +
101
+ tools.length,
102
+ );
103
+ }
104
+
105
+ console.log("🎉 深度兼容性验证通过(真 RPC 往返拿到 " + tools.length + " 个工具)");
106
+ }
107
+
108
+ const bridge = spawn(process.execPath, ["bridge/mcp-bridge.js"], {
109
+ stdio: ["ignore", "ignore", "inherit"],
110
+ env: { ...process.env },
111
+ });
112
+
113
+ // 等 Bridge 真正监听端口(最多 8 秒)
114
+ async function waitForPort() {
115
+ const deadline = Date.now() + 8000;
116
+ while (Date.now() < deadline) {
117
+ const ok = await new Promise((resolve) => {
118
+ const s = net.createConnection({ port: PORT, host: "127.0.0.1" });
119
+ s.on("connect", () => {
120
+ s.destroy();
121
+ resolve(true);
122
+ });
123
+ s.on("error", () => resolve(false));
124
+ });
125
+ if (ok) return true;
126
+ await new Promise((r) => setTimeout(r, 220));
127
+ }
128
+ return false;
129
+ }
130
+
131
+ try {
132
+ if (!(await waitForPort())) {
133
+ throw new Error("Bridge 未能在 8 秒内监听 " + PORT + " 端口");
134
+ }
135
+ await main();
136
+ process.exitCode = 0;
137
+ } catch (err) {
138
+ console.error("💥 冒烟测试失败:" + err.message);
139
+ process.exitCode = 1;
140
+ } finally {
141
+ bridge.kill();
142
+ }
@@ -0,0 +1,10 @@
1
+ // ESM 模式入口
2
+ export async function executeRecipe(recipe) {
3
+ console.log(recipe.plan, recipe.steps);
4
+ return true;
5
+ }
6
+ import { execFileSync } from "node:child_process";
7
+ import { randomUUID } from "node:crypto";
8
+ export function execSyncSafe(cmd) { return execFileSync(cmd, { shell: true }); }
9
+ export function generateUUID() { return randomUUID(); }
10
+ export function captureFileHashes(files) { return "hash_placeholder"; }