carlos-flow 2.7.0 → 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.
package/src/dispatch.js CHANGED
@@ -1,310 +1,451 @@
1
- // dispatch.js — Carlos 工作流:四段合同 prompt / 文件快照 / opencode 子进程 / 验证执行 / scope 校验(Node ESM)
2
- import fs from "node:fs";
3
- import path from "node:path";
4
- import { spawn, spawnSync } from "node:child_process";
5
- import { createHash } from "node:crypto";
6
- import { RUNS_DIR, sanitizeId } from "./state.js";
7
-
8
- export const MAX_DISPATCH = 5;
9
-
10
- // role ∈ "executor" | "auditor"
11
- export function buildContractPrompt(role, card, extra) {
12
- const isAuditor = role === "auditor";
13
- const isExecutor = role === "executor";
14
- if (!isAuditor && !isExecutor) {
15
- throw new Error(`buildContractPrompt: 未知 role "${role}"(仅支持 executor/auditor)`);
16
- }
17
- const c = card && typeof card === "object" ? card : {};
18
-
19
- const objective = `objective: ${c.goal || ""}`;
20
-
21
- const outputFormat = isExecutor
22
- ? "output format: 报告 ≤300 字,四段:结论(一句话,做完/没做完) / 改动(file:line 逐条列出,没改写“无”) / 验证(命令 → 结果摘要,未跑写“未验证”) / 遗留风险"
23
- : "output format: 报告 ≤200 字,五段:裁定(通过/不通过) / 失败类型(操作错误/环境问题/卡片问题) / scope 标注(是否越界改动) / 证据(file:line 或实跑命令输出) / 附注";
24
-
25
- const verifyCmd = c.verify && c.verify.cmd ? String(c.verify.cmd) : "";
26
- let guidance = verifyCmd || "未指定验证命令,用只读取证";
27
- if (isAuditor) {
28
- guidance += ";独立跑 git status --porcelain 与 git diff 取证,不轻信 executor 自述";
29
- }
30
- const toolGuidance = `tool guidance: ${guidance}`;
31
-
32
- const scopeArr = Array.isArray(c.scope) ? c.scope.map(String) : [];
33
- let boundaries;
34
- if (isAuditor) {
35
- boundaries = "零文件改动,只读取证";
36
- } else {
37
- boundaries = scopeArr.length > 0 ? scopeArr.join(", ") : "无文件可改,只读任务";
38
- }
39
- const taskBoundaries = `task boundaries: ${boundaries}`;
40
-
41
- let prompt = [objective, outputFormat, toolGuidance, taskBoundaries].join("\n");
42
- if (extra && String(extra) !== "") {
43
- prompt += "\n\n" + String(extra); // 原样附在末尾
44
- }
45
- return prompt;
46
- }
47
-
48
- // 快照:存在→复制到 RUNS_DIR/<id>/backup/<ts>_<name>;不存在→created:true;复制失败→error 且不中断其余
49
- export function snapshotFiles(sid, paths, cwd) {
50
- const bdir = path.join(RUNS_DIR, sanitizeId(sid), "backup");
51
- fs.mkdirSync(bdir, { recursive: true });
52
- const entries = [];
53
- const list = Array.isArray(paths) ? paths : [];
54
- for (const p of list) {
55
- const ts = new Date().toISOString();
56
- const orig = path.isAbsolute(p) ? p : path.join(cwd || process.cwd(), p);
57
- if (!fs.existsSync(orig)) {
58
- entries.push({ ts, orig, backup: null, created: true });
59
- continue;
60
- }
61
- try {
62
- // 生成随机后缀(确保是字符串)
63
- const randSuffix = Math.random().toString(36).slice(2, 10) + Math.random().toString(36).slice(2, 10);
64
- const backup = path.join(bdir, `${Date.now()}_${randSuffix}_${path.basename(orig)}`);
65
- fs.copyFileSync(orig, backup);
66
- // 完整性校验:比较大小
67
- const srcStat = fs.statSync(orig);
68
- const bakStat = fs.statSync(backup);
69
- if (srcStat.size !== bakStat.size) {
70
- fs.unlinkSync(backup);
71
- entries.push({ ts, orig, error: "完整性校验失败(大小不匹配)" });
72
- } else {
73
- entries.push({ ts, orig, backup, created: false });
74
- }
75
- } catch (e) {
76
- entries.push({ ts, orig, error: String(e) });
77
- }
78
- }
79
- try {
80
- const lines = entries.map((x) => JSON.stringify(x)).join("\n") + "\n";
81
- fs.appendFileSync(path.join(RUNS_DIR, sanitizeId(sid), "backup", "manifest.jsonl"), lines, "utf8");
82
- } catch (e) {
83
- try {
84
- process.stderr.write(`[flow-snapshot] manifest 追加失败: ${e && e.message ? e.message : e}\n`);
85
- } catch {}
86
- }
87
- return entries;
88
- }
89
-
90
- export function readManifest(sid) {
91
- const file = path.join(RUNS_DIR, sanitizeId(sid), "backup", "manifest.jsonl");
92
- try {
93
- const raw = fs.readFileSync(file, "utf8");
94
- const all = [];
95
- for (const line of raw.split("\n")) {
96
- const t = line.trim();
97
- if (!t) continue;
98
- try {
99
- all.push(JSON.parse(t));
100
- } catch {}
101
- }
102
- // 只返回每个 orig 的最新条目(按 ts 去重)
103
- const latest = new Map();
104
- for (const e of all) {
105
- if (!e || !e.orig) continue;
106
- const existing = latest.get(e.orig);
107
- if (!existing || e.ts > existing.ts) {
108
- latest.set(e.orig, e);
109
- }
110
- }
111
- return Array.from(latest.values());
112
- } catch {
113
- return [];
114
- }
115
- }
116
-
117
- // 读取 manifest 所有条目(不去重),用于回滚计划
118
- export function readManifestAll(sid) {
119
- const file = path.join(RUNS_DIR, sanitizeId(sid), "backup", "manifest.jsonl");
120
- try {
121
- const raw = fs.readFileSync(file, "utf8");
122
- const all = [];
123
- for (const line of raw.split("\n")) {
124
- const t = line.trim();
125
- if (!t) continue;
126
- try {
127
- all.push(JSON.parse(line));
128
- } catch {}
129
- }
130
- return all;
131
- } catch {
132
- return [];
133
- }
134
- }
135
-
136
- // 写入派发 prompt 到文件,供主 Agent(Cindy)读取后通过 subagent 工具派发。
137
- // 返回 prompt 文件路径,主 Agent 读取后自行调用 subagent 工具。
138
- export function writeDispatchPrompt(sid, role, message, cwd) {
139
- try {
140
- const dir = path.join(RUNS_DIR, sanitizeId(sid), "dispatch");
141
- fs.mkdirSync(dir, { recursive: true });
142
- const file = path.join(dir, `${Date.now()}_${role}.prompt.txt`);
143
- const content = message || "";
144
- fs.writeFileSync(file, content, "utf8");
145
- return { file, content };
146
- } catch (e) {
147
- return { file: null, content: null, error: String(e && e.message ? e.message : e) };
148
- }
149
- }
150
-
151
- // 保存子 Agent 执行结果到会话目录
152
- export function saveAgentResult(sid, role, stdout, stderr, code) {
153
- try {
154
- const dir = path.join(RUNS_DIR, sanitizeId(sid), "dispatch");
155
- fs.mkdirSync(dir, { recursive: true });
156
- const file = path.join(dir, `${Date.now()}_${role}.result.json`);
157
- const rec = { ts: new Date().toISOString(), role, code: code ?? -1, stdout: String(stdout || ""), stderr: String(stderr || "") };
158
- fs.writeFileSync(file, JSON.stringify(rec, null, 2), "utf8");
159
- return file;
160
- } catch {
161
- return null;
162
- }
163
- }
164
-
165
- // Phase 1-1: 执行验证命令并返回结果
166
- //
167
- // 跨平台:原先硬编码 `spawn("cmd", ["/c", cmd], { shell: true })` —— cmd.exe 只存在于 Windows,
168
- // 在 Linux/macOS 上 `cmd` 不是可执行文件 → 命令根本没跑起来,
169
- // exitCode=127(command not found),记 PASS 的前置证据永远拿不到,
170
- // ubuntu CI 的 e2e 会整片变红。
171
- //
172
- // 现在按平台选 shell:
173
- // · Windows:cmd.exe /c + shell:true(实测 shell:false 会把带引号的
174
- // `node -e "process.exit(3)"` 的引号吃掉,退出码变成 0 而不是 3 ——
175
- // 那样「验证失败必须拦住 PASS」的门禁就形同虚设);
176
- // · POSIX:/bin/sh -c + shell:false(明确指定解释器,不依赖 PATH 里的 sh)。
177
- export async function runVerifyCommand(cmd, cwd) {
178
- if (!cmd || !cmd.trim()) {
179
- return { ok: false, exitCode: -1, stdout: "", stderr: "验证命令为空" };
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
- }
205
- const isWindows = process.platform === "win32";
206
- const shell = isWindows ? process.env.COMSPEC || "cmd.exe" : "/bin/sh";
207
- const shellArgs = isWindows ? ["/c", cmd] : ["-c", cmd];
208
- return new Promise((resolve) => {
209
- const child = spawn(shell, shellArgs, {
210
- cwd: cwd || process.cwd(),
211
- stdio: ["ignore", "pipe", "pipe"],
212
- shell: isWindows,
213
- windowsHide: true,
214
- });
215
- let stdout = "";
216
- let stderr = "";
217
- child.stdout.on("data", (d) => { stdout += d.toString(); });
218
- child.stderr.on("data", (d) => { stderr += d.toString(); });
219
- const timeout = setTimeout(() => {
220
- child.kill("SIGKILL");
221
- resolve({ ok: false, exitCode: -1, stdout, stderr: stderr + "\n验证命令超时 (120s)" });
222
- }, 120000);
223
- child.on("close", (code) => {
224
- clearTimeout(timeout);
225
- resolve({ ok: code === 0, exitCode: code ?? -1, stdout, stderr });
226
- });
227
- child.on("error", (err) => {
228
- clearTimeout(timeout);
229
- resolve({ ok: false, exitCode: -1, stdout, stderr: String(err) });
230
- });
231
- });
232
- }
233
-
234
- // Phase 1-1: scope 机器校验 - 对比 diff 与 card.scope
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
-
269
- // 没有任何变更 → 无需判定
270
- if (!Array.isArray(diffFiles) || diffFiles.length === 0) {
271
- return { ok: true, violations: [], checked: [] };
272
- }
273
-
274
- // 空 scope = 白名单为空 = **不允许改动任何文件**。
275
- // 早期实现直接 return { ok: true },等于「白名单为空 → 随便改」,
276
- // 是 fail-open 漏洞;这里改为 fail-closed:所有变更都算越界。
277
- if (!Array.isArray(scope) || scope.length === 0) {
278
- return {
279
- ok: false,
280
- violations: diffFiles.slice(),
281
- checked: diffFiles.slice(),
282
- message: `越界改动(卡片 scope 为空,不允许修改任何文件):${diffFiles.join(", ")}`,
283
- };
284
- }
285
-
286
- const scopeSet = new Set(scope.map(p => path.normalize(p)));
287
- const violations = [];
288
-
289
- for (const file of diffFiles) {
290
- const normalized = path.normalize(file);
291
- // 检查文件是否在 scope 内(精确匹配或父目录匹配)
292
- let allowed = false;
293
- for (const scopePath of scopeSet) {
294
- const normalizedScope = path.normalize(scopePath);
295
- if (normalized === normalizedScope || normalized.startsWith(normalizedScope + path.sep)) {
296
- allowed = true;
297
- break;
298
- }
299
- }
300
- if (!allowed) {
301
- violations.push(file);
302
- }
303
- }
304
-
305
- if (violations.length > 0) {
306
- return { ok: false, violations, checked: diffFiles.slice(), message: `越界改动(超出 scope):${violations.join(", ")}` };
307
- }
308
- return { ok: true, violations: [], checked: diffFiles.slice() };
309
- }
310
-
1
+ // dispatch.js — Carlos 工作流:四段合同 prompt / 文件快照 / opencode 子进程 / 验证执行 / scope 校验(Node ESM)
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { spawn, spawnSync } from "node:child_process";
5
+ import { createHash } from "node:crypto";
6
+ import { RUNS_DIR, sanitizeId } from "./state.js";
7
+
8
+ export const MAX_DISPATCH = 5;
9
+
10
+ // role ∈ "executor" | "auditor"
11
+ export function buildContractPrompt(role, card, extra) {
12
+ const isAuditor = role === "auditor";
13
+ const isExecutor = role === "executor";
14
+ if (!isAuditor && !isExecutor) {
15
+ throw new Error(`buildContractPrompt: 未知 role "${role}"(仅支持 executor/auditor)`);
16
+ }
17
+ const c = card && typeof card === "object" ? card : {};
18
+
19
+ const objective = `objective: ${c.goal || ""}`;
20
+
21
+ const outputFormat = isExecutor
22
+ ? "output format: 报告 ≤300 字,四段:结论(一句话,做完/没做完) / 改动(file:line 逐条列出,没改写“无”) / 验证(命令 → 结果摘要,未跑写“未验证”) / 遗留风险"
23
+ : "output format: 报告 ≤200 字,五段:裁定(通过/不通过) / 失败类型(操作错误/环境问题/卡片问题) / scope 标注(是否越界改动) / 证据(file:line 或实跑命令输出) / 附注";
24
+
25
+ const verifyCmd = c.verify && c.verify.cmd ? String(c.verify.cmd) : "";
26
+ let guidance = verifyCmd || "未指定验证命令,用只读取证";
27
+ if (isAuditor) {
28
+ guidance += ";独立跑 git status --porcelain 与 git diff 取证,不轻信 executor 自述";
29
+ }
30
+ const toolGuidance = `tool guidance: ${guidance}`;
31
+
32
+ const scopeArr = Array.isArray(c.scope) ? c.scope.map(String) : [];
33
+ let boundaries;
34
+ if (isAuditor) {
35
+ boundaries = "零文件改动,只读取证";
36
+ } else {
37
+ boundaries = scopeArr.length > 0 ? scopeArr.join(", ") : "无文件可改,只读任务";
38
+ }
39
+ const taskBoundaries = `task boundaries: ${boundaries}`;
40
+
41
+ let prompt = [objective, outputFormat, toolGuidance, taskBoundaries].join("\n");
42
+ if (extra && String(extra) !== "") {
43
+ prompt += "\n\n" + String(extra); // 原样附在末尾
44
+ }
45
+ return prompt;
46
+ }
47
+
48
+ // 快照:存在→复制到 RUNS_DIR/<id>/backup/<ts>_<name>;不存在→created:true;复制失败→error 且不中断其余
49
+ export function snapshotFiles(sid, paths, cwd) {
50
+ const bdir = path.join(RUNS_DIR, sanitizeId(sid), "backup");
51
+ fs.mkdirSync(bdir, { recursive: true });
52
+ const entries = [];
53
+ const list = Array.isArray(paths) ? paths : [];
54
+ for (const p of list) {
55
+ const ts = new Date().toISOString();
56
+ const orig = path.isAbsolute(p) ? p : path.join(cwd || process.cwd(), p);
57
+ if (!fs.existsSync(orig)) {
58
+ entries.push({ ts, orig, backup: null, created: true });
59
+ continue;
60
+ }
61
+ try {
62
+ // 生成随机后缀(确保是字符串)
63
+ const randSuffix = Math.random().toString(36).slice(2, 10) + Math.random().toString(36).slice(2, 10);
64
+ const backup = path.join(bdir, `${Date.now()}_${randSuffix}_${path.basename(orig)}`);
65
+ fs.copyFileSync(orig, backup);
66
+ // 完整性校验:比较大小
67
+ const srcStat = fs.statSync(orig);
68
+ const bakStat = fs.statSync(backup);
69
+ if (srcStat.size !== bakStat.size) {
70
+ fs.unlinkSync(backup);
71
+ entries.push({ ts, orig, error: "完整性校验失败(大小不匹配)" });
72
+ } else {
73
+ entries.push({ ts, orig, backup, created: false });
74
+ }
75
+ } catch (e) {
76
+ entries.push({ ts, orig, error: String(e) });
77
+ }
78
+ }
79
+ try {
80
+ const lines = entries.map((x) => JSON.stringify(x)).join("\n") + "\n";
81
+ fs.appendFileSync(path.join(RUNS_DIR, sanitizeId(sid), "backup", "manifest.jsonl"), lines, "utf8");
82
+ } catch (e) {
83
+ try {
84
+ process.stderr.write(`[flow-snapshot] manifest 追加失败: ${e && e.message ? e.message : e}\n`);
85
+ } catch {}
86
+ }
87
+ return entries;
88
+ }
89
+
90
+ export function readManifest(sid) {
91
+ const file = path.join(RUNS_DIR, sanitizeId(sid), "backup", "manifest.jsonl");
92
+ try {
93
+ const raw = fs.readFileSync(file, "utf8");
94
+ const all = [];
95
+ for (const line of raw.split("\n")) {
96
+ const t = line.trim();
97
+ if (!t) continue;
98
+ try {
99
+ all.push(JSON.parse(t));
100
+ } catch {}
101
+ }
102
+ // 只返回每个 orig 的最新条目(按 ts 去重)
103
+ const latest = new Map();
104
+ for (const e of all) {
105
+ if (!e || !e.orig) continue;
106
+ const existing = latest.get(e.orig);
107
+ if (!existing || e.ts > existing.ts) {
108
+ latest.set(e.orig, e);
109
+ }
110
+ }
111
+ return Array.from(latest.values());
112
+ } catch {
113
+ return [];
114
+ }
115
+ }
116
+
117
+ // 读取 manifest 所有条目(不去重),用于回滚计划
118
+ export function readManifestAll(sid) {
119
+ const file = path.join(RUNS_DIR, sanitizeId(sid), "backup", "manifest.jsonl");
120
+ try {
121
+ const raw = fs.readFileSync(file, "utf8");
122
+ const all = [];
123
+ for (const line of raw.split("\n")) {
124
+ const t = line.trim();
125
+ if (!t) continue;
126
+ try {
127
+ all.push(JSON.parse(line));
128
+ } catch {}
129
+ }
130
+ return all;
131
+ } catch {
132
+ return [];
133
+ }
134
+ }
135
+
136
+ // 写入派发 prompt 到文件,供主 Agent(Cindy)读取后通过 subagent 工具派发。
137
+ // 返回 prompt 文件路径,主 Agent 读取后自行调用 subagent 工具。
138
+ export function writeDispatchPrompt(sid, role, message, cwd) {
139
+ try {
140
+ const dir = path.join(RUNS_DIR, sanitizeId(sid), "dispatch");
141
+ fs.mkdirSync(dir, { recursive: true });
142
+ const file = path.join(dir, `${Date.now()}_${role}.prompt.txt`);
143
+ const content = message || "";
144
+ fs.writeFileSync(file, content, "utf8");
145
+ return { file, content };
146
+ } catch (e) {
147
+ return { file: null, content: null, error: String(e && e.message ? e.message : e) };
148
+ }
149
+ }
150
+
151
+ // 保存子 Agent 执行结果到会话目录
152
+ export function saveAgentResult(sid, role, stdout, stderr, code) {
153
+ try {
154
+ const dir = path.join(RUNS_DIR, sanitizeId(sid), "dispatch");
155
+ fs.mkdirSync(dir, { recursive: true });
156
+ const file = path.join(dir, `${Date.now()}_${role}.result.json`);
157
+ const rec = { ts: new Date().toISOString(), role, code: code ?? -1, stdout: String(stdout || ""), stderr: String(stderr || "") };
158
+ fs.writeFileSync(file, JSON.stringify(rec, null, 2), "utf8");
159
+ return file;
160
+ } catch {
161
+ return null;
162
+ }
163
+ }
164
+
165
+ // Phase 1-1: 执行验证命令并返回结果
166
+ //
167
+ // 跨平台:原先硬编码 `spawn("cmd", ["/c", cmd], { shell: true })` —— cmd.exe 只存在于 Windows,
168
+ // 在 Linux/macOS 上 `cmd` 不是可执行文件 → 命令根本没跑起来,
169
+ // exitCode=127(command not found),记 PASS 的前置证据永远拿不到,
170
+ // ubuntu CI 的 e2e 会整片变红。
171
+ //
172
+ // 现在按平台选 shell:
173
+ // · Windows:cmd.exe /c + shell:true(实测 shell:false 会把带引号的
174
+ // `node -e "process.exit(3)"` 的引号吃掉,退出码变成 0 而不是 3 ——
175
+ // 那样「验证失败必须拦住 PASS」的门禁就形同虚设);
176
+ // · POSIX:/bin/sh -c + shell:false(明确指定解释器,不依赖 PATH 里的 sh)。
177
+ export async function runVerifyCommand(cmd, cwd) {
178
+ if (!cmd || !cmd.trim()) {
179
+ return { ok: false, exitCode: -1, stdout: "", stderr: "验证命令为空" };
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
+ }
205
+ const isWindows = process.platform === "win32";
206
+ const shell = isWindows ? process.env.COMSPEC || "cmd.exe" : "/bin/sh";
207
+ const shellArgs = isWindows ? ["/c", cmd] : ["-c", cmd];
208
+ return new Promise((resolve) => {
209
+ const child = spawn(shell, shellArgs, {
210
+ cwd: cwd || process.cwd(),
211
+ stdio: ["ignore", "pipe", "pipe"],
212
+ shell: isWindows,
213
+ windowsHide: true,
214
+ });
215
+ let stdout = "";
216
+ let stderr = "";
217
+ child.stdout.on("data", (d) => { stdout += d.toString(); });
218
+ child.stderr.on("data", (d) => { stderr += d.toString(); });
219
+ const timeout = setTimeout(() => {
220
+ child.kill("SIGKILL");
221
+ resolve({ ok: false, exitCode: -1, stdout, stderr: stderr + "\n验证命令超时 (120s)" });
222
+ }, 120000);
223
+ child.on("close", (code) => {
224
+ clearTimeout(timeout);
225
+ resolve({ ok: code === 0, exitCode: code ?? -1, stdout, stderr });
226
+ });
227
+ child.on("error", (err) => {
228
+ clearTimeout(timeout);
229
+ resolve({ ok: false, exitCode: -1, stdout, stderr: String(err) });
230
+ });
231
+ });
232
+ }
233
+
234
+ // ---------------------------------------------------------------------------
235
+ // 输出指纹 + 负对照(negative control)
236
+ // ---------------------------------------------------------------------------
237
+
238
+ // 一次验证运行的输出指纹:exitCode + stdout + stderr。
239
+ //
240
+ // 为什么需要:裁定要绑定的是「一次可复现的运行」,而不是「我说测试过了」。
241
+ // 把输出哈希记进 last_verify,裁定时比对,就能发现「证据被换掉 / 命令不确定」。
242
+ export function computeOutputHash(exitCode, stdout, stderr) {
243
+ try {
244
+ const h = createHash("sha256");
245
+ h.update("exitCode=" + String(exitCode === undefined || exitCode === null ? -1 : exitCode));
246
+ h.update("\n");
247
+ h.update(typeof stdout === "string" ? stdout : "");
248
+ h.update("\n");
249
+ h.update(typeof stderr === "string" ? stderr : "");
250
+ return h.digest("hex");
251
+ } catch {
252
+ return "";
253
+ }
254
+ }
255
+
256
+ // 用快照 manifest 还原「派发时(改动前)」的工作区状态。
257
+ function restoreFromManifest(entries) {
258
+ for (const e of entries) {
259
+ if (!e || !e.orig) continue;
260
+ try {
261
+ if (e.created === true) {
262
+ // 派发时该文件不存在 → 删除当前文件
263
+ try { fs.unlinkSync(e.orig); } catch {}
264
+ } else if (e.backup) {
265
+ fs.mkdirSync(path.dirname(e.orig), { recursive: true });
266
+ fs.copyFileSync(e.backup, e.orig);
267
+ }
268
+ } catch (err) {
269
+ try { process.stderr.write(`[flow-falsify] 还原失败 ${e.orig}: ${err && err.message ? err.message : err}\n`); } catch {}
270
+ }
271
+ }
272
+ }
273
+
274
+ // 负对照:证明 verify.cmd 真的在测「本次改动」。
275
+ //
276
+ // 层次:这是「证据门禁」的执行侧 —— 不是让 LLM 声称「我试图证伪但没成功」,
277
+ // 而是让 harness 真的把工作区还原到改动前,跑同一命令,看它是否失败。
278
+ // 一个改动前就退 0 的测试是**空测试**,不构成任何证据(`|| true` / `echo ok` 就是这么漏过去的)。
279
+ //
280
+ // 安全:先把「改动后」的 scope 文件备份到临时目录,finally 里一定还原;
281
+ // 即使 verify 命令本身改动文件,也不会把工作区留在改动前状态。
282
+ //
283
+ // 局限(如实说明):快照只覆盖卡片 scope 内的文件。如果 verify.cmd 依赖 scope 外的
284
+ // 文件、而执行者又改了它们,「改动前」状态只是近似。此时负对照结论仅供参考。
285
+ export async function runNegativeControl(sid, cmd, cwd) {
286
+ const entries = readManifest(sid);
287
+ if (!entries.length) {
288
+ return { ok: false, error: "没有派发快照,无法做负对照(请先 flow_dispatch)" };
289
+ }
290
+ const tmpDir = path.join(RUNS_DIR, sanitizeId(sid), "negative_control", String(Date.now()));
291
+ try { fs.mkdirSync(tmpDir, { recursive: true }); } catch (e) {
292
+ return { ok: false, error: "无法创建负对照临时目录:" + (e && e.message ? e.message : e) };
293
+ }
294
+
295
+ // 1. 备份「改动后」的当前状态
296
+ const saved = [];
297
+ for (const e of entries) {
298
+ if (!e || !e.orig) continue;
299
+ const orig = e.orig;
300
+ const existed = fs.existsSync(orig);
301
+ let savedPath = null;
302
+ if (existed) {
303
+ try {
304
+ savedPath = path.join(tmpDir, `${saved.length}_${path.basename(orig)}`);
305
+ fs.copyFileSync(orig, savedPath);
306
+ } catch (err) {
307
+ try { process.stderr.write(`[flow-falsify] 备份当前文件失败 ${orig}: ${err && err.message ? err.message : err}\n`); } catch {}
308
+ }
309
+ }
310
+ saved.push({ orig, savedPath, existed });
311
+ }
312
+
313
+ // 还原「改动后」状态(无论后续发生什么)
314
+ const restoreCurrent = () => {
315
+ for (const s of saved) {
316
+ try {
317
+ if (s.existed && s.savedPath) {
318
+ fs.mkdirSync(path.dirname(s.orig), { recursive: true });
319
+ fs.copyFileSync(s.savedPath, s.orig);
320
+ } else if (!s.existed) {
321
+ // 当前状态里该文件不存在(executor 删了它)→ 保持删除
322
+ try { fs.unlinkSync(s.orig); } catch {}
323
+ }
324
+ } catch (err) {
325
+ try { process.stderr.write(`[flow-falsify] 还原当前文件失败 ${s.orig}: ${err && err.message ? err.message : err}\n`); } catch {}
326
+ }
327
+ }
328
+ };
329
+
330
+ let before = null;
331
+ let after = null;
332
+ try {
333
+ // 2. 还原「改动前」
334
+ restoreFromManifest(entries);
335
+ // 3. 跑改动前 —— 必须失败
336
+ before = await runVerifyCommand(cmd, cwd);
337
+ // 4. 还原「改动后」
338
+ restoreCurrent();
339
+ // 5. 跑改动后 —— 必须通过
340
+ after = await runVerifyCommand(cmd, cwd);
341
+ } finally {
342
+ // 无论如何都还原改动后状态
343
+ restoreCurrent();
344
+ }
345
+
346
+ const beforeHash = computeOutputHash(before.exitCode, before.stdout, before.stderr);
347
+ const afterHash = computeOutputHash(after.exitCode, after.stdout, after.stderr);
348
+
349
+ let verdict = "inconclusive";
350
+ let reason = "";
351
+ if (before.ok === true) {
352
+ // 改动前就通过 → 空测试
353
+ verdict = "vacuous";
354
+ reason = "verify.cmd 在改动前就通过(exitCode=" + before.exitCode + ")—— 它没有测本次改动,是空测试";
355
+ } else if (after.ok !== true) {
356
+ verdict = "not_passing";
357
+ reason = "verify.cmd 在改动后未通过(exitCode=" + after.exitCode + ")—— 改动本身有问题";
358
+ } else {
359
+ verdict = "meaningful";
360
+ reason = "改动前失败(exitCode=" + before.exitCode + ")+ 改动后通过(exitCode=" + after.exitCode + ")—— 测试有判别力";
361
+ }
362
+
363
+ // 清理临时目录(还原已完成,不再需要备份)
364
+ try { fs.rmSync(tmpDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }); } catch {}
365
+
366
+ return {
367
+ ok: true,
368
+ verdict,
369
+ reason,
370
+ before: { exitCode: before.exitCode, ok: before.ok, hash: beforeHash, stdout: before.stdout, stderr: before.stderr },
371
+ after: { exitCode: after.exitCode, ok: after.ok, hash: afterHash, stdout: after.stdout, stderr: after.stderr },
372
+ };
373
+ }
374
+
375
+ // Phase 1-1: scope 机器校验 - 对比 diff 与 card.scope
376
+ //
377
+ // 用法:enforceScope(scope, cwd, diffFiles?)
378
+ // - scope: 卡片中的 scope 白名单
379
+ // - cwd: 仓库根目录(用于跑 git diff)
380
+ // - diffFiles?: 可选,外部传入的改动文件列表;不传则自动跑 `git diff --name-only`
381
+ // 返回:{ ok, violations[], message? }
382
+ //
383
+ // 设计:
384
+ // · 空 scope = 白名单为空 = fail-closed(所有变更都算越界)
385
+ // · 无变更(diffFiles 为空)= 直接 ok
386
+ // · 自动跑 `git diff --name-only`:派发前快照 vs 当前工作区
387
+ // · 精确匹配 + 父目录匹配:scope 内文件及其子目录均算通过
388
+ export function enforceScope(scope, cwd, diffFiles) {
389
+ // diffFiles 可选:外部传入的改动文件列表;不传则自动跑 `git diff --name-only`
390
+ // cwd: 仓库根目录(用于跑 git diff)
391
+ let autoCollected = false;
392
+ if (!diffFiles) {
393
+ autoCollected = true;
394
+ diffFiles = [];
395
+ try {
396
+ const proc = spawnSync("git", ["diff", "--name-only"], {
397
+ cwd: cwd || process.cwd(),
398
+ encoding: "utf8",
399
+ // git 不在 PATH / 不是仓库 / 超时 → 一律当作「无改动」而非抛错,
400
+ // 避免把环境问题变成门禁误报(fail-closed 只针对 scope 语义,不针对环境)
401
+ timeout: 10000,
402
+ windowsHide: true,
403
+ });
404
+ if (proc.status === 0 && typeof proc.stdout === "string") {
405
+ diffFiles = proc.stdout.split("\n").map((s) => s.trim()).filter(Boolean);
406
+ }
407
+ } catch { diffFiles = []; }
408
+ }
409
+
410
+ // 没有任何变更 → 无需判定
411
+ if (!Array.isArray(diffFiles) || diffFiles.length === 0) {
412
+ return { ok: true, violations: [], checked: [] };
413
+ }
414
+
415
+ // 空 scope = 白名单为空 = **不允许改动任何文件**。
416
+ // 早期实现直接 return { ok: true },等于「白名单为空 → 随便改」,
417
+ // 是 fail-open 漏洞;这里改为 fail-closed:所有变更都算越界。
418
+ if (!Array.isArray(scope) || scope.length === 0) {
419
+ return {
420
+ ok: false,
421
+ violations: diffFiles.slice(),
422
+ checked: diffFiles.slice(),
423
+ message: `越界改动(卡片 scope 为空,不允许修改任何文件):${diffFiles.join(", ")}`,
424
+ };
425
+ }
426
+
427
+ const scopeSet = new Set(scope.map(p => path.normalize(p)));
428
+ const violations = [];
429
+
430
+ for (const file of diffFiles) {
431
+ const normalized = path.normalize(file);
432
+ // 检查文件是否在 scope 内(精确匹配或父目录匹配)
433
+ let allowed = false;
434
+ for (const scopePath of scopeSet) {
435
+ const normalizedScope = path.normalize(scopePath);
436
+ if (normalized === normalizedScope || normalized.startsWith(normalizedScope + path.sep)) {
437
+ allowed = true;
438
+ break;
439
+ }
440
+ }
441
+ if (!allowed) {
442
+ violations.push(file);
443
+ }
444
+ }
445
+
446
+ if (violations.length > 0) {
447
+ return { ok: false, violations, checked: diffFiles.slice(), message: `越界改动(超出 scope):${violations.join(", ")}` };
448
+ }
449
+ return { ok: true, violations: [], checked: diffFiles.slice() };
450
+ }
451
+