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

1321 lines
51 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.

/**
* capabilities-misc 完整测试套件 —— T17(approval + credentials + settings + lsp)。
*
* 被测模块均为纯逻辑(零 pi 依赖、无硬件、无网络),可直接 import 命名导出。
* 唯一可注入依赖是 CredentialsStore 的 envLookup;approval 的计时器用
* vi.useFakeTimers() 注入控制。无 appendEntry/exec/emitter/runTsc/readFile 依赖
* (这四个模块设计上不触碰它们)。
*
* 应用的测试方法论(每个 describe 块以【方法论】标签标注):
* - 等价类划分(有效/无效/边界类)
* - 边界值分析(off-by-one、空、单元素、min/max)
* - 决策表(组合输入→期望,覆盖全分支)
* - 状态转换(mode + approver 注册/注销迁移 + 重入 + 不可达状态兜底)
* - 变异测试:6 个 seeded bug 内联副本,每个断言被某测试杀死(植入后该测试失败=被杀)
* - 对抗/fuzz:null/undefined/巨大/NaN/负 timeout/并发重入
* - 元蜕变/不变式:fail-closed 单调 deny、freeze→篡改抛 TypeError、
* redact 不残留明文、snapshot 副本隔离内部状态、waterfall 不调 next=短路
*
* 门:
* 1. 真实代码全绿(npx vitest run tests/capabilities-misc.test.ts)
* 2. 每个 seeded bug 变体内联副本断言被某测试杀死(buggyResult ≠ correctResult → 杀)
*
* 见架构设计文档 §6.1 T17。
*/
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import {
ApprovalGate,
DEFAULT_APPROVAL_MODE,
type ApprovalMode,
type ApprovalRequest,
type ApprovalResult,
type ApproverFn,
} from "../src/capabilities/approval.js";
import {
CredentialsStore,
REDACTED_PLACEHOLDER,
} from "../src/capabilities/credentials.js";
import { SettingsStore } from "../src/capabilities/settings.js";
import {
NoopLspBridge,
type LspBridge,
type LspInitOptions,
} from "../src/capabilities/lsp.js";
// ----------------------------------------------------------------------------
// 共用工厂
// ----------------------------------------------------------------------------
/** 立即 approver:按 decision 字面量返回。 */
function makeApprover(
decision: "approve" | "deny",
reason = "mock",
): ApproverFn {
return async (): Promise<ApprovalResult> => ({
decision,
reason,
by: "approver",
});
}
/** 慢 approver:延迟 delayMs 后 resolve(配合 fake timers)。 */
function makeSlowApprover(
delayMs: number,
decision: "approve" | "deny" = "approve",
): ApproverFn {
return () =>
new Promise<ApprovalResult>((resolve) =>
setTimeout(
() => resolve({ decision, reason: "late", by: "approver" }),
delayMs,
),
);
}
/** 记录是否被调用的 approver(用于短路断言)。 */
function makeRecordingApprover(
decision: "approve" | "deny" = "approve",
): { fn: ApproverFn; called: () => boolean } {
let called = false;
return {
fn: async (): Promise<ApprovalResult> => {
called = true;
return { decision, reason: "rec", by: "approver" };
},
called: () => called,
};
}
// ============================================================================
// 【等价类划分】approval —— 三模式有效类 + 未知/缺省无效类
// ============================================================================
describe("【等价类划分】approval mode 有效/无效类", () => {
it("auto-deny 类:任意 risk/action/context 一律 deny by auto", async () => {
const gate = new ApprovalGate({ mode: "auto-deny" });
const reqs: ApprovalRequest[] = [
{ action: "flash", risk: "high" },
{ action: "devmem-write", risk: "low", context: "0x40020000" },
{ action: "dd", risk: "medium" },
{ action: "rm", risk: "high", context: "/lib" },
];
for (const req of reqs) {
const r = await gate.request(req);
expect(r.decision).toBe("deny");
expect(r.by).toBe("auto");
expect(r.reason).toContain("auto-deny");
}
});
it("auto-approve 类:任意请求 approve by auto,reason 固定", async () => {
const gate = new ApprovalGate({ mode: "auto-approve" });
for (const req of [
{ action: "read", risk: "low" },
{ action: "flash", risk: "high" },
] as ApprovalRequest[]) {
const r = await gate.request(req);
expect(r).toMatchObject({ decision: "approve", by: "auto" });
expect(r.reason).toBe("auto-approve mode");
}
});
it("interactive 有效类:有 approver → approver 裁决透传(approve/deny 均可)", async () => {
for (const decision of ["approve", "deny"] as const) {
const gate = new ApprovalGate({ mode: "interactive" });
gate.registerApprover(makeApprover(decision, `mock-${decision}`));
const r = await gate.request({ action: "flash", risk: "high" });
expect(r.decision).toBe(decision);
expect(r.by).toBe("approver");
expect(r.reason).toBe(`mock-${decision}`);
}
});
it("无效类:未知 mode 一律按 fail-closed deny(含 'zzz'/'AUTO-DENY' 大写/'deny'/'')", async () => {
const gate = new ApprovalGate();
// 默认就是 auto-deny
expect(DEFAULT_APPROVAL_MODE).toBe<ApprovalMode>("auto-deny");
for (const m of ["zzz", "AUTO-DENY", "deny", ""] as unknown as ApprovalMode[]) {
gate.setMode(m);
const r = await gate.request({ action: "x", risk: "low" });
expect(r.decision).toBe("deny");
expect(r.by).toBe("auto");
expect(r.reason).toContain("auto-deny");
}
});
it("缺省类:不传 opts → 默认 auto-deny(fail-closed 无人值守默认)", async () => {
const gate = new ApprovalGate();
const r = await gate.request({ action: "flash", risk: "high" });
expect(r).toMatchObject({ decision: "deny", by: "auto" });
});
it("DEFAULT_APPROVAL_MODE 常量值=auto-deny(下游契约不得改名)", () => {
expect(DEFAULT_APPROVAL_MODE).toBe("auto-deny");
});
});
// ============================================================================
// 【边界值分析】approval timeout —— 优先级、off-by-one、0、负、NaN、缺省
// ============================================================================
describe("【边界值分析】approval timeout 优先级与边界", () => {
beforeEach(() => vi.useFakeTimers());
afterEach(() => vi.useRealTimers());
it("req.timeoutMs > 构造 timeoutMs(更短者):用 req → timeout deny", async () => {
const gate = new ApprovalGate({ mode: "interactive", timeoutMs: 10_000 });
gate.registerApprover(makeSlowApprover(10_000, "approve"));
const p = gate.request({ action: "flash", risk: "high", timeoutMs: 50 });
vi.advanceTimersByTime(50);
const r = await p;
expect(r).toMatchObject({ decision: "deny", by: "timeout" });
expect(r.reason).toContain("50ms");
});
it("构造 timeoutMs 生效(缺 req.timeoutMs)→ timeout deny", async () => {
const gate = new ApprovalGate({ mode: "interactive", timeoutMs: 30 });
gate.registerApprover(makeSlowApprover(10_000));
const p = gate.request({ action: "flash", risk: "high" });
vi.advanceTimersByTime(30);
const r = await p;
expect(r).toMatchObject({ decision: "deny", by: "timeout" });
expect(r.reason).toContain("30ms");
});
it("DEFAULT_TIMEOUT_MS 兜底(两者均缺省=10000)", async () => {
const gate = new ApprovalGate({ mode: "interactive" });
gate.registerApprover(makeSlowApprover(10_010));
const p = gate.request({ action: "flash", risk: "high" });
vi.advanceTimersByTime(10_000);
const r = await p;
expect(r).toMatchObject({ decision: "deny", by: "timeout" });
expect(r.reason).toContain("10000ms");
});
it("approver 先于超时 resolve → approver 裁决胜出(边界:恰好不超时)", async () => {
const gate = new ApprovalGate({ mode: "interactive", timeoutMs: 100 });
gate.registerApprover(makeSlowApprover(10, "approve"));
const p = gate.request({ action: "flash", risk: "high" });
vi.advanceTimersByTime(10);
const r = await p;
expect(r).toMatchObject({ decision: "approve", by: "approver" });
});
it("timeoutMs=0 边界:req 显式 0 → 立即超时 deny(0 非 null/undefined)", async () => {
const gate = new ApprovalGate({ mode: "interactive", timeoutMs: 10_000 });
gate.registerApprover(makeSlowApprover(10_000));
const p = gate.request({ action: "flash", risk: "high", timeoutMs: 0 });
vi.advanceTimersByTime(1);
const r = await p;
expect(r.by).toBe("timeout");
expect(r.decision).toBe("deny");
});
it("负 timeoutMs 边界:setTimeout 视同 0 → 仍 timeout deny(不报错)", async () => {
const gate = new ApprovalGate({ mode: "interactive", timeoutMs: 10_000 });
gate.registerApprover(makeSlowApprover(10_000));
const p = gate.request({ action: "flash", risk: "high", timeoutMs: -5 });
vi.advanceTimersByTime(1);
const r = await p;
expect(r.by).toBe("timeout");
expect(r.decision).toBe("deny");
});
it("NaN timeoutMs 边界:setTimeout(NaN) 视同 0 → timeout deny(不报错)", async () => {
const gate = new ApprovalGate({ mode: "interactive", timeoutMs: 10_000 });
gate.registerApprover(makeSlowApprover(10_000));
const p = gate.request({
action: "flash",
risk: "high",
timeoutMs: NaN,
});
vi.advanceTimersByTime(1);
const r = await p;
expect(r.by).toBe("timeout");
expect(r.decision).toBe("deny");
});
});
// ============================================================================
// 【决策表】approval —— mode × approver存在性 × approver行为 → 期望
// ============================================================================
describe("【决策表】approval mode×approver×行为 → decision/by", () => {
type Row = {
name: string;
mode: ApprovalMode;
registerApprover: boolean;
approverThrows?: boolean;
approverSlow?: boolean;
approverDecision?: "approve" | "deny";
timeoutMs?: number;
expectDecision: "approve" | "deny";
expectBy: "auto" | "approver" | "timeout";
expectApproverCalled: boolean;
};
const rows: Row[] = [
{ name: "auto-deny / no approver", mode: "auto-deny", registerApprover: false, expectDecision: "deny", expectBy: "auto", expectApproverCalled: false },
{ name: "auto-deny / has approver (短路不调)", mode: "auto-deny", registerApprover: true, approverDecision: "approve", expectDecision: "deny", expectBy: "auto", expectApproverCalled: false },
{ name: "auto-approve / no approver", mode: "auto-approve", registerApprover: false, expectDecision: "approve", expectBy: "auto", expectApproverCalled: false },
{ name: "auto-approve / has approver (短路不调)", mode: "auto-approve", registerApprover: true, approverDecision: "deny", expectDecision: "approve", expectBy: "auto", expectApproverCalled: false },
{ name: "interactive / no approver → fail-closed", mode: "interactive", registerApprover: false, expectDecision: "deny", expectBy: "auto", expectApproverCalled: false },
{ name: "interactive / approver approve", mode: "interactive", registerApprover: true, approverDecision: "approve", expectDecision: "approve", expectBy: "approver", expectApproverCalled: true },
{ name: "interactive / approver deny", mode: "interactive", registerApprover: true, approverDecision: "deny", expectDecision: "deny", expectBy: "approver", expectApproverCalled: true },
{ name: "interactive / approver throws → deny fail-closed", mode: "interactive", registerApprover: true, approverThrows: true, expectDecision: "deny", expectBy: "auto", expectApproverCalled: true },
{ name: "interactive / approver slow → timeout", mode: "interactive", registerApprover: true, approverSlow: true, approverDecision: "approve", timeoutMs: 50, expectDecision: "deny", expectBy: "timeout", expectApproverCalled: true },
];
for (const row of rows) {
it(row.name, async () => {
const useFake = row.approverSlow === true;
if (useFake) vi.useFakeTimers();
try {
const gate = new ApprovalGate({ mode: row.mode, timeoutMs: 10_000 });
let approverCalled = false;
if (row.registerApprover) {
if (row.approverThrows) {
gate.registerApprover(async () => {
approverCalled = true;
throw new Error("approver boom");
});
} else if (row.approverSlow) {
gate.registerApprover(
() => {
approverCalled = true; // 同步标记:approver 已被调用
return new Promise<ApprovalResult>((resolve) =>
setTimeout(
() =>
resolve({ decision: row.approverDecision ?? "approve", reason: "ok", by: "approver" }),
10_000,
),
);
},
);
} else {
gate.registerApprover(async () => {
approverCalled = true;
return { decision: row.approverDecision ?? "approve", reason: "ok", by: "approver" } as ApprovalResult;
});
}
}
const p = gate.request({ action: "flash", risk: "high", timeoutMs: row.timeoutMs });
if (useFake) vi.advanceTimersByTime(row.timeoutMs ?? 0);
const r = await p;
expect(r.decision).toBe(row.expectDecision);
expect(r.by).toBe(row.expectBy);
expect(approverCalled).toBe(row.expectApproverCalled);
if (row.approverThrows) {
expect(r.reason).toContain("approver threw");
}
} finally {
if (useFake) vi.useRealTimers();
}
});
}
});
// ============================================================================
// 【状态转换】approval —— mode/approver 注册/注销迁移 + 重入 + 不可达态兜底
// ============================================================================
describe("【状态转换】approval mode & approver 注册/注销迁移", () => {
it("初始态=auto-deny;setMode 迁移后行为随之变;再迁回 auto-deny", async () => {
const gate = new ApprovalGate(); // 初始 auto-deny
expect(await gate.request({ action: "x", risk: "low" })).toMatchObject({
decision: "deny",
by: "auto",
});
gate.setMode("auto-approve");
expect(await gate.request({ action: "x", risk: "low" })).toMatchObject({
decision: "approve",
by: "auto",
});
// 迁到 interactive 无 approver(不可达态兜底 → deny)
gate.setMode("interactive");
expect(await gate.request({ action: "x", risk: "low" })).toMatchObject({
decision: "deny",
by: "auto",
});
gate.setMode("auto-deny");
expect(await gate.request({ action: "x", risk: "low" })).toMatchObject({
decision: "deny",
by: "auto",
});
});
it("registerApprover→request→dispose→request 状态迁移闭环", async () => {
const gate = new ApprovalGate({ mode: "interactive" });
// 态 A:无 approver → deny
expect(await gate.request({ action: "f", risk: "high" })).toMatchObject({
decision: "deny",
by: "auto",
});
// 态 B:注册 → approve
const dispose = gate.registerApprover(makeApprover("approve"));
expect(await gate.request({ action: "f", risk: "high" })).toMatchObject({
decision: "approve",
by: "approver",
});
// 态 C:dispose → 回 deny
dispose();
expect(await gate.request({ action: "f", risk: "high" })).toMatchObject({
decision: "deny",
by: "auto",
});
});
it("disposer 幂等重入:dispose 两次不报错", async () => {
const gate = new ApprovalGate({ mode: "interactive" });
const dispose = gate.registerApprover(makeApprover("approve"));
expect(() => {
dispose();
dispose(); // 重入幂等
}).not.toThrow();
expect(await gate.request({ action: "f", risk: "high" })).toMatchObject({
decision: "deny",
by: "auto",
});
});
it("后注册者覆盖前者;旧 disposer 不误摘后来注册者", async () => {
const gate = new ApprovalGate({ mode: "interactive" });
const disposeA = gate.registerApprover(makeApprover("deny", "A"));
const disposeB = gate.registerApprover(makeApprover("approve", "B")); // B 覆盖 A
// 当前应 B:approve
expect(await gate.request({ action: "f", risk: "high" })).toMatchObject({
decision: "approve",
by: "approver",
});
// 旧 disposer(A)调用:approver 现是 B≠A,不应摘除 B
disposeA();
expect(await gate.request({ action: "f", risk: "high" })).toMatchObject({
decision: "approve",
by: "approver",
});
// B 的 disposer 才摘除
disposeB();
expect(await gate.request({ action: "f", risk: "high" })).toMatchObject({
decision: "deny",
by: "auto",
});
});
it("同一 fn 注册两次后 dispose 一次即清空(=== 自摘除语义)", async () => {
const gate = new ApprovalGate({ mode: "interactive" });
const fn = makeApprover("approve", "same");
const d1 = gate.registerApprover(fn);
const d2 = gate.registerApprover(fn); // 同一引用覆盖
// d1 此时已不再 === 当前 approver? 当前 approver===fn,d1 的 disposer 检查 ===fn 仍真
// dispose d1:因 this.approver===fn → 摘除
d1();
expect(await gate.request({ action: "f", risk: "high" })).toMatchObject({
decision: "deny",
by: "auto",
});
// d2 再 dispose 幂等
expect(() => d2()).not.toThrow();
});
it("并发重入:同一 gate 多个 request 并发不互相干扰(各自 race)", async () => {
vi.useFakeTimers();
try {
const gate = new ApprovalGate({ mode: "interactive", timeoutMs: 100 });
let callCount = 0;
gate.registerApprover(
() =>
new Promise<ApprovalResult>((resolve) =>
setTimeout(() => {
callCount++;
resolve({ decision: "approve", reason: "ok", by: "approver" });
}, 10),
),
);
const p1 = gate.request({ action: "a", risk: "low" });
const p2 = gate.request({ action: "b", risk: "low" });
const p3 = gate.request({ action: "c", risk: "low" });
vi.advanceTimersByTime(10);
const [r1, r2, r3] = await Promise.all([p1, p2, p3]);
for (const r of [r1, r2, r3]) {
expect(r).toMatchObject({ decision: "approve", by: "approver" });
}
expect(callCount).toBe(3);
} finally {
vi.useRealTimers();
}
});
});
// ============================================================================
// 【对抗/fuzz】approval —— 畸形 req、approver 抛非 Error、超长 context
// ============================================================================
describe("【对抗/fuzz】approval 畸形/滥用输入", () => {
it("approver 抛非 Error 值(null/string/NaN/undefined/42/{})→ 仍 fail-closed deny by auto", async () => {
const gate = new ApprovalGate({ mode: "interactive" });
for (const thrown of [null, "string-err", NaN, undefined, 42, {}]) {
gate.registerApprover(async () => {
throw thrown;
});
const r = await gate.request({ action: "f", risk: "high" });
expect(r.decision).toBe("deny");
expect(r.by).toBe("auto");
expect(r.reason).toContain("approver threw");
}
});
it("approver 返回非法 decision 字面量 → 原样透传(gate 不做白名单校验,契约由调用方保证)", async () => {
const gate = new ApprovalGate({ mode: "interactive" });
gate.registerApprover(
async () =>
({ decision: "maybe", reason: "x", by: "approver" }) as unknown as ApprovalResult,
);
const r = await gate.request({ action: "f", risk: "high" });
expect(r.by).toBe("approver");
expect(r.decision as string).toBe("maybe");
});
it("超长 context 字符串不致崩溃/超时", async () => {
const gate = new ApprovalGate({ mode: "interactive" });
const big = "x".repeat(1_000_000);
gate.registerApprover(makeApprover("approve"));
const r = await gate.request({ action: "dd", risk: "high", context: big });
expect(r).toMatchObject({ decision: "approve", by: "approver" });
});
it("risk/action 为空串 → 仍正常裁决(不校验枚举)", async () => {
const gate = new ApprovalGate({ mode: "auto-approve" });
const r = await gate.request({ action: "", risk: "" } as unknown as ApprovalRequest);
expect(r).toMatchObject({ decision: "approve", by: "auto" });
});
});
// ============================================================================
// 【元蜕变/不变式】approval —— fail-closed 单调 deny、计时器不悬挂、短路
// ============================================================================
describe("【元蜕变/不变式】approval fail-closed 单调性 + 计时器清理 + 短路", () => {
it("不变式:auto-deny 模式对任意 N 个不同请求恒 deny(单调)", async () => {
const gate = new ApprovalGate({ mode: "auto-deny" });
const decisions = new Set<string>();
const bys = new Set<string>();
for (let i = 0; i < 20; i++) {
const r = await gate.request({ action: `act${i}`, risk: "low", context: `c${i}` });
decisions.add(r.decision);
bys.add(r.by);
}
expect(decisions).toEqual(new Set(["deny"]));
expect(bys).toEqual(new Set(["auto"]));
});
it("不变式:approver 先 resolve 后计时器必 clear(无悬挂 timer)", async () => {
vi.useFakeTimers();
const clearSpy = vi.spyOn(globalThis, "clearTimeout");
try {
const gate = new ApprovalGate({ mode: "interactive", timeoutMs: 10_000 });
gate.registerApprover(makeSlowApprover(10, "approve"));
const p = gate.request({ action: "f", risk: "high" });
vi.advanceTimersByTime(10);
await p;
// 再推过超时点:若计时器未 clear,残留超时回调会触发
vi.advanceTimersByTime(10_000);
expect(clearSpy).toHaveBeenCalled();
} finally {
clearSpy.mockRestore();
vi.useRealTimers();
}
});
it("不变式:timeout 路径也必 clear 计时器(finally 不分胜负均执行)", async () => {
vi.useFakeTimers();
const clearSpy = vi.spyOn(globalThis, "clearTimeout");
try {
const gate = new ApprovalGate({ mode: "interactive", timeoutMs: 50 });
gate.registerApprover(makeSlowApprover(10_000, "approve")); // 超时胜
const p = gate.request({ action: "f", risk: "high" });
vi.advanceTimersByTime(50);
const r = await p;
expect(r.by).toBe("timeout");
expect(clearSpy).toHaveBeenCalled();
} finally {
clearSpy.mockRestore();
vi.useRealTimers();
}
});
it("不变式:auto-* 模式 waterfall 不调 next=短路(approver 永不被调)", async () => {
for (const mode of ["auto-deny", "auto-approve"] as const) {
const gate = new ApprovalGate({ mode });
const rec = makeRecordingApprover("approve");
gate.registerApprover(rec.fn);
await gate.request({ action: "f", risk: "high" });
expect(rec.called()).toBe(false); // 短路:approver 永不被调
}
});
it("元蜕变:approver 同一裁决在有无 timeoutMs(足够大)下等价(变换保持)", async () => {
const gate = new ApprovalGate({ mode: "interactive", timeoutMs: 10_000 });
gate.registerApprover(makeApprover("approve", "stable"));
const r1 = await gate.request({ action: "f", risk: "high" }); // 无 req.timeoutMs
const r2 = await gate.request({ action: "f", risk: "high", timeoutMs: 10_000 }); // 大 timeoutMs
expect(r1).toEqual(r2);
});
});
// ============================================================================
// 【等价类 + 边界值】credentials —— redact 匹配类与边界
// ============================================================================
describe("【等价类划分】credentials redact 有效/无效类", () => {
const store = new CredentialsStore();
it("有效类:所有已知前缀密钥(8+ 后缀)→ <redacted>", () => {
for (const prefix of [
"sk-",
"ghp_",
"gho_",
"ghs_",
"ghr_",
"ghu_",
"github_pat_",
"xoxb-",
"xoxp-",
"glpat-",
]) {
const tok = prefix + "abcdefgh"; // 前缀 + 恰好 8 位
expect(store.redact(tok)).toBe(REDACTED_PLACEHOLDER);
}
});
it("有效类:长不透明 token(40+ 连续 [A-Za-z0-9_-])→ <redacted>", () => {
expect(store.redact("a".repeat(40))).toBe(REDACTED_PLACEHOLDER);
expect(store.redact("a".repeat(64))).toBe(REDACTED_PLACEHOLDER); // SHA-256 长度
expect(store.redact("A1-b_C2-d".repeat(5))).toBe(REDACTED_PLACEHOLDER); // 含 _- 的 50 位
});
it("无效类:普通短串/配置/无密钥串 → 原样不动", () => {
for (const s of ["board=x5 retries=3", "hello world", "Authorization", "no secret here"]) {
expect(store.redact(s)).toBe(s);
}
});
it("无效类:sk- 后缀 < 8 位 → 不脱敏(按设计阈值,非密钥)", () => {
expect(store.redact("sk-abcd123")).toBe("sk-abcd123"); // sk- + 7 位
});
it("REDACTED_PLACEHOLDER 常量=<redacted>(下游契约不得改名)", () => {
expect(REDACTED_PLACEHOLDER).toBe("<redacted>");
});
});
describe("【边界值分析】credentials redact 长度边界(off-by-one)", () => {
const store = new CredentialsStore();
it("长 token 边界:39 位不脱敏 / 40 位脱敏 / 41 位脱敏", () => {
expect(store.redact("a".repeat(39))).toBe("a".repeat(39));
expect(store.redact("a".repeat(40))).toBe(REDACTED_PLACEHOLDER);
expect(store.redact("a".repeat(41))).toBe(REDACTED_PLACEHOLDER);
});
it("前缀后缀边界:8 位脱敏 / 7 位不脱敏", () => {
expect(store.redact("sk-abcdefgh")).toBe(REDACTED_PLACEHOLDER); // 8
expect(store.redact("sk-abcdefg")).toBe("sk-abcdefg"); // 7
});
it("空串/单字符边界:redact('')='' / redact('x')='x'", () => {
expect(store.redact("")).toBe("");
expect(store.redact("x")).toBe("x");
});
it("多个密钥同时出现:全部替换,明文零残留", () => {
const log = "k1=sk-abcdefghij k2=" + "b".repeat(45) + " k3=ghp_xxxxxxxxxx";
const out = store.redact(log);
expect(out).not.toContain("sk-abcdef");
expect(out).not.toContain("bbbbb");
expect(out).not.toContain("ghp_xxx");
expect(out.split(REDACTED_PLACEHOLDER).length - 1).toBe(3);
});
it("密钥后接非匹配字符:密钥部分脱敏,后缀保留(部分匹配)", () => {
// sk- + 8 位后接点号(点不在 [A-Za-z0-9_-])
expect(store.redact("sk-abcdefgh.tail")).toBe(`${REDACTED_PLACEHOLDER}.tail`);
});
});
// ============================================================================
// 【决策表】credentials get/set/has —— 内存×env 组合
// ============================================================================
describe("【决策表】credentials get/has 内存×env 组合", () => {
type Row = {
name: string;
mem?: string;
env?: string;
expectGet: string | undefined;
expectHas: boolean;
};
const rows: Row[] = [
{ name: "仅内存有", mem: "mem-val", expectGet: "mem-val", expectHas: true },
{ name: "仅 env 有", env: "env-val", expectGet: "env-val", expectHas: true },
{ name: "内存+env(内存优先)", mem: "mem-val", env: "env-val", expectGet: "mem-val", expectHas: true },
{ name: "两者皆无", expectGet: undefined, expectHas: false },
{ name: "内存有但空串(区分 undefined 与 '')", mem: "", env: "env-val", expectGet: "", expectHas: true },
{ name: "env 有但空串", env: "", expectGet: "", expectHas: true },
];
for (const row of rows) {
it(row.name, () => {
const env = new Map<string, string>();
if (row.env !== undefined) env.set("K", row.env);
const store = new CredentialsStore((n) => env.get(n));
if (row.mem !== undefined) store.set("K", row.mem);
expect(store.get("K")).toBe(row.expectGet);
expect(store.has("K")).toBe(row.expectHas);
});
}
});
// ============================================================================
// 【对抗/fuzz】credentials —— null/undefined/巨大/非字符串
// ============================================================================
describe("【对抗/fuzz】credentials 畸形输入", () => {
it("redact(null/undefined/0/false) → 原样返回(!s 短路,不抛)", () => {
const store = new CredentialsStore();
expect(store.redact(null as unknown as string)).toBe(null);
expect(store.redact(undefined as unknown as string)).toBe(undefined);
// @ts-expect-error 故意传非串
expect(store.redact(0)).toBe(0);
// @ts-expect-error 故意传 false
expect(store.redact(false)).toBe(false);
});
it("redact 巨大串(1MB)不崩溃且替换密钥", () => {
const store = new CredentialsStore();
const big = "sk-abcdefgh".repeat(100_000); // ~1.1MB 含 10 万密钥
const out = store.redact(big);
expect(out).not.toContain("sk-abc");
expect(out.length).toBeGreaterThan(0);
});
it("redact 含 _- 与字母数字混合的长 token 边界(不误伤短 token)", () => {
const store = new CredentialsStore();
const t39 = "a1_b2-c3_d4-e5_f6-g7_h8-i9_j0-k1_l2-m3_n4".slice(0, 39);
expect(t39.length).toBe(39);
expect(store.redact(t39)).toBe(t39);
// 幂等
expect(store.redact(t39)).toBe(store.redact(t39));
});
it("get(undefined/空名) → undefined,不抛", () => {
const store = new CredentialsStore(() => undefined);
expect(store.get("")).toBeUndefined();
expect(store.get(undefined as unknown as string)).toBeUndefined();
expect(store.has("")).toBe(false);
});
it("set 不落盘不写 env:set 后 envLookup 不见该 key", () => {
const env = new Map<string, string>([["K", "env-only"]]);
const spy = vi.fn((n: string) => env.get(n));
const store = new CredentialsStore(spy);
store.set("K", "mem-val");
// get 走内存优先,不触发 envLookup
expect(store.get("K")).toBe("mem-val");
expect(spy).not.toHaveBeenCalled();
// 未 set 的 key 才查 env
expect(store.get("OTHER")).toBeUndefined();
expect(spy).toHaveBeenCalledWith("OTHER");
});
});
// ============================================================================
// 【元蜕变/不变式】credentials —— key 永不 echo、redact 幂等、set→get 等价
// ============================================================================
describe("【元蜕变/不变式】credentials key 永不 echo", () => {
it("不变式:任意含密钥串 redact 后不含原密钥子串", () => {
const store = new CredentialsStore();
const secrets = ["sk-abcdefghijkl", "ghp_abcdefghijkl", "x".repeat(50)];
for (const s of secrets) {
const out = store.redact(`log: ${s} done`);
expect(out).not.toContain(s);
expect(out).toContain(REDACTED_PLACEHOLDER);
}
});
it("元蜕变:redact(redact(s)) == redact(s)(幂等)", () => {
const store = new CredentialsStore();
for (const s of [
"a sk-abcdefghij b",
"x".repeat(50),
"plain text only",
"multi sk-aaaa1111 and ghp_bbbb2222",
]) {
const once = store.redact(s);
const twice = store.redact(once);
expect(twice).toBe(once);
}
});
it("元蜕变:set(k,v) 后 get(k)==v 恒成立(replay 等价:多次 get 等价)", () => {
const store = new CredentialsStore(() => undefined);
store.set("K", "v1");
const g1 = store.get("K");
const g2 = store.get("K");
const g3 = store.get("K");
expect(g1).toBe("v1");
expect(g1).toBe(g2);
expect(g2).toBe(g3);
});
});
// ============================================================================
// 【等价类 + 边界值】settings —— defaults 类、深冻结、键约束
// ============================================================================
describe("【等价类划分】settings defaults 有效/边界类", () => {
it("有效类:多类型值(number/string/boolean/对象/数组/null)get/set", () => {
type Cfg = {
n: number;
s: string;
b: boolean;
o: { x: number };
arr: number[];
z: null;
};
const s = new SettingsStore<Cfg>({
n: 1,
s: "x",
b: true,
o: { x: 2 },
arr: [1, 2],
z: null,
});
expect(s.get("n")).toBe(1);
expect(s.get("s")).toBe("x");
expect(s.get("b")).toBe(true);
expect(s.get("o")).toEqual({ x: 2 });
expect(s.get("arr")).toEqual([1, 2]);
expect(s.get("z")).toBe(null);
s.set("n", 99);
s.set("s", "y");
s.set("b", false);
expect(s.get("n")).toBe(99);
expect(s.get("s")).toBe("y");
expect(s.get("b")).toBe(false);
});
it("边界类:空对象 defaults → snapshot 为 {}(深冻结空对象)", () => {
const s = new SettingsStore({});
const snap = s.snapshot();
expect(snap).toEqual({});
expect(Object.isFrozen(snap)).toBe(true);
});
it("边界类:单键 defaults", () => {
const s = new SettingsStore({ only: 42 });
expect(s.get("only")).toBe(42);
s.set("only", 0);
expect(s.get("only")).toBe(0);
});
it("隔离类:构造后篡改外部 defaults 顶层属性不影响 store(浅拷贝顶层隔离)", () => {
// defaults 带索引签名以便后续加键;store 泛型显式收窄到 {a,b} 以便 get("c") 报错。
const defaults: { a: number; b: number; [k: string]: number } = {
a: 1,
b: 2,
};
const s = new SettingsStore<{ a: number; b: number }>(defaults);
defaults.a = 999; // 篡改外部顶层(原对象,非副本)
defaults.c = 3; // 加键
expect(s.get("a")).toBe(1); // 顶层不受影响(浅拷贝复制了原语值)
// @ts-expect-error c 不在收窄键集 {a,b}
expect(s.get("c")).toBeUndefined();
});
it("隔离类:构造后篡改外部 defaults 嵌套对象不影响 store(深拷贝隔离)", () => {
const defaults = { o: { x: 1 } };
const s = new SettingsStore(defaults);
defaults.o.x = 999; // 篡改嵌套引用
expect(s.get("o").x).toBe(1); // 深拷贝隔离,不受影响
});
});
// ============================================================================
// 【边界值分析】settings snapshot 深冻结 —— off-by-one 层级
// ============================================================================
describe("【边界值分析】settings snapshot 深冻结层级", () => {
it("顶层冻结:篡改 snapshot 顶层属性抛 TypeError", () => {
const s = new SettingsStore({ a: 1, b: { x: 1 } });
const snap = s.snapshot();
expect(Object.isFrozen(snap)).toBe(true);
expect(() => {
(snap as { a: number }).a = 999;
}).toThrow(TypeError);
});
it("一层嵌套冻结:篡改 snapshot.b.x 抛 TypeError", () => {
const s = new SettingsStore({ b: { x: 1 } });
const snap = s.snapshot();
expect(Object.isFrozen(snap.b)).toBe(true);
expect(() => {
(snap as { b: { x: number } }).b.x = 999;
}).toThrow(TypeError);
});
it("两层嵌套冻结:篡改 snapshot.b.c.x 抛 TypeError(深递归 off-by-one 防漏)", () => {
const s = new SettingsStore({ b: { c: { x: 1 } } });
const snap = s.snapshot();
expect(Object.isFrozen(snap.b.c)).toBe(true);
expect(() => {
(snap as { b: { c: { x: number } } }).b.c.x = 999;
}).toThrow(TypeError);
});
it("数组元素冻结:snapshot.arr 冻结,元素不可变", () => {
const s = new SettingsStore({ arr: [1, 2, 3] });
const snap = s.snapshot();
expect(Object.isFrozen(snap.arr)).toBe(true);
expect(() => {
(snap as { arr: number[] }).arr[0] = 999;
}).toThrow(TypeError);
});
it("snapshot 不冻结内部 store(store 仍可 set)", () => {
const s = new SettingsStore({ a: 1 });
const snap = s.snapshot();
expect(Object.isFrozen(snap)).toBe(true);
// 内部 store 仍可写
expect(() => s.set("a", 5)).not.toThrow();
expect(s.get("a")).toBe(5);
// 旧 snapshot 不受影响
expect(snap.a).toBe(1);
});
it("Map 值深冻结:snapshot 含 Map 时 Map 与键值均冻结", () => {
const s = new SettingsStore({ m: new Map([["k", { v: 1 }]]) });
const snap = s.snapshot();
expect(Object.isFrozen(snap.m)).toBe(true);
// Map.set 在冻结的 Map 上静默失败(非 strict),但深层值对象应已冻结
// 篡改 Map 内的 value 对象应抛 TypeError
const inner = (snap as { m: Map<string, { v: number }> }).m.get("k")!;
expect(Object.isFrozen(inner)).toBe(true);
expect(() => {
inner.v = 999;
}).toThrow(TypeError);
});
it("Set 值深冻结:snapshot 含 Set 时 Set 与元素均冻结", () => {
const s = new SettingsStore({ set: new Set([{ v: 1 }]) });
const snap = s.snapshot();
expect(Object.isFrozen(snap.set)).toBe(true);
const elem = (snap as { set: Set<{ v: number }> }).set.values().next().value!;
expect(Object.isFrozen(elem)).toBe(true);
expect(() => {
elem.v = 999;
}).toThrow(TypeError);
});
});
// ============================================================================
// 【状态转换】settings —— set 迁移与 snapshot 时序
// ============================================================================
describe("【状态转换】settings set 迁移与 snapshot 时序", () => {
it("初始态=get defaults;set 迁移值;snapshot 反映当时态", () => {
const s = new SettingsStore({ a: 1 });
expect(s.get("a")).toBe(1); // 初始态
const snap0 = s.snapshot();
s.set("a", 2); // 迁移
const snap1 = s.snapshot();
expect(snap0.a).toBe(1); // 旧态冻结不变
expect(snap1.a).toBe(2); // 新态反映
expect(s.get("a")).toBe(2);
});
it("多次 set 覆盖:最后值胜出(单调迁移)", () => {
const s = new SettingsStore({ a: 0 });
for (let i = 1; i <= 5; i++) s.set("a", i);
expect(s.get("a")).toBe(5);
});
});
// ============================================================================
// 【元蜕变/不变式】settings —— snapshot 副本隔离内部状态
// ============================================================================
describe("【元蜕变/不变式】settings snapshot 副本隔离", () => {
it("不变式:snapshot 不影响内部 store 顶层值(set 后再 snapshot 反映新值)", () => {
const s = new SettingsStore({ a: 1 });
const snap1 = s.snapshot();
s.set("a", 2);
const snap2 = s.snapshot();
expect(snap1.a).toBe(1); // 旧快照不变
expect(snap2.a).toBe(2); // 新快照反映
expect(s.get("a")).toBe(2);
});
it("不变式:snapshot 嵌套对象与内部 store 嵌套对象无共享引用(深克隆隔离)", () => {
const s = new SettingsStore({ b: { x: 1 } });
const snap = s.snapshot();
// snapshot 的 b 与 store 内部 b 不是同一引用
expect(snap.b).not.toBe(s.get("b"));
// 篡改 snapshot.b(会抛,因为已冻结)—— 先确认已冻结
expect(Object.isFrozen(snap.b)).toBe(true);
// 内部 store 仍可经 set 替换整个对象
s.set("b", { x: 2 });
expect(s.get("b").x).toBe(2);
expect(snap.b.x).toBe(1); // 旧 snapshot 不受影响
});
it("元蜕变:两次 snapshot 同状态等价(replay 等价)", () => {
const s = new SettingsStore({ a: 1, b: { x: 1 } });
const snap1 = s.snapshot();
const snap2 = s.snapshot();
expect(snap1).toEqual(snap2);
});
it("不变式:Date 值深克隆隔离(构造后篡改外部 Date 不影响 store)", () => {
const d = new Date(2020, 0, 1);
const s = new SettingsStore({ when: d });
d.setFullYear(2099); // 篡改外部 Date
expect(s.get("when").getTime()).toBe(new Date(2020, 0, 1).getTime());
});
});
// ============================================================================
// 【等价类 + 状态转换】lsp NoopLspBridge —— 初始化/关闭/幂等
// ============================================================================
describe("【等价类划分】lsp noop initialize/shutdown", () => {
it("有效类:initialize 任意 rootUri → {ok:true}", async () => {
const bridge: LspBridge = new NoopLspBridge();
for (const rootUri of [
"file:///workspace",
"file:///abs/path",
"",
] as LspInitOptions["rootUri"][]) {
const r = await bridge.initialize({ rootUri });
expect(r.ok).toBe(true);
expect(r.reason).toBeUndefined();
}
});
it("有效类:含 initializationOptions 透传不报错", async () => {
const bridge: LspBridge = new NoopLspBridge();
const r = await bridge.initialize({
rootUri: "file:///w",
initializationOptions: { clangd: { fallbackFlags: ["--target=aarch64"] } },
});
expect(r.ok).toBe(true);
});
});
describe("【状态转换】lsp shutdown 幂等 + 顺序无关", () => {
it("shutdown 前未 initialize 也可直接 shutdown(无状态前置)", async () => {
const bridge: LspBridge = new NoopLspBridge();
await expect(bridge.shutdown()).resolves.toBeUndefined();
});
it("shutdown 多次调用幂等(重入不报错)", async () => {
const bridge: LspBridge = new NoopLspBridge();
await bridge.initialize({ rootUri: "file:///w" });
await bridge.shutdown();
await bridge.shutdown();
await bridge.shutdown();
});
it("initialize→shutdown→initialize 可循环(无残留状态)", async () => {
const bridge: LspBridge = new NoopLspBridge();
const r1 = await bridge.initialize({ rootUri: "file:///a" });
await bridge.shutdown();
const r2 = await bridge.initialize({ rootUri: "file:///b" });
await bridge.shutdown();
expect(r1.ok).toBe(true);
expect(r2.ok).toBe(true);
});
});
describe("【元蜕变/不变式】lsp noop 契约", () => {
it("不变式:NoopLspBridge.initialize 永返回 ok=true(不假装诊断能力)", async () => {
const bridge: LspBridge = new NoopLspBridge();
for (let i = 0; i < 10; i++) {
const r = await bridge.initialize({ rootUri: `file:///w${i}` });
expect(r.ok).toBe(true);
}
});
it("元蜕变:initialize(a) 与 initialize(b) 结果等价(rootUri 不影响 noop 结果)", async () => {
const bridge: LspBridge = new NoopLspBridge();
const ra = await bridge.initialize({ rootUri: "file:///aaa" });
const rb = await bridge.initialize({ rootUri: "file:///bbb" });
expect(ra).toEqual(rb);
});
});
// ============================================================================
// 【变异测试】6 个 seeded bug 内联副本 —— 每个断言被某测试杀死
// ============================================================================
//
// 约定:每个 seeded bug 内联一份带 bug 的逻辑副本(不动真实源码)。
// 杀伤断言模式(双断言):
// - 真实逻辑满足 correctness 期望 → expect(() => expect(real).toEqual(correct)).not.toThrow()
// - 带 bug 副本不满足 correctness 期望 → expect(() => expect(buggy).toEqual(correct)).toThrow()
// (后者抛 AssertionError = buggy≠correct = bug 被杀)
//
// 植入 bug 清单(文档化):
// B1 approval:fail-closed 守卫 `&&` 改 `||` → auto-approve 永远 deny
// 杀手:"auto-approve 应 approve(真实 approve / buggy deny)"
// B2 credentials:LONG_TOKEN_MIN 40 → 41(off-by-one)→ 恰好 40 位 token 漏脱
// 杀手:"恰好 40 位长 token 应脱敏(真实脱敏 / buggy 漏脱)"
// B3 settings:snapshot 漏 freeze 递归(只冻顶层)→ 嵌套对象可被篡改不抛
// 杀手:"snapshot 嵌套属性篡改应抛 TypeError(真实抛 / buggy 不抛)"
// B4 approval:timeout 优先级漏 req.timeoutMs(恒用 ctor ?? DEFAULT)
// 杀手:"req.timeoutMs=50, ctor=10000 → 应用 50(真实 50 / buggy 10000)"
// B5 credentials:前缀后缀量词 {8,} → {9,}(off-by-one)→ sk-+8 位后缀漏脱
// 杀手:"sk-+8 位后缀应脱敏(真实脱敏 / buggy 漏脱)"
// B6 approval:registerApprover disposer 无代际校验(直接置 undefined)
// 杀手:"旧 disposer 不误摘后来注册者(真实保留 B / buggy 误删 B)"
// ---------------------------------------------------------------------------
describe("【变异测试】seeded bug 1:approval fail-closed && → || 短路反", () => {
// BUG:把 `mode !== "auto-approve" && mode !== "interactive"` 改成 `||`。
// 效果:mode="auto-approve" 时第一支为真(auto-approve≠interactive)→ 永远 deny。
function buggyDecide(mode: ApprovalMode): ApprovalResult {
// BUG: || 而非 &&。注意:此 mutation 亦被 tsc 检出(TS2367 无重叠比较),
// 此处 @ts-expect-error 压制以保留 buggy 副本供运行时杀伤断言。
// @ts-expect-error bug: || 短路反, TS 亦检出 '"auto-approve"' 与 '"interactive"' 无重叠
if (mode !== "auto-approve" || mode !== "interactive") {
return { decision: "deny", reason: `mode "${mode}" → auto-deny`, by: "auto" };
}
if (mode === "auto-approve") {
return { decision: "approve", reason: "auto-approve mode", by: "auto" };
}
return { decision: "deny", reason: "interactive stub", by: "auto" };
}
it("杀 bug1:auto-approve 应 approve(真实 approve / buggy deny)", async () => {
const correct: ApprovalResult = {
decision: "approve",
reason: "auto-approve mode",
by: "auto",
};
const real = await new ApprovalGate({ mode: "auto-approve" }).request({
action: "x",
risk: "low",
});
const buggy = buggyDecide("auto-approve");
// 真实满足
expect(() => expect(real).toEqual(correct)).not.toThrow();
// buggy 不满足 = bug 被杀
expect(() => expect(buggy).toEqual(correct)).toThrow();
});
});
describe("【变异测试】seeded bug 2:credentials LONG_TOKEN_MIN 40 → 41(off-by-one)", () => {
// BUG:长 token 阈值从 40 改成 41 → 恰好 40 位 token 不再脱敏。
const PREFIXES = [
"sk-",
"ghp_",
"gho_",
"ghs_",
"ghr_",
"ghu_",
"github_pat_",
"xoxb-",
"xoxp-",
"glpat-",
];
const BUGGY_PATTERN = new RegExp(
`(?:${PREFIXES.join("|")})[A-Za-z0-9_-]{8,}|[A-Za-z0-9_-]{41}`,
"g",
);
function buggyRedact(s: string): string {
if (!s) return s;
return s.replace(BUGGY_PATTERN, REDACTED_PLACEHOLDER);
}
it("杀 bug2:恰好 40 位长 token 应脱敏(真实脱敏 / buggy 漏脱)", () => {
const store = new CredentialsStore();
const tok = "a".repeat(40);
const correct = REDACTED_PLACEHOLDER;
const real = store.redact(tok);
const buggy = buggyRedact(tok);
expect(() => expect(real).toBe(correct)).not.toThrow();
expect(() => expect(buggy).toBe(correct)).toThrow(); // buggy 漏脱 = 被杀
});
});
describe("【变异测试】seeded bug 3:settings snapshot 漏 freeze 递归(只冻顶层)", () => {
// BUG:snapshot 只 Object.freeze 顶层,不递归 → 嵌套对象可被篡改。
function buggyShallowFreeze<T>(obj: T): Readonly<T> {
if (obj === null || typeof obj !== "object") return obj as Readonly<T>;
Object.freeze(obj);
// BUG:漏掉递归
return obj as Readonly<T>;
}
function buggySnapshot<T extends object>(store: T): Readonly<T> {
return buggyShallowFreeze({ ...store });
}
// 尝试篡改嵌套属性,返回是否抛错。
function tryMutateNested(snap: Readonly<{ b: { c: { x: number } } }>): boolean {
try {
(snap as { b: { c: { x: number } } }).b.c.x = 999;
return false; // 未抛 = 未冻结
} catch {
return true; // 抛 = 已冻结
}
}
it("杀 bug3:snapshot 嵌套属性篡改应抛 TypeError(真实抛 / buggy 不抛)", () => {
const s = new SettingsStore({ b: { c: { x: 1 } } });
const realSnap = s.snapshot();
const buggySnap = buggySnapshot({ b: { c: { x: 1 } } });
const correct = true; // 期望抛(已冻结)
expect(() => expect(tryMutateNested(realSnap)).toBe(correct)).not.toThrow();
expect(() => expect(tryMutateNested(buggySnap)).toBe(correct)).toThrow(); // buggy 不抛 = 被杀
});
});
describe("【变异测试】seeded bug 4:approval timeout 优先级忽略 req.timeoutMs", () => {
// BUG:计算 timeoutMs 时漏掉 req.timeoutMs,恒用 ctor ?? DEFAULT。
function realTimeoutMs(
reqT: number | undefined,
ctorT: number | undefined,
): number {
return reqT ?? ctorT ?? 10_000;
}
function buggyTimeoutMs(
reqT: number | undefined,
ctorT: number | undefined,
): number {
// BUG:漏 reqT
void reqT;
return ctorT ?? 10_000;
}
it("杀 bug4:req.timeoutMs=50, ctor=10000 → 应用 50(真实 50 / buggy 10000)", () => {
const correct = 50;
expect(() => expect(realTimeoutMs(50, 10_000)).toBe(correct)).not.toThrow();
expect(() => expect(buggyTimeoutMs(50, 10_000)).toBe(correct)).toThrow(); // buggy=10000
});
it("杀 bug4(补充):req.timeoutMs=0 应生效(0 非 null)(真实 0 / buggy 10000)", () => {
expect(() => expect(realTimeoutMs(0, 10_000)).toBe(0)).not.toThrow();
expect(() => expect(buggyTimeoutMs(0, 10_000)).toBe(0)).toThrow(); // buggy 忽略 0
});
});
describe("【变异测试】seeded bug 5:credentials 前缀后缀 {8,} → {9,}(off-by-one)", () => {
// BUG:前缀密钥后缀量词从 {8,} 改成 {9,} → 恰好 8 位后缀不再脱敏。
const PREFIXES = [
"sk-",
"ghp_",
"gho_",
"ghs_",
"ghr_",
"ghu_",
"github_pat_",
"xoxb-",
"xoxp-",
"glpat-",
];
const BUGGY_PATTERN = new RegExp(
`(?:${PREFIXES.join("|")})[A-Za-z0-9_-]{9,}|[A-Za-z0-9_-]{40}`,
"g",
);
function buggyRedact(s: string): string {
if (!s) return s;
return s.replace(BUGGY_PATTERN, REDACTED_PLACEHOLDER);
}
it("杀 bug5:sk-+8 位后缀应脱敏(真实脱敏 / buggy 漏脱)", () => {
const store = new CredentialsStore();
const tok = "sk-abcdefgh"; // 恰好 8 位后缀,总长 11(<40,长 token 分支不救)
const correct = REDACTED_PLACEHOLDER;
const real = store.redact(tok);
const buggy = buggyRedact(tok);
expect(() => expect(real).toBe(correct)).not.toThrow();
expect(() => expect(buggy).toBe(correct)).toThrow(); // buggy 漏脱 = 被杀
});
});
describe("【变异测试】seeded bug 6:approval disposer 无代际校验(直接置 undefined)", () => {
// BUG:registerApprover 的 disposer 直接 `this.approver = undefined`,
// 不检查 === fn → 旧 disposer 调用会误摘后来注册者。
class BuggyApprovalGate {
private mode: ApprovalMode = "interactive";
private approver: ApproverFn | undefined;
setMode(m: ApprovalMode): void { this.mode = m; }
registerApprover(fn: ApproverFn): () => void {
this.approver = fn;
return () => {
// BUG:无 `if (this.approver === fn)` 代际校验,直接清空
this.approver = undefined;
};
}
async request(req: ApprovalRequest): Promise<ApprovalResult> {
if (this.mode !== "auto-approve" && this.mode !== "interactive") {
return { decision: "deny", reason: "auto-deny", by: "auto" };
}
if (this.mode === "auto-approve") {
return { decision: "approve", reason: "auto-approve mode", by: "auto" };
}
const approver = this.approver;
if (approver === undefined) {
return { decision: "deny", reason: "no approver", by: "auto" };
}
return approver(req).catch(
(): ApprovalResult => ({ decision: "deny", reason: "threw", by: "auto" }),
);
}
}
it("杀 bug6:旧 disposer 不误摘后来注册者(真实保留 B / buggy 误删 B)", async () => {
// 真实 gate:B 覆盖 A,disposeA 不影响 B
const realGate = new ApprovalGate({ mode: "interactive" });
const realDispA = realGate.registerApprover(makeApprover("deny", "A"));
realGate.registerApprover(makeApprover("approve", "B"));
realDispA();
const realR = await realGate.request({ action: "f", risk: "high" });
const realCorrect: ApprovalResult = { decision: "approve", reason: "B", by: "approver" };
// buggy gate:disposeA 直接清空 → B 被误删 → deny
const buggyGate = new BuggyApprovalGate();
const buggyDispA = buggyGate.registerApprover(makeApprover("deny", "A"));
buggyGate.registerApprover(makeApprover("approve", "B"));
buggyDispA();
const buggyR = await buggyGate.request({ action: "f", risk: "high" });
// 期望(正确)行为是 approve;buggy 会 deny
expect(() => expect(realR).toMatchObject(realCorrect)).not.toThrow();
// buggy 不满足 correct(decision=deny ≠ approve)→ 断言抛 = bug 被杀
expect(() => expect(buggyR).toMatchObject(realCorrect)).toThrow();
});
});
// ============================================================================
// 【集成不变式】跨模块 fail-closed 一致性
// ============================================================================
describe("【集成不变式】跨模块 fail-closed / unusable 拒绝一致性", () => {
it("approval 未知 mode + credentials 未注入 key + lsp stub:全链路 fail-closed/unusable 不放行", async () => {
// approval:未知 mode → deny
const gate = new ApprovalGate();
gate.setMode("unknown-mode" as unknown as ApprovalMode);
const ar = await gate.request({ action: "flash", risk: "high" });
expect(ar.decision).toBe("deny");
// credentials:未注入的 key → get 返回 undefined(unusable)
const store = new CredentialsStore(() => undefined);
expect(store.get("MISSING_GATEWAY_KEY")).toBeUndefined();
expect(store.has("MISSING_GATEWAY_KEY")).toBe(false);
// lsp:noop stub 永不假装真实能力,但 initialize ok(占位稳定)
const bridge: LspBridge = new NoopLspBridge();
const lr = await bridge.initialize({ rootUri: "file:///w" });
expect(lr.ok).toBe(true);
await expect(bridge.shutdown()).resolves.toBeUndefined();
});
});