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>
1168 lines
44 KiB
TypeScript
1168 lines
44 KiB
TypeScript
/**
|
||
* @module context-injector.test
|
||
*
|
||
* T13 上下文注入三段(inject / steer / followup)—— 严谨多方法论测试套件。
|
||
*
|
||
* 被测对象:src/core/context-injector.ts 的命名导出
|
||
* - 常量:INJECTION_PHASES / CONTEXT_INJECTION_TYPE
|
||
* - 类型:InjectionPhase / Injection / RuntimeSnapshot / InjectionSink / ActiveContext
|
||
* - 类:ContextInjector(inject / steer / followup / snapshot / deriveActiveContext / clear)
|
||
* - 函数:toSessionEntry
|
||
*
|
||
* 直接 import 真实模块;mock 注入依赖(appendEntry sink),无 pi 运行时 / 无硬件 / 无网络。
|
||
*
|
||
* 多测试方法论(每个 describe 块标注方法论名):
|
||
* 1. 等价类划分(Equivalence Partitioning)
|
||
* 2. 边界值分析(Boundary Value Analysis)
|
||
* 3. 决策表(Decision Table)
|
||
* 4. 状态转换(State Transition)
|
||
* 5. 对抗 / Fuzz(Adversarial / Fuzz)
|
||
* 6. 元蜕变 / 不变式(Metamorphic / Invariant)
|
||
* 7. 变异测试(Mutation Testing)—— 5 个植入 bug(A-E),gated by MUTATION_BUG env
|
||
*
|
||
* 门:
|
||
* - 默认(无 MUTATION_BUG)跑 → 真实代码全绿(变异块 skipIf 跳过)。
|
||
* - MUTATION_BUG=A/B/C/D/E 单独跑 → 对应植入 bug 副本的测试 FAIL(bug 被杀)。
|
||
* - 验证门:先跑 `npx vitest run tests/context-injector.test.ts`(all green),
|
||
* 再对每个 bug 跑 `MUTATION_BUG=X npx vitest run tests/context-injector.test.ts`,
|
||
* 期望该 it FAIL(exit!=0)= bug 被杀。
|
||
*/
|
||
|
||
import { describe, it, expect } from "vitest";
|
||
import {
|
||
ContextInjector,
|
||
INJECTION_PHASES,
|
||
CONTEXT_INJECTION_TYPE,
|
||
toSessionEntry,
|
||
type Injection,
|
||
type InjectionPhase,
|
||
type RuntimeSnapshot,
|
||
type ActiveContext,
|
||
type InjectionSink,
|
||
} from "../src/core/context-injector.js";
|
||
import type { PbaSessionEntry } from "../src/core/pba-session.js";
|
||
|
||
/** 测试用:把 readonly 字段变 mutable 以验证冻结。 */
|
||
type Mutable<T> = { -readonly [K in keyof T]: T[K] };
|
||
|
||
// ============================================================================
|
||
// 工具
|
||
// ============================================================================
|
||
|
||
/** 收集 appendEntry 下沉事件的 mock sink。 */
|
||
function makeSink(): { sink: InjectionSink; calls: Array<{ type: string; data: unknown }> } {
|
||
const calls: Array<{ type: string; data: unknown }> = [];
|
||
return {
|
||
calls,
|
||
sink: (type: string, data: unknown) => calls.push({ type, data }),
|
||
};
|
||
}
|
||
|
||
/** 构造一个不冻结的注入器(测试默认;冻结语义单独验证)。 */
|
||
function softCi(appendEntry?: InjectionSink): ContextInjector {
|
||
return new ContextInjector({ deepFreeze: false, ...(appendEntry ? { appendEntry } : {}) });
|
||
}
|
||
|
||
// ============================================================================
|
||
// 1. 等价类划分(Equivalence Partitioning)—— 有效 phase / 无效 phase / 有效 content / 无效 content
|
||
// 每一类取代表值,覆盖全部合法/非法分支。
|
||
// ============================================================================
|
||
|
||
describe("等价类划分:phase 合法集 + content 有效性", () => {
|
||
it("有效 phase 类:inject → { phase:'inject', nextStep:true, nextTurn:false, boardId:undef, replacesSnapshot:undef }", () => {
|
||
const ci = softCi();
|
||
const inj = ci.inject("reg map 0x48=RTC");
|
||
expect(inj.phase).toBe("inject");
|
||
expect(inj.nextStep).toBe(true);
|
||
expect(inj.nextTurn).toBe(false);
|
||
expect(inj.boardId).toBeUndefined();
|
||
expect(inj.replacesSnapshot).toBeUndefined();
|
||
});
|
||
|
||
it("有效 phase 类:steer → { phase:'steer', nextStep:true, nextTurn:false, boardId?:arg }", () => {
|
||
const ci = softCi();
|
||
const inj = ci.steer("switch to S100", "s100");
|
||
expect(inj.phase).toBe("steer");
|
||
expect(inj.nextStep).toBe(true);
|
||
expect(inj.nextTurn).toBe(false);
|
||
expect(inj.boardId).toBe("s100");
|
||
});
|
||
|
||
it("有效 phase 类:steer 无 boardId → boardId:undefined(可选省略)", () => {
|
||
const ci = softCi();
|
||
const inj = ci.steer("switch board (unspecified)");
|
||
expect(inj.boardId).toBeUndefined();
|
||
});
|
||
|
||
it("有效 phase 类:followup → { phase:'followup', nextStep:false, nextTurn:true, boardId:undef }", () => {
|
||
const ci = softCi();
|
||
const inj = ci.followup("flash new bootloader");
|
||
expect(inj.phase).toBe("followup");
|
||
expect(inj.nextStep).toBe(false);
|
||
expect(inj.nextTurn).toBe(true);
|
||
expect(inj.boardId).toBeUndefined();
|
||
});
|
||
|
||
it("有效 content 类:单字符 'x' 与长文本均通过(最小/最大有效边界)", () => {
|
||
const ci = softCi();
|
||
expect(() => ci.inject("x")).not.toThrow();
|
||
const long = "reg ".repeat(10000).trimEnd();
|
||
const inj = ci.inject(long);
|
||
expect(inj.content).toBe(long);
|
||
});
|
||
|
||
it("有效 content 类:含 Unicode / emoji / CJK 均通过(非 ASCII 等价类)", () => {
|
||
const ci = softCi();
|
||
const inj = ci.inject("寄存器 0x48 = RTC 🚀");
|
||
expect(inj.content).toBe("寄存器 0x48 = RTC 🚀");
|
||
});
|
||
|
||
it("无效 content 类:空串 '' → 三个入口均 fail-closed 抛错", () => {
|
||
const ci = new ContextInjector();
|
||
expect(() => ci.inject("")).toThrow();
|
||
expect(() => ci.steer("")).toThrow();
|
||
expect(() => ci.followup("")).toThrow();
|
||
});
|
||
|
||
it("无效 content 类:纯空白(空格/制表/换行混合)→ fail-closed 抛错(trim 归零)", () => {
|
||
const ci = new ContextInjector();
|
||
expect(() => ci.inject(" ")).toThrow();
|
||
expect(() => ci.steer("\t\n")).toThrow();
|
||
expect(() => ci.followup(" \t ")).toThrow();
|
||
});
|
||
|
||
it("无效 content 类:非字符串(null/undefined/number/object/array/boolean/symbol)→ fail-closed 抛错", () => {
|
||
const ci = new ContextInjector();
|
||
for (const bad of [null, undefined, 42, {}, [], true, Symbol("s")] as unknown[]) {
|
||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||
expect(() => ci.inject(bad as any)).toThrow();
|
||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||
expect(() => ci.steer(bad as any, "b")).toThrow();
|
||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||
expect(() => ci.followup(bad as any)).toThrow();
|
||
}
|
||
});
|
||
|
||
it("无效 phase 类:clear(非法 phase) → assertPhase 抛错(fail-closed)", () => {
|
||
const ci = softCi();
|
||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||
expect(() => ci.clear("evil" as any)).toThrow();
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// 2. 边界值分析(Boundary Value Analysis)—— 空/单/max/off-by-one
|
||
// off-by-one 是注入器最易错点(slice 端点 / seq 自增 / 分隔符计数)。
|
||
// ============================================================================
|
||
|
||
describe("边界值分析:空 / 单元素 / 多元素 / seq off-by-one", () => {
|
||
it("空寄存器:snapshot content='' / boardId=undef / ts>0(live 空集合边界)", () => {
|
||
const ci = softCi();
|
||
const snap = ci.snapshot();
|
||
expect(snap.content).toBe("");
|
||
expect(snap.boardId).toBeUndefined();
|
||
expect(snap.ts).toBeGreaterThan(0);
|
||
});
|
||
|
||
it("空寄存器:deriveActiveContext → injections=[] / active=null", () => {
|
||
const ci = softCi();
|
||
const ctx = ci.deriveActiveContext();
|
||
expect(ctx.injections).toHaveLength(0);
|
||
expect(ctx.active).toBeNull();
|
||
});
|
||
|
||
it("单元素 inject:snapshot content === 该单条(无拼接,单元素分隔符边界)", () => {
|
||
const ci = softCi();
|
||
ci.inject("only");
|
||
const snap = ci.snapshot();
|
||
expect(snap.content).toBe("only");
|
||
});
|
||
|
||
it("单元素 inject:deriveActiveContext.active === 该单条", () => {
|
||
const ci = softCi();
|
||
const inj = ci.inject("only");
|
||
const ctx = ci.deriveActiveContext();
|
||
expect(ctx.active).toBe(inj);
|
||
});
|
||
|
||
it("单元素 steer(无 boardId):snapshot boardId=undef(无 boardId 可取边界)", () => {
|
||
const ci = softCi();
|
||
ci.steer("switch");
|
||
const snap = ci.snapshot();
|
||
expect(snap.boardId).toBeUndefined();
|
||
});
|
||
|
||
it("双元素 inject:snapshot content 用 '\\n\\n' 拼接(off-by-one 分隔符边界:N=2 → 1 个分隔符)", () => {
|
||
const ci = softCi();
|
||
ci.inject("a");
|
||
ci.inject("b");
|
||
expect(ci.snapshot().content).toBe("a\n\nb");
|
||
});
|
||
|
||
it("三元素 inject:content === 'a\\n\\nb\\n\\nc'(N=3 → 2 个分隔符)", () => {
|
||
const ci = softCi();
|
||
ci.inject("a");
|
||
ci.inject("b");
|
||
ci.inject("c");
|
||
expect(ci.snapshot().content).toBe("a\n\nb\n\nc");
|
||
});
|
||
|
||
it("snapshot seq 边界:首快照 id snap-1(snapshotSeq 从 0 自增到 1,off-by-one 不偏)", () => {
|
||
const ci = softCi();
|
||
ci.inject("x");
|
||
ci.snapshot(); // snap-1
|
||
expect(ci.steer("s", "b").replacesSnapshot).toBe("snap-1");
|
||
});
|
||
|
||
it("snapshot seq 边界:第二快照 id snap-2(链指向最新前驱)", () => {
|
||
const ci = softCi();
|
||
ci.inject("x");
|
||
ci.snapshot(); // snap-1
|
||
ci.steer("s1", "b1"); // replaces=snap-1
|
||
ci.snapshot(); // snap-2
|
||
expect(ci.followup("new").replacesSnapshot).toBe("snap-2");
|
||
});
|
||
|
||
it("steer 后无快照:replacesSnapshot=undef(currentSnapshotId 边界:无快照)", () => {
|
||
const ci = softCi();
|
||
ci.inject("x");
|
||
// 未 snapshot → 无快照历史 → steer 不取代
|
||
expect(ci.steer("s", "b").replacesSnapshot).toBeUndefined();
|
||
});
|
||
|
||
it("inject 永不取代:有快照后 inject 的 replacesSnapshot 仍 undef(inject 边界恒定)", () => {
|
||
const ci = softCi();
|
||
ci.inject("baseline");
|
||
ci.snapshot(); // snap-1 存在
|
||
expect(ci.inject("more").replacesSnapshot).toBeUndefined();
|
||
});
|
||
|
||
it("clear() 后 snapshotSeq 归零:新首快照 id snap-1(reset 边界)", () => {
|
||
const ci = softCi();
|
||
ci.inject("x");
|
||
ci.snapshot(); // snap-1, seq=1
|
||
ci.clear(); // seq 归 0
|
||
ci.inject("y");
|
||
ci.snapshot(); // snap-1 again
|
||
expect(ci.steer("s", "b").replacesSnapshot).toBe("snap-1");
|
||
});
|
||
|
||
it("clear(phase) 不重置 snapshotSeq:phase 清除后快照 id 链不变", () => {
|
||
const ci = softCi();
|
||
ci.inject("a");
|
||
ci.snapshot(); // snap-1
|
||
ci.inject("b");
|
||
ci.clear("inject" as InjectionPhase); // 清全部 inject,但不重置 seq/快照
|
||
// 快照历史仍在 → 下次 steer 取代 snap-1
|
||
expect(ci.steer("s", "b").replacesSnapshot).toBe("snap-1");
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// 3. 决策表(Decision Table)—— phase × {nextStep,nextTurn,boardId,replacesSnapshot} × {有无快照}
|
||
// 全分支覆盖:每个 phase 在「无快照」「有快照」两列下的期望。
|
||
// ============================================================================
|
||
|
||
describe("决策表:phase × 快照存在性 → 期望字段矩阵", () => {
|
||
// 决策表(R = replacesSnapshot;— = 不适用/undef)
|
||
// ┌──────────┬──────────┬─────────┬─────────┬──────────┬──────────────────────┐
|
||
// │ phase │ snapshot │ nextStep│ nextTurn│ boardId │ replacesSnapshot │
|
||
// ├──────────┼──────────┼─────────┼─────────┼──────────┼──────────────────────┤
|
||
// │ inject │ 无/有 │ true │ false │ undef │ undef(不取代) │
|
||
// │ steer │ 无 │ true │ false │ arg │ undef(无前驱) │
|
||
// │ steer │ 有 │ true │ false │ arg │ <最新快照 id> │
|
||
// │ followup │ 无 │ false │ true │ undef │ undef(无前驱) │
|
||
// │ followup │ 有 │ false │ true │ undef │ <最新快照 id> │
|
||
// └──────────┴──────────┴─────────┴─────────┴──────────┴──────────────────────┘
|
||
|
||
it("inject 行(无快照):nextStep=true,nextTurn=false,boardId=undef,R=undef", () => {
|
||
const ci = softCi();
|
||
const inj = ci.inject("a");
|
||
expect(inj).toMatchObject({ phase: "inject", nextStep: true, nextTurn: false });
|
||
expect(inj.boardId).toBeUndefined();
|
||
expect(inj.replacesSnapshot).toBeUndefined();
|
||
});
|
||
|
||
it("inject 行(有快照):有快照也不取代(replacesSnapshot 恒 undef)", () => {
|
||
const ci = softCi();
|
||
ci.inject("baseline");
|
||
ci.snapshot(); // snap-1 存在
|
||
const inj = ci.inject("more regs");
|
||
expect(inj.nextStep).toBe(true);
|
||
expect(inj.nextTurn).toBe(false);
|
||
expect(inj.boardId).toBeUndefined();
|
||
expect(inj.replacesSnapshot).toBeUndefined(); // inject 不取代
|
||
});
|
||
|
||
it("steer 行(无快照):replacesSnapshot=undef", () => {
|
||
const ci = softCi();
|
||
const inj = ci.steer("switch", "b");
|
||
expect(inj.nextStep).toBe(true);
|
||
expect(inj.nextTurn).toBe(false);
|
||
expect(inj.boardId).toBe("b");
|
||
expect(inj.replacesSnapshot).toBeUndefined();
|
||
});
|
||
|
||
it("steer 行(有快照):replacesSnapshot=<最新快照 id>", () => {
|
||
const ci = softCi();
|
||
ci.inject("x");
|
||
ci.snapshot(); // snap-1
|
||
const inj = ci.steer("switch", "b");
|
||
expect(inj.nextStep).toBe(true);
|
||
expect(inj.nextTurn).toBe(false);
|
||
expect(inj.boardId).toBe("b");
|
||
expect(inj.replacesSnapshot).toBe("snap-1");
|
||
});
|
||
|
||
it("followup 行(无快照):replacesSnapshot=undef", () => {
|
||
const ci = softCi();
|
||
const inj = ci.followup("new task");
|
||
expect(inj.nextStep).toBe(false);
|
||
expect(inj.nextTurn).toBe(true);
|
||
expect(inj.boardId).toBeUndefined();
|
||
expect(inj.replacesSnapshot).toBeUndefined();
|
||
});
|
||
|
||
it("followup 行(有快照):replacesSnapshot=<最新快照 id>", () => {
|
||
const ci = softCi();
|
||
ci.inject("x");
|
||
ci.snapshot(); // snap-1
|
||
const inj = ci.followup("new task");
|
||
expect(inj.nextStep).toBe(false);
|
||
expect(inj.nextTurn).toBe(true);
|
||
expect(inj.boardId).toBeUndefined();
|
||
expect(inj.replacesSnapshot).toBe("snap-1");
|
||
});
|
||
|
||
it("boardId 决策:inject/followup 恒 undef;steer 取 arg(含省略→undef)", () => {
|
||
const ci = softCi();
|
||
expect(ci.inject("a").boardId).toBeUndefined();
|
||
expect(ci.followup("c").boardId).toBeUndefined();
|
||
expect(ci.steer("b", "s100").boardId).toBe("s100");
|
||
expect(ci.steer("b2").boardId).toBeUndefined();
|
||
});
|
||
|
||
it("nextStep/nextTurn 互斥决策:steer/inject 绑 step 不绑 turn;followup 绑 turn 不绑 step", () => {
|
||
const ci = softCi();
|
||
const i = ci.inject("a");
|
||
const s = ci.steer("b", "x");
|
||
const f = ci.followup("c");
|
||
expect(i.nextStep && !i.nextTurn).toBe(true);
|
||
expect(s.nextStep && !s.nextTurn).toBe(true);
|
||
expect(!f.nextStep && f.nextTurn).toBe(true);
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// 4. 状态转换(State Transition)—— live 集合随 steer/followup 刷新;
|
||
// snapshot 历史 append-only;clear 全重置;sink 重入;不可达状态验证。
|
||
// ============================================================================
|
||
|
||
describe("状态转换:live 集合刷新 + snapshot 历史 + clear 重置", () => {
|
||
it("初始态:全部注入 live(无 steer/followup pivot)", () => {
|
||
const ci = softCi();
|
||
ci.inject("a");
|
||
ci.inject("b");
|
||
const snap = ci.snapshot();
|
||
expect(snap.content).toBe("a\n\nb"); // 两条都在 live
|
||
});
|
||
|
||
it("迁移 inject→steer:live 收缩为 steer(含)之后(取代更早 inject)", () => {
|
||
const ci = softCi();
|
||
ci.inject("old X=1");
|
||
ci.steer("switch board", "s100");
|
||
ci.inject("new Y=2");
|
||
const snap = ci.snapshot();
|
||
// live = [steer, inject(new)] —— steer 之前的 inject 被取代
|
||
expect(snap.content).toBe("switch board\n\nnew Y=2");
|
||
expect(snap.boardId).toBe("s100");
|
||
});
|
||
|
||
it("迁移 steer→followup:live 收缩为 followup(含)之后", () => {
|
||
const ci = softCi();
|
||
ci.steer("board A", "a");
|
||
ci.inject("reg A");
|
||
ci.followup("new task");
|
||
ci.inject("reg B");
|
||
const snap = ci.snapshot();
|
||
// live = [followup, inject(reg B)] —— followup 之前的 steer/inject 被取代
|
||
expect(snap.content).toBe("new task\n\nreg B");
|
||
expect(snap.boardId).toBeUndefined(); // followup 无 boardId,且其前 steer 已不在 live
|
||
});
|
||
|
||
it("迁移 followup→steer:live 收缩为 steer(含)之后", () => {
|
||
const ci = softCi();
|
||
ci.followup("task1");
|
||
ci.inject("reg1");
|
||
ci.steer("board B", "b");
|
||
ci.inject("reg2");
|
||
const snap = ci.snapshot();
|
||
expect(snap.content).toBe("board B\n\nreg2");
|
||
expect(snap.boardId).toBe("b");
|
||
});
|
||
|
||
it("连续 steer:live 只含最后一次 steer(含)之后(每次 steer 刷新 pivot)", () => {
|
||
const ci = softCi();
|
||
ci.steer("first", "a");
|
||
ci.inject("r1");
|
||
ci.steer("second", "b");
|
||
ci.inject("r2");
|
||
const snap = ci.snapshot();
|
||
expect(snap.content).toBe("second\n\nr2");
|
||
expect(snap.boardId).toBe("b");
|
||
});
|
||
|
||
it("连续 followup:live 只含最后一次 followup(含)之后", () => {
|
||
const ci = softCi();
|
||
ci.followup("task1");
|
||
ci.followup("task2");
|
||
ci.inject("reg");
|
||
const snap = ci.snapshot();
|
||
expect(snap.content).toBe("task2\n\nreg");
|
||
});
|
||
|
||
it("snapshot 历史态:连续多次 snapshot 互不取代(append-only);replacesSnapshot 链指向最新前驱", () => {
|
||
const ci = softCi();
|
||
ci.inject("a");
|
||
ci.snapshot(); // snap-1: "a"
|
||
ci.inject("b");
|
||
ci.snapshot(); // snap-2: "a\n\nb"
|
||
ci.inject("c");
|
||
ci.snapshot(); // snap-3: "a\n\nb\n\nc"
|
||
const s = ci.followup("new");
|
||
expect(s.replacesSnapshot).toBe("snap-3");
|
||
});
|
||
|
||
it("clear(phase) 转移:仅删该 phase,live 可能重算(pivot 不受影响)", () => {
|
||
const ci = softCi();
|
||
ci.inject("old"); // 在 steer pivot 前
|
||
ci.steer("switch", "b");
|
||
ci.inject("new");
|
||
ci.clear("inject" as InjectionPhase);
|
||
// 删了 inject(old) + inject(new);剩 steer
|
||
const ctx = ci.deriveActiveContext();
|
||
expect(ctx.injections).toHaveLength(1);
|
||
expect(ctx.injections[0]!.phase).toBe("steer");
|
||
expect(ctx.active!.content).toBe("switch");
|
||
});
|
||
|
||
it("clear(phase=steer) 转移:删 steer 后 pivot 消失,剩余 inject 全部 live", () => {
|
||
const ci = softCi();
|
||
ci.inject("old");
|
||
ci.steer("switch", "b");
|
||
ci.inject("new");
|
||
ci.clear("steer" as InjectionPhase);
|
||
// 删了 steer → 无 pivot → 剩 [inject(old), inject(new)] 全 live
|
||
const snap = ci.snapshot();
|
||
expect(snap.content).toBe("old\n\nnew");
|
||
expect(snap.boardId).toBeUndefined();
|
||
});
|
||
|
||
it("clear() 全重置态:寄存器/快照/seq 全归零(不可达旧态残留)", () => {
|
||
const ci = softCi();
|
||
ci.inject("a");
|
||
ci.snapshot();
|
||
ci.steer("b", "x");
|
||
ci.snapshot();
|
||
ci.clear();
|
||
expect(ci.deriveActiveContext().injections).toHaveLength(0);
|
||
expect(ci.deriveActiveContext().active).toBeNull();
|
||
// seq 归零 → 新快照 snap-1
|
||
ci.inject("fresh");
|
||
ci.snapshot();
|
||
expect(ci.steer("s", "y").replacesSnapshot).toBe("snap-1");
|
||
});
|
||
|
||
it("不可达状态:无快照时 steer 的 replacesSnapshot 不可能指向非 undef", () => {
|
||
// 状态不变式:snapshotSeq=0 ∧ snapshots=[] ⟹ currentSnapshotId()=undef
|
||
const ci = softCi();
|
||
expect(ci.steer("a", "b").replacesSnapshot).toBeUndefined();
|
||
ci.inject("x");
|
||
expect(ci.steer("c", "d").replacesSnapshot).toBeUndefined(); // 仍无快照
|
||
});
|
||
|
||
it("重入态:sink 回调内再 inject 不崩溃(push 无迭代,顺序追加)", () => {
|
||
const calls: unknown[] = [];
|
||
let reentrant: ContextInjector | null = null;
|
||
const sink: InjectionSink = (_t, d) => {
|
||
calls.push(d);
|
||
// 首次回调时再注入一条(重入)
|
||
if (calls.length === 1 && reentrant) {
|
||
reentrant.inject("reentrant");
|
||
}
|
||
};
|
||
const ci = new ContextInjector({ appendEntry: sink, deepFreeze: false });
|
||
reentrant = ci;
|
||
ci.inject("first");
|
||
// first + reentrant 两条均下沉
|
||
expect(calls).toHaveLength(2);
|
||
expect((calls[0] as Injection).content).toBe("first");
|
||
expect((calls[1] as Injection).content).toBe("reentrant");
|
||
});
|
||
|
||
it("重入态:sink 回调内再 steer 也正常追加(更深重入)", () => {
|
||
const calls: unknown[] = [];
|
||
let reentrant: ContextInjector | null = null;
|
||
const sink: InjectionSink = (_t, d) => {
|
||
calls.push(d);
|
||
if (calls.length === 1 && reentrant) {
|
||
reentrant.steer("reentrant-steer", "board2");
|
||
}
|
||
};
|
||
const ci = new ContextInjector({ appendEntry: sink, deepFreeze: false });
|
||
reentrant = ci;
|
||
ci.steer("first-steer", "board1");
|
||
expect(calls).toHaveLength(2);
|
||
expect((calls[0] as Injection).boardId).toBe("board1");
|
||
expect((calls[1] as Injection).boardId).toBe("board2");
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// 5. 对抗 / Fuzz(Adversarial / Fuzz)—— 畸形 / 滥用 / 极端输入
|
||
// ============================================================================
|
||
|
||
describe("对抗 / Fuzz:畸形与滥用输入", () => {
|
||
it("null/undefined content → fail-closed 抛错(不静默吞)", () => {
|
||
const ci = new ContextInjector();
|
||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||
expect(() => ci.inject(null as any)).toThrow();
|
||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||
expect(() => ci.steer(undefined as any, "b")).toThrow();
|
||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||
expect(() => ci.followup(undefined as any)).toThrow();
|
||
});
|
||
|
||
it("number/object/array/boolean/symbol content → fail-closed 抛错", () => {
|
||
const ci = new ContextInjector();
|
||
for (const bad of [42, {}, [], true, Symbol("s")] as unknown[]) {
|
||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||
expect(() => ci.inject(bad as any)).toThrow();
|
||
}
|
||
});
|
||
|
||
it("循环引用对象作 content → 对象非 string → assertContent 抛错(断绝循环引用进 content)", () => {
|
||
const ci = new ContextInjector();
|
||
const obj: Record<string, unknown> = { self: null };
|
||
obj.self = obj; // 循环引用
|
||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||
expect(() => ci.inject(obj as any)).toThrow();
|
||
});
|
||
|
||
it("巨大 content(10MB)→ 接受且不截断(无长度门)", () => {
|
||
const ci = softCi();
|
||
const huge = "A".repeat(10 * 1024 * 1024);
|
||
const inj = ci.inject(huge);
|
||
expect(inj.content).toHaveLength(10 * 1024 * 1024);
|
||
});
|
||
|
||
it("boardId 不校验类型:steer 第二参数非 string 被原样存(契约未要求校验,文档化行为)", () => {
|
||
// boardId 无 fail-closed 门:非 string 原样落 Injection
|
||
const ci = softCi();
|
||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||
const inj = ci.steer("switch", 123 as any);
|
||
expect(inj.boardId).toBe(123);
|
||
});
|
||
|
||
it("负 seq / NaN seq / Infinity seq 传 toSessionEntry → 原样透传(序列化器不校验 seq)", () => {
|
||
const inj: Injection = { phase: "inject", content: "x", nextStep: true, nextTurn: false };
|
||
expect(toSessionEntry(inj, -5, 1000).seq).toBe(-5);
|
||
expect(Number.isNaN(toSessionEntry(inj, NaN, 1000).seq)).toBe(true);
|
||
expect(toSessionEntry(inj, Infinity, 1000).seq).toBe(Infinity);
|
||
});
|
||
|
||
it("toSessionEntry 传非法 injection 对象 → 原样放 data(不校验结构)", () => {
|
||
// toSessionEntry 是纯序列化器,不校验 data 形状
|
||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||
const entry = toSessionEntry({ wrong: true } as any, 1, 1000);
|
||
expect((entry.data as Record<string, unknown>).wrong).toBe(true);
|
||
});
|
||
|
||
it("INJECTION_PHASES 被篡改 push/pop/splice → 抛 TypeError(深冻结)", () => {
|
||
expect(() => (INJECTION_PHASES as unknown as string[]).push("evil")).toThrow(TypeError);
|
||
expect(() => (INJECTION_PHASES as unknown as string[]).pop()).toThrow(TypeError);
|
||
expect(() => (INJECTION_PHASES as unknown as string[]).splice(0, 1)).toThrow(TypeError);
|
||
});
|
||
|
||
it("clear(非法 phase) → assertPhase 抛错(fail-closed)", () => {
|
||
const ci = softCi();
|
||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||
expect(() => ci.clear("evil" as any)).toThrow();
|
||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||
expect(() => ci.clear("" as any)).toThrow();
|
||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||
expect(() => ci.clear("INJECT" as any)).toThrow(); // 大小写敏感
|
||
});
|
||
|
||
it("snapshot 连续调用 1000 次 → seq 单调递增到 1000(无累积异常)", () => {
|
||
const ci = softCi();
|
||
ci.inject("x");
|
||
for (let i = 0; i < 1000; i++) {
|
||
ci.snapshot();
|
||
}
|
||
// 末尾快照 id = snap-1000
|
||
expect(ci.steer("s", "b").replacesSnapshot).toBe("snap-1000");
|
||
});
|
||
|
||
it("大量 inject(10000) → live 全量拼接正确(性能/正确性 fuzz)", () => {
|
||
const ci = softCi();
|
||
const n = 10000;
|
||
for (let i = 0; i < n; i++) {
|
||
ci.inject(`r${i}`);
|
||
}
|
||
const snap = ci.snapshot();
|
||
const parts = snap.content.split("\n\n");
|
||
expect(parts).toHaveLength(n);
|
||
expect(parts[0]).toBe("r0");
|
||
expect(parts[n - 1]).toBe(`r${n - 1}`);
|
||
});
|
||
|
||
it("交替 steer/inject/followup 混合序列 → live 始终等于最后一次 steer/followup(含)之后", () => {
|
||
const ci = softCi();
|
||
ci.inject("i1");
|
||
ci.steer("s1", "b1");
|
||
ci.inject("i2");
|
||
ci.followup("f1");
|
||
ci.inject("i3");
|
||
ci.steer("s2", "b2");
|
||
ci.inject("i4");
|
||
ci.followup("f2");
|
||
ci.inject("i5");
|
||
const snap = ci.snapshot();
|
||
// 最后 pivot = followup("f2") → live = [f2, i5]
|
||
expect(snap.content).toBe("f2\n\ni5");
|
||
expect(snap.boardId).toBeUndefined();
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// 6. 元蜕变 / 不变式(Metamorphic / Invariant)—— 跨变换保持的性质
|
||
// ============================================================================
|
||
|
||
describe("元蜕变 / 不变式:跨变换保持的性质", () => {
|
||
it("蜕变:append 两次的 live snapshot === 独立实例等价重放(顺序合并等价,ts 不比)", () => {
|
||
// 路径 A:ci1 注入 a,b 后 snapshot
|
||
const ci1 = softCi();
|
||
ci1.inject("a");
|
||
ci1.inject("b");
|
||
const snapA = ci1.snapshot();
|
||
// 路径 B:ci2 注入同样 a,b 后 snapshot(独立实例,等价重放)
|
||
const ci2 = softCi();
|
||
ci2.inject("a");
|
||
ci2.inject("b");
|
||
const snapB = ci2.snapshot();
|
||
// 蜕变不变式:content 等价
|
||
expect(snapA.content).toBe(snapB.content);
|
||
expect(snapA.content).toBe("a\n\nb");
|
||
});
|
||
|
||
it("蜕变:replay 注入序列 → live 集合仅依赖最终序列,与中间快照时刻无关", () => {
|
||
// 路径 A:中途多次 snapshot
|
||
const ci1 = softCi();
|
||
ci1.inject("a");
|
||
ci1.snapshot();
|
||
ci1.inject("b");
|
||
ci1.snapshot();
|
||
ci1.inject("c");
|
||
// 路径 B:无中途 snapshot,同样注入序列
|
||
const ci2 = softCi();
|
||
ci2.inject("a");
|
||
ci2.inject("b");
|
||
ci2.inject("c");
|
||
// 最终 live content 等价(snapshot 时刻不影响 live 计算)
|
||
expect(ci1.snapshot().content).toBe(ci2.snapshot().content);
|
||
expect(ci1.snapshot().content).toBe("a\n\nb\n\nc");
|
||
});
|
||
|
||
it("不变式:freeze→篡改任意 readonly 字段均抛 TypeError(deepFreeze 递归)", () => {
|
||
const ci = new ContextInjector(); // deepFreeze 默认 true
|
||
const inj = ci.inject("frozen");
|
||
expect(() => {
|
||
(inj as Mutable<Injection>).content = "tampered";
|
||
}).toThrow(TypeError);
|
||
expect(() => {
|
||
(inj as Mutable<Injection>).phase = "steer";
|
||
}).toThrow(TypeError);
|
||
expect(() => {
|
||
(inj as Mutable<Injection>).nextStep = false;
|
||
}).toThrow(TypeError);
|
||
expect(() => {
|
||
(inj as Mutable<Injection>).nextTurn = true;
|
||
}).toThrow(TypeError);
|
||
expect(() => {
|
||
(inj as Mutable<Injection>).replacesSnapshot = "fake";
|
||
}).toThrow(TypeError);
|
||
|
||
const snap = ci.snapshot();
|
||
expect(() => {
|
||
(snap as Mutable<RuntimeSnapshot>).content = "tampered";
|
||
}).toThrow(TypeError);
|
||
expect(() => {
|
||
(snap as Mutable<RuntimeSnapshot>).boardId = "tampered";
|
||
}).toThrow(TypeError);
|
||
expect(() => {
|
||
(snap as Mutable<RuntimeSnapshot>).ts = 0;
|
||
}).toThrow(TypeError);
|
||
|
||
const ctx = ci.deriveActiveContext();
|
||
expect(() => {
|
||
(ctx as Mutable<ActiveContext>).active = null;
|
||
}).toThrow(TypeError);
|
||
expect(() => {
|
||
(ctx as Mutable<ActiveContext>).injections = [];
|
||
}).toThrow(TypeError);
|
||
// injections 数组元素仍冻结
|
||
expect(() => {
|
||
(ctx.injections[0] as Mutable<Injection>).content = "tampered";
|
||
}).toThrow(TypeError);
|
||
// injections 数组本身冻结(不可 push)
|
||
expect(() => {
|
||
(ctx.injections as Injection[]).push(inj);
|
||
}).toThrow(TypeError);
|
||
});
|
||
|
||
it("不变式:deepFreeze=false 时不冻结(可变,不抛 TypeError)", () => {
|
||
const ci = new ContextInjector({ deepFreeze: false });
|
||
const inj = ci.inject("mutable");
|
||
expect(() => {
|
||
(inj as Mutable<Injection>).content = "changed";
|
||
}).not.toThrow();
|
||
expect(inj.content).toBe("changed");
|
||
});
|
||
|
||
it("不变式:deriveActiveContext 返回的 injections 是副本(改原寄存器不影响快照视图)", () => {
|
||
const ci = new ContextInjector({ deepFreeze: false });
|
||
ci.inject("a");
|
||
const ctx = ci.deriveActiveContext();
|
||
ci.inject("b"); // 改原寄存器
|
||
expect(ctx.injections).toHaveLength(1); // 副本不受影响
|
||
});
|
||
|
||
it("不变式:waterfall 不短路——inject 不取代、不绑 turn(被动补料,多 inject 累积无取代)", () => {
|
||
// inject 是被动补料:不产生 replacesSnapshot,不绑 turn
|
||
const ci = softCi();
|
||
ci.inject("a");
|
||
ci.inject("b");
|
||
ci.inject("c");
|
||
// 多次 inject 后无 steer/followup → live 仍含全部(无短路取代)
|
||
expect(ci.snapshot().content).toBe("a\n\nb\n\nc");
|
||
expect(ci.deriveActiveContext().active!.content).toBe("c");
|
||
});
|
||
|
||
it("不变式:单调 deny——deriveActiveContext.active 永远 === live 最新一条或 null", () => {
|
||
const ci = softCi();
|
||
expect(ci.deriveActiveContext().active).toBeNull(); // 空 → null
|
||
ci.inject("a");
|
||
expect(ci.deriveActiveContext().active!.content).toBe("a");
|
||
ci.steer("switch", "b");
|
||
expect(ci.deriveActiveContext().active!.content).toBe("switch"); // steer 是 live 最新
|
||
ci.inject("after");
|
||
expect(ci.deriveActiveContext().active!.content).toBe("after");
|
||
ci.followup("newtask");
|
||
expect(ci.deriveActiveContext().active!.content).toBe("newtask");
|
||
});
|
||
|
||
it("不变式:fail-closed unusable——空/空白 content 拒绝注册(不入寄存器表,无半注册)", () => {
|
||
const ci = softCi();
|
||
const before = ci.deriveActiveContext().injections.length;
|
||
expect(() => ci.inject("")).toThrow();
|
||
expect(() => ci.steer(" ")).toThrow();
|
||
expect(() => ci.followup("\t")).toThrow();
|
||
// 抛错后寄存器表不变(无半注册)
|
||
expect(ci.deriveActiveContext().injections.length).toBe(before);
|
||
});
|
||
|
||
it("不变式:fail-closed 拒绝零宽 Default_Ignorable(U+200B/ZWJ)——trim() 不剥这些,须手动剥", () => {
|
||
const ci = softCi();
|
||
// U+200B 不被 String.prototype.trim() 剥离(语言事实)→ 须手动剥
|
||
const zwsp = ""; // U+200B
|
||
expect(zwsp.trim().length).toBe(1); // 证实 trim 不剥(故需 INVISIBLE_CHARS)
|
||
expect(() => ci.inject(zwsp)).toThrow(); // 已修复:零宽被剥 → 判空 → 抛
|
||
expect(() => ci.steer(zwsp, "b")).toThrow();
|
||
expect(() => ci.followup(zwsp)).toThrow();
|
||
// ZWJ (U+200D) 同理
|
||
const zwj = "";
|
||
expect(zwj.trim().length).toBe(1);
|
||
expect(() => ci.inject(zwj)).toThrow();
|
||
// BOM (U+FEFF) —— 注意:U+FEFF 属 ECMAScript WhiteSpace 故 trim() 会剥,
|
||
// 但 assertContent 的 INVISIBLE_CHARS 兜底也剥,纯 BOM 仍判空 → fail-closed 抛
|
||
const bom = "";
|
||
expect(() => ci.inject(bom)).toThrow();
|
||
// 混合:零宽 + 普通空格 → 仍判空抛错
|
||
expect(() => ci.inject(" ")).toThrow();
|
||
});
|
||
|
||
it("不变式:可见但含零宽的 content 仍接受(零宽不作为唯一判空依据,只剥后判)", () => {
|
||
const ci = softCi();
|
||
const mixed = "regmap"; // 含 U+200B 但有可见字符
|
||
const inj = ci.inject(mixed);
|
||
expect(inj.content).toBe(mixed);
|
||
});
|
||
|
||
it("不变式:appendEntry 下沉 = 寄存器表全量(每条注入经 sink 落库一次,type 恒定)", () => {
|
||
const { sink, calls } = makeSink();
|
||
const ci = new ContextInjector({ appendEntry: sink, deepFreeze: false });
|
||
ci.inject("a");
|
||
ci.steer("b", "boardB");
|
||
ci.followup("c");
|
||
expect(calls).toHaveLength(3);
|
||
expect(calls.every((c) => c.type === CONTEXT_INJECTION_TYPE)).toBe(true);
|
||
expect((calls[0]!.data as Injection).content).toBe("a");
|
||
expect((calls[1]!.data as Injection).boardId).toBe("boardB");
|
||
expect((calls[2]!.data as Injection).phase).toBe("followup");
|
||
// sink 数据 === 寄存器表(同一引用,append 顺序一致)
|
||
const ctx = ci.deriveActiveContext();
|
||
expect(ctx.injections.map((i) => i.content)).toEqual(
|
||
calls.map((c) => (c.data as Injection).content),
|
||
);
|
||
});
|
||
|
||
it("不变式:无 appendEntry sink 时不抛错(纯内存模式)", () => {
|
||
const ci = softCi(); // 无 appendEntry
|
||
expect(() => ci.inject("a")).not.toThrow();
|
||
expect(() => ci.snapshot()).not.toThrow();
|
||
expect(() => ci.deriveActiveContext()).not.toThrow();
|
||
});
|
||
|
||
it("不变式:sink 收到的 Injection 与 register 返回值同一引用(不复制)", () => {
|
||
const { sink, calls } = makeSink();
|
||
const ci = new ContextInjector({ appendEntry: sink, deepFreeze: false });
|
||
const ret = ci.inject("same-ref");
|
||
expect(calls[0]!.data).toBe(ret); // 同一引用
|
||
});
|
||
|
||
it("不变式:toSessionEntry 产出 PbaSessionEntry 形状(type/data/seq/ts 四字段)", () => {
|
||
const inj: Injection = {
|
||
phase: "steer",
|
||
content: "switch",
|
||
boardId: "s100",
|
||
nextStep: true,
|
||
nextTurn: false,
|
||
};
|
||
const entry = toSessionEntry(inj, 7, 1730000000000);
|
||
expect(entry).toMatchObject({
|
||
type: CONTEXT_INJECTION_TYPE,
|
||
data: inj,
|
||
seq: 7,
|
||
ts: 1730000000000,
|
||
});
|
||
// 结构守恒:恰好四键
|
||
expect(Object.keys(entry).sort()).toEqual(["data", "seq", "ts", "type"]);
|
||
});
|
||
|
||
it("不变式:toSessionEntry 默认 ts = Date.now()(正数 epoch ms)", () => {
|
||
const inj: Injection = { phase: "inject", content: "x", nextStep: true, nextTurn: false };
|
||
const before = Date.now();
|
||
const entry = toSessionEntry(inj, 1);
|
||
const after = Date.now();
|
||
expect(entry.ts).toBeGreaterThanOrEqual(before);
|
||
expect(entry.ts).toBeLessThanOrEqual(after);
|
||
});
|
||
|
||
it("不变式:toSessionEntry 是纯函数(无副作用,多次调用等价)", () => {
|
||
const inj: Injection = { phase: "inject", content: "x", nextStep: true, nextTurn: false };
|
||
const e1 = toSessionEntry(inj, 1, 1000);
|
||
const e2 = toSessionEntry(inj, 1, 1000);
|
||
expect(e1.type).toBe(e2.type);
|
||
expect(e1.seq).toBe(e2.seq);
|
||
expect(e1.ts).toBe(e2.ts);
|
||
expect(e1.data).toBe(e2.data); // 同引用(data 不复制)
|
||
});
|
||
|
||
it("不变式:toSessionEntry type 恒为 CONTEXT_INJECTION_TYPE('context-injection')", () => {
|
||
const inj: Injection = { phase: "inject", content: "x", nextStep: true, nextTurn: false };
|
||
for (const seq of [0, 1, 99, 1_000_000]) {
|
||
expect(toSessionEntry(inj, seq, 1000).type).toBe(CONTEXT_INJECTION_TYPE);
|
||
}
|
||
});
|
||
|
||
it("不变式:INJECTION_PHASES 恒为 ['inject','steer','followup'](顺序固定)", () => {
|
||
expect([...INJECTION_PHASES]).toEqual(["inject", "steer", "followup"]);
|
||
});
|
||
|
||
it("不变式:CONTEXT_INJECTION_TYPE 恒为 'context-injection'", () => {
|
||
expect(CONTEXT_INJECTION_TYPE).toBe("context-injection");
|
||
expect(typeof CONTEXT_INJECTION_TYPE).toBe("string");
|
||
});
|
||
|
||
it("不变式:snapshot 取代更早快照——live 永远由最新 steer/followup 决定(更早被取代)", () => {
|
||
const ci = softCi();
|
||
ci.steer("first board", "b1");
|
||
ci.inject("r1");
|
||
ci.steer("second board", "b2");
|
||
ci.inject("r2");
|
||
const snap = ci.snapshot();
|
||
// 更早的 steer("first board") 被取代 → live 不含
|
||
expect(snap.content).not.toContain("first board");
|
||
expect(snap.content).toContain("second board");
|
||
expect(snap.boardId).toBe("b2");
|
||
});
|
||
|
||
it("不变式:boardId 在 live 中取最新(steer 之后的 inject 不覆盖 boardId)", () => {
|
||
const ci = softCi();
|
||
ci.steer("board A", "a");
|
||
ci.inject("reg after A"); // inject 无 boardId,不覆盖
|
||
const snap = ci.snapshot();
|
||
expect(snap.boardId).toBe("a");
|
||
ci.steer("board B", "b");
|
||
expect(ci.snapshot().boardId).toBe("b"); // 最新 steer 的 boardId
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// 7. 变异测试(Mutation Testing)—— 5 个植入 bug(A-E)的逻辑副本
|
||
//
|
||
// 机制:
|
||
// - BuggyCI 是 ContextInjector 的忠实内联副本,按 `bug` 选择植入一处缺陷。
|
||
// - 默认(无 MUTATION_BUG env)整个 describe 块 skipIf 跳过 → 文件全绿。
|
||
// - 设 MUTATION_BUG=A/B/C/D/E 时,仅对应 bug 的 it 运行,断言【正确契约行为】→
|
||
// 副本因 bug 产出错误结果 → 该 it FAIL → bug 被杀。
|
||
//
|
||
// 植入 bug 清单(每个 bug + 杀它的测试):
|
||
// A. computeLiveInjections slice(pivot+1):漏掉 pivot 的 steer/followup → live 缺该条。
|
||
// 杀它的测试:steer 后 snapshot content 须含 steer 文本(live 应含 steer)。
|
||
// B. snapshot content join 用 "\n" 非 "\n\n":分隔符变窄。
|
||
// 杀它的测试:双 inject snapshot content === "a\n\nb"(严格相等)。
|
||
// C. assertContent 不 trim:纯空白 content 被接受。
|
||
// 杀它的测试:纯空白 followup 须抛错(fail-closed)。
|
||
// D. clear() 漏 reset snapshotSeq:清空后新快照 id 错位。
|
||
// 杀它的测试:clear→snapshot→steer 的 replacesSnapshot 须为 "snap-1"。
|
||
// E. deriveActiveContext active 取 live[0] 而非 live[last]:active 指向最旧。
|
||
// 杀它的测试:多 inject 后 active.content === 最新一条(非最旧)。
|
||
// ============================================================================
|
||
|
||
const MUTATION = (process.env.MUTATION_BUG ?? "") as "" | "A" | "B" | "C" | "D" | "E";
|
||
|
||
type BugId = "A" | "B" | "C" | "D" | "E";
|
||
|
||
const SNAP_PREFIX = "snap-";
|
||
|
||
const INVISIBLE_CHARS_COPY = /[-]/g;
|
||
|
||
/** localDeepFreeze:deepFreeze 的忠实副本(递归冻结)。 */
|
||
function localDeepFreeze<T>(value: T): T {
|
||
if (value === null || typeof value !== "object") return value;
|
||
if (Array.isArray(value)) {
|
||
for (const v of value) localDeepFreeze(v);
|
||
} else {
|
||
for (const v of Object.values(value as Record<string, unknown>)) localDeepFreeze(v);
|
||
}
|
||
Object.freeze(value);
|
||
return value;
|
||
}
|
||
|
||
/**
|
||
* liveOf:computeLiveInjections 的忠实副本。
|
||
* bug=A 时 slice(pivot+1) 漏掉 pivot 的 steer/followup。
|
||
*/
|
||
function liveOf(injections: Injection[], bug: BugId): Injection[] {
|
||
let pivot = -1;
|
||
for (let i = injections.length - 1; i >= 0; i--) {
|
||
const phase = injections[i]!.phase;
|
||
if (phase === "steer" || phase === "followup") {
|
||
pivot = i;
|
||
break;
|
||
}
|
||
}
|
||
if (pivot === -1) return [...injections];
|
||
return bug === "A" ? injections.slice(pivot + 1) : injections.slice(pivot);
|
||
}
|
||
|
||
/** BuggyCI:ContextInjector 内联副本,按 bug 植入一处缺陷。 */
|
||
class BuggyCI {
|
||
private appendEntry: InjectionSink | undefined;
|
||
private useFreeze: boolean;
|
||
private injections: Injection[] = [];
|
||
private snapshots: Array<{ id: string; content: string; boardId?: string; ts: number }> = [];
|
||
private snapshotSeq = 0;
|
||
private bug: BugId;
|
||
|
||
constructor(bug: BugId, opts: { appendEntry?: InjectionSink; deepFreeze?: boolean } = {}) {
|
||
this.bug = bug;
|
||
this.appendEntry = opts.appendEntry;
|
||
this.useFreeze = opts.deepFreeze ?? true;
|
||
}
|
||
|
||
private assertContent(content: string): void {
|
||
// BUG C: 不 trim(也不剥零宽)→ 纯空白被接受
|
||
if (this.bug === "C") {
|
||
if (typeof content !== "string" || content.length === 0) {
|
||
throw new Error("bad content");
|
||
}
|
||
return;
|
||
}
|
||
// 忠实副本:剥零宽 + trim(与真实一致)
|
||
if (typeof content !== "string" || content.replace(INVISIBLE_CHARS_COPY, "").trim().length === 0) {
|
||
throw new Error("bad content");
|
||
}
|
||
}
|
||
|
||
private currentSnapshotId(): string | undefined {
|
||
return this.snapshots.length > 0 ? this.snapshots[this.snapshots.length - 1]!.id : undefined;
|
||
}
|
||
|
||
private register(p: {
|
||
phase: InjectionPhase;
|
||
content: string;
|
||
boardId?: string;
|
||
nextStep: boolean;
|
||
nextTurn: boolean;
|
||
replacesSnapshot?: string;
|
||
}): Injection {
|
||
const inj: Injection = {
|
||
phase: p.phase,
|
||
content: p.content,
|
||
boardId: p.boardId,
|
||
nextStep: p.nextStep,
|
||
nextTurn: p.nextTurn,
|
||
replacesSnapshot: p.replacesSnapshot,
|
||
};
|
||
const frozen = this.useFreeze ? (localDeepFreeze(inj) as Injection) : inj;
|
||
this.injections.push(frozen);
|
||
if (this.appendEntry) this.appendEntry(CONTEXT_INJECTION_TYPE, frozen);
|
||
return frozen;
|
||
}
|
||
|
||
inject(content: string): Injection {
|
||
this.assertContent(content);
|
||
return this.register({ phase: "inject", content, nextStep: true, nextTurn: false });
|
||
}
|
||
|
||
steer(content: string, boardId?: string): Injection {
|
||
this.assertContent(content);
|
||
return this.register({
|
||
phase: "steer",
|
||
content,
|
||
boardId,
|
||
nextStep: true,
|
||
nextTurn: false,
|
||
replacesSnapshot: this.currentSnapshotId(),
|
||
});
|
||
}
|
||
|
||
followup(content: string): Injection {
|
||
this.assertContent(content);
|
||
return this.register({
|
||
phase: "followup",
|
||
content,
|
||
nextStep: false,
|
||
nextTurn: true,
|
||
replacesSnapshot: this.currentSnapshotId(),
|
||
});
|
||
}
|
||
|
||
snapshot(): RuntimeSnapshot {
|
||
const live = liveOf(this.injections, this.bug);
|
||
// BUG B: join 用 "\n" 非 "\n\n"
|
||
const content =
|
||
this.bug === "B" ? live.map((i) => i.content).join("\n") : live.map((i) => i.content).join("\n\n");
|
||
let boardId: string | undefined;
|
||
for (let i = live.length - 1; i >= 0; i--) {
|
||
if (live[i]!.boardId !== undefined) {
|
||
boardId = live[i]!.boardId;
|
||
break;
|
||
}
|
||
}
|
||
this.snapshotSeq += 1;
|
||
const internal = { id: `${SNAP_PREFIX}${this.snapshotSeq}`, content, boardId, ts: Date.now() };
|
||
this.snapshots.push(internal);
|
||
const ext: RuntimeSnapshot = { content: internal.content, boardId: internal.boardId, ts: internal.ts };
|
||
return this.useFreeze ? (localDeepFreeze(ext) as RuntimeSnapshot) : ext;
|
||
}
|
||
|
||
deriveActiveContext(): ActiveContext {
|
||
const live = liveOf(this.injections, this.bug);
|
||
// BUG E: active 取 live[0] 而非 live[last]
|
||
const active =
|
||
live.length > 0
|
||
? this.bug === "E"
|
||
? (live[0] as Injection)
|
||
: (live[live.length - 1] as Injection)
|
||
: null;
|
||
const view: ActiveContext = {
|
||
injections: this.useFreeze
|
||
? (localDeepFreeze([...this.injections]) as ReadonlyArray<Injection>)
|
||
: [...this.injections],
|
||
active,
|
||
};
|
||
return this.useFreeze ? (localDeepFreeze(view) as ActiveContext) : view;
|
||
}
|
||
|
||
clear(phase?: InjectionPhase): void {
|
||
if (phase !== undefined) {
|
||
for (let i = this.injections.length - 1; i >= 0; i--) {
|
||
if (this.injections[i]!.phase === phase) this.injections.splice(i, 1);
|
||
}
|
||
return;
|
||
}
|
||
this.injections.length = 0;
|
||
this.snapshots.length = 0;
|
||
// BUG D: 漏 reset snapshotSeq
|
||
if (this.bug !== "D") this.snapshotSeq = 0;
|
||
}
|
||
}
|
||
|
||
describe.skipIf(!MUTATION)("变异测试:植入 bug 副本(MUTATION_BUG=A/B/C/D/E 触发)", () => {
|
||
it.skipIf(MUTATION !== "A")(
|
||
"BUG A 被 killed:steer 后 snapshot content 须含 steer 文本(副本 slice(pivot+1) 漏 pivot → 缺 steer 文本 → toContain 失败)",
|
||
() => {
|
||
const ci = new BuggyCI("A", { deepFreeze: false });
|
||
ci.inject("old reg");
|
||
ci.steer("switch board", "b");
|
||
ci.inject("new reg");
|
||
const snap = ci.snapshot();
|
||
// 真实:live=[steer,inject] → "switch board\n\nnew reg"
|
||
// 副本 A:slice(pivot+1) → [inject] → "new reg"(缺 steer 文本)
|
||
expect(snap.content).toContain("switch board");
|
||
},
|
||
);
|
||
|
||
it.skipIf(MUTATION !== "B")(
|
||
'BUG B 被 killed:双 inject snapshot content === "a\\n\\nb"(副本 join 用 "\\n" → 得 "a\\nb" → 严格相等失败)',
|
||
() => {
|
||
const ci = new BuggyCI("B", { deepFreeze: false });
|
||
ci.inject("a");
|
||
ci.inject("b");
|
||
const snap = ci.snapshot();
|
||
// 真实:"a\n\nb";副本 B:"a\nb"
|
||
expect(snap.content).toBe("a\n\nb");
|
||
},
|
||
);
|
||
|
||
it.skipIf(MUTATION !== "C")(
|
||
"BUG C 被 killed:纯空白 followup 须抛错(副本不 trim → 不抛 → toThrow 失败)",
|
||
() => {
|
||
const ci = new BuggyCI("C", { deepFreeze: false });
|
||
// 真实:trim 归零 → 抛;副本 C:length>0 不抛
|
||
expect(() => ci.followup(" ")).toThrow();
|
||
},
|
||
);
|
||
|
||
it.skipIf(MUTATION !== "D")(
|
||
'BUG D 被 killed:clear() 后 snapshot→steer 的 replacesSnapshot 须为 "snap-1"(副本漏 reset seq → 得 "snap-2" → 严格相等失败)',
|
||
() => {
|
||
const ci = new BuggyCI("D", { deepFreeze: false });
|
||
ci.inject("x");
|
||
ci.snapshot(); // seq→1, id snap-1
|
||
ci.clear(); // 真实 reset seq→0;副本 D 漏 reset(seq 保持 1)
|
||
ci.snapshot(); // 真实 id snap-1;副本 D id snap-2
|
||
const s = ci.steer("again", "b");
|
||
// 真实:snap-1;副本 D:snap-2
|
||
expect(s.replacesSnapshot).toBe("snap-1");
|
||
},
|
||
);
|
||
|
||
it.skipIf(MUTATION !== "E")(
|
||
"BUG E 被 killed:多 inject 后 deriveActiveContext.active.content === 最新一条(副本取 live[0] → 得最旧 → 严格相等失败)",
|
||
() => {
|
||
const ci = new BuggyCI("E", { deepFreeze: false });
|
||
ci.inject("oldest");
|
||
ci.inject("middle");
|
||
ci.inject("newest");
|
||
const ctx = ci.deriveActiveContext();
|
||
// 真实:active = live[last] = "newest";副本 E:active = live[0] = "oldest"
|
||
expect(ctx.active!.content).toBe("newest");
|
||
},
|
||
);
|
||
});
|