physical_byte_agent/tests/compaction.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

1329 lines
49 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.

/**
* compaction 模块完整测试套件(T09)—— 多方法论、测试前置。
*
* 被测对象(命名导出,按契约直 import,无 pi 运行时无硬件无网络):
* - src/compaction/token-meter.ts estimateTokens / measureContext
* - src/compaction/tool-result-pruner.ts pruneToolResult / PruneOptions / PruneResult
* - src/compaction/summarizer.ts buildCompactionSummary / CompactionSummary
* - src/compaction/spill.ts SpillStore / SpillLocator
*
* 每个 describe 块标注方法论名(等价类划分 / 边界值分析 / 决策表 / 状态转换 /
* 变异测试 / 对抗-fuzz / 元蜕变-不变式)。
*
* 变异测试:6 个 seeded bug(B1-B6)以"带 bug 逻辑副本"内联于本文件。每个 bug 配一条
* kill-test,用 `expect(() => expect(bugFn(x)).toBe(correct)).toThrow()` 模式直接证明
* 「若真实代码被此 bug 污染,正确性断言会 FAIL」= bug 被杀。文档化见各 bug 注释。
* 门 #1:真实(未植入 bug)代码全过;门 #2:每个 bug 副本单独被证明偏离正确。
*/
import { describe, it, expect } from "vitest";
import { estimateTokens, measureContext } from "../src/compaction/token-meter.js";
import {
pruneToolResult,
type PruneOptions,
type PruneResult,
} from "../src/compaction/tool-result-pruner.js";
import { buildCompactionSummary } from "../src/compaction/summarizer.js";
import { SpillStore, type SpillLocator } from "../src/compaction/spill.js";
// ============================================================================
// 变异测试基础设施:带 bug 逻辑副本
// ----------------------------------------------------------------------------
// 每个 seeded bug 是真实算法的忠实副本,植入一个单点缺陷。kill-test 同时断言:
// (a) 真实代码产出正确值;
// (b) bug 副本产出【偏离正确】的值(bugFn(x) !== correct);
// (c) 若把正确性断言套到 bug 副本上会抛(expect(bugFn(x)).toBe(correct) → throw)。
// (c) 即「植入后该测试 FAIL」的形式化证明,无需改源码。
// ============================================================================
/**
* B1 — token-meter estimateTokens 植入 bug:nonCjk 用 Math.floor 而非 Math.ceil。
* 真实代码 token-meter.ts:66 `Math.ceil(nonCjk / 4)`,变异为 `Math.floor`。
* 杀它:「边界值·5 char ASCII 跨档」真实 ⌈5/4⌉=2,bug floor=1。
*/
function estimateTokensB1(text: string): number {
if (text.length === 0) return 0;
const cjkRe = /[一-鿿㐀-䶿豈-﫿]/g;
let cjk = 0;
for (const _ of text.matchAll(cjkRe)) cjk++;
const nonCjk = text.length - cjk;
const nonCjkTokens = Math.floor(nonCjk / 4); // BUG: floor 而非 ceil
return cjk + nonCjkTokens;
}
/**
* B2 — pruner general 植入 bug:截断 off-by-one,slice(0, max)→slice(0, max+1)。
* 真实代码 tool-result-pruner.ts:185 `kept = lines.slice(0, max)`,变异多保留 1 行。
* 杀它:「决策表·general maxLines 截断」真实 dropped=3,bug dropped=2。
*/
function pruneGeneralB2(content: string, maxLines: number): PruneResult {
if (content.length === 0) return { pruned: "", dropped: 0 };
const lines = content.split("\n");
const max = Math.max(0, maxLines);
const kept = lines.slice(0, max + 1); // BUG: +1 off-by-one
return { pruned: kept.join("\n"), dropped: lines.length - kept.length };
}
/**
* B3 — pruner i2cdump 植入 bug:漏「最后非空 dump 行」补入。
* 真实代码 tool-result-pruner.ts:199-208 的 tail 补入逻辑被删,非地址末行丢失。
* 杀它:「边界·i2cdump 末行非地址」真实 pruned 含 tail,bug 不含。
*/
function pruneI2cB3(content: string): PruneResult {
if (content.length === 0)
return { pruned: "", dropped: 0, preservedAddrs: [] };
const lines = content.split("\n");
const I2C_ADDR_LINE = /^(?:0x[0-9a-fA-F]+|[0-9a-fA-F]{1,4}):/;
const I2C_ADDR_LABEL = /^(0x[0-9a-fA-F]+|[0-9a-fA-F]{1,4}):/;
const kept: string[] = [];
for (const ln of lines) if (I2C_ADDR_LINE.test(ln)) kept.push(ln);
const addrs: string[] = [];
for (const ln of kept) {
const m = I2C_ADDR_LABEL.exec(ln);
if (m && m[1] && !addrs.includes(m[1])) addrs.push(m[1]);
}
// BUG: 删除 tail 补入(最后非空行若非地址行应保留,这里漏了)
const preserved = kept;
return {
pruned: preserved.join("\n"),
dropped: lines.length - preserved.length,
preservedAddrs: addrs,
};
}
/**
* B4 — summarizer fitDigestsToBudget 植入 bug:超预算丢最新而非最旧(.pop 替换 .shift)。
* 真实代码 summarizer.ts:99-101 `kept.shift()`,变异为 `kept.pop()`。
* 杀它:「状态·超预算丢最旧保最新」真实保留 idx49,bug 丢 idx49。
*/
function buildCompactionSummaryB4(opts: {
prefix: string;
recentEntries: ReadonlyArray<{ type: string; data: unknown }>;
maxTokens: number;
}): { summary: string; reusedPrefix: boolean; droppedEntries: number } {
const { prefix, recentEntries, maxTokens } = opts;
const reusedPrefix = prefix.trim().length > 0;
const directiveLine =
`## Compaction Summary\n` +
`${recentEntries.length} recent entries compacted (model-free digest):`;
const baseParts: string[] = [];
if (reusedPrefix) baseParts.push(prefix);
baseParts.push(directiveLine);
const base = baseParts.join("\n\n");
const digestLines = recentEntries.map((entry) => {
let body: string;
try {
body = JSON.stringify(entry.data);
} catch {
body = "[unserializable]";
}
if (body.length > 120) body = body.slice(0, 120) + "…";
return `- ${entry.type}: ${body}`;
});
const kept = [...digestLines];
const estimateAll = () =>
estimateTokens(base) + (kept.length > 0 ? estimateTokens(kept.join("\n")) : 0);
while (kept.length > 0 && estimateAll() > maxTokens) {
kept.pop(); // BUG: pop 丢最新而非 shift 丢最旧
}
const summary = kept.length > 0 ? `${base}\n${kept.join("\n")}` : base;
return { summary, reusedPrefix, droppedEntries: recentEntries.length };
}
/**
* B5 — spill evict 植入 bug:阈值比较 `>` 改 `>=`(恰等于阈值的条目被误回收)。
* 真实代码 spill.ts:159 `entry.bytes > olderThanBytes`,变异为 `>=`。
* 杀它:「边界·evict 恰等于阈值保留」真实保留,bug 误回收。
*/
function makeSpillStoreB5() {
const store = new Map<string, { data: unknown; bytes: number }>();
const seqByKey = new Map<string, number>();
const encoder = new TextEncoder();
const makeLocator = (key: string, seq: number): SpillLocator =>
`pba-spill:${key}:${seq}` as SpillLocator;
const measureBytes = (value: unknown): number => {
let text: string;
try {
text = JSON.stringify(value);
} catch {
text = String(value);
}
if (typeof text !== "string") text = String(value);
if (text.length === 0) return 0;
return encoder.encode(text).length;
};
return {
spill(key: string, data: unknown): SpillLocator {
const seq = (seqByKey.get(key) ?? 0) + 1;
seqByKey.set(key, seq);
const loc = makeLocator(key, seq);
store.set(loc, { data, bytes: measureBytes(data) });
return loc;
},
evict(olderThanBytes?: number): number {
if (olderThanBytes === undefined) {
const n = store.size;
store.clear();
return n;
}
let evicted = 0;
for (const [loc, entry] of store) {
if (entry.bytes >= olderThanBytes) {
// BUG: >= 而非 >
store.delete(loc);
evicted++;
}
}
return evicted;
},
};
}
/**
* B6 — spill spill 植入 bug:漏 seq 自增(同 key 多次 spill 返同一 locator)。
* 真实代码 spill.ts:111 `const seq = (this.seqByKey.get(key) ?? 0) + 1;`,变异固定 seq=1。
* 杀它:「边界·同 key 多次 spill 返不同 locator」真实 a≠b,bug a===b。
*/
function makeSpillStoreB6() {
const store = new Map<string, { data: unknown; bytes: number }>();
const makeLocator = (key: string, seq: number): SpillLocator =>
`pba-spill:${key}:${seq}` as SpillLocator;
return {
spill(key: string, data: unknown): SpillLocator {
const seq = 1; // BUG: 固定 seq=1,漏自增
const loc = makeLocator(key, seq);
store.set(loc, { data, bytes: 0 });
return loc;
},
};
}
// ============================================================================
// ① token-meter — 等价类划分 + 边界值分析
// ============================================================================
describe("compaction token-meter — 等价类划分(有效/无效/边界类)", () => {
// 等价类:① 空串 ② 纯 ASCII ③ 纯 CJK ④ 混合 ⑤ 单字符
it("等价类·空串: estimateTokens('') → 0", () => {
expect(estimateTokens("")).toBe(0);
});
it("等价类·纯 ASCII: 'hello world'(11 char) → ⌈11/4⌉=3", () => {
expect(estimateTokens("hello world")).toBe(3);
});
it("等价类·纯 CJK: '寄存器配置'(5 CJK) → 每 char 1 = 5", () => {
expect(estimateTokens("寄存器配置")).toBe(5);
});
it("等价类·混合: 'ab寄存器'(2 ASCII + 3 CJK) → 3 + ⌈2/4⌉=1 = 4", () => {
expect(estimateTokens("ab寄存器")).toBe(4);
});
it("等价类·单字符 ASCII: 'a' → ⌈1/4⌉=1", () => {
expect(estimateTokens("a")).toBe(1);
});
it("等价类·单字符 CJK: '寄' → 1", () => {
expect(estimateTokens("寄")).toBe(1);
});
it("等价类·纯标点/空格混合: ' !! '(5 non-CJK) → ⌈5/4⌉=2", () => {
expect(estimateTokens(" !! ")).toBe(2);
});
});
describe("compaction token-meter — 边界值分析(off-by-one、空、4 倍数边界)", () => {
it("边界·4 char ASCII 恰好整除: 'abcd' → ⌈4/4⌉=1", () => {
expect(estimateTokens("abcd")).toBe(1);
});
it("边界·5 char ASCII 跨档 off-by-one: 'abcde' → ⌈5/4⌉=2", () => {
expect(estimateTokens("abcde")).toBe(2);
});
it("边界·3 char 未跨档: 'abc' → ⌈3/4⌉=1", () => {
expect(estimateTokens("abc")).toBe(1);
});
it("边界·单空格非空串: ' ' → 1", () => {
expect(estimateTokens(" ")).toBe(1);
});
it("边界·measureContext 空数组 → 0", () => {
expect(measureContext([])).toBe(0);
});
it("边界·measureContext 单条空 content → 0 + 4 overhead = 4", () => {
expect(measureContext([{ role: "user", content: "" }])).toBe(4);
});
it("边界·measureContext 单条单字符 content → 1 + 4 = 5", () => {
expect(measureContext([{ role: "user", content: "a" }])).toBe(5);
});
it("边界·4 char ×N 恰好整除不漏算: 'abcd'.repeat(10)=40 → 10", () => {
expect(estimateTokens("abcd".repeat(10))).toBe(10);
});
});
describe("compaction token-meter — 对抗/fuzz(null/undefined/缺失字段/畸形/巨大)", () => {
it("fuzz·消息 content 为 undefined → 当 '' 处理(不抛)", () => {
expect(measureContext([{ role: "user" } as any])).toBe(4);
});
it("fuzz·消息为 null → 跳过(不抛、不计)", () => {
expect(measureContext([null as any])).toBe(0);
});
it("fuzz·巨大 ASCII 串 (10000 char) → ⌈10000/4⌉=2500,不抛", () => {
expect(estimateTokens("a".repeat(10000))).toBe(2500);
});
it("fuzz·巨大 CJK 串 (5000 CJK) → 5000,不抛", () => {
expect(estimateTokens("寄".repeat(5000))).toBe(5000);
});
it("fuzz·混合 null + 正常消息: null 被跳过,只计正常条", () => {
const msgs = [
null,
{ role: "user", content: "ab" },
undefined,
{ role: "assistant", content: "abcd" },
] as any;
expect(measureContext(msgs)).toBe(estimateTokens("ab") + estimateTokens("abcd") + 8);
});
});
describe("compaction token-meter — 元蜕变/不变式(确定性 + 线性叠加 + 非负)", () => {
it("不变式·estimateTokens 确定性: 同输入多次调用恒同输出", () => {
const t = "Hello 寄存器 world 配置!";
const a = estimateTokens(t);
expect(a).toBe(estimateTokens(t));
expect(a).toBe(estimateTokens(t));
});
it("不变式·measureContext = Σ(estimateTokens(content) + 4) 对非空消息", () => {
const msgs = [
{ role: "user", content: "ab" },
{ role: "assistant", content: "abcd" },
{ role: "tool", content: "寄存器" },
];
const expected =
estimateTokens("ab") +
estimateTokens("abcd") +
estimateTokens("寄存器") +
4 * 3;
expect(measureContext(msgs)).toBe(expected);
});
it("不变式·estimateTokens ≥ 0 对任意输入(非负)", () => {
expect(estimateTokens("")).toBeGreaterThanOrEqual(0);
expect(estimateTokens("x")).toBeGreaterThanOrEqual(0);
expect(estimateTokens("寄")).toBeGreaterThanOrEqual(0);
});
it("不变式·estimateTokens(a+b) ≤ estimateTokens(a)+estimateTokens(b)(ceil 次可加性)", () => {
const a = "abc";
const b = "defg";
expect(estimateTokens(a + b)).toBeLessThanOrEqual(
estimateTokens(a) + estimateTokens(b),
);
});
});
// ============================================================================
// token-meter — 变异测试 kill-test
// ============================================================================
describe("compaction token-meter — 变异测试 kill-test", () => {
it("B1 kill: 5 char ASCII 跨档 ⌈5/4⌉=2(真实=2;bug floor=1 偏离→正确性断言套 bug 抛)", () => {
const correct = 2;
// (a) 真实代码正确
expect(estimateTokens("abcde")).toBe(correct);
// (b) bug 副本偏离正确
expect(estimateTokensB1("abcde")).not.toBe(correct);
// (c) 若真实被此 bug 污染,正确性断言会 FAIL
expect(() => expect(estimateTokensB1("abcde")).toBe(correct)).toThrow();
});
});
// ============================================================================
// ② tool-result-pruner — 等价类划分 + 决策表 + 边界 + fuzz + 不变式
// ============================================================================
const I2CDUMP_SAMPLE = [
"WARNING: i2c-1 adapter unavailable, using i2c-0",
" 0 1 2 3 4 5 6 7 8 9 a b c d e f",
"00: 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f",
"10: 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f",
"20: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff",
"70: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00",
].join("\n");
describe("compaction tool-result-pruner — 等价类划分(四类工具 + 空内容)", () => {
it("等价类·i2cdump: 保留全部地址行 + 末行,丢 WARNING/列头", () => {
const res = pruneToolResult(I2CDUMP_SAMPLE, { tool: "i2cdump" });
expect(res.pruned).toContain("00: 00 01");
expect(res.pruned).toContain("70: 00 00");
expect(res.pruned).not.toContain("WARNING");
expect(res.pruned).not.toContain("0 1 2 3");
expect(res.preservedAddrs).toEqual(["00", "10", "20", "70"]);
expect(res.dropped).toBe(2);
});
it("等价类·gdb: 保留 #frame 行,丢非帧行", () => {
const gdb = [
"Reading symbols from vmlinux...",
"#0 0xffffffff in do_fault ()",
"#1 0xaaaa in handle_irq (irq=12)",
"warning: ",
].join("\n");
const res = pruneToolResult(gdb, { tool: "gdb" });
expect(res.pruned).toContain("#0 0xffffffff");
expect(res.pruned).toContain("#1 0xaaaa");
expect(res.pruned).not.toContain("Reading symbols");
expect(res.dropped).toBe(2);
});
it("等价类·dmesg: 保留 severe(级别标记 + 关键字),丢 benign", () => {
const dmesg = [
"[ 1.0] Bluetooth: started",
"[ 2.0] <4> thermal: warning threshold exceeded",
"[ 3.0] <3> iommu: error mapping failed",
"[ 4.0] USB: device enumerated",
].join("\n");
const res = pruneToolResult(dmesg, { tool: "dmesg" });
expect(res.pruned).toContain("warning threshold");
expect(res.pruned).toContain("error mapping");
expect(res.pruned).not.toContain("Bluetooth: started");
expect(res.dropped).toBe(2);
});
it("等价类·general: 截断到 maxLines,超出丢弃", () => {
const content = Array.from({ length: 10 }, (_, i) => `line${i}`).join("\n");
const res = pruneToolResult(content, { tool: "general", maxLines: 3 });
expect(res.pruned).toBe("line0\nline1\nline2");
expect(res.dropped).toBe(7);
});
it("等价类·空内容: 四类工具均 { pruned:'', dropped:0 }", () => {
for (const tool of ["i2cdump", "gdb", "dmesg", "general"] as const) {
const res = pruneToolResult("", { tool });
expect(res.pruned).toBe("");
expect(res.dropped).toBe(0);
expect(res.preservedAddrs).toEqual(tool === "i2cdump" ? [] : undefined);
}
});
});
describe("compaction tool-result-pruner — 决策表(组合输入→期望,覆盖全分支)", () => {
const cases: Array<{
name: string;
content: string;
opts: PruneOptions;
expectInPruned: string[];
expectNotInPruned: string[];
expectDropped: number;
}> = [
{
name: "i2cdump+有地址行+末行非地址",
content: "warn\n00: aa\n10: bb\ntail-line-no-addr",
opts: { tool: "i2cdump" },
expectInPruned: ["00: aa", "10: bb", "tail-line-no-addr"],
expectNotInPruned: ["warn"],
expectDropped: 1,
},
{
name: "i2cdump+末行已是地址行(去重不重复)",
content: "00: aa\n10: bb",
opts: { tool: "i2cdump" },
expectInPruned: ["00: aa", "10: bb"],
expectNotInPruned: [],
expectDropped: 0,
},
{
name: "gdb+无帧行→fail-soft 首尾",
content: "no frame here\njust prose",
opts: { tool: "gdb" },
expectInPruned: ["no frame here", "just prose"],
expectNotInPruned: [],
expectDropped: 0,
},
{
name: "dmesg+benign 全无匹配→pruned 空(正确语义不兜底)",
content: "[1] ok\n[2] fine",
opts: { tool: "dmesg" },
expectInPruned: [],
expectNotInPruned: ["[1] ok", "[2] fine"],
expectDropped: 2,
},
{
name: "general+maxLines=0→全丢",
content: "a\nb\nc",
opts: { tool: "general", maxLines: 0 },
expectInPruned: [],
expectNotInPruned: ["a", "b", "c"],
expectDropped: 3,
},
{
name: "general+maxLines 缺省→默认 200(只给 5 行,全保留)",
content: "a\nb\nc\nd\ne",
opts: { tool: "general" },
expectInPruned: ["a", "b", "c", "d", "e"],
expectNotInPruned: [],
expectDropped: 0,
},
{
name: "general+maxLines 负数→Math.max(0,neg)=0→全丢",
content: "a\nb",
opts: { tool: "general", maxLines: -5 },
expectInPruned: [],
expectNotInPruned: ["a", "b"],
expectDropped: 2,
},
{
name: "general+maxLines 大于行数→全保留 dropped=0",
content: "a\nb\nc",
opts: { tool: "general", maxLines: 999 },
expectInPruned: ["a", "b", "c"],
expectNotInPruned: [],
expectDropped: 0,
},
];
for (const c of cases) {
it(`决策表·${c.name}`, () => {
const res = pruneToolResult(c.content, c.opts);
for (const s of c.expectInPruned) expect(res.pruned).toContain(s);
for (const s of c.expectNotInPruned) expect(res.pruned).not.toContain(s);
expect(res.dropped).toBe(c.expectDropped);
});
}
});
describe("compaction tool-result-pruner — 边界值分析(单行/全空/0x 前缀/去重)", () => {
it("边界·单行 i2cdump 地址行: '00: aa' → 保留,dropped 0", () => {
const res = pruneToolResult("00: aa", { tool: "i2cdump" });
expect(res.pruned).toBe("00: aa");
expect(res.dropped).toBe(0);
expect(res.preservedAddrs).toEqual(["00"]);
});
it("边界·单行非地址 prose: 'just prose' → fail-soft 退回首=尾(同行)", () => {
const res = pruneToolResult("just prose", { tool: "i2cdump" });
expect(res.pruned).toBe("just prose");
expect(res.dropped).toBe(0);
expect(res.preservedAddrs).toEqual([]);
});
it("边界·i2cdump 末行非地址: '00: aa\\ntail' → tail 补入保留", () => {
const res = pruneToolResult("00: aa\ntail-no-addr", { tool: "i2cdump" });
expect(res.pruned).toBe("00: aa\ntail-no-addr");
expect(res.dropped).toBe(0);
expect(res.preservedAddrs).toEqual(["00"]);
});
it("边界·0x 前缀地址行: '0x50: aa bb' → 保留 + preservedAddrs=['0x50']", () => {
const res = pruneToolResult("0x50: aa bb", { tool: "i2cdump" });
expect(res.pruned).toBe("0x50: aa bb");
expect(res.preservedAddrs).toEqual(["0x50"]);
});
it("边界·全空行 i2cdump: '\\n\\n' → fail-soft 空,dropped=3", () => {
const res = pruneToolResult("\n\n", { tool: "i2cdump" });
expect(res.pruned).toBe("");
expect(res.preservedAddrs).toEqual([]);
expect(res.dropped).toBe(3);
});
it("边界·gdb 单帧行 '#0 frame' → 保留 1 行", () => {
const res = pruneToolResult("#0 frame", { tool: "gdb" });
expect(res.pruned).toBe("#0 frame");
expect(res.dropped).toBe(0);
});
it("边界·dmesg 单 severe '<3> err' → 保留", () => {
const res = pruneToolResult("<3> err", { tool: "dmesg" });
expect(res.pruned).toBe("<3> err");
expect(res.dropped).toBe(0);
});
it("边界·i2cdump preservedAddrs 去重: 同地址标签多次只记一次", () => {
const res = pruneToolResult("00: aa\n00: bb", { tool: "i2cdump" });
expect(res.preservedAddrs).toEqual(["00"]);
});
it("边界·general 单行 maxLines=1 → 保留首行", () => {
const res = pruneToolResult("only line", { tool: "general", maxLines: 1 });
expect(res.pruned).toBe("only line");
expect(res.dropped).toBe(0);
});
});
describe("compaction tool-result-pruner — 对抗/fuzz(畸形 maxLines/特殊字符/边界 addr)", () => {
it("fuzz·general maxLines=NaN → slice(0,NaN)=[] → 全丢", () => {
const res = pruneToolResult("a\nb\nc", { tool: "general", maxLines: NaN });
expect(res.pruned).toBe("");
expect(res.dropped).toBe(3);
});
it("fuzz·i2cdump 含 0x 但无冒号 → 不算地址行", () => {
const res = pruneToolResult("0x50 no colon here\ntail", { tool: "i2cdump" });
expect(res.preservedAddrs).toEqual([]);
expect(res.pruned.length).toBeGreaterThan(0);
});
it("fuzz·i2cdump 5 位 hex 前缀不匹配({1,4} 上界): 'abcde: x' → 非地址", () => {
const res = pruneToolResult("abcde: x\ntail", { tool: "i2cdump" });
expect(res.preservedAddrs).toEqual([]);
});
it("fuzz·gdb 帧号超长 '#99999 frame' → 仍算帧", () => {
const res = pruneToolResult("noise\n#99999 frame", { tool: "gdb" });
expect(res.pruned).toBe("#99999 frame");
});
it("fuzz·dmesg 大小写不敏感: 'ERROR' 与 'Warning' 均匹配", () => {
const res = pruneToolResult(
"[1] ERROR here\n[2] Warning there\n[3] benign",
{ tool: "dmesg" },
);
expect(res.pruned).toContain("ERROR here");
expect(res.pruned).toContain("Warning there");
expect(res.pruned).not.toContain("benign");
});
it("fuzz·dmesg 级别 <5> 不在 [0-4] 范围 → 不算 severe", () => {
const res = pruneToolResult("[1] <5> info notice\n[2] <4> warn line", {
tool: "dmesg",
});
expect(res.pruned).not.toContain("<5> info");
expect(res.pruned).toContain("<4> warn line");
});
});
describe("compaction tool-result-pruner — 元蜕变/不变式(dropped 恒等式 + 不创造新行)", () => {
it("不变式·dropped === lines.length - preservedLines 对四类工具", () => {
const samples = [
{ content: I2CDUMP_SAMPLE, opts: { tool: "i2cdump" } as PruneOptions },
{
content: "noise\n#0 f\n#1 g\ntail",
opts: { tool: "gdb" } as PruneOptions,
},
{
content: "[1] ok\n<3> err\n[2] warn word\nfine",
opts: { tool: "dmesg" } as PruneOptions,
},
{
content: "a\nb\nc\nd\ne",
opts: { tool: "general", maxLines: 2 } as PruneOptions,
},
];
for (const { content, opts } of samples) {
const res = pruneToolResult(content, opts);
const lines = content.length === 0 ? [""] : content.split("\n");
const preservedLines =
res.pruned.length === 0 ? 0 : res.pruned.split("\n").length;
expect(res.dropped).toBe(lines.length - preservedLines);
}
});
it("不变式·pruned 保留行均来自原文(不创造新行)", () => {
const res = pruneToolResult(I2CDUMP_SAMPLE, { tool: "i2cdump" });
const originalLines = new Set(I2CDUMP_SAMPLE.split("\n"));
for (const line of res.pruned.split("\n")) {
expect(originalLines.has(line)).toBe(true);
}
});
});
// ============================================================================
// tool-result-pruner — 变异测试 kill-tests
// ============================================================================
describe("compaction tool-result-pruner — 变异测试 kill-tests", () => {
it("B2 kill: general maxLines 截断 dropped=3(真实=3;bug +1 off-by-one dropped=2 偏离)", () => {
const content = "a\nb\nc\nd\ne"; // 5 行
const correctDropped = 3; // maxLines=2 → 保留 2 行,丢 3 行
// (a) 真实代码正确
expect(pruneToolResult(content, { tool: "general", maxLines: 2 }).dropped).toBe(
correctDropped,
);
// (b) bug 副本偏离正确
expect(pruneGeneralB2(content, 2).dropped).not.toBe(correctDropped);
// (c) 若真实被此 bug 污染,正确性断言会 FAIL
expect(() =>
expect(pruneGeneralB2(content, 2).dropped).toBe(correctDropped),
).toThrow();
});
it("B3 kill: i2cdump 末行非地址补入(真实含 tail;bug 漏 tail 偏离)", () => {
const content = "00: aa\ntail-no-addr";
// (a) 真实代码保留 tail
expect(pruneToolResult(content, { tool: "i2cdump" }).pruned).toContain(
"tail-no-addr",
);
// (b) bug 副本不含 tail
expect(pruneI2cB3(content).pruned).not.toContain("tail-no-addr");
// (c) 若真实被此 bug 污染,正确性断言会 FAIL
expect(() =>
expect(pruneI2cB3(content).pruned).toContain("tail-no-addr"),
).toThrow();
});
});
// ============================================================================
// ③ summarizer — 等价类 + 边界 + 状态/预算 + fuzz + 不变式
// ============================================================================
describe("compaction summarizer — 等价类划分(前缀/entries/预算)", () => {
it("等价类·非空前缀+有 entries+预算充足: reusedPrefix=true,含前缀+指令+摘要", () => {
const res = buildCompactionSummary({
prefix: "已初始化 i2c-0,地址 0x50。",
recentEntries: [
{ type: "tool-result", data: { name: "i2cdump", rows: 4 } },
{ type: "user-message", data: { role: "user", content: "读 0x50" } },
],
maxTokens: 2000,
});
expect(res.reusedPrefix).toBe(true);
expect(res.summary).toContain("已初始化 i2c-0");
expect(res.summary).toContain("## Compaction Summary");
expect(res.summary).toContain("tool-result");
expect(res.summary).toContain("user-message");
expect(res.droppedEntries).toBe(2);
});
it("等价类·空前缀+有 entries: reusedPrefix=false(冷启动)", () => {
const res = buildCompactionSummary({
prefix: "",
recentEntries: [{ type: "tool-call", data: { name: "gpioget" } }],
maxTokens: 2000,
});
expect(res.reusedPrefix).toBe(false);
expect(res.droppedEntries).toBe(1);
});
it("等价类·空白前缀(空格/tab): trim 后空 → reusedPrefix=false", () => {
const res = buildCompactionSummary({
prefix: " \n\t ",
recentEntries: [{ type: "x", data: 1 }],
maxTokens: 2000,
});
expect(res.reusedPrefix).toBe(false);
});
it("等价类·非空前缀+零 entries: 含前缀+指令(0 entries),droppedEntries=0", () => {
const res = buildCompactionSummary({
prefix: "prefix-stable",
recentEntries: [],
maxTokens: 2000,
});
expect(res.reusedPrefix).toBe(true);
expect(res.summary).toContain("0 recent entries compacted");
expect(res.droppedEntries).toBe(0);
});
});
describe("compaction summarizer — 边界值分析(预算临界、单 entry、空 entries)", () => {
it("边界·maxTokens 极小(1): base 自身超预算,无摘要行,droppedEntries 仍 = entries 数", () => {
const res = buildCompactionSummary({
prefix: "prefix",
recentEntries: [{ type: "t", data: { x: 1 } }],
maxTokens: 1,
});
expect(res.droppedEntries).toBe(1);
expect(res.summary).toContain("prefix");
});
it("边界·单 entry + 预算充足: 该 entry 摘要保留", () => {
const res = buildCompactionSummary({
prefix: "p",
recentEntries: [{ type: "tool-result", data: { name: "i2cdump" } }],
maxTokens: 2000,
});
expect(res.summary).toContain("i2cdump");
});
it("边界·零 entries: summary 仅 base,droppedEntries=0", () => {
const res = buildCompactionSummary({
prefix: "p",
recentEntries: [],
maxTokens: 100,
});
expect(res.droppedEntries).toBe(0);
expect(res.summary).toContain("## Compaction Summary");
});
it("边界·maxTokens 恰好容下单 entry(不裁剪): entry 出现在 summary", () => {
const entry = { type: "t", data: { i: 7 } };
const probe = buildCompactionSummary({
prefix: "",
recentEntries: [entry],
maxTokens: 2000,
});
const needed = estimateTokens(probe.summary);
// 给刚好足够的预算,entry 仍保留
const res = buildCompactionSummary({
prefix: "",
recentEntries: [entry],
maxTokens: needed,
});
expect(res.summary).toContain('"i":7');
});
});
describe("compaction summarizer — 状态转换/预算裁剪(最旧丢弃、前缀不裁)", () => {
it("状态·超预算: 优先丢最旧摘要行、保留最新;前缀永不裁剪", () => {
const prefix = "P".repeat(20); // 5 token
const entries = Array.from({ length: 50 }, (_, i) => ({
type: "tool-result",
data: { idx: i, payload: "X".repeat(60) },
}));
const res = buildCompactionSummary({
prefix,
recentEntries: entries,
maxTokens: 50,
});
expect(res.reusedPrefix).toBe(true);
expect(res.summary.startsWith(prefix)).toBe(true);
expect(res.summary).toContain('"idx":49');
expect(res.summary).not.toContain('"idx":0');
});
it("状态·预算刚好容下全部: 无裁剪,全部 entries 出现在 summary", () => {
const entries = [
{ type: "a", data: { i: 1 } },
{ type: "b", data: { i: 2 } },
{ type: "c", data: { i: 3 } },
];
const res = buildCompactionSummary({
prefix: "p",
recentEntries: entries,
maxTokens: 2000,
});
expect(res.summary).toContain('"i":1');
expect(res.summary).toContain('"i":2');
expect(res.summary).toContain('"i":3');
});
it("状态·部分裁剪: 中间预算只丢部分最旧,保留最新 N 条", () => {
const entries = Array.from({ length: 10 }, (_, i) => ({
type: "t",
data: { idx: i, p: "X".repeat(40) },
}));
const res = buildCompactionSummary({
prefix: "",
recentEntries: entries,
maxTokens: 80,
});
expect(res.summary).toContain('"idx":9');
expect(res.summary).not.toContain('"idx":0');
});
});
describe("compaction summarizer — 对抗/fuzz(循环引用/超长 data/单字符前缀)", () => {
it("fuzz·data 含循环引用: digestEntry fail-soft 退回 [unserializable]", () => {
const cyclic: any = { name: "x" };
cyclic.self = cyclic;
const res = buildCompactionSummary({
prefix: "p",
recentEntries: [{ type: "tool-result", data: cyclic }],
maxTokens: 2000,
});
expect(res.summary).toContain("[unserializable]");
});
it("fuzz·超长 data: 截断到 120 字符 + 省略号", () => {
const longData = { blob: "0".repeat(500) };
const res = buildCompactionSummary({
prefix: "p",
recentEntries: [{ type: "t", data: longData }],
maxTokens: 5000,
});
expect(res.summary).toContain("…");
expect(res.summary).not.toContain("0".repeat(500));
});
it("fuzz·单字符前缀 'P': trim 非空 → reusedPrefix=true", () => {
const res = buildCompactionSummary({
prefix: "P",
recentEntries: [],
maxTokens: 100,
});
expect(res.reusedPrefix).toBe(true);
});
});
describe("compaction summarizer — 元蜕变/不变式(确定性 + 前缀恒在 + 计数恒等)", () => {
it("不变式·buildCompactionSummary 确定性: 同输入多次调用恒同 summary", () => {
const opts = {
prefix: "stable prefix",
recentEntries: [
{ type: "t", data: { a: 1 } },
{ type: "u", data: { b: 2 } },
],
maxTokens: 500,
};
const a = buildCompactionSummary(opts);
const b = buildCompactionSummary(opts);
expect(a.summary).toBe(b.summary);
expect(a.reusedPrefix).toBe(b.reusedPrefix);
expect(a.droppedEntries).toBe(b.droppedEntries);
});
it("不变式·非空前缀始终出现在 summary 里(无论预算多紧)", () => {
const res = buildCompactionSummary({
prefix: "must-survive",
recentEntries: Array.from({ length: 100 }, (_, i) => ({
type: "t",
data: { i, p: "X".repeat(50) },
})),
maxTokens: 10,
});
expect(res.summary).toContain("must-survive");
});
it("不变式·droppedEntries === recentEntries.length 恒成立", () => {
for (const n of [0, 1, 5, 50]) {
const res = buildCompactionSummary({
prefix: "p",
recentEntries: Array.from({ length: n }, (_, i) => ({
type: "t",
data: i,
})),
maxTokens: 2000,
});
expect(res.droppedEntries).toBe(n);
}
});
});
// ============================================================================
// summarizer — 变异测试 kill-test
// ============================================================================
describe("compaction summarizer — 变异测试 kill-test", () => {
it("B4 kill: 超预算丢最旧保最新(真实含 idx49;bug pop 丢 idx49 偏离)", () => {
const prefix = "P".repeat(20);
const entries = Array.from({ length: 50 }, (_, i) => ({
type: "tool-result",
data: { idx: i, payload: "X".repeat(60) },
}));
// (a) 真实代码保留最新 idx49
const real = buildCompactionSummary({ prefix, recentEntries: entries, maxTokens: 50 });
expect(real.summary).toContain('"idx":49');
// (b) bug 副本丢最新 idx49
const bugged = buildCompactionSummaryB4({ prefix, recentEntries: entries, maxTokens: 50 });
expect(bugged.summary).not.toContain('"idx":49');
// (c) 若真实被此 bug 污染,正确性断言会 FAIL
expect(() =>
expect(buildCompactionSummaryB4({ prefix, recentEntries: entries, maxTokens: 50 }).summary).toContain('"idx":49'),
).toThrow();
});
});
// ============================================================================
// ④ spill — 等价类 + 边界 + 状态转换 + fuzz + 不变式
// ============================================================================
describe("compaction spill — 等价类划分(spill/recall/has/evict)", () => {
it("等价类·spill→recall round-trip: 取回原数据 + has 反映存活", () => {
const store = new SpillStore();
const big = { page: "datasheet rmii chapter", text: "0".repeat(5000) };
const loc = store.spill("datasheet:rmii", big);
expect(store.has(loc)).toBe(true);
expect(store.recall(loc)).toEqual(big);
});
it("等价类·recall 未知 locator → undefined(fail-closed)", () => {
const store = new SpillStore();
store.spill("k", { v: 1 });
const fake = "pba-spill:nonexistent:99" as SpillLocator;
expect(store.recall(fake)).toBeUndefined();
expect(store.has(fake)).toBe(false);
});
it("等价类·evict 无参: 清空全部 + 返回被清条数", () => {
const store = new SpillStore();
store.spill("a", 1);
store.spill("b", 2);
store.spill("c", 3);
expect(store.evict()).toBe(3);
expect(store.evict()).toBe(0);
});
it("等价类·evict 阈值: 回收大 blob,小 blob 保留", () => {
const store = new SpillStore();
store.spill("small", { x: 1 });
store.spill("big", { x: "0".repeat(500) });
store.spill("mid", { x: "0".repeat(250) });
const evicted = store.evict(200);
expect(evicted).toBe(2);
expect(store.has("pba-spill:small:1" as SpillLocator)).toBe(true);
});
});
describe("compaction spill — 边界值分析(同 key 多次/阈值边界/空 store)", () => {
it("边界·同 key 多次 spill: 返不同 locator,各可 recall", () => {
const store = new SpillStore();
const a = store.spill("i2c", { n: 1 });
const b = store.spill("i2c", { n: 2 });
expect(a).not.toBe(b);
expect(a).toBe("pba-spill:i2c:1");
expect(b).toBe("pba-spill:i2c:2");
expect(store.recall(a)).toEqual({ n: 1 });
expect(store.recall(b)).toEqual({ n: 2 });
});
it("边界·空 store evict(): 返回 0", () => {
expect(new SpillStore().evict()).toBe(0);
});
it("边界·空 store evict(100): 返回 0", () => {
expect(new SpillStore().evict(100)).toBe(0);
});
it("边界·locator 格式: pba-spill:{key}:{seq}", () => {
const store = new SpillStore();
expect(store.spill("datasheet:rmii", { x: 1 })).toBe(
"pba-spill:datasheet:rmii:1",
);
});
it("边界·evict(0): 回收所有 bytes>0 的条目", () => {
const store = new SpillStore();
store.spill("a", "x"); // '"x"' → 3 bytes > 0
store.spill("b", "yy"); // '"yy"' → 4 bytes > 0
expect(store.evict(0)).toBe(2);
});
it("边界·evict 阈值恰等于某条目 bytes: 该条目保留(> 而非 >=)", () => {
const store = new SpillStore();
store.spill("exact", { x: 1 }); // {"x":1} → 7 bytes
const evicted = store.evict(7); // bytes > 7 → 7 不 > 7 → 保留
expect(evicted).toBe(0);
expect(store.has("pba-spill:exact:1" as SpillLocator)).toBe(true);
});
it("边界·evict 阈值 = bytes-1: 恰大于阈值的条目被回收", () => {
const store = new SpillStore();
store.spill("exact", { x: 1 }); // 7 bytes
expect(store.evict(6)).toBe(1); // 7 > 6 → 回收
expect(store.has("pba-spill:exact:1" as SpillLocator)).toBe(false);
});
});
describe("compaction spill — 状态转换(存活/回收 + 重入 + 不可达 + 单调续号)", () => {
it("状态·spill→存活→evict→不存活: has 状态正确迁移", () => {
const store = new SpillStore();
const loc = store.spill("k", { v: 1 });
expect(store.has(loc)).toBe(true);
store.evict();
expect(store.has(loc)).toBe(false);
expect(store.recall(loc)).toBeUndefined();
});
it("状态·evict 后同 key 再 spill: seqByKey 不清 → seq 单调续号,旧 locator 仍 fail-closed", () => {
const store = new SpillStore();
const a = store.spill("k", 1); // pba-spill:k:1
store.evict(); // 清 store,不清 seqByKey
const b = store.spill("k", 2); // seq 续号 → pba-spill:k:2
expect(b).toBe("pba-spill:k:2");
expect(store.has(b)).toBe(true);
expect(store.recall(b)).toBe(2);
expect(store.has(a)).toBe(false);
expect(store.recall(a)).toBeUndefined();
});
it("状态·部分 evict 后存活条目仍可 recall(不影响存活条)", () => {
const store = new SpillStore();
const small = store.spill("small", { x: 1 });
const big = store.spill("big", { x: "0".repeat(500) });
store.evict(200);
expect(store.has(big)).toBe(false);
expect(store.has(small)).toBe(true);
expect(store.recall(small)).toEqual({ x: 1 });
});
it("状态·recall 不改状态(只读):多次 recall 同 locator 恒同结果", () => {
const store = new SpillStore();
const loc = store.spill("k", { v: 42 });
expect(store.recall(loc)).toEqual({ v: 42 });
expect(store.recall(loc)).toEqual({ v: 42 });
expect(store.has(loc)).toBe(true);
});
it("状态·不可达: 已 evict 的 locator 字符串不被同 key 再 spill 复用", () => {
const store = new SpillStore();
const a = store.spill("k", "first");
store.evict();
const b = store.spill("k", "second");
// a 的字符串 "pba-spill:k:1" 不应再被发放(b 用新 seq 2)
expect(a).not.toBe(b);
expect(store.recall(a)).toBeUndefined();
expect(store.recall(b)).toBe("second");
});
});
describe("compaction spill — 对抗/fuzz(null/undefined/巨大/循环/空 key)", () => {
it("fuzz·spill null data: 不抛,recall 返 null", () => {
const store = new SpillStore();
const loc = store.spill("k", null);
expect(store.recall(loc)).toBeNull();
});
it("fuzz·spill undefined data: fail-soft 不抛(typeof 守卫)", () => {
const store = new SpillStore();
expect(() => store.spill("k", undefined)).not.toThrow();
const loc = store.spill("k", undefined);
expect(store.has(loc)).toBe(true);
expect(store.recall(loc)).toBeUndefined();
});
it("fuzz·spill 循环引用对象: measureBytes fail-soft 不抛", () => {
const store = new SpillStore();
const cyclic: any = { a: 1 };
cyclic.self = cyclic;
expect(() => store.spill("k", cyclic)).not.toThrow();
});
it("fuzz·spill 巨大对象 (100KB): 不抛,bytes 正确度量", () => {
const store = new SpillStore();
const big = { text: "0".repeat(100000) };
const loc = store.spill("big", big);
expect(store.recall(loc)).toEqual(big);
expect(store.has(loc)).toBe(true);
});
it("fuzz·spill 空字符串 key: locator 格式正常", () => {
const store = new SpillStore();
const loc = store.spill("", { v: 1 });
expect(loc).toBe("pba-spill::1");
expect(store.recall(loc)).toEqual({ v: 1 });
});
it("fuzz·spill 数字 key: key 被字符串化进 locator", () => {
const store = new SpillStore();
expect(store.spill(123 as any, { v: 1 })).toBe("pba-spill:123:1");
});
it("fuzz·evict 负阈值: 所有 bytes > 负数 → 全回收", () => {
const store = new SpillStore();
store.spill("a", 1);
store.spill("b", 2);
expect(store.evict(-1)).toBe(2);
});
});
describe("compaction spill — 元蜕变/不变式(brand 不可伪造/单调 deny/fail-closed)", () => {
it("不变式·brand 不可伪造: 外部构造的 locator recall 返 undefined", () => {
const store = new SpillStore();
store.spill("real", { v: 1 });
const forged = "pba-spill:real:999" as SpillLocator;
expect(store.recall(forged)).toBeUndefined();
expect(store.has(forged)).toBe(false);
});
it("不变式·recall 单调 deny: 未发放/已回收的 locator 恒返 undefined", () => {
const store = new SpillStore();
const loc = store.spill("k", 1);
store.evict();
expect(store.recall(loc)).toBeUndefined();
expect(store.recall(loc)).toBeUndefined();
});
it("不变式·spill→recall 等价: 取回的数据 === 存入的数据", () => {
const store = new SpillStore();
const data = { nested: { a: [1, 2, { b: "c" }] } };
const loc = store.spill("k", data);
expect(store.recall(loc)).toEqual(data);
});
it("不变式·evict 返回值 = 实际被回收条数", () => {
const store = new SpillStore();
store.spill("a", "1");
store.spill("b", "2");
store.spill("c", "3");
expect(store.evict()).toBe(3);
expect(store.evict()).toBe(0);
});
it("元蜕变·append 两次=replay 等价: 两次 spill 同 key 同数据 → 各自 recall 等价", () => {
const store = new SpillStore();
const data = { v: 42, arr: [1, 2, 3] };
const loc1 = store.spill("k", data);
const loc2 = store.spill("k", data);
expect(store.recall(loc1)).toEqual(store.recall(loc2));
expect(store.recall(loc1)).toEqual(data);
});
it("fail-closed 不变式·unusable spill locator 一律拒: 未发放/已 evict/伪造 均 undefined", () => {
const store = new SpillStore();
const loc = store.spill("k", 1);
store.evict();
const forged = "pba-spill:k:1" as SpillLocator;
const neverIssued = "pba-spill:k:999" as SpillLocator;
expect(store.recall(forged)).toBeUndefined();
expect(store.recall(neverIssued)).toBeUndefined();
expect(store.has(forged)).toBe(false);
expect(store.has(neverIssued)).toBe(false);
});
});
// ============================================================================
// spill — 变异测试 kill-tests
// ============================================================================
describe("compaction spill — 变异测试 kill-tests", () => {
it("B5 kill: evict 恰等于阈值的条目保留(真实保留;bug >= 误回收 偏离)", () => {
const store = new SpillStore();
store.spill("exact", { x: 1 }); // 7 bytes
const realEvicted = store.evict(7); // bytes > 7 → 保留
expect(realEvicted).toBe(0);
// bug 副本: bytes >= 7 → 误回收
const bstore = makeSpillStoreB5();
bstore.spill("exact", { x: 1 });
const buggedEvicted = bstore.evict(7);
expect(buggedEvicted).toBe(1); // bug 误回收
expect(buggedEvicted).not.toBe(realEvicted);
// (c) 若真实被此 bug 污染,正确性断言会 FAIL(用全新 bug store 避免排空误判)
const bstore2 = makeSpillStoreB5();
bstore2.spill("exact", { x: 1 });
expect(() => expect(bstore2.evict(7)).toBe(realEvicted)).toThrow();
});
it("B6 kill: 同 key 多次 spill 返不同 locator(真实 a≠b;bug a===b 偏离)", () => {
const store = new SpillStore();
const a = store.spill("k", 1);
const b = store.spill("k", 2);
expect(a).not.toBe(b);
// bug 副本: 固定 seq=1 → a===b
const bstore = makeSpillStoreB6();
const ba = bstore.spill("k", 1);
const bb = bstore.spill("k", 2);
expect(ba).toBe(bb);
expect(() => expect(ba).not.toBe(bb)).toThrow();
});
});
// ============================================================================
// 跨模块元蜕变/不变式(append 两次=replay 等价、waterfall 不调 next=短路、
// fail-closed unusable=拒、pruner↔summarizer 兼容)
// ============================================================================
describe("compaction 跨模块 — 元蜕变/不变式", () => {
it("不变式·summarizer 用 token-meter 估算预算: summary token ≤ maxTokens(base+摘要)", () => {
const res = buildCompactionSummary({
prefix: "P".repeat(20),
recentEntries: Array.from({ length: 30 }, (_, i) => ({
type: "t",
data: { idx: i, p: "X".repeat(60) },
})),
maxTokens: 60,
});
expect(estimateTokens(res.summary)).toBeLessThanOrEqual(60);
});
it("不变式·pruner 与 summarizer 兼容: pruned 内容可作 summarizer entry data", () => {
const pruned = pruneToolResult(I2CDUMP_SAMPLE, { tool: "i2cdump" });
const res = buildCompactionSummary({
prefix: "p",
recentEntries: [{ type: "tool-result", data: pruned.pruned }],
maxTokens: 2000,
});
expect(res.summary).toContain("00: 00 01");
expect(res.droppedEntries).toBe(1);
});
it("不变式·spill locator 当作 summarizer data 不影响 spill store(brand 隔离)", () => {
const store = new SpillStore();
const realLoc = store.spill("k", { v: 1 });
const res = buildCompactionSummary({
prefix: "p",
recentEntries: [{ type: "locator-as-data", data: realLoc }],
maxTokens: 2000,
});
expect(res.summary).toContain("locator-as-data");
expect(store.recall(realLoc)).toEqual({ v: 1 });
});
it("waterfall 不调 next=短路: pruner 空 pruned 喂 summarizer 仍出合法 summary", () => {
const empty = pruneToolResult("", { tool: "general" });
const res = buildCompactionSummary({
prefix: "p",
recentEntries: [{ type: "tool-result", data: empty.pruned }],
maxTokens: 2000,
});
expect(res.summary).toContain("## Compaction Summary");
expect(res.droppedEntries).toBe(1);
});
it("元蜕变·append 两次=replay 等价: 两次 spill 同 key 同数据 → 两个 locator 各自 recall 等价", () => {
const store = new SpillStore();
const data = { v: 42, arr: [1, 2, 3] };
const loc1 = store.spill("k", data);
const loc2 = store.spill("k", data);
expect(store.recall(loc1)).toEqual(store.recall(loc2));
expect(store.recall(loc1)).toEqual(data);
});
it("fail-closed 不变式·unusable spill locator 一律拒: 未发放/已 evict/伪造 均 undefined", () => {
const store = new SpillStore();
const loc = store.spill("k", 1);
store.evict();
const forged = "pba-spill:k:1" as SpillLocator;
const neverIssued = "pba-spill:k:999" as SpillLocator;
expect(store.recall(forged)).toBeUndefined();
expect(store.recall(neverIssued)).toBeUndefined();
expect(store.has(forged)).toBe(false);
expect(store.has(neverIssued)).toBe(false);
});
});
// ============================================================================
// 变异测试总览:确认真实(未植入 bug)代码全过 + 每个 bug 被某测试杀死
// ============================================================================
describe("compaction 变异测试 — 总览(6 个 seeded bug 全被杀)", () => {
it("文档化: B1-B6 每个 bug 都被对应 kill-test 杀死(带 bug 副本偏离正确 → 正确性断言套 bug 抛)", () => {
// B1: estimateTokens floor 替 ceil → kill: 'abcde' 真实=2,bug=1
expect(estimateTokens("abcde")).toBe(2);
expect(estimateTokensB1("abcde")).toBe(1);
expect(() => expect(estimateTokensB1("abcde")).toBe(2)).toThrow();
// B2: general off-by-one +1 → kill: 5 行 maxLines=2 真实 dropped=3,bug=2
expect(pruneToolResult("a\nb\nc\nd\ne", { tool: "general", maxLines: 2 }).dropped).toBe(3);
expect(pruneGeneralB2("a\nb\nc\nd\ne", 2).dropped).toBe(2);
expect(() => expect(pruneGeneralB2("a\nb\nc\nd\ne", 2).dropped).toBe(3)).toThrow();
// B3: i2cdump 漏 tail 补入 → kill: '00: aa\ntail' 真实含 tail,bug 不含
expect(pruneToolResult("00: aa\ntail-no-addr", { tool: "i2cdump" }).pruned).toContain("tail-no-addr");
expect(pruneI2cB3("00: aa\ntail-no-addr").pruned).not.toContain("tail-no-addr");
expect(() => expect(pruneI2cB3("00: aa\ntail-no-addr").pruned).toContain("tail-no-addr")).toThrow();
// B4: summarizer pop 丢最新 → kill: 超预算真实保留 idx49,bug 丢 idx49
const entries = Array.from({ length: 50 }, (_, i) => ({
type: "tool-result",
data: { idx: i, payload: "X".repeat(60) },
}));
expect(buildCompactionSummary({ prefix: "P".repeat(20), recentEntries: entries, maxTokens: 50 }).summary).toContain('"idx":49');
expect(buildCompactionSummaryB4({ prefix: "P".repeat(20), recentEntries: entries, maxTokens: 50 }).summary).not.toContain('"idx":49');
// B5: spill evict >= → kill: 7 bytes 恰等于阈值真实保留(evict=0),bug 误回收(=1)
const s5 = new SpillStore();
s5.spill("e", { x: 1 });
expect(s5.evict(7)).toBe(0);
const bs5 = makeSpillStoreB5();
bs5.spill("e", { x: 1 });
expect(bs5.evict(7)).toBe(1);
// B6: spill 漏 seq 自增 → kill: 同 key 多次真实 a≠b,bug a===b
const s6 = new SpillStore();
expect(s6.spill("k", 1)).not.toBe(s6.spill("k", 2));
const bs6 = makeSpillStoreB6();
expect(bs6.spill("k", 1)).toBe(bs6.spill("k", 2));
});
});