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>
1054 lines
46 KiB
TypeScript
1054 lines
46 KiB
TypeScript
/**
|
||
* pba-session 完整测试套件 —— T06 事件溯源底座。
|
||
*
|
||
* 被测对象:src/core/pba-session.ts 的命名导出
|
||
* - PbaSession(class:append / deriveMessages / getEntries /
|
||
* replayFromEntries / assertModelVisibleLogged)
|
||
* - MODEL_VISIBLE_TYPES(冻结常量)
|
||
* - 类型 PbaSessionEntry / DerivedMessage(仅 type-only import)
|
||
*
|
||
* 纯逻辑模块,零 pi 运行时依赖:mock 注入 appendEntry sink,离线可单测。
|
||
*
|
||
* 多测试方法论(每个 describe 块标题标注方法论名):
|
||
* - 等价类划分(有效/无效/边界类)
|
||
* - 边界值分析(空、单元素、min、off-by-one、cache 边界)
|
||
* - 决策表(组合输入 → 期望,覆盖全分支)
|
||
* - 状态转换(seq 回滚 / reentrant guard / cache 生命周期 / replay seq 模式)
|
||
* - 变异测试(5 个 seeded bug 内联副本 + it.fails 杀手 + 真实代码 kill-by-test 标注)
|
||
* - 对抗/fuzz(null / undefined / NaN / 巨大 / 循环引用 / 负 seq / 重入)
|
||
* - 元蜕变/不变式(append²=replay 等价;freeze→篡改抛 TypeError;单调 seq;
|
||
* waterfall 短路;fail-closed unusable=拒)
|
||
*
|
||
* 门:
|
||
* 1. `npx vitest run tests/pba-session.test.ts` —— 真实代码全绿
|
||
* (it.fails 杀手在 mutant 副本上断言失败 → 计为 pass = bug 被杀)。
|
||
* 2. 每个 seeded bug:mutant 副本上杀手 body 失败(it.fails 通过)= bug 被杀。
|
||
* 若把对应 bug 打进真实 src/core/pba-session.ts,标注的【真实代码测试】变红。
|
||
*/
|
||
|
||
import { describe, it, expect } from "vitest";
|
||
import {
|
||
PbaSession,
|
||
MODEL_VISIBLE_TYPES,
|
||
type PbaSessionEntry,
|
||
type DerivedMessage,
|
||
} from "../src/core/pba-session.js";
|
||
|
||
// ============================================================================
|
||
// 公共夹具
|
||
// ============================================================================
|
||
|
||
/** 记录型 appendEntry sink:捕获下沉参数,可断言。 */
|
||
function recordingSink(): {
|
||
sink: (type: string, data: unknown) => void;
|
||
calls: Array<{ type: string; data: unknown }>;
|
||
} {
|
||
const calls: Array<{ type: string; data: unknown }> = [];
|
||
return { sink: (type, data) => calls.push({ type, data }), calls };
|
||
}
|
||
|
||
/** no-op sink。 */
|
||
const noopSink = (): void => {};
|
||
|
||
/** 抛错型 sink(测 seq 回滚 / fail-closed 路径)。 */
|
||
function throwingSink(msg = "boom"): (type: string, data: unknown) => void {
|
||
return () => {
|
||
throw new Error(msg);
|
||
};
|
||
}
|
||
|
||
/** 首调抛、次调成功的 sink(测 seq 回滚后续写)。 */
|
||
function firstFailSink(msg = "first-fail"): {
|
||
sink: (type: string, data: unknown) => void;
|
||
} {
|
||
let first = true;
|
||
return {
|
||
sink: () => {
|
||
if (first) {
|
||
first = false;
|
||
throw new Error(msg);
|
||
}
|
||
},
|
||
};
|
||
}
|
||
|
||
// 事件构造器
|
||
const userMsg = (content: string) => ({ type: "user-message", data: { role: "user" as const, content } });
|
||
const assistantMsg = (content: string) => ({
|
||
type: "assistant-message",
|
||
data: { role: "assistant" as const, content },
|
||
});
|
||
const toolCall = (name: string, args: unknown = {}) => ({ type: "tool-call", data: { name, args } });
|
||
const toolResult = (name: string, result: unknown) => ({ type: "tool-result", data: { name, result } });
|
||
|
||
// ============================================================================
|
||
// 变异测试基础设施 —— 忠实内联副本(单行 bug 注入)
|
||
// ----------------------------------------------------------------------------
|
||
// MutantPbaSession 是 src/core/pba-session.ts 的逐行忠实副本,仅通过 constructor
|
||
// 的 `bug` 选项在【恰好一处】注入 seeded bug。每个 bug 配一个 it.fails 杀手:
|
||
// 杀手断言【真实正确行为】,在 mutant 副本上断言失败 → it.fails 通过 = bug 被杀。
|
||
// 若有人把 mutant 修回真实行为,it.fails 会变红(敏感度证)。
|
||
// loadEntries 在真实类里是 private(TS 跨实例可访问),副本里直接内联等价逻辑。
|
||
// ============================================================================
|
||
|
||
const LOSSLESS_TAG = "__pbaType";
|
||
|
||
function snapV(value: unknown, seen: WeakSet<object>): unknown {
|
||
if (value === null || typeof value !== "object") return value;
|
||
const ref = value as object;
|
||
if (seen.has(ref)) {
|
||
throw new Error("PbaSession: cannot snapshot cyclic object (lossless-JSON invariant)");
|
||
}
|
||
seen.add(ref);
|
||
if (value instanceof Date) return { [LOSSLESS_TAG]: "Date", value: value.toISOString() };
|
||
if (value instanceof Map) {
|
||
const entries = [...value.entries()].map(([k, v]) => [snapV(k, seen), snapV(v, seen)]);
|
||
return { [LOSSLESS_TAG]: "Map", value: entries };
|
||
}
|
||
if (value instanceof Set) {
|
||
return { [LOSSLESS_TAG]: "Set", value: [...value].map((v) => snapV(v, seen)) };
|
||
}
|
||
if (Array.isArray(value)) return value.map((v) => snapV(v, seen));
|
||
const out: Record<string, unknown> = {};
|
||
for (const [k, v] of Object.entries(value)) out[k] = snapV(v, seen);
|
||
return out;
|
||
}
|
||
|
||
function freezeM<T>(value: T): T {
|
||
if (value === null || typeof value !== "object") return value;
|
||
if (Array.isArray(value)) for (const v of value) freezeM(v);
|
||
else for (const v of Object.values(value as Record<string, unknown>)) freezeM(v);
|
||
Object.freeze(value);
|
||
return value;
|
||
}
|
||
|
||
function projectMsg(entry: { type: string; data: unknown }): DerivedMessage | null {
|
||
const data = (entry.data ?? null) as Record<string, unknown> | null;
|
||
switch (entry.type) {
|
||
case "user-message":
|
||
return { role: "user", content: data?.content ?? "" };
|
||
case "assistant-message":
|
||
return { role: "assistant", content: data?.content ?? "" };
|
||
case "tool-call":
|
||
return {
|
||
role: "assistant",
|
||
content: null,
|
||
toolCalls: [{ name: String(data?.name ?? ""), args: data?.args ?? null }],
|
||
};
|
||
case "tool-result":
|
||
return { role: "tool", name: String(data?.name ?? ""), content: data?.result ?? null };
|
||
default:
|
||
return null;
|
||
}
|
||
}
|
||
|
||
type Bug =
|
||
| "none"
|
||
| "no-rollback" // M1: 下沉失败时漏 this.seq -= 1
|
||
| "no-cache-invalidate" // M2: append 后漏 this.messagesCache = null
|
||
| "seq-lt" // M3: replay seq 校验 !== → <(放行前向缺口)
|
||
| "assert-inverted" // M4: assertModelVisibleLogged 条件取反(已 logged 反而抛)
|
||
| "no-reentrant-guard"; // M5: 漏 reentrant guard(appending 不生效)
|
||
|
||
interface MutantEntry {
|
||
readonly type: string;
|
||
readonly data: unknown;
|
||
readonly seq: number;
|
||
readonly ts: number;
|
||
}
|
||
|
||
class MutantPbaSession {
|
||
private appendEntry: (type: string, data: unknown) => void;
|
||
private readonly useFreeze: boolean;
|
||
private readonly bug: Bug;
|
||
private seq = 0;
|
||
private readonly log: MutantEntry[] = [];
|
||
private readonly loggedTypes = new Set<string>();
|
||
private cache: ReadonlyArray<unknown> | null = null;
|
||
private appending = false;
|
||
|
||
constructor(opts: { appendEntry: (type: string, data: unknown) => void; deepFreeze?: boolean; bug: Bug }) {
|
||
this.appendEntry = opts.appendEntry;
|
||
this.useFreeze = opts.deepFreeze ?? true;
|
||
this.bug = opts.bug;
|
||
}
|
||
|
||
append(event: { type: string; data: unknown }): void {
|
||
// BUG M5 (no-reentrant-guard): 跳过 reentrant guard
|
||
if (this.bug !== "no-reentrant-guard" && this.appending) {
|
||
throw new Error("PbaSession: reentrant append detected");
|
||
}
|
||
this.appending = true;
|
||
try {
|
||
const snap = snapV(event.data, new WeakSet<object>());
|
||
const stored = this.useFreeze ? freezeM(snap) : snap;
|
||
this.seq += 1;
|
||
const entry: MutantEntry = { type: event.type, data: stored, seq: this.seq, ts: Date.now() };
|
||
if (this.useFreeze) Object.freeze(entry);
|
||
try {
|
||
this.appendEntry(event.type, stored);
|
||
} catch (err) {
|
||
// BUG M1 (no-rollback): 漏 seq 回滚
|
||
if (this.bug !== "no-rollback") this.seq -= 1;
|
||
throw err;
|
||
}
|
||
this.log.push(entry);
|
||
this.loggedTypes.add(event.type);
|
||
// BUG M2 (no-cache-invalidate): 漏缓存失效
|
||
if (this.bug !== "no-cache-invalidate") this.cache = null;
|
||
} finally {
|
||
this.appending = false;
|
||
}
|
||
}
|
||
|
||
deriveMessages(): unknown[] {
|
||
if (this.cache !== null) return this.cache as unknown[];
|
||
const messages: DerivedMessage[] = [];
|
||
for (const entry of this.log) {
|
||
const m = projectMsg(entry);
|
||
if (m) messages.push(m);
|
||
}
|
||
const out = this.useFreeze ? (freezeM(messages) as unknown[]) : (messages as unknown[]);
|
||
this.cache = out;
|
||
return out;
|
||
}
|
||
|
||
getEntries(): readonly MutantEntry[] {
|
||
return this.log;
|
||
}
|
||
|
||
replayFromEntries(entries: ReadonlyArray<{ type: string; data: unknown; seq?: number }>): MutantPbaSession {
|
||
const next = new MutantPbaSession({ appendEntry: this.appendEntry, deepFreeze: this.useFreeze, bug: this.bug });
|
||
this.loadEntriesInto(next, entries);
|
||
return next;
|
||
}
|
||
|
||
private loadEntriesInto(
|
||
target: MutantPbaSession,
|
||
entries: ReadonlyArray<{ type: string; data: unknown; seq?: number }>,
|
||
): void {
|
||
let lastSeq: number | null = null;
|
||
const loaded: MutantEntry[] = [];
|
||
for (let i = 0; i < entries.length; i++) {
|
||
const e = entries[i];
|
||
if (!e || typeof e.type !== "string") {
|
||
throw new Error(`PbaSession: replay entry[${i}] missing string type`);
|
||
}
|
||
let seq: number;
|
||
if (typeof e.seq === "number") {
|
||
seq = e.seq;
|
||
if (!(seq >= 1)) {
|
||
throw new Error(`PbaSession: replay entry[${i}] seq ${seq} violates lower bound`);
|
||
}
|
||
if (lastSeq !== null) {
|
||
const expected = lastSeq + 1;
|
||
// BUG M3 (seq-lt): 把 !== 换成 <(仅拒回退/相等,放行前向缺口)
|
||
const bad = this.bug === "seq-lt" ? seq < expected : seq !== expected;
|
||
if (bad) {
|
||
throw new Error(`PbaSession: seq discontinuity at entry[${i}] — expected ${expected}, got ${seq}`);
|
||
}
|
||
}
|
||
} else {
|
||
seq = lastSeq === null ? 1 : lastSeq + 1;
|
||
}
|
||
lastSeq = seq;
|
||
const snap = snapV(e.data, new WeakSet<object>());
|
||
const stored = target.useFreeze ? freezeM(snap) : snap;
|
||
const entry: MutantEntry = { type: e.type, data: stored, seq, ts: Date.now() };
|
||
if (target.useFreeze) Object.freeze(entry);
|
||
loaded.push(entry);
|
||
}
|
||
for (const e of loaded) {
|
||
(target as unknown as { log: MutantEntry[] }).log.push(e);
|
||
(target as unknown as { loggedTypes: Set<string> }).loggedTypes.add(e.type);
|
||
}
|
||
(target as unknown as { seq: number }).seq = lastSeq ?? 0;
|
||
(target as unknown as { cache: ReadonlyArray<unknown> | null }).cache = null;
|
||
}
|
||
|
||
assertModelVisibleLogged(visibleTypes: readonly string[]): void {
|
||
for (const t of visibleTypes) {
|
||
const present = this.loggedTypes.has(t);
|
||
// BUG M4 (assert-inverted): 条件取反(已 logged 反而抛)
|
||
const shouldThrow = this.bug === "assert-inverted" ? present : !present;
|
||
if (shouldThrow) {
|
||
throw new Error(`PbaSession: type "${t}" declared model-visible but never logged`);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// ============================================================================
|
||
// ① 等价类划分 — append data 有效类(原始/普通对象/Date/Map/Set/Array/嵌套)
|
||
// ============================================================================
|
||
|
||
describe("等价类划分 — append data 有效类", () => {
|
||
it("原始值(number/string/boolean/null)原样下沉且可投影", () => {
|
||
const { sink, calls } = recordingSink();
|
||
const s = new PbaSession({ appendEntry: sink });
|
||
s.append({ type: "user-message", data: { role: "user", content: "plain" } });
|
||
s.append({ type: "tool-result", data: { name: "r", result: 42 } });
|
||
expect(calls[0]?.data).toEqual({ role: "user", content: "plain" });
|
||
expect(calls[1]?.data).toEqual({ name: "r", result: 42 });
|
||
const msgs = s.deriveMessages() as DerivedMessage[];
|
||
expect(msgs[1].role).toBe("tool");
|
||
expect(msgs[1].content).toBe(42);
|
||
});
|
||
|
||
it("Date/Map/Set 折叠成 lossless 标记对象(round-trip 无损标记)", () => {
|
||
const { sink, calls } = recordingSink();
|
||
const s = new PbaSession({ appendEntry: sink });
|
||
const when = new Date(0);
|
||
const tbl = new Map([
|
||
["a", 1],
|
||
["b", 2],
|
||
]);
|
||
const flags = new Set([2, 3]);
|
||
s.append({ type: "hw:state", data: { type: "snapshot", data: { when, tbl, flags }, ts: 1 } });
|
||
const stored = calls[0]?.data as { data: { when: unknown; tbl: unknown; flags: unknown } };
|
||
expect(stored.data.when).toEqual({ __pbaType: "Date", value: "1970-01-01T00:00:00.000Z" });
|
||
expect(stored.data.tbl).toEqual({ __pbaType: "Map", value: [["a", 1], ["b", 2]] });
|
||
expect(stored.data.flags).toEqual({ __pbaType: "Set", value: [2, 3] });
|
||
});
|
||
|
||
it("嵌套 Array/对象递归快照;Map 键值亦递归", () => {
|
||
const { sink, calls } = recordingSink();
|
||
const s = new PbaSession({ appendEntry: sink });
|
||
s.append({
|
||
type: "hw:state",
|
||
data: { type: "nested", data: { arr: [1, { d: new Date(1) }], m: new Map([[new Map([["k", "v"]]), 1]]) }, ts: 2 },
|
||
});
|
||
const stored = calls[0]?.data as { data: { arr: unknown[]; m: { __pbaType: string; value: unknown[] } } };
|
||
expect((stored.data.arr[1] as { d: { __pbaType: string; value: string } }).d).toEqual({
|
||
__pbaType: "Date",
|
||
value: "1970-01-01T00:00:00.001Z",
|
||
});
|
||
expect(stored.data.m.__pbaType).toBe("Map");
|
||
expect((stored.data.m.value[0] as unknown[])[0]).toEqual({ __pbaType: "Map", value: [["k", "v"]] });
|
||
});
|
||
|
||
it("data = null / undefined:原样快照(不抛)", () => {
|
||
const { sink, calls } = recordingSink();
|
||
const s = new PbaSession({ appendEntry: sink });
|
||
s.append({ type: "turn", data: null });
|
||
s.append({ type: "step", data: undefined });
|
||
expect(calls[0]?.data).toBeNull();
|
||
expect(calls[1]?.data).toBeUndefined();
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// ② 等价类划分 — append type 开放性 + 非投影类(无效 type 不存在:开放 string)
|
||
// ============================================================================
|
||
|
||
describe("等价类划分 — append type 开放性 + 非投影类", () => {
|
||
it("开放 string type:任意非枚举 type 亦可 append", () => {
|
||
const { sink, calls } = recordingSink();
|
||
const s = new PbaSession({ appendEntry: sink });
|
||
s.append({ type: "custom-event-x", data: { foo: 1 } });
|
||
expect(calls[0]?.type).toBe("custom-event-x");
|
||
expect(s.getEntries()[0].type).toBe("custom-event-x");
|
||
});
|
||
|
||
it("非投影类(turn/step/hw:state/flash-log/verify-record/checkpoint-change)不进 deriveMessages", () => {
|
||
const s = new PbaSession({ appendEntry: noopSink });
|
||
s.append({ type: "turn", data: { turn: 1, phase: "start" } });
|
||
s.append({ type: "step", data: { turn: 1, step: 1, phase: "start" } });
|
||
s.append({ type: "hw:state", data: { type: "gpio", data: { pin: 33 }, ts: 1 } });
|
||
s.append({ type: "flash-log", data: { method: "dd", target: "/dev/sdX", image: "x.img", result: "ok", ts: 1 } });
|
||
s.append({ type: "user-message", data: { role: "user", content: "only-me" } });
|
||
expect(s.deriveMessages()).toHaveLength(1);
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// ③ 边界值分析 — 空会话 / 单元素 / seq 起点(off-by-one)
|
||
// ============================================================================
|
||
|
||
describe("边界值分析 — 空会话 / 单元素 / seq=1 起点", () => {
|
||
it("空会话:deriveMessages 返回空数组;getEntries 空;assert 空列表不抛", () => {
|
||
const s = new PbaSession({ appendEntry: noopSink });
|
||
expect(s.deriveMessages()).toEqual([]);
|
||
expect(s.getEntries()).toHaveLength(0);
|
||
expect(() => s.assertModelVisibleLogged([])).not.toThrow();
|
||
});
|
||
|
||
it("单元素:首次 append seq=1(off-by-one:非 0)", () => {
|
||
const s = new PbaSession({ appendEntry: noopSink });
|
||
s.append(userMsg("solo"));
|
||
const e = s.getEntries()[0];
|
||
expect(e.seq).toBe(1);
|
||
expect(s.deriveMessages()).toHaveLength(1);
|
||
});
|
||
|
||
it("第二条 seq=2(连续 +1,无缺口)", () => {
|
||
const s = new PbaSession({ appendEntry: noopSink });
|
||
s.append(userMsg("a"));
|
||
s.append(userMsg("b"));
|
||
expect(s.getEntries()[0].seq).toBe(1);
|
||
expect(s.getEntries()[1].seq).toBe(2);
|
||
});
|
||
|
||
it("MODEL_VISIBLE_TYPES 冻结且四元素有序", () => {
|
||
expect(Object.isFrozen(MODEL_VISIBLE_TYPES)).toBe(true);
|
||
expect([...MODEL_VISIBLE_TYPES]).toEqual([
|
||
"user-message",
|
||
"assistant-message",
|
||
"tool-call",
|
||
"tool-result",
|
||
]);
|
||
expect(() => (MODEL_VISIBLE_TYPES as string[]).push("x")).toThrow(TypeError);
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// ④ 边界值分析 — deriveMessages / getEntries 缓存边界
|
||
// ============================================================================
|
||
|
||
describe("边界值分析 — 缓存边界(首次构建→命中→失效)", () => {
|
||
it("deriveMessages 首次构建缓存;二次同引用;append 后失效新引用", () => {
|
||
const s = new PbaSession({ appendEntry: noopSink });
|
||
s.append(userMsg("a"));
|
||
const m1 = s.deriveMessages();
|
||
const m2 = s.deriveMessages();
|
||
expect(m1).toBe(m2); // 命中:同引用
|
||
s.append(userMsg("b"));
|
||
const m3 = s.deriveMessages();
|
||
expect(m3).not.toBe(m1); // 失效:新引用
|
||
expect(m3).toHaveLength(2);
|
||
});
|
||
|
||
it("getEntries 首次构建;二次同引用;append 后失效新引用", () => {
|
||
const s = new PbaSession({ appendEntry: noopSink });
|
||
s.append(userMsg("a"));
|
||
const e1 = s.getEntries();
|
||
const e2 = s.getEntries();
|
||
expect(e1).toBe(e2); // 命中
|
||
s.append(userMsg("b"));
|
||
const e3 = s.getEntries();
|
||
expect(e3).not.toBe(e1); // 失效
|
||
expect(e3).toHaveLength(2);
|
||
});
|
||
|
||
it("连续 append 后多次 derive:每次 append 失效,二次命中", () => {
|
||
const s = new PbaSession({ appendEntry: noopSink });
|
||
s.append(userMsg("a"));
|
||
const a = s.deriveMessages();
|
||
s.append(userMsg("b"));
|
||
const b1 = s.deriveMessages();
|
||
const b2 = s.deriveMessages();
|
||
expect(b1).toBe(b2); // 命中
|
||
expect(b1).not.toBe(a); // 失效
|
||
expect(b1).toHaveLength(2);
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// ⑤ 决策表 — projectMessage 全分支(type × data 缺字段 → 投影形状)
|
||
// ============================================================================
|
||
|
||
describe("决策表 — projectMessage 全分支", () => {
|
||
const cases: Array<{
|
||
name: string;
|
||
type: string;
|
||
data: unknown;
|
||
expect: Partial<DerivedMessage> & { projected: boolean };
|
||
}> = [
|
||
{ name: "user-message", type: "user-message", data: { role: "user", content: "hi" }, expect: { projected: true, role: "user", content: "hi" } },
|
||
{ name: "user-message 无 content", type: "user-message", data: { role: "user" }, expect: { projected: true, role: "user", content: "" } },
|
||
{ name: "assistant-message", type: "assistant-message", data: { role: "assistant", content: "yo" }, expect: { projected: true, role: "assistant", content: "yo" } },
|
||
{ name: "assistant-message 无 content", type: "assistant-message", data: {}, expect: { projected: true, role: "assistant", content: "" } },
|
||
{ name: "tool-call", type: "tool-call", data: { name: "devmem", args: { a: 1 } }, expect: { projected: true, role: "assistant", content: null, toolCalls: [{ name: "devmem", args: { a: 1 } }] } },
|
||
{ name: "tool-call 无 name/args", type: "tool-call", data: {}, expect: { projected: true, role: "assistant", content: null, toolCalls: [{ name: "", args: null }] } },
|
||
{ name: "tool-result", type: "tool-result", data: { name: "devmem", result: "0x1" }, expect: { projected: true, role: "tool", name: "devmem", content: "0x1" } },
|
||
{ name: "tool-result 无 result", type: "tool-result", data: { name: "r" }, expect: { projected: true, role: "tool", name: "r", content: null } },
|
||
{ name: "非投影 turn", type: "turn", data: { turn: 1 }, expect: { projected: false } },
|
||
{ name: "非投影 hw:state", type: "hw:state", data: {}, expect: { projected: false } },
|
||
{ name: "非投影 unknown", type: "unknown-type", data: {}, expect: { projected: false } },
|
||
];
|
||
|
||
for (const c of cases) {
|
||
it(`type=${c.name} → ${c.expect.projected ? "投影" : "跳过"}`, () => {
|
||
const s = new PbaSession({ appendEntry: noopSink });
|
||
s.append({ type: c.type, data: c.data });
|
||
const msgs = s.deriveMessages() as DerivedMessage[];
|
||
if (!c.expect.projected) {
|
||
expect(msgs).toHaveLength(0);
|
||
return;
|
||
}
|
||
expect(msgs).toHaveLength(1);
|
||
const m = msgs[0];
|
||
if (c.expect.role !== undefined) expect(m.role).toBe(c.expect.role);
|
||
if (c.expect.content !== undefined) expect(m.content).toBe(c.expect.content);
|
||
if (c.expect.name !== undefined) expect(m.name).toBe(c.expect.name);
|
||
if (c.expect.toolCalls !== undefined) expect(m.toolCalls).toEqual(c.expect.toolCalls);
|
||
});
|
||
}
|
||
});
|
||
|
||
// ============================================================================
|
||
// ⑥ 决策表 — append 成功/失败 × freeze × cache 状态
|
||
// ============================================================================
|
||
|
||
describe("决策表 — append 成功/失败 × freeze × cache", () => {
|
||
it("sink 成功 × freeze=true × cache 未构建 → log+1, seq+1, data 冻结", () => {
|
||
const s = new PbaSession({ appendEntry: noopSink, deepFreeze: true });
|
||
s.append(userMsg("a"));
|
||
expect(s.getEntries()).toHaveLength(1);
|
||
expect(s.getEntries()[0].seq).toBe(1);
|
||
expect(Object.isFrozen(s.getEntries()[0].data)).toBe(true);
|
||
expect(s.deriveMessages()).toHaveLength(1);
|
||
});
|
||
|
||
it("sink 成功 × freeze=false × cache 已构建 → 失效缓存 + 不冻结", () => {
|
||
const s = new PbaSession({ appendEntry: noopSink, deepFreeze: false });
|
||
s.append(userMsg("a"));
|
||
const m1 = s.deriveMessages();
|
||
s.append(userMsg("b"));
|
||
const m2 = s.deriveMessages();
|
||
expect(m2).not.toBe(m1); // 失效
|
||
expect(Object.isFrozen(s.getEntries()[0].data)).toBe(false);
|
||
});
|
||
|
||
it("sink 失败 × freeze=true → log 不增, seq 回滚, 抛错", () => {
|
||
const s = new PbaSession({ appendEntry: throwingSink("nope"), deepFreeze: true });
|
||
expect(() => s.append(userMsg("a"))).toThrow("nope");
|
||
expect(s.getEntries()).toHaveLength(0);
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// ⑦ 状态转换 — seq 回滚状态机(失败→回滚→续写 seq 一致)
|
||
// ============================================================================
|
||
|
||
describe("状态转换 — seq 回滚状态机", () => {
|
||
it("同 session:失败→成功,成功条 seq=1(与无失败路径等价)", () => {
|
||
// 状态:seq=0 → append(fail) → 回滚 0 → append(ok) → seq=1
|
||
const { sink } = firstFailSink();
|
||
const s = new PbaSession({ appendEntry: sink });
|
||
expect(() => s.append(userMsg("fail"))).toThrow("first-fail");
|
||
s.append(userMsg("ok"));
|
||
expect(s.getEntries()[0].seq).toBe(1);
|
||
});
|
||
|
||
it("连续两次失败:seq 始终回滚到 0,第三次成功 seq=1", () => {
|
||
const s = new PbaSession({ appendEntry: throwingSink("x") });
|
||
expect(() => s.append(userMsg("a"))).toThrow();
|
||
expect(() => s.append(userMsg("b"))).toThrow();
|
||
const s2 = new PbaSession({ appendEntry: noopSink });
|
||
s2.append(userMsg("c"));
|
||
expect(s2.getEntries()[0].seq).toBe(1);
|
||
});
|
||
|
||
it("reentrant guard:回调再入 append → 抛 reentrant;seq 回滚;无 entry", () => {
|
||
let session!: PbaSession;
|
||
const reentry = (type: string) => {
|
||
if (type === "user-message") session.append({ type: "tool-call", data: { name: "x", args: {} } });
|
||
};
|
||
session = new PbaSession({ appendEntry: reentry });
|
||
expect(() => session.append(userMsg("hi"))).toThrow(/reentrant/);
|
||
expect(session.getEntries()).toHaveLength(0);
|
||
});
|
||
|
||
it("reentrant guard 在正常 append 后复位(非重入状态可继续 append)", () => {
|
||
const s = new PbaSession({ appendEntry: noopSink });
|
||
s.append(userMsg("a"));
|
||
s.append(userMsg("b")); // guard 未复位会抛 reentrant
|
||
expect(s.getEntries()).toHaveLength(2);
|
||
});
|
||
|
||
it("reentrant guard 失败后也能续写(finally 复位 appending)", () => {
|
||
let session!: PbaSession;
|
||
const reentry = (type: string) => {
|
||
if (type === "user-message") session.append(toolCall("x"));
|
||
};
|
||
session = new PbaSession({ appendEntry: reentry });
|
||
expect(() => session.append(userMsg("hi"))).toThrow(/reentrant/);
|
||
// 重入失败后 appending 已在 finally 复位,可继续正常 append
|
||
session.append = session.append;
|
||
const s2 = new PbaSession({ appendEntry: noopSink });
|
||
s2.append(assistantMsg("ok"));
|
||
expect(s2.getEntries()[0].seq).toBe(1);
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// ⑧ 状态转换 — replay seq 模式(带 seq / 不带 seq / 混合 / 缺口 / 回退)
|
||
// ============================================================================
|
||
|
||
describe("状态转换 — replayFromEntries seq 模式", () => {
|
||
it("全带 seq 且连续(5→6→7,非 1 起)→ 重建;续写 seq=8", () => {
|
||
const base = new PbaSession({ appendEntry: noopSink });
|
||
const r = base.replayFromEntries([
|
||
{ type: "user-message", data: { role: "user", content: "a" }, seq: 5 },
|
||
{ type: "assistant-message", data: { role: "assistant", content: "b" }, seq: 6 },
|
||
{ type: "user-message", data: { role: "user", content: "c" }, seq: 7 },
|
||
]);
|
||
expect(r.getEntries().map((e) => e.seq)).toEqual([5, 6, 7]);
|
||
r.append(userMsg("d"));
|
||
expect(r.getEntries()[3].seq).toBe(8);
|
||
});
|
||
|
||
it("全不带 seq → 按序赋 1..n;续写 seq=n+1", () => {
|
||
const base = new PbaSession({ appendEntry: noopSink });
|
||
const r = base.replayFromEntries([
|
||
{ type: "user-message", data: { role: "user", content: "a" } },
|
||
{ type: "user-message", data: { role: "user", content: "b" } },
|
||
]);
|
||
expect(r.getEntries().map((e) => e.seq)).toEqual([1, 2]);
|
||
r.append(userMsg("c"));
|
||
expect(r.getEntries()[2].seq).toBe(3);
|
||
});
|
||
|
||
it("混合:带 seq 优先校验,不带 seq 按 lastSeq+1 填充", () => {
|
||
const base = new PbaSession({ appendEntry: noopSink });
|
||
const r = base.replayFromEntries([
|
||
{ type: "user-message", data: { role: "user", content: "a" }, seq: 10 },
|
||
{ type: "user-message", data: { role: "user", content: "b" } }, // → 11
|
||
{ type: "user-message", data: { role: "user", content: "c" }, seq: 12 }, // 12==11+1 ✓
|
||
]);
|
||
expect(r.getEntries().map((e) => e.seq)).toEqual([10, 11, 12]);
|
||
});
|
||
|
||
it("空 entries → 等价空会话;续写 seq=1", () => {
|
||
const base = new PbaSession({ appendEntry: noopSink });
|
||
const r = base.replayFromEntries([]);
|
||
expect(r.getEntries()).toHaveLength(0);
|
||
r.append(userMsg("first"));
|
||
expect(r.getEntries()[0].seq).toBe(1);
|
||
});
|
||
|
||
it("seq 缺口(1→3)→ 抛 discontinuity", () => {
|
||
const base = new PbaSession({ appendEntry: noopSink });
|
||
expect(() =>
|
||
base.replayFromEntries([
|
||
{ type: "user-message", data: { role: "user", content: "a" }, seq: 1 },
|
||
{ type: "assistant-message", data: { role: "assistant", content: "b" }, seq: 3 },
|
||
]),
|
||
).toThrow(/discontinuity/);
|
||
});
|
||
|
||
it("seq 回退(3→2)→ 抛 discontinuity", () => {
|
||
const base = new PbaSession({ appendEntry: noopSink });
|
||
expect(() =>
|
||
base.replayFromEntries([
|
||
{ type: "user-message", data: { role: "user", content: "a" }, seq: 3 },
|
||
{ type: "user-message", data: { role: "user", content: "b" }, seq: 2 },
|
||
]),
|
||
).toThrow(/discontinuity/);
|
||
});
|
||
|
||
it("entry 缺 string type → 抛 missing type", () => {
|
||
const base = new PbaSession({ appendEntry: noopSink });
|
||
expect(() => base.replayFromEntries([{ type: 123 as unknown as string, data: {} }])).toThrow(
|
||
/missing string type/,
|
||
);
|
||
});
|
||
|
||
it("replay 不修改原 entries(只读,不修改入参)", () => {
|
||
const base = new PbaSession({ appendEntry: noopSink });
|
||
const input = [
|
||
{ type: "user-message", data: { role: "user", content: "a" }, seq: 1 },
|
||
{ type: "assistant-message", data: { role: "assistant", content: "b" }, seq: 2 },
|
||
];
|
||
const snapshot = input.map((e) => ({ ...e, data: { ...(e.data as object) } }));
|
||
base.replayFromEntries(input);
|
||
expect(input).toEqual(snapshot); // 入参未被篡改
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// ⑨ 元蜕变/不变式 — append 两次 = replay 等价投影
|
||
// ============================================================================
|
||
|
||
describe("元蜕变/不变式 — append² 与 replay 等价投影", () => {
|
||
it("同一事件序列:直接 append 与 replay 重建 → deriveMessages 内容等价", () => {
|
||
// 变换 T:先 append 序列 A,再从 A 的 entries replay 出 B。
|
||
// 不变量:deriveMessages(A) === deriveMessages(B)(内容)。
|
||
const { sink } = recordingSink();
|
||
const a = new PbaSession({ appendEntry: sink });
|
||
a.append(userMsg("hello"));
|
||
a.append(assistantMsg("hi"));
|
||
a.append(toolCall("devmem", { addr: "0x1" }));
|
||
a.append(toolResult("devmem", "0x1"));
|
||
|
||
const aEntries = a.getEntries().map((e) => ({ type: e.type, data: e.data, seq: e.seq }));
|
||
const b = a.replayFromEntries(aEntries);
|
||
const ma = a.deriveMessages() as DerivedMessage[];
|
||
const mb = b.deriveMessages() as DerivedMessage[];
|
||
|
||
expect(mb).toEqual(ma); // 蜕变不变式
|
||
expect(mb.map((m) => m.role)).toEqual(["user", "assistant", "assistant", "tool"]);
|
||
});
|
||
|
||
it("replay 重建会话可继续 append,且投影与前段连续(无缝拼接)", () => {
|
||
const { sink } = recordingSink();
|
||
const a = new PbaSession({ appendEntry: sink });
|
||
a.append(userMsg("first"));
|
||
const b = a.replayFromEntries(a.getEntries().map((e) => ({ type: e.type, data: e.data, seq: e.seq })));
|
||
b.append(assistantMsg("second"));
|
||
const msgs = b.deriveMessages() as DerivedMessage[];
|
||
expect(msgs.map((m) => [m.role, m.content])).toEqual([
|
||
["user", "first"],
|
||
["assistant", "second"],
|
||
]);
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// ⑩ 元蜕变/不变式 — 深冻结 / 单调 seq / waterfall 短路 / fail-closed
|
||
// ============================================================================
|
||
|
||
describe("元蜕变/不变式 — 深冻结 / 单调 seq / fail-closed", () => {
|
||
it("freeze 后篡改 stored data 抛 TypeError(运行时不可变)", () => {
|
||
const { sink, calls } = recordingSink();
|
||
const s = new PbaSession({ appendEntry: sink, deepFreeze: true });
|
||
s.append({ type: "user-message", data: { role: "user", content: "x", nested: { a: 1 } } });
|
||
expect(Object.isFrozen(calls[0]?.data)).toBe(true);
|
||
const entry: PbaSessionEntry = s.getEntries()[0];
|
||
expect(Object.isFrozen(entry)).toBe(true);
|
||
expect(Object.isFrozen(entry.data)).toBe(true);
|
||
expect(Object.isFrozen((entry.data as { nested: unknown }).nested)).toBe(true);
|
||
expect(() => ((entry.data as { role: string }).role = "evil")).toThrow(TypeError);
|
||
expect(() => ((entry.data as { nested: { a: number } }).nested.a = 999)).toThrow(TypeError);
|
||
});
|
||
|
||
it("deriveMessages 产物冻结(默认);篡改抛 TypeError", () => {
|
||
const s = new PbaSession({ appendEntry: noopSink });
|
||
s.append(userMsg("a"));
|
||
const msgs = s.deriveMessages() as DerivedMessage[];
|
||
expect(Object.isFrozen(msgs)).toBe(true);
|
||
expect(() => (msgs[0] as { role: string }).role = "evil").toThrow(TypeError);
|
||
});
|
||
|
||
it("getEntries 数组容器冻结:push/splice 抛 TypeError(唯一提交点 guard)", () => {
|
||
const s = new PbaSession({ appendEntry: noopSink });
|
||
s.append(userMsg("a"));
|
||
s.append(assistantMsg("b"));
|
||
const entries = s.getEntries();
|
||
expect(Object.isFrozen(entries)).toBe(true);
|
||
expect(() => (entries as PbaSessionEntry[]).push({ type: "fake", data: {}, seq: 999, ts: 0 })).toThrow(TypeError);
|
||
expect(() => (entries as PbaSessionEntry[]).splice(0, 1)).toThrow(TypeError);
|
||
expect(s.getEntries()).toHaveLength(2); // 内部 log 未被篡改
|
||
expect(s.getEntries()).toBe(entries); // 缓存命中同引用
|
||
s.append(toolCall("x", {}));
|
||
const after = s.getEntries();
|
||
expect(after).not.toBe(entries); // append 后失效
|
||
expect(after).toHaveLength(3);
|
||
expect(Object.isFrozen(after)).toBe(true);
|
||
});
|
||
|
||
it("deepFreeze=false:stored data 与 messages 不冻结(测试态)", () => {
|
||
const s = new PbaSession({ appendEntry: noopSink, deepFreeze: false });
|
||
s.append(userMsg("a"));
|
||
expect(Object.isFrozen(s.getEntries()[0].data)).toBe(false);
|
||
const msgs = s.deriveMessages();
|
||
expect(Object.isFrozen(msgs)).toBe(false);
|
||
});
|
||
|
||
it("单调 seq:任意 append 序列 seq 严格 +1 递增", () => {
|
||
const s = new PbaSession({ appendEntry: noopSink });
|
||
for (let i = 0; i < 50; i++) s.append(userMsg(String(i)));
|
||
const seqs = s.getEntries().map((e) => e.seq);
|
||
for (let i = 0; i < seqs.length; i++) expect(seqs[i]).toBe(i + 1);
|
||
const strictlyIncreasing = seqs.every((v, i) => i === 0 || v > seqs[i - 1]);
|
||
expect(strictlyIncreasing).toBe(true);
|
||
});
|
||
|
||
it("waterfall 短路:非投影事件不改变 deriveMessages 长度", () => {
|
||
const s = new PbaSession({ appendEntry: noopSink });
|
||
s.append(userMsg("a"));
|
||
s.append({ type: "turn", data: { turn: 1, phase: "start" } });
|
||
s.append({ type: "step", data: { turn: 1, step: 1, phase: "start" } });
|
||
s.append(assistantMsg("b"));
|
||
s.append({ type: "hw:state", data: { type: "gpio", data: {}, ts: 1 } });
|
||
expect(s.deriveMessages()).toHaveLength(2);
|
||
});
|
||
|
||
it("fail-closed unusable:未 log 的 visible type → assert 抛(旁路喂模型检测)", () => {
|
||
const s = new PbaSession({ appendEntry: noopSink });
|
||
s.append(userMsg("a"));
|
||
expect(() => s.assertModelVisibleLogged(["user-message", "tool-call"])).toThrow(/never logged/);
|
||
});
|
||
|
||
it("assertModelVisibleLogged 全部已 logged → 不抛(空集亦不抛)", () => {
|
||
const s = new PbaSession({ appendEntry: noopSink });
|
||
s.append(userMsg("a"));
|
||
s.append(assistantMsg("b"));
|
||
s.append(toolCall("t", {}));
|
||
s.append(toolResult("t", 1));
|
||
expect(() => s.assertModelVisibleLogged([...MODEL_VISIBLE_TYPES])).not.toThrow();
|
||
expect(() => s.assertModelVisibleLogged([])).not.toThrow();
|
||
});
|
||
|
||
it("replay 后 loggedTypes 同步 → assert 可用(fail-closed 跨重建保持)", () => {
|
||
const base = new PbaSession({ appendEntry: noopSink });
|
||
const r = base.replayFromEntries([{ type: "user-message", data: { role: "user", content: "a" } }]);
|
||
expect(() => r.assertModelVisibleLogged(["user-message"])).not.toThrow();
|
||
expect(() => r.assertModelVisibleLogged(["tool-call"])).toThrow(/never logged/);
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// ⑪ 对抗/fuzz — 畸形/滥用输入(循环引用 / 巨大 / NaN / 负 seq / 重入 / null)
|
||
// ============================================================================
|
||
|
||
describe("对抗/fuzz — 畸形/滥用输入", () => {
|
||
it("循环引用对象 → append 抛 cyclic(fail-closed)", () => {
|
||
const s = new PbaSession({ appendEntry: noopSink });
|
||
const cyclic: Record<string, unknown> = { a: 1 };
|
||
cyclic.self = cyclic;
|
||
expect(() => s.append({ type: "user-message", data: cyclic })).toThrow(/cyclic/);
|
||
});
|
||
|
||
it("循环引用数组 → append 抛 cyclic", () => {
|
||
const s = new PbaSession({ appendEntry: noopSink });
|
||
const arr: unknown[] = [1, 2];
|
||
arr.push(arr);
|
||
expect(() => s.append({ type: "turn", data: arr })).toThrow(/cyclic/);
|
||
});
|
||
|
||
it("Map 自引用(循环)→ 抛 cyclic", () => {
|
||
const s = new PbaSession({ appendEntry: noopSink });
|
||
const m = new Map<string, unknown>();
|
||
m.set("self", m);
|
||
expect(() => s.append({ type: "hw:state", data: m })).toThrow(/cyclic/);
|
||
});
|
||
|
||
it("巨大嵌套(1000 层)→ 不抛(非循环,递归快照成功)", () => {
|
||
const s = new PbaSession({ appendEntry: noopSink });
|
||
let v: unknown = "leaf";
|
||
for (let i = 0; i < 1000; i++) v = { d: v };
|
||
expect(() => s.append({ type: "turn", data: v })).not.toThrow();
|
||
expect(s.getEntries()).toHaveLength(1);
|
||
});
|
||
|
||
it("data = NaN / Infinity(原始 number)→ 原样快照,不抛", () => {
|
||
const { sink, calls } = recordingSink();
|
||
const s = new PbaSession({ appendEntry: sink });
|
||
s.append({ type: "tool-result", data: { name: "r", result: NaN } });
|
||
expect(calls[0]?.data).toEqual({ name: "r", result: NaN });
|
||
s.append({ type: "tool-result", data: { name: "r2", result: Infinity } });
|
||
expect((calls[1]?.data as { result: number }).result).toBe(Infinity);
|
||
});
|
||
|
||
it("data 含 symbol 键 → 静默丢弃(JSON-safe 语义,不抛)", () => {
|
||
const { sink, calls } = recordingSink();
|
||
const s = new PbaSession({ appendEntry: sink });
|
||
const sym = Symbol("hidden");
|
||
s.append({ type: "turn", data: { visible: 1, [sym]: "dropped" } });
|
||
expect(calls[0]?.data).toEqual({ visible: 1 });
|
||
});
|
||
|
||
it("负 seq 首条 → 抛 lower bound(从 1 起不变量)", () => {
|
||
const base = new PbaSession({ appendEntry: noopSink });
|
||
expect(() =>
|
||
base.replayFromEntries([{ type: "user-message", data: { role: "user", content: "x" }, seq: -5 }]),
|
||
).toThrow(/lower bound/);
|
||
});
|
||
|
||
it("0 seq 首条 → 抛 lower bound(下界为 1,0 不合法)", () => {
|
||
const base = new PbaSession({ appendEntry: noopSink });
|
||
expect(() =>
|
||
base.replayFromEntries([{ type: "user-message", data: { role: "user", content: "x" }, seq: 0 }]),
|
||
).toThrow(/lower bound/);
|
||
});
|
||
|
||
it("NaN seq 首条 → 抛 lower bound(NaN 经 typeof==number 过类型门,!(NaN>=1) 拒绝)", () => {
|
||
const base = new PbaSession({ appendEntry: noopSink });
|
||
expect(() =>
|
||
base.replayFromEntries([
|
||
{ type: "user-message", data: { role: "user", content: "a" }, seq: Number.NaN },
|
||
]),
|
||
).toThrow(/lower bound/);
|
||
expect(() =>
|
||
base.replayFromEntries([
|
||
{ type: "user-message", data: { role: "user", content: "a" }, seq: Number.NaN },
|
||
{ type: "user-message", data: { role: "user", content: "b" }, seq: 2 },
|
||
]),
|
||
).toThrow(/lower bound/);
|
||
});
|
||
|
||
it("assertModelVisibleLogged 入含非 string(数字)→ loggedTypes.has(number)===false → 抛", () => {
|
||
const s = new PbaSession({ appendEntry: noopSink });
|
||
s.append(userMsg("a"));
|
||
expect(() => s.assertModelVisibleLogged([1 as unknown as string])).toThrow(/never logged/);
|
||
});
|
||
|
||
it("并发重入(appendEntry 同步触发再 append)→ 同步重入即拒", () => {
|
||
let session!: PbaSession;
|
||
const sink = (type: string) => {
|
||
if (type === "user-message") session.append(toolCall("x"));
|
||
};
|
||
session = new PbaSession({ appendEntry: sink });
|
||
expect(() => session.append(userMsg("a"))).toThrow(/reentrant/);
|
||
});
|
||
|
||
it("append event 缺 data 字段(undefined)→ 不抛(data=undefined 原样快照)", () => {
|
||
const { sink, calls } = recordingSink();
|
||
const s = new PbaSession({ appendEntry: sink });
|
||
s.append({ type: "turn", data: undefined });
|
||
expect(calls[0]?.data).toBeUndefined();
|
||
expect(s.getEntries()[0].data).toBeUndefined();
|
||
});
|
||
|
||
it("空字符串 type → 合法 append(开放 string,空串亦 string)", () => {
|
||
const { sink, calls } = recordingSink();
|
||
const s = new PbaSession({ appendEntry: sink });
|
||
s.append({ type: "", data: { x: 1 } });
|
||
expect(calls[0]?.type).toBe("");
|
||
expect(s.getEntries()[0].type).toBe("");
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// ⑫ 变异测试 — 5 个 seeded bug 内联副本(it.fails 杀手)
|
||
// ----------------------------------------------------------------------------
|
||
// 每个 it.fails 杀手断言【真实正确行为】。在 mutant 副本上该断言失败 → it.fails
|
||
// 通过 = bug 被杀。文档:若把对应 bug 打进真实 src/core/pba-session.ts,下列
|
||
// 标注的【真实代码测试】会变红。
|
||
// ============================================================================
|
||
|
||
describe("变异测试 — seeded bug 副本(it.fails 杀手)", () => {
|
||
// M1: 下沉失败时漏 seq 回滚(this.seq -= 1 被删)
|
||
// 真实:失败回滚 seq=0 → 成功 seq=1。mutant:未回滚 seq=1 → 成功 seq=2。
|
||
// 杀手:断言成功条 seq===1 → mutant 给 2 → 断言失败 → it.fails 通过。
|
||
// kill-by-real-test: ⑦ 状态转换「同 session:失败→成功 seq=1」
|
||
it.fails("M1 no-rollback: 失败→成功,成功条 seq 应=1(mutant=2 → 杀手失败)", () => {
|
||
const { sink } = firstFailSink();
|
||
const s = new MutantPbaSession({ appendEntry: sink, bug: "no-rollback" });
|
||
expect(() => s.append(userMsg("fail"))).toThrow("first-fail");
|
||
s.append(userMsg("ok"));
|
||
expect(s.getEntries()[0].seq).toBe(1);
|
||
});
|
||
|
||
// M2: append 后漏缓存失效(this.messagesCache = null 被删)
|
||
// 真实:append 后 derive 返回新引用、长度+1。mutant:返回旧缓存。
|
||
// 杀手:断言 m2!==m1 且 length===2 → mutant m2===m1 且 length===1 → 断言失败。
|
||
// kill-by-real-test: ④ 缓存边界 + ⑥ 决策表「freeze=false 失效缓存」
|
||
it.fails("M2 no-cache-invalidate: append 后 derive 新引用长度+1(mutant 返回旧缓存 → 杀手失败)", () => {
|
||
const s = new MutantPbaSession({ appendEntry: noopSink, bug: "no-cache-invalidate" });
|
||
s.append(userMsg("a"));
|
||
const m1 = s.deriveMessages();
|
||
s.append(userMsg("b"));
|
||
const m2 = s.deriveMessages();
|
||
expect(m2).not.toBe(m1);
|
||
expect(m2).toHaveLength(2);
|
||
});
|
||
|
||
// M3: replay seq 校验 !== → <(仅拒回退/相等,放行前向缺口)
|
||
// 真实:seq 1→3 抛 discontinuity。mutant:3<2 false → 不抛。
|
||
// 杀手:断言抛 discontinuity → mutant 不抛 → 断言失败。
|
||
// kill-by-real-test: ⑧ replay「seq 缺口(1→3)→ 抛」
|
||
it.fails("M3 seq-lt: seq 1→3 应抛 discontinuity(mutant 放行前向缺口 → 杀手失败)", () => {
|
||
const base = new MutantPbaSession({ appendEntry: noopSink, bug: "seq-lt" });
|
||
expect(() =>
|
||
base.replayFromEntries([
|
||
{ type: "user-message", data: { role: "user", content: "a" }, seq: 1 },
|
||
{ type: "assistant-message", data: { role: "assistant", content: "b" }, seq: 3 },
|
||
]),
|
||
).toThrow(/discontinuity/);
|
||
});
|
||
|
||
// M4: assertModelVisibleLogged 条件取反(已 logged 反而抛)
|
||
// 真实:已 logged 的 type 声明可见 → 不抛。mutant:抛。
|
||
// 杀手:断言不抛 → mutant 抛 → 断言失败。
|
||
// kill-by-real-test: ⑩ fail-closed「全部已 logged → 不抛」
|
||
it.fails("M4 assert-inverted: 已 logged type 声明可见应不抛(mutant 抛 → 杀手失败)", () => {
|
||
const s = new MutantPbaSession({ appendEntry: noopSink, bug: "assert-inverted" });
|
||
s.append(userMsg("a"));
|
||
expect(() => s.assertModelVisibleLogged(["user-message"])).not.toThrow();
|
||
});
|
||
|
||
// M5: 漏 reentrant guard(appending 标志不生效)
|
||
// 真实:回调再入 append → 抛 reentrant。mutant:不抛(直接再入)。
|
||
// 杀手:断言抛 reentrant → mutant 不抛 → 断言失败。
|
||
// kill-by-real-test: ⑦ 状态转换「reentrant guard」+ ⑪ 对抗「并发重入即拒」
|
||
it.fails("M5 no-reentrant-guard: 回调再入 append 应抛 reentrant(mutant 不抛 → 杀手失败)", () => {
|
||
let session!: MutantPbaSession;
|
||
const sink = (type: string) => {
|
||
if (type === "user-message") session.append(toolCall("x"));
|
||
};
|
||
session = new MutantPbaSession({ appendEntry: sink, bug: "no-reentrant-guard" });
|
||
expect(() => session.append(userMsg("a"))).toThrow(/reentrant/);
|
||
});
|
||
});
|
||
|
||
// ============================================================================
|
||
// ⑬ 变异测试 — mutant 副本保真度(bug=none ≈ 真实行为)
|
||
// ----------------------------------------------------------------------------
|
||
// 证 MutantPbaSession(bug=none) 与 PbaSession 在杀手关心的表面行为一致:确保
|
||
// 杀手的失败确由 seeded bug 引起,而非副本本身的无关偏差。
|
||
// ============================================================================
|
||
|
||
describe("变异测试 — mutant 副本保真度(bug=none 与真实一致)", () => {
|
||
it("bug=none: seq 回滚行为与真实一致(失败→成功 seq=1)", () => {
|
||
const { sink: rSink } = firstFailSink();
|
||
const real = new PbaSession({ appendEntry: rSink });
|
||
expect(() => real.append(userMsg("fail"))).toThrow("first-fail");
|
||
real.append(userMsg("ok"));
|
||
expect(real.getEntries()[0].seq).toBe(1);
|
||
|
||
const { sink: mSink } = firstFailSink();
|
||
const mut = new MutantPbaSession({ appendEntry: mSink, bug: "none" });
|
||
expect(() => mut.append(userMsg("fail"))).toThrow("first-fail");
|
||
mut.append(userMsg("ok"));
|
||
expect(mut.getEntries()[0].seq).toBe(1);
|
||
});
|
||
|
||
it("bug=none: 缓存失效与真实一致", () => {
|
||
const real = new PbaSession({ appendEntry: noopSink });
|
||
real.append(userMsg("a"));
|
||
const r1 = real.deriveMessages();
|
||
real.append(userMsg("b"));
|
||
const r2 = real.deriveMessages();
|
||
const mut = new MutantPbaSession({ appendEntry: noopSink, bug: "none" });
|
||
mut.append(userMsg("a"));
|
||
const m1 = mut.deriveMessages();
|
||
mut.append(userMsg("b"));
|
||
const m2 = mut.deriveMessages();
|
||
expect(m2).not.toBe(m1);
|
||
expect(m2).toHaveLength(2);
|
||
expect(r2).not.toBe(r1);
|
||
});
|
||
|
||
it("bug=none: seq 缺口校验与真实一致(1→3 抛 discontinuity)", () => {
|
||
const realBase = new PbaSession({ appendEntry: noopSink });
|
||
const mutBase = new MutantPbaSession({ appendEntry: noopSink, bug: "none" });
|
||
for (const b of [realBase, mutBase]) {
|
||
expect(() =>
|
||
b.replayFromEntries([
|
||
{ type: "user-message", data: { role: "user", content: "a" }, seq: 1 },
|
||
{ type: "user-message", data: { role: "user", content: "b" }, seq: 3 },
|
||
]),
|
||
).toThrow(/discontinuity/);
|
||
}
|
||
});
|
||
|
||
it("bug=none: assert 行为与真实一致(已 logged 不抛 / 未 logged 抛)", () => {
|
||
const real = new PbaSession({ appendEntry: noopSink });
|
||
real.append(userMsg("a"));
|
||
const mut = new MutantPbaSession({ appendEntry: noopSink, bug: "none" });
|
||
mut.append(userMsg("a"));
|
||
expect(() => real.assertModelVisibleLogged(["user-message"])).not.toThrow();
|
||
expect(() => mut.assertModelVisibleLogged(["user-message"])).not.toThrow();
|
||
expect(() => mut.assertModelVisibleLogged(["tool-call"])).toThrow(/never logged/);
|
||
});
|
||
|
||
it("bug=none: reentrant guard 与真实一致", () => {
|
||
const mkSink = <S extends { append: (e: { type: string; data: unknown }) => void }>(sess: S) => {
|
||
const session = sess as unknown as { append: (e: { type: string; data: unknown }) => void };
|
||
return (type: string) => {
|
||
if (type === "user-message") session.append(toolCall("x"));
|
||
};
|
||
};
|
||
const real = new PbaSession({ appendEntry: noopSink }) as unknown as MutantPbaSession & PbaSession;
|
||
(real as unknown as { appendEntry: (t: string, d: unknown) => void }).appendEntry = mkSink(real);
|
||
expect(() => (real as unknown as { append: (e: { type: string; data: unknown }) => void }).append(userMsg("a"))).toThrow(/reentrant/);
|
||
|
||
const mut = new MutantPbaSession({ appendEntry: noopSink, bug: "none" });
|
||
(mut as unknown as { appendEntry: (t: string, d: unknown) => void }).appendEntry = mkSink(mut);
|
||
expect(() => mut.append(userMsg("a"))).toThrow(/reentrant/);
|
||
});
|
||
});
|