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

348 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 {
parseHexAddr,
toHexAddr,
isValidI2cAddr,
parseI2cDetect,
presentAddresses,
parseGpioInfo,
probeGpio,
probeI2c,
discoverI2cBuses,
probeSpi,
probeUdev,
probeMemSnap,
type ExecFn,
} from "../src/extensions/peripheral-probe.js";
// ---- mock ExecFn 工厂 ----
function mkExec(
map: Record<string, (args: string[]) => { stdout: string; stderr: string; exitCode: number }>,
): ExecFn {
return async (command: string, args: string[]) => {
const fn = map[command];
if (fn) return fn(args);
return { stdout: "", stderr: `command not found: ${command}`, exitCode: 127 };
};
}
// ---- i2cdetect 输出构造器(固定 3 字符列)----
function buildI2cDetect(
overrides: Record<string, "present" | "empty" | "inuse" | "blank"> = {},
): string {
const lines = [" 0 1 2 3 4 5 6 7 8 9 a b c d e f"];
for (let row = 0; row < 8; row++) {
const base = row * 16;
const header = base.toString(16).padStart(2, "0") + ":";
const fields: string[] = [];
for (let col = 0; col < 16; col++) {
const addr = base + col;
const key = "0x" + addr.toString(16).padStart(2, "0");
const v = overrides[key];
const def = row === 0 && col < 8 ? "blank" : "empty";
const kind = v ?? def;
if (kind === "present") fields.push(addr.toString(16).padStart(2, "0") + " ");
else if (kind === "empty") fields.push("-- ");
else if (kind === "inuse") fields.push("UU ");
else fields.push(" ");
}
lines.push(header + " " + fields.join(""));
}
return lines.join("\n");
}
describe("peripheral-probe hex 防御 — parseHexAddr", () => {
it('"0x50" → 0x50 (80)', () => {
expect(parseHexAddr("0x50")).toBe(0x50);
});
it('"80"(十进制)→ 80 = 0x50,与 hex 等值', () => {
// 缺陷 #8 核心:agent 传十进制 80 和 hex 0x50 解析为同一 I2C 地址
expect(parseHexAddr("80")).toBe(0x50);
expect(parseHexAddr("80")).toBe(parseHexAddr("0x50"));
});
it("number 80 → 80 = 0x50", () => {
expect(parseHexAddr(80)).toBe(0x50);
});
it("0x10 寄存器地址 → 16", () => {
expect(parseHexAddr("0x10")).toBe(16);
});
it('fallback 纯 hex "FF" → 0xFF', () => {
expect(parseHexAddr("FF")).toBe(0xff);
});
it("非法值抛错(fail-closed)", () => {
expect(() => parseHexAddr("")).toThrow();
expect(() => parseHexAddr("xyz")).toThrow();
});
it("toHexAddr 规整成两位填充大写", () => {
expect(toHexAddr(0x50)).toBe("0x50");
expect(toHexAddr(0x5)).toBe("0x05");
});
it("isValidI2cAddr 7-bit 范围 0x03–0x77", () => {
expect(isValidI2cAddr(0x03)).toBe(true);
expect(isValidI2cAddr(0x77)).toBe(true);
expect(isValidI2cAddr(0x00)).toBe(false);
expect(isValidI2cAddr(0x7f)).toBe(false);
});
});
describe("peripheral-probe parseI2cDetect — i2cdetect 输出解析", () => {
const table = parseI2cDetect(
buildI2cDetect({
"0x20": "present",
"0x21": "present",
"0x22": "present",
"0x23": "present",
"0x24": "present",
"0x25": "present",
"0x26": "present",
"0x27": "present",
"0x68": "present",
"0x77": "present",
"0x50": "inuse",
"0x78": "inuse",
}),
);
it("解析 0x20–0x27 为 present", () => {
const present = table.filter((r) => r.status === "present");
for (let a = 0x20; a <= 0x27; a++) {
expect(present.some((r) => r.addr === a)).toBe(true);
}
});
it("0x20 的 hex 标记正确", () => {
const r = table.find((x) => x.addr === 0x20);
expect(r?.hex).toBe("0x20");
});
it("UU 标记为 in-use", () => {
const r = table.find((x) => x.addr === 0x50);
expect(r?.status).toBe("in-use");
const r78 = table.find((x) => x.addr === 0x78);
expect(r78?.status).toBe("in-use");
});
it("-- 标记为 empty", () => {
const r = table.find((x) => x.addr === 0x10);
expect(r?.status).toBe("empty");
});
it("保留地址 0x00–0x02 不出现(i2cdetect 不探测)", () => {
expect(table.find((x) => x.addr === 0x00)).toBeUndefined();
expect(table.find((x) => x.addr === 0x02)).toBeUndefined();
});
it("presentAddresses 返回数值数组(排除 empty/in-use)", () => {
const addrs = presentAddresses(table);
expect(addrs).toContain(0x20);
expect(addrs).toContain(0x68);
expect(addrs).toContain(0x77);
expect(addrs).not.toContain(0x10); // empty
expect(addrs).not.toContain(0x50); // in-use
});
it("空输出返回空数组", () => {
expect(parseI2cDetect("")).toEqual([]);
expect(parseI2cDetect("no match here")).toEqual([]);
});
});
describe("peripheral-probe parseGpioInfo — gpioinfo 输出解析", () => {
const output = `gpiochip0 - 512 lines:
\tline 0: "PIN3" unused output active-high
\tline 1: "PIN5" unused input active-high
gpiochip1 - 256 lines:
\tline 0: unnamed unused input active-high`;
const chips = parseGpioInfo(output);
it("解析出两个 chip", () => {
expect(chips).toHaveLength(2);
expect(chips[0]?.chip).toBe("gpiochip0");
expect(chips[0]?.lines).toBe(512);
expect(chips[1]?.chip).toBe("gpiochip1");
expect(chips[1]?.lines).toBe(256);
});
it("chip0 line0 = PIN3 / output", () => {
const l = chips[0]?.lineDetails[0];
expect(l?.offset).toBe(0);
expect(l?.name).toBe("PIN3");
expect(l?.direction).toBe("output");
});
it("chip0 line1 = PIN5 / input", () => {
const l = chips[0]?.lineDetails[1];
expect(l?.offset).toBe(1);
expect(l?.direction).toBe("input");
});
});
describe("peripheral-probe probeGpio — mock 返回 chip", () => {
it("probeGpio mock 返回 gpiochip0(核心路径)", async () => {
const exec = mkExec({
gpioinfo: () => ({
stdout: `gpiochip0 - 512 lines:
\tline 0: "PIN3" unused output active-high`,
stderr: "",
exitCode: 0,
}),
});
const chips = await probeGpio(exec);
expect(chips[0]?.chip).toBe("gpiochip0");
expect(chips[0]?.lines).toBe(512);
expect(chips[0]?.lineDetails[0]?.name).toBe("PIN3");
});
it("gpioinfo 失败抛错(fail-closed)", async () => {
const exec = mkExec({
gpioinfo: () => ({ stdout: "", stderr: "gpioinfo: not found", exitCode: 127 }),
});
await expect(probeGpio(exec)).rejects.toThrow(/gpioinfo failed/);
});
});
describe("peripheral-probe probeI2c — mock 总线探测", () => {
it("probeI2c mock 返回 bus 0 + 0x20–0x27 设备", async () => {
const detect = buildI2cDetect({
"0x20": "present",
"0x21": "present",
"0x22": "present",
"0x23": "present",
"0x24": "present",
"0x25": "present",
"0x26": "present",
"0x27": "present",
"0x50": "inuse",
});
const exec = mkExec({
i2cdetect: () => ({ stdout: detect, stderr: "", exitCode: 0 }),
});
const buses = await probeI2c(exec, [0]);
expect(buses).toHaveLength(1);
expect(buses[0]?.bus).toBe(0);
expect(buses[0]?.devices).toEqual([0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27]);
expect(buses[0]?.inUse).toEqual([0x50]);
});
it("i2cdetect 非零退出 → 记录 error 不抛(fail-closed 暴露)", async () => {
const exec = mkExec({
i2cdetect: () => ({ stdout: "", stderr: "could not open file", exitCode: 1 }),
});
const buses = await probeI2c(exec, [2]);
expect(buses[0]?.bus).toBe(2);
expect(buses[0]?.devices).toEqual([]);
expect(buses[0]?.error).toContain("could not open file");
});
it("无 buses 参数 → discoverI2cBuses 枚举 /dev/i2c-*", async () => {
const exec = mkExec({
sh: (args) => {
if (args[1]?.includes("/dev/i2c-")) {
return { stdout: "/dev/i2c-0\n/dev/i2c-1\n", stderr: "", exitCode: 0 };
}
return { stdout: "", stderr: "", exitCode: 0 };
},
i2cdetect: () => ({ stdout: buildI2cDetect({ "0x20": "present" }), stderr: "", exitCode: 0 }),
});
const buses = await probeI2c(exec);
expect(buses.map((b) => b.bus)).toEqual([0, 1]);
});
it("discoverI2cBuses 解析总线号并升序", async () => {
const exec = mkExec({
sh: () => ({ stdout: "/dev/i2c-3\n/dev/i2c-1\n/dev/i2c-0\n", stderr: "", exitCode: 0 }),
});
const buses = await discoverI2cBuses(exec);
expect(buses).toEqual([0, 1, 3]);
});
});
describe("peripheral-probe probeSpi — /dev/spidev* 枚举", () => {
it("返回 spidev 设备并解析 bus/cs", async () => {
const exec = mkExec({
sh: () => ({ stdout: "/dev/spidev0.0\n/dev/dev/spidev1.1\n/dev/spidev2.0\n", stderr: "", exitCode: 0 }),
});
const devs = await probeSpi(exec);
expect(devs).toHaveLength(2);
expect(devs[0]?.dev).toBe("/dev/spidev0.0");
expect(devs[0]?.bus).toBe(0);
expect(devs[0]?.chipSelect).toBe(0);
expect(devs[1]?.dev).toBe("/dev/spidev2.0");
expect(devs[1]?.bus).toBe(2);
});
it("无 SPI 设备返回空", async () => {
const exec = mkExec({
sh: () => ({ stdout: "", stderr: "", exitCode: 0 }),
});
expect(await probeSpi(exec)).toEqual([]);
});
});
describe("peripheral-probe probeUdev — sysfs class 枚举", () => {
it('probeUdev("net") 返回网卡', async () => {
const exec = mkExec({
sh: (args) => ({
stdout: args[1]?.includes("/sys/class/net/") ? "eth0\nwlan0\n" : "",
stderr: "",
exitCode: 0,
}),
});
const devs = await probeUdev(exec, "net");
expect(devs.map((d) => d.name).sort()).toEqual(["eth0", "wlan0"]);
expect(devs[0]?.subsystem).toBe("net");
});
it("subsystem 清洗防 shell 注入", async () => {
const calls: string[] = [];
const exec: ExecFn = async (_cmd, args) => {
calls.push(args.join(" "));
return { stdout: "", stderr: "", exitCode: 0 };
};
await probeUdev(exec, "net; rm -rf /");
// 危险字符被剥离,只剩字母数字下划线连字符
expect(calls[0]).not.toContain("rm -rf");
expect(calls[0]).not.toContain(";");
});
it("空 subsystem 返回空数组", async () => {
const exec = mkExec({});
expect(await probeUdev(exec, "")).toEqual([]);
});
});
describe("peripheral-probe probeMemSnap — /proc 快照", () => {
it("返回 iomem + interrupts 内容", async () => {
const exec = mkExec({
cat: (args) => {
if (args[0] === "/proc/iomem") {
return { stdout: "40000000-40000fff : uart\n", stderr: "", exitCode: 0 };
}
if (args[0] === "/proc/interrupts") {
return { stdout: " 0: 1234 ARM GIC\n", stderr: "", exitCode: 0 };
}
return { stdout: "", stderr: "", exitCode: 1 };
},
});
const snap = await probeMemSnap(exec);
expect(snap.iomem).toContain("uart");
expect(snap.interrupts).toContain("GIC");
});
it("/proc 不可读时返回空串(不抛)", async () => {
const exec = mkExec({
cat: () => ({ stdout: "", stderr: "denied", exitCode: 1 }),
});
const snap = await probeMemSnap(exec);
expect(snap.iomem).toBe("");
expect(snap.interrupts).toBe("");
});
});