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.
@@ -0,0 +1,188 @@
1
+ #!/usr/bin/env node
2
+ // check-params.mjs — 「工具参数不得静默失效」门禁
3
+ //
4
+ // 为什么要它:
5
+ // 2026-11-07 的第三方审查发现 flow_audit 的 inputSchema 里声明了 date 参数、
6
+ // 工具描述也写着「可按日期过滤」,但 handler 里算出了 rawDate 却**从未使用**
7
+ // —— 文件路径仍用 localDate()。
8
+ //
9
+ // 这个 bug 的隐蔽之处:它**不报错**、测试也全绿,只是安静地返回错误的数据
10
+ // (传 date=2020-01-01 拿到的是今天的数据)。属于典型的「静默失效」。
11
+ //
12
+ // 本门禁的判定:对每个工具的 inputSchema 声明的每个参数,
13
+ // 断言它在 handler(或该工具直接调用的下游函数)里**真的被读取**。
14
+ //
15
+ // 退出码:0 = 无静默失效;1 = 发现静默失效(逐条打印)
16
+ import { readFileSync } from "node:fs";
17
+ import { resolve, dirname, join } from "node:path";
18
+ import { fileURLToPath } from "node:url";
19
+
20
+ const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
21
+ const read = (p) => { try { return readFileSync(join(ROOT, p), "utf8"); } catch { return null; } };
22
+
23
+ let failed = 0;
24
+ const pass = (m) => console.log(` ✅ ${m}`);
25
+ const fail = (m) => { console.log(` ❌ ${m}`); failed++; };
26
+ const section = (t) => console.log(`\n▶ ${t}`);
27
+
28
+ console.log("=".repeat(72));
29
+ console.log("Carlos Flow · 参数有效性门禁(inputSchema 声明 ↔ handler 实际读取)");
30
+ console.log("=".repeat(72));
31
+
32
+ const indexSrc = read("src/index.js") || "";
33
+ const stateSrc = read("src/state.js") || "";
34
+
35
+ /** 从 src 的第 idx 个字符开始(idx 指向 '{'),返回配对括号内的内容与结束位置 */
36
+ function matchBraces(src, idx) {
37
+ if (src[idx] !== "{") return null;
38
+ let depth = 0;
39
+ for (let i = idx; i < src.length; i++) {
40
+ const c = src[i];
41
+ if (c === "{") depth++;
42
+ else if (c === "}") {
43
+ depth--;
44
+ if (depth === 0) return { body: src.slice(idx + 1, i), end: i };
45
+ }
46
+ }
47
+ return null;
48
+ }
49
+
50
+ /** 抽取 TOOLS 数组内容 */
51
+ function extractTools(src) {
52
+ const arrStart = src.indexOf("const TOOLS = [");
53
+ if (arrStart < 0) return [];
54
+ const arrBody = src.slice(arrStart);
55
+ const end = arrBody.indexOf("\n];");
56
+ const list = arrBody.slice(0, end < 0 ? arrBody.length : end);
57
+
58
+ const tools = [];
59
+ const re = /name:\s*"(flow_[a-z_]+)"/g;
60
+ const marks = [];
61
+ let m;
62
+ while ((m = re.exec(list)) !== null) marks.push({ name: m[1], at: m.index });
63
+ for (let i = 0; i < marks.length; i++) {
64
+ const start = marks[i].at;
65
+ const stop = i + 1 < marks.length ? marks[i + 1].at : list.length;
66
+ const block = list.slice(start, stop);
67
+
68
+ // inputSchema.properties
69
+ const schemaAt = block.indexOf("inputSchema:");
70
+ const schemaOpen = block.indexOf("{", schemaAt);
71
+ const schema = schemaOpen >= 0 ? matchBraces(block, schemaOpen) : null;
72
+ let props = [];
73
+ if (schema) {
74
+ const pAt = schema.body.indexOf("properties:");
75
+ const pOpen = schema.body.indexOf("{", pAt);
76
+ const pBlock = pOpen >= 0 ? matchBraces(schema.body, pOpen) : null;
77
+ if (pBlock) {
78
+ // 只取**顶层**直接子键 —— 嵌套 schema 里的 items / properties / path / line
79
+ // 不是工具参数,误当参数会报一堆假问题。
80
+ props = [];
81
+ const depthOf = (pos) => {
82
+ let d = 0;
83
+ for (let i = 0; i < pos; i++) {
84
+ if (pBlock.body[i] === "{") d++;
85
+ else if (pBlock.body[i] === "}") d--;
86
+ }
87
+ return d;
88
+ };
89
+ const keyRe = /([A-Za-z_][A-Za-z0-9_]*)\s*:\s*\{/g;
90
+ let km;
91
+ while ((km = keyRe.exec(pBlock.body)) !== null) {
92
+ if (depthOf(km.index) === 0) props.push(km[1]);
93
+ }
94
+ }
95
+ }
96
+ // handler 体
97
+ const hAt = block.indexOf("handler:");
98
+ let handler = "";
99
+ if (hAt >= 0) {
100
+ const hOpen = block.indexOf("{", hAt);
101
+ const hBlock = hOpen >= 0 ? matchBraces(block, hOpen) : null;
102
+ handler = hBlock ? hBlock.body : block.slice(hAt);
103
+ }
104
+ tools.push({ name: marks[i].name, props, handler });
105
+ }
106
+ return tools;
107
+ }
108
+
109
+ /** 抽取具名函数的函数体 */
110
+ function extractFunction(src, name) {
111
+ const at = src.indexOf(`function ${name}(`);
112
+ if (at < 0) return null;
113
+ // 跳过参数列表(`opts = {}` 里也有花括号,不能当函数体起点)
114
+ let i = src.indexOf("(", at);
115
+ let depth = 0;
116
+ let open = -1;
117
+ for (; i < src.length; i++) {
118
+ const c = src[i];
119
+ if (c === "(") depth++;
120
+ else if (c === ")") {
121
+ depth--;
122
+ if (depth === 0) { i++; break; }
123
+ }
124
+ }
125
+ while (i < src.length && src[i] !== "{") i++;
126
+ open = i;
127
+ const b = open >= 0 ? matchBraces(src, open) : null;
128
+ return b ? b.body : null;
129
+ }
130
+
131
+ const tools = extractTools(indexSrc);
132
+ section(`共解析到 ${tools.length} 个工具`);
133
+
134
+ // ---- 逐工具逐参数检查 ----
135
+ const IGNORE = new Set(["sessionId", "cwd"]); // 有明确通用处理,但仍确认被读
136
+ for (const t of tools) {
137
+ if (!t.props.length) continue;
138
+ const unused = [];
139
+ for (const p of t.props) {
140
+ const used = new RegExp(`\\b${p}\\b`).test(t.handler);
141
+ if (!used) unused.push(p);
142
+ }
143
+ if (unused.length) {
144
+ fail(`工具 ${t.name}:inputSchema 声明了但 handler 从未读取 → ${unused.join(", ")}`);
145
+ }
146
+ }
147
+ if (!failed) pass("所有工具的 inputSchema 参数都在 handler 里被真实读取");
148
+
149
+ // ---- 专项:state.js 里「算出来却没用」的死变量 ----
150
+ section("死变量检测(算出却从未使用)");
151
+ for (const [file, src] of [["src/state.js", stateSrc], ["src/index.js", indexSrc]]) {
152
+ const deadVars = [];
153
+ const re = /^[ \t]*const\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*=/gm;
154
+ let m;
155
+ while ((m = re.exec(src)) !== null) {
156
+ const name = m[1];
157
+ if (["i", "j", "k", "n", "r", "t", "e", "a", "b", "c", "d", "f", "s", "v", "x", "y"].includes(name)) continue;
158
+ // 取该变量所在语句的结束位置
159
+ let stmtEnd = src.indexOf(";", m.index);
160
+ if (stmtEnd < 0) continue;
161
+ const after = src.slice(stmtEnd + 1);
162
+ if (!new RegExp(`\\b${name}\\b`).test(after)) deadVars.push(name);
163
+ }
164
+ if (deadVars.length) {
165
+ fail(`${file}:存在「算出却从未使用」的死变量 → ${deadVars.join(", ")}`);
166
+ }
167
+ }
168
+ if (!failed) pass("没有「算出却从未使用」的死变量");
169
+
170
+ // ---- 专项:opts.date 必须在下游真的用上 ----
171
+ section("date 参数贯通检查");
172
+ const readAuditBody = extractFunction(stateSrc, "readAudit");
173
+ const verifyBody = extractFunction(stateSrc, "verifyAuditChain");
174
+ const usesDate = (b) => b && /rawDate[}`]*\.jsonl/.test(b);
175
+ if (usesDate(readAuditBody)) pass("readAudit 用 rawDate 构造文件路径");
176
+ else fail("readAudit 没有用 rawDate 构造文件路径(date 参数静默失效)");
177
+ if (usesDate(verifyBody)) pass("verifyAuditChain 用 rawDate 构造文件路径");
178
+ else fail("verifyAuditChain 没有用 rawDate 构造文件路径(date 参数静默失效)");
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);
@@ -70,54 +70,54 @@ const MUTANTS = [
70
70
  from: ` ...(!cardHasScope ? ["scope"] : []),`,
71
71
  to: ` ...(false ? ["scope"] : []), // MUTANT: scope 未补也不算缺`,
72
72
  },
73
- {
74
- id: "M6-半补齐绕过闸门",
75
- desc: "已激活会话改成「只要提交就解闸」(移除幂等派生)",
76
- file: "src/index.js",
77
- // 锚点必须**唯一且足够长**:曾经 M6/M9 共用同一段 from,
78
- // 该段一改缩进/注释 → 两个变异体同时 SKIP(变异测试失去守护却仍报 13/13)。
79
- // 现在带上 else-if 分支的专属上下文。
80
- from: ` } else if (wasActivatedBefore) {
81
- // 该会话开过占位卡:继续按**当前卡片实际缺什么**锁定。
82
- // 幂等派生(而不是「上一轮 pending 传递」),所以即使并发丢更新,
83
- // 落盘的 pending 永远与同一份落盘卡片一致,不会出现「卡片空却 pending=[]」。
84
- activationPending = currentMissing;
85
- } else {`,
86
- to: ` } else if (wasActivatedBefore) {
87
- // 该会话开过占位卡:继续按**当前卡片实际缺什么**锁定。
88
- // 幂等派生(而不是「上一轮 pending 传递」),所以即使并发丢更新,
89
- // 落盘的 pending 永远与同一份落盘卡片一致,不会出现「卡片空却 pending=[]」。
90
- activationPending = []; // MUTANT: 只要提交就解闸
91
- } else {`,
92
- },
93
- {
94
- id: "M9-闸门派生回退",
95
- desc: "把「普通卡分支」的待补项改回上一轮 pending 传递(并发丢更新时会失效)",
96
- file: "src/index.js",
97
- // 锚点与 M6 区分:M6 改「已激活会话」的赋值,M9 改「普通卡」分支的赋值。
98
- from: ` } else {
99
- // 普通卡(未标 activation,且本会话从未激活过):不上闸门。
100
- // 档位必填项已由 validateCard 按 tier 强制(read_only 只要 goal+quote),
101
- // 此处再加闸门会误伤 T1 只读调研。
102
- activationPending = [];`,
103
- to: ` } else {
104
- // 普通卡(未标 activation,且该会话从未激活过):不上闸门。
105
- // 档位必填项已由 validateCard 按 tier 强制(read_only 只要 goal+quote),
106
- // 此处再加闸门会误伤 T1 只读调研。
107
- activationPending = prevPendingBefore; // MUTANT: 回退到状态传递`,
108
- },
109
- {
110
- id: "M10-普通卡也上闸",
111
- desc: "普通卡(无 activation 且此前未被锁)也被上闸 —— 会误伤 T1 只读调研",
112
- file: "src/index.js",
113
- // 锚点从 2 行加长到 4 行:原来的 from 过短,任何相邻代码改动都可能连带改写它。
114
- from: ` // 此处再加闸门会误伤 T1 只读调研。
115
- activationPending = [];
116
- }`,
117
- to: ` // 此处再加闸门会误伤 T1 只读调研。
118
- activationPending = currentMissing; // MUTANT: 普通卡也上闸
119
- }`,
120
- },
73
+ {
74
+ id: "M6-半补齐绕过闸门",
75
+ desc: "已激活会话改成「只要提交就解闸」(移除幂等派生)",
76
+ file: "src/index.js",
77
+ // 锚点必须**唯一且足够长**:曾经 M6/M9 共用同一段 from,
78
+ // 该段一改缩进/注释 → 两个变异体同时 SKIP(变异测试失去守护却仍报 13/13)。
79
+ // 现在带上 else-if 分支的专属上下文。
80
+ from: ` } else if (wasActivatedBefore) {
81
+ // 该会话开过占位卡:继续按**当前卡片实际缺什么**锁定。
82
+ // 幂等派生(而不是「上一轮 pending 传递」),所以即使并发丢更新,
83
+ // 落盘的 pending 永远与同一份落盘卡片一致,不会出现「卡片空却 pending=[]」。
84
+ activationPending = currentMissing;
85
+ } else {`,
86
+ to: ` } else if (wasActivatedBefore) {
87
+ // 该会话开过占位卡:继续按**当前卡片实际缺什么**锁定。
88
+ // 幂等派生(而不是「上一轮 pending 传递」),所以即使并发丢更新,
89
+ // 落盘的 pending 永远与同一份落盘卡片一致,不会出现「卡片空却 pending=[]」。
90
+ activationPending = []; // MUTANT: 只要提交就解闸
91
+ } else {`,
92
+ },
93
+ {
94
+ id: "M9-闸门派生回退",
95
+ desc: "把「普通卡分支」的待补项改回上一轮 pending 传递(并发丢更新时会失效)",
96
+ file: "src/index.js",
97
+ // 锚点与 M6 区分:M6 改「已激活会话」的赋值,M9 改「普通卡」分支的赋值。
98
+ from: ` } else {
99
+ // 普通卡(未标 activation,且本会话从未激活过):不上闸门。
100
+ // 档位必填项已由 validateCard 按 tier 强制(read_only 只要 goal+quote),
101
+ // 此处再加闸门会误伤 T1 只读调研。
102
+ activationPending = [];`,
103
+ to: ` } else {
104
+ // 普通卡(未标 activation,且该会话从未激活过):不上闸门。
105
+ // 档位必填项已由 validateCard 按 tier 强制(read_only 只要 goal+quote),
106
+ // 此处再加闸门会误伤 T1 只读调研。
107
+ activationPending = prevPendingBefore; // MUTANT: 回退到状态传递`,
108
+ },
109
+ {
110
+ id: "M10-普通卡也上闸",
111
+ desc: "普通卡(无 activation 且此前未被锁)也被上闸 —— 会误伤 T1 只读调研",
112
+ file: "src/index.js",
113
+ // 锚点从 2 行加长到 4 行:原来的 from 过短,任何相邻代码改动都可能连带改写它。
114
+ from: ` // 此处再加闸门会误伤 T1 只读调研。
115
+ activationPending = [];
116
+ }`,
117
+ to: ` // 此处再加闸门会误伤 T1 只读调研。
118
+ activationPending = currentMissing; // MUTANT: 普通卡也上闸
119
+ }`,
120
+ },
121
121
  {
122
122
  id: "M11-占位卡硬编码三项",
123
123
  desc: "占位卡待补项退回硬编码三项(服务端派生失效)",
@@ -143,6 +143,42 @@ const MUTANTS = [
143
143
  to: ` const hasMutating = mut.some((w) => s.includes(String(w).toLowerCase()));
144
144
  return true; // MUTANT: 无视改动动词`,
145
145
  },
146
+ {
147
+ id: "M14-审计链断链",
148
+ desc: "审计链去掉 prevHash 链接(每条记录各自独立哈希 → 删改中间记录也不会被发现)",
149
+ file: "src/state.js",
150
+ from: ` rec.prevHash = prev;
151
+ rec.hash = computeAuditHash(rec, prev);`,
152
+ to: ` rec.prevHash = prev;
153
+ rec.hash = computeAuditHash(rec, ""); // MUTANT: 断开链式链接`,
154
+ },
155
+ {
156
+ id: "M15-审计链校验恒真",
157
+ desc: "verifyAuditChain 永远返回 ok:true → 任何篡改都发现不了",
158
+ file: "src/state.js",
159
+ from: ` return { ok: broken === 0, total, broken, legacy, brokenAt, file, mode: auditHashMode() };`,
160
+ to: ` return { ok: true, total, broken, legacy, brokenAt, file, mode: auditHashMode() }; // MUTANT: 恒真`,
161
+ },
162
+ {
163
+ id: "M16-越界检查退回 fail-open",
164
+ desc: "enforceScope 遇到任何越界都返回 ok:true → 越界改动直接放行",
165
+ file: "src/dispatch.js",
166
+ from: ` if (violations.length > 0) {
167
+ return { ok: false, violations, checked: diffFiles.slice(), message: \`越界改动(超出 scope):\${violations.join(", ")}\` };
168
+ }`,
169
+ to: ` if (violations.length > 0) {
170
+ return { ok: true, violations, checked: diffFiles.slice(), message: \`越界改动(超出 scope):\${violations.join(", ")}\` }; // MUTANT: fail-open
171
+ }`,
172
+ },
173
+ {
174
+ id: "M17-date 参数失效",
175
+ desc: "readAudit 用 localDate() 代替 rawDate → date 参数静默失效(读到的永远是今天)",
176
+ file: "src/state.js",
177
+ from: ` // ⚠️ 必须用 rawDate(而不是 localDate())—— 否则 opts.date 完全失效。
178
+ const file = path.join(AUDIT_DIR, \`\${rawDate}.jsonl\`);`,
179
+ to: ` // MUTANT: 用回 localDate() → date 参数静默失效
180
+ const file = path.join(AUDIT_DIR, \`\${localDate()}.jsonl\`);`,
181
+ },
146
182
  {
147
183
  id: "M7-空scope fail-open",
148
184
  desc: "enforceScope 在空 scope 时直接返回 ok:true(任意路径都算未越界)",
@@ -151,6 +187,7 @@ const MUTANTS = [
151
187
  return {
152
188
  ok: false,
153
189
  violations: diffFiles.slice(),
190
+ checked: diffFiles.slice(),
154
191
  message: \`越界改动(卡片 scope 为空,不允许修改任何文件):\${diffFiles.join(", ")}\`,
155
192
  };
156
193
  }`,
@@ -264,7 +301,7 @@ const SRC_BRIDGES = new Set(bridgePidFiles(SRC));
264
301
  // 导致套件启动失败/结果失真(表现为 concurrency 套件输出异常)。
265
302
  const PORT_BASE = Number(process.env.MUTATION_PORT_BASE || 20100);
266
303
 
267
- const base = sh("npm run test:e2e 2>&1; echo E2E_EXIT=$?; npm run test:trigger 2>&1; echo TR_EXIT=$?; npm run test:concurrency 2>&1; echo CONC_EXIT=$?", SRC, {
304
+ const base = sh("npm run test:e2e 2>&1; echo E2E_EXIT=$?; npm run test:trigger 2>&1; echo TR_EXIT=$?; npm run test:concurrency 2>&1; echo CONC_EXIT=$?; npm run test:scope 2>&1; echo SCOPE_EXIT=$?; npm run test:audit 2>&1; echo AUDIT_EXIT=$?", SRC, {
268
305
  CARLOS_FLOW_HOME: join(tmpdir(), "carlos-flow-mutant-home", "base"),
269
306
  });
270
307
  const baseE2e = /════ 结果: (\d+) 通过 \/ (\d+) 失败/.exec(base);
@@ -359,7 +396,7 @@ for (const [mi, m] of MUTANTS.entries()) {
359
396
  }
360
397
  writeFileSync(target, mutated, "utf8");
361
398
 
362
- const out = sh("npm run test:e2e 2>&1; echo E2E_EXIT=$?; npm run test:trigger 2>&1; echo TR_EXIT=$?; npm run test:concurrency 2>&1; echo CONC_EXIT=$?", workDir, {
399
+ const out = sh("npm run test:e2e 2>&1; echo E2E_EXIT=$?; npm run test:trigger 2>&1; echo TR_EXIT=$?; npm run test:concurrency 2>&1; echo CONC_EXIT=$?; npm run test:scope 2>&1; echo SCOPE_EXIT=$?; npm run test:audit 2>&1; echo AUDIT_EXIT=$?", workDir, {
363
400
  CARLOS_FLOW_HOME: join(tmpdir(), "carlos-flow-mutant-home", m.id.replace(/[^A-Za-z0-9]/g, "_")),
364
401
  // 每个变异体用**独立端口**:否则会复用上一轮副本拉起的旧 bridge,
365
402
  // 旧 bridge 内存里跑的是旧代码 → 测试结果失真(可能假绿 / 假红)。
@@ -376,6 +413,10 @@ for (const [mi, m] of MUTANTS.entries()) {
376
413
  if (!e2eFail) unparsed.push("e2e");
377
414
  if (!trFail) unparsed.push("trigger");
378
415
  if (!concFail) unparsed.push("concurrency");
416
+ const scopeOut = out.slice(out.lastIndexOf("越界拦截真实验证"));
417
+ const auditOut = out.slice(out.lastIndexOf("审计链篡改检测验证"));
418
+ if (!/════ 结果: \d+ 通过 \/ \d+ 失败/.test(scopeOut)) unparsed.push("scope");
419
+ if (!/════ 结果: \d+ 通过 \/ \d+ 失败/.test(auditOut)) unparsed.push("audit");
379
420
  if (unparsed.length) {
380
421
  lines.push(`## ${m.id}`);
381
422
  lines.push("");
@@ -394,7 +435,9 @@ for (const [mi, m] of MUTANTS.entries()) {
394
435
  const caught =
395
436
  (e2eFail && Number(e2eFail[2]) > 0) ||
396
437
  (trFail && Number(trFail[3]) > 0) ||
397
- (concFail && Number(concFail[2]) > 0);
438
+ (concFail && Number(concFail[2]) > 0) ||
439
+ /SCOPE_EXIT=[1-9]/.test(out) ||
440
+ /AUDIT_EXIT=[1-9]/.test(out);
398
441
  const verdict = caught ? "CAUGHT ✅" : "NOT CAUGHT ❌";
399
442
  results.push({
400
443
  ...m,
package/src/dispatch.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // dispatch.js — Carlos 工作流:四段合同 prompt / 文件快照 / opencode 子进程 / 验证执行 / scope 校验(Node ESM)
2
2
  import fs from "node:fs";
3
3
  import path from "node:path";
4
- import { spawn } from "node:child_process";
4
+ import { spawn, spawnSync } from "node:child_process";
5
5
  import { createHash } from "node:crypto";
6
6
  import { RUNS_DIR, sanitizeId } from "./state.js";
7
7
 
@@ -178,6 +178,30 @@ export async function runVerifyCommand(cmd, cwd) {
178
178
  if (!cmd || !cmd.trim()) {
179
179
  return { ok: false, exitCode: -1, stdout: "", stderr: "验证命令为空" };
180
180
  }
181
+ // 可选:拦截高危命令模式。
182
+ //
183
+ // 威胁模型说明(重要,不要夸大):
184
+ // · verify.cmd 本质上就是「执行用户指定的验证命令」—— 它的设计目标就是能跑任意命令
185
+ // (`npm test` / `pytest` / `cargo build` …),所以**默认不拦**。
186
+ // · 真正的风险来源是「verify.cmd 的来源可信度」:
187
+ // - 人工填写的任务卡 → 可信,是用户/Agent 的本意
188
+ // - 自动激活产生的占位卡 → activation 时 scope/acceptance 为空、**没有 verify.cmd**,
189
+ // 必须人工补齐才能过闸门 → 自动触发路径已被 activation 闸门挡住
190
+ // · 因此默认不拦是对的;把黑名单默认打开会误伤合法脚本
191
+ // (比如 `rm -rf node_modules` 出现在清理步骤里是完全合法的)。
192
+ // · 需要更严的用户可以打开 CARLOS_FLOW_BLOCK_DANGEROUS=1。
193
+ if (process.env.CARLOS_FLOW_BLOCK_DANGEROUS === "1") {
194
+ const dangerous = /\b(rm\s+-[rRf]{1,2}[^\s]*\s+\/|sudo\s|curl\s+[^|]*\|\s*(ba)?sh|mkfs(\.|\s)|dd\s+if=|:\(\)\{|>\s*\/dev\/sd[a-z])/i;
195
+ if (dangerous.test(cmd)) {
196
+ return {
197
+ ok: false,
198
+ exitCode: -1,
199
+ stdout: "",
200
+ stderr: `验证命令包含高危模式,已拒绝执行:${cmd}\n` +
201
+ "(CARLOS_FLOW_BLOCK_DANGEROUS=1 已开启;确认该命令安全后可关闭此开关)",
202
+ };
203
+ }
204
+ }
181
205
  const isWindows = process.platform === "win32";
182
206
  const shell = isWindows ? process.env.COMSPEC || "cmd.exe" : "/bin/sh";
183
207
  const shellArgs = isWindows ? ["/c", cmd] : ["-c", cmd];
@@ -208,10 +232,43 @@ export async function runVerifyCommand(cmd, cwd) {
208
232
  }
209
233
 
210
234
  // Phase 1-1: scope 机器校验 - 对比 diff 与 card.scope
211
- export function enforceScope(scope, diffFiles) {
235
+ //
236
+ // 用法:enforceScope(scope, cwd, diffFiles?)
237
+ // - scope: 卡片中的 scope 白名单
238
+ // - cwd: 仓库根目录(用于跑 git diff)
239
+ // - diffFiles?: 可选,外部传入的改动文件列表;不传则自动跑 `git diff --name-only`
240
+ // 返回:{ ok, violations[], message? }
241
+ //
242
+ // 设计:
243
+ // · 空 scope = 白名单为空 = fail-closed(所有变更都算越界)
244
+ // · 无变更(diffFiles 为空)= 直接 ok
245
+ // · 自动跑 `git diff --name-only`:派发前快照 vs 当前工作区
246
+ // · 精确匹配 + 父目录匹配:scope 内文件及其子目录均算通过
247
+ export function enforceScope(scope, cwd, diffFiles) {
248
+ // diffFiles 可选:外部传入的改动文件列表;不传则自动跑 `git diff --name-only`
249
+ // cwd: 仓库根目录(用于跑 git diff)
250
+ let autoCollected = false;
251
+ if (!diffFiles) {
252
+ autoCollected = true;
253
+ diffFiles = [];
254
+ try {
255
+ const proc = spawnSync("git", ["diff", "--name-only"], {
256
+ cwd: cwd || process.cwd(),
257
+ encoding: "utf8",
258
+ // git 不在 PATH / 不是仓库 / 超时 → 一律当作「无改动」而非抛错,
259
+ // 避免把环境问题变成门禁误报(fail-closed 只针对 scope 语义,不针对环境)
260
+ timeout: 10000,
261
+ windowsHide: true,
262
+ });
263
+ if (proc.status === 0 && typeof proc.stdout === "string") {
264
+ diffFiles = proc.stdout.split("\n").map((s) => s.trim()).filter(Boolean);
265
+ }
266
+ } catch { diffFiles = []; }
267
+ }
268
+
212
269
  // 没有任何变更 → 无需判定
213
270
  if (!Array.isArray(diffFiles) || diffFiles.length === 0) {
214
- return { ok: true, violations: [] };
271
+ return { ok: true, violations: [], checked: [] };
215
272
  }
216
273
 
217
274
  // 空 scope = 白名单为空 = **不允许改动任何文件**。
@@ -221,6 +278,7 @@ export function enforceScope(scope, diffFiles) {
221
278
  return {
222
279
  ok: false,
223
280
  violations: diffFiles.slice(),
281
+ checked: diffFiles.slice(),
224
282
  message: `越界改动(卡片 scope 为空,不允许修改任何文件):${diffFiles.join(", ")}`,
225
283
  };
226
284
  }
@@ -245,8 +303,8 @@ export function enforceScope(scope, diffFiles) {
245
303
  }
246
304
 
247
305
  if (violations.length > 0) {
248
- return { ok: false, violations, message: `越界改动(超出 scope):${violations.join(", ")}` };
306
+ return { ok: false, violations, checked: diffFiles.slice(), message: `越界改动(超出 scope):${violations.join(", ")}` };
249
307
  }
250
- return { ok: true };
308
+ return { ok: true, violations: [], checked: diffFiles.slice() };
251
309
  }
252
310
 
package/src/index.js CHANGED
@@ -2,13 +2,14 @@
2
2
  // Carlos 工作流的机械门禁工具集(留痕 / 派发 / 裁定 / 审计 / 快照还原计划)。
3
3
  // 重要:stdout 是 MCP 传输通道,所有日志一律走 stderr。
4
4
  import { spawnSync } from "node:child_process";
5
+ import path from "node:path";
5
6
  import { createServer, connect } from "node:net";
6
7
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
7
8
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
8
9
  import { ListToolsRequestSchema, CallToolRequestSchema } from "@modelcontextprotocol/sdk/types.js";
9
10
  import { PROTOCOL } from "./protocol.js";
10
11
  import { parseCard, validateCard, riskTier, isSensitive } from "./card.js";
11
- import { loadState, saveState, defaultState, audit, readAudit, getUserMessages, writeUserMessage, pathExists, gitHead, isStale, isBypassed, verifyAuditChain, withStateLock } from "./state.js";
12
+ import { loadState, saveState, defaultState, audit, readAudit, getUserMessages, writeUserMessage, pathExists, gitHead, isStale, isBypassed, verifyAuditChain, withStateLock, auditHashMode } from "./state.js";
12
13
  import { buildContractPrompt, snapshotFiles, readManifest, readManifestAll, writeDispatchPrompt, saveAgentResult, runVerifyCommand, enforceScope, MAX_DISPATCH } from "./dispatch.js";
13
14
 
14
15
  const log = (msg) => {
@@ -313,7 +314,6 @@ const TOOLS = [
313
314
  properties: {
314
315
  sessionId: { type: "string", description: "会话 ID,默认 unknown" },
315
316
  role: { type: "string", enum: ["executor", "auditor"], description: "领取角色" },
316
- cwd: { type: "string", description: "工作目录,默认 process.cwd()" },
317
317
  },
318
318
  },
319
319
  handler: async (args) => {
@@ -431,6 +431,25 @@ const TOOLS = [
431
431
  const entries = snapshotFiles(sessionId, scope, cwd);
432
432
  audit("run", sessionId, { kind: "snapshot", role, files: scope.length, ok: true });
433
433
 
434
+ // Phase 1-1: 记录「派发前基线」。
435
+ //
436
+ // 为什么是记录而不是当场阻断:
437
+ // 派发这一刻,子 Agent **还没动手** —— 它之后会改哪些文件根本无从得知。
438
+ // 此时跑 git diff 得到的是「用户自己已有的未提交改动」,
439
+ // 拿它当越界拦下来会**误伤正常用法**(用户本来就在改这些文件)。
440
+ //
441
+ // 正确的时机是**裁定前**:用「当前改动 - 派发基线」算出**本次执行引入的**
442
+ // 改动,再与卡片 scope 比对 —— 这才是「越界直接阻断」的真实落点,
443
+ // 阻断的是「越界之后仍然拿到 PASS」这个闭环。
444
+ const baseline = enforceScope(scope, cwd);
445
+ state.dispatch_baseline = Array.isArray(baseline.checked) ? baseline.checked : [];
446
+ saveState(sessionId, state);
447
+ audit("run", sessionId, {
448
+ kind: "dispatch_baseline",
449
+ role,
450
+ files: state.dispatch_baseline.length,
451
+ });
452
+
434
453
  if (a.run === true) {
435
454
  // 写入 prompt 文件,供主 Agent 读取后通过 subagent 工具派发
436
455
  const { file } = writeDispatchPrompt(sessionId, role, prompt, cwd);
@@ -557,6 +576,36 @@ const TOOLS = [
557
576
  return fail("已有的验证结果对应的命令与当前卡片的 verify.cmd 不一致,不能记录 PASS 裁定。" +
558
577
  "请对当前卡片重新执行 flow_run_verify,再记录裁定。");
559
578
  }
579
+
580
+ // 防假闭环之四:越界改动必须被拦住。
581
+ //
582
+ // 「越界直接阻断」的**真实落点**在这里:判定「本次执行有没有改到
583
+ // scope 之外的文件」,而不是「派发前工作区干不干净」。
584
+ //
585
+ // 做法:拿「当前 git 改动清单」减去「派发时记录的基线」,
586
+ // 剩下的就是**本次执行引入的**改动 —— 用户自己原有的未提交改动
587
+ // 不会被误判为越界。
588
+ //
589
+ // 无基线(未走过 flow_dispatch)时退化为「全量改动」判定:
590
+ // 此时没有参照点,用全量更保守(fail-closed)。
591
+ const scopeNow = Array.isArray(state.card.scope) ? state.card.scope : [];
592
+ const current = enforceScope(scopeNow, a.cwd || process.cwd());
593
+ const baseline = Array.isArray(state.dispatch_baseline) ? state.dispatch_baseline : [];
594
+ const baselineSet = new Set(baseline.map((f) => path.normalize(f)));
595
+ const introduced = (current.checked || []).filter((f) => !baselineSet.has(path.normalize(f)));
596
+ const scopeCheck = enforceScope(scopeNow, a.cwd || process.cwd(), introduced);
597
+ if (!scopeCheck.ok) {
598
+ audit("decision", sessionId, {
599
+ kind: "scope_violation",
600
+ reason: "越界改动",
601
+ violations: scopeCheck.violations,
602
+ introduced: introduced.length,
603
+ });
604
+ return fail("检测到越界改动,不能记录 PASS 裁定:" +
605
+ (scopeCheck.violations || []).join(", ") +
606
+ "。这些文件不在卡片 scope 白名单内。" +
607
+ "请把越界文件加入 scope(重新提交任务卡)后重试,或先撤销这些改动。");
608
+ }
560
609
  }
561
610
 
562
611
  const findings = [];
@@ -666,7 +715,7 @@ const TOOLS = [
666
715
  chainResult = verifyAuditChain(opts);
667
716
  }
668
717
 
669
- return ok({ total: rows.length, by_type, by_kind, events: rows, chain: chainResult });
718
+ return ok({ total: rows.length, by_type, by_kind, events: rows, chain: chainResult, mode: auditHashMode() });
670
719
  } catch (e) {
671
720
  return fail(e && e.message ? e.message : String(e));
672
721
  }
@@ -859,7 +908,6 @@ const TOOLS = [
859
908
  type: "object",
860
909
  properties: {
861
910
  sessionId: { type: "string", description: "会话 ID,默认 unknown" },
862
- cwd: { type: "string", description: "工作目录,默认 process.cwd()" },
863
911
  },
864
912
  },
865
913
  handler: async (args) => {
@@ -958,9 +1006,13 @@ const TOOLS = [
958
1006
 
959
1007
  const scope = Array.isArray(state.card.scope) ? state.card.scope : [];
960
1008
  const paths = Array.isArray(a.paths) ? a.paths : [];
961
- const result = enforceScope(scope, a.paths, a.cwd);
1009
+ // 不传 paths → 自动跑 `git diff --name-only` 取当前实际改动清单。
1010
+ // 传了 paths → 用调用方给的清单(自查场景)。
1011
+ const result = paths.length
1012
+ ? enforceScope(scope, a.cwd, paths)
1013
+ : enforceScope(scope, a.cwd);
962
1014
 
963
- return ok({ ok: result.ok, scope, checked: a.paths, ...result });
1015
+ return ok({ ok: result.ok, scope, checked: paths.length ? paths : result.checked || [], ...result });
964
1016
  } catch (e) {
965
1017
  return fail(e && e.message ? e.message : String(e));
966
1018
  }
@@ -1085,7 +1137,6 @@ const TOOLS = [
1085
1137
  const tier = riskTier(card.scope);
1086
1138
  const withLock = withStateLock(sessionId, () => {
1087
1139
  const prev = loadState(sessionId);
1088
- const wasActivated = prev.activation_activated === true;
1089
1140
  const state = {
1090
1141
  ...defaultState(),
1091
1142
  ...prev,
@@ -1141,20 +1192,14 @@ server.setRequestHandler(ListToolsRequestSchema, async () => ({
1141
1192
  tools: TOOLS.map((t) => ({ name: t.name, description: t.description, inputSchema: t.inputSchema })),
1142
1193
  }));
1143
1194
 
1144
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
1145
- const t = TOOLS.find((x) => x.name === request.params.name);
1146
- if (!t) {
1147
- return { content: [{ type: "text", text: "Unknown tool: " + request.params.name }], isError: true };
1148
- }
1149
- try {
1150
- return await t.handler(request.params.arguments || {});
1151
- } catch (e) {
1152
- return {
1153
- content: [{ type: "text", text: "ERROR: " + (e && e.message ? e.message : String(e)) }],
1154
- isError: true,
1155
- };
1156
- }
1157
- });
1195
+ // ⚠️ 这里曾经**重复注册**过一次 CallToolRequestSchema(另一个不带参数校验的版本)。
1196
+ // MCP SDK 的 setRequestHandler 用 Map.set → 后注册的覆盖先注册的,
1197
+ // 于是先注册的那个(含约 17 行)**永远不会执行** —— 当前行为是对的,
1198
+ // 但它靠的是「注册顺序」这种隐式约定:任何一次重排或插入都会静默
1199
+ // 丢掉参数校验(required 字段 / 类型 / enum 全部失效)。
1200
+ // 现在只保留下面那一个带 validateToolArgs 的注册。
1201
+ //
1202
+ // check:no-dead-handler 门禁会统计同一 schema 的注册次数,>1 即红。
1158
1203
 
1159
1204
  // ---- Phase 1-1: 工具参数校验器(required 字段 / 类型 / enum)----
1160
1205
  function validateToolArgs(toolName, args) {