physical_byte_agent/tests/checkpoint-state.test.ts
d-robotics 6d6a805d46
Some checks are pending
CI / quality-gate (push) Waiting to run
CI / type-drift (push) Waiting to run
feat(v3): P1+P2 全落地 — T06–T17 + 系统集成测试
12 模块多 agent 并行开发(dev+test+fix 每,两层 + barrier):
- T06 PbaSession 事件溯源 + deriveMessages + logged 不变量
- T07 PbaEventBus typed event bus + waterfall + ScopeKey 隔离
- T08 能力接缝三角色(board-link + flash Provider/Registry/consumer)
- T09 compaction 完整工程(token-meter/pruner/summarizer/spill)
- T10 CI 质量门 + snapshot + doc-sync
- T11 类型镜像漂移检测(tsconfig.realpi + type-drift-check)
- T12 子代理 + 工作流编排(parallel/pipeline/InlineSubagentProvider)
- T13 上下文注入三段(inject/steer/followup)
- T14 plan/goal/todo checkpoint logged state(look-ahead 状态机)
- T15 profile/bundle 分层(维修诊断 vs 嵌入式开发,共享 base)
- T16 多 LLM provider 适配(ProviderRegistry + glm-5.2/deepseek)
- T17 审批接缝(fail-closed auto-deny)+ credentials/settings/lsp

集成(串行):
- src/index.ts 公共 re-export(board-link/flash 具名避 shared/types 重名)
- tests/system-integration.test.ts 跨模块 10 闭环(事件溯源→compaction→bus→
  接缝→checkpoint→inject→workflow→approval→provider→profile)
- 全量 tsc=0;vitest 39 文件 2449 passed/5 skipped(1044 baseline +~1400 模块 + 10 系统)
- 密钥铁律:\${DROBOTICS_LLM_KEY} 占位,grep sk- 明文 0

68 workflow agent / 0 error / ~3M token;mutation 测试每模块 3-9 seeded bug 全杀。

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-14 15:35:49 +08:00

1158 lines
53 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* checkpoint-state 完整测试套件 —— T14 plan/goal/todo logged state.
*
* 被测对象:src/core/checkpoint-state.ts 的命名导出
* - CheckpointRecorder (class:record / current / rebuild / fork)
* - CHECKPOINT_CHANGE_TYPE (事件类型常量 "checkpoint-change")
* - STEP_ORDER (步骤顺序常量,深冻结)
* - INITIAL_CHECKPOINT_STATE (初始态常量,深冻结)
* - CheckpointAppendEntry (append 入参类型)
*
* 纯逻辑模块,零 pi 运行时依赖:mock 注入 append sink,离线可单测。
*
* 多方法论(每个 describe 块标注方法论名):
* ① 等价类划分(有效/无效/边界类)
* ② 边界值分析(off-by-one、空、单元素、max、min)
* ③ 决策表(组合输入→期望,覆盖全分支)
* ④ 状态转换(状态+迁移+不可达状态+重入)
* ⑤ 变异测试(4 个 seeded bug,每个被 kill-assertion 杀死 + 独立 mutant 文件确认 FAIL)
* ⑥ 对抗/fuzz(畸形/滥用输入:null、undefined、巨大、NaN、循环引用、负 seq)
* ⑦ 元蜕变/不变式(append 两次≡replay;freeze→篡改抛 TypeError;单调;waterfall 短路;fail-closed)
*
* 门:
* `npx vitest run tests/checkpoint-state.test.ts` —— 真实代码必须 all green。
* 每个 seeded bug 另用独立 mutant 脚本(tests/.mutation-kill/m{1..4}.mjs,node:assert)
* 单独跑确认 FAIL(exit=1 = bug 被杀)。M1/M2/M3/M4 均已验证 exit=1。
*
* 关键设计:realAdvance 是 advanceState 的【忠实】纯函数副本(含 failed 分支
* `idx <= curIdx` 守卫与 done 分支 `idx <= curIdx` 守卫),使变异对比在触碰
* failed/done 守卫的场景下也成立。副本保真自验见 ⑤ "副本保真" 测试。
*/
import { describe, it, expect } from "vitest";
import {
CheckpointRecorder,
CHECKPOINT_CHANGE_TYPE,
STEP_ORDER,
INITIAL_CHECKPOINT_STATE,
} from "../src/core/checkpoint-state.js";
import type { CheckpointState, CheckpointStep } from "../src/shared/types.js";
// ============================================================================
// 公共夹具
// ============================================================================
type Entry = { type: string; data: unknown };
/** 记录型 append sink:捕获下沉参数,可断言。 */
function recordingSink(): { sink: (entry: Entry) => void; calls: Entry[] } {
const calls: Entry[] = [];
return { sink: (entry) => calls.push(entry), calls };
}
/** no-op sink。 */
function noopSink(): (entry: Entry) => void {
return () => {};
}
/** 构造一个可变的初始 CheckpointState(独立拷贝,可自由 push/改)。 */
function freshState(): CheckpointState {
return { currentStep: "edit", stepPassed: false, history: [] };
}
/** 完整 happy-path 序列:edit→compile→flash→verify→check→done 全通过。 */
const FULL_PASS_SEQ: Array<{ step: CheckpointStep; passed: true; ts: number }> = [
{ step: "edit", passed: true, ts: 1000 },
{ step: "compile", passed: true, ts: 2000 },
{ step: "flash", passed: true, ts: 3000 },
{ step: "verify", passed: true, ts: 4000 },
{ step: "check", passed: true, ts: 5000 },
{ step: "done", passed: true, ts: 6000 },
];
// ============================================================================
// advanceState 忠实副本 + 变异副本(变异测试用)
// ============================================================================
/**
* 真实 advance 纯函数【忠实】副本(与 src/core/checkpoint-state.ts advanceState
* 逐行同形,含 done 分支 `idx <= curIdx` 守卫 + failed 分支 `idx <= curIdx` 守卫)。
* 用于与带虫副本在同一场景下对比发散。保真自验见 ⑤ "副本保真" 测试。
*/
function realAdvance(state: CheckpointState, step: CheckpointStep, passed: boolean, timestamp: number): void {
state.history.push({ step, passed, timestamp });
const idx = STEP_ORDER.indexOf(step);
if (idx < 0) return;
const curIdx = STEP_ORDER.indexOf(state.currentStep);
if (passed) {
if (idx === STEP_ORDER.length - 1) {
if (idx <= curIdx) {
state.currentStep = step;
state.stepPassed = true;
}
} else {
const targetIdx = idx + 1;
if (targetIdx > curIdx) {
state.currentStep = STEP_ORDER[targetIdx] as CheckpointStep;
state.stepPassed = false;
}
}
} else {
if (idx <= curIdx) {
state.currentStep = step;
state.stepPassed = false;
}
}
}
/** 对 state 序列应用一个 advance 函数,返回最终状态(独立 freshState)。 */
function applySeq(
advanceFn: (s: CheckpointState, step: CheckpointStep, passed: boolean, ts: number) => void,
ops: Array<{ step: CheckpointStep; passed: boolean; ts: number }>,
): CheckpointState {
const s = freshState();
for (const o of ops) advanceFn(s, o.step, o.passed, o.ts);
return s;
}
// ---- 变异 M1:`targetIdx > curIdx` → `targetIdx >= curIdx`(passed 非末分支 off-by-one)----
// 杀它的场景:全通过到 done(stepPassed=true) → 再 pass check(targetIdx=5===curIdx=5)。
// 真实:5>5 false → 不动,stepPassed 保持 true。带虫:5>=5 true → stepPassed 重置 false。
function m1Advance(state: CheckpointState, step: CheckpointStep, passed: boolean, timestamp: number): void {
state.history.push({ step, passed, timestamp });
const idx = STEP_ORDER.indexOf(step);
if (idx < 0) return;
const curIdx = STEP_ORDER.indexOf(state.currentStep);
if (passed) {
if (idx === STEP_ORDER.length - 1) {
if (idx <= curIdx) {
state.currentStep = step;
state.stepPassed = true;
}
} else {
const targetIdx = idx + 1;
// 🐛 变异:> → >=
if (targetIdx >= curIdx) {
state.currentStep = STEP_ORDER[targetIdx] as CheckpointStep;
state.stepPassed = false;
}
}
} else {
if (idx <= curIdx) {
state.currentStep = step;
state.stepPassed = false;
}
}
}
// ---- 变异 M2:`idx === STEP_ORDER.length - 1` → `idx === STEP_ORDER.length`(末步检测 off-by-one)----
// 杀它的场景:全通过到 done。真实:pass done 停 done+stepPassed=true。
// 带虫:5===6 false → else,targetIdx=6 越界 → currentStep=undefined。
function m2Advance(state: CheckpointState, step: CheckpointStep, passed: boolean, timestamp: number): void {
state.history.push({ step, passed, timestamp });
const idx = STEP_ORDER.indexOf(step);
if (idx < 0) return;
const curIdx = STEP_ORDER.indexOf(state.currentStep);
if (passed) {
// 🐛 变异:length - 1 → length
if (idx === STEP_ORDER.length) {
state.currentStep = step;
state.stepPassed = true;
} else {
const targetIdx = idx + 1;
if (targetIdx > curIdx) {
state.currentStep = STEP_ORDER[targetIdx] as CheckpointStep;
state.stepPassed = false;
}
}
} else {
if (idx <= curIdx) {
state.currentStep = step;
state.stepPassed = false;
}
}
}
// ---- 变异 M3:passed 非末前进 `stepPassed = false` → `stepPassed = true`(错默认值)----
// 杀它的场景:pass edit → 前进到 compile。真实 stepPassed=false,带虫=true。
function m3Advance(state: CheckpointState, step: CheckpointStep, passed: boolean, timestamp: number): void {
state.history.push({ step, passed, timestamp });
const idx = STEP_ORDER.indexOf(step);
if (idx < 0) return;
const curIdx = STEP_ORDER.indexOf(state.currentStep);
if (passed) {
if (idx === STEP_ORDER.length - 1) {
if (idx <= curIdx) {
state.currentStep = step;
state.stepPassed = true;
}
} else {
const targetIdx = idx + 1;
if (targetIdx > curIdx) {
state.currentStep = STEP_ORDER[targetIdx] as CheckpointStep;
// 🐛 变异:false → true
state.stepPassed = true;
}
}
} else {
if (idx <= curIdx) {
state.currentStep = step;
state.stepPassed = false;
}
}
}
// ---- 变异 M4:failed 分支 `idx <= curIdx` → `idx < curIdx`(漏 = 校验,守卫放宽)----
// 杀它的场景:全通过到 done(stepPassed=true) → 再 fail done(idx=5===curIdx=5)。
// 真实:5<=5 true → stepPassed 重置 false(退回 done 重试)。
// 带虫:5<5 false → 不动,stepPassed 保持 true(fail 不清除完成态=伪造完成)。
function m4Advance(state: CheckpointState, step: CheckpointStep, passed: boolean, timestamp: number): void {
state.history.push({ step, passed, timestamp });
const idx = STEP_ORDER.indexOf(step);
if (idx < 0) return;
const curIdx = STEP_ORDER.indexOf(state.currentStep);
if (passed) {
if (idx === STEP_ORDER.length - 1) {
if (idx <= curIdx) {
state.currentStep = step;
state.stepPassed = true;
}
} else {
const targetIdx = idx + 1;
if (targetIdx > curIdx) {
state.currentStep = STEP_ORDER[targetIdx] as CheckpointStep;
state.stepPassed = false;
}
}
} else {
// 🐛 变异:<= → <
if (idx < curIdx) {
state.currentStep = step;
state.stepPassed = false;
}
}
}
const ALL_MUTANTS: Array<{ name: string; fn: typeof realAdvance }> = [
{ name: "M1", fn: m1Advance },
{ name: "M2", fn: m2Advance },
{ name: "M3", fn: m3Advance },
{ name: "M4", fn: m4Advance },
];
// ============================================================================
// ⑦ 元蜕变/不变式 —— 常量导出(后续 describe 依赖这些不变式)
// ============================================================================
describe("⑦ 元蜕变/不变式 — 常量导出", () => {
it("CHECKPOINT_CHANGE_TYPE === 'checkpoint-change'(与 PbaSessionEventMap 对齐)", () => {
expect(CHECKPOINT_CHANGE_TYPE).toBe("checkpoint-change");
});
it("STEP_ORDER 内容与顺序正确:edit→compile→flash→verify→check→done", () => {
expect(STEP_ORDER).toEqual(["edit", "compile", "flash", "verify", "check", "done"]);
});
it("STEP_ORDER 长度=6", () => {
expect(STEP_ORDER.length).toBe(6);
});
it("STEP_ORDER 是深冻结(push 抛 TypeError)", () => {
expect(() => (STEP_ORDER as CheckpointStep[]).push("edit" as CheckpointStep)).toThrow(TypeError);
});
it("STEP_ORDER 元素不可重写(冻结)", () => {
expect(() => ((STEP_ORDER as unknown as { 0: unknown })[0] = "done")).toThrow(TypeError);
});
it("INITIAL_CHECKPOINT_STATE 初始态正确:edit / stepPassed=false / history=[]", () => {
expect(INITIAL_CHECKPOINT_STATE.currentStep).toBe("edit");
expect(INITIAL_CHECKPOINT_STATE.stepPassed).toBe(false);
expect(INITIAL_CHECKPOINT_STATE.history).toEqual([]);
});
it("INITIAL_CHECKPOINT_STATE 顶层冻结(改字段抛 TypeError)", () => {
expect(() => {
(INITIAL_CHECKPOINT_STATE as unknown as { currentStep: unknown }).currentStep = "done";
}).toThrow(TypeError);
});
it("INITIAL_CHECKPOINT_STATE.history 冻结(push 抛 TypeError)", () => {
expect(() => {
(INITIAL_CHECKPOINT_STATE.history as unknown[]).push({ step: "edit", passed: true, timestamp: 1 });
}).toThrow(TypeError);
});
it("INITIAL_CHECKPOINT_STATE 是 CheckpointRecorder 的默认起点", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
expect(rec.current()).toEqual({
currentStep: "edit",
stepPassed: false,
history: [],
});
});
});
// ============================================================================
// ① 等价类划分 —— record 推进语义(有效/无效/边界类)
// ============================================================================
describe("① 等价类划分 — record(step, passed, ts)", () => {
it("有效类·正常前进:pass edit → currentStep=compile, stepPassed=false", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
rec.record("edit", true, 1000);
expect(rec.current().currentStep).toBe("compile");
expect(rec.current().stepPassed).toBe(false);
});
it("有效类·失败当前步:fail compile → currentStep=compile, stepPassed=false(退回重试)", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
rec.record("edit", true, 1000);
rec.record("compile", false, 2000);
expect(rec.current().currentStep).toBe("compile");
expect(rec.current().stepPassed).toBe(false);
});
it("有效类·末步 done 通过:currentStep=done, stepPassed=true(停在 done)", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
for (const op of FULL_PASS_SEQ) rec.record(op.step, op.passed, op.ts);
expect(rec.current().currentStep).toBe("done");
expect(rec.current().stepPassed).toBe(true);
});
it("有效类·check 通过推进到 done 但 stepPassed=false(done 尚未通过)", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
for (const op of FULL_PASS_SEQ.slice(0, 5)) rec.record(op.step, op.passed, op.ts);
expect(rec.current().currentStep).toBe("done");
expect(rec.current().stepPassed).toBe(false);
});
it("无效类·未知 step('bogus'):仅记 history,currentStep 不动", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
rec.record("bogus" as CheckpointStep, true, 1000);
expect(rec.current().currentStep).toBe("edit");
expect(rec.current().stepPassed).toBe(false);
expect(rec.current().history.length).toBe(1);
expect(rec.current().history[0]!.step).toBe("bogus");
});
it("无效类·未知 step 失败:仅记 history,currentStep 不动", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
rec.record("zzz" as CheckpointStep, false, 1000);
expect(rec.current().currentStep).toBe("edit");
expect(rec.current().stepPassed).toBe(false);
expect(rec.current().history.length).toBe(1);
});
it("有效类·重入补跑已通过步骤(pass edit 再 pass edit):不回退、不重复前进", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
rec.record("edit", true, 1000); // → compile
rec.record("edit", true, 2000); // targetIdx=1(curIdx) 不>,不推进
expect(rec.current().currentStep).toBe("compile");
expect(rec.current().stepPassed).toBe(false);
expect(rec.current().history.length).toBe(2);
});
it("有效类·失败已过步骤(退回):flash 失败后 currentStep=flash", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
rec.record("edit", true, 1000);
rec.record("compile", true, 2000); // → flash
rec.record("flash", false, 3000); // 退回 flash
expect(rec.current().currentStep).toBe("flash");
expect(rec.current().stepPassed).toBe(false);
});
});
// ============================================================================
// ② 边界值分析 —— off-by-one / 空 / 单元素 / max / min
// ============================================================================
describe("② 边界值分析 — history 与推进边界", () => {
it("空边界:新 recorder current() 是初始态、history 空", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
const s = rec.current();
expect(s.history).toEqual([]);
expect(s.currentStep).toBe("edit");
expect(s.stepPassed).toBe(false);
});
it("单元素边界:一次 record 后 history 恰 1 条", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
rec.record("edit", true, 1000);
expect(rec.current().history.length).toBe(1);
expect(rec.current().history[0]).toEqual({ step: "edit", passed: true, timestamp: 1000 });
});
it("off-by-one·targetIdx === curIdx 不前进(pass edit 后再 pass edit 不动)", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
rec.record("edit", true, 1000); // curIdx 现 1 (compile)
const before = rec.current();
rec.record("edit", true, 2000); // targetIdx=1, curIdx=1 → 1>1 false → 不动
expect(rec.current().currentStep).toBe(before.currentStep);
expect(rec.current().stepPassed).toBe(before.stepPassed);
});
it("off-by-one·targetIdx === curIdx+1 恰好前进(边界刚好越过)", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
rec.record("edit", true, 1000); // → compile (curIdx=1)
rec.record("compile", true, 2000); // targetIdx=2 > 1 → → flash
expect(rec.current().currentStep).toBe("flash");
});
it("max 边界:到达 done(末步 idx=STEP_ORDER.length-1)停在 done", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
for (const op of FULL_PASS_SEQ) rec.record(op.step, op.passed, op.ts);
expect(rec.current().currentStep).toBe("done");
expect(STEP_ORDER.indexOf(rec.current().currentStep)).toBe(STEP_ORDER.length - 1);
});
it("min 边界:第一步 edit pass 后 currentStep=STEP_ORDER[1]", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
rec.record("edit", true, 0);
expect(rec.current().currentStep).toBe(STEP_ORDER[1]);
});
it("末步 done 失败:currentStep=done, stepPassed=false(停在末步重试)", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
for (const op of FULL_PASS_SEQ) rec.record(op.step, op.passed, op.ts);
rec.record("done", false, 7000); // 已到 done stepPassed=true → fail done 退回重试
expect(rec.current().currentStep).toBe("done");
expect(rec.current().stepPassed).toBe(false);
});
it("history 边界:fail 与 pass 都各 push 一条(不区分有效性)", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
rec.record("edit", true, 1);
rec.record("edit", false, 2);
rec.record("edit", true, 3);
expect(rec.current().history.length).toBe(3);
expect(rec.current().history.map((h) => h.passed)).toEqual([true, false, true]);
});
});
// ============================================================================
// ③ 决策表 —— (passed, isTerminal, targetIdx vs curIdx / idx vs curIdx) → 全分支
// ============================================================================
describe("③ 决策表 — advance 全分支组合", () => {
type Row = {
name: string;
ops: Array<{ step: CheckpointStep; passed: boolean }>;
expectStep: CheckpointStep;
expectPassedFlag: boolean;
};
// 前置:record("edit", true) → compile(curIdx=1, stepPassed=false)
const cases: Row[] = [
// passed=true, isTerminal=false, targetIdx > curIdx → 前进
{ name: "pass+非末+target>cur → 前进", ops: [{ step: "edit", passed: true }, { step: "compile", passed: true }], expectStep: "flash", expectPassedFlag: false },
// passed=true, isTerminal=false, targetIdx === curIdx → 不动
{ name: "pass+非末+target===cur → 不动", ops: [{ step: "edit", passed: true }, { step: "edit", passed: true }], expectStep: "compile", expectPassedFlag: false },
// passed=true, isTerminal=false, targetIdx < curIdx → 不动(不回退)
{ name: "pass+非末+target<cur → 不动", ops: [{ step: "edit", passed: true }, { step: "compile", passed: true }, { step: "edit", passed: true }], expectStep: "flash", expectPassedFlag: false },
// passed=true, isTerminal=true (done) → 停 done stepPassed=true
{ name: "pass+末步(done) → 停done stepPassed=true", ops: FULL_PASS_SEQ.map((o) => ({ step: o.step, passed: o.passed })), expectStep: "done", expectPassedFlag: true },
// passed=true, isTerminal=true (done) 但 idx > curIdx(从 check 试图直接 pass done)→ 不设 stepPassed=true
{ name: "pass+done(未抵达, idx>cur) → 不伪造完成", ops: [{ step: "edit", passed: true }, { step: "compile", passed: true }, { step: "flash", passed: true }, { step: "verify", passed: true }, { step: "done", passed: true }], expectStep: "check", expectPassedFlag: false },
// passed=false, idx === curIdx → 停该步(当前步失败)
{ name: "fail+idx===cur → 停该步 stepPassed=false", ops: [{ step: "edit", passed: true }, { step: "compile", passed: false }], expectStep: "compile", expectPassedFlag: false },
// passed=false, idx < curIdx → 退回该步
{ name: "fail+idx<cur → 退回该步 stepPassed=false", ops: [{ step: "edit", passed: true }, { step: "compile", passed: true }, { step: "flash", passed: false }], expectStep: "flash", expectPassedFlag: false },
// passed=false, idx > curIdx → 不前进(仅记 history)
{ name: "fail+idx>cur → 不前进 stepPassed 不动", ops: [{ step: "edit", passed: true }, { step: "compile", passed: true }, { step: "verify", passed: false }], expectStep: "flash", expectPassedFlag: false },
// passed=false, idx > curIdx (极端:fail done from flash) → 不前进
{ name: "fail+done(远超 cur) → 不前进", ops: [{ step: "edit", passed: true }, { step: "compile", passed: true }, { step: "done", passed: false }], expectStep: "flash", expectPassedFlag: false },
// passed=false, idx === curIdx at done (fail done after fully done) → stepPassed 重置 false(退回重试)
{ name: "fail+done(已抵达) → stepPassed 重置 false", ops: [...FULL_PASS_SEQ.map((o) => ({ step: o.step, passed: o.passed })), { step: "done", passed: false }], expectStep: "done", expectPassedFlag: false },
];
for (const c of cases) {
it(c.name, () => {
const rec = new CheckpointRecorder({ append: noopSink() });
c.ops.forEach((o, i) => rec.record(o.step, o.passed, (i + 1) * 1000));
expect(rec.current().currentStep).toBe(c.expectStep);
expect(rec.current().stepPassed).toBe(c.expectPassedFlag);
});
}
});
// ============================================================================
// ④ 状态转换 —— 全链路 + 重入 + 退回 + 终态 + 不可达
// ============================================================================
describe("④ 状态转换 — 闭环状态机迁移", () => {
it("完整迁移 edit→compile→flash→verify→check→done(每步 currentStep 逐步前进)", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
// pass edit→compile, pass compile→flash, pass flash→verify, pass verify→check,
// pass check→done(stepPassed=false), pass done→done(stepPassed=true)
const expectAfter: CheckpointStep[] = ["compile", "flash", "verify", "check", "done", "done"];
const expectPassed: boolean[] = [false, false, false, false, false, true];
FULL_PASS_SEQ.forEach((op, i) => {
rec.record(op.step, op.passed, op.ts);
expect(rec.current().currentStep).toBe(expectAfter[i]);
expect(rec.current().stepPassed).toBe(expectPassed[i]);
});
expect(rec.current().currentStep).toBe("done");
expect(rec.current().stepPassed).toBe(true);
});
it("失败重试可达迁移:compile 失败→退回 compile→重试通过→继续前进", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
rec.record("edit", true, 1000);
rec.record("compile", false, 2000); // 退回 compile
expect(rec.current().currentStep).toBe("compile");
rec.record("compile", true, 3000); // 重试通过 → flash
expect(rec.current().currentStep).toBe("flash");
expect(rec.current().history.length).toBe(3);
});
it("终态 done 不可回退:pass done 后再 pass 任意非末步不回退、stepPassed 保持 true", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
for (const op of FULL_PASS_SEQ) rec.record(op.step, op.passed, op.ts);
expect(rec.current().stepPassed).toBe(true);
// 重入 pass check(targetIdx=5===curIdx=5 不>)→ 不动,stepPassed 保持 true
rec.record("check", true, 7000);
expect(rec.current().currentStep).toBe("done");
expect(rec.current().stepPassed).toBe(true);
});
it("重入补跑不丢 history(补跑 edit 在 compile 期间 history 累加)", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
rec.record("edit", true, 1000);
rec.record("edit", true, 2000); // 补跑
expect(rec.current().history.length).toBe(2);
expect(rec.current().currentStep).toBe("compile");
});
it("状态转换可重复到达终态:到 done 后多次补跑 done 仍保持 done+stepPassed=true", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
for (const op of FULL_PASS_SEQ) rec.record(op.step, op.passed, op.ts);
rec.record("done", true, 7000);
rec.record("done", true, 8000);
expect(rec.current().currentStep).toBe("done");
expect(rec.current().stepPassed).toBe(true);
expect(rec.current().history.length).toBe(8);
});
it("不可达状态:不经 pass done 绝不会 stepPassed=true(仅 pass done 设 true)", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
// 到 check 通过 → currentStep=done 但 stepPassed=false(done 未通过)
for (const op of FULL_PASS_SEQ.slice(0, 5)) rec.record(op.step, op.passed, op.ts);
expect(rec.current().currentStep).toBe("done");
expect(rec.current().stepPassed).toBe(false);
// 补跑任意非 done 不设 stepPassed=true
rec.record("edit", true, 6000);
rec.record("check", true, 7000);
expect(rec.current().stepPassed).toBe(false);
});
it("不可达状态:从 check 直接 pass done 不伪造完成(idx>curIdx 守卫)", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
// 推到 check (currentStep=check, curIdx=4)
rec.record("edit", true, 1);
rec.record("compile", true, 2);
rec.record("flash", true, 3);
rec.record("verify", true, 4); // → check
expect(rec.current().currentStep).toBe("check");
// 直接 pass done:idx=5 > curIdx=4 → done 守卫 idx<=curIdx 为 false → 不设 stepPassed=true
rec.record("done", true, 5);
expect(rec.current().currentStep).toBe("check");
expect(rec.current().stepPassed).toBe(false);
});
});
// ============================================================================
// fork 专项
// ============================================================================
describe("fork — 子任务独立 + 共享 sink", () => {
it("fork 后子 == 父当前状态(深拷贝),各自 record 互不影响", () => {
const { sink } = recordingSink();
const parent = new CheckpointRecorder({ append: sink });
parent.record("edit", true, 1000);
parent.record("compile", true, 2000);
const child = parent.fork();
expect(child.current()).toEqual(parent.current());
child.record("verify", true, 3000);
expect(child.current().currentStep).toBe("check");
expect(parent.current().currentStep).toBe("flash");
parent.record("flash", true, 4000);
expect(parent.current().currentStep).toBe("verify");
expect(child.current().currentStep).toBe("check");
});
it("fork 共享父 append sink(子 record 写进同一 session)", () => {
const { sink, calls } = recordingSink();
const parent = new CheckpointRecorder({ append: sink });
parent.record("edit", true, 1000);
const child = parent.fork();
child.record("compile", true, 2000);
expect(calls.length).toBe(2);
expect(calls[1]!.type).toBe(CHECKPOINT_CHANGE_TYPE);
expect((calls[1]!.data as CheckpointState).currentStep).toBe("flash");
});
it("fork 从初始态 fork:子也是初始态", () => {
const { sink } = recordingSink();
const parent = new CheckpointRecorder({ append: sink });
const child = parent.fork();
expect(child.current()).toEqual({
currentStep: "edit",
stepPassed: false,
history: [],
});
});
it("fork 链:fork 的 fork 仍共享同一 sink 且独立", () => {
const { sink, calls } = recordingSink();
const parent = new CheckpointRecorder({ append: sink });
parent.record("edit", true, 1000);
const child = parent.fork();
const grandchild = child.fork();
grandchild.record("compile", true, 2000);
expect(calls.length).toBe(2);
expect((calls[1]!.data as CheckpointState).currentStep).toBe("flash");
expect(parent.current().currentStep).toBe("compile");
expect(child.current().currentStep).toBe("compile");
});
it("fork 后父子交替 record 互不串扰(同步模拟并发重入)", () => {
const { sink } = recordingSink();
const parent = new CheckpointRecorder({ append: sink });
parent.record("edit", true, 1000); // parent history=1, currentStep=compile
const child = parent.fork(); // child 拿到 history=1(edit) 拷贝
child.record("compile", true, 1100); // child: compile→flash, history=2
parent.record("compile", true, 1200); // parent: compile→flash, history=2
child.record("flash", true, 1300); // child: flash→verify, history=3
parent.record("flash", true, 1400); // parent: flash→verify, history=3
expect(child.current().currentStep).toBe("verify");
expect(parent.current().currentStep).toBe("verify");
expect(parent.current().history.length).toBe(3);
expect(child.current().history.length).toBe(3);
});
});
// ============================================================================
// rebuild 专项
// ============================================================================
describe("rebuild — 状态重建", () => {
it("空 entries → 回初始态", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
const state = rec.rebuild([]);
expect(state).toEqual({ currentStep: "edit", stepPassed: false, history: [] });
});
it("无 checkpoint-change 条目(其他 type)→ 回初始态", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
const state = rec.rebuild([
{ type: "user-message", data: { content: "hi" } },
{ type: "tool-call", data: { name: "bash", args: {} } },
]);
expect(state.currentStep).toBe("edit");
expect(state.history.length).toBe(0);
});
it("多条 checkpoint-change 取最后一条全量快照", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
const entries = [
{ type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "compile", stepPassed: false, history: [{ step: "edit", passed: true, timestamp: 1 }] } },
{ type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "done", stepPassed: true, history: [{ step: "done", passed: true, timestamp: 9 }] } },
];
const state = rec.rebuild(entries);
expect(state.currentStep).toBe("done");
expect(state.stepPassed).toBe(true);
expect(state.history.length).toBe(1);
});
it("rebuild 后 record 在重建基础上继续推进", () => {
const { sink, calls } = recordingSink();
const src = new CheckpointRecorder({ append: sink });
src.record("edit", true, 1000);
src.record("compile", true, 2000); // → flash
const resumed = new CheckpointRecorder({ append: noopSink() });
resumed.rebuild(calls);
expect(resumed.current().currentStep).toBe("flash");
resumed.record("flash", true, 3000); // → verify
expect(resumed.current().currentStep).toBe("verify");
});
it("rebuild 返回独立拷贝(篡改不影响内部)", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
const entries = [{ type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "verify", stepPassed: false, history: [] } }];
const state = rec.rebuild(entries);
state.currentStep = "edit";
state.history.push({ step: "x" as unknown as CheckpointStep, passed: true, timestamp: 1 });
expect(rec.current().currentStep).toBe("verify");
expect(rec.current().history.length).toBe(0);
});
it("坏 checkpoint-change data 后跟好 data:好 data 胜出(每条独立校验)", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
const state = rec.rebuild([
{ type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "flash" } }, // 坏
{ type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "check", stepPassed: false, history: [{ step: "verify", passed: true, timestamp: 5 }] } }, // 好
]);
expect(state.currentStep).toBe("check");
expect(state.history.length).toBe(1);
});
it("好 data 后跟坏 data:好 data 保持(坏 data 不覆盖)", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
const state = rec.rebuild([
{ type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "check", stepPassed: false, history: [] } }, // 好
{ type: CHECKPOINT_CHANGE_TYPE, data: null }, // 坏
{ type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "flash" } }, // 坏
]);
expect(state.currentStep).toBe("check");
});
it("rebuild 重建的 history 完整回填(多步快照)", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
const state = rec.rebuild([
{ type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "verify", stepPassed: false, history: [
{ step: "edit", passed: true, timestamp: 1 },
{ step: "compile", passed: true, timestamp: 2 },
{ step: "flash", passed: true, timestamp: 3 },
] } },
]);
expect(state.history.length).toBe(3);
expect(state.history[2]).toEqual({ step: "flash", passed: true, timestamp: 3 });
});
it("rebuild 不修改传入 entries(只读契约)", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
const entries: Entry[] = [
{ type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "flash", stepPassed: false, history: [] } },
];
const snapshot = JSON.stringify(entries);
rec.rebuild(entries);
expect(JSON.stringify(entries)).toBe(snapshot);
});
});
// ============================================================================
// ⑥ 对抗/fuzz —— 畸形/滥用输入
// ============================================================================
describe("⑥ 对抗/fuzz — 畸形 entries 与输入", () => {
it("rebuild 容忍数组内 null/undefined 条目(静默跳过)", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
const state = rec.rebuild([
null as unknown as Entry,
undefined as unknown as Entry,
{ type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "flash", stepPassed: false, history: [{ step: "edit", passed: true, timestamp: 1 }] } },
]);
expect(state.currentStep).toBe("flash");
});
it("rebuild 容忍 entry.type 非 string(如 number/object)→ 跳过", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
const state = rec.rebuild([
{ type: 123, data: {} },
{ type: { x: 1 }, data: {} },
{ type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "verify", stepPassed: false, history: [] } },
] as unknown as Entry[]);
expect(state.currentStep).toBe("verify");
});
it("rebuild 容忍 entry.data 含循环引用的 history 条目(仅取合法字段,多余字段丢弃)", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
const circular: unknown = { step: "edit", passed: true, timestamp: 1 };
(circular as Record<string, unknown>).self = circular;
const data = { currentStep: "compile", stepPassed: false, history: [circular] };
const state = rec.rebuild([{ type: CHECKPOINT_CHANGE_TYPE, data }]);
expect(state.currentStep).toBe("compile");
expect(state.history[0]).toEqual({ step: "edit", passed: true, timestamp: 1 });
});
it("rebuild 拒绝 history 非数组的 data(缺 Array)→ 回初始态", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
const state = rec.rebuild([
{ type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "flash", stepPassed: false, history: "not-array" } },
]);
expect(state.currentStep).toBe("edit");
expect(state.history.length).toBe(0);
});
it("rebuild 拒绝 history 条目字段类型错(passed 非 boolean)→ 回初始态", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
const state = rec.rebuild([
{ type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "flash", stepPassed: false, history: [{ step: "edit", passed: "yes", timestamp: 1 }] } },
]);
expect(state.currentStep).toBe("edit");
});
it("rebuild 拒绝 history 条目缺 timestamp → 回初始态", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
const state = rec.rebuild([
{ type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "flash", stepPassed: false, history: [{ step: "edit", passed: true }] } },
]);
expect(state.currentStep).toBe("edit");
});
it("rebuild 拒绝 history 条目 step 非 string → 回初始态", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
const state = rec.rebuild([
{ type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "flash", stepPassed: false, history: [{ step: 42, passed: true, timestamp: 1 }] } },
]);
expect(state.currentStep).toBe("edit");
});
it("rebuild 拒绝 data 顶层 stepPassed 非 boolean → 回初始态", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
const state = rec.rebuild([
{ type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "flash", stepPassed: "yes", history: [] } },
]);
expect(state.currentStep).toBe("edit");
});
it("rebuild 接受 NaN/Infinity timestamp(typeof number 通过校验,宽松容差)", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
const state = rec.rebuild([
{ type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "flash", stepPassed: false, history: [{ step: "edit", passed: true, timestamp: NaN }] } },
]);
expect(state.currentStep).toBe("flash");
expect(Number.isNaN(state.history[0]!.timestamp)).toBe(true);
});
it("rebuild 拒绝越界 currentStep(非 STEP_ORDER 合法步骤)→ 回初始态(fail-closed)", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
const state = rec.rebuild([
{ type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "bogus", stepPassed: false, history: [] } },
]);
// isCheckpointState 校验 currentStep 须在 STEP_ORDER 内,坏快照 → 回初始态
expect(state.currentStep).toBe("edit");
expect(state.stepPassed).toBe(false);
expect(state.history).toEqual([]);
});
it("rebuild 拒绝越界 currentStep 后不伪造完成态(防 forward-jump 绕过推进门)", () => {
// 回归 finding:坏快照 currentStep='bogus' 不得被接受为内部态。
// 旧实现 curIdx=-1,使后续 record 的 targetIdx>-1 恒成立,可从被篡改日志
// 向前跳过 edit→compile→flash→verify→check→done 正常推进门伪造完成。
// 修复后坏快照被拒 → 内部回初始态(currentStep=edit),不再携带越界串。
const rec = new CheckpointRecorder({ append: noopSink() });
const state = rec.rebuild([{ type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "bogus", stepPassed: false, history: [] } }]);
expect(state.currentStep).toBe("edit");
expect(state.stepPassed).toBe(false);
// 内部态既非越界 'bogus' 亦非终态 'done':未从坏快照继承任何伪造进度
expect(STEP_ORDER.includes(state.currentStep)).toBe(true);
expect(state.currentStep).not.toBe("bogus");
expect(state.currentStep).not.toBe("done");
});
it("rebuild 越界 currentStep 快照被当作坏条跳过,后续合法快照胜出(与坏 data 一致处理)", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
const state = rec.rebuild([
{ type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "bogus", stepPassed: false, history: [] } }, // 坏(越界 currentStep)
{ type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "flash", stepPassed: false, history: [{ step: "edit", passed: true, timestamp: 1 }] } }, // 好
]);
expect(state.currentStep).toBe("flash");
expect(state.history.length).toBe(1);
});
it("record 接受负/零 timestamp(注入式确定性,不做值校验)", () => {
const { sink, calls } = recordingSink();
const rec = new CheckpointRecorder({ append: sink });
rec.record("edit", true, -1);
rec.record("edit", true, 0);
expect(calls[0]!.data as CheckpointState).toMatchObject({ currentStep: "compile" });
expect((calls[0]!.data as CheckpointState).history[0]!.timestamp).toBe(-1);
expect((calls[1]!.data as CheckpointState).history[1]!.timestamp).toBe(0);
});
it("巨大 history(1000 条)不爆栈、rebuild 等价", () => {
const { sink, calls } = recordingSink();
const rec = new CheckpointRecorder({ append: sink });
for (let i = 0; i < 1000; i++) rec.record("edit", true, i);
expect(rec.current().history.length).toBe(1000);
const resumed = new CheckpointRecorder({ append: noopSink() });
const rebuilt = resumed.rebuild(calls);
expect(rebuilt.history.length).toBe(1000);
expect(rebuilt.currentStep).toBe("compile");
});
it("rebuild 非数组入参(null/undefined/number/object/string)静默回初始态不抛", () => {
const badInputs: unknown[] = [null, undefined, 42, "nope", { a: 1 }, true];
for (const bad of badInputs) {
const rec = new CheckpointRecorder({ append: noopSink() });
expect(() => rec.rebuild(bad as unknown as Entry[])).not.toThrow();
const state = rec.rebuild(bad as unknown as Entry[]);
expect(state.currentStep).toBe("edit");
expect(state.history.length).toBe(0);
}
});
it("rebuild 空数组对象 entry(无 type 字段)静默跳过", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
const state = rec.rebuild([{} as Entry, { data: {} } as Entry]);
expect(state.currentStep).toBe("edit");
});
it("rebuild 期间 append sink 不被调用(rebuild 是只读重建)", () => {
const { sink, calls } = recordingSink();
const rec = new CheckpointRecorder({ append: sink });
rec.rebuild([{ type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "done", stepPassed: true, history: [] } }]);
expect(calls.length).toBe(0);
});
it("record 写出的事件 type 恒为 CHECKPOINT_CHANGE_TYPE(无论 step/passed)", () => {
const { sink, calls } = recordingSink();
const rec = new CheckpointRecorder({ append: sink });
rec.record("edit", true, 1);
rec.record("compile", false, 2);
rec.record("bogus" as CheckpointStep, true, 3);
expect(calls.every((c) => c.type === CHECKPOINT_CHANGE_TYPE)).toBe(true);
});
});
// ============================================================================
// ⑦ 元蜕变/不变式 —— fail-closed / 深拷贝 / 单调 / waterfall 短路
// ============================================================================
describe("⑦ 元蜕变/不变式 — fail-closed 与深拷贝", () => {
it("current() 返回独立深拷贝:篡改返回值不影响内部状态", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
rec.record("edit", true, 1000);
const snap = rec.current();
snap.currentStep = "done";
snap.stepPassed = true;
snap.history.push({ step: "done", passed: true, timestamp: 999 });
expect(rec.current().currentStep).toBe("compile");
expect(rec.current().stepPassed).toBe(false);
expect(rec.current().history.length).toBe(1);
});
it("record 写出的 snapshot 是独立拷贝:篡改下沉的 data 不影响后续 current()", () => {
const { sink, calls } = recordingSink();
const rec = new CheckpointRecorder({ append: sink });
rec.record("edit", true, 1000);
const written = calls[0]!.data as CheckpointState;
written.history.push({ step: "bogus" as unknown as CheckpointStep, passed: true, timestamp: 0 });
written.currentStep = "done";
expect(rec.current().currentStep).toBe("compile");
expect(rec.current().history.length).toBe(1);
});
it("两次 current() 返回互不共享(深拷贝独立性)", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
rec.record("edit", true, 1000);
const a = rec.current();
const b = rec.current();
a.history.push({ step: "x" as unknown as CheckpointStep, passed: true, timestamp: 0 });
expect(b.history.length).toBe(1);
});
it("单调不变式:pass 任意已过步骤不会回退 currentStep", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
for (const op of FULL_PASS_SEQ) rec.record(op.step, op.passed, op.ts);
const before = rec.current().currentStep; // done
rec.record("edit", true, 8000);
rec.record("compile", true, 8100);
rec.record("flash", true, 8200);
rec.record("verify", true, 8300);
rec.record("check", true, 8400);
expect(rec.current().currentStep).toBe(before);
expect(rec.current().stepPassed).toBe(true);
});
it("waterfall 短路不变式:failed record 不前进到 next 步(停在失败步)", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
rec.record("edit", true, 1000); // → compile
rec.record("compile", false, 2000); // 失败 → 停 compile,不进 flash
expect(rec.current().currentStep).toBe("compile");
expect(rec.current().currentStep).not.toBe("flash");
});
it("fail-closed unusable=拒:rebuild 全坏条 → 回初始态(不采用任何坏快照)", () => {
const rec = new CheckpointRecorder({ append: noopSink() });
const state = rec.rebuild([
{ type: CHECKPOINT_CHANGE_TYPE, data: null },
{ type: CHECKPOINT_CHANGE_TYPE, data: "string" },
{ type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "flash" } },
{ type: CHECKPOINT_CHANGE_TYPE, data: { currentStep: "flash", stepPassed: false, history: [{ step: "edit", passed: "true", timestamp: 1 }] } },
]);
expect(state.currentStep).toBe(INITIAL_CHECKPOINT_STATE.currentStep);
expect(state.stepPassed).toBe(false);
expect(state.history).toEqual([]);
});
it("元蜕变·append 两次 ≡ 从 log replay 重建(rebuild 等价不变式)", () => {
const { sink, calls } = recordingSink();
const rec = new CheckpointRecorder({ append: sink });
rec.record("edit", true, 1000);
rec.record("compile", false, 2000);
rec.record("compile", true, 3000);
const original = rec.current();
const replayed = new CheckpointRecorder({ append: noopSink() });
const rebuiltState = replayed.rebuild(calls);
expect(rebuiltState).toEqual(original);
});
it("元蜕变·fork 后子状态 == 父状态(拷贝等价),再各自演进仍保持各自一致", () => {
const { sink } = recordingSink();
const parent = new CheckpointRecorder({ append: sink });
for (const op of FULL_PASS_SEQ.slice(0, 3)) parent.record(op.step, op.passed, op.ts);
const child = parent.fork();
expect(child.current()).toEqual(parent.current());
child.record("verify", true, 4000);
parent.record("verify", false, 4100);
expect(child.current().currentStep).not.toBe(parent.current().currentStep);
expect(child.current().currentStep).toBe("check");
expect(parent.current().currentStep).toBe("verify");
});
it("freeze→篡改抛 TypeError:INITIAL_CHECKPOINT_STATE 顶层冻结", () => {
expect(() => {
(INITIAL_CHECKPOINT_STATE as unknown as { stepPassed: unknown }).stepPassed = true;
}).toThrow(TypeError);
});
it("元蜕变·record 后 current() ≡ sink 中最后一条快照(写出即当前)", () => {
const { sink, calls } = recordingSink();
const rec = new CheckpointRecorder({ append: sink });
rec.record("edit", true, 1);
rec.record("compile", true, 2);
expect(rec.current()).toEqual(calls[calls.length - 1]!.data as CheckpointState);
});
});
// ============================================================================
// ⑤ 变异测试 —— 4 个 seeded bug,每个被 kill-assertion 杀死
// ============================================================================
/**
* 变异测试策略:
* 对每个 seeded bug,内联一份带 bug 的 advance 逻辑副本(与源 advanceState 同形,
* 仅一处变异,且【含 done/failed 分支守卫】保真)。对同一场景,分别用【真实 advance 副本】
* 与【带虫副本】推进,断言:
* (a) 真实副本结果 == 正确期望(real code passes → gate 1 green);
* (b) 带虫副本结果 != 正确期望,且对带虫结果断言正确值会 throw(kill-assertion:
* 若该 bug 植入真实代码,此断言失败 = bug 被杀)。
*
* 此外,tests/.mutation-kill/ 下每个 mutant 有独立 .mjs 文件(node:assert),
* 单独跑 `node tests/.mutation-kill/mN.mjs` 确认 FAIL(exit=1 = bug 被杀)。
*
* 这使得套件对真实(未植入)代码全绿,同时自验每个变异被某条断言杀死。
*/
describe("⑤ 变异测试 — 自验每个 seeded bug 被杀死", () => {
it("副本保真·真实 advance 副本与 CheckpointRecorder 行为一致——全 passed 序列", () => {
const ops = FULL_PASS_SEQ.map((o) => ({ step: o.step, passed: o.passed, ts: o.ts }));
const copyState = applySeq(realAdvance, ops);
const rec = new CheckpointRecorder({ append: noopSink() });
for (const o of ops) rec.record(o.step, o.passed, o.ts);
expect(copyState).toEqual(rec.current());
});
it("副本保真·含 failed + done 守卫序列(failed/done 分支保真)", () => {
// 此场景触碰 failed 分支的 idx<=curIdx 守卫与 done 分支守卫——
// 不忠实副本(漏守卫)会在此发散
const ops: Array<{ step: CheckpointStep; passed: boolean; ts: number }> = [
{ step: "edit", passed: true, ts: 1000 },
{ step: "compile", passed: true, ts: 2000 }, // → flash
{ step: "flash", passed: false, ts: 3000 }, // 退回 flash (idx=cur=2)
{ step: "verify", passed: false, ts: 4000 }, // idx=3>cur=2 → 不动
{ step: "done", passed: false, ts: 5000 }, // idx=5>cur=2 → 不动
{ step: "check", passed: true, ts: 6000 }, // idx=4>cur=2 → 不动(非末 targetIdx=5>2 前进到 done?)
];
const copyState = applySeq(realAdvance, ops);
const rec = new CheckpointRecorder({ append: noopSink() });
for (const o of ops) rec.record(o.step, o.passed, o.ts);
expect(copyState).toEqual(rec.current());
});
it("M1 killed: `> → >=` — done 后补跑 check 应保持 stepPassed=true,带虫副本变 false", () => {
// 场景:全通过到 done(stepPassed=true) → 再 pass check(targetIdx=5===curIdx=5)
const ops: Array<{ step: CheckpointStep; passed: boolean; ts: number }> = [
...FULL_PASS_SEQ.map((o) => ({ step: o.step, passed: o.passed as boolean, ts: o.ts })),
{ step: "check" as CheckpointStep, passed: true, ts: 7000 },
];
const realResult = applySeq(realAdvance, ops);
const bugResult = applySeq(m1Advance, ops);
// (a) 真实正确
expect(realResult.stepPassed).toBe(true);
expect(realResult.currentStep).toBe("done");
// (b) 带虫发散:stepPassed 变 false → kill-assertion 对带虫断言 true 会 throw
expect(bugResult.stepPassed).toBe(false);
expect(() => expect(bugResult.stepPassed).toBe(true)).toThrow();
});
it("M2 killed: `length-1 → length` — pass done 应 currentStep=done+stepPassed=true,带虫副本 currentStep=undefined", () => {
const ops = FULL_PASS_SEQ.map((o) => ({ step: o.step, passed: o.passed as boolean, ts: o.ts }));
const realResult = applySeq(realAdvance, ops);
const bugResult = applySeq(m2Advance, ops);
// (a) 真实正确
expect(realResult.currentStep).toBe("done");
expect(realResult.stepPassed).toBe(true);
// (b) 带虫发散:currentStep=undefined → kill-assertion 断言 "done" 会 throw
expect(bugResult.currentStep).toBeUndefined();
expect(() => expect(bugResult.currentStep).toBe("done")).toThrow();
});
it("M3 killed: `stepPassed=false → true` — 正常前进后 stepPassed 应 false,带虫副本变 true", () => {
const ops: Array<{ step: CheckpointStep; passed: boolean; ts: number }> = [
{ step: "edit", passed: true, ts: 1000 },
];
const realResult = applySeq(realAdvance, ops);
const bugResult = applySeq(m3Advance, ops);
// (a) 真实正确
expect(realResult.stepPassed).toBe(false);
expect(realResult.currentStep).toBe("compile");
// (b) 带虫发散:stepPassed=true → kill-assertion 断言 false 会 throw
expect(bugResult.stepPassed).toBe(true);
expect(() => expect(bugResult.stepPassed).toBe(false)).toThrow();
});
it("M4 killed: failed `<= → <` — fail done 应 stepPassed=false,带虫副本保持 true(伪造完成)", () => {
// 场景:全通过到 done(stepPassed=true) → 再 fail done(idx=5===curIdx=5)
// 真实:5<=5 true → stepPassed 重置 false(退回 done 重试)
// 带虫:5<5 false → 不动,stepPassed 保持 true(fail 不清除完成态=伪造)
const ops: Array<{ step: CheckpointStep; passed: boolean; ts: number }> = [
...FULL_PASS_SEQ.map((o) => ({ step: o.step, passed: o.passed as boolean, ts: o.ts })),
{ step: "done" as CheckpointStep, passed: false, ts: 7000 },
];
const realResult = applySeq(realAdvance, ops);
const bugResult = applySeq(m4Advance, ops);
// (a) 真实正确
expect(realResult.stepPassed).toBe(false);
expect(realResult.currentStep).toBe("done");
// (b) 带虫发散:stepPassed 保持 true → kill-assertion 断言 false 会 throw
expect(bugResult.stepPassed).toBe(true);
expect(() => expect(bugResult.stepPassed).toBe(false)).toThrow();
});
it("变异汇总:4 个 bug 在各自 kill 场景均与真实副本发散(均被杀死)", () => {
// 汇总不变式:每个带虫副本在其 kill 场景下输出 != 真实副本输出
const fullOps = FULL_PASS_SEQ.map((o) => ({ step: o.step, passed: o.passed as boolean, ts: o.ts }));
const realFull = applySeq(realAdvance, fullOps);
expect(realFull.currentStep).toBe("done");
// 各 kill 场景断言
expect(applySeq(m1Advance, [...fullOps, { step: "check", passed: true, ts: 7 }]).stepPassed).toBe(false);
expect(applySeq(m2Advance, fullOps).currentStep).toBeUndefined();
expect(applySeq(m3Advance, [{ step: "edit", passed: true, ts: 1 }]).stepPassed).toBe(true);
expect(applySeq(m4Advance, [...fullOps, { step: "done", passed: false, ts: 7 }]).stepPassed).toBe(true);
// 真实副本在 M4 kill 场景应为 false(对照)
expect(applySeq(realAdvance, [...fullOps, { step: "done", passed: false, ts: 7 }]).stepPassed).toBe(false);
});
it("每个 mutant 至少在一条 kill 场景与 realAdvance 发散(无等价/存活 mutant)", () => {
// 对每个 mutant,至少存在一组 ops 使其输出 != realAdvance 输出
const killScenarios: Record<string, Array<{ step: CheckpointStep; passed: boolean; ts: number }>> = {
M1: [...FULL_PASS_SEQ.map((o) => ({ step: o.step, passed: o.passed as boolean, ts: o.ts })), { step: "check", passed: true, ts: 7 }],
M2: FULL_PASS_SEQ.map((o) => ({ step: o.step, passed: o.passed as boolean, ts: o.ts })),
M3: [{ step: "edit", passed: true, ts: 1 }],
M4: [...FULL_PASS_SEQ.map((o) => ({ step: o.step, passed: o.passed as boolean, ts: o.ts })), { step: "done", passed: false, ts: 7 }],
};
for (const { name, fn } of ALL_MUTANTS) {
const ops = killScenarios[name]!;
const realOut = JSON.stringify(applySeq(realAdvance, ops));
const bugOut = JSON.stringify(applySeq(fn, ops));
expect(bugOut).not.toBe(realOut);
}
});
});