carlos-flow 2.12.6 → 2.12.8
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/AGENTS.md +5 -5
- package/CHANGELOG.md +663 -660
- package/README.en.md +29 -0
- package/README.md +39 -0
- package/README.zh.md +39 -0
- package/TRIGGER_GUIDE.md +2 -2
- package/bridge/mcp-bridge.js +203 -203
- package/check-all.sh +0 -0
- package/ghost.json +1 -7
- package/package.json +114 -114
- package/plugins/carlos-flow-trigger.js +215 -215
- package/scripts/check-no-dead-handler.mjs +87 -87
- package/scripts/check-templates.mjs +126 -126
- package/scripts/clean-readme-noise.mjs +53 -53
- package/scripts/install-hooks.mjs +166 -166
- package/scripts/lang-audit.mjs +172 -172
- package/scripts/mutation-check.mjs +483 -483
- package/scripts/release.mjs +6 -6
- package/scripts/sync-readme.mjs +102 -102
- package/scripts/verify-activation-e2e.sh +55 -55
- package/smoke-test.js +142 -142
- package/src/card.js +296 -296
- package/src/commander.js +9 -9
- package/src/dispatch.js +750 -557
- package/src/index.js +1808 -1713
- package/src/protocol.js +95 -95
- package/src/state.js +930 -930
- package/src/trigger.js +909 -909
package/src/dispatch.js
CHANGED
|
@@ -1,557 +1,750 @@
|
|
|
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
|
-
//
|
|
381
|
-
//
|
|
382
|
-
//
|
|
383
|
-
|
|
384
|
-
//
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
}
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
//
|
|
482
|
-
//
|
|
483
|
-
//
|
|
484
|
-
//
|
|
485
|
-
//
|
|
486
|
-
//
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
const
|
|
534
|
-
const
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
}
|
|
555
|
-
|
|
556
|
-
|
|
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
|
+
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
|
+
// ---------------------------------------------------------------------------
|
|
381
|
+
// 负对照的状态工具:把「改动前态」「改动后态」显式化、可证明
|
|
382
|
+
// ---------------------------------------------------------------------------
|
|
383
|
+
|
|
384
|
+
// 文件内容摘要:存在→sha256 十六进制;不存在→"ABSENT";无法读取→"UNKNOWN"
|
|
385
|
+
function digestOf(file) {
|
|
386
|
+
if (!file) return "ABSENT";
|
|
387
|
+
try {
|
|
388
|
+
return createHash("sha256").update(fs.readFileSync(file)).digest("hex");
|
|
389
|
+
} catch (e) {
|
|
390
|
+
if (e && (e.code === "ENOENT" || e.code === "ENOTDIR")) return "ABSENT";
|
|
391
|
+
return "UNKNOWN";
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
// 状态指纹:一组 {文件路径: 摘要} → 稳定 sha256。
|
|
396
|
+
// 用途:证明「改动前」「改动后」确实是**两个可区分的状态**,而不是同一份内容跑两遍。
|
|
397
|
+
function fingerprintOfState(digests) {
|
|
398
|
+
const lines = Object.keys(digests).sort().map((k) => k + "=" + digests[k]);
|
|
399
|
+
return createHash("sha256").update(lines.join("\n")).digest("hex");
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
// 比较「改动前」态与某个候选「改动后」态。
|
|
403
|
+
// changed:内容确实不同的文件(= 本次改动留下的痕迹)
|
|
404
|
+
// unknown:状态不可还原/不可读的文件(无法证明)
|
|
405
|
+
function diffStates(pre, post) {
|
|
406
|
+
const changed = [];
|
|
407
|
+
const unknown = [];
|
|
408
|
+
for (const k of Object.keys(pre)) {
|
|
409
|
+
const a = pre[k];
|
|
410
|
+
const b = Object.prototype.hasOwnProperty.call(post, k) ? post[k] : "UNKNOWN";
|
|
411
|
+
if (a === "UNKNOWN" || b === "UNKNOWN") { unknown.push(k); continue; }
|
|
412
|
+
if (a !== b) changed.push(k);
|
|
413
|
+
}
|
|
414
|
+
for (const k of Object.keys(post)) {
|
|
415
|
+
if (Object.prototype.hasOwnProperty.call(pre, k)) continue;
|
|
416
|
+
const b = post[k];
|
|
417
|
+
if (b === "UNKNOWN") { unknown.push(k); continue; }
|
|
418
|
+
if (b !== "ABSENT") changed.push(k);
|
|
419
|
+
}
|
|
420
|
+
return { changed, unknown };
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
// 「改动后」态的**显式记录**文件。
|
|
424
|
+
//
|
|
425
|
+
// 为什么要单独一个文件:manifest.jsonl 的语义是「派发时的改动前快照」,
|
|
426
|
+
// restoreFromManifest() 完全依赖这个语义。把改动后态写进 manifest 会污染它,
|
|
427
|
+
// 导致「还原改动前」还原成「改动后」——负对照直接失效。
|
|
428
|
+
// 因此改动后态单独落在 backup/after_state.jsonl + backup/after_state_<ts>/ 目录。
|
|
429
|
+
function afterStateFile(sid) {
|
|
430
|
+
return path.join(RUNS_DIR, sanitizeId(sid), "backup", "after_state.jsonl");
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
// 读取本会话最近一次记录的「改动后」态(按追加顺序,后写的覆盖先写的)
|
|
434
|
+
function readAfterState(sid) {
|
|
435
|
+
const latest = new Map();
|
|
436
|
+
try {
|
|
437
|
+
const raw = fs.readFileSync(afterStateFile(sid), "utf8");
|
|
438
|
+
for (const line of raw.split("\n")) {
|
|
439
|
+
const t = line.trim();
|
|
440
|
+
if (!t) continue;
|
|
441
|
+
try {
|
|
442
|
+
const e = JSON.parse(t);
|
|
443
|
+
if (!e || !e.orig) continue;
|
|
444
|
+
latest.set(e.orig, e);
|
|
445
|
+
} catch {}
|
|
446
|
+
}
|
|
447
|
+
} catch {}
|
|
448
|
+
return Array.from(latest.values());
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
// 追加记录「改动后」态
|
|
452
|
+
function writeAfterState(sid, records) {
|
|
453
|
+
try {
|
|
454
|
+
const file = afterStateFile(sid);
|
|
455
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
456
|
+
const lines = records.map((r) => JSON.stringify(r)).join("\n") + "\n";
|
|
457
|
+
fs.appendFileSync(file, lines, "utf8");
|
|
458
|
+
} catch (e) {
|
|
459
|
+
try { process.stderr.write(`[flow-falsify] 记录改动后态失败: ${e && e.message ? e.message : e}\n`); } catch {}
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
// 负对照:证明 verify.cmd 真的在测「本次改动」。
|
|
464
|
+
//
|
|
465
|
+
// 层次:这是「证据门禁」的执行侧 —— 不是让 LLM 声称「我试图证伪但没成功」,
|
|
466
|
+
// 而是让 harness 真的把工作区还原到改动前,跑同一命令,看它是否失败。
|
|
467
|
+
// 一个改动前就退 0 的测试是**空测试**,不构成任何证据(`|| true` / `echo ok` 就是这么漏过去的)。
|
|
468
|
+
//
|
|
469
|
+
// 判定依据(本次修复的核心 —— 去掉隐含前提):
|
|
470
|
+
// before 与 after 必须是**两个可区分的状态**,否则「前失败/后通过」就没有归因意义。
|
|
471
|
+
// 本实现把两态都显式构造出来,并逐文件比对内容摘要:
|
|
472
|
+
// · 改动前态 = 派发快照 manifest 的备份(restoreFromManifest);
|
|
473
|
+
// · 改动后态 = ①当前工作区(显式捕获后再显式还原),
|
|
474
|
+
// ②本会话上次负对照**显式记录**下来的改动后态(backup/after_state.jsonl);
|
|
475
|
+
// 当①与改动前态逐字节一致(=工作区里根本没有改动后状态,例如主 Agent 手工改动后
|
|
476
|
+
// 未走标准派发窗口、或改动被回退)时,才启用②作为改动后态;
|
|
477
|
+
// 两者都没有可用时,如实标注「前后是同一状态」,并按保守口径判负对照,
|
|
478
|
+
// 绝不把「同一状态跑两遍」当成 meaningful。
|
|
479
|
+
// 改动后态在每次负对照后被显式落盘记录(after_state.jsonl + after_state_<ts>/),
|
|
480
|
+
// 于是「改动后应有的状态」不再依赖「调用时工作区恰好已经是改动后」这个隐含前提。
|
|
481
|
+
//
|
|
482
|
+
// 安全:先把进入时的 scope 文件备份到临时目录,finally 里一定还原成进入时的样子;
|
|
483
|
+
// 即使 verify 命令本身改动文件,也不会把工作区留在改动前状态。
|
|
484
|
+
//
|
|
485
|
+
// 局限(如实说明):快照只覆盖卡片 scope 内的文件。如果 verify.cmd 依赖 scope 外的
|
|
486
|
+
// 文件、而执行者又改了它们,「改动前」状态只是近似。此时负对照结论仅供参考。
|
|
487
|
+
export async function runNegativeControl(sid, cmd, cwd) {
|
|
488
|
+
const entries = readManifest(sid);
|
|
489
|
+
if (!entries.length) {
|
|
490
|
+
return { ok: false, error: "没有派发快照,无法做负对照(请先 flow_dispatch)" };
|
|
491
|
+
}
|
|
492
|
+
const tmpDir = path.join(RUNS_DIR, sanitizeId(sid), "negative_control", String(Date.now()));
|
|
493
|
+
try { fs.mkdirSync(tmpDir, { recursive: true }); } catch (e) {
|
|
494
|
+
return { ok: false, error: "无法创建负对照临时目录:" + (e && e.message ? e.message : e) };
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
// ---- 状态 A:改动前态(派发时的快照,来自 manifest 备份) ----
|
|
498
|
+
const preDigests = {};
|
|
499
|
+
for (const e of entries) {
|
|
500
|
+
if (!e || !e.orig) continue;
|
|
501
|
+
if (e.created === true) preDigests[e.orig] = "ABSENT";
|
|
502
|
+
else if (e.backup) preDigests[e.orig] = digestOf(e.backup);
|
|
503
|
+
else preDigests[e.orig] = "UNKNOWN"; // 备份缺失 → 改动前态无法完整还原
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
// ---- 状态 B:改动后候选① —— 当前工作区(显式捕获,之后显式还原) ----
|
|
507
|
+
const saved = [];
|
|
508
|
+
for (const e of entries) {
|
|
509
|
+
if (!e || !e.orig) continue;
|
|
510
|
+
const orig = e.orig;
|
|
511
|
+
const existed = fs.existsSync(orig);
|
|
512
|
+
let savedPath = null;
|
|
513
|
+
if (existed) {
|
|
514
|
+
try {
|
|
515
|
+
savedPath = path.join(tmpDir, `${saved.length}_${path.basename(orig)}`);
|
|
516
|
+
fs.copyFileSync(orig, savedPath);
|
|
517
|
+
} catch (err) {
|
|
518
|
+
try { process.stderr.write(`[flow-falsify] 备份当前文件失败 ${orig}: ${err && err.message ? err.message : err}\n`); } catch {}
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
saved.push({ orig, savedPath, existed });
|
|
522
|
+
}
|
|
523
|
+
const currentDigests = {};
|
|
524
|
+
for (const s of saved) {
|
|
525
|
+
if (!s.existed) currentDigests[s.orig] = "ABSENT";
|
|
526
|
+
else if (s.savedPath) currentDigests[s.orig] = digestOf(s.savedPath);
|
|
527
|
+
else currentDigests[s.orig] = "UNKNOWN";
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
// ---- 状态 C:改动后候选② —— 本会话显式记录过的改动后态 ----
|
|
531
|
+
const recorded = readAfterState(sid);
|
|
532
|
+
const recordedMap = new Map();
|
|
533
|
+
const recordedDigests = {};
|
|
534
|
+
for (const r of recorded) {
|
|
535
|
+
if (!r || !r.orig) continue;
|
|
536
|
+
recordedMap.set(r.orig, r);
|
|
537
|
+
recordedDigests[r.orig] = r.absent === true ? "ABSENT" : digestOf(r.backup);
|
|
538
|
+
}
|
|
539
|
+
// 只有当记录覆盖了本次快照的全部文件时,才敢把它当作完整的「改动后态」
|
|
540
|
+
const recordedCoversAll = entries.every((e) => e && e.orig && recordedMap.has(e.orig));
|
|
541
|
+
|
|
542
|
+
// ---- 选定改动后态:优先当前工作区;当前工作区与改动前态完全一致时,退回显式记录 ----
|
|
543
|
+
const curDiff = diffStates(preDigests, currentDigests);
|
|
544
|
+
const recDiff = diffStates(preDigests, recordedDigests);
|
|
545
|
+
let afterSource = "workspace";
|
|
546
|
+
let afterDigests = currentDigests;
|
|
547
|
+
let changedFiles = curDiff.changed;
|
|
548
|
+
let unknownFiles = curDiff.unknown;
|
|
549
|
+
if (curDiff.changed.length === 0 && recordedCoversAll && recDiff.changed.length > 0) {
|
|
550
|
+
afterSource = "recorded";
|
|
551
|
+
afterDigests = recordedDigests;
|
|
552
|
+
changedFiles = recDiff.changed;
|
|
553
|
+
unknownFiles = recDiff.unknown;
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
// 还原「改动后」状态(无论后续发生什么)
|
|
557
|
+
const restoreCurrent = () => {
|
|
558
|
+
for (const s of saved) {
|
|
559
|
+
try {
|
|
560
|
+
if (s.existed && s.savedPath) {
|
|
561
|
+
fs.mkdirSync(path.dirname(s.orig), { recursive: true });
|
|
562
|
+
fs.copyFileSync(s.savedPath, s.orig);
|
|
563
|
+
} else if (!s.existed) {
|
|
564
|
+
// 当前状态里该文件不存在(executor 删了它)→ 保持删除
|
|
565
|
+
try { fs.unlinkSync(s.orig); } catch {}
|
|
566
|
+
}
|
|
567
|
+
} catch (err) {
|
|
568
|
+
try { process.stderr.write(`[flow-falsify] 还原当前文件失败 ${s.orig}: ${err && err.message ? err.message : err}\n`); } catch {}
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
};
|
|
572
|
+
|
|
573
|
+
// 还原「显式记录的改动后态」
|
|
574
|
+
const restoreRecorded = () => {
|
|
575
|
+
for (const r of recorded) {
|
|
576
|
+
if (!r || !r.orig) continue;
|
|
577
|
+
try {
|
|
578
|
+
if (r.absent === true) {
|
|
579
|
+
try { fs.unlinkSync(r.orig); } catch {}
|
|
580
|
+
} else if (r.backup) {
|
|
581
|
+
fs.mkdirSync(path.dirname(r.orig), { recursive: true });
|
|
582
|
+
fs.copyFileSync(r.backup, r.orig);
|
|
583
|
+
}
|
|
584
|
+
} catch (err) {
|
|
585
|
+
try { process.stderr.write(`[flow-falsify] 还原记录的改动后态失败 ${r.orig}: ${err && err.message ? err.message : err}\n`); } catch {}
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
};
|
|
589
|
+
|
|
590
|
+
// ---- 把选定的「改动后态」显式落盘记录(让下次负对照能按记录还原,而不是靠隐含前提) ----
|
|
591
|
+
try {
|
|
592
|
+
const afterDir = path.join(RUNS_DIR, sanitizeId(sid), "backup", "after_state_" + Date.now());
|
|
593
|
+
fs.mkdirSync(afterDir, { recursive: true });
|
|
594
|
+
const ts = new Date().toISOString();
|
|
595
|
+
const records = [];
|
|
596
|
+
for (const s of saved) {
|
|
597
|
+
let backup = null;
|
|
598
|
+
let absent = false;
|
|
599
|
+
if (afterSource === "recorded") {
|
|
600
|
+
const r = recordedMap.get(s.orig);
|
|
601
|
+
if (r) { absent = r.absent === true; backup = r.absent === true ? null : r.backup; }
|
|
602
|
+
} else if (!s.existed) {
|
|
603
|
+
absent = true;
|
|
604
|
+
} else if (s.savedPath) {
|
|
605
|
+
backup = path.join(afterDir, `${records.length}_${path.basename(s.orig)}`);
|
|
606
|
+
fs.copyFileSync(s.savedPath, backup);
|
|
607
|
+
}
|
|
608
|
+
records.push({ ts, orig: s.orig, backup, absent });
|
|
609
|
+
}
|
|
610
|
+
writeAfterState(sid, records);
|
|
611
|
+
} catch (e) {
|
|
612
|
+
try { process.stderr.write(`[flow-falsify] 快照改动后态失败: ${e && e.message ? e.message : e}\n`); } catch {}
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
let before = null;
|
|
616
|
+
let after = null;
|
|
617
|
+
try {
|
|
618
|
+
// 1. 还原「改动前」(派发快照)—— 必须失败
|
|
619
|
+
restoreFromManifest(entries);
|
|
620
|
+
before = await runVerifyCommand(cmd, cwd);
|
|
621
|
+
// 2. 显式还原「改动后」态再跑第二次 —— 必须通过
|
|
622
|
+
if (afterSource === "recorded") restoreRecorded();
|
|
623
|
+
else restoreCurrent();
|
|
624
|
+
after = await runVerifyCommand(cmd, cwd);
|
|
625
|
+
} finally {
|
|
626
|
+
// 无论如何都把工作区还原成进入负对照时的样子
|
|
627
|
+
restoreCurrent();
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
const beforeHash = computeOutputHash(before.exitCode, before.stdout, before.stderr);
|
|
631
|
+
const afterHash = computeOutputHash(after.exitCode, after.stdout, after.stderr);
|
|
632
|
+
const beforeStateHash = fingerprintOfState(preDigests);
|
|
633
|
+
const afterStateHash = fingerprintOfState(afterDigests);
|
|
634
|
+
|
|
635
|
+
// 两态是否可区分 —— 判定的前提,必须写进 reason(不能靠隐含假设)
|
|
636
|
+
const stateNote = changedFiles.length > 0
|
|
637
|
+
? ";改动后态来源=" + (afterSource === "recorded" ? "上次负对照显式记录的改动后态" : "当前工作区") +
|
|
638
|
+
",检出改动文件 " + changedFiles.length + " 个:" + changedFiles.join(", ")
|
|
639
|
+
: (unknownFiles.length > 0
|
|
640
|
+
? ";无法确认改动后态:" + unknownFiles.length + " 个文件状态不可还原/不可读(" + unknownFiles.join(", ") + ")"
|
|
641
|
+
: ";未检出任何改动:工作区与派发快照逐字节一致,「改动前」「改动后」是同一状态");
|
|
642
|
+
|
|
643
|
+
let verdict = "";
|
|
644
|
+
let reason = "";
|
|
645
|
+
if (before.ok === true) {
|
|
646
|
+
// 改动前就通过 → 空测试
|
|
647
|
+
verdict = "vacuous";
|
|
648
|
+
reason = "verify.cmd 在改动前就通过(exitCode=" + before.exitCode + ")—— 它没有测本次改动,是空测试" + stateNote;
|
|
649
|
+
} else if (after.ok !== true) {
|
|
650
|
+
verdict = "not_passing";
|
|
651
|
+
reason = "verify.cmd 在改动后未通过(exitCode=" + after.exitCode + ")—— 改动本身有问题" + stateNote;
|
|
652
|
+
} else if (changedFiles.length > 0) {
|
|
653
|
+
verdict = "meaningful";
|
|
654
|
+
reason = "改动前失败(exitCode=" + before.exitCode + ")+ 改动后通过(exitCode=" + after.exitCode + ")—— 测试有判别力" + stateNote;
|
|
655
|
+
} else {
|
|
656
|
+
// 两次运行处于同一状态 → 结果差异不可能来自本次改动(只可能来自命令本身的不确定)
|
|
657
|
+
verdict = "vacuous";
|
|
658
|
+
reason = "改动前失败(exitCode=" + before.exitCode + ")+ 改动后通过(exitCode=" + after.exitCode + ")," +
|
|
659
|
+
"但两次运行处于同一状态(未检出任何改动文件)—— 结果差异无法归因于本次改动," +
|
|
660
|
+
"不能证明该命令在测本次改动,按保守口径记为空测试" + stateNote;
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
// 清理临时目录(还原已完成,不再需要备份)
|
|
664
|
+
try { fs.rmSync(tmpDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }); } catch {}
|
|
665
|
+
|
|
666
|
+
return {
|
|
667
|
+
ok: true,
|
|
668
|
+
verdict,
|
|
669
|
+
reason,
|
|
670
|
+
before: { exitCode: before.exitCode, ok: before.ok, hash: beforeHash, stdout: before.stdout, stderr: before.stderr, state_hash: beforeStateHash },
|
|
671
|
+
after: { exitCode: after.exitCode, ok: after.ok, hash: afterHash, stdout: after.stdout, stderr: after.stderr, state_hash: afterStateHash },
|
|
672
|
+
};
|
|
673
|
+
}
|
|
674
|
+
// Phase 1-1: scope 机器校验 - 对比 diff 与 card.scope
|
|
675
|
+
//
|
|
676
|
+
// 用法:enforceScope(scope, cwd, diffFiles?)
|
|
677
|
+
// - scope: 卡片中的 scope 白名单
|
|
678
|
+
// - cwd: 仓库根目录(用于跑 git diff)
|
|
679
|
+
// - diffFiles?: 可选,外部传入的改动文件列表;不传则自动跑 `git diff --name-only`
|
|
680
|
+
// 返回:{ ok, violations[], message? }
|
|
681
|
+
//
|
|
682
|
+
// 设计:
|
|
683
|
+
// · 空 scope = 白名单为空 = fail-closed(所有变更都算越界)
|
|
684
|
+
// · 无变更(diffFiles 为空)= 直接 ok
|
|
685
|
+
// · 自动跑 `git diff --name-only`:派发前快照 vs 当前工作区
|
|
686
|
+
// · 精确匹配 + 父目录匹配:scope 内文件及其子目录均算通过
|
|
687
|
+
export function enforceScope(scope, cwd, diffFiles) {
|
|
688
|
+
// diffFiles 可选:外部传入的改动文件列表;不传则自动跑 `git diff --name-only`
|
|
689
|
+
// cwd: 仓库根目录(用于跑 git diff)
|
|
690
|
+
let autoCollected = false;
|
|
691
|
+
if (!diffFiles) {
|
|
692
|
+
autoCollected = true;
|
|
693
|
+
diffFiles = [];
|
|
694
|
+
try {
|
|
695
|
+
const proc = spawnSync("git", ["diff", "--name-only"], {
|
|
696
|
+
cwd: cwd || process.cwd(),
|
|
697
|
+
encoding: "utf8",
|
|
698
|
+
// git 不在 PATH / 不是仓库 / 超时 → 一律当作「无改动」而非抛错,
|
|
699
|
+
// 避免把环境问题变成门禁误报(fail-closed 只针对 scope 语义,不针对环境)
|
|
700
|
+
timeout: 10000,
|
|
701
|
+
windowsHide: true,
|
|
702
|
+
});
|
|
703
|
+
if (proc.status === 0 && typeof proc.stdout === "string") {
|
|
704
|
+
diffFiles = proc.stdout.split("\n").map((s) => s.trim()).filter(Boolean);
|
|
705
|
+
}
|
|
706
|
+
} catch { diffFiles = []; }
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
// 没有任何变更 → 无需判定
|
|
710
|
+
if (!Array.isArray(diffFiles) || diffFiles.length === 0) {
|
|
711
|
+
return { ok: true, violations: [], checked: [] };
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
// 空 scope = 白名单为空 = **不允许改动任何文件**。
|
|
715
|
+
// 早期实现直接 return { ok: true },等于「白名单为空 → 随便改」,
|
|
716
|
+
// 是 fail-open 漏洞;这里改为 fail-closed:所有变更都算越界。
|
|
717
|
+
if (!Array.isArray(scope) || scope.length === 0) {
|
|
718
|
+
return {
|
|
719
|
+
ok: false,
|
|
720
|
+
violations: diffFiles.slice(),
|
|
721
|
+
checked: diffFiles.slice(),
|
|
722
|
+
message: `越界改动(卡片 scope 为空,不允许修改任何文件):${diffFiles.join(", ")}`,
|
|
723
|
+
};
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
const scopeSet = new Set(scope.map(p => path.normalize(p)));
|
|
727
|
+
const violations = [];
|
|
728
|
+
|
|
729
|
+
for (const file of diffFiles) {
|
|
730
|
+
const normalized = path.normalize(file);
|
|
731
|
+
// 检查文件是否在 scope 内(精确匹配或父目录匹配)
|
|
732
|
+
let allowed = false;
|
|
733
|
+
for (const scopePath of scopeSet) {
|
|
734
|
+
const normalizedScope = path.normalize(scopePath);
|
|
735
|
+
if (normalized === normalizedScope || normalized.startsWith(normalizedScope + path.sep)) {
|
|
736
|
+
allowed = true;
|
|
737
|
+
break;
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
if (!allowed) {
|
|
741
|
+
violations.push(file);
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
if (violations.length > 0) {
|
|
746
|
+
return { ok: false, violations, checked: diffFiles.slice(), message: `越界改动(超出 scope):${violations.join(", ")}` };
|
|
747
|
+
}
|
|
748
|
+
return { ok: true, violations: [], checked: diffFiles.slice() };
|
|
749
|
+
}
|
|
750
|
+
|