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

1482 lines
54 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.

/**
* profiles 全量测试套件 —— T15 profile/bundle 分层(测试 Agent 独占文件)。
*
* 被测对象:src/profiles/{base,repair-diagnosis,embedded-dev,index}.ts 的命名导出。
* 纯逻辑模块:零 pi 运行时依赖、零硬件、零网络、零 IO。直接 import 命名导出;
* 变异测试用模块内联的带 bug 副本(mutant),不 mock 真实代码、不改源码。
*
* 被测命名导出(按契约):
* - base.ts : Profile(类型), DOMAIN_TOOLS, BASE_EXTENSIONS, BASE_PROFILE,
* toolsFor, mergeProfiles, diffProfiles
* - repair : REPAIR_DIAGNOSIS_DELTA, REPAIR_DIAGNOSIS_PROFILE
* - embedded : EMBEDDED_DEV_DELTA, EMBEDDED_DEV_PROFILE
* - index.ts : 上述全部 re-export + resolveProfile
*
* 多测试方法论(每个 describe 块标注方法论名):
* ① 等价类划分 —— resolveProfile / toolsFor 有效/无效/边界类
* ② 边界值分析 —— 空 / 单元素 / max / off-by-one
* ③ 决策表 —— mergeProfiles 并集去重全分支 / diffProfiles 全分支
* ④ 状态转换 —— Object.freeze 不可变状态机(冻结态→篡改→TypeError 终态)
* ⑤ 变异测试 —— 6 个 seeded bug(M1~M6),每个文档化 bug+杀手测试 +
* 显式 kill harness(真实通过 / mutant 断言失败=被杀)
* ⑥ 对抗/fuzz —— null / undefined / NaN / 巨大 / 循环引用 / 并发重入 / 非字符串
* ⑦ 元蜕变/不变式 —— append 两次=replay 等价 / freeze 篡改抛 TypeError /
* 单调 fail-closed / mergeProfiles 不重派生(短路)/
* diff 对称幂等 / DOMAIN_TOOLS 全量 referent 无魔法串
*
* 门:
* - 真实代码:npx vitest run tests/profiles.test.ts → all green
* - 每个植入 bug 变体:mutant 函数被对应杀手断言杀死(mutant 输出 ≠ 真实输出,
* 且同一杀手断言在 mutant 上失败=AssertionError)
*
* 已修复的真实 bug(原 findings[],源码已修,本套件作永久回归守护):
* - F1: resolveProfile 对 "toString"/"constructor"/"__proto__" 等 Object.prototype
* 继承键不 fail-closed,返回继承的函数/对象而非抛错(src/profiles/index.ts)。
* 修复:resolveProfile 改用 Object.hasOwn(PROFILE_REGISTRY, id) 判定,只认自身
* 属性,继承键一律判为未注册 → fail-closed 抛错。
*/
import { describe, it, expect } from "vitest";
import type { Profile } from "../src/profiles/base.js";
import {
BASE_PROFILE,
BASE_EXTENSIONS,
REPAIR_DIAGNOSIS_PROFILE,
REPAIR_DIAGNOSIS_DELTA,
EMBEDDED_DEV_PROFILE,
EMBEDDED_DEV_DELTA,
DOMAIN_TOOLS,
resolveProfile,
mergeProfiles,
diffProfiles,
toolsFor,
} from "../src/profiles/index.js";
// ============================================================================
// 变异测试基础设施 —— 内联带 bug 副本(mutant)+ 显式 kill harness
// ----------------------------------------------------------------------------
// 这些副本刻意复制 base.ts 的纯逻辑并植入单点 bug,用于证明对应杀手测试能区分
// 真实与 mutant。真实代码不被 mock,mutant 仅参与变异测试 describe 块。
// 每个 mutant 标注:BUG 描述 + 后果 + 杀手测试位置。
//
// kill harness 范式(canonical mutation testing):
// 一个"杀手断言" killer(fn) 对【真实】函数输出成立(不抛),
// 对【mutant】函数输出失败(抛 AssertionError)。
// expect(() => killer(real)).not.toThrow() // 真实通过
// expect(() => killer(mutant)).toThrow() // mutant 被杀
// ============================================================================
/** 真实 frozen 副本(无 bug,供 mutant 对比基准)。 */
function frozenReal(xs: readonly string[]): readonly string[] {
return Object.freeze([...xs]) as readonly string[];
}
/** 真实 unionStable 副本(无 bug)。 */
function unionStableReal(
base: readonly string[],
delta: readonly string[],
): readonly string[] {
const seen = new Set<string>(base);
const out: string[] = [...base];
for (const x of delta) {
if (!seen.has(x)) {
seen.add(x);
out.push(x);
}
}
return frozenReal(out);
}
/** 真实 toolsFor 副本(无 bug)。 */
function toolsForReal(domains: readonly string[]): readonly string[] {
const out: string[] = [];
const seen = new Set<string>();
for (const d of domains) {
const tools = DOMAIN_TOOLS[d];
if (tools === undefined) {
throw new Error(`toolsFor: unknown extension domain "${d}"`);
}
for (const t of tools) {
if (!seen.has(t)) {
seen.add(t);
out.push(t);
}
}
}
return frozenReal(out);
}
/** 真实 mergeProfiles 副本(无 bug)。 */
function mergeProfilesReal(
base: Profile,
delta: Pick<Profile, "extensions" | "tools">,
): Profile {
return Object.freeze({
id: base.id,
extensions: unionStableReal(base.extensions, delta.extensions),
tools: unionStableReal(base.tools, delta.tools),
note: base.note,
}) as Profile;
}
/** 真实 diffProfiles 副本(无 bug)。 */
function diffProfilesReal(
a: Profile,
b: Profile,
): { added: readonly string[]; removed: readonly string[] } {
const aSet = new Set(a.extensions);
const bSet = new Set(b.extensions);
const added: string[] = [];
for (const x of b.extensions) {
if (!aSet.has(x)) added.push(x);
}
const removed: string[] = [];
for (const x of a.extensions) {
if (!bSet.has(x)) removed.push(x);
}
return Object.freeze({
added: frozenReal(added),
removed: frozenReal(removed),
}) as { added: readonly string[]; removed: readonly string[] };
}
// ---- MUTANT M1: 并集去重条件反转(!seen.has → seen.has) -------------------
/**
* BUG: unionStable 中 `if (!seen.has(x))` 改为 `if (seen.has(x))`。
* 后果:delta 中 base 已含项被重复追加,base 未含的新项被丢弃。
* 杀手:见 "⑤ 变异测试 — M1" describe 块(delta 新项必须出现)。
*/
function unionStableM1(
base: readonly string[],
delta: readonly string[],
): readonly string[] {
const seen = new Set<string>(base);
const out: string[] = [...base];
for (const x of delta) {
// BUG: 条件反转
if (seen.has(x)) {
seen.add(x);
out.push(x);
}
}
return frozenReal(out);
}
// ---- MUTANT M2: 未知域用 ?? [] 默认空(fail-closed 失效) -------------------
/**
* BUG: toolsFor 中 `if (tools === undefined) throw` 改为 `DOMAIN_TOOLS[d] ?? []`。
* 后果:未知域取值 undefined → 兜底空数组 → 不抛错,未知域静默产出空工具集。
* 杀手:见 "⑤ 变异测试 — M2" describe 块(未知域必抛 domain-specific Error)。
*/
function toolsForM2(domains: readonly string[]): readonly string[] {
const out: string[] = [];
const seen = new Set<string>();
for (const d of domains) {
// BUG: throw 改为 ?? [] 默认(fail-closed 失效)
const tools = DOMAIN_TOOLS[d] ?? [];
for (const t of tools) {
if (!seen.has(t)) {
seen.add(t);
out.push(t);
}
}
}
return frozenReal(out);
}
// ---- MUTANT M3: 漏 Object.freeze(mergeProfiles 结果可变) -------------------
/**
* BUG: mergeProfiles 末尾漏 Object.freeze(外层 + 内层数组均不冻结)。
* 后果:运行时篡改 mergeProfiles 返回的 profile(id / extensions / tools)不抛 TypeError。
* 杀手:见 "⑤ 变异测试 — M3" describe 块(篡改必抛 TypeError)。
*/
function unionStableM3NoFreeze(
base: readonly string[],
delta: readonly string[],
): readonly string[] {
const seen = new Set<string>(base);
const out: string[] = [...base];
for (const x of delta) {
if (!seen.has(x)) {
seen.add(x);
out.push(x);
}
}
// BUG: 漏 Object.freeze
return out;
}
function mergeProfilesM3(
base: Profile,
delta: Pick<Profile, "extensions" | "tools">,
): Profile {
// BUG: 漏 Object.freeze(外层 + 内层数组均不冻结)
return {
id: base.id,
extensions: unionStableM3NoFreeze(base.extensions, delta.extensions),
tools: unionStableM3NoFreeze(base.tools, delta.tools),
note: base.note,
} as Profile;
}
// ---- MUTANT M4: diffProfiles added/removed 互换 -----------------------------
/**
* BUG: diffProfiles 返回时 added 与 removed 互换。
* 后果:diffProfiles 的 added 与 removed 颠倒(方向敏感)。
* 杀手:见 "⑤ 变异测试 — M4" describe 块(added 含 b 专属、方向敏感)。
*/
function diffProfilesM4(
a: Profile,
b: Profile,
): { added: readonly string[]; removed: readonly string[] } {
const aSet = new Set(a.extensions);
const bSet = new Set(b.extensions);
const added: string[] = [];
for (const x of b.extensions) {
if (!aSet.has(x)) added.push(x);
}
const removed: string[] = [];
for (const x of a.extensions) {
if (!bSet.has(x)) removed.push(x);
}
// BUG: added 与 removed 互换
return Object.freeze({
added: frozenReal(removed),
removed: frozenReal(added),
}) as { added: readonly string[]; removed: readonly string[] };
}
// ---- MUTANT M5: mergeProfiles 漏继承 note(note: undefined) ----------------
/**
* BUG: mergeProfiles 返回 `note: undefined` 而非 `note: base.note`。
* 后果:合并结果的 note 丢失(契约要求 id/note 继承 base)。
* 杀手:见 "⑤ 变异测试 — M5" describe 块(note === base.note)。
*/
function mergeProfilesM5(
base: Profile,
delta: Pick<Profile, "extensions" | "tools">,
): Profile {
return Object.freeze({
id: base.id,
extensions: unionStableReal(base.extensions, delta.extensions),
tools: unionStableReal(base.tools, delta.tools),
// BUG: note 漏继承(应为 base.note)
note: undefined,
}) as Profile;
}
// ---- MUTANT M6: unionStable 漏 seen.add(delta 内部重复不去重) --------------
/**
* BUG: unionStable 中新项追加后漏 `seen.add(x)`。
* 后果:delta 内部重复的非 base 项被多次追加(去重失效,仅对 delta 内部重复)。
* 杀手:见 "⑤ 变异测试 — M6" describe 块(delta 含内部重复 → 结果恰 1 份)。
*/
function unionStableM6(
base: readonly string[],
delta: readonly string[],
): readonly string[] {
const seen = new Set<string>(base);
const out: string[] = [...base];
for (const x of delta) {
if (!seen.has(x)) {
// BUG: 漏 seen.add(x)
out.push(x);
}
}
return frozenReal(out);
}
// ============================================================================
// 公共 fixture
// ============================================================================
const ALL_PROFILE_IDS = ["base", "repair-diagnosis", "embedded-dev"] as const;
const ALL_PROFILES: readonly Profile[] = [
BASE_PROFILE,
REPAIR_DIAGNOSIS_PROFILE,
EMBEDDED_DEV_PROFILE,
];
// Object.prototype 继承键(resolveProfile 应对这些也 fail-closed,F1 修复后必抛)
const PROTO_KEYS = [
"toString",
"constructor",
"hasOwnProperty",
"valueOf",
"isPrototypeOf",
"__proto__",
"propertyIsEnumerable",
"toLocaleString",
] as const;
// DOMAIN_TOOLS 全量工具去重(不变式基准,从源表派生,非硬编码)
const ALL_TOOLS_SET: Set<string> = (() => {
const s = new Set<string>();
for (const list of Object.values(DOMAIN_TOOLS)) {
for (const t of list) s.add(t);
}
return s;
})();
// 已核对的 defineTool name 全集(取自各扩展 defineTool({ name }),非臆造)
const KNOWN_DEFINE_TOOL_NAMES = new Set([
"glm_status", "pshell", "read_pdf", "length_recovery_status",
"isolated_exec", "env_status", "mcp_list", "mcp_call",
"server_session", "hw_state", "xcompile", "flash", "bus_probe",
"debugger", "dt", "board_connect", "board_exec", "board_scp",
"board_console", "datasheet_query", "verify", "loop_status",
"build", "build_status", "reg",
]);
// ============================================================================
// ① 等价类划分
// ============================================================================
describe("① 等价类划分 — resolveProfile 有效/无效类", () => {
// 有效类:三个已注册 id
for (const id of ALL_PROFILE_IDS) {
it(`有效类:resolveProfile("${id}") 返回对应 profile(引用共享,不复制)`, () => {
const p = resolveProfile(id);
const expected =
id === "base"
? BASE_PROFILE
: id === "repair-diagnosis"
? REPAIR_DIAGNOSIS_PROFILE
: EMBEDDED_DEV_PROFILE;
expect(p).toBe(expected);
expect(p.id).toBe(id);
});
}
// 无效类:未注册 id
it("无效类:resolveProfile(未注册 id) 抛错且消息含 registered 列表(fail-closed)", () => {
expect(() => resolveProfile("nonexistent")).toThrow(
/unknown profile id "nonexistent"/,
);
expect(() => resolveProfile("nonexistent")).toThrow(/fail-closed/);
expect(() => resolveProfile("nonexistent")).toThrow(
/registered: base, repair-diagnosis, embedded-dev/,
);
});
it("无效类:resolveProfile(空串) 抛错", () => {
expect(() => resolveProfile("")).toThrow(/unknown profile id ""/);
});
it("无效类:resolveProfile(大小写变体) 抛错(大小写敏感)", () => {
expect(() => resolveProfile("BASE")).toThrow();
expect(() => resolveProfile("Repair-Diagnosis")).toThrow();
expect(() => resolveProfile("embedded_dev")).toThrow();
});
it("无效类:resolveProfile(数字串 id) 抛错", () => {
expect(() => resolveProfile("1" as string)).toThrow();
});
it("有效类:三个 profile 的 id 两两不同", () => {
const ids = new Set(ALL_PROFILES.map((p) => p.id));
expect(ids.size).toBe(ALL_PROFILES.length);
});
it("有效类:resolveProfile 错误消息列出全部已注册 id(可诊断)", () => {
try {
resolveProfile("zzz");
throw new Error("should have thrown");
} catch (e) {
const msg = (e as Error).message;
for (const id of ALL_PROFILE_IDS) {
expect(msg).toContain(id);
}
}
});
});
describe("① 等价类划分 — toolsFor 有效/无效/空类", () => {
// 有效类:DOMAIN_TOOLS 收录的每个域
it("有效类:每个 DOMAIN_TOOLS 域单独 toolsFor 返回其工具清单", () => {
for (const [domain, tools] of Object.entries(DOMAIN_TOOLS)) {
const got = toolsFor([domain]);
expect([...got]).toEqual([...tools]);
}
});
it("有效类:多域并集去重保序", () => {
const got = toolsFor(["glm-provider", "persistent-shell", "mcp-bridge"]);
// glm_status, pshell, mcp_list, mcp_call
expect([...got]).toEqual(["glm_status", "pshell", "mcp_list", "mcp_call"]);
});
it("有效类:空工具域(safety-gate / edit-strict)产出空贡献但不破坏序", () => {
const got = toolsFor(["safety-gate", "glm-provider", "edit-strict"]);
expect([...got]).toEqual(["glm_status"]);
});
it("有效类:含空工具域 + 重复域 → 工具不重复", () => {
const got = toolsFor([
"glm-provider",
"glm-provider",
"safety-gate",
"mcp-bridge",
"mcp-bridge",
]);
expect([...got]).toEqual(["glm_status", "mcp_list", "mcp_call"]);
});
// 无效类:未知域
it("无效类:toolsFor 含未知域抛错(消息含域名)", () => {
expect(() => toolsFor(["no-such-domain"])).toThrow(
/unknown extension domain "no-such-domain"/,
);
expect(() => toolsFor(["no-such-domain"])).toThrow(/fail-closed/);
});
it("无效类:toolsFor 混入未知域在任意位置均抛错", () => {
expect(() => toolsFor(["no-such", "glm-provider"])).toThrow();
expect(() => toolsFor(["glm-provider", "no-such"])).toThrow();
expect(() =>
toolsFor(["glm-provider", "no-such", "persistent-shell"]),
).toThrow();
});
// 空类
it("空类:toolsFor([]) 返回空数组(非 undefined),且冻结", () => {
const got = toolsFor([]);
expect(got).toBeDefined();
expect([...got]).toEqual([]);
expect(Object.isFrozen(got)).toBe(true);
});
});
// ============================================================================
// ② 边界值分析
// ============================================================================
describe("② 边界值分析 — 空 / 单元素 / max / off-by-one", () => {
it("边界-空:toolsFor([]) 长度 0", () => {
expect(toolsFor([]).length).toBe(0);
});
it("边界-单元素:toolsFor(单域) 长度等于该域工具数", () => {
expect(toolsFor(["glm-provider"]).length).toBe(1);
expect(toolsFor(["board-link"]).length).toBe(4);
expect(toolsFor(["build-tracker"]).length).toBe(2);
expect(toolsFor(["safety-gate"]).length).toBe(0);
});
it("边界-max:toolsFor(全域) 等于 DOMAIN_TOOLS 全工具去重", () => {
const allDomains = Object.keys(DOMAIN_TOOLS);
const got = toolsFor(allDomains);
const expectedDedup: string[] = [];
const seen = new Set<string>();
for (const d of allDomains) {
for (const t of DOMAIN_TOOLS[d]) {
if (!seen.has(t)) {
seen.add(t);
expectedDedup.push(t);
}
}
}
expect([...got]).toEqual(expectedDedup);
});
it("边界-off-by-one:mergeProfiles delta 单元素正确并入(长度 = base+1)", () => {
const merged = mergeProfiles(BASE_PROFILE, {
extensions: ["pdf-reader"],
tools: toolsFor(["pdf-reader"]),
});
expect(merged.extensions.length).toBe(BASE_EXTENSIONS.length + 1);
expect(merged.extensions[merged.extensions.length - 1]).toBe(
"pdf-reader",
);
});
it("边界-空 delta:mergeProfiles 空 delta = base 内容等价(id/note 继承)", () => {
const merged = mergeProfiles(BASE_PROFILE, {
extensions: [],
tools: [],
});
expect([...merged.extensions]).toEqual([...BASE_PROFILE.extensions]);
expect([...merged.tools]).toEqual([...BASE_PROFILE.tools]);
expect(merged.id).toBe(BASE_PROFILE.id);
expect(merged.note).toBe(BASE_PROFILE.note);
// 但不是同一引用(新对象)
expect(merged).not.toBe(BASE_PROFILE);
});
it("边界-相同 profile:diffProfiles(a, a) added/removed 均空", () => {
const d = diffProfiles(REPAIR_DIAGNOSIS_PROFILE, REPAIR_DIAGNOSIS_PROFILE);
expect([...d.added]).toEqual([]);
expect([...d.removed]).toEqual([]);
});
it("边界-单边差异:diff(base, repair) added=3 removed=0", () => {
const d = diffProfiles(BASE_PROFILE, REPAIR_DIAGNOSIS_PROFILE);
expect(d.added.length).toBe(3);
expect(d.removed.length).toBe(0);
});
it("边界-BASE_EXTENSIONS 长度 = 10(off-by-one 守护:不漏 edit-strict/length-recovery)", () => {
expect(BASE_EXTENSIONS.length).toBe(10);
expect(BASE_EXTENSIONS).toContain("edit-strict");
expect(BASE_EXTENSIONS).toContain("length-recovery");
// base 工具数 < 扩展数(safety-gate/edit-strict 不注册工具)
expect(BASE_PROFILE.tools.length).toBeLessThan(
BASE_PROFILE.extensions.length,
);
});
it("边界-单边差异:diff(base, embedded) added=6 removed=0", () => {
const d = diffProfiles(BASE_PROFILE, EMBEDDED_DEV_PROFILE);
expect(d.added.length).toBe(6);
expect(d.removed.length).toBe(0);
});
it("边界-全差异:diff(repair, embedded) added=6 removed=3", () => {
const d = diffProfiles(REPAIR_DIAGNOSIS_PROFILE, EMBEDDED_DEV_PROFILE);
expect(d.added.length).toBe(6);
expect(d.removed.length).toBe(3);
});
});
// ============================================================================
// ③ 决策表 — mergeProfiles 并集去重全分支
// ============================================================================
describe("③ 决策表 — mergeProfiles 并集去重(全分支覆盖)", () => {
// 决策表:
// | base 含 x | delta 含 x | 期望结果含 x 几次 |
// | Y | Y | 1(去重) |
// | Y | N | 1 |
// | N | Y | 1(追加) |
// | N | N | 0 |
const base: Profile = Object.freeze({
id: "stub",
extensions: Object.freeze(["a", "b"]) as readonly string[],
tools: Object.freeze(["ta", "tb"]) as readonly string[],
note: undefined,
}) as Profile;
it("决策行1:base 含 + delta 含 → 结果恰好 1 次(去重)", () => {
const merged = mergeProfiles(base, {
extensions: ["a"],
tools: ["ta"],
});
expect(merged.extensions.filter((x) => x === "a"))
.toStrictEqual(["a"]);
expect(merged.tools.filter((t) => t === "ta"))
.toStrictEqual(["ta"]);
});
it("决策行2:base 含 + delta 不含 → 结果 1 次", () => {
const merged = mergeProfiles(base, {
extensions: [],
tools: [],
});
expect(merged.extensions.filter((x) => x === "a"))
.toStrictEqual(["a"]);
expect(merged.tools.filter((t) => t === "ta"))
.toStrictEqual(["ta"]);
});
it("决策行3:base 不含 + delta 含 → 结果 1 次(追加在尾)", () => {
const merged = mergeProfiles(base, {
extensions: ["c"],
tools: ["tc"],
});
expect(merged.extensions.filter((x) => x === "c"))
.toStrictEqual(["c"]);
expect(merged.extensions[merged.extensions.length - 1]).toBe("c");
expect(merged.tools.filter((t) => t === "tc"))
.toStrictEqual(["tc"]);
});
it("决策行4:base 不含 + delta 不含 → 结果 0 次", () => {
const merged = mergeProfiles(base, {
extensions: [],
tools: [],
});
expect(merged.extensions.filter((x) => x === "zzz"))
.toStrictEqual([]);
expect(merged.tools.filter((t) => t === "tzzz"))
.toStrictEqual([]);
});
it("决策-序不变式:base 序始终在前,delta 新项始终在后", () => {
const merged = mergeProfiles(base, {
extensions: ["c", "d"],
tools: ["tc", "td"],
});
expect([...merged.extensions]).toEqual(["a", "b", "c", "d"]);
expect([...merged.tools]).toEqual(["ta", "tb", "tc", "td"]);
});
it("决策-id/note 继承:delta 无 id/note 时继承 base", () => {
const merged = mergeProfiles(base, {
extensions: ["c"],
tools: ["tc"],
});
expect(merged.id).toBe("stub");
expect(merged.note).toBeUndefined();
});
});
describe("③ 决策表 — diffProfiles added/removed(全分支覆盖)", () => {
const a: Profile = Object.freeze({
id: "a",
extensions: Object.freeze(["x", "y", "z"]) as readonly string[],
tools: Object.freeze([]) as readonly string[],
note: undefined,
}) as Profile;
const b: Profile = Object.freeze({
id: "b",
extensions: Object.freeze(["y", "z", "w"]) as readonly string[],
tools: Object.freeze([]) as readonly string[],
note: undefined,
}) as Profile;
it("决策:added = b 有 a 无 = ['w'],removed = a 有 b 无 = ['x']", () => {
const d = diffProfiles(a, b);
expect([...d.added]).toEqual(["w"]);
expect([...d.removed]).toEqual(["x"]);
});
it("决策:added/removed 互斥(无交集)", () => {
const d = diffProfiles(a, b);
const addedSet = new Set(d.added);
for (const r of d.removed) {
expect(addedSet.has(r)).toBe(false);
}
});
it("决策:a=b → added=removed=空", () => {
const d = diffProfiles(a, a);
expect([...d.added]).toEqual([]);
expect([...d.removed]).toEqual([]);
});
it("决策:a⊂b(b 含 a 全部 + 更多)→ removed=空", () => {
const sup: Profile = Object.freeze({
id: "sup",
extensions: Object.freeze(["x", "y", "z", "w"]) as readonly string[],
tools: Object.freeze([]) as readonly string[],
note: undefined,
}) as Profile;
const d = diffProfiles(a, sup);
expect([...d.removed]).toEqual([]);
expect([...d.added]).toEqual(["w"]);
});
it("决策:b⊂a → added=空", () => {
const sub: Profile = Object.freeze({
id: "sub",
extensions: Object.freeze(["x"]) as readonly string[],
tools: Object.freeze([]) as readonly string[],
note: undefined,
}) as Profile;
const d = diffProfiles(a, sub);
expect([...d.added]).toEqual([]);
expect([...d.removed]).toEqual(["y", "z"]);
});
it("决策:diff 结果不依赖 tools(只 diff extensions)", () => {
const aDiffTools: Profile = Object.freeze({
id: "a",
extensions: Object.freeze(["x"]) as readonly string[],
tools: Object.freeze(["ta", "tb"]) as readonly string[],
note: undefined,
}) as Profile;
const bDiffTools: Profile = Object.freeze({
id: "b",
extensions: Object.freeze(["x"]) as readonly string[],
tools: Object.freeze(["tc"]) as readonly string[],
note: undefined,
}) as Profile;
const d = diffProfiles(aDiffTools, bDiffTools);
expect([...d.added]).toEqual([]);
expect([...d.removed]).toEqual([]);
});
});
// ============================================================================
// ④ 状态转换 — Object.freeze 不可变状态机
// ============================================================================
describe("④ 状态转换 — Object.freeze 不可变状态机", () => {
// 状态机:[未冻结] --freeze--> [冻结] --篡改--> TypeError(终态)
// 不可达:[冻结] --freeze--> [冻结](幂等,不报错)
// 重入:重复 freeze 同一对象 = 幂等
it("状态-冻结态:篡改 profile 顶层字段抛 TypeError", () => {
for (const p of ALL_PROFILES) {
expect(() => {
(p as Profile & { id: string }).id = "tampered";
}).toThrow(TypeError);
}
});
it("状态-冻结态:篡改 profile.extensions(push/pop/splice)抛 TypeError", () => {
expect(() => {
(BASE_PROFILE.extensions as string[]).push("x");
}).toThrow(TypeError);
expect(() => {
(REPAIR_DIAGNOSIS_PROFILE.extensions as string[]).pop();
}).toThrow(TypeError);
expect(() => {
(EMBEDDED_DEV_PROFILE.extensions as string[]).splice(0, 1);
}).toThrow(TypeError);
});
it("状态-冻结态:篡改 profile.tools 抛 TypeError", () => {
expect(() => {
(BASE_PROFILE.tools as string[]).push("zzz");
}).toThrow(TypeError);
});
it("状态-冻结态:DOMAIN_TOOLS 顶层表与每个域数组均冻结", () => {
expect(Object.isFrozen(DOMAIN_TOOLS)).toBe(true);
for (const tools of Object.values(DOMAIN_TOOLS)) {
expect(Object.isFrozen(tools)).toBe(true);
}
});
it("状态-冻结态:篡改 DOMAIN_TOOLS 表(新增键)抛(strict 模式)", () => {
expect(() => {
(DOMAIN_TOOLS as Record<string, readonly string[]>).evil = Object.freeze(
["nope"],
);
}).toThrow();
});
it("状态-冻结态:BASE_EXTENSIONS / 两 DELTA 派生均冻结", () => {
expect(Object.isFrozen(BASE_EXTENSIONS)).toBe(true);
expect(Object.isFrozen(REPAIR_DIAGNOSIS_DELTA)).toBe(true);
expect(Object.isFrozen(EMBEDDED_DEV_DELTA)).toBe(true);
expect(Object.isFrozen(REPAIR_DIAGNOSIS_DELTA.extensions)).toBe(true);
expect(Object.isFrozen(REPAIR_DIAGNOSIS_DELTA.tools)).toBe(true);
expect(Object.isFrozen(EMBEDDED_DEV_DELTA.extensions)).toBe(true);
expect(Object.isFrozen(EMBEDDED_DEV_DELTA.tools)).toBe(true);
});
it("状态-幂等:对已冻结对象再次 Object.freeze 不报错(不可达态验证)", () => {
expect(() => Object.freeze(BASE_PROFILE)).not.toThrow();
expect(() => Object.freeze(DOMAIN_TOOLS)).not.toThrow();
expect(Object.isFrozen(BASE_PROFILE)).toBe(true);
});
it("状态-派生冻结:toolsFor / mergeProfiles / diffProfiles 返回值均冻结", () => {
expect(Object.isFrozen(toolsFor(["glm-provider"]))).toBe(true);
expect(Object.isFrozen(toolsFor([]))).toBe(true);
const merged = mergeProfiles(BASE_PROFILE, {
extensions: ["pdf-reader"],
tools: toolsFor(["pdf-reader"]),
});
expect(Object.isFrozen(merged)).toBe(true);
expect(Object.isFrozen(merged.extensions)).toBe(true);
expect(Object.isFrozen(merged.tools)).toBe(true);
const d = diffProfiles(BASE_PROFILE, REPAIR_DIAGNOSIS_PROFILE);
expect(Object.isFrozen(d)).toBe(true);
expect(Object.isFrozen(d.added)).toBe(true);
expect(Object.isFrozen(d.removed)).toBe(true);
});
it("状态-重入:并发调用纯函数无状态污染(同步重入安全)", () => {
// 纯函数无共享可变态;多次/嵌套调用结果一致
const r1 = toolsFor(["glm-provider", "mcp-bridge"]);
const r2 = toolsFor(["glm-provider", "mcp-bridge"]);
expect([...r1]).toEqual([...r2]);
// 嵌套:mergeProfiles 内调 toolsFor
const nested = mergeProfiles(mergeProfiles(BASE_PROFILE, {
extensions: ["pdf-reader"],
tools: toolsFor(["pdf-reader"]),
}), {
extensions: ["peripheral-probe"],
tools: toolsFor(["peripheral-probe"]),
});
expect(nested.extensions).toContain("pdf-reader");
expect(nested.extensions).toContain("peripheral-probe");
expect(nested.tools).toContain("read_pdf");
expect(nested.tools).toContain("bus_probe");
});
});
// ============================================================================
// ⑤ 变异测试 — 6 个 seeded bugs(M1~M6)
// ----------------------------------------------------------------------------
// kill harness 范式:killer(fn) 对真实输出成立(不抛),对 mutant 输出失败
// (抛 AssertionError)。expect(() => killer(real)).not.toThrow() 证明真实通过;
// expect(() => killer(mutant)).toThrow() 证明 mutant 被杀手断言杀死。
// ============================================================================
describe("⑤ 变异测试 — M1:并集去重条件反转(!seen.has → seen.has)", () => {
// BUG: unionStable 中 `if (!seen.has(x))` 改为 `if (seen.has(x))`,
// delta 中 base 未含的新项被丢弃,base 已含项被重复追加。
// 杀手断言:delta 中 base 未含的新项必须在结果中出现(恰好 1 次)。
const killer = (fn: typeof unionStableReal) => {
const out = fn(["a"], ["b"]); // b 不在 base
expect(out).toContain("b");
expect([...out]).toEqual(["a", "b"]);
};
it("M1 真实通过:unionStableReal 追加 delta 新项", () => {
expect(() => killer(unionStableReal)).not.toThrow();
});
it("M1 被杀:unionStableM1 丢弃 delta 新项(杀手断言失败)", () => {
expect(() => killer(unionStableM1)).toThrow();
});
it("M1 被杀(直接观测):mutant 丢弃新项 + 重复已含项", () => {
expect([...unionStableM1(["a"], ["b"])]).toEqual(["a"]);
expect(unionStableM1(["a"], ["a"]).filter((x) => x === "a").length)
.toBe(2);
});
it("M1 端到端:mergeProfiles delta 新扩展出现在结果(真实对,M1 错)", () => {
const delta = {
extensions: ["pdf-reader"],
tools: toolsFor(["pdf-reader"]),
};
const real = mergeProfiles(BASE_PROFILE, delta);
expect([...real.extensions]).toContain("pdf-reader");
const m1Merged = Object.freeze({
id: BASE_PROFILE.id,
extensions: unionStableM1(BASE_PROFILE.extensions, delta.extensions),
tools: unionStableM1(BASE_PROFILE.tools, delta.tools),
note: BASE_PROFILE.note,
}) as Profile;
expect([...m1Merged.extensions]).not.toContain("pdf-reader");
});
});
describe("⑤ 变异测试 — M2:未知域用 ?? [] 默认空(fail-closed 失效)", () => {
// BUG: toolsFor 中 `if (tools === undefined) throw` 改为
// `const tools = DOMAIN_TOOLS[d] ?? []`,未知域取值 undefined → 兜底空数组,
// mutant 不抛错,未知域静默产出空工具集(fail-closed 失效)。
// 杀手断言:未知域必抛 domain-specific Error(消息含域名)。
const killer = (fn: typeof toolsForReal) => {
expect(() => fn(["no-such-domain"])).toThrow(
/unknown extension domain "no-such-domain"/,
);
};
it("M2 真实通过:toolsForReal 未知域抛 domain-specific Error", () => {
expect(() => killer(toolsForReal)).not.toThrow();
});
it("M2 被杀:toolsForM2 不抛(杀手断言失败)", () => {
expect(() => killer(toolsForM2)).toThrow();
});
it("M2 被杀(直接观测):mutant 静默吞掉未知域产出已知域工具", () => {
expect(() => toolsForM2(["no-such-domain"])).not.toThrow();
expect([...toolsForM2(["no-such-domain"])]).toEqual([]);
const m2Out = toolsForM2(["glm-provider", "no-such", "mcp-bridge"]);
expect([...m2Out]).toEqual(["glm_status", "mcp_list", "mcp_call"]);
});
it("M2 端到端:toolsFor 未知域必抛(真实对,M2 错)", () => {
expect(() => toolsFor(["typo-domain"])).toThrow(
/unknown extension domain "typo-domain"/,
);
expect(() => toolsForM2(["typo-domain"])).not.toThrow();
});
});
describe("⑤ 变异测试 — M3:漏 Object.freeze(mergeProfiles 结果可变)", () => {
// BUG: mergeProfiles 末尾漏 Object.freeze,结果对象可变。
// 杀手断言:篡改 mergeProfiles 结果 id 必抛 TypeError。
const killer = (fn: typeof mergeProfilesReal) => {
const merged = fn(BASE_PROFILE, {
extensions: ["pdf-reader"],
tools: toolsFor(["pdf-reader"]),
});
expect(() => {
(merged as Profile & { id: string }).id = "evil";
}).toThrow(TypeError);
};
it("M3 真实通过:mergeProfilesReal 结果冻结,篡改抛 TypeError", () => {
expect(() => killer(mergeProfilesReal)).not.toThrow();
});
it("M3 被杀:mergeProfilesM3 结果未冻结,篡改不抛(杀手断言失败)", () => {
expect(() => killer(mergeProfilesM3)).toThrow();
});
it("M3 被杀(直接观测):mutant 结果 Object.isFrozen=false", () => {
const delta = {
extensions: ["pdf-reader"],
tools: toolsFor(["pdf-reader"]),
};
expect(Object.isFrozen(mergeProfilesReal(BASE_PROFILE, delta))).toBe(true);
expect(Object.isFrozen(mergeProfilesM3(BASE_PROFILE, delta))).toBe(false);
});
it("M3 端到端:篡改真实 mergeProfiles extensions.push 抛 TypeError(真实对,M3 错)", () => {
const delta = { extensions: ["pdf-reader"], tools: toolsFor(["pdf-reader"]) };
const real = mergeProfiles(BASE_PROFILE, delta);
expect(() => {
(real.extensions as string[]).push("evil");
}).toThrow(TypeError);
const mutant = mergeProfilesM3(BASE_PROFILE, delta);
expect(() => {
(mutant.extensions as string[]).push("evil");
}).not.toThrow();
});
});
describe("⑤ 变异测试 — M4:diffProfiles added/removed 互换", () => {
// BUG: diffProfiles 返回时 added 与 removed 互换。
// 杀手断言:diff(base, repair).added 含 repair 专属扩展 pdf-reader。
const killer = (fn: typeof diffProfilesReal) => {
const d = fn(BASE_PROFILE, REPAIR_DIAGNOSIS_PROFILE);
expect([...d.added]).toContain("pdf-reader");
expect([...d.added]).toContain("datasheet-rag");
expect(d.removed.length).toBe(0);
};
it("M4 真实通过:diffProfilesReal added 含 repair 专属", () => {
expect(() => killer(diffProfilesReal)).not.toThrow();
});
it("M4 被杀:diffProfilesM4 added 被换成 removed(杀手断言失败)", () => {
expect(() => killer(diffProfilesM4)).toThrow();
});
it("M4 被杀(方向敏感):diff(repair, embedded) 真实 added=embedded、removed=repair", () => {
const real = diffProfiles(REPAIR_DIAGNOSIS_PROFILE, EMBEDDED_DEV_PROFILE);
expect([...real.added]).toContain("cross-compile");
expect([...real.added]).toContain("flash");
expect([...real.removed]).toContain("pdf-reader");
const mutant = diffProfilesM4(REPAIR_DIAGNOSIS_PROFILE, EMBEDDED_DEV_PROFILE);
expect([...mutant.added]).not.toContain("cross-compile");
expect([...mutant.added]).toContain("pdf-reader");
});
});
describe("⑤ 变异测试 — M5:mergeProfiles 漏继承 note(note: undefined)", () => {
// BUG: mergeProfiles 返回 `note: undefined` 而非 `note: base.note`。
// 契约要求 id/note 继承 base;mutant 丢失 note。
// 杀手断言:mergeProfiles 空 delta 时 note === base.note(非 undefined)。
const killer = (fn: typeof mergeProfilesReal) => {
const merged = fn(BASE_PROFILE, { extensions: [], tools: [] });
expect(merged.note).toBe(BASE_PROFILE.note);
expect(merged.note).not.toBeUndefined();
};
it("M5 真实通过:mergeProfilesReal note 继承 base", () => {
expect(() => killer(mergeProfilesReal)).not.toThrow();
});
it("M5 被杀:mergeProfilesM5 note 丢失(杀手断言失败)", () => {
expect(() => killer(mergeProfilesM5)).toThrow();
});
it("M5 端到端:真实 mergeProfiles 单 delta 时 note 仍继承(真实对,M5 错)", () => {
const delta = {
extensions: ["peripheral-probe"],
tools: toolsFor(["peripheral-probe"]),
};
expect(mergeProfiles(BASE_PROFILE, delta).note).toBe(BASE_PROFILE.note);
expect(mergeProfilesM5(BASE_PROFILE, delta).note).not.toBe(
BASE_PROFILE.note,
);
expect(mergeProfilesM5(BASE_PROFILE, delta).note).toBeUndefined();
});
});
describe("⑤ 变异测试 — M6:unionStable 漏 seen.add(delta 内部重复不去重)", () => {
// BUG: unionStable 中新项追加后漏 `seen.add(x)`。
// 后果:delta 内部重复的非 base 项被多次追加(去重失效,仅对 delta 内部重复)。
// 杀手断言:delta 含内部重复非 base 项 → 结果中该项恰 1 份。
const killer = (fn: typeof unionStableReal) => {
const out = fn(["a"], ["b", "b"]); // b 不在 base,delta 内重复
expect(out.filter((x) => x === "b")).toStrictEqual(["b"]);
};
it("M6 真实通过:unionStableReal 对 delta 内重复去重为 1", () => {
expect(() => killer(unionStableReal)).not.toThrow();
});
it("M6 被杀:unionStableM6 不去重 delta 内重复(杀手断言失败)", () => {
expect(() => killer(unionStableM6)).toThrow();
});
it("M6 被杀(直接观测):mutant 对 delta 内重复产出 2 份", () => {
expect(unionStableM6(["a"], ["b", "b"]).filter((x) => x === "b").length)
.toBe(2);
expect(unionStableReal(["a"], ["b", "b"]).filter((x) => x === "b").length)
.toBe(1);
});
});
describe("⑤ 变异测试 — 汇总:6 个 mutant 均被杀手断言区分(被杀)", () => {
it("汇总:每个 mutant 至少一处输出/行为与真实不同(被杀)", () => {
// M1:新项被丢弃
expect([...unionStableReal(["a"], ["b"])]).not.toEqual([
...unionStableM1(["a"], ["b"]),
]);
// M2:未知域不抛
let m2threw = true;
try {
toolsForM2(["no-such"]);
m2threw = false;
} catch {
m2threw = true;
}
expect(m2threw).toBe(false); // mutant 不抛 = 与真实不同
expect(() => toolsForReal(["no-such"])).toThrow();
// M3:未冻结
expect(Object.isFrozen(mergeProfilesM3(BASE_PROFILE, {
extensions: [],
tools: [],
}))).toBe(false);
expect(Object.isFrozen(mergeProfilesReal(BASE_PROFILE, {
extensions: [],
tools: [],
}))).toBe(true);
// M4:added 互换
expect([...diffProfilesM4(BASE_PROFILE, REPAIR_DIAGNOSIS_PROFILE).added])
.not.toEqual([...diffProfilesReal(BASE_PROFILE, REPAIR_DIAGNOSIS_PROFILE).added]);
// M5:note 丢失
expect(mergeProfilesM5(BASE_PROFILE, { extensions: [], tools: [] }).note)
.not.toBe(mergeProfilesReal(BASE_PROFILE, { extensions: [], tools: [] }).note);
// M6:delta 内重复不去重
expect([...unionStableReal(["a"], ["b", "b"])]).not.toEqual([
...unionStableM6(["a"], ["b", "b"]),
]);
});
});
// ============================================================================
// ⑥ 对抗 / fuzz —— 畸形/滥用输入
// ============================================================================
describe("⑥ 对抗/fuzz — 畸形/滥用输入", () => {
it("fuzz-undefined 元素:toolsFor([undefined]) 抛错(fail-closed)", () => {
expect(() => toolsFor([undefined as unknown as string])).toThrow();
});
it("fuzz-null 元素:toolsFor([null]) 抛错(fail-closed)", () => {
expect(() => toolsFor([null as unknown as string])).toThrow();
});
it("fuzz-NaN 元素:toolsFor([NaN]) 抛错(DOMAIN_TOOLS['NaN'] undefined)", () => {
expect(() => toolsFor([NaN as unknown as string])).toThrow();
});
it("fuzz-数字串元素:toolsFor([123]) 抛错('123' 非域)", () => {
expect(() => toolsFor([123 as unknown as string])).toThrow();
});
it("fuzz-空串元素:toolsFor(['']) 抛错('' 非域)", () => {
expect(() => toolsFor([""])).toThrow(/unknown extension domain ""/);
});
it("fuzz-巨大输入:toolsFor(全域重复 1000 次) 不崩且结果等于全域去重", () => {
const allDomains = Object.keys(DOMAIN_TOOLS);
const huge: string[] = [];
for (let i = 0; i < 1000; i++) {
huge.push(allDomains[i % allDomains.length]);
}
const got = toolsFor(huge);
const once = toolsFor(allDomains);
expect([...got]).toEqual([...once]);
});
it("fuzz-非 string 元素:mergeProfiles delta.extensions 含数字 → 不崩(并集原样保留)", () => {
// mergeProfiles 不校验元素类型(并集原语),数字被当 string 比较
const merged = mergeProfiles(BASE_PROFILE, {
extensions: [123 as unknown as string],
tools: [],
});
// 123 被 Set 当作不同项追加(与 base 字符串不同)
expect(merged.extensions).toContain(123);
});
it("fuzz-mergeProfiles null base → 抛 TypeError(访问 base.id)", () => {
expect(() =>
mergeProfiles(null as unknown as Profile, {
extensions: [],
tools: [],
}),
).toThrow(TypeError);
});
it("fuzz-mergeProfiles undefined delta → 抛 TypeError", () => {
expect(() =>
mergeProfiles(
BASE_PROFILE,
undefined as unknown as Pick<Profile, "extensions" | "tools">,
),
).toThrow(TypeError);
});
it("fuzz-diffProfiles 重复扩展:a 含重复 → removed 保留重复(实现不主动去重)", () => {
// base.ts diffProfiles 文档(base.ts:244-248)明确声明"不主动去重":
// 遍历 a.extensions 逐条 push,含重复输入 → 输出含重复。
// 真实 profile 无重复扩展,故实际无害;此 fuzz 断言"实现不主动去重"的当前行为。
const a: Profile = Object.freeze({
id: "a",
extensions: Object.freeze(["x", "x", "y"]) as readonly string[],
tools: Object.freeze([]) as readonly string[],
note: undefined,
}) as Profile;
const b: Profile = Object.freeze({
id: "b",
extensions: Object.freeze(["y"]) as readonly string[],
tools: Object.freeze([]) as readonly string[],
note: undefined,
}) as Profile;
const d = diffProfiles(a, b);
// 当前行为:removed 含重复 ["x","x"](不主动去重,与文档一致)
expect([...d.removed]).toEqual(["x", "x"]);
});
it("fuzz-resolveProfile 数字/对象/布尔 id → 抛错", () => {
expect(() => resolveProfile(123 as unknown as string)).toThrow();
expect(() => resolveProfile(true as unknown as string)).toThrow();
expect(() =>
resolveProfile({} as unknown as string),
).toThrow();
});
it("fuzz-并发重入:toolsFor 与 mergeProfiles 嵌套/交错调用结果确定", () => {
const r1 = toolsFor(["glm-provider", "mcp-bridge"]);
const r2 = toolsFor(["mcp-bridge", "glm-provider"]);
// 集合相同(去重),但序不同(保序)
expect(new Set(r1)).toEqual(new Set(r2));
const m1 = mergeProfiles(BASE_PROFILE, {
extensions: ["pdf-reader"],
tools: toolsFor(["pdf-reader"]),
});
const m2 = mergeProfiles(BASE_PROFILE, {
extensions: ["pdf-reader"],
tools: toolsFor(["pdf-reader"]),
});
expect([...m1.extensions]).toEqual([...m2.extensions]);
});
it("fuzz-超长 id:resolveProfile(超长串) 抛错(非注册 id)", () => {
const long = "x".repeat(10000);
expect(() => resolveProfile(long)).toThrow(/unknown profile id/);
});
it("fuzz-unicode/空白 id:resolveProfile 不误匹配(大小写+空白敏感)", () => {
expect(() => resolveProfile(" base")).toThrow();
expect(() => resolveProfile("base ")).toThrow();
expect(() => resolveProfile("base")).toThrow();
expect(() => resolveProfile(" base")).toThrow();
});
});
// ============================================================================
// ⑥ 对抗/fuzz — F1 回归(已修复:Object.prototype 继承键 fail-closed)
// ----------------------------------------------------------------------------
// F1 原 findings[]:resolveProfile 用 `PROFILE_REGISTRY[id]` 查表(index.ts),
// 该属性查找走原型链,对 "toString"/"constructor"/"__proto__" 等 Object.prototype
// 继承键取到继承成员(!== undefined → 不抛 → 返回函数/对象当 Profile 用)。
// 修复(index.ts):改用 Object.hasOwn(PROFILE_REGISTRY, id) 判定,只认自身属性,
// 继承键一律判为未注册 → fail-closed 抛错。原 it.fails 标记已翻成 it(修复后
// 断言成功 → 绿),转为永久回归守护,防止退回原型链查表。
// ============================================================================
describe("⑥ 对抗/fuzz — F1 回归:resolveProfile 对 Object.prototype 继承键 fail-closed(已修复)", () => {
for (const key of PROTO_KEYS) {
it(`F1 回归:resolveProfile("${key}") 抛 fail-closed(不返回继承成员)`, () => {
expect(() => resolveProfile(key)).toThrow(/unknown profile id/);
expect(() => resolveProfile(key)).toThrow(/fail-closed/);
});
}
it("F1 回归:resolveProfile('__proto__') 抛而非返回 Object.prototype", () => {
expect(() => resolveProfile("__proto__")).toThrow(/unknown profile id/);
});
// 对照组:正常未注册 id 也抛(证明 fail-closed 对继承键与普通键一致)
it("F1 对照:正常未注册 id 'nope' 抛错(fail-closed 一致)", () => {
expect(() => resolveProfile("nope")).toThrow(/unknown profile id "nope"/);
});
// 回归:继承键不再返回继承成员(直接观测,不依赖 it.fails 语义)
it("F1 回归:resolveProfile('toString') 抛错而非返回 function", () => {
let got: unknown;
try {
got = resolveProfile("toString");
} catch {
got = "THREW";
}
expect(got).toBe("THREW");
});
it("F1 回归:resolveProfile('__proto__') 抛错而非返回 object", () => {
let got: unknown;
try {
got = resolveProfile("__proto__");
} catch {
got = "THREW";
}
expect(got).toBe("THREW");
});
});
// ============================================================================
// ⑦ 元蜕变 / 不变式
// ============================================================================
describe("⑦ 元蜕变/不变式 — append 两次 = replay 等价(并集结合律)", () => {
// 不变式:mergeProfiles(mergeProfiles(base, d1), d2)
// ≡ mergeProfiles(base, d1++d2) (在 extensions/tools 并集语义下)
it("不变式:分两步合并 = 一次性合并(extensions 集合等价)", () => {
const d1 = {
extensions: ["pdf-reader"],
tools: toolsFor(["pdf-reader"]),
};
const d2 = {
extensions: ["peripheral-probe"],
tools: toolsFor(["peripheral-probe"]),
};
const twoStep = mergeProfiles(mergeProfiles(BASE_PROFILE, d1), d2);
const oneShot = mergeProfiles(BASE_PROFILE, {
extensions: [...d1.extensions, ...d2.extensions],
tools: toolsFor(["pdf-reader", "peripheral-probe"]),
});
expect(new Set(twoStep.extensions)).toEqual(new Set(oneShot.extensions));
expect(new Set(twoStep.tools)).toEqual(new Set(oneShot.tools));
// 序也一致(base 在前,delta 按 d1→d2 序追加)
expect([...twoStep.extensions]).toEqual([...oneShot.extensions]);
expect([...twoStep.tools]).toEqual([...oneShot.tools]);
});
it("不变式:三步合并 = 全量一次性合并(repair 三差异域)", () => {
const repairDeltaExt = REPAIR_DIAGNOSIS_DELTA.extensions;
const step1 = mergeProfiles(BASE_PROFILE, {
extensions: [repairDeltaExt[0]],
tools: toolsFor([repairDeltaExt[0]]),
});
const step2 = mergeProfiles(step1, {
extensions: [repairDeltaExt[1]],
tools: toolsFor([repairDeltaExt[1]]),
});
const step3 = mergeProfiles(step2, {
extensions: [repairDeltaExt[2]],
tools: toolsFor([repairDeltaExt[2]]),
});
// 等价于直接 repair profile 的 extensions 集合
expect(new Set(step3.extensions)).toEqual(
new Set(REPAIR_DIAGNOSIS_PROFILE.extensions),
);
expect(new Set(step3.tools)).toEqual(
new Set(REPAIR_DIAGNOSIS_PROFILE.tools),
);
});
});
describe("⑦ 元蜕变/不变式 — freeze → 篡改抛 TypeError(单调不可变)", () => {
it("不变式:所有导出常量 + 所有派生函数返回值篡改均抛 TypeError", () => {
const tamper = (fn: () => void) => expect(fn).toThrow(TypeError);
tamper(() => {
(BASE_PROFILE as Profile & { id: string }).id = "x";
});
tamper(() => {
(REPAIR_DIAGNOSIS_PROFILE as Profile & { id: string }).id = "x";
});
tamper(() => {
(EMBEDDED_DEV_PROFILE as Profile & { id: string }).id = "x";
});
tamper(() => {
(BASE_EXTENSIONS as string[]).push("x");
});
tamper(() => {
(REPAIR_DIAGNOSIS_DELTA.extensions as string[]).push("x");
});
tamper(() => {
(EMBEDDED_DEV_DELTA.tools as string[]).push("x");
});
// 派生
tamper(() => {
(toolsFor(["glm-provider"]) as string[]).push("x");
});
tamper(() => {
(mergeProfiles(BASE_PROFILE, {
extensions: [],
tools: [],
}) as Profile & { id: string }).id = "x";
});
tamper(() => {
(diffProfiles(BASE_PROFILE, REPAIR_DIAGNOSIS_PROFILE).added as string[])
.push("x");
});
});
});
describe("⑦ 元蜕变/不变式 — 单调 fail-closed(unusable = 拒绝)", () => {
it("不变式:resolveProfile 未知 id 不返回 undefined/默认,必抛", () => {
// 不返回 undefined
let result: Profile | undefined;
try {
result = resolveProfile("does-not-exist");
} catch {
result = undefined;
}
expect(result).toBeUndefined(); // 抛错 → 未赋值
});
it("不变式:toolsFor 未知域不静默返回空,必抛", () => {
// 纯未知域:必抛而非返回空
expect(() => toolsFor(["totally-fake"])).toThrow();
// 与 toolsFor([]) 的空数组语义对照:空输入返回空是合法的
expect(toolsFor([]).length).toBe(0);
});
it("不变式:resolveProfile 返回注册表冻结实例(引用共享,不复制)", () => {
// 多次调用返回同一引用(确定性、无复制)
expect(resolveProfile("base")).toBe(resolveProfile("base"));
expect(resolveProfile("repair-diagnosis")).toBe(
resolveProfile("repair-diagnosis"),
);
expect(resolveProfile("embedded-dev")).toBe(
resolveProfile("embedded-dev"),
);
});
});
describe("⑦ 元蜕变/不变式 — mergeProfiles 不重派生(短路:并集原语不调 toolsFor)", () => {
// 不变式:mergeProfiles 对 delta.tools 做原样并集,不调 toolsFor 重新派生。
// 即:若 delta.tools 与 delta.extensions 不一致,结果反映 delta.tools 字面值,
// 不短路重派生。这验证了"并集原语"边界——mergeProfiles 是 dumb combiner。
it("不变式:delta.tools 与 delta.extensions 不一致时,结果 tools 取 delta.tools 字面值", () => {
const merged = mergeProfiles(BASE_PROFILE, {
extensions: ["pdf-reader", "peripheral-probe"],
// 故意只给一个工具(不一致)
tools: ["read_pdf"],
});
// extensions 含两个域
expect(merged.extensions).toContain("pdf-reader");
expect(merged.extensions).toContain("peripheral-probe");
// tools 只含 delta.tools 字面 + base(不重派生 bus_probe)
expect(merged.tools).toContain("read_pdf");
expect(merged.tools).not.toContain("bus_probe");
});
it("不变式:真实 REPAIR/EMBEDDED delta 的 tools 与 extensions 一致(派生自 toolsFor)", () => {
// 契约保证:delta.tools = toolsFor(delta.extensions)
expect([...REPAIR_DIAGNOSIS_DELTA.tools]).toEqual([
...toolsFor([...REPAIR_DIAGNOSIS_DELTA.extensions]),
]);
expect([...EMBEDDED_DEV_DELTA.tools]).toEqual([
...toolsFor([...EMBEDDED_DEV_DELTA.extensions]),
]);
});
});
describe("⑦ 元蜕变/不变式 — 命名 profile = mergeProfiles(base, delta) + 覆盖 id/note", () => {
it("不变式:REPAIR_DIAGNOSIS_PROFILE.extensions = base ∪ repair delta(集合等价)", () => {
const expected = new Set([
...BASE_PROFILE.extensions,
...REPAIR_DIAGNOSIS_DELTA.extensions,
]);
expect(new Set(REPAIR_DIAGNOSIS_PROFILE.extensions)).toEqual(expected);
});
it("不变式:EMBEDDED_DEV_PROFILE.tools = base ∪ embedded delta(集合等价)", () => {
const expected = new Set([
...BASE_PROFILE.tools,
...EMBEDDED_DEV_DELTA.tools,
]);
expect(new Set(EMBEDDED_DEV_PROFILE.tools)).toEqual(expected);
});
it("不变式:两业务 profile ⊇ base(extensions + tools 双超集)", () => {
const baseExt = new Set(BASE_PROFILE.extensions);
const baseTools = new Set(BASE_PROFILE.tools);
for (const p of [REPAIR_DIAGNOSIS_PROFILE, EMBEDDED_DEV_PROFILE]) {
for (const e of baseExt) {
expect(new Set(p.extensions).has(e)).toBe(true);
}
for (const t of baseTools) {
expect(new Set(p.tools).has(t)).toBe(true);
}
}
});
it("不变式:repair 与 embedded 差异扩展不重叠", () => {
const repairOnly = new Set(REPAIR_DIAGNOSIS_DELTA.extensions);
for (const e of EMBEDDED_DEV_DELTA.extensions) {
expect(repairOnly.has(e)).toBe(false);
}
const embeddedOnly = new Set(EMBEDDED_DEV_DELTA.extensions);
for (const e of REPAIR_DIAGNOSIS_DELTA.extensions) {
expect(embeddedOnly.has(e)).toBe(false);
}
});
it("不变式:每个 profile 的 tools ⊆ DOMAIN_TOOLS 全量(无魔法串)", () => {
for (const p of ALL_PROFILES) {
for (const t of p.tools) {
expect(ALL_TOOLS_SET.has(t)).toBe(true);
}
}
});
it("不变式:repair 不含 embedded 专属工具,反之亦然", () => {
expect(REPAIR_DIAGNOSIS_PROFILE.tools).not.toContain("flash");
expect(REPAIR_DIAGNOSIS_PROFILE.tools).not.toContain("xcompile");
expect(REPAIR_DIAGNOSIS_PROFILE.tools).not.toContain("reg");
expect(EMBEDDED_DEV_PROFILE.tools).not.toContain("read_pdf");
expect(EMBEDDED_DEV_PROFILE.tools).not.toContain("datasheet_query");
expect(EMBEDDED_DEV_PROFILE.tools).not.toContain("bus_probe");
});
it("不变式:DOMAIN_TOOLS 每个工具名在真实扩展 defineTool name 中有 referent", () => {
for (const t of ALL_TOOLS_SET) {
expect(KNOWN_DEFINE_TOOL_NAMES.has(t)).toBe(true);
}
// 反向:每个已知 defineTool name 必在 DOMAIN_TOOLS 某域下
for (const name of KNOWN_DEFINE_TOOL_NAMES) {
expect(ALL_TOOLS_SET.has(name)).toBe(true);
}
});
});
describe("⑦ 元蜕变/不变式 — diffProfiles 对称性 / 幂等性", () => {
it("不变式:diff(a,b) 的 added = diff(b,a) 的 removed(方向反转对称)", () => {
const ab = diffProfiles(BASE_PROFILE, REPAIR_DIAGNOSIS_PROFILE);
const ba = diffProfiles(REPAIR_DIAGNOSIS_PROFILE, BASE_PROFILE);
expect([...ab.added]).toEqual([...ba.removed]);
expect([...ab.removed]).toEqual([...ba.added]);
});
it("不变式:diff 幂等(重复调用结果等价)", () => {
const d1 = diffProfiles(BASE_PROFILE, EMBEDDED_DEV_PROFILE);
const d2 = diffProfiles(BASE_PROFILE, EMBEDDED_DEV_PROFILE);
expect([...d1.added]).toEqual([...d2.added]);
expect([...d1.removed]).toEqual([...d2.removed]);
});
it("不变式:diff 结果 added/removed 对无重复输入各自保序(无重复)", () => {
// 真实 profile 的 extensions 无重复,故 added/removed 无重复(输入驱动的不重复)
const d = diffProfiles(BASE_PROFILE, EMBEDDED_DEV_PROFILE);
const addedDedup = new Set(d.added);
expect(addedDedup.size).toBe(d.added.length);
const removedDedup = new Set(d.removed);
expect(removedDedup.size).toBe(d.removed.length);
});
it("不变式:diff 三角不变式——added ∪ removed ∪ 交集 = a∪b extensions 全集", () => {
const d = diffProfiles(BASE_PROFILE, REPAIR_DIAGNOSIS_PROFILE);
const union = new Set([...BASE_PROFILE.extensions, ...REPAIR_DIAGNOSIS_PROFILE.extensions]);
const onlyB = new Set(d.added); // b 有 a 无
const onlyA = new Set(d.removed); // a 有 b 无
const both = new Set([...BASE_PROFILE.extensions].filter((e) => union.has(e) && !onlyA.has(e) && !onlyB.has(e)));
// added ∪ removed ∪ 交集 应等于 a∪b 全集
const recon = new Set([...onlyA, ...onlyB, ...both]);
expect(recon).toEqual(union);
});
});