carlos-flow 2.13.0 → 2.14.1
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 +27 -2
- package/CHANGELOG.md +26 -0
- package/README.en.md +40 -2
- package/README.md +39 -3
- package/README.zh.md +39 -3
- package/TRIGGER_GUIDE.md +3 -3
- package/bridge/mcp-bridge.js +106 -6
- package/client/carlos.js +187 -4
- package/ghost.json +19 -559
- package/main.js +267 -0
- package/package.json +12 -7
- package/scripts/check-stubs.mjs +1 -1
- package/scripts/check-templates.mjs +42 -3
- package/scripts/full-audit.mjs +66 -6
- package/scripts/lang-audit.mjs +7 -1
- package/scripts/mutation-check.mjs +74 -7
- package/src/dispatch.js +204 -17
- package/src/index.js +208 -74
- package/src/mcp-stdio.mjs +139 -0
- package/src/protocol.js +182 -1
- package/src/state.js +36 -4
|
@@ -164,10 +164,12 @@ const MUTANTS = [
|
|
|
164
164
|
desc: "enforceScope 遇到任何越界都返回 ok:true → 越界改动直接放行",
|
|
165
165
|
file: "src/dispatch.js",
|
|
166
166
|
from: ` if (violations.length > 0) {
|
|
167
|
-
|
|
167
|
+
const msg = \`越界改动(超出 scope):\${violations.join(", ")}\`;
|
|
168
|
+
return { ok: false, violations, checked: diffFiles.slice(), message: formatError(msg) };
|
|
168
169
|
}`,
|
|
169
170
|
to: ` if (violations.length > 0) {
|
|
170
|
-
|
|
171
|
+
const msg = \`越界改动(超出 scope):\${violations.join(", ")}\`;
|
|
172
|
+
return { ok: true, violations, checked: diffFiles.slice(), message: formatError(msg) }; // MUTANT: fail-open
|
|
171
173
|
}`,
|
|
172
174
|
},
|
|
173
175
|
{
|
|
@@ -188,13 +190,35 @@ const MUTANTS = [
|
|
|
188
190
|
ok: false,
|
|
189
191
|
violations: diffFiles.slice(),
|
|
190
192
|
checked: diffFiles.slice(),
|
|
191
|
-
message: \`越界改动(卡片 scope 为空,不允许修改任何文件):\${diffFiles.join(", ")}
|
|
193
|
+
message: formatError(\`越界改动(卡片 scope 为空,不允许修改任何文件):\${diffFiles.join(", ")}\`),
|
|
192
194
|
};
|
|
193
195
|
}`,
|
|
194
196
|
to: ` if (!Array.isArray(scope) || scope.length === 0) {
|
|
195
197
|
return { ok: true, violations: [] }; // MUTANT: fail-open
|
|
196
198
|
}`,
|
|
197
199
|
},
|
|
200
|
+
{
|
|
201
|
+
id: "M18-项目级敏感规则不生效",
|
|
202
|
+
desc: "isSensitive 在判定完内置基线后直接 return false(.carlos.json 追加的规则全部失效)",
|
|
203
|
+
file: "src/protocol.js",
|
|
204
|
+
from: ` // 项目级扩展(只能追加;为空时零开销)
|
|
205
|
+
if (EXTRA_SENSITIVE.names.size && EXTRA_SENSITIVE.names.has(base)) return true;`,
|
|
206
|
+
to: ` return false; // MUTANT: 项目级敏感规则不生效`,
|
|
207
|
+
},
|
|
208
|
+
{
|
|
209
|
+
id: "M19-负对照还原不核对",
|
|
210
|
+
desc: "把还原后的逐文件摘要核对换成恒真(工作区可能停在改动前却报 ok)",
|
|
211
|
+
file: "src/dispatch.js",
|
|
212
|
+
from: ` restoreReport = verifyRestoredState(saved, currentDigests);`,
|
|
213
|
+
to: ` restoreReport = { ok: true, checked: 0, mismatched: [], unreadable: [] }; // MUTANT: 不核对`,
|
|
214
|
+
},
|
|
215
|
+
{
|
|
216
|
+
id: "M20-死锁号不回收",
|
|
217
|
+
desc: "锁持有者 pid 已死(ESRCH)时不回收 → 崩溃后同一会话永久卡死",
|
|
218
|
+
file: "src/state.js",
|
|
219
|
+
from: ` if (err && err.code === "ESRCH") holderDead = true;`,
|
|
220
|
+
to: ` if (false) holderDead = true; // MUTANT: 不回收死锁号`,
|
|
221
|
+
},
|
|
198
222
|
{
|
|
199
223
|
id: "M8-未派发可记PASS",
|
|
200
224
|
desc: "移除 flow_verdict 的 dispatch_count 检查(未派发也能记 PASS)",
|
|
@@ -225,7 +249,7 @@ function sh(cmd, cwd, env = {}) {
|
|
|
225
249
|
const lines = [];
|
|
226
250
|
lines.push("# 变异测试报告");
|
|
227
251
|
lines.push("");
|
|
228
|
-
lines.push(
|
|
252
|
+
lines.push("- 源仓库:`carlos-flow`(单包,工作副本路径已改写为占位符)");
|
|
229
253
|
lines.push(`- 变异副本:临时目录(用完自动删除,不入库)`);
|
|
230
254
|
lines.push(`- 目的:确认测试套件能抓住「激活只打印日志」「闸门失效」「会话撞名」等退化`);
|
|
231
255
|
lines.push("");
|
|
@@ -301,12 +325,28 @@ const SRC_BRIDGES = new Set(bridgePidFiles(SRC));
|
|
|
301
325
|
// 导致套件启动失败/结果失真(表现为 concurrency 套件输出异常)。
|
|
302
326
|
const PORT_BASE = Number(process.env.MUTATION_PORT_BASE || 20100);
|
|
303
327
|
|
|
304
|
-
|
|
328
|
+
// 门禁加固三件套(敏感规则 / 状态锁 / 负对照还原)也纳入变异守护:
|
|
329
|
+
// 它们各自有独立回归套件,不跑就等于「新守卫没被证明有效」。
|
|
330
|
+
const SUITES =
|
|
331
|
+
"npm run test:e2e 2>&1; echo E2E_EXIT=$?; " +
|
|
332
|
+
"npm run test:trigger 2>&1; echo TR_EXIT=$?; " +
|
|
333
|
+
"npm run test:concurrency 2>&1; echo CONC_EXIT=$?; " +
|
|
334
|
+
"npm run test:scope 2>&1; echo SCOPE_EXIT=$?; " +
|
|
335
|
+
"npm run test:audit 2>&1; echo AUDIT_EXIT=$?; " +
|
|
336
|
+
"npm run test:sensitive 2>&1; echo SENS_EXIT=$?; " +
|
|
337
|
+
"npm run test:lock 2>&1; echo LOCK_EXIT=$?; " +
|
|
338
|
+
"npm run test:falsify 2>&1; echo FALSIFY_EXIT=$?";
|
|
339
|
+
|
|
340
|
+
const base = sh(SUITES, SRC, {
|
|
305
341
|
CARLOS_FLOW_HOME: join(tmpdir(), "carlos-flow-mutant-home", "base"),
|
|
306
342
|
});
|
|
307
343
|
const baseE2e = /════ 结果: (\d+) 通过 \/ (\d+) 失败/.exec(base);
|
|
308
344
|
const baseTr = /总测试数: (\d+)[\s\S]*?✅ 通过: (\d+)[\s\S]*?❌ 失败: (\d+)/.exec(base);
|
|
309
345
|
const baseConc = /✅ 通过: (\d+)[\s\S]*?❌ 失败: (\d+)/.exec(base.slice(base.lastIndexOf("跨进程并发")));
|
|
346
|
+
// 三条加固套件用各自的 OK 标记判定「真的跑通了」(不是崩在半路)
|
|
347
|
+
const baseSens = /SENSITIVE_CONFIG_OK/.test(base);
|
|
348
|
+
const baseLock = /STATE_LOCK_OK/.test(base);
|
|
349
|
+
const baseFalsify = /FALSIFY_RESTORE_OK/.test(base);
|
|
310
350
|
|
|
311
351
|
// 基线必须全绿:否则每个变异体「注入后仍然失败」会被误判成「被抓住」,
|
|
312
352
|
// 脚本就会在基线本身是红的情况下报「全部被抓住」并 exit 0(假绿)。
|
|
@@ -317,6 +357,9 @@ if (!baseTr) baseProblems.push("trigger 未取到结果");
|
|
|
317
357
|
else if (Number(baseTr[3]) > 0) baseProblems.push(`trigger ${baseTr[3]} 条失败`);
|
|
318
358
|
if (!baseConc) baseProblems.push("concurrency 未取到结果");
|
|
319
359
|
else if (Number(baseConc[2]) > 0) baseProblems.push(`concurrency ${baseConc[2]} 条失败`);
|
|
360
|
+
if (!baseSens) baseProblems.push("sensitive 未跑通");
|
|
361
|
+
if (!baseLock) baseProblems.push("lock 未跑通");
|
|
362
|
+
if (!baseFalsify) baseProblems.push("falsify 未跑通");
|
|
320
363
|
const baseGreen = baseProblems.length === 0;
|
|
321
364
|
|
|
322
365
|
lines.push(`## 基线(未变异)`);
|
|
@@ -396,7 +439,7 @@ for (const [mi, m] of MUTANTS.entries()) {
|
|
|
396
439
|
}
|
|
397
440
|
writeFileSync(target, mutated, "utf8");
|
|
398
441
|
|
|
399
|
-
const out = sh(
|
|
442
|
+
const out = sh(SUITES, workDir, {
|
|
400
443
|
CARLOS_FLOW_HOME: join(tmpdir(), "carlos-flow-mutant-home", m.id.replace(/[^A-Za-z0-9]/g, "_")),
|
|
401
444
|
// 每个变异体用**独立端口**:否则会复用上一轮副本拉起的旧 bridge,
|
|
402
445
|
// 旧 bridge 内存里跑的是旧代码 → 测试结果失真(可能假绿 / 假红)。
|
|
@@ -432,12 +475,36 @@ for (const [mi, m] of MUTANTS.entries()) {
|
|
|
432
475
|
process.exit(1);
|
|
433
476
|
}
|
|
434
477
|
|
|
478
|
+
// 三条加固套件:先确认它「真的跑了」(打印了结果块),再看是否通过
|
|
479
|
+
const sensRan = /SENSITIVE_CONFIG_OK/.test(out) || /SENS_EXIT=[1-9]/.test(out);
|
|
480
|
+
const lockRan = /STATE_LOCK_OK/.test(out) || /LOCK_EXIT=[1-9]/.test(out);
|
|
481
|
+
const falsifyRan = /FALSIFY_RESTORE_OK/.test(out) || /FALSIFY_EXIT=[1-9]/.test(out);
|
|
482
|
+
if (!sensRan || !lockRan || !falsifyRan) {
|
|
483
|
+
const missing = [];
|
|
484
|
+
if (!sensRan) missing.push("sensitive");
|
|
485
|
+
if (!lockRan) missing.push("lock");
|
|
486
|
+
if (!falsifyRan) missing.push("falsify");
|
|
487
|
+
lines.push(`## ${m.id}`);
|
|
488
|
+
lines.push("");
|
|
489
|
+
lines.push(`- 注入:${m.desc}`);
|
|
490
|
+
lines.push(`- 文件:\`${m.file}\``);
|
|
491
|
+
lines.push("- 结果:**加固套件未成功运行(结果不可信)**");
|
|
492
|
+
lines.push(`- 详情:未跑通的套件:${missing.join("、")}`);
|
|
493
|
+
lines.push("");
|
|
494
|
+
writeFileSync(REPORT, lines.join("\n") + "\n", "utf8");
|
|
495
|
+
console.error(`✗ 变异体 ${m.id}:加固套件未跑通(${missing.join("、")})—— 结果不可信。`);
|
|
496
|
+
console.error(" 报告已写入: " + REPORT);
|
|
497
|
+
process.exit(1);
|
|
498
|
+
}
|
|
435
499
|
const caught =
|
|
436
500
|
(e2eFail && Number(e2eFail[2]) > 0) ||
|
|
437
501
|
(trFail && Number(trFail[3]) > 0) ||
|
|
438
502
|
(concFail && Number(concFail[2]) > 0) ||
|
|
439
503
|
/SCOPE_EXIT=[1-9]/.test(out) ||
|
|
440
|
-
/AUDIT_EXIT=[1-9]/.test(out)
|
|
504
|
+
/AUDIT_EXIT=[1-9]/.test(out) ||
|
|
505
|
+
/SENS_EXIT=[1-9]/.test(out) ||
|
|
506
|
+
/LOCK_EXIT=[1-9]/.test(out) ||
|
|
507
|
+
/FALSIFY_EXIT=[1-9]/.test(out);
|
|
441
508
|
const verdict = caught ? "CAUGHT ✅" : "NOT CAUGHT ❌";
|
|
442
509
|
results.push({
|
|
443
510
|
...m,
|
package/src/dispatch.js
CHANGED
|
@@ -282,7 +282,7 @@ export function saveAgentResult(sid, role, stdout, stderr, code) {
|
|
|
282
282
|
// · POSIX:/bin/sh -c + shell:false(明确指定解释器,不依赖 PATH 里的 sh)。
|
|
283
283
|
export async function runVerifyCommand(cmd, cwd) {
|
|
284
284
|
if (!cmd || !cmd.trim()) {
|
|
285
|
-
return { ok: false, exitCode: -1, stdout: "", stderr: "验证命令为空" };
|
|
285
|
+
return { ok: false, exitCode: -1, stdout: "", stderr: formatError("验证命令为空") };
|
|
286
286
|
}
|
|
287
287
|
// 可选:拦截高危命令模式。
|
|
288
288
|
//
|
|
@@ -303,17 +303,18 @@ export async function runVerifyCommand(cmd, cwd) {
|
|
|
303
303
|
ok: false,
|
|
304
304
|
exitCode: -1,
|
|
305
305
|
stdout: "",
|
|
306
|
-
stderr: `验证命令包含高危模式,已拒绝执行:${cmd}
|
|
307
|
-
"(CARLOS_FLOW_BLOCK_DANGEROUS=1 已开启;确认该命令安全后可关闭此开关)",
|
|
306
|
+
stderr: formatError(`验证命令包含高危模式,已拒绝执行:${cmd}`),
|
|
308
307
|
};
|
|
309
308
|
}
|
|
310
309
|
}
|
|
311
310
|
const isWindows = process.platform === "win32";
|
|
312
311
|
const shell = isWindows ? process.env.COMSPEC || "cmd.exe" : "/bin/sh";
|
|
313
312
|
const shellArgs = isWindows ? ["/c", cmd] : ["-c", cmd];
|
|
313
|
+
// 安全修复:禁止 cwd = '.' 或空(这会在 Windows 上触发 %SystemDrive% 目录扩展,污染仓库)
|
|
314
|
+
const safeCwd = typeof cwd === "string" && cwd.length > 0 && cwd !== "." ? cwd : process.cwd();
|
|
314
315
|
return new Promise((resolve) => {
|
|
315
316
|
const child = spawn(shell, shellArgs, {
|
|
316
|
-
cwd:
|
|
317
|
+
cwd: safeCwd,
|
|
317
318
|
stdio: ["ignore", "pipe", "pipe"],
|
|
318
319
|
shell: isWindows,
|
|
319
320
|
windowsHide: true,
|
|
@@ -328,11 +329,16 @@ export async function runVerifyCommand(cmd, cwd) {
|
|
|
328
329
|
}, 120000);
|
|
329
330
|
child.on("close", (code) => {
|
|
330
331
|
clearTimeout(timeout);
|
|
331
|
-
|
|
332
|
+
if (code === 0) {
|
|
333
|
+
resolve({ ok: true, exitCode: code, stdout, stderr });
|
|
334
|
+
} else {
|
|
335
|
+
// 所有 child 错误输出都必须带上建议层
|
|
336
|
+
resolve({ ok: false, exitCode: code, stdout, stderr: formatError(String(stderr)) });
|
|
337
|
+
}
|
|
332
338
|
});
|
|
333
339
|
child.on("error", (err) => {
|
|
334
340
|
clearTimeout(timeout);
|
|
335
|
-
resolve({ ok: false, exitCode: -1, stdout, stderr: String(err) });
|
|
341
|
+
resolve({ ok: false, exitCode: -1, stdout, stderr: formatError(String(err)) });
|
|
336
342
|
});
|
|
337
343
|
});
|
|
338
344
|
}
|
|
@@ -460,6 +466,100 @@ function writeAfterState(sid, records) {
|
|
|
460
466
|
}
|
|
461
467
|
}
|
|
462
468
|
|
|
469
|
+
// ---------------------------------------------------------------------------
|
|
470
|
+
// 负对照的安全边界:崩溃恢复日志 + 还原结果可核验
|
|
471
|
+
// ---------------------------------------------------------------------------
|
|
472
|
+
//
|
|
473
|
+
// 背景(为什么需要这两个函数):负对照的本质是**在真实工作区里临时把文件改回旧内容**,
|
|
474
|
+
// 跑一次验证,再把文件写回来。旧实现只有 try/finally 的「意图保证」:
|
|
475
|
+
// · 进程被强杀 / 断电 → finally 不执行 → 工作区停在「改动前」状态,
|
|
476
|
+
// 用户的改动看起来凭空消失(最坏情况:把已修好的验证脚本回滚成坏的);
|
|
477
|
+
// · finally 里某次 copyFileSync 失败(文件被占用、权限不足)→ 只写一行 stderr,
|
|
478
|
+
// 调用方拿到的仍是 ok:true,没人知道工作区已经不干净了。
|
|
479
|
+
// 现在补两条机械保证:
|
|
480
|
+
// ① **进入前写日志**(negative_control/<ts>/journal.json):记录每个文件的原位、
|
|
481
|
+
// 进入时备份、是否需要删除。下次调用负对照时先把残留日志里的状态恢复回去,
|
|
482
|
+
// 所以「上一次被中断」不会把脏状态带到下一次;
|
|
483
|
+
// ② **还原后核对摘要**:逐文件比对内容哈希与「进入时」是否一致,结果写回返回值
|
|
484
|
+
// (restore.ok / restore.mismatched),失败时明确告警而不是静默放过。
|
|
485
|
+
|
|
486
|
+
function negativeControlRoot(sid) {
|
|
487
|
+
return path.join(RUNS_DIR, sanitizeId(sid), "negative_control");
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
// 扫描并恢复被中断的负对照。返回 { dirs, files, unresolved }。
|
|
491
|
+
// 只处理「日志还标着 pending」的目录:正常结束的目录在 finishJournal 里已被删除。
|
|
492
|
+
export function recoverInterruptedNegativeControl(sid) {
|
|
493
|
+
const root = negativeControlRoot(sid);
|
|
494
|
+
const out = { dirs: 0, files: 0, unresolved: [] };
|
|
495
|
+
let names = [];
|
|
496
|
+
try { names = fs.readdirSync(root); } catch { return out; }
|
|
497
|
+
for (const name of names) {
|
|
498
|
+
const dir = path.join(root, name);
|
|
499
|
+
const journalFile = path.join(dir, "journal.json");
|
|
500
|
+
let journal = null;
|
|
501
|
+
try {
|
|
502
|
+
journal = JSON.parse(fs.readFileSync(journalFile, "utf8"));
|
|
503
|
+
} catch { continue; } // 没有日志(或坏了):不是本机制写的目录,不碰
|
|
504
|
+
if (!journal || journal.status === "restored") {
|
|
505
|
+
try { fs.rmSync(dir, { recursive: true, force: true }); } catch {}
|
|
506
|
+
continue;
|
|
507
|
+
}
|
|
508
|
+
out.dirs++;
|
|
509
|
+
for (const e of Array.isArray(journal.saved) ? journal.saved : []) {
|
|
510
|
+
if (!e || typeof e.orig !== "string") continue;
|
|
511
|
+
try {
|
|
512
|
+
if (e.existed === true && e.savedPath) {
|
|
513
|
+
fs.mkdirSync(path.dirname(e.orig), { recursive: true });
|
|
514
|
+
fs.copyFileSync(e.savedPath, e.orig);
|
|
515
|
+
out.files++;
|
|
516
|
+
} else if (e.existed !== true) {
|
|
517
|
+
try { fs.unlinkSync(e.orig); } catch {}
|
|
518
|
+
out.files++;
|
|
519
|
+
} else {
|
|
520
|
+
// 进入时有文件但备份丢了:无法还原,如实记账
|
|
521
|
+
out.unresolved.push(e.orig);
|
|
522
|
+
}
|
|
523
|
+
} catch (err) {
|
|
524
|
+
out.unresolved.push(e.orig);
|
|
525
|
+
try {
|
|
526
|
+
process.stderr.write(`[flow-falsify] 恢复中断的负对照失败 ${e.orig}: ${err && err.message ? err.message : err}\n`);
|
|
527
|
+
} catch {}
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
try {
|
|
531
|
+
fs.writeFileSync(journalFile, JSON.stringify({ ...journal, status: "restored", recoveredAt: new Date().toISOString() }, null, 2), "utf8");
|
|
532
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
533
|
+
} catch {}
|
|
534
|
+
}
|
|
535
|
+
return out;
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
// 还原后核对:逐文件比对内容摘要与「进入负对照时」是否一致。
|
|
539
|
+
// UNKNOWN(读不到)不算失配 —— 无法证明 ≠ 证明坏了,如实归到 unreadable。
|
|
540
|
+
function verifyRestoredState(saved, expectedDigests) {
|
|
541
|
+
let checked = 0;
|
|
542
|
+
const mismatched = [];
|
|
543
|
+
const unreadable = [];
|
|
544
|
+
for (const s of saved) {
|
|
545
|
+
if (!s || typeof s.orig !== "string") continue;
|
|
546
|
+
const want = Object.prototype.hasOwnProperty.call(expectedDigests, s.orig)
|
|
547
|
+
? expectedDigests[s.orig]
|
|
548
|
+
: null;
|
|
549
|
+
if (want === null) continue;
|
|
550
|
+
checked++;
|
|
551
|
+
let got;
|
|
552
|
+
try {
|
|
553
|
+
got = fs.existsSync(s.orig) ? digestOf(s.orig) : "ABSENT";
|
|
554
|
+
} catch {
|
|
555
|
+
got = "UNKNOWN";
|
|
556
|
+
}
|
|
557
|
+
if (got === "UNKNOWN" || want === "UNKNOWN") { unreadable.push(s.orig); continue; }
|
|
558
|
+
if (got !== want) mismatched.push(s.orig);
|
|
559
|
+
}
|
|
560
|
+
return { ok: mismatched.length === 0, checked, mismatched, unreadable };
|
|
561
|
+
}
|
|
562
|
+
|
|
463
563
|
// 负对照:证明 verify.cmd 真的在测「本次改动」。
|
|
464
564
|
//
|
|
465
565
|
// 层次:这是「证据门禁」的执行侧 —— 不是让 LLM 声称「我试图证伪但没成功」,
|
|
@@ -487,11 +587,13 @@ function writeAfterState(sid, records) {
|
|
|
487
587
|
export async function runNegativeControl(sid, cmd, cwd) {
|
|
488
588
|
const entries = readManifest(sid);
|
|
489
589
|
if (!entries.length) {
|
|
490
|
-
return { ok: false, error: "没有派发快照,无法做负对照(请先 flow_dispatch)" };
|
|
590
|
+
return { ok: false, error: formatError("没有派发快照,无法做负对照(请先 flow_dispatch)") };
|
|
491
591
|
}
|
|
492
|
-
|
|
592
|
+
// 先把上一次「被中断的负对照」恢复掉,否则脏状态会带进本次的 before/after 判定。
|
|
593
|
+
const recovered = recoverInterruptedNegativeControl(sid);
|
|
594
|
+
const tmpDir = path.join(negativeControlRoot(sid), String(Date.now()));
|
|
493
595
|
try { fs.mkdirSync(tmpDir, { recursive: true }); } catch (e) {
|
|
494
|
-
return { ok: false, error: "无法创建负对照临时目录:" + (e && e.message ? e.message : e) };
|
|
596
|
+
return { ok: false, error: formatError("无法创建负对照临时目录:" + (e && e.message ? e.message : e)) };
|
|
495
597
|
}
|
|
496
598
|
|
|
497
599
|
// ---- 状态 A:改动前态(派发时的快照,来自 manifest 备份) ----
|
|
@@ -587,6 +689,25 @@ export async function runNegativeControl(sid, cmd, cwd) {
|
|
|
587
689
|
}
|
|
588
690
|
};
|
|
589
691
|
|
|
692
|
+
// ---- 进入「会改动工作区」的临界区之前,先把还原所需信息落盘 ----
|
|
693
|
+
// 这一步是崩溃恢复的唯一依据:进程被强杀时,下次调用靠它把工作区还原回去。
|
|
694
|
+
const journalFile = path.join(tmpDir, "journal.json");
|
|
695
|
+
const writeJournal = (status, extra) => {
|
|
696
|
+
try {
|
|
697
|
+
fs.writeFileSync(journalFile, JSON.stringify({
|
|
698
|
+
sid,
|
|
699
|
+
ts: new Date().toISOString(),
|
|
700
|
+
cwd: cwd || null,
|
|
701
|
+
status,
|
|
702
|
+
saved: saved.map((x) => ({ orig: x.orig, savedPath: x.savedPath, existed: x.existed })),
|
|
703
|
+
...(extra || {}),
|
|
704
|
+
}, null, 2), "utf8");
|
|
705
|
+
} catch (e) {
|
|
706
|
+
try { process.stderr.write(`[flow-falsify] 写还原日志失败: ${e && e.message ? e.message : e}\n`); } catch {}
|
|
707
|
+
}
|
|
708
|
+
};
|
|
709
|
+
writeJournal("pending");
|
|
710
|
+
|
|
590
711
|
// ---- 把选定的「改动后态」显式落盘记录(让下次负对照能按记录还原,而不是靠隐含前提) ----
|
|
591
712
|
try {
|
|
592
713
|
const afterDir = path.join(RUNS_DIR, sanitizeId(sid), "backup", "after_state_" + Date.now());
|
|
@@ -614,6 +735,7 @@ export async function runNegativeControl(sid, cmd, cwd) {
|
|
|
614
735
|
|
|
615
736
|
let before = null;
|
|
616
737
|
let after = null;
|
|
738
|
+
let restoreReport = { ok: true, checked: 0, mismatched: [], unreadable: [] };
|
|
617
739
|
try {
|
|
618
740
|
// 1. 还原「改动前」(派发快照)—— 必须失败
|
|
619
741
|
restoreFromManifest(entries);
|
|
@@ -623,8 +745,24 @@ export async function runNegativeControl(sid, cmd, cwd) {
|
|
|
623
745
|
else restoreCurrent();
|
|
624
746
|
after = await runVerifyCommand(cmd, cwd);
|
|
625
747
|
} finally {
|
|
626
|
-
//
|
|
748
|
+
// 无论如何都把工作区还原成进入负对照时的样子。
|
|
749
|
+
// 还原后必须**核对摘要**:只靠 try/finally 是意图保证,
|
|
750
|
+
// 一次失败的文件写回会让用户改动静默消失,而调用方还以为一切正常。
|
|
627
751
|
restoreCurrent();
|
|
752
|
+
restoreReport = verifyRestoredState(saved, currentDigests);
|
|
753
|
+
writeJournal(restoreReport.ok ? "restored" : "restore_failed", {
|
|
754
|
+
restore: restoreReport,
|
|
755
|
+
finishedAt: new Date().toISOString(),
|
|
756
|
+
});
|
|
757
|
+
if (!restoreReport.ok) {
|
|
758
|
+
try {
|
|
759
|
+
process.stderr.write(
|
|
760
|
+
"[flow-falsify] ⚠️ 工作区还原不完整,以下文件与进入负对照前不一致:" +
|
|
761
|
+
restoreReport.mismatched.join(", ") +
|
|
762
|
+
"(备份保留在 " + tmpDir + ",下次调用 flow_falsify 会先尝试恢复)\n",
|
|
763
|
+
);
|
|
764
|
+
} catch { /* ignore */ }
|
|
765
|
+
}
|
|
628
766
|
}
|
|
629
767
|
|
|
630
768
|
const beforeHash = computeOutputHash(before.exitCode, before.stdout, before.stderr);
|
|
@@ -660,8 +798,12 @@ export async function runNegativeControl(sid, cmd, cwd) {
|
|
|
660
798
|
"不能证明该命令在测本次改动,按保守口径记为空测试" + stateNote;
|
|
661
799
|
}
|
|
662
800
|
|
|
663
|
-
//
|
|
664
|
-
|
|
801
|
+
// 清理临时目录:**只有还原被核对通过时才删**。
|
|
802
|
+
// 还原失败时保留备份与日志 —— 下一次 flow_falsify 会先用它把工作区救回来,
|
|
803
|
+
// 删掉就等于把用户改动的唯一副本扔了。
|
|
804
|
+
if (restoreReport.ok) {
|
|
805
|
+
try { fs.rmSync(tmpDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }); } catch {}
|
|
806
|
+
}
|
|
665
807
|
|
|
666
808
|
return {
|
|
667
809
|
ok: true,
|
|
@@ -669,11 +811,55 @@ export async function runNegativeControl(sid, cmd, cwd) {
|
|
|
669
811
|
reason,
|
|
670
812
|
before: { exitCode: before.exitCode, ok: before.ok, hash: beforeHash, stdout: before.stdout, stderr: before.stderr, state_hash: beforeStateHash },
|
|
671
813
|
after: { exitCode: after.exitCode, ok: after.ok, hash: afterHash, stdout: after.stdout, stderr: after.stderr, state_hash: afterStateHash },
|
|
814
|
+
// 还原结果可核验:ok=false 表示工作区没能完整回到进入负对照前的状态
|
|
815
|
+
restore: restoreReport,
|
|
816
|
+
// 本次调用开始时顺手恢复掉的「上一次被中断的负对照」残留
|
|
817
|
+
recovered: { dirs: recovered.dirs, files: recovered.files, unresolved: recovered.unresolved },
|
|
672
818
|
};
|
|
673
819
|
}
|
|
674
|
-
//
|
|
675
|
-
//
|
|
676
|
-
//
|
|
820
|
+
// 辅助建议映射表
|
|
821
|
+
// 每条都回答三个问题:为什么被拦 / 依据什么规则 / 下一步怎么走
|
|
822
|
+
// 键是错误信息里的特征子串(按声明顺序匹配,先命中先用)
|
|
823
|
+
const ERROR_SUGGESTIONS = {
|
|
824
|
+
"验证命令为空": " Carlos 需要一个可执行的验证命令(如 `npm test` / `pytest -q`)来判断改动是否真的做对了。它写在任务卡的 verify.cmd 里。",
|
|
825
|
+
"包含高危模式": " 该命令里有删除系统路径、管道执行脚本、写块设备这类不可逆操作。默认不拦(因为清理命令本身合法),但开启 CARLOS_FLOW_BLOCK_DANGEROUS=1 后会拦。",
|
|
826
|
+
"没有派发快照": " 负对照要拿「派发时的文件备份」当对照物,没派发就没有备份。先把任务派出去(flow_dispatch)再回来做负对照。",
|
|
827
|
+
"越界改动": " 你改到了任务卡 scope 白名单之外的文件。这是机械门禁里最硬的一条 —— 防止 executor 顺手改了不该改的地方。",
|
|
828
|
+
"卡片 scope 为空": " 空 scope 按 fail-closed 处理:既然没声明允许改什么,就视为什么都不许改。",
|
|
829
|
+
"验证未通过": " verify.cmd 跑出了非 0 退出码,说明改动还没让验证通过。PASS 不能落,DIRTECTION/LOCAL 可以。",
|
|
830
|
+
"验证结果已过期": " 验证通过后代码又被改动了(diff 指纹变了),所以那次验证已经不能证明当前代码。重新跑一次 flow_run_verify 即可。",
|
|
831
|
+
"验证命令与当前卡片不一致": " 现有的验证结果对应的是另一个 verify.cmd(可能是旧卡的)。对当前卡重新跑一次验证。",
|
|
832
|
+
"尚未执行验证": " 还没有跑过 verify.cmd,没有可核验的凭据。",
|
|
833
|
+
"尚未派发任何执行": " 门禁要求改动必须经过派发窗口(有快照、有基线),跳过派发直接落 PASS 是不允许的。",
|
|
834
|
+
"尚未做负对照": " 负对照用来证明 verify.cmd 真的有判别力(改动前失败、改动后通过),防止 `|| true` 这种空测试混过去。",
|
|
835
|
+
"负对照未通过": " 验证命令没有判别力(例如改动前后都退出 0),不能拿它当「改动正确」的证据。",
|
|
836
|
+
"缺少必填字段": " 当前风险档要求的字段没填齐。低风险档只要求 goal/quote/scope,cross_module 还要 acceptance 和 files。",
|
|
837
|
+
"类型错误": " 参数类型与工具 schema 声明不符。常见于把数组写成字符串、或数组元素嵌套了一层。",
|
|
838
|
+
"值非法": " 该参数只接受枚举里的值。",
|
|
839
|
+
"未 claim": " 派发前要先 claim 领一个名额(executor 或 auditor),这是为了让审计知道是谁在做。",
|
|
840
|
+
"quote 锚点": " quote 必须能在你的原话里定位到,防止 Agent 替你编需求。",
|
|
841
|
+
"路径在磁盘上不存在": " scope 里的路径找不到。常见原因是没传 cwd,导致相对路径按 server 进程目录(而不是仓库根)解析。",
|
|
842
|
+
"敏感路径": " scope 里包含敏感路径,需要你显式确认(confirmed=true)才能提交。",
|
|
843
|
+
"获取状态锁超时": " 同一会话有另一个进程正在写状态,等它释放即可,不要绕过锁直接写。",
|
|
844
|
+
"没有留痕": " 门禁要求先有任务卡(留痕),否则 executor/auditor 不知道边界在哪、也无法事后追溯。",
|
|
845
|
+
"留痕已过期": " 卡片有 TTL(默认 4 小时),过期后再派发就不算同一张卡了,需重新提交。",
|
|
846
|
+
"派发次数已达上限": " 同一张卡可派发次数有上限,防止无限重试把同一张卡磨到绿灯。",
|
|
847
|
+
"占位卡尚未补齐": " 智能触发只开了一张占位卡,scope / acceptance / verify.cmd 还没填,填完才能派发。",
|
|
848
|
+
"卡片未指定 verify": " 没有 verify.cmd 就没有可核验的证据,PASS 无法成立。",
|
|
849
|
+
"两轴": " PASS 要求两轴(规范轴 + 验收轴)各自取证,单轴意见不足以放行。",
|
|
850
|
+
"至少一轴": " 至少一轴判了 FAIL,说明问题确实存在,修完重跑再提。",
|
|
851
|
+
"auditor": " PASS 只能由已领取 auditor 角色的会话落下,防止执行方自批。",
|
|
852
|
+
};
|
|
853
|
+
|
|
854
|
+
|
|
855
|
+
export function formatError(err) {
|
|
856
|
+
const msg = typeof err === 'string' ? err : String((err && err.message) || err);
|
|
857
|
+
let suggestion = "";
|
|
858
|
+
for (const [key, val] of Object.entries(ERROR_SUGGESTIONS)) {
|
|
859
|
+
if (msg.includes(key)) { suggestion = `\n💡 **为什么被拦**:${val}`; break; }
|
|
860
|
+
}
|
|
861
|
+
return `${msg}${suggestion}`;
|
|
862
|
+
}
|
|
677
863
|
// - scope: 卡片中的 scope 白名单
|
|
678
864
|
// - cwd: 仓库根目录(用于跑 git diff)
|
|
679
865
|
// - diffFiles?: 可选,外部传入的改动文件列表;不传则自动跑 `git diff --name-only`
|
|
@@ -719,7 +905,7 @@ export function enforceScope(scope, cwd, diffFiles) {
|
|
|
719
905
|
ok: false,
|
|
720
906
|
violations: diffFiles.slice(),
|
|
721
907
|
checked: diffFiles.slice(),
|
|
722
|
-
message: `越界改动(卡片 scope 为空,不允许修改任何文件):${diffFiles.join(", ")}
|
|
908
|
+
message: formatError(`越界改动(卡片 scope 为空,不允许修改任何文件):${diffFiles.join(", ")}`),
|
|
723
909
|
};
|
|
724
910
|
}
|
|
725
911
|
|
|
@@ -743,7 +929,8 @@ export function enforceScope(scope, cwd, diffFiles) {
|
|
|
743
929
|
}
|
|
744
930
|
|
|
745
931
|
if (violations.length > 0) {
|
|
746
|
-
|
|
932
|
+
const msg = `越界改动(超出 scope):${violations.join(", ")}`;
|
|
933
|
+
return { ok: false, violations, checked: diffFiles.slice(), message: formatError(msg) };
|
|
747
934
|
}
|
|
748
935
|
return { ok: true, violations: [], checked: diffFiles.slice() };
|
|
749
936
|
}
|