physical_byte_agent/tests/hardware-state.test.ts
d-robotics 06a19a61e8 refactor: 重构为生产级 pi Agent 项目(散装脚本 → npm 库包 + 单一 barrel 装配)
- 工程形态:@d-robotics/physical-byte-agent npm 库包
  - 单一 barrel src/extensions/index.ts 装配 21 域扩展(package.json pi.extensions 清单 + .pi/extensions/index.ts 重导出,pi 自动加载)
  - src/agent.ts PhysicalByteAgent(launch() 程序化调 createAgentSession + verifyAssembly() 离线自检)
  - bin/pba.ts CLI、models.json(glm-5.2 条目)、README.md、AGENTS.md
- 命名:全部域命名(glm-provider/safety-gate/flash/jtag-debugger/loop-orchestrator…),去掉 F 编号
- 架构:内联逻辑 + 顶层仅 import type(esbuild 擦除)+ 工厂内动态 import defineTool/Type
  - 逻辑离线可单测(不解析 pi),工厂在真 pi 内装配;fail-closed 语义保留
- 两命门:glm-provider.ts buildGlmModelConfig()(thinkingFormat:qwen + maxTokens:8192 + thinkingLevelMap 全 null)+ detectEmptyOutput();normalizeHexArg() + makeHexNormalizingPrepareArguments()
- 验证:tsc --noEmit 0 错(对 src/types/pi.d.ts 类型镜像)+ vitest 732 用例/21 文件全绿 + tsx 离线装配冒烟 21 扩展全就位
- 密钥铁律:grep sk-nAm 在 src/tests/bin/.pi = 0,key 全程 ${DROBOTICS_LLM_KEY} 占位

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-13 19:54:20 +08:00

282 lines
10 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.

import { describe, it, expect } from "vitest";
import {
makeHwEntry,
replayFromEntries,
selectProtected,
formatHwStateAsText,
buildCompactionProtection,
HW_STATE_CUSTOM_TYPE,
type HwEntry,
} from "../src/extensions/hardware-state.js";
// 辅助:构造一条 hw entry,ts 固定
function hw(type: string, data: Record<string, unknown>, ts: number): HwEntry {
return makeHwEntry(type, data, ts);
}
describe("hardware-state 序列化 — makeHwEntry", () => {
it("产出 CustomEntry{customType:'hw:state', data:{type,data,ts}}", () => {
const e = makeHwEntry("i2c", { bus: 0, occupiedAddresses: [0x48, 0x68] }, 1730000000000);
expect(e.customType).toBe("hw:state");
expect(e.data.type).toBe("i2c");
expect(e.data.ts).toBe(1730000000000);
expect(e.data.data).toEqual({ bus: 0, occupiedAddresses: [0x48, 0x68] });
});
it("HW_STATE_CUSTOM_TYPE 常量 = 'hw:state'", () => {
expect(HW_STATE_CUSTOM_TYPE).toBe("hw:state");
});
it("省略 timestamp 时用 Date.now() 填充 ts", () => {
const before = Date.now();
const e = makeHwEntry("gpio", { pin: 33, direction: "out" });
const after = Date.now();
expect(e.data.ts).toBeGreaterThanOrEqual(before);
expect(e.data.ts).toBeLessThanOrEqual(after);
});
it("data 为空对象也合法(fail-open 不崩)", () => {
const e = makeHwEntry("serial", {}, 1);
expect(e.data.data).toEqual({});
expect(e.data.type).toBe("serial");
});
it("data 可携带任意嵌套结构(gdb 断点表)", () => {
const e = makeHwEntry(
"gdb",
{ breakpoints: [{ file: "main.c", line: 42, enabled: true }] },
5,
);
const bp = (e.data.data as { breakpoints: Array<{ line: number }> }).breakpoints;
expect(bp[0]?.line).toBe(42);
});
it("序列化+反序列化 round-trip 保留数据(JSONL 持久化模拟)", () => {
const e = makeHwEntry("openocd", { target: "stm32", state: "halted" }, 99);
const json = JSON.stringify(e);
const back = JSON.parse(json) as HwEntry;
expect(back.customType).toBe("hw:state");
expect(back.data.type).toBe("openocd");
expect(back.data.ts).toBe(99);
expect((back.data.data as { target: string }).target).toBe("stm32");
});
});
describe("hardware-state 重放重建 — replayFromEntries", () => {
it("lock acquire/release 重建 locks 表", () => {
const entries = [
hw("lock", { device: "i2c-bus-0", owner: "call-A", action: "acquire" }, 1),
hw("lock", { device: "gpiochip0", owner: "call-A", action: "acquire" }, 2),
hw("lock", { device: "i2c-bus-0", owner: "call-A", action: "release" }, 3),
];
const r = replayFromEntries(entries);
expect(r.locks["i2c-bus-0"]).toBeUndefined();
expect(r.locks["gpiochip0"]).toBe("call-A");
});
it("同设备 acquire 覆盖 owner(最后一次胜)", () => {
const entries = [
hw("lock", { device: "i2c-bus-0", owner: "A", action: "acquire" }, 1),
hw("lock", { device: "i2c-bus-0", owner: "B", action: "acquire" }, 2),
];
const r = replayFromEntries(entries);
expect(r.locks["i2c-bus-0"]).toBe("B");
});
it("i2c occupiedAddresses 落成锁(每地址一条)", () => {
const entries = [
hw("i2c", { bus: 1, occupiedAddresses: [0x48, 0x68], owner: "probe" }, 10),
];
const r = replayFromEntries(entries);
expect(r.locks["i2c-1-72"]).toBe("probe"); // 0x48=72
expect(r.locks["i2c-1-104"]).toBe("probe"); // 0x68=104
});
it("checkpoint 重建最新状态 + 累积 history", () => {
const entries = [
hw("checkpoint", { step: "edit", passed: true }, 100),
hw("checkpoint", { step: "compile", passed: true }, 200),
hw("checkpoint", { step: "flash", passed: false }, 300),
];
const r = replayFromEntries(entries);
expect(r.checkpoint).not.toBeNull();
expect(r.checkpoint!.currentStep).toBe("flash");
expect(r.checkpoint!.stepPassed).toBe(false);
expect(r.checkpoint!.history).toHaveLength(3);
expect(r.checkpoint!.history[2]?.passed).toBe(false);
});
it("flashLog 按序累积", () => {
const entries = [
hw("flash", { method: "dd", target: "/dev/mmcblk0", image: "boot.img", result: "ok" }, 1),
hw("flash", { method: "openocd", target: "stm32", image: "fw.elf", sha256: "abc", result: "fail" }, 2),
];
const r = replayFromEntries(entries);
expect(r.flashLog).toHaveLength(2);
expect(r.flashLog[0]!.method).toBe("dd");
expect(r.flashLog[0]!.result).toBe("ok");
expect(r.flashLog[1]!.method).toBe("openocd");
expect(r.flashLog[1]!.sha256).toBe("abc");
expect(r.flashLog[1]!.result).toBe("fail");
});
it("忽略非 hw:state entry(向后兼容,旧 session 不崩)", () => {
const entries = [
{ customType: "glm:adapter-loaded", data: {} } as unknown as HwEntry,
{ type: "custom", customType: "safegate:override", data: {} } as unknown as HwEntry,
hw("lock", { device: "i2c-bus-0", owner: "A", action: "acquire" }, 1),
];
const r = replayFromEntries(entries);
expect(r.locks["i2c-bus-0"]).toBe("A");
expect(r.flashLog).toHaveLength(0);
expect(r.checkpoint).toBeNull();
});
it("空 entries 数组返回空状态", () => {
const r = replayFromEntries([]);
expect(r.locks).toEqual({});
expect(r.checkpoint).toBeNull();
expect(r.flashLog).toEqual([]);
});
it("乱序/缺字段 lock entry fail-closed 不崩", () => {
const entries = [
hw("lock", {}, 1),
hw("lock", { device: "x" }, 2),
hw("i2c", {}, 3),
];
const r = replayFromEntries(entries);
// 不抛异常;device:"x" 无 owner 仍记一条空 owner 锁,无幽灵条目
expect(Object.keys(r.locks)).toEqual(["x"]);
expect(r.locks["x"]).toBe("");
expect(r.flashLog).toEqual([]);
expect(r.checkpoint).toBeNull();
});
});
describe("hardware-state compaction 保护 — selectProtected", () => {
it("返回最近 N 条 hw entry(keepLatestPerType:false 严格截断)", () => {
const entries = [
hw("i2c", { bus: 0 }, 1),
hw("gpio", { pin: 33 }, 2),
hw("gdb", { bp: 1 }, 3),
hw("serial", { baud: 115200 }, 4),
hw("flash", { method: "dd" }, 5),
];
const prot = selectProtected(entries, { keepRecent: 3, keepLatestPerType: false });
expect(prot).toHaveLength(3);
expect(prot[0]!.data.type).toBe("gdb");
expect(prot[2]!.data.type).toBe("flash");
});
it("默认 keepLatestPerType=true 时每类型代表都存活(5 类型全保留)", () => {
const entries = [
hw("i2c", { bus: 0 }, 1),
hw("gpio", { pin: 33 }, 2),
hw("gdb", { bp: 1 }, 3),
hw("serial", { baud: 115200 }, 4),
hw("flash", { method: "dd" }, 5),
];
const prot = selectProtected(entries, { keepRecent: 3 });
// 5 个不同类型,最近 3 条覆盖 gdb/serial/flash,补齐 i2c/gpio → 5 条
expect(prot).toHaveLength(5);
const types = prot.map((e) => e.data.type);
expect(types.sort()).toEqual(["flash", "gdb", "gpio", "i2c", "serial"]);
});
it("keepLatestPerType 保证每类型至少最新一条存活(跨 N 不丢关键状态)", () => {
const entries = [
hw("i2c", { bus: 0 }, 1),
hw("i2c", { bus: 1 }, 2),
hw("gpio", { pin: 33 }, 3),
hw("flash", { method: "dd" }, 4),
hw("flash", { method: "dd" }, 5),
];
// keepRecent=1 会只留最后 1 条,但 keepLatestPerType 会补齐每类型最新
const prot = selectProtected(entries, { keepRecent: 1, keepLatestPerType: true });
const types = prot.map((e) => e.data.type);
expect(types).toContain("i2c");
expect(types).toContain("gpio");
expect(types).toContain("flash");
// i2c 最新是 bus:1
const i2cEntry = prot.find((e) => e.data.type === "i2c")!;
expect((i2cEntry.data.data as { bus: number }).bus).toBe(1);
});
it("keepLatestPerType=false 时严格只取最近 N 条", () => {
const entries = [
hw("i2c", { bus: 0 }, 1),
hw("gpio", { pin: 33 }, 2),
hw("flash", { method: "dd" }, 3),
];
const prot = selectProtected(entries, { keepRecent: 1, keepLatestPerType: false });
expect(prot).toHaveLength(1);
expect(prot[0]!.data.type).toBe("flash");
});
it("无 hw entry 返回空数组", () => {
const prot = selectProtected([]);
expect(prot).toEqual([]);
});
it("hw entry 少于 N 时全部保留", () => {
const entries = [hw("i2c", { bus: 0 }, 1)];
const prot = selectProtected(entries, { keepRecent: 5 });
expect(prot).toHaveLength(1);
});
});
describe("hardware-state 上下文格式化 — formatHwStateAsText", () => {
it("产出 LLM 可读多行文本,含 type 与 ts", () => {
const e = makeHwEntry("i2c", { bus: 0, occupiedAddresses: [0x48] }, 1730000000000);
const txt = formatHwStateAsText(e);
expect(txt).toContain("hw:state");
expect(txt).toContain("i2c");
expect(txt).toContain("bus");
// 0x48=72, JSON.stringify 数组 → [72]
expect(txt).toContain("72");
expect(txt).toContain("2024");
});
it("嵌套对象以 JSON 序列化呈现", () => {
const e = makeHwEntry("gdb", { bps: [{ file: "a.c", line: 1 }] }, 1);
const txt = formatHwStateAsText(e);
expect(txt).toContain("bps");
expect(txt).toContain("a.c");
});
});
describe("hardware-state compaction 注入 — buildCompactionProtection", () => {
it("找到最后一条 hw entry,把 firstKeptEntryId 拉到它并扩展 summary", () => {
const branch = [
{ type: "custom", customType: "glm:adapter-loaded", data: {}, id: "e1" },
{ type: "custom", customType: "hw:state", data: { type: "i2c", data: { bus: 0 }, ts: 1 }, id: "e2" },
{ type: "user", id: "e3", customType: undefined, data: undefined },
];
const prep = { summary: "prev", previousSummary: "prev", firstKeptEntryId: "e3" };
const res = buildCompactionProtection(branch, prep);
expect(res).not.toBeNull();
expect(res!.compaction.firstKeptEntryId).toBe("e2");
expect(res!.compaction.summary).toContain("Hardware State");
expect(res!.compaction.summary).toContain("i2c");
});
it("无 hw entry 时返回 null(不干预 compaction)", () => {
const branch = [
{ type: "custom", customType: "glm:adapter-loaded", data: {}, id: "e1" },
];
const res = buildCompactionProtection(branch, { summary: "prev" });
expect(res).toBeNull();
});
it("previousSummary 为空时仍能拼出 Hardware State 段", () => {
const branch = [
{ type: "custom", customType: "hw:state", data: { type: "gpio", data: { pin: 33 }, ts: 1 }, id: "e1" },
];
const res = buildCompactionProtection(branch, null);
expect(res).not.toBeNull();
expect(res!.compaction.summary).toContain("Hardware State");
expect(res!.compaction.firstKeptEntryId).toBe("e1");
});
});