carlos-flow 2.6.3 → 2.8.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.
@@ -1,215 +1,215 @@
1
- // carlos-flow-trigger — OpenCode 插件:把智能触发引擎真正接到消息事件上
2
- //
3
- // 为什么需要这个插件:
4
- // Carlos 工作流的「智能触发引擎」(src/trigger.js)原本只接在**命令行客户端**
5
- // (client/carlos.js)上 —— MCP server 根本不接触发引擎。
6
- // 而在 OpenCode 里,Agent 走的是 MCP 工具路径(直接调 flow_* 工具),
7
- // 于是 README 里那张「工作流会自己认出该上场的时候」的流程图在**实际使用路径上是不成立的**。
8
- //
9
- // 本插件做的事:
10
- // 监听 OpenCode 的 `chat.message` 钩子(用户每发一条消息都会触发),
11
- // 把消息原文交给 MCP 的 flow_trigger_check 工具 —— 由它做评分与决策,
12
- // 达标时**实际完成激活**(写入用户原话 + 开占位卡 → 会话进入门禁态)。
13
- //
14
- // 评分与决策逻辑与命令行路径**共用同一份实现**(src/trigger.js),
15
- // 所以两条路径的行为完全一致,不会出现「命令行能触发、MCP 不能」。
16
- //
17
- // 安装:
18
- // 方式 A(本地文件):把本文件放到 OpenCode 的插件目录
19
- // ~/.config/opencode/plugins/carlos-flow-trigger.js
20
- // Windows 下则是 %APPDATA%\opencode\plugins\carlos-flow-trigger.js
21
- // 项目级则放 .opencode/plugins/carlos-flow-trigger.js
22
- // 方式 B(npm 包):在 opencode.json 里加
23
- // { "plugin": ["carlos-flow/plugins/carlos-flow-trigger.js"] }
24
- // 然后重启 OpenCode。
25
- //
26
- // 可选环境变量:
27
- // CARLOS_FLOW_TRIGGER=off 关闭插件(临时停用自动触发)
28
- // CARLOS_FLOW_TRIGGER_DEBUG=1 打印触发决策日志
29
- //
30
- // 说明:
31
- // · 插件只做「判断 + 激活」,**不代替 Agent 决定改哪些文件**;
32
- // 激活后仍需补齐 scope / acceptance / verify.cmd 才能派发(闸门不放松);
33
- // · 任何异常都只记日志、绝不阻断用户消息(插件出错不应该让 OpenCode 挂掉)。
34
-
35
- import { spawn } from "node:child_process";
36
- import { existsSync } from "node:fs";
37
- import { homedir } from "node:os";
38
- import { join, resolve } from "node:path";
39
-
40
- const DEBUG = process.env.CARLOS_FLOW_TRIGGER_DEBUG === "1";
41
- const ENABLED = process.env.CARLOS_FLOW_TRIGGER !== "off";
42
-
43
- // 找到 MCP server 的 src/index.js。
44
- // 插件可能位于:
45
- // 1) <pkg>/plugins/carlos-flow-trigger.js(npm 包内,方式 B)
46
- // 2) ~/.config/opencode/plugins/carlos-flow-trigger.js(本地文件,方式 A)
47
- // 3) <repo>/plugins/carlos-flow-trigger.js(源码 checkout)
48
- //
49
- // ⚠️ 包名是 **carlos-flow**(v2.6.0 起统一单包)。
50
- // 旧版这里硬编码的是 carlos-flow-opencode —— 单包化之后那个目录根本不存在,
51
- // 于是除「方式 B」(插件就在包内)外的所有安装方式都**找不到 MCP server**,
52
- // 自动触发**静默失效**。
53
- // 现在同时接受新包名与两个已弃用的旧包名(兼容老用户尚未迁移的 node_modules)。
54
- const PKG_NAMES = ["carlos-flow", "carlos-flow-opencode", "carlos-flow-cindy"];
55
- function findMcpServer() {
56
- const here = new URL(".", import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, "$1");
57
- const dir = resolve(here);
58
- const candidates = [
59
- join(dir, "..", "src", "index.js"), // <pkg>/plugins/ → <pkg>/src/
60
- ];
61
- for (const name of PKG_NAMES) {
62
- candidates.push(
63
- join(dir, "..", "..", "node_modules", name, "src", "index.js"),
64
- join(dir, "..", "..", "..", "node_modules", name, "src", "index.js"),
65
- join(homedir(), ".config", "opencode", "node_modules", name, "src", "index.js"),
66
- join(homedir(), "AppData", "Roaming", "opencode", "node_modules", name, "src", "index.js"),
67
- );
68
- }
69
- for (const p of candidates) {
70
- try {
71
- if (existsSync(p)) return p;
72
- } catch {}
73
- }
74
- return null;
75
- }
76
-
77
- // 以 MCP 的 stdio 协议调一个工具(一次性拉起,用完即退)
78
- async function callMcpTool(serverPath, toolName, args, timeoutMs = 15000) {
79
- return new Promise((resolvePromise) => {
80
- const child = spawn(process.execPath, [serverPath], {
81
- stdio: ["pipe", "pipe", "pipe"],
82
- windowsHide: true,
83
- });
84
- let buf = "";
85
- let stderr = "";
86
- const pending = new Map();
87
- let id = 1;
88
-
89
- const timer = setTimeout(() => {
90
- try { child.kill(); } catch {}
91
- resolvePromise({ ok: false, error: "timeout" });
92
- }, timeoutMs);
93
-
94
- child.stdout.on("data", (d) => {
95
- buf += d.toString();
96
- let i;
97
- while ((i = buf.indexOf("\n")) >= 0) {
98
- const line = buf.slice(0, i);
99
- buf = buf.slice(i + 1);
100
- if (!line.trim()) continue;
101
- try {
102
- const msg = JSON.parse(line);
103
- if (msg.id && pending.has(msg.id)) {
104
- pending.get(msg.id)(msg);
105
- pending.delete(msg.id);
106
- }
107
- } catch {}
108
- }
109
- });
110
- child.stderr.on("data", (d) => { stderr += d.toString(); });
111
-
112
- const req = (method, params) => new Promise((r) => {
113
- const rid = id++;
114
- pending.set(rid, r);
115
- child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id: rid, method, params }) + "\n");
116
- });
117
-
118
- child.on("error", (e) => {
119
- clearTimeout(timer);
120
- try { child.kill(); } catch {}
121
- resolvePromise({ ok: false, error: String(e && e.message ? e.message : e) });
122
- });
123
- child.on("exit", () => {
124
- clearTimeout(timer);
125
- resolvePromise({ ok: false, error: stderr.slice(-300) || "server exited" });
126
- });
127
-
128
- (async () => {
129
- try {
130
- await req("initialize", {
131
- protocolVersion: "2024-11-05",
132
- capabilities: {},
133
- clientInfo: { name: "carlos-flow-trigger", version: "1.0.0" },
134
- });
135
- const res = await req("tools/call", { name: toolName, arguments: args });
136
- const text = res?.result?.content?.[0]?.text || "";
137
- clearTimeout(timer);
138
- try { child.kill(); } catch {}
139
- if (res?.result?.isError) {
140
- resolvePromise({ ok: false, error: String(text).slice(0, 300) });
141
- } else {
142
- try {
143
- resolvePromise({ ok: true, data: JSON.parse(text) });
144
- } catch {
145
- resolvePromise({ ok: false, error: "bad json: " + String(text).slice(0, 200) });
146
- }
147
- }
148
- } catch (e) {
149
- clearTimeout(timer);
150
- try { child.kill(); } catch {}
151
- resolvePromise({ ok: false, error: String(e && e.message ? e.message : e) });
152
- }
153
- })();
154
- });
155
- }
156
-
157
- // 从 parts 里取出用户消息文本(只看 type==="text" 的部分)
158
- function extractText(parts) {
159
- if (!Array.isArray(parts)) return "";
160
- return parts
161
- .filter((p) => p && p.type === "text" && typeof p.text === "string")
162
- .map((p) => p.text)
163
- .join("\n")
164
- .trim();
165
- }
166
-
167
- export const CarlosFlowTriggerPlugin = async ({ client, $, worktree, directory }) => {
168
- const serverPath = findMcpServer();
169
- if (!serverPath) {
170
- console.error("[carlos-flow-trigger] 未找到 MCP server(src/index.js),自动触发未启用");
171
- console.error("[carlos-flow-trigger] 请确认已全局安装:npm install -g carlos-flow");
172
- }
173
- if (DEBUG) {
174
- console.error("[carlos-flow-trigger] server:", serverPath, "cwd:", worktree || directory);
175
- }
176
-
177
- return {
178
- "chat.message": async (input, output) => {
179
- if (!ENABLED) return;
180
- if (!serverPath) return;
181
-
182
- const message = extractText(output && output.parts);
183
- if (!message) return;
184
-
185
- const sessionId = input.sessionID || "default";
186
- try {
187
- const res = await callMcpTool(serverPath, "flow_trigger_check", {
188
- sessionId,
189
- message,
190
- cwd: worktree || directory || process.cwd(),
191
- });
192
-
193
- if (!res.ok) {
194
- if (DEBUG) console.error("[carlos-flow-trigger] 调用失败:", res.error);
195
- return; // 插件出错绝不阻断用户消息
196
- }
197
-
198
- const d = res.data || {};
199
- if (DEBUG) {
200
- console.error(
201
- `[carlos-flow-trigger] decision=${d.decision} score=${d.score} activated=${d.activated}`
202
- );
203
- }
204
- if (d.activated) {
205
- console.error(
206
- `[carlos-flow-trigger] 已自动激活 Carlos 工作流(评分 ${d.score})—— ` +
207
- `请补齐 ${(d.pending_fields || []).join(" / ")} 后再派发`
208
- );
209
- }
210
- } catch (e) {
211
- if (DEBUG) console.error("[carlos-flow-trigger] 异常:", e && e.message ? e.message : e);
212
- }
213
- },
214
- };
215
- };
1
+ // carlos-flow-trigger — OpenCode 插件:把智能触发引擎真正接到消息事件上
2
+ //
3
+ // 为什么需要这个插件:
4
+ // Carlos 工作流的「智能触发引擎」(src/trigger.js)原本只接在**命令行客户端**
5
+ // (client/carlos.js)上 —— MCP server 根本不接触发引擎。
6
+ // 而在 OpenCode 里,Agent 走的是 MCP 工具路径(直接调 flow_* 工具),
7
+ // 于是 README 里那张「工作流会自己认出该上场的时候」的流程图在**实际使用路径上是不成立的**。
8
+ //
9
+ // 本插件做的事:
10
+ // 监听 OpenCode 的 `chat.message` 钩子(用户每发一条消息都会触发),
11
+ // 把消息原文交给 MCP 的 flow_trigger_check 工具 —— 由它做评分与决策,
12
+ // 达标时**实际完成激活**(写入用户原话 + 开占位卡 → 会话进入门禁态)。
13
+ //
14
+ // 评分与决策逻辑与命令行路径**共用同一份实现**(src/trigger.js),
15
+ // 所以两条路径的行为完全一致,不会出现「命令行能触发、MCP 不能」。
16
+ //
17
+ // 安装:
18
+ // 方式 A(本地文件):把本文件放到 OpenCode 的插件目录
19
+ // ~/.config/opencode/plugins/carlos-flow-trigger.js
20
+ // Windows 下则是 %APPDATA%\opencode\plugins\carlos-flow-trigger.js
21
+ // 项目级则放 .opencode/plugins/carlos-flow-trigger.js
22
+ // 方式 B(npm 包):在 opencode.json 里加
23
+ // { "plugin": ["carlos-flow/plugins/carlos-flow-trigger.js"] }
24
+ // 然后重启 OpenCode。
25
+ //
26
+ // 可选环境变量:
27
+ // CARLOS_FLOW_TRIGGER=off 关闭插件(临时停用自动触发)
28
+ // CARLOS_FLOW_TRIGGER_DEBUG=1 打印触发决策日志
29
+ //
30
+ // 说明:
31
+ // · 插件只做「判断 + 激活」,**不代替 Agent 决定改哪些文件**;
32
+ // 激活后仍需补齐 scope / acceptance / verify.cmd 才能派发(闸门不放松);
33
+ // · 任何异常都只记日志、绝不阻断用户消息(插件出错不应该让 OpenCode 挂掉)。
34
+
35
+ import { spawn } from "node:child_process";
36
+ import { existsSync } from "node:fs";
37
+ import { homedir } from "node:os";
38
+ import { join, resolve } from "node:path";
39
+
40
+ const DEBUG = process.env.CARLOS_FLOW_TRIGGER_DEBUG === "1";
41
+ const ENABLED = process.env.CARLOS_FLOW_TRIGGER !== "off";
42
+
43
+ // 找到 MCP server 的 src/index.js。
44
+ // 插件可能位于:
45
+ // 1) <pkg>/plugins/carlos-flow-trigger.js(npm 包内,方式 B)
46
+ // 2) ~/.config/opencode/plugins/carlos-flow-trigger.js(本地文件,方式 A)
47
+ // 3) <repo>/plugins/carlos-flow-trigger.js(源码 checkout)
48
+ //
49
+ // ⚠️ 包名是 **carlos-flow**(v2.6.0 起统一单包)。
50
+ // 旧版这里硬编码的是 carlos-flow-opencode —— 单包化之后那个目录根本不存在,
51
+ // 于是除「方式 B」(插件就在包内)外的所有安装方式都**找不到 MCP server**,
52
+ // 自动触发**静默失效**。
53
+ // 现在同时接受新包名与两个已弃用的旧包名(兼容老用户尚未迁移的 node_modules)。
54
+ const PKG_NAMES = ["carlos-flow", "carlos-flow-opencode", "carlos-flow-cindy"];
55
+ function findMcpServer() {
56
+ const here = new URL(".", import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, "$1");
57
+ const dir = resolve(here);
58
+ const candidates = [
59
+ join(dir, "..", "src", "index.js"), // <pkg>/plugins/ → <pkg>/src/
60
+ ];
61
+ for (const name of PKG_NAMES) {
62
+ candidates.push(
63
+ join(dir, "..", "..", "node_modules", name, "src", "index.js"),
64
+ join(dir, "..", "..", "..", "node_modules", name, "src", "index.js"),
65
+ join(homedir(), ".config", "opencode", "node_modules", name, "src", "index.js"),
66
+ join(homedir(), "AppData", "Roaming", "opencode", "node_modules", name, "src", "index.js"),
67
+ );
68
+ }
69
+ for (const p of candidates) {
70
+ try {
71
+ if (existsSync(p)) return p;
72
+ } catch {}
73
+ }
74
+ return null;
75
+ }
76
+
77
+ // 以 MCP 的 stdio 协议调一个工具(一次性拉起,用完即退)
78
+ async function callMcpTool(serverPath, toolName, args, timeoutMs = 15000) {
79
+ return new Promise((resolvePromise) => {
80
+ const child = spawn(process.execPath, [serverPath], {
81
+ stdio: ["pipe", "pipe", "pipe"],
82
+ windowsHide: true,
83
+ });
84
+ let buf = "";
85
+ let stderr = "";
86
+ const pending = new Map();
87
+ let id = 1;
88
+
89
+ const timer = setTimeout(() => {
90
+ try { child.kill(); } catch {}
91
+ resolvePromise({ ok: false, error: "timeout" });
92
+ }, timeoutMs);
93
+
94
+ child.stdout.on("data", (d) => {
95
+ buf += d.toString();
96
+ let i;
97
+ while ((i = buf.indexOf("\n")) >= 0) {
98
+ const line = buf.slice(0, i);
99
+ buf = buf.slice(i + 1);
100
+ if (!line.trim()) continue;
101
+ try {
102
+ const msg = JSON.parse(line);
103
+ if (msg.id && pending.has(msg.id)) {
104
+ pending.get(msg.id)(msg);
105
+ pending.delete(msg.id);
106
+ }
107
+ } catch {}
108
+ }
109
+ });
110
+ child.stderr.on("data", (d) => { stderr += d.toString(); });
111
+
112
+ const req = (method, params) => new Promise((r) => {
113
+ const rid = id++;
114
+ pending.set(rid, r);
115
+ child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id: rid, method, params }) + "\n");
116
+ });
117
+
118
+ child.on("error", (e) => {
119
+ clearTimeout(timer);
120
+ try { child.kill(); } catch {}
121
+ resolvePromise({ ok: false, error: String(e && e.message ? e.message : e) });
122
+ });
123
+ child.on("exit", () => {
124
+ clearTimeout(timer);
125
+ resolvePromise({ ok: false, error: stderr.slice(-300) || "server exited" });
126
+ });
127
+
128
+ (async () => {
129
+ try {
130
+ await req("initialize", {
131
+ protocolVersion: "2024-11-05",
132
+ capabilities: {},
133
+ clientInfo: { name: "carlos-flow-trigger", version: "1.0.0" },
134
+ });
135
+ const res = await req("tools/call", { name: toolName, arguments: args });
136
+ const text = res?.result?.content?.[0]?.text || "";
137
+ clearTimeout(timer);
138
+ try { child.kill(); } catch {}
139
+ if (res?.result?.isError) {
140
+ resolvePromise({ ok: false, error: String(text).slice(0, 300) });
141
+ } else {
142
+ try {
143
+ resolvePromise({ ok: true, data: JSON.parse(text) });
144
+ } catch {
145
+ resolvePromise({ ok: false, error: "bad json: " + String(text).slice(0, 200) });
146
+ }
147
+ }
148
+ } catch (e) {
149
+ clearTimeout(timer);
150
+ try { child.kill(); } catch {}
151
+ resolvePromise({ ok: false, error: String(e && e.message ? e.message : e) });
152
+ }
153
+ })();
154
+ });
155
+ }
156
+
157
+ // 从 parts 里取出用户消息文本(只看 type==="text" 的部分)
158
+ function extractText(parts) {
159
+ if (!Array.isArray(parts)) return "";
160
+ return parts
161
+ .filter((p) => p && p.type === "text" && typeof p.text === "string")
162
+ .map((p) => p.text)
163
+ .join("\n")
164
+ .trim();
165
+ }
166
+
167
+ export const CarlosFlowTriggerPlugin = async ({ client, $, worktree, directory }) => {
168
+ const serverPath = findMcpServer();
169
+ if (!serverPath) {
170
+ console.error("[carlos-flow-trigger] 未找到 MCP server(src/index.js),自动触发未启用");
171
+ console.error("[carlos-flow-trigger] 请确认已全局安装:npm install -g carlos-flow");
172
+ }
173
+ if (DEBUG) {
174
+ console.error("[carlos-flow-trigger] server:", serverPath, "cwd:", worktree || directory);
175
+ }
176
+
177
+ return {
178
+ "chat.message": async (input, output) => {
179
+ if (!ENABLED) return;
180
+ if (!serverPath) return;
181
+
182
+ const message = extractText(output && output.parts);
183
+ if (!message) return;
184
+
185
+ const sessionId = input.sessionID || "default";
186
+ try {
187
+ const res = await callMcpTool(serverPath, "flow_trigger_check", {
188
+ sessionId,
189
+ message,
190
+ cwd: worktree || directory || process.cwd(),
191
+ });
192
+
193
+ if (!res.ok) {
194
+ if (DEBUG) console.error("[carlos-flow-trigger] 调用失败:", res.error);
195
+ return; // 插件出错绝不阻断用户消息
196
+ }
197
+
198
+ const d = res.data || {};
199
+ if (DEBUG) {
200
+ console.error(
201
+ `[carlos-flow-trigger] decision=${d.decision} score=${d.score} activated=${d.activated}`
202
+ );
203
+ }
204
+ if (d.activated) {
205
+ console.error(
206
+ `[carlos-flow-trigger] 已自动激活 Carlos 工作流(评分 ${d.score})—— ` +
207
+ `请补齐 ${(d.pending_fields || []).join(" / ")} 后再派发`
208
+ );
209
+ }
210
+ } catch (e) {
211
+ if (DEBUG) console.error("[carlos-flow-trigger] 异常:", e && e.message ? e.message : e);
212
+ }
213
+ },
214
+ };
215
+ };
@@ -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);