carlos-flow 2.12.0 → 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/src/dispatch.js CHANGED
@@ -1,548 +1,557 @@
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
- // 通用设计基线(坏味道清单)—— Standards 轴的第二层基线。
11
- //
12
- // 出处与边界(重要,不要夸大):
13
- // · 本表由 Carlos 项目自维护,**术语对齐** Fowler et al.《Refactoring:
14
- // Improving the Design of Existing Code》第二版第 3 章「Code Smells」;
15
- // · 但它**不是原书全表**,也不声称逐条等同原书 —— 原书两版条目数不同,
16
- // 市面上流传的「Fowler 12 种坏味道」是二手博客的说法、不是书里的口径。
17
- // 把一个无法核实的数字写进审计权威,subagent 就会拿着错的基准去判定。
18
- // · 显式化清单的价值不在「权威」,在**可枚举、可测试、口径一致**:
19
- // 判定不再依赖模型记性,测试也能断言基线条目一条都没被静默删掉。
20
- export const SMELL_BASELINE = [
21
- { name: "Duplicated Code", desc: "同一段逻辑重复出现,改一处漏一处" },
22
- { name: "Long Method", desc: "函数承担过多职责,应拆分" },
23
- { name: "Long Parameter List", desc: "参数过多,应封装成对象" },
24
- { name: "Large Class", desc: "类承担过多职责" },
25
- { name: "Data Clumps", desc: "同一组字段/参数反复成组出现" },
26
- { name: "Primitive Obsession", desc: "用基本类型代替领域对象" },
27
- { name: "Feature Envy", desc: "方法比宿主对象更依赖别的对象的数据" },
28
- { name: "Message Chains", desc: "过长的链式调用(a.getB().getC().getD())" },
29
- { name: "Middle Man", desc: "类/方法只做转发,自己没有职责" },
30
- { name: "Divergent Change", desc: "一个类因多种不相关的原因被修改" },
31
- { name: "Shotgun Surgery", desc: "一处逻辑改动要同步改多个文件" },
32
- { name: "Speculative Generality", desc: "为尚不存在的需求预留扩展点" },
33
- { name: "Temporary Field", desc: "字段只在某段流程内有值" },
34
- { name: "Refused Bequest", desc: "子类继承父类却拒绝/覆盖其大部分行为" },
35
- { name: "Data Class", desc: "只有数据没有行为" },
36
- { name: "Lazy Class", desc: "只有方法没有实质职责" },
37
- { name: "Comments", desc: "用注释掩盖代码本该表达的东西" },
38
- { name: "Dead Code", desc: "永不可达的废弃代码" },
39
- ];
40
-
41
- // 渲染审计 checklist 段:条目逐条编号,便于 subagent 按项检查、便于测试逐条断言。
42
- function renderChecklist(checklist) {
43
- const items = (checklist.items || [])
44
- .map((it, i) => `${i + 1}. ${it.name} — ${it.desc}`)
45
- .join("\n");
46
- return `${checklist.title}(逐条检查,命中即给 file:line 证据):\n${items}\n注:${checklist.note}`;
47
- }
48
-
49
- // Dispatcher 配置:双轴审查 prompt 配置表。
50
- // 新增轴只改这里,不动 buildContractPrompt 的函数体(避免分支膨胀)。
51
- //
52
- // 判定词表必须与 flow_audit_submit 的 enum(PASS / WARN / FAIL)对齐:
53
- // 词表不一致时 subagent 会输出「通过/违规」这类自然语言,由主 Agent 手工映射,
54
- // 而 FAIL(硬拦)与 WARN(不拦)的差别就在这一步 —— 映射错了硬拦就失效了。
55
- const AXIS_PROMPTS = {
56
- standards: {
57
- objective: "审计:仓库代码规范与坏味道",
58
- format: "判定(PASS / WARN / FAIL) / 规范依据 / file:line 证据 / 是否硬违规",
59
- guidance:
60
- "两层基线同时执行:" +
61
- "① 仓库规范层:先在目标仓库内发现规范文件(eslint 配置、prettier 配置、editorconfig、" +
62
- "CONTRIBUTING.md、AGENTS.md、tsconfig 的 lint 选项、CI 里的 lint/test 命令)," +
63
- "把发现的规范文件清单写进报告,再逐条对照;" +
64
- "② 通用设计层:按下面的「坏味道基线」逐条检查。" +
65
- "只读取证 git diff,不轻信 executor 自述,每条命中都要给 file:line 证据。" +
66
- "判定口径:违反仓库明文规范判 FAIL;命中通用设计基线判 WARN。",
67
- boundaries: "零文件改动,只读取证",
68
- checklist: {
69
- title: "坏味道基线",
70
- items: SMELL_BASELINE,
71
- note: "本表由 Carlos 自维护,术语对齐 Fowler《Refactoring》第二版第 3 章 Code Smells,非原书全表",
72
- },
73
- },
74
- spec: {
75
- objective: "审计:任务卡验收标准忠实度",
76
- format: "判定(PASS / WARN / FAIL) / 验收标准逐条核对结果 / 越界改动(file:line)",
77
- guidance:
78
- "对照任务卡 goal/acceptance/scope,逐条核对卡上的验收标准,跑 flow_check_scope 校验越界," +
79
- "独立跑验证命令取证。判定口径:验收标准全部满足且无越界判 PASS;未实现验收或越界改动判 FAIL;" +
80
- "仅部分存疑判 WARN。",
81
- boundaries: "零文件改动,只读取证",
82
- },
83
- };
84
-
85
- // role ∈ "executor" | "auditor"
86
- // axis ∈ undefined(默认四段合同) | "standards" | "spec"(双轴审计模式)
87
- export function buildContractPrompt(role, card, extra, axis) {
88
- const isAuditor = role === "auditor";
89
- const isExecutor = role === "executor";
90
- if (!isAuditor && !isExecutor) {
91
- throw new Error(`buildContractPrompt: 未知 role "${role}"(仅支持 executor/auditor)`);
92
- }
93
-
94
- // 模式注入:指定了 axis 就走配置表(覆盖式),否则走原有逻辑
95
- let objective, outputFormat, toolGuidance, taskBoundaries;
96
-
97
- if (axis && AXIS_PROMPTS[axis]) {
98
- const cfg = AXIS_PROMPTS[axis];
99
- objective = `objective: ${cfg.objective}`;
100
- outputFormat = `output format: ${cfg.format}`;
101
- toolGuidance = `tool guidance: ${cfg.guidance}`;
102
- taskBoundaries = `task boundaries: ${cfg.boundaries}`;
103
- } else {
104
- const c = card && typeof card === "object" ? card : {};
105
-
106
- objective = `objective: ${c.goal || ""}`;
107
-
108
- outputFormat = isExecutor
109
- ? "output format: 报告 ≤300 字,四段:结论(一句话,做完/没做完) / 改动(file:line 逐条列出,没改写“无”) / 验证(命令 → 结果摘要,未跑写“未验证”) / 遗留风险"
110
- : "output format: 报告 ≤200 字,五段:裁定(通过/不通过) / 失败类型(操作错误/环境问题/卡片问题) / scope 标注(是否越界改动) / 证据(file:line 或实跑命令输出) / 附注";
111
-
112
- const verifyCmd = c.verify && c.verify.cmd ? String(c.verify.cmd) : "";
113
- let guidance = verifyCmd || "未指定验证命令,用只读取证";
114
- if (isAuditor) {
115
- guidance += ";独立跑 git status --porcelain 与 git diff 取证,不轻信 executor 自述";
116
- }
117
- toolGuidance = `tool guidance: ${guidance}`;
118
-
119
- const scopeArr = Array.isArray(c.scope) ? c.scope.map(String) : [];
120
- let boundaries;
121
- if (isAuditor) {
122
- boundaries = "零文件改动,只读取证";
123
- } else {
124
- boundaries = scopeArr.length > 0 ? scopeArr.join(", ") : "无文件可改,只读任务";
125
- }
126
- taskBoundaries = `task boundaries: ${boundaries}`;
127
- }
128
-
129
- let prompt = [objective, outputFormat, toolGuidance, taskBoundaries].join("\n");
130
-
131
- // 轴模式:附上该轴的基线清单(Standards 轴的坏味道基线)。
132
- // 清单必须内联进 prompt —— 审计 subagent 跑在**目标仓库**里,
133
- // 读不到 carlos-flow 包内的文件,写成 docs/xxx.md 让它去读等于没写。
134
- const axisCfg = axis ? AXIS_PROMPTS[axis] : null;
135
- if (axisCfg && axisCfg.checklist) {
136
- prompt += "\n\n" + renderChecklist(axisCfg.checklist);
137
- }
138
-
139
- if (extra && String(extra) !== "") {
140
- prompt += "\n\n" + String(extra); // 原样附在末尾
141
- }
142
- return prompt;
143
- }
144
-
145
- // 快照:存在→复制到 RUNS_DIR/<id>/backup/<ts>_<name>;不存在→created:true;复制失败→error 且不中断其余
146
- export function snapshotFiles(sid, paths, cwd) {
147
- const bdir = path.join(RUNS_DIR, sanitizeId(sid), "backup");
148
- fs.mkdirSync(bdir, { recursive: true });
149
- const entries = [];
150
- const list = Array.isArray(paths) ? paths : [];
151
- for (const p of list) {
152
- const ts = new Date().toISOString();
153
- const orig = path.isAbsolute(p) ? p : path.join(cwd || process.cwd(), p);
154
- if (!fs.existsSync(orig)) {
155
- entries.push({ ts, orig, backup: null, created: true });
156
- continue;
157
- }
158
- try {
159
- // 生成随机后缀(确保是字符串)
160
- const randSuffix = Math.random().toString(36).slice(2, 10) + Math.random().toString(36).slice(2, 10);
161
- const backup = path.join(bdir, `${Date.now()}_${randSuffix}_${path.basename(orig)}`);
162
- fs.copyFileSync(orig, backup);
163
- // 完整性校验:比较大小
164
- const srcStat = fs.statSync(orig);
165
- const bakStat = fs.statSync(backup);
166
- if (srcStat.size !== bakStat.size) {
167
- fs.unlinkSync(backup);
168
- entries.push({ ts, orig, error: "完整性校验失败(大小不匹配)" });
169
- } else {
170
- entries.push({ ts, orig, backup, created: false });
171
- }
172
- } catch (e) {
173
- entries.push({ ts, orig, error: String(e) });
174
- }
175
- }
176
- try {
177
- const lines = entries.map((x) => JSON.stringify(x)).join("\n") + "\n";
178
- fs.appendFileSync(path.join(RUNS_DIR, sanitizeId(sid), "backup", "manifest.jsonl"), lines, "utf8");
179
- } catch (e) {
180
- try {
181
- process.stderr.write(`[flow-snapshot] manifest 追加失败: ${e && e.message ? e.message : e}\n`);
182
- } catch {}
183
- }
184
- return entries;
185
- }
186
-
187
- export function readManifest(sid) {
188
- const file = path.join(RUNS_DIR, sanitizeId(sid), "backup", "manifest.jsonl");
189
- try {
190
- const raw = fs.readFileSync(file, "utf8");
191
- const all = [];
192
- for (const line of raw.split("\n")) {
193
- const t = line.trim();
194
- if (!t) continue;
195
- try {
196
- all.push(JSON.parse(t));
197
- } catch {}
198
- }
199
- // 只返回每个 orig 的最新条目(按 ts 去重)
200
- const latest = new Map();
201
- for (const e of all) {
202
- if (!e || !e.orig) continue;
203
- const existing = latest.get(e.orig);
204
- if (!existing || e.ts > existing.ts) {
205
- latest.set(e.orig, e);
206
- }
207
- }
208
- return Array.from(latest.values());
209
- } catch {
210
- return [];
211
- }
212
- }
213
-
214
- // 读取 manifest 所有条目(不去重),用于回滚计划
215
- export function readManifestAll(sid) {
216
- const file = path.join(RUNS_DIR, sanitizeId(sid), "backup", "manifest.jsonl");
217
- try {
218
- const raw = fs.readFileSync(file, "utf8");
219
- const all = [];
220
- for (const line of raw.split("\n")) {
221
- const t = line.trim();
222
- if (!t) continue;
223
- try {
224
- all.push(JSON.parse(line));
225
- } catch {}
226
- }
227
- return all;
228
- } catch {
229
- return [];
230
- }
231
- }
232
-
233
- // 写入派发 prompt 到文件,供主 Agent(Cindy)读取后通过 subagent 工具派发。
234
- // 返回 prompt 文件路径,主 Agent 读取后自行调用 subagent 工具。
235
- export function writeDispatchPrompt(sid, role, message, cwd) {
236
- try {
237
- const dir = path.join(RUNS_DIR, sanitizeId(sid), "dispatch");
238
- fs.mkdirSync(dir, { recursive: true });
239
- const file = path.join(dir, `${Date.now()}_${role}.prompt.txt`);
240
- const content = message || "";
241
- fs.writeFileSync(file, content, "utf8");
242
- return { file, content };
243
- } catch (e) {
244
- return { file: null, content: null, error: String(e && e.message ? e.message : e) };
245
- }
246
- }
247
-
248
- // 保存子 Agent 执行结果到会话目录
249
- export function saveAgentResult(sid, role, stdout, stderr, code) {
250
- try {
251
- const dir = path.join(RUNS_DIR, sanitizeId(sid), "dispatch");
252
- fs.mkdirSync(dir, { recursive: true });
253
- const file = path.join(dir, `${Date.now()}_${role}.result.json`);
254
- const rec = { ts: new Date().toISOString(), role, code: code ?? -1, stdout: String(stdout || ""), stderr: String(stderr || "") };
255
- fs.writeFileSync(file, JSON.stringify(rec, null, 2), "utf8");
256
- return file;
257
- } catch {
258
- return null;
259
- }
260
- }
261
-
262
- // Phase 1-1: 执行验证命令并返回结果
263
- //
264
- // 跨平台:原先硬编码 `spawn("cmd", ["/c", cmd], { shell: true })` —— cmd.exe 只存在于 Windows,
265
- // 在 Linux/macOS 上 `cmd` 不是可执行文件 → 命令根本没跑起来,
266
- // exitCode=127(command not found),记 PASS 的前置证据永远拿不到,
267
- // ubuntu CI 的 e2e 会整片变红。
268
- //
269
- // 现在按平台选 shell:
270
- // · Windows:cmd.exe /c + shell:true(实测 shell:false 会把带引号的
271
- // `node -e "process.exit(3)"` 的引号吃掉,退出码变成 0 而不是 3 ——
272
- // 那样「验证失败必须拦住 PASS」的门禁就形同虚设);
273
- // · POSIX:/bin/sh -c + shell:false(明确指定解释器,不依赖 PATH 里的 sh)。
274
- export async function runVerifyCommand(cmd, cwd) {
275
- if (!cmd || !cmd.trim()) {
276
- return { ok: false, exitCode: -1, stdout: "", stderr: "验证命令为空" };
277
- }
278
- // 可选:拦截高危命令模式。
279
- //
280
- // 威胁模型说明(重要,不要夸大):
281
- // · verify.cmd 本质上就是「执行用户指定的验证命令」—— 它的设计目标就是能跑任意命令
282
- // (`npm test` / `pytest` / `cargo build` …),所以**默认不拦**。
283
- // · 真正的风险来源是「verify.cmd 的来源可信度」:
284
- // - 人工填写的任务卡 → 可信,是用户/Agent 的本意
285
- // - 自动激活产生的占位卡 → activation 时 scope/acceptance 为空、**没有 verify.cmd**,
286
- // 必须人工补齐才能过闸门 → 自动触发路径已被 activation 闸门挡住
287
- // · 因此默认不拦是对的;把黑名单默认打开会误伤合法脚本
288
- // (比如 `rm -rf node_modules` 出现在清理步骤里是完全合法的)。
289
- // · 需要更严的用户可以打开 CARLOS_FLOW_BLOCK_DANGEROUS=1。
290
- if (process.env.CARLOS_FLOW_BLOCK_DANGEROUS === "1") {
291
- 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;
292
- if (dangerous.test(cmd)) {
293
- return {
294
- ok: false,
295
- exitCode: -1,
296
- stdout: "",
297
- stderr: `验证命令包含高危模式,已拒绝执行:${cmd}\n` +
298
- "(CARLOS_FLOW_BLOCK_DANGEROUS=1 已开启;确认该命令安全后可关闭此开关)",
299
- };
300
- }
301
- }
302
- const isWindows = process.platform === "win32";
303
- const shell = isWindows ? process.env.COMSPEC || "cmd.exe" : "/bin/sh";
304
- const shellArgs = isWindows ? ["/c", cmd] : ["-c", cmd];
305
- return new Promise((resolve) => {
306
- const child = spawn(shell, shellArgs, {
307
- cwd: cwd || process.cwd(),
308
- stdio: ["ignore", "pipe", "pipe"],
309
- shell: isWindows,
310
- windowsHide: true,
311
- });
312
- let stdout = "";
313
- let stderr = "";
314
- child.stdout.on("data", (d) => { stdout += d.toString(); });
315
- child.stderr.on("data", (d) => { stderr += d.toString(); });
316
- const timeout = setTimeout(() => {
317
- child.kill("SIGKILL");
318
- resolve({ ok: false, exitCode: -1, stdout, stderr: stderr + "\n验证命令超时 (120s)" });
319
- }, 120000);
320
- child.on("close", (code) => {
321
- clearTimeout(timeout);
322
- resolve({ ok: code === 0, exitCode: code ?? -1, stdout, stderr });
323
- });
324
- child.on("error", (err) => {
325
- clearTimeout(timeout);
326
- resolve({ ok: false, exitCode: -1, stdout, stderr: String(err) });
327
- });
328
- });
329
- }
330
-
331
- // ---------------------------------------------------------------------------
332
- // 输出指纹 + 负对照(negative control)
333
- // ---------------------------------------------------------------------------
334
-
335
- // 一次验证运行的输出指纹:exitCode + stdout + stderr。
336
- //
337
- // 为什么需要:裁定要绑定的是「一次可复现的运行」,而不是「我说测试过了」。
338
- // 把输出哈希记进 last_verify,裁定时比对,就能发现「证据被换掉 / 命令不确定」。
339
- export function computeOutputHash(exitCode, stdout, stderr) {
340
- try {
341
- const h = createHash("sha256");
342
- h.update("exitCode=" + String(exitCode === undefined || exitCode === null ? -1 : exitCode));
343
- h.update("\n");
344
- h.update(typeof stdout === "string" ? stdout : "");
345
- h.update("\n");
346
- h.update(typeof stderr === "string" ? stderr : "");
347
- return h.digest("hex");
348
- } catch {
349
- return "";
350
- }
351
- }
352
-
353
- // 用快照 manifest 还原「派发时(改动前)」的工作区状态。
354
- function restoreFromManifest(entries) {
355
- for (const e of entries) {
356
- if (!e || !e.orig) continue;
357
- try {
358
- if (e.created === true) {
359
- // 派发时该文件不存在 → 删除当前文件
360
- try { fs.unlinkSync(e.orig); } catch {}
361
- } else if (e.backup) {
362
- fs.mkdirSync(path.dirname(e.orig), { recursive: true });
363
- fs.copyFileSync(e.backup, e.orig);
364
- }
365
- } catch (err) {
366
- try { process.stderr.write(`[flow-falsify] 还原失败 ${e.orig}: ${err && err.message ? err.message : err}\n`); } catch {}
367
- }
368
- }
369
- }
370
-
371
- // 负对照:证明 verify.cmd 真的在测「本次改动」。
372
- //
373
- // 层次:这是「证据门禁」的执行侧 —— 不是让 LLM 声称「我试图证伪但没成功」,
374
- // 而是让 harness 真的把工作区还原到改动前,跑同一命令,看它是否失败。
375
- // 一个改动前就退 0 的测试是**空测试**,不构成任何证据(`|| true` / `echo ok` 就是这么漏过去的)。
376
- //
377
- // 安全:先把「改动后」的 scope 文件备份到临时目录,finally 里一定还原;
378
- // 即使 verify 命令本身改动文件,也不会把工作区留在改动前状态。
379
- //
380
- // 局限(如实说明):快照只覆盖卡片 scope 内的文件。如果 verify.cmd 依赖 scope 外的
381
- // 文件、而执行者又改了它们,「改动前」状态只是近似。此时负对照结论仅供参考。
382
- export async function runNegativeControl(sid, cmd, cwd) {
383
- const entries = readManifest(sid);
384
- if (!entries.length) {
385
- return { ok: false, error: "没有派发快照,无法做负对照(请先 flow_dispatch)" };
386
- }
387
- const tmpDir = path.join(RUNS_DIR, sanitizeId(sid), "negative_control", String(Date.now()));
388
- try { fs.mkdirSync(tmpDir, { recursive: true }); } catch (e) {
389
- return { ok: false, error: "无法创建负对照临时目录:" + (e && e.message ? e.message : e) };
390
- }
391
-
392
- // 1. 备份「改动后」的当前状态
393
- const saved = [];
394
- for (const e of entries) {
395
- if (!e || !e.orig) continue;
396
- const orig = e.orig;
397
- const existed = fs.existsSync(orig);
398
- let savedPath = null;
399
- if (existed) {
400
- try {
401
- savedPath = path.join(tmpDir, `${saved.length}_${path.basename(orig)}`);
402
- fs.copyFileSync(orig, savedPath);
403
- } catch (err) {
404
- try { process.stderr.write(`[flow-falsify] 备份当前文件失败 ${orig}: ${err && err.message ? err.message : err}\n`); } catch {}
405
- }
406
- }
407
- saved.push({ orig, savedPath, existed });
408
- }
409
-
410
- // 还原「改动后」状态(无论后续发生什么)
411
- const restoreCurrent = () => {
412
- for (const s of saved) {
413
- try {
414
- if (s.existed && s.savedPath) {
415
- fs.mkdirSync(path.dirname(s.orig), { recursive: true });
416
- fs.copyFileSync(s.savedPath, s.orig);
417
- } else if (!s.existed) {
418
- // 当前状态里该文件不存在(executor 删了它)→ 保持删除
419
- try { fs.unlinkSync(s.orig); } catch {}
420
- }
421
- } catch (err) {
422
- try { process.stderr.write(`[flow-falsify] 还原当前文件失败 ${s.orig}: ${err && err.message ? err.message : err}\n`); } catch {}
423
- }
424
- }
425
- };
426
-
427
- let before = null;
428
- let after = null;
429
- try {
430
- // 2. 还原「改动前」
431
- restoreFromManifest(entries);
432
- // 3. 跑改动前 —— 必须失败
433
- before = await runVerifyCommand(cmd, cwd);
434
- // 4. 还原「改动后」
435
- restoreCurrent();
436
- // 5. 跑改动后 —— 必须通过
437
- after = await runVerifyCommand(cmd, cwd);
438
- } finally {
439
- // 无论如何都还原改动后状态
440
- restoreCurrent();
441
- }
442
-
443
- const beforeHash = computeOutputHash(before.exitCode, before.stdout, before.stderr);
444
- const afterHash = computeOutputHash(after.exitCode, after.stdout, after.stderr);
445
-
446
- let verdict = "inconclusive";
447
- let reason = "";
448
- if (before.ok === true) {
449
- // 改动前就通过 → 空测试
450
- verdict = "vacuous";
451
- reason = "verify.cmd 在改动前就通过(exitCode=" + before.exitCode + ")—— 它没有测本次改动,是空测试";
452
- } else if (after.ok !== true) {
453
- verdict = "not_passing";
454
- reason = "verify.cmd 在改动后未通过(exitCode=" + after.exitCode + ")—— 改动本身有问题";
455
- } else {
456
- verdict = "meaningful";
457
- reason = "改动前失败(exitCode=" + before.exitCode + ")+ 改动后通过(exitCode=" + after.exitCode + ")—— 测试有判别力";
458
- }
459
-
460
- // 清理临时目录(还原已完成,不再需要备份)
461
- try { fs.rmSync(tmpDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }); } catch {}
462
-
463
- return {
464
- ok: true,
465
- verdict,
466
- reason,
467
- before: { exitCode: before.exitCode, ok: before.ok, hash: beforeHash, stdout: before.stdout, stderr: before.stderr },
468
- after: { exitCode: after.exitCode, ok: after.ok, hash: afterHash, stdout: after.stdout, stderr: after.stderr },
469
- };
470
- }
471
-
472
- // Phase 1-1: scope 机器校验 - 对比 diff 与 card.scope
473
- //
474
- // 用法:enforceScope(scope, cwd, diffFiles?)
475
- // - scope: 卡片中的 scope 白名单
476
- // - cwd: 仓库根目录(用于跑 git diff)
477
- // - diffFiles?: 可选,外部传入的改动文件列表;不传则自动跑 `git diff --name-only`
478
- // 返回:{ ok, violations[], message? }
479
- //
480
- // 设计:
481
- // · 空 scope = 白名单为空 = fail-closed(所有变更都算越界)
482
- // · 无变更(diffFiles 为空)= 直接 ok
483
- // · 自动跑 `git diff --name-only`:派发前快照 vs 当前工作区
484
- // · 精确匹配 + 父目录匹配:scope 内文件及其子目录均算通过
485
- export function enforceScope(scope, cwd, diffFiles) {
486
- // diffFiles 可选:外部传入的改动文件列表;不传则自动跑 `git diff --name-only`
487
- // cwd: 仓库根目录(用于跑 git diff)
488
- let autoCollected = false;
489
- if (!diffFiles) {
490
- autoCollected = true;
491
- diffFiles = [];
492
- try {
493
- const proc = spawnSync("git", ["diff", "--name-only"], {
494
- cwd: cwd || process.cwd(),
495
- encoding: "utf8",
496
- // git 不在 PATH / 不是仓库 / 超时 → 一律当作「无改动」而非抛错,
497
- // 避免把环境问题变成门禁误报(fail-closed 只针对 scope 语义,不针对环境)
498
- timeout: 10000,
499
- windowsHide: true,
500
- });
501
- if (proc.status === 0 && typeof proc.stdout === "string") {
502
- diffFiles = proc.stdout.split("\n").map((s) => s.trim()).filter(Boolean);
503
- }
504
- } catch { diffFiles = []; }
505
- }
506
-
507
- // 没有任何变更 → 无需判定
508
- if (!Array.isArray(diffFiles) || diffFiles.length === 0) {
509
- return { ok: true, violations: [], checked: [] };
510
- }
511
-
512
- // 空 scope = 白名单为空 = **不允许改动任何文件**。
513
- // 早期实现直接 return { ok: true },等于「白名单为空 → 随便改」,
514
- // 是 fail-open 漏洞;这里改为 fail-closed:所有变更都算越界。
515
- if (!Array.isArray(scope) || scope.length === 0) {
516
- return {
517
- ok: false,
518
- violations: diffFiles.slice(),
519
- checked: diffFiles.slice(),
520
- message: `越界改动(卡片 scope 为空,不允许修改任何文件):${diffFiles.join(", ")}`,
521
- };
522
- }
523
-
524
- const scopeSet = new Set(scope.map(p => path.normalize(p)));
525
- const violations = [];
526
-
527
- for (const file of diffFiles) {
528
- const normalized = path.normalize(file);
529
- // 检查文件是否在 scope 内(精确匹配或父目录匹配)
530
- let allowed = false;
531
- for (const scopePath of scopeSet) {
532
- const normalizedScope = path.normalize(scopePath);
533
- if (normalized === normalizedScope || normalized.startsWith(normalizedScope + path.sep)) {
534
- allowed = true;
535
- break;
536
- }
537
- }
538
- if (!allowed) {
539
- violations.push(file);
540
- }
541
- }
542
-
543
- if (violations.length > 0) {
544
- return { ok: false, violations, checked: diffFiles.slice(), message: `越界改动(超出 scope):${violations.join(", ")}` };
545
- }
546
- return { ok: true, violations: [], checked: diffFiles.slice() };
547
- }
548
-
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
+ // 通用设计基线(坏味道清单)—— Standards 轴的第二层基线。
11
+ //
12
+ // 出处与边界(重要,不要夸大):
13
+ // · 本表由 Carlos 项目自维护,**术语对齐** Fowler et al.《Refactoring:
14
+ // Improving the Design of Existing Code》第二版第 3 章「Code Smells」;
15
+ // · 但它**不是原书全表**,也不声称逐条等同原书 —— 原书两版条目数不同,
16
+ // 市面上流传的「Fowler 12 种坏味道」是二手博客的说法、不是书里的口径。
17
+ // 把一个无法核实的数字写进审计权威,subagent 就会拿着错的基准去判定。
18
+ // · 显式化清单的价值不在「权威」,在**可枚举、可测试、口径一致**:
19
+ // 判定不再依赖模型记性,测试也能断言基线条目一条都没被静默删掉。
20
+ export const SMELL_BASELINE = [
21
+ { name: "Duplicated Code", desc: "同一段逻辑重复出现,改一处漏一处" },
22
+ { name: "Long Method", desc: "函数承担过多职责,应拆分" },
23
+ { name: "Long Parameter List", desc: "参数过多,应封装成对象" },
24
+ { name: "Large Class", desc: "类承担过多职责" },
25
+ { name: "Data Clumps", desc: "同一组字段/参数反复成组出现" },
26
+ { name: "Primitive Obsession", desc: "用基本类型代替领域对象" },
27
+ { name: "Feature Envy", desc: "方法比宿主对象更依赖别的对象的数据" },
28
+ { name: "Message Chains", desc: "过长的链式调用(a.getB().getC().getD())" },
29
+ { name: "Middle Man", desc: "类/方法只做转发,自己没有职责" },
30
+ { name: "Divergent Change", desc: "一个类因多种不相关的原因被修改" },
31
+ { name: "Shotgun Surgery", desc: "一处逻辑改动要同步改多个文件" },
32
+ { name: "Speculative Generality", desc: "为尚不存在的需求预留扩展点" },
33
+ { name: "Temporary Field", desc: "字段只在某段流程内有值" },
34
+ { name: "Refused Bequest", desc: "子类继承父类却拒绝/覆盖其大部分行为" },
35
+ { name: "Data Class", desc: "只有数据没有行为" },
36
+ { name: "Lazy Class", desc: "只有方法没有实质职责" },
37
+ { name: "Comments", desc: "用注释掩盖代码本该表达的东西" },
38
+ { name: "Dead Code", desc: "永不可达的废弃代码" },
39
+ ];
40
+
41
+ // 渲染审计 checklist 段:条目逐条编号,便于 subagent 按项检查、便于测试逐条断言。
42
+ function renderChecklist(checklist) {
43
+ const items = (checklist.items || [])
44
+ .map((it, i) => `${i + 1}. ${it.name} — ${it.desc}`)
45
+ .join("\n");
46
+ return `${checklist.title}(逐条检查,命中即给 file:line 证据):\n${items}\n注:${checklist.note}`;
47
+ }
48
+
49
+ // Dispatcher 配置:双轴审查 prompt 配置表。
50
+ // 新增轴只改这里,不动 buildContractPrompt 的函数体(避免分支膨胀)。
51
+ //
52
+ // 判定词表必须与 flow_audit_submit 的 enum(PASS / WARN / FAIL)对齐:
53
+ // 词表不一致时 subagent 会输出「通过/违规」这类自然语言,由主 Agent 手工映射,
54
+ // 而 FAIL(硬拦)与 WARN(不拦)的差别就在这一步 —— 映射错了硬拦就失效了。
55
+ const AXIS_PROMPTS = {
56
+ standards: {
57
+ objective: "审计:仓库代码规范与坏味道",
58
+ format: "判定(PASS / WARN / FAIL) / 规范依据 / file:line 证据 / 是否硬违规",
59
+ guidance:
60
+ "两层基线同时执行:" +
61
+ "① 仓库规范层:先在目标仓库内发现规范文件(eslint 配置、prettier 配置、editorconfig、" +
62
+ "CONTRIBUTING.md、AGENTS.md、tsconfig 的 lint 选项、CI 里的 lint/test 命令)," +
63
+ "把发现的规范文件清单写进报告,再逐条对照;" +
64
+ "② 通用设计层:按下面的「坏味道基线」逐条检查。" +
65
+ "只读取证 git diff,不轻信 executor 自述,每条命中都要给 file:line 证据。" +
66
+ "判定口径:违反仓库明文规范判 FAIL;命中通用设计基线判 WARN。",
67
+ boundaries: "零文件改动,只读取证",
68
+ checklist: {
69
+ title: "坏味道基线",
70
+ items: SMELL_BASELINE,
71
+ note: "本表由 Carlos 自维护,术语对齐 Fowler《Refactoring》第二版第 3 章 Code Smells,非原书全表",
72
+ },
73
+ },
74
+ spec: {
75
+ objective: "审计:任务卡验收标准忠实度",
76
+ format: "判定(PASS / WARN / FAIL) / 验收标准逐条核对结果 / 越界改动(file:line)",
77
+ guidance:
78
+ "对照任务卡 goal/acceptance/scope,逐条核对卡上的验收标准,跑 flow_check_scope 校验越界," +
79
+ "独立跑验证命令取证。判定口径:验收标准全部满足且无越界判 PASS;未实现验收或越界改动判 FAIL;" +
80
+ "仅部分存疑判 WARN。",
81
+ boundaries: "零文件改动,只读取证",
82
+ },
83
+ };
84
+
85
+ import { PROMPT_PROFILES } from "./profiles.js";
86
+
87
+ // role ∈ "executor" | "auditor"
88
+ // options ∈ { axis?: "standards"|"spec", profile?: string }
89
+ export function buildContractPrompt(role, card, extra, options = {}) {
90
+ const isAuditor = role === "auditor";
91
+ const isExecutor = role === "executor";
92
+ if (!isAuditor && !isExecutor) {
93
+ throw new Error(`buildContractPrompt: 未知 role "${role}"(仅支持 executor/auditor)`);
94
+ }
95
+
96
+ // 模式注入:指定了 axis/profile 就走配置表(覆盖式),否则走原有逻辑
97
+ let objective, outputFormat, toolGuidance, taskBoundaries;
98
+ const { axis, profile } = typeof options === 'string' ? { axis: options } : options;
99
+
100
+ if (axis && AXIS_PROMPTS[axis]) {
101
+ const cfg = AXIS_PROMPTS[axis];
102
+ objective = `objective: ${cfg.objective}`;
103
+ outputFormat = `output format: ${cfg.format}`;
104
+ toolGuidance = `tool guidance: ${cfg.guidance}`;
105
+ taskBoundaries = `task boundaries: ${cfg.boundaries}`;
106
+ } else if (profile && PROMPT_PROFILES[profile]) {
107
+ const cfg = PROMPT_PROFILES[profile];
108
+ objective = `objective: ${cfg.objective}`;
109
+ outputFormat = `output format: ${cfg.format}`;
110
+ toolGuidance = `tool guidance: ${cfg.guidance}`;
111
+ taskBoundaries = isAuditor ? "task boundaries: 零文件改动,只读取证" : "task boundaries: 无文件可改,只读任务";
112
+ } else {
113
+ const c = card && typeof card === "object" ? card : {};
114
+
115
+ objective = `objective: ${c.goal || ""}`;
116
+
117
+ outputFormat = isExecutor
118
+ ? "output format: 报告 ≤300 字,四段:结论(一句话,做完/没做完) / 改动(file:line 逐条列出,没改写“无”) / 验证(命令 → 结果摘要,未跑写“未验证”) / 遗留风险"
119
+ : "output format: 报告 ≤200 字,五段:裁定(通过/不通过) / 失败类型(操作错误/环境问题/卡片问题) / scope 标注(是否越界改动) / 证据(file:line 或实跑命令输出) / 附注";
120
+
121
+ const verifyCmd = c.verify && c.verify.cmd ? String(c.verify.cmd) : "";
122
+ let guidance = verifyCmd || "未指定验证命令,用只读取证";
123
+ if (isAuditor) {
124
+ guidance += ";独立跑 git status --porcelain 与 git diff 取证,不轻信 executor 自述";
125
+ }
126
+ toolGuidance = `tool guidance: ${guidance}`;
127
+
128
+ const scopeArr = Array.isArray(c.scope) ? c.scope.map(String) : [];
129
+ let boundaries;
130
+ if (isAuditor) {
131
+ boundaries = "零文件改动,只读取证";
132
+ } else {
133
+ boundaries = scopeArr.length > 0 ? scopeArr.join(", ") : "无文件可改,只读任务";
134
+ }
135
+ taskBoundaries = `task boundaries: ${boundaries}`;
136
+ }
137
+
138
+ let prompt = [objective, outputFormat, toolGuidance, taskBoundaries].join("\n");
139
+
140
+ // 轴模式:附上该轴的基线清单(Standards 轴的坏味道基线)。
141
+ // 清单必须内联进 prompt —— 审计 subagent 跑在**目标仓库**里,
142
+ // 读不到 carlos-flow 包内的文件,写成 docs/xxx.md 让它去读等于没写。
143
+ const axisCfg = axis ? AXIS_PROMPTS[axis] : null;
144
+ if (axisCfg && axisCfg.checklist) {
145
+ prompt += "\n\n" + renderChecklist(axisCfg.checklist);
146
+ }
147
+
148
+ if (extra && String(extra) !== "") {
149
+ prompt += "\n\n" + String(extra); // 原样附在末尾
150
+ }
151
+ return prompt;
152
+ }
153
+
154
+ // 快照:存在→复制到 RUNS_DIR/<id>/backup/<ts>_<name>;不存在→created:true;复制失败→error 且不中断其余
155
+ export function snapshotFiles(sid, paths, cwd) {
156
+ const bdir = path.join(RUNS_DIR, sanitizeId(sid), "backup");
157
+ fs.mkdirSync(bdir, { recursive: true });
158
+ const entries = [];
159
+ const list = Array.isArray(paths) ? paths : [];
160
+ for (const p of list) {
161
+ const ts = new Date().toISOString();
162
+ const orig = path.isAbsolute(p) ? p : path.join(cwd || process.cwd(), p);
163
+ if (!fs.existsSync(orig)) {
164
+ entries.push({ ts, orig, backup: null, created: true });
165
+ continue;
166
+ }
167
+ try {
168
+ // 生成随机后缀(确保是字符串)
169
+ const randSuffix = Math.random().toString(36).slice(2, 10) + Math.random().toString(36).slice(2, 10);
170
+ const backup = path.join(bdir, `${Date.now()}_${randSuffix}_${path.basename(orig)}`);
171
+ fs.copyFileSync(orig, backup);
172
+ // 完整性校验:比较大小
173
+ const srcStat = fs.statSync(orig);
174
+ const bakStat = fs.statSync(backup);
175
+ if (srcStat.size !== bakStat.size) {
176
+ fs.unlinkSync(backup);
177
+ entries.push({ ts, orig, error: "完整性校验失败(大小不匹配)" });
178
+ } else {
179
+ entries.push({ ts, orig, backup, created: false });
180
+ }
181
+ } catch (e) {
182
+ entries.push({ ts, orig, error: String(e) });
183
+ }
184
+ }
185
+ try {
186
+ const lines = entries.map((x) => JSON.stringify(x)).join("\n") + "\n";
187
+ fs.appendFileSync(path.join(RUNS_DIR, sanitizeId(sid), "backup", "manifest.jsonl"), lines, "utf8");
188
+ } catch (e) {
189
+ try {
190
+ process.stderr.write(`[flow-snapshot] manifest 追加失败: ${e && e.message ? e.message : e}\n`);
191
+ } catch {}
192
+ }
193
+ return entries;
194
+ }
195
+
196
+ export function readManifest(sid) {
197
+ const file = path.join(RUNS_DIR, sanitizeId(sid), "backup", "manifest.jsonl");
198
+ try {
199
+ const raw = fs.readFileSync(file, "utf8");
200
+ const all = [];
201
+ for (const line of raw.split("\n")) {
202
+ const t = line.trim();
203
+ if (!t) continue;
204
+ try {
205
+ all.push(JSON.parse(t));
206
+ } catch {}
207
+ }
208
+ // 只返回每个 orig 的最新条目(按 ts 去重)
209
+ const latest = new Map();
210
+ for (const e of all) {
211
+ if (!e || !e.orig) continue;
212
+ const existing = latest.get(e.orig);
213
+ if (!existing || e.ts > existing.ts) {
214
+ latest.set(e.orig, e);
215
+ }
216
+ }
217
+ return Array.from(latest.values());
218
+ } catch {
219
+ return [];
220
+ }
221
+ }
222
+
223
+ // 读取 manifest 所有条目(不去重),用于回滚计划
224
+ export function readManifestAll(sid) {
225
+ const file = path.join(RUNS_DIR, sanitizeId(sid), "backup", "manifest.jsonl");
226
+ try {
227
+ const raw = fs.readFileSync(file, "utf8");
228
+ const all = [];
229
+ for (const line of raw.split("\n")) {
230
+ const t = line.trim();
231
+ if (!t) continue;
232
+ try {
233
+ all.push(JSON.parse(line));
234
+ } catch {}
235
+ }
236
+ return all;
237
+ } catch {
238
+ return [];
239
+ }
240
+ }
241
+
242
+ // 写入派发 prompt 到文件,供主 Agent(Cindy)读取后通过 subagent 工具派发。
243
+ // 返回 prompt 文件路径,主 Agent 读取后自行调用 subagent 工具。
244
+ export function writeDispatchPrompt(sid, role, message, cwd) {
245
+ try {
246
+ const dir = path.join(RUNS_DIR, sanitizeId(sid), "dispatch");
247
+ fs.mkdirSync(dir, { recursive: true });
248
+ const file = path.join(dir, `${Date.now()}_${role}.prompt.txt`);
249
+ const content = message || "";
250
+ fs.writeFileSync(file, content, "utf8");
251
+ return { file, content };
252
+ } catch (e) {
253
+ return { file: null, content: null, error: String(e && e.message ? e.message : e) };
254
+ }
255
+ }
256
+
257
+ // 保存子 Agent 执行结果到会话目录
258
+ export function saveAgentResult(sid, role, stdout, stderr, code) {
259
+ try {
260
+ const dir = path.join(RUNS_DIR, sanitizeId(sid), "dispatch");
261
+ fs.mkdirSync(dir, { recursive: true });
262
+ const file = path.join(dir, `${Date.now()}_${role}.result.json`);
263
+ const rec = { ts: new Date().toISOString(), role, code: code ?? -1, stdout: String(stdout || ""), stderr: String(stderr || "") };
264
+ fs.writeFileSync(file, JSON.stringify(rec, null, 2), "utf8");
265
+ return file;
266
+ } catch {
267
+ return null;
268
+ }
269
+ }
270
+
271
+ // Phase 1-1: 执行验证命令并返回结果
272
+ //
273
+ // 跨平台:原先硬编码 `spawn("cmd", ["/c", cmd], { shell: true })` —— cmd.exe 只存在于 Windows,
274
+ // 在 Linux/macOS 上 `cmd` 不是可执行文件 → 命令根本没跑起来,
275
+ // exitCode=127(command not found),记 PASS 的前置证据永远拿不到,
276
+ // ubuntu CI 的 e2e 会整片变红。
277
+ //
278
+ // 现在按平台选 shell:
279
+ // · Windows:cmd.exe /c + shell:true(实测 shell:false 会把带引号的
280
+ // `node -e "process.exit(3)"` 的引号吃掉,退出码变成 0 而不是 3 ——
281
+ // 那样「验证失败必须拦住 PASS」的门禁就形同虚设);
282
+ // · POSIX:/bin/sh -c + shell:false(明确指定解释器,不依赖 PATH 里的 sh)。
283
+ export async function runVerifyCommand(cmd, cwd) {
284
+ if (!cmd || !cmd.trim()) {
285
+ return { ok: false, exitCode: -1, stdout: "", stderr: "验证命令为空" };
286
+ }
287
+ // 可选:拦截高危命令模式。
288
+ //
289
+ // 威胁模型说明(重要,不要夸大):
290
+ // · verify.cmd 本质上就是「执行用户指定的验证命令」—— 它的设计目标就是能跑任意命令
291
+ // (`npm test` / `pytest` / `cargo build` …),所以**默认不拦**。
292
+ // · 真正的风险来源是「verify.cmd 的来源可信度」:
293
+ // - 人工填写的任务卡 → 可信,是用户/Agent 的本意
294
+ // - 自动激活产生的占位卡 → activation 时 scope/acceptance 为空、**没有 verify.cmd**,
295
+ // 必须人工补齐才能过闸门 → 自动触发路径已被 activation 闸门挡住
296
+ // · 因此默认不拦是对的;把黑名单默认打开会误伤合法脚本
297
+ // (比如 `rm -rf node_modules` 出现在清理步骤里是完全合法的)。
298
+ // · 需要更严的用户可以打开 CARLOS_FLOW_BLOCK_DANGEROUS=1。
299
+ if (process.env.CARLOS_FLOW_BLOCK_DANGEROUS === "1") {
300
+ 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;
301
+ if (dangerous.test(cmd)) {
302
+ return {
303
+ ok: false,
304
+ exitCode: -1,
305
+ stdout: "",
306
+ stderr: `验证命令包含高危模式,已拒绝执行:${cmd}\n` +
307
+ "(CARLOS_FLOW_BLOCK_DANGEROUS=1 已开启;确认该命令安全后可关闭此开关)",
308
+ };
309
+ }
310
+ }
311
+ const isWindows = process.platform === "win32";
312
+ const shell = isWindows ? process.env.COMSPEC || "cmd.exe" : "/bin/sh";
313
+ const shellArgs = isWindows ? ["/c", cmd] : ["-c", cmd];
314
+ return new Promise((resolve) => {
315
+ const child = spawn(shell, shellArgs, {
316
+ cwd: cwd || process.cwd(),
317
+ stdio: ["ignore", "pipe", "pipe"],
318
+ shell: isWindows,
319
+ windowsHide: true,
320
+ });
321
+ let stdout = "";
322
+ let stderr = "";
323
+ child.stdout.on("data", (d) => { stdout += d.toString(); });
324
+ child.stderr.on("data", (d) => { stderr += d.toString(); });
325
+ const timeout = setTimeout(() => {
326
+ child.kill("SIGKILL");
327
+ resolve({ ok: false, exitCode: -1, stdout, stderr: stderr + "\n验证命令超时 (120s)" });
328
+ }, 120000);
329
+ child.on("close", (code) => {
330
+ clearTimeout(timeout);
331
+ resolve({ ok: code === 0, exitCode: code ?? -1, stdout, stderr });
332
+ });
333
+ child.on("error", (err) => {
334
+ clearTimeout(timeout);
335
+ resolve({ ok: false, exitCode: -1, stdout, stderr: String(err) });
336
+ });
337
+ });
338
+ }
339
+
340
+ // ---------------------------------------------------------------------------
341
+ // 输出指纹 + 负对照(negative control)
342
+ // ---------------------------------------------------------------------------
343
+
344
+ // 一次验证运行的输出指纹:exitCode + stdout + stderr。
345
+ //
346
+ // 为什么需要:裁定要绑定的是「一次可复现的运行」,而不是「我说测试过了」。
347
+ // 把输出哈希记进 last_verify,裁定时比对,就能发现「证据被换掉 / 命令不确定」。
348
+ export function computeOutputHash(exitCode, stdout, stderr) {
349
+ try {
350
+ const h = createHash("sha256");
351
+ h.update("exitCode=" + String(exitCode === undefined || exitCode === null ? -1 : exitCode));
352
+ h.update("\n");
353
+ h.update(typeof stdout === "string" ? stdout : "");
354
+ h.update("\n");
355
+ h.update(typeof stderr === "string" ? stderr : "");
356
+ return h.digest("hex");
357
+ } catch {
358
+ return "";
359
+ }
360
+ }
361
+
362
+ // 用快照 manifest 还原「派发时(改动前)」的工作区状态。
363
+ function restoreFromManifest(entries) {
364
+ for (const e of entries) {
365
+ if (!e || !e.orig) continue;
366
+ try {
367
+ if (e.created === true) {
368
+ // 派发时该文件不存在 → 删除当前文件
369
+ try { fs.unlinkSync(e.orig); } catch {}
370
+ } else if (e.backup) {
371
+ fs.mkdirSync(path.dirname(e.orig), { recursive: true });
372
+ fs.copyFileSync(e.backup, e.orig);
373
+ }
374
+ } catch (err) {
375
+ try { process.stderr.write(`[flow-falsify] 还原失败 ${e.orig}: ${err && err.message ? err.message : err}\n`); } catch {}
376
+ }
377
+ }
378
+ }
379
+
380
+ // 负对照:证明 verify.cmd 真的在测「本次改动」。
381
+ //
382
+ // 层次:这是「证据门禁」的执行侧 —— 不是让 LLM 声称「我试图证伪但没成功」,
383
+ // 而是让 harness 真的把工作区还原到改动前,跑同一命令,看它是否失败。
384
+ // 一个改动前就退 0 的测试是**空测试**,不构成任何证据(`|| true` / `echo ok` 就是这么漏过去的)。
385
+ //
386
+ // 安全:先把「改动后」的 scope 文件备份到临时目录,finally 里一定还原;
387
+ // 即使 verify 命令本身改动文件,也不会把工作区留在改动前状态。
388
+ //
389
+ // 局限(如实说明):快照只覆盖卡片 scope 内的文件。如果 verify.cmd 依赖 scope 外的
390
+ // 文件、而执行者又改了它们,「改动前」状态只是近似。此时负对照结论仅供参考。
391
+ export async function runNegativeControl(sid, cmd, cwd) {
392
+ const entries = readManifest(sid);
393
+ if (!entries.length) {
394
+ return { ok: false, error: "没有派发快照,无法做负对照(请先 flow_dispatch)" };
395
+ }
396
+ const tmpDir = path.join(RUNS_DIR, sanitizeId(sid), "negative_control", String(Date.now()));
397
+ try { fs.mkdirSync(tmpDir, { recursive: true }); } catch (e) {
398
+ return { ok: false, error: "无法创建负对照临时目录:" + (e && e.message ? e.message : e) };
399
+ }
400
+
401
+ // 1. 备份「改动后」的当前状态
402
+ const saved = [];
403
+ for (const e of entries) {
404
+ if (!e || !e.orig) continue;
405
+ const orig = e.orig;
406
+ const existed = fs.existsSync(orig);
407
+ let savedPath = null;
408
+ if (existed) {
409
+ try {
410
+ savedPath = path.join(tmpDir, `${saved.length}_${path.basename(orig)}`);
411
+ fs.copyFileSync(orig, savedPath);
412
+ } catch (err) {
413
+ try { process.stderr.write(`[flow-falsify] 备份当前文件失败 ${orig}: ${err && err.message ? err.message : err}\n`); } catch {}
414
+ }
415
+ }
416
+ saved.push({ orig, savedPath, existed });
417
+ }
418
+
419
+ // 还原「改动后」状态(无论后续发生什么)
420
+ const restoreCurrent = () => {
421
+ for (const s of saved) {
422
+ try {
423
+ if (s.existed && s.savedPath) {
424
+ fs.mkdirSync(path.dirname(s.orig), { recursive: true });
425
+ fs.copyFileSync(s.savedPath, s.orig);
426
+ } else if (!s.existed) {
427
+ // 当前状态里该文件不存在(executor 删了它)→ 保持删除
428
+ try { fs.unlinkSync(s.orig); } catch {}
429
+ }
430
+ } catch (err) {
431
+ try { process.stderr.write(`[flow-falsify] 还原当前文件失败 ${s.orig}: ${err && err.message ? err.message : err}\n`); } catch {}
432
+ }
433
+ }
434
+ };
435
+
436
+ let before = null;
437
+ let after = null;
438
+ try {
439
+ // 2. 还原「改动前」
440
+ restoreFromManifest(entries);
441
+ // 3. 跑改动前 —— 必须失败
442
+ before = await runVerifyCommand(cmd, cwd);
443
+ // 4. 还原「改动后」
444
+ restoreCurrent();
445
+ // 5. 跑改动后 —— 必须通过
446
+ after = await runVerifyCommand(cmd, cwd);
447
+ } finally {
448
+ // 无论如何都还原改动后状态
449
+ restoreCurrent();
450
+ }
451
+
452
+ const beforeHash = computeOutputHash(before.exitCode, before.stdout, before.stderr);
453
+ const afterHash = computeOutputHash(after.exitCode, after.stdout, after.stderr);
454
+
455
+ let verdict = "inconclusive";
456
+ let reason = "";
457
+ if (before.ok === true) {
458
+ // 改动前就通过 → 空测试
459
+ verdict = "vacuous";
460
+ reason = "verify.cmd 在改动前就通过(exitCode=" + before.exitCode + ")—— 它没有测本次改动,是空测试";
461
+ } else if (after.ok !== true) {
462
+ verdict = "not_passing";
463
+ reason = "verify.cmd 在改动后未通过(exitCode=" + after.exitCode + ")—— 改动本身有问题";
464
+ } else {
465
+ verdict = "meaningful";
466
+ reason = "改动前失败(exitCode=" + before.exitCode + ")+ 改动后通过(exitCode=" + after.exitCode + ")—— 测试有判别力";
467
+ }
468
+
469
+ // 清理临时目录(还原已完成,不再需要备份)
470
+ try { fs.rmSync(tmpDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }); } catch {}
471
+
472
+ return {
473
+ ok: true,
474
+ verdict,
475
+ reason,
476
+ before: { exitCode: before.exitCode, ok: before.ok, hash: beforeHash, stdout: before.stdout, stderr: before.stderr },
477
+ after: { exitCode: after.exitCode, ok: after.ok, hash: afterHash, stdout: after.stdout, stderr: after.stderr },
478
+ };
479
+ }
480
+
481
+ // Phase 1-1: scope 机器校验 - 对比 diff 与 card.scope
482
+ //
483
+ // 用法:enforceScope(scope, cwd, diffFiles?)
484
+ // - scope: 卡片中的 scope 白名单
485
+ // - cwd: 仓库根目录(用于跑 git diff)
486
+ // - diffFiles?: 可选,外部传入的改动文件列表;不传则自动跑 `git diff --name-only`
487
+ // 返回:{ ok, violations[], message? }
488
+ //
489
+ // 设计:
490
+ // · 空 scope = 白名单为空 = fail-closed(所有变更都算越界)
491
+ // · 无变更(diffFiles 为空)= 直接 ok
492
+ // · 自动跑 `git diff --name-only`:派发前快照 vs 当前工作区
493
+ // · 精确匹配 + 父目录匹配:scope 内文件及其子目录均算通过
494
+ export function enforceScope(scope, cwd, diffFiles) {
495
+ // diffFiles 可选:外部传入的改动文件列表;不传则自动跑 `git diff --name-only`
496
+ // cwd: 仓库根目录(用于跑 git diff)
497
+ let autoCollected = false;
498
+ if (!diffFiles) {
499
+ autoCollected = true;
500
+ diffFiles = [];
501
+ try {
502
+ const proc = spawnSync("git", ["diff", "--name-only"], {
503
+ cwd: cwd || process.cwd(),
504
+ encoding: "utf8",
505
+ // git 不在 PATH / 不是仓库 / 超时 → 一律当作「无改动」而非抛错,
506
+ // 避免把环境问题变成门禁误报(fail-closed 只针对 scope 语义,不针对环境)
507
+ timeout: 10000,
508
+ windowsHide: true,
509
+ });
510
+ if (proc.status === 0 && typeof proc.stdout === "string") {
511
+ diffFiles = proc.stdout.split("\n").map((s) => s.trim()).filter(Boolean);
512
+ }
513
+ } catch { diffFiles = []; }
514
+ }
515
+
516
+ // 没有任何变更 → 无需判定
517
+ if (!Array.isArray(diffFiles) || diffFiles.length === 0) {
518
+ return { ok: true, violations: [], checked: [] };
519
+ }
520
+
521
+ // 空 scope = 白名单为空 = **不允许改动任何文件**。
522
+ // 早期实现直接 return { ok: true },等于「白名单为空 → 随便改」,
523
+ // 是 fail-open 漏洞;这里改为 fail-closed:所有变更都算越界。
524
+ if (!Array.isArray(scope) || scope.length === 0) {
525
+ return {
526
+ ok: false,
527
+ violations: diffFiles.slice(),
528
+ checked: diffFiles.slice(),
529
+ message: `越界改动(卡片 scope 为空,不允许修改任何文件):${diffFiles.join(", ")}`,
530
+ };
531
+ }
532
+
533
+ const scopeSet = new Set(scope.map(p => path.normalize(p)));
534
+ const violations = [];
535
+
536
+ for (const file of diffFiles) {
537
+ const normalized = path.normalize(file);
538
+ // 检查文件是否在 scope 内(精确匹配或父目录匹配)
539
+ let allowed = false;
540
+ for (const scopePath of scopeSet) {
541
+ const normalizedScope = path.normalize(scopePath);
542
+ if (normalized === normalizedScope || normalized.startsWith(normalizedScope + path.sep)) {
543
+ allowed = true;
544
+ break;
545
+ }
546
+ }
547
+ if (!allowed) {
548
+ violations.push(file);
549
+ }
550
+ }
551
+
552
+ if (violations.length > 0) {
553
+ return { ok: false, violations, checked: diffFiles.slice(), message: `越界改动(超出 scope):${violations.join(", ")}` };
554
+ }
555
+ return { ok: true, violations: [], checked: diffFiles.slice() };
556
+ }
557
+