chore: establish TypeScript diagnosis baseline
This commit is contained in:
parent
c14c0e57b3
commit
5afa87f30a
2
.gitignore
vendored
2
.gitignore
vendored
@ -1,4 +1,6 @@
|
||||
.DS_Store
|
||||
.idea/
|
||||
.worktrees/
|
||||
node_modules/
|
||||
dist/
|
||||
*.tsbuildinfo
|
||||
|
||||
832
extensions/rdk-diagnose.ts
Normal file
832
extensions/rdk-diagnose.ts
Normal file
@ -0,0 +1,832 @@
|
||||
/**
|
||||
* RDK Diagnose — Pi Extension 入口
|
||||
*/
|
||||
|
||||
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
||||
import { defineTool } from "@earendil-works/pi-coding-agent";
|
||||
import { Type, StringEnum } from "@earendil-works/pi-ai";
|
||||
import { checkConnection, execSsh, type SshConfig } from "../src/transports/ssh.js";
|
||||
import { collectDeviceContext } from "../src/context/collector.js";
|
||||
import { createTarget, getTarget, updateTargetStatus, setTargetProfile } from "../src/targets/registry.js";
|
||||
import {
|
||||
createDiagnosis,
|
||||
getDiagnosis,
|
||||
advancePhase,
|
||||
advanceRound,
|
||||
setDiagnosisStatus,
|
||||
recordAction,
|
||||
addObservation,
|
||||
addEvidence,
|
||||
addHypothesis,
|
||||
saveArtifact,
|
||||
generateReport,
|
||||
} from "../src/core/diagnosis.js";
|
||||
import {
|
||||
parseCameraInitLog,
|
||||
parseI2cDetect,
|
||||
parseCameraDeviceTree,
|
||||
parseSensorMapping,
|
||||
} from "../src/parsers/camera.js";
|
||||
import { readFileSync } from "fs";
|
||||
import { join } from "path";
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────
|
||||
|
||||
function okResult(text: string, details: Record<string, unknown> = {}) {
|
||||
return { content: [{ type: "text" as const, text }], details };
|
||||
}
|
||||
|
||||
function errResult(text: string, details: Record<string, unknown> = {}) {
|
||||
return { content: [{ type: "text" as const, text: `❌ ${text}` }], details };
|
||||
}
|
||||
|
||||
function resolveTargetAndDiagnosis(diagnosisId: string) {
|
||||
const diag = getDiagnosis(diagnosisId);
|
||||
if (!diag) return { diag: null, target: null };
|
||||
const target = getTarget(diag.target_id);
|
||||
if (!target) return { diag, target: null };
|
||||
return { diag, target };
|
||||
}
|
||||
|
||||
// ─── Entry ────────────────────────────────────────────────
|
||||
|
||||
export default function (pi: ExtensionAPI): void {
|
||||
registerCoreTools(pi);
|
||||
registerPreparationTools(pi);
|
||||
registerSystemTools(pi);
|
||||
registerKnowledgeTools(pi);
|
||||
registerCameraTools(pi);
|
||||
}
|
||||
|
||||
// ─── Core Tools ───────────────────────────────────────────
|
||||
|
||||
function registerCoreTools(pi: ExtensionAPI): void {
|
||||
pi.registerTool(
|
||||
defineTool({
|
||||
name: "rdk_diag_create",
|
||||
label: "创建诊断会话",
|
||||
description: "创建诊断 Target 和 Diagnosis 会话。首次使用时传入 transport + expected。",
|
||||
promptSnippet: "Create a new diagnosis session.",
|
||||
parameters: Type.Object({
|
||||
target_id: Type.Optional(Type.String({ description: "已有 Target ID" })),
|
||||
transport: Type.Optional(
|
||||
Type.Object({
|
||||
host: Type.String({ description: "SSH 主机地址" }),
|
||||
user: Type.String({ description: "SSH 用户名", default: "root" }),
|
||||
port: Type.Optional(Type.Number({ description: "SSH 端口", default: 22 })),
|
||||
})
|
||||
),
|
||||
expected: Type.Optional(
|
||||
Type.Object({
|
||||
product: Type.String({ description: "预期产品型号" }),
|
||||
attached_devices: Type.Optional(
|
||||
Type.Array(
|
||||
Type.Object({
|
||||
type: Type.String({ description: "设备类型" }),
|
||||
model: Type.String({ description: "设备型号" }),
|
||||
})
|
||||
)
|
||||
),
|
||||
})
|
||||
),
|
||||
symptom: Type.String({ description: "用户描述的症状", minLength: 1 }),
|
||||
invocation: StringEnum(["preflight", "failure_diagnosis", "post_change_verification"], {
|
||||
description: "调用场景",
|
||||
default: "failure_diagnosis",
|
||||
}),
|
||||
}),
|
||||
async execute(_toolCallId, params) {
|
||||
const transport: SshConfig = {
|
||||
type: "ssh",
|
||||
host: params.transport?.host ?? "",
|
||||
user: params.transport?.user ?? "root",
|
||||
port: params.transport?.port ?? 22,
|
||||
};
|
||||
const expected = {
|
||||
product: params.expected?.product ?? "rdk-s100",
|
||||
transport,
|
||||
permissions: { read_only: true } as const,
|
||||
attached_devices: params.expected?.attached_devices ?? [],
|
||||
};
|
||||
|
||||
const target = createTarget(transport, expected);
|
||||
const diagnosis = createDiagnosis({
|
||||
target_id: target.id,
|
||||
symptom: params.symptom,
|
||||
invocation: params.invocation as "preflight" | "failure_diagnosis" | "post_change_verification",
|
||||
});
|
||||
|
||||
return okResult(
|
||||
[
|
||||
`诊断会话已创建。`,
|
||||
`Target ID: ${target.id}`,
|
||||
`Diagnosis ID: ${diagnosis.id}`,
|
||||
`Phase: ${diagnosis.phase} / Round: ${diagnosis.round}`,
|
||||
`下一步:使用 rdk_diag_connection_check 检查 SSH 连接。`,
|
||||
].join("\n"),
|
||||
{ target_id: target.id, diagnosis_id: diagnosis.id }
|
||||
);
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
pi.registerTool(
|
||||
defineTool({
|
||||
name: "rdk_diag_get",
|
||||
label: "获取诊断状态",
|
||||
description: "根据 Diagnosis ID 获取完整的诊断状态。",
|
||||
promptSnippet: "Get the full state of a diagnosis session.",
|
||||
parameters: Type.Object({
|
||||
diagnosis_id: Type.String({ description: "Diagnosis ID", minLength: 1 }),
|
||||
}),
|
||||
async execute(_toolCallId, params) {
|
||||
const { diag } = resolveTargetAndDiagnosis(params.diagnosis_id);
|
||||
if (!diag) return errResult(`诊断会话 ${params.diagnosis_id} 未找到。`);
|
||||
return okResult(
|
||||
[
|
||||
`Diagnosis: ${diag.id}`,
|
||||
`Target: ${diag.target_id}`,
|
||||
`Phase: ${diag.phase} / Round: ${diag.round}`,
|
||||
`Status: ${diag.status}`,
|
||||
`Symptom: ${diag.symptom}`,
|
||||
`Actions: ${diag.actions.length} | Observations: ${diag.observation_ids.length} | Evidence: ${diag.evidence_ids.length} | Hypotheses: ${diag.hypothesis_ids.length}`,
|
||||
].join("\n"),
|
||||
{ diagnosis_id: diag.id, target_id: diag.target_id, phase: diag.phase, round: diag.round, status: diag.status }
|
||||
);
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
pi.registerTool(
|
||||
defineTool({
|
||||
name: "rdk_diag_finish_round",
|
||||
label: "结束当前诊断轮次",
|
||||
description: "结束当前诊断轮次,生成报告并推进到下一轮。",
|
||||
promptSnippet: "Finish the current diagnosis round.",
|
||||
parameters: Type.Object({
|
||||
diagnosis_id: Type.String({ description: "Diagnosis ID", minLength: 1 }),
|
||||
}),
|
||||
async execute(_toolCallId, params) {
|
||||
const { diag } = resolveTargetAndDiagnosis(params.diagnosis_id);
|
||||
if (!diag) return errResult(`诊断会话 ${params.diagnosis_id} 未找到。`);
|
||||
advanceRound(params.diagnosis_id);
|
||||
const report = generateReport(params.diagnosis_id);
|
||||
return okResult(
|
||||
[
|
||||
`轮次结束。当前 Round: ${diag.round + 1}`,
|
||||
`已排除假设: ${report?.ruled_out.join(", ") ?? "无"}`,
|
||||
`最高置信度层级: ${report?.highest_confidence_layer ?? "N/A"}`,
|
||||
].join("\n"),
|
||||
{ round: diag.round + 1 }
|
||||
);
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
pi.registerTool(
|
||||
defineTool({
|
||||
name: "rdk_diag_close",
|
||||
label: "关闭诊断会话",
|
||||
description: "关闭诊断会话并生成最终 Diagnosis Report。",
|
||||
promptSnippet: "Close a diagnosis session.",
|
||||
parameters: Type.Object({
|
||||
diagnosis_id: Type.String({ description: "Diagnosis ID", minLength: 1 }),
|
||||
}),
|
||||
async execute(_toolCallId, params) {
|
||||
setDiagnosisStatus(params.diagnosis_id, "completed");
|
||||
const report = generateReport(params.diagnosis_id);
|
||||
const text = report
|
||||
? [
|
||||
`诊断已关闭。`,
|
||||
`最高置信度层级: ${report.highest_confidence_layer ?? "N/A"}`,
|
||||
`已排除: ${report.ruled_out.join(", ") ?? "无"}`,
|
||||
`下一步: ${report.next_steps.join("; ") ?? "无"}`,
|
||||
].join("\n")
|
||||
: `诊断已关闭。`;
|
||||
return okResult(text);
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Preparation Tools ────────────────────────────────────
|
||||
|
||||
function registerPreparationTools(pi: ExtensionAPI): void {
|
||||
pi.registerTool(
|
||||
defineTool({
|
||||
name: "rdk_diag_connection_check",
|
||||
label: "检查 SSH 连接",
|
||||
description: "检查到目标设备的 SSH 连接是否可用。",
|
||||
promptSnippet: "Check SSH connectivity.",
|
||||
parameters: Type.Object({
|
||||
diagnosis_id: Type.String({ description: "Diagnosis ID", minLength: 1 }),
|
||||
}),
|
||||
async execute(_toolCallId, params) {
|
||||
const { diag, target } = resolveTargetAndDiagnosis(params.diagnosis_id);
|
||||
if (!diag || !target) return errResult(`诊断会话或 Target 未找到。`);
|
||||
|
||||
const { reachable, errorType, result } = await checkConnection(target.transport as SshConfig);
|
||||
|
||||
const action = recordAction(
|
||||
params.diagnosis_id, diag.round, "ssh_command", "rdk_diag_connection_check",
|
||||
`SSH 连接检查: ${target.transport.user}@${target.transport.host}`,
|
||||
{ host: target.transport.host, user: target.transport.user },
|
||||
reachable ? "success" : "failure",
|
||||
result.exitCode ?? undefined,
|
||||
result.durationMs
|
||||
);
|
||||
|
||||
const obs = addObservation(
|
||||
action.id, "deterministic", "ssh.connection",
|
||||
reachable, result.stderr.slice(0, 500),
|
||||
{ error_type: errorType, duration_ms: result.durationMs }
|
||||
);
|
||||
|
||||
addEvidence(
|
||||
[obs.id],
|
||||
reachable ? `SSH 连接 ${target.transport.user}@${target.transport.host} 正常` : `SSH 连接失败: ${errorType}`,
|
||||
`单次 ${target.transport.host} 连接测试`,
|
||||
reachable ? "SSH 服务可用、认证通过、网络可达" : `SSH 连接失败,错误类型: ${errorType}`,
|
||||
reachable ? "不证明内核、驱动、外设状态正常" : "不排除网络瞬断或临时故障",
|
||||
[]
|
||||
);
|
||||
|
||||
return okResult(
|
||||
reachable
|
||||
? `✅ SSH 连接正常 (${target.transport.user}@${target.transport.host}, ${result.durationMs}ms)`
|
||||
: `❌ SSH 连接失败: ${errorType}\n\n${result.stderr.slice(0, 500)}`,
|
||||
{ reachable, errorType, duration_ms: result.durationMs }
|
||||
);
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
pi.registerTool(
|
||||
defineTool({
|
||||
name: "rdk_diag_identify_target",
|
||||
label: "识别目标设备",
|
||||
description: "采集目标设备的身份信息(产品型号、SoC、内核版本等)。",
|
||||
promptSnippet: "Identify the target device.",
|
||||
parameters: Type.Object({
|
||||
diagnosis_id: Type.String({ description: "Diagnosis ID", minLength: 1 }),
|
||||
}),
|
||||
async execute(_toolCallId, params) {
|
||||
const { diag, target } = resolveTargetAndDiagnosis(params.diagnosis_id);
|
||||
if (!diag || !target) return errResult(`诊断会话或 Target 未找到。`);
|
||||
|
||||
const ctx = await collectDeviceContext(target.transport as SshConfig);
|
||||
|
||||
const action = recordAction(
|
||||
params.diagnosis_id, diag.round, "system_inspection", "rdk_diag_identify_target",
|
||||
"采集设备身份信息", {}, "success"
|
||||
);
|
||||
|
||||
const obs = addObservation(
|
||||
action.id, "deterministic", "device.identity",
|
||||
ctx.product ?? "unknown", ctx.raw_uname ?? undefined,
|
||||
{ product: ctx.product, soc: ctx.soc, board: ctx.board, kernel: ctx.kernel_version }
|
||||
);
|
||||
|
||||
if (ctx.product && ctx.product === target.expected.product) {
|
||||
updateTargetStatus(target.id, "verified", ctx.product);
|
||||
setTargetProfile(target.id, target.expected.product);
|
||||
advancePhase(params.diagnosis_id, "diagnosis");
|
||||
} else if (ctx.product && ctx.product !== target.expected.product) {
|
||||
updateTargetStatus(target.id, "conflict", ctx.product);
|
||||
}
|
||||
|
||||
addEvidence(
|
||||
[obs.id],
|
||||
ctx.product ? `设备识别为 ${ctx.product}` : "设备身份未能识别",
|
||||
`设备树 + /etc/os-release 采集`,
|
||||
ctx.product ? `确认板型为 ${ctx.product}` : "未能通过设备树或 os-release 确认板型",
|
||||
"不证明外设或驱动状态",
|
||||
[]
|
||||
);
|
||||
|
||||
const matched = ctx.product === target.expected.product;
|
||||
return okResult(
|
||||
[
|
||||
`设备身份采集完成。`,
|
||||
`产品: ${ctx.product ?? "未识别"}`,
|
||||
`SoC: ${ctx.soc ?? "未知"}`,
|
||||
`板型: ${ctx.board ?? "未知"}`,
|
||||
`内核: ${ctx.kernel_version ?? "未知"}`,
|
||||
`主机名: ${ctx.hostname ?? "未知"}`,
|
||||
"",
|
||||
matched
|
||||
? `✅ 与预期一致 (${target.expected.product}),已进入诊断阶段。`
|
||||
: ctx.product
|
||||
? `⚠️ 与预期不一致!预期: ${target.expected.product}, 实际: ${ctx.product}`
|
||||
: `⚠️ 未能识别产品型号,需要人工确认。`,
|
||||
].join("\n"),
|
||||
{ product: ctx.product, matched }
|
||||
);
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
// ─── System Tools ─────────────────────────────────────────
|
||||
|
||||
function registerSystemTools(pi: ExtensionAPI): void {
|
||||
pi.registerTool(
|
||||
defineTool({
|
||||
name: "rdk_diag_inspect_system",
|
||||
label: "采集系统信息",
|
||||
description: "采集系统信息(内核、发行版、CPU、内存)。",
|
||||
promptSnippet: "Inspect system information.",
|
||||
parameters: Type.Object({
|
||||
diagnosis_id: Type.String({ description: "Diagnosis ID", minLength: 1 }),
|
||||
}),
|
||||
async execute(_toolCallId, params) {
|
||||
const { diag, target } = resolveTargetAndDiagnosis(params.diagnosis_id);
|
||||
if (!diag || !target) return errResult(`诊断会话或 Target 未找到。`);
|
||||
|
||||
const [cpuResult, memResult, diskResult] = await Promise.all([
|
||||
execSsh(target.transport as SshConfig, "cat /proc/cpuinfo | grep -E 'processor|model name|Hardware' | head -10", 5_000),
|
||||
execSsh(target.transport as SshConfig, "free -h", 5_000),
|
||||
execSsh(target.transport as SshConfig, "df -h /", 5_000),
|
||||
]);
|
||||
|
||||
const action = recordAction(
|
||||
params.diagnosis_id, diag.round, "system_inspection", "rdk_diag_inspect_system",
|
||||
"采集系统信息", {}, "success"
|
||||
);
|
||||
saveArtifact(action.id, [cpuResult.stdout, memResult.stdout, diskResult.stdout].join("\n---\n"));
|
||||
|
||||
return okResult(
|
||||
["=== CPU ===", cpuResult.stdout.slice(0, 1000), "=== 内存 ===", memResult.stdout.slice(0, 500), "=== 磁盘 ===", diskResult.stdout.slice(0, 500)].join("\n")
|
||||
);
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
pi.registerTool(
|
||||
defineTool({
|
||||
name: "rdk_diag_read_log",
|
||||
label: "读取日志文件",
|
||||
description: "按时间和关键词读取指定日志文件。",
|
||||
promptSnippet: "Read a log file from the target device.",
|
||||
parameters: Type.Object({
|
||||
diagnosis_id: Type.String({ description: "Diagnosis ID", minLength: 1 }),
|
||||
source: StringEnum(["dmesg", "syslog", "custom"], { description: "日志来源", default: "dmesg" }),
|
||||
path: Type.Optional(Type.String({ description: "自定义日志路径" })),
|
||||
keyword: Type.Optional(Type.String({ description: "过滤关键词" })),
|
||||
lines: Type.Optional(Type.Number({ description: "读取行数", default: 200 })),
|
||||
}),
|
||||
async execute(_toolCallId, params) {
|
||||
const { diag, target } = resolveTargetAndDiagnosis(params.diagnosis_id);
|
||||
if (!diag || !target) return errResult(`诊断会话或 Target 未找到。`);
|
||||
|
||||
const maxLines = Math.min(params.lines ?? 200, 500);
|
||||
let cmd: string;
|
||||
switch (params.source) {
|
||||
case "dmesg": cmd = `dmesg | tail -n ${maxLines}`; break;
|
||||
case "syslog": cmd = `journalctl -n ${maxLines} --no-pager`; break;
|
||||
case "custom": cmd = `tail -n ${maxLines} ${params.path ?? "/var/log/syslog"}`; break;
|
||||
default: cmd = `dmesg | tail -n ${maxLines}`;
|
||||
}
|
||||
if (params.keyword) {
|
||||
const safeKeyword = params.keyword.replace(/'/g, "'\\''");
|
||||
cmd += ` | grep -i '${safeKeyword}'`;
|
||||
}
|
||||
|
||||
const result = await execSsh(target.transport as SshConfig, cmd, 10_000);
|
||||
const action = recordAction(
|
||||
params.diagnosis_id, diag.round, "ssh_command", "rdk_diag_read_log",
|
||||
`读取日志: ${params.source}`, { source: params.source, keyword: params.keyword ?? null },
|
||||
result.exitCode === 0 ? "success" : "failure", result.exitCode ?? undefined, result.durationMs
|
||||
);
|
||||
saveArtifact(action.id, result.stdout);
|
||||
|
||||
return okResult(result.stdout.slice(0, 3000) || "(无输出)", { exit_code: result.exitCode });
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
pi.registerTool(
|
||||
defineTool({
|
||||
name: "rdk_diag_inspect_device_tree",
|
||||
label: "检查设备树",
|
||||
description: "检查设备树中与 Camera 相关的节点和绑定状态。",
|
||||
promptSnippet: "Inspect the device tree.",
|
||||
parameters: Type.Object({
|
||||
diagnosis_id: Type.String({ description: "Diagnosis ID", minLength: 1 }),
|
||||
}),
|
||||
async execute(_toolCallId, params) {
|
||||
const { diag, target } = resolveTargetAndDiagnosis(params.diagnosis_id);
|
||||
if (!diag || !target) return errResult(`诊断会话或 Target 未找到。`);
|
||||
|
||||
const result = await execSsh(
|
||||
target.transport as SshConfig,
|
||||
"find /proc/device-tree /sys/firmware/devicetree -name '*camera*' -o -name '*sensor*' -o -name '*mipi*' -o -name '*csi*' 2>/dev/null | head -30",
|
||||
10_000
|
||||
);
|
||||
|
||||
const dtSummary = parseCameraDeviceTree(result.stdout);
|
||||
const action = recordAction(
|
||||
params.diagnosis_id, diag.round, "ssh_command", "rdk_diag_inspect_device_tree",
|
||||
"检查设备树 Camera 节点", {}, "success", result.exitCode ?? undefined, result.durationMs
|
||||
);
|
||||
saveArtifact(action.id, result.stdout);
|
||||
|
||||
addObservation(
|
||||
action.id, "deterministic", "device_tree.camera_nodes",
|
||||
dtSummary.camera_nodes.length, result.stdout.slice(0, 500),
|
||||
{ camera_nodes: dtSummary.camera_nodes, status_ok: dtSummary.status_ok, status_disabled: dtSummary.status_disabled }
|
||||
);
|
||||
|
||||
return okResult(
|
||||
[
|
||||
`Camera 相关设备树节点: ${dtSummary.camera_nodes.length} 个`,
|
||||
dtSummary.status_disabled.length > 0 ? `⚠️ 禁用节点: ${dtSummary.status_disabled.length} 个` : "",
|
||||
`\n前 30 个节点:\n${dtSummary.camera_nodes.slice(0, 30).join("\n")}`,
|
||||
].join("\n"),
|
||||
{ camera_node_count: dtSummary.camera_nodes.length, disabled_count: dtSummary.status_disabled.length }
|
||||
);
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
pi.registerTool(
|
||||
defineTool({
|
||||
name: "rdk_diag_inspect_device_nodes",
|
||||
label: "检查设备节点",
|
||||
description: "检查 /dev 下与 Camera 相关的设备节点。",
|
||||
promptSnippet: "Inspect /dev device nodes.",
|
||||
parameters: Type.Object({
|
||||
diagnosis_id: Type.String({ description: "Diagnosis ID", minLength: 1 }),
|
||||
}),
|
||||
async execute(_toolCallId, params) {
|
||||
const { diag, target } = resolveTargetAndDiagnosis(params.diagnosis_id);
|
||||
if (!diag || !target) return errResult(`诊断会话或 Target 未找到。`);
|
||||
|
||||
const result = await execSsh(target.transport as SshConfig, "ls -la /dev/video* /dev/media* /dev/v4l* 2>/dev/null || echo 'No video devices found'", 5_000);
|
||||
|
||||
const action = recordAction(
|
||||
params.diagnosis_id, diag.round, "ssh_command", "rdk_diag_inspect_device_nodes",
|
||||
"检查 /dev 设备节点", {}, "success", result.exitCode ?? undefined, result.durationMs
|
||||
);
|
||||
saveArtifact(action.id, result.stdout);
|
||||
|
||||
const hasVideoDevices = result.stdout.includes("video") && !result.stdout.includes("No video devices");
|
||||
addObservation(action.id, "deterministic", "device_nodes.video_devices", hasVideoDevices, result.stdout.slice(0, 500));
|
||||
|
||||
return okResult(result.stdout || "未找到 video 设备节点。", { has_video_devices: hasVideoDevices });
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
pi.registerTool(
|
||||
defineTool({
|
||||
name: "rdk_diag_list_i2c_buses",
|
||||
label: "列出 I2C 总线",
|
||||
description: "列出 I2C 总线和已绑定设备(不主动探测)。",
|
||||
promptSnippet: "List I2C buses.",
|
||||
parameters: Type.Object({
|
||||
diagnosis_id: Type.String({ description: "Diagnosis ID", minLength: 1 }),
|
||||
}),
|
||||
async execute(_toolCallId, params) {
|
||||
const { diag, target } = resolveTargetAndDiagnosis(params.diagnosis_id);
|
||||
if (!diag || !target) return errResult(`诊断会话或 Target 未找到。`);
|
||||
|
||||
const result = await execSsh(target.transport as SshConfig, "i2cdetect -l 2>/dev/null || echo 'i2cdetect not available'", 5_000);
|
||||
|
||||
const action = recordAction(
|
||||
params.diagnosis_id, diag.round, "ssh_command", "rdk_diag_list_i2c_buses",
|
||||
"列出 I2C 总线", {}, "success", result.exitCode ?? undefined, result.durationMs
|
||||
);
|
||||
saveArtifact(action.id, result.stdout);
|
||||
|
||||
const busCount = result.stdout.split("\n").filter((l: string) => l.includes("i2c-")).length;
|
||||
addObservation(action.id, "deterministic", "i2c.bus_count", busCount, result.stdout.slice(0, 500));
|
||||
|
||||
return okResult(result.stdout || "i2cdetect 不可用。", { bus_count: busCount });
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Knowledge Tools ──────────────────────────────────────
|
||||
|
||||
function registerKnowledgeTools(pi: ExtensionAPI): void {
|
||||
const KNOWLEDGE_DIR = join(import.meta.dirname ?? process.cwd(), "..", "knowledge");
|
||||
|
||||
const ROUTE_MAP: Record<string, string[]> = {
|
||||
camera_sensor_detection: [
|
||||
"diagnostic_rules/camera_sensor_detection.md",
|
||||
"diagnostic_cases/s100_gs130w_sensor_bringup.md",
|
||||
],
|
||||
camera_init_failure: [
|
||||
"device_bringup_patterns/layered_hardware_debugging.md",
|
||||
"diagnostic_rules/camera_sensor_detection.md",
|
||||
"diagnostic_cases/s100_gs130w_sensor_bringup.md",
|
||||
],
|
||||
i2c_no_ack: [
|
||||
"device_bringup_patterns/layered_hardware_debugging.md",
|
||||
"diagnostic_rules/camera_sensor_detection.md",
|
||||
],
|
||||
device_not_found: [
|
||||
"device_bringup_patterns/layered_hardware_debugging.md",
|
||||
],
|
||||
peripheral_bringup: [
|
||||
"device_bringup_patterns/layered_hardware_debugging.md",
|
||||
],
|
||||
};
|
||||
|
||||
pi.registerTool(
|
||||
defineTool({
|
||||
name: "rdk_diag_get_knowledge",
|
||||
label: "Load diagnostic knowledge",
|
||||
description:
|
||||
"Load knowledge files for the current symptom. Must be called before any peripheral Inspector.",
|
||||
promptSnippet: "Load diagnostic knowledge for the current symptom.",
|
||||
parameters: Type.Object({
|
||||
diagnosis_id: Type.String({ description: "Current Diagnosis ID" }),
|
||||
symptom_tags: Type.Array(Type.String({ description: "Symptom tag" }), {
|
||||
description: "Symptom tags, e.g. camera_init_failure, camera_sensor_detection",
|
||||
}),
|
||||
}),
|
||||
async execute(_toolCallId, params) {
|
||||
const diag = getDiagnosis(params.diagnosis_id);
|
||||
if (!diag) {
|
||||
return errResult("Diagnosis not found.");
|
||||
}
|
||||
|
||||
const tags = params.symptom_tags;
|
||||
const filesToLoad = new Set<string>();
|
||||
const reasons: string[] = [];
|
||||
|
||||
for (const tag of tags) {
|
||||
const routes = ROUTE_MAP[tag];
|
||||
if (routes) {
|
||||
for (const r of routes) {
|
||||
filesToLoad.add(r);
|
||||
}
|
||||
reasons.push(tag + " -> " + routes.join(", "));
|
||||
} else {
|
||||
reasons.push(tag + " -> no match, fallback to general pattern");
|
||||
filesToLoad.add("device_bringup_patterns/layered_hardware_debugging.md");
|
||||
}
|
||||
}
|
||||
|
||||
if (filesToLoad.size === 0) {
|
||||
filesToLoad.add("device_bringup_patterns/layered_hardware_debugging.md");
|
||||
reasons.push("default -> general layered pattern");
|
||||
}
|
||||
|
||||
const sections: string[] = [];
|
||||
const loaded: string[] = [];
|
||||
const failed: string[] = [];
|
||||
|
||||
for (const relPath of filesToLoad) {
|
||||
const fullPath = join(KNOWLEDGE_DIR, relPath);
|
||||
try {
|
||||
const raw = readFileSync(fullPath, "utf-8");
|
||||
sections.push("## " + relPath + "\n\n" + raw);
|
||||
loaded.push(relPath);
|
||||
} catch {
|
||||
failed.push(relPath);
|
||||
}
|
||||
}
|
||||
|
||||
const lines: string[] = [];
|
||||
lines.push("Knowledge route result (Diagnosis: " + params.diagnosis_id + ")");
|
||||
lines.push("Symptom tags: " + tags.join(", "));
|
||||
lines.push("Route reasons:");
|
||||
reasons.forEach(function(r) { lines.push(" - " + r); });
|
||||
if (loaded.length > 0) lines.push("Loaded: " + loaded.join(", "));
|
||||
if (failed.length > 0) lines.push("Not found: " + failed.join(", "));
|
||||
lines.push("");
|
||||
lines.push("These knowledge files guide diagnostic reasoning, not evidence.");
|
||||
lines.push("Current device Inspector results always take priority over knowledge files.");
|
||||
lines.push("");
|
||||
lines.push("---");
|
||||
lines.push("");
|
||||
sections.forEach(function(s) { lines.push(s); lines.push(""); lines.push("---"); lines.push(""); });
|
||||
|
||||
return okResult(lines.join("\n"), {
|
||||
loaded: loaded,
|
||||
failed: failed,
|
||||
symptom_tags: tags,
|
||||
routes: reasons,
|
||||
});
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
function registerCameraTools(pi: ExtensionAPI): void {
|
||||
pi.registerTool(
|
||||
defineTool({
|
||||
name: "rdk_diag_camera_inspect_runtime",
|
||||
label: "检查摄像头运行时状态",
|
||||
description: "检查摄像头运行时状态(进程、内存、错误)。",
|
||||
promptSnippet: "Inspect camera runtime state.",
|
||||
parameters: Type.Object({
|
||||
diagnosis_id: Type.String({ description: "Diagnosis ID", minLength: 1 }),
|
||||
}),
|
||||
async execute(_toolCallId, params) {
|
||||
const { diag, target } = resolveTargetAndDiagnosis(params.diagnosis_id);
|
||||
if (!diag || !target) return errResult(`诊断会话或 Target 未找到。`);
|
||||
|
||||
const result = await execSsh(
|
||||
target.transport as SshConfig,
|
||||
"ps aux | grep -E 'camera|sensor|v4l|mipi|csi|ros' | grep -v grep",
|
||||
5_000
|
||||
);
|
||||
|
||||
const action = recordAction(
|
||||
params.diagnosis_id, diag.round, "ssh_command", "rdk_diag_camera_inspect_runtime",
|
||||
"检查摄像头运行时状态", {}, "success", result.exitCode ?? undefined, result.durationMs
|
||||
);
|
||||
saveArtifact(action.id, result.stdout);
|
||||
|
||||
const hasProcess = result.stdout.trim().length > 0;
|
||||
addObservation(action.id, "deterministic", "camera.runtime_processes", hasProcess, result.stdout.slice(0, 500));
|
||||
|
||||
return okResult(result.stdout || "未发现 Camera 相关进程。", { has_runtime_process: hasProcess });
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
pi.registerTool(
|
||||
defineTool({
|
||||
name: "rdk_diag_camera_inspect_mapping",
|
||||
label: "检查摄像头映射",
|
||||
description: "检查摄像头到设备节点的映射关系。",
|
||||
promptSnippet: "Inspect camera-to-device mapping.",
|
||||
parameters: Type.Object({
|
||||
diagnosis_id: Type.String({ description: "Diagnosis ID", minLength: 1 }),
|
||||
}),
|
||||
async execute(_toolCallId, params) {
|
||||
const { diag, target } = resolveTargetAndDiagnosis(params.diagnosis_id);
|
||||
if (!diag || !target) return errResult(`诊断会话或 Target 未找到。`);
|
||||
|
||||
const result = await execSsh(
|
||||
target.transport as SshConfig,
|
||||
"for dev in /dev/video*; do [ -e \"$dev\" ] && echo \"$dev $(cat /sys/class/video4linux/$(basename $dev)/name 2>/dev/null)\"; done",
|
||||
5_000
|
||||
);
|
||||
|
||||
const action = recordAction(
|
||||
params.diagnosis_id, diag.round, "ssh_command", "rdk_diag_camera_inspect_mapping",
|
||||
"检查摄像头映射", {}, "success", result.exitCode ?? undefined, result.durationMs
|
||||
);
|
||||
saveArtifact(action.id, result.stdout);
|
||||
|
||||
const mappings = parseSensorMapping(result.stdout);
|
||||
const sensorCount = mappings.length;
|
||||
|
||||
addObservation(
|
||||
action.id, "deterministic", "camera.sensor_mapping_count",
|
||||
sensorCount, result.stdout.slice(0, 500),
|
||||
{ mappings: JSON.stringify(mappings) }
|
||||
);
|
||||
|
||||
return okResult(
|
||||
[`检测到 ${sensorCount} 个 Video 设备:`, ...mappings.map((m) => ` ${m.device_path} → ${m.sensor_name ?? "未知"}`)].join("\n"),
|
||||
{ sensor_count: sensorCount }
|
||||
);
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
pi.registerTool(
|
||||
defineTool({
|
||||
name: "rdk_diag_camera_read_initialization_log",
|
||||
label: "读取摄像头初始化日志",
|
||||
description: "读取摄像头初始化日志,解析 Sensor 检测情况。",
|
||||
promptSnippet: "Read camera initialization log.",
|
||||
parameters: Type.Object({
|
||||
diagnosis_id: Type.String({ description: "Diagnosis ID", minLength: 1 }),
|
||||
}),
|
||||
async execute(_toolCallId, params) {
|
||||
const { diag, target } = resolveTargetAndDiagnosis(params.diagnosis_id);
|
||||
if (!diag || !target) return errResult(`诊断会话或 Target 未找到。`);
|
||||
|
||||
const result = await execSsh(
|
||||
target.transport as SshConfig,
|
||||
"dmesg | grep -iE 'camera|sensor|mipi|csi|v4l|i2c.*0x' | tail -50",
|
||||
10_000
|
||||
);
|
||||
|
||||
const action = recordAction(
|
||||
params.diagnosis_id, diag.round, "ssh_command", "rdk_diag_camera_read_initialization_log",
|
||||
"读取摄像头初始化日志", {}, "success", result.exitCode ?? undefined, result.durationMs
|
||||
);
|
||||
saveArtifact(action.id, result.stdout);
|
||||
|
||||
const logSummary = parseCameraInitLog(result.stdout);
|
||||
|
||||
const obs = addObservation(
|
||||
action.id, "deterministic", "camera.init_log",
|
||||
logSummary.sensor_count ?? "unknown", result.stdout.slice(0, 1000),
|
||||
{
|
||||
sensor_count: logSummary.sensor_count,
|
||||
expected_sensor_count: logSummary.expected_sensor_count,
|
||||
sensor_ids: logSummary.sensor_ids.join(","),
|
||||
detection_phase: logSummary.detection_phase,
|
||||
error_count: logSummary.errors.length,
|
||||
warning_count: logSummary.warnings.length,
|
||||
}
|
||||
);
|
||||
|
||||
if (logSummary.sensor_count !== null && logSummary.expected_sensor_count !== null) {
|
||||
const mismatch = logSummary.sensor_count < logSummary.expected_sensor_count;
|
||||
addEvidence(
|
||||
[obs.id],
|
||||
mismatch
|
||||
? `检测到 ${logSummary.sensor_count}/${logSummary.expected_sensor_count} 个 Sensor,实际少 ${logSummary.expected_sensor_count - logSummary.sensor_count} 个`
|
||||
: `检测到 ${logSummary.sensor_count}/${logSummary.expected_sensor_count} 个 Sensor,数量匹配`,
|
||||
"本次启动日志",
|
||||
mismatch ? "Sensor 检测数量与预期不符" : "Sensor 数量符合预期",
|
||||
mismatch ? "不证明 Sensor 本体损坏或硬件链路故障;需进一步排查 I2C 和映射" : "不证明数据链路正常",
|
||||
logSummary.errors.length > 0 ? [`有 ${logSummary.errors.length} 条错误日志`] : []
|
||||
);
|
||||
}
|
||||
|
||||
return okResult(
|
||||
[
|
||||
`=== Camera 初始化日志解析 ===`,
|
||||
`检测阶段: ${logSummary.detection_phase}`,
|
||||
`检测到 Sensor 数量: ${logSummary.sensor_count ?? "N/A"}`,
|
||||
`预期 Sensor 数量: ${logSummary.expected_sensor_count ?? "N/A"}`,
|
||||
`Sensor ID: ${logSummary.sensor_ids.join(", ") || "无"}`,
|
||||
`错误: ${logSummary.errors.length} 条`,
|
||||
`警告: ${logSummary.warnings.length} 条`,
|
||||
logSummary.errors.length > 0 ? `\n前 5 条错误:\n${logSummary.errors.slice(0, 5).join("\n")}` : "",
|
||||
].join("\n"),
|
||||
{
|
||||
sensor_count: logSummary.sensor_count,
|
||||
expected_sensor_count: logSummary.expected_sensor_count,
|
||||
detection_phase: logSummary.detection_phase,
|
||||
error_count: logSummary.errors.length,
|
||||
}
|
||||
);
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
pi.registerTool(
|
||||
defineTool({
|
||||
name: "rdk_diag_camera_probe_i2c_target",
|
||||
label: "受控 I2C 目标探测",
|
||||
description: "对 Camera Profile 批准的 I2C 总线执行受控地址探测。需要用户确认。",
|
||||
promptSnippet: "Controlled I2C target probe.",
|
||||
parameters: Type.Object({
|
||||
diagnosis_id: Type.String({ description: "Diagnosis ID", minLength: 1 }),
|
||||
bus: Type.String({ description: "I2C 总线编号", minLength: 1 }),
|
||||
}),
|
||||
async execute(_toolCallId, params) {
|
||||
const { diag, target } = resolveTargetAndDiagnosis(params.diagnosis_id);
|
||||
if (!diag || !target) return errResult(`诊断会话或 Target 未找到。`);
|
||||
|
||||
const result = await execSsh(
|
||||
target.transport as SshConfig,
|
||||
`sudo i2cdetect -r -y ${params.bus}`,
|
||||
15_000
|
||||
);
|
||||
|
||||
const action = recordAction(
|
||||
params.diagnosis_id, diag.round, "ssh_command", "rdk_diag_camera_probe_i2c_target",
|
||||
`I2C 目标探测: bus ${params.bus}`, { bus: params.bus },
|
||||
result.exitCode === 0 ? "success" : "failure", result.exitCode ?? undefined, result.durationMs
|
||||
);
|
||||
saveArtifact(action.id, result.stdout);
|
||||
|
||||
const i2cResult = parseI2cDetect(result.stdout, params.bus);
|
||||
const hasDevices = i2cResult.detected_addresses.length > 0;
|
||||
const addrStr = i2cResult.detected_addresses.map((a) => `0x${a.toString(16)}`).join(", ");
|
||||
|
||||
const obs = addObservation(
|
||||
action.id, "deterministic", "camera.i2c_probe",
|
||||
hasDevices ? addrStr : "none", result.stdout.slice(0, 1000),
|
||||
{ bus: params.bus, detected_addresses: addrStr, has_devices: hasDevices }
|
||||
);
|
||||
|
||||
addEvidence(
|
||||
[obs.id],
|
||||
hasDevices
|
||||
? `I2C bus ${params.bus} 检测到 ${i2cResult.detected_addresses.length} 个设备: ${addrStr}`
|
||||
: `I2C bus ${params.bus} 未见响应设备`,
|
||||
`单次 i2cdetect 扫描 bus ${params.bus}`,
|
||||
hasDevices ? "I2C 总线上有设备响应" : "当前探测未见 I2C 设备响应",
|
||||
hasDevices ? "不证明设备功能正常" : "不证明硬件损坏;可能是总线未上电、复位未释放、地址不在扫描范围",
|
||||
hasDevices ? [] : ["需确认总线电源、复位、时钟"]
|
||||
);
|
||||
|
||||
return okResult(
|
||||
[
|
||||
`=== I2C Bus ${params.bus} 探测结果 ===`,
|
||||
hasDevices ? `检测到 ${i2cResult.detected_addresses.length} 个设备:` : `未检测到 I2C 设备响应。`,
|
||||
...(hasDevices ? i2cResult.detected_addresses.map((a) => ` - 0x${a.toString(16).padStart(2, "0")}`) : []),
|
||||
`\n原始输出:\n${result.stdout.slice(0, 2000)}`,
|
||||
].join("\n"),
|
||||
{ bus: params.bus, detected_addresses: addrStr, has_devices: hasDevices }
|
||||
);
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
4855
package-lock.json
generated
Normal file
4855
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
47
package.json
Normal file
47
package.json
Normal file
@ -0,0 +1,47 @@
|
||||
{
|
||||
"name": "@d-robotics/rdk-diagnose",
|
||||
"version": "0.1.0",
|
||||
"description": "RDK S100 嵌入式诊断 Agent — 基于证据的外设 Bring-up 与故障定位",
|
||||
"keywords": ["pi-package", "rdk", "d-robotics", "embedded", "diagnosis", "bring-up"],
|
||||
"author": "yintao.li",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"files": [
|
||||
"extensions/",
|
||||
"skills/",
|
||||
"knowledge/",
|
||||
"README.md",
|
||||
"AGENTS.md",
|
||||
"ARCHITECTURE.md",
|
||||
"PROJECT_CONTEXT.md",
|
||||
"docs/MVP_DESIGN.md",
|
||||
"docs/design/",
|
||||
"docs/adr/"
|
||||
],
|
||||
"pi": {
|
||||
"extensions": [
|
||||
"./extensions/rdk-diagnose.ts"
|
||||
],
|
||||
"skills": ["./skills"]
|
||||
},
|
||||
"dependencies": {
|
||||
"ssh2": "^1.17.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@earendil-works/pi-coding-agent": "0.79.9",
|
||||
"@earendil-works/pi-ai": "0.79.9"
|
||||
},
|
||||
"devDependencies": {
|
||||
"typescript": "^5.5.0",
|
||||
"@types/node": "^22.0.0",
|
||||
"@types/ssh2": "^1.15.5",
|
||||
"@earendil-works/pi-coding-agent": "0.79.9",
|
||||
"@earendil-works/pi-ai": "0.79.9",
|
||||
"vitest": "^2.1.0"
|
||||
},
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest"
|
||||
}
|
||||
}
|
||||
191
skills/rdk-diagnose/SKILL.md
Normal file
191
skills/rdk-diagnose/SKILL.md
Normal file
@ -0,0 +1,191 @@
|
||||
---
|
||||
description: |
|
||||
RDK 嵌入式诊断 Agent。基于证据推理的硬件 Bring-up 与故障定位框架。
|
||||
教模型"怎么思考"而非"执行什么步骤",适配任意外设类型。
|
||||
---
|
||||
|
||||
# RDK Diagnose — 诊断推理框架
|
||||
|
||||
## 你的身份
|
||||
|
||||
你是 RDK 嵌入式诊断 Agent,运行在开发者主机上,通过 SSH 只读访问目标开发板。你是诊断推理者,不是命令执行器。你的价值不在于执行更多检查,而在于**选择能区分竞争假设的检查**,并**持续追问当前结论的边界**。
|
||||
|
||||
## 核心思维模型
|
||||
|
||||
### 模型一:诊断的本质是逐步缩小故障层
|
||||
|
||||
你面对的不是一个"摄像头问题",而是一个从应用到硬件的 7 层堆栈。每一层的"通过"只证明该层的有限事实,不能自动证明下一层也正常。你的任务是**用证据逐层收敛**,而不是跳跃归因。
|
||||
|
||||
### 模型二:信号矛盾是最高价值线索
|
||||
|
||||
单一信号告诉你"什么可能错了",信号矛盾告诉你"什么不可能同时成立"。当你看到两个互相矛盾的信号时,矛盾本身才是最值得分析的对象——而不是急于选一边站队。
|
||||
|
||||
例如:I2C 有响应 ≠ 控制链路全通,但 I2C 有响应 + 初始化失败 = 控制链路通但数据链路不通。这个矛盾比任何一个单独信号都更有诊断价值。
|
||||
|
||||
### 模型三:假设必须覆盖全部已知 Observation
|
||||
|
||||
如果你提出的假设只能解释部分观察结果,而解释不了另一部分,那这个假设就是不完备的——置信度自动降级。好的假设能解释所有已知事实,差的假设选择性忽略不方便的事实。
|
||||
|
||||
### 模型四:可复现性是诊断信号
|
||||
|
||||
- 持续性故障 → 倾向于配置、软件、永久性物理连接问题
|
||||
- 间歇性故障 → 倾向于接触不良、时序竞态、供电波动
|
||||
- 重启后行为变化 → 检查初始化顺序、上电时序、是否需要预热
|
||||
|
||||
不要把"重启后好了"当作终点——它自身就是一条证据,说明故障不是永久性的。
|
||||
|
||||
## 三类知识及其用法
|
||||
|
||||
诊断依赖三类知识,它们的作用和权威性不同:
|
||||
|
||||
| 类型 | 作用 | 权威性 | 示例 |
|
||||
|------|------|--------|------|
|
||||
| 模式知识 | 指导**怎么思考** | 通用,适用所有外设 | 分层排查、信号矛盾分析、假设覆盖度检查 |
|
||||
| 规则知识 | 防止**跳跃归因** | 按外设领域 | I2C 空 ≠ 硬件坏、进程启动 ≠ 驱动正常 |
|
||||
| 案例知识 | 提示**假设方向** | 仅参考,不能当证据 | GS130W 排查经历中哪些假设被推翻过 |
|
||||
|
||||
**使用原则:**
|
||||
|
||||
- 模式知识是思维方式,始终带着,不需要"读取"
|
||||
- 规则知识在进入具体外设领域时加载,防止踩已知的坑
|
||||
- 案例知识提供假设候选和历史教训,但**当前设备证据永远优先于历史案例**
|
||||
|
||||
**进入新外设诊断前,必须加载:**
|
||||
1. 该外设的领域规则知识
|
||||
2. 与该外设和设备型号相关的历史案例
|
||||
3. 通用分层模式始终适用,无需额外加载
|
||||
|
||||
## 诊断循环
|
||||
|
||||
### 循环结构
|
||||
|
||||
每轮诊断按以下流程推进,不是线性步骤,是循环迭代:
|
||||
|
||||
```
|
||||
当前已知事实 (All Observations)
|
||||
↓
|
||||
信号矛盾分析 (哪些信号互相矛盾?)
|
||||
↓
|
||||
更新假设 (哪些假设概率上升/下降?)
|
||||
↓
|
||||
假设覆盖度检查 (当前假设能解释全部 Observation 吗?)
|
||||
↓
|
||||
选择下一个检查 (哪个检查最能区分仍成立的假设?)
|
||||
↓
|
||||
执行检查 → 获得新 Observation → 回到开头
|
||||
```
|
||||
|
||||
### 选择下一个检查的原则
|
||||
|
||||
不是按固定清单执行,而是按以下优先级选择:
|
||||
|
||||
1. **信息增益最高**:哪个检查能最大程度区分当前竞争假设?
|
||||
2. **风险最低**:只读 > 主动探测,被动观察 > 修改状态
|
||||
3. **不重复**:相同检查不无理由重复执行
|
||||
4. **从上层开始**:软件层检查成本低、风险低,先排除上层再深入硬件
|
||||
|
||||
### 停止条件
|
||||
|
||||
诊断停止不是因为"到了 5 轮",而是因为:
|
||||
|
||||
- **信息增益耗尽**:安全范围内,所有可区分竞争假设的检查都已完成
|
||||
- **证据充分**:某假设置信度达到 high,且覆盖全部 Observation
|
||||
- **需要人工介入**:剩余不确定性需要物理检查(排线、拨码、供电测量)或更换部件
|
||||
|
||||
5 轮是安全阀,不是方法论。如果 3 轮已经收敛,不要为了凑轮数做无意义的检查。
|
||||
|
||||
## 信号模式识别
|
||||
|
||||
以下模式是通用的,不依赖外设类型:
|
||||
|
||||
### 模式:控制链路通但数据链路不通
|
||||
|
||||
| 信号组合 | 含义 |
|
||||
|----------|------|
|
||||
| 控制总线有响应 (I2C ACK / SPI ID / UART 回显) | 控制链路通 |
|
||||
| 数据通道无活动 (无设备节点 / 无数据流 / 无中断) | 数据链路不通 |
|
||||
|
||||
**通用推理:** 控制通 + 数据不通 → 优先排查物理数据通路(排线、MIPI、高速接口方向、锁扣),而非软件配置。控制链路已经证明配置大概率正确。
|
||||
|
||||
### 模式:所有层都正常但无最终输出
|
||||
|
||||
**通用推理:** 如果应用层、运行时、驱动、设备树、总线都正常,但没有最终输出,问题在数据格式、时钟同步、上层处理链,而非底层硬件。
|
||||
|
||||
### 模式:单次阴性结果
|
||||
|
||||
**通用推理:** 单次空扫描、单次 timeout、单次失败日志,只能记录为"当前时刻未观察到 X"。不能直接推断硬件损坏。需要先确认:设备当时是否处于可响应状态?bus/供电/复位/时钟条件是否满足?
|
||||
|
||||
## 假设管理
|
||||
|
||||
### 假设的置信度升降规则
|
||||
|
||||
- **上升**:新 Observation 与假设预测一致,且排除了竞争假设
|
||||
- **下降**:新 Observation 与假设预测矛盾,或有其他假设能更好解释
|
||||
- **不变**:新 Observation 与假设无关,或无法区分多个假设
|
||||
|
||||
### 假设覆盖度检查
|
||||
|
||||
每轮结束前,追问自己:
|
||||
|
||||
1. 当前假设能解释**全部**已知 Observation 吗?
|
||||
2. 有没有 Observation 是当前假设解释不了的?
|
||||
3. 如果这个假设成立,**什么现象应该出现但没有出现**?
|
||||
4. 如果这个假设错误,**什么现象会出现**?
|
||||
|
||||
只有能解释全部 Observation 且没有反证的假设,才能达到 high 置信度。
|
||||
|
||||
### 禁止的推理捷径
|
||||
|
||||
| 错误模式 | 正确做法 |
|
||||
|----------|----------|
|
||||
| 用平台架构特点解释异常 | 平台特点只能解释正常行为,不能解释故障 |
|
||||
| 看到配置差异就断言是根因 | 确认差异是否真的是故障原因,而非正常变体 |
|
||||
| 用一条 Observation 直接宣布根因 | 根因需要多条收敛的 Evidence |
|
||||
| 把"可能"说成"已确认" | 区分 confidence 等级 |
|
||||
| 跳过应用层直接检查硬件 | 从上层开始,逐层排除 |
|
||||
|
||||
## 两阶段诊断流程
|
||||
|
||||
### Phase 1: Preparation(建立连接与身份,不计入正式轮次)
|
||||
|
||||
1. 用户提供 SSH 目标和问题描述
|
||||
2. 调用 `rdk_diag_create` 创建 Target 和 Diagnosis
|
||||
3. 调用 `rdk_diag_connection_check` 验证 SSH
|
||||
4. 调用 `rdk_diag_identify_target` 识别产品身份
|
||||
5. 调用 `rdk_diag_inspect_system` 采集系统信息
|
||||
|
||||
### Phase 2: Diagnosis(正式诊断,应用上述推理框架)
|
||||
|
||||
6. **强制知识路由**:调用 `rdk_diag_get_knowledge` 加载对应外设的规则知识和案例知识。**未完成此步骤前,不得执行任何 Inspector。** 根据症状选择标签:
|
||||
- 摄像头初始化失败:`camera_init_failure`
|
||||
- 摄像头 Sensor 检测问题:`camera_sensor_detection`
|
||||
- I2C 无响应:`i2c_no_ack`
|
||||
- 设备节点缺失:`device_not_found`
|
||||
- 通用外设 Bring-up:`peripheral_bringup`
|
||||
7. 进入诊断循环,每次只执行一个 Inspector
|
||||
8. 每轮调用 `rdk_diag_finish_round` 结束本轮
|
||||
9. 信息增益耗尽或证据充分时调用 `rdk_diag_close` 结束
|
||||
|
||||
## 可用 Tool
|
||||
|
||||
所有远程操作通过 `rdk_diag_*` 语义化 Tool,不暴露任意 Shell。
|
||||
|
||||
**Core:** `rdk_diag_create` / `rdk_diag_get` / `rdk_diag_finish_round` / `rdk_diag_close`
|
||||
**Knowledge:** `rdk_diag_get_knowledge`(Phase 2 入口,强制调用)
|
||||
**Transport:** `rdk_diag_connection_check` / `rdk_diag_identify_target`
|
||||
**Context:** `rdk_diag_inspect_system`
|
||||
**General:** `rdk_diag_read_log` / `rdk_diag_inspect_device_tree` / `rdk_diag_inspect_device_nodes` / `rdk_diag_list_i2c_buses`
|
||||
**Camera:** `rdk_diag_camera_inspect_runtime` / `rdk_diag_camera_inspect_mapping` / `rdk_diag_camera_read_initialization_log` / `rdk_diag_camera_probe_i2c_target`
|
||||
|
||||
## 安全约束
|
||||
|
||||
- 不修改目标设备(不写文件、不装软件、不重启服务、不修改设备树、不刷固件)
|
||||
- 不保存密码、私钥或 Token
|
||||
- 不主动启动/停止/重启程序来重现故障
|
||||
- 不向用户暴露任意 Shell 命令执行能力
|
||||
|
||||
## 输出要求
|
||||
|
||||
每轮结束后汇报:当前假设、置信度、已排除项、假设覆盖度自检、下一步建议。
|
||||
|
||||
诊断结束时生成结构化 Report:Diagnosis ID、故障层级、已确认事实、剩余不确定性、Verification Plan。
|
||||
76
src/context/collector.ts
Normal file
76
src/context/collector.ts
Normal file
@ -0,0 +1,76 @@
|
||||
/**
|
||||
* Device Context Collector
|
||||
*
|
||||
* 通过 SSH 采集目标设备的身份信息,不做任何修改。
|
||||
* 只采集 Observed 事实,不掺杂 Expected 假设。
|
||||
*/
|
||||
|
||||
import { execSsh, type SshConfig } from "../transports/ssh.js";
|
||||
|
||||
export interface DeviceContext {
|
||||
vendor: string | null;
|
||||
product: string | null;
|
||||
soc: string | null;
|
||||
board: string | null;
|
||||
kernel_version: string | null;
|
||||
os_release: string | null;
|
||||
hostname: string | null;
|
||||
raw_uname: string | null;
|
||||
collected_at: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 S100 设备采集身份信息。
|
||||
* 只执行安全的只读命令。
|
||||
*/
|
||||
export async function collectDeviceContext(config: SshConfig): Promise<DeviceContext> {
|
||||
const now = new Date().toISOString();
|
||||
|
||||
// 并行采集多个命令
|
||||
const [unameResult, modelResult, osReleaseResult, hostnameResult] = await Promise.all([
|
||||
execSsh(config, "uname -a", 5_000),
|
||||
execSsh(config, "cat /sys/firmware/devicetree/base/model 2>/dev/null || echo 'N/A'", 5_000),
|
||||
execSsh(config, "cat /etc/os-release 2>/dev/null || echo 'N/A'", 5_000),
|
||||
execSsh(config, "hostname", 5_000),
|
||||
]);
|
||||
|
||||
const uname = unameResult.stdout.trim();
|
||||
const dtModel = modelResult.stdout.trim();
|
||||
const osRelease = osReleaseResult.stdout.trim();
|
||||
const hostname = hostnameResult.stdout.trim();
|
||||
|
||||
// 解析产品信息
|
||||
let vendor: string | null = null;
|
||||
let product: string | null = null;
|
||||
let soc: string | null = null;
|
||||
let board: string | null = null;
|
||||
|
||||
if (dtModel !== "N/A" && dtModel.length > 0) {
|
||||
// 设备树模型处理:去除 null 终止符
|
||||
const clean = dtModel.replace(/\0/g, "").trim();
|
||||
if (clean) {
|
||||
board = clean;
|
||||
if (clean.toLowerCase().includes("s100")) {
|
||||
product = "rdk-s100";
|
||||
vendor = "d-robotics";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 从 uname 提取架构信息
|
||||
if (uname.toLowerCase().includes("aarch64")) {
|
||||
soc = soc ?? "aarch64";
|
||||
}
|
||||
|
||||
return {
|
||||
vendor,
|
||||
product,
|
||||
soc,
|
||||
board,
|
||||
kernel_version: uname ? uname.split(" ")[2] ?? null : null,
|
||||
os_release: osRelease,
|
||||
hostname,
|
||||
raw_uname: uname,
|
||||
collected_at: now,
|
||||
};
|
||||
}
|
||||
329
src/core/diagnosis.ts
Normal file
329
src/core/diagnosis.ts
Normal file
@ -0,0 +1,329 @@
|
||||
/**
|
||||
* Diagnosis Core
|
||||
*
|
||||
* 管理诊断生命周期:创建、轮次推进、状态转换。
|
||||
* 不依赖 Pi Runtime,纯 TypeScript 逻辑。
|
||||
*/
|
||||
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type {
|
||||
Diagnosis,
|
||||
DiagnosisPhase,
|
||||
DiagnosisStatus,
|
||||
Action,
|
||||
ActionType,
|
||||
ActionResult,
|
||||
Observation,
|
||||
ExtractionMethod,
|
||||
Evidence,
|
||||
Hypothesis,
|
||||
ConclusionLevel,
|
||||
Artifact,
|
||||
DiagnosisReport,
|
||||
} from "./types.js";
|
||||
|
||||
// ─── In-memory store (MVP) ───────────────────────────────
|
||||
|
||||
const diagnoses = new Map<string, DiagnosisRecord>();
|
||||
const actions = new Map<string, ActionRecord>();
|
||||
const observations = new Map<string, ObservationRecord>();
|
||||
const evidences = new Map<string, EvidenceRecord>();
|
||||
const hypotheses = new Map<string, HypothesisRecord>();
|
||||
const artifacts = new Map<string, ArtifactRecord>();
|
||||
|
||||
// ─── Record types (mirror interface types) ─────────────────
|
||||
|
||||
interface DiagnosisRecord extends Diagnosis {
|
||||
actions: string[];
|
||||
observation_ids: string[];
|
||||
evidence_ids: string[];
|
||||
hypothesis_ids: string[];
|
||||
}
|
||||
|
||||
interface ActionRecord extends Action {}
|
||||
|
||||
interface ObservationRecord {
|
||||
id: string;
|
||||
action_id: string;
|
||||
extraction: ExtractionMethod;
|
||||
signal: string;
|
||||
value: string | number | boolean | null;
|
||||
raw_excerpt?: string;
|
||||
source_excerpt?: string;
|
||||
details?: Record<string, unknown>;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
interface EvidenceRecord extends Evidence {}
|
||||
|
||||
interface HypothesisRecord extends Hypothesis {}
|
||||
|
||||
interface ArtifactRecord extends Artifact {}
|
||||
|
||||
// ─── Diagnosis CRUD ───────────────────────────────────────
|
||||
|
||||
export interface CreateDiagnosisInput {
|
||||
target_id: string;
|
||||
symptom: string;
|
||||
invocation: "preflight" | "failure_diagnosis" | "post_change_verification";
|
||||
}
|
||||
|
||||
export function createDiagnosis(input: CreateDiagnosisInput): DiagnosisRecord {
|
||||
const id = randomUUID();
|
||||
const now = new Date().toISOString();
|
||||
const diag: DiagnosisRecord = {
|
||||
id,
|
||||
target_id: input.target_id,
|
||||
phase: "preparation",
|
||||
round: 0,
|
||||
status: "in_progress",
|
||||
symptom: input.symptom,
|
||||
invocation: input.invocation,
|
||||
actions: [],
|
||||
observation_ids: [],
|
||||
evidence_ids: [],
|
||||
hypothesis_ids: [],
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
};
|
||||
diagnoses.set(id, diag);
|
||||
return diag;
|
||||
}
|
||||
|
||||
export function getDiagnosis(id: string): DiagnosisRecord | undefined {
|
||||
return diagnoses.get(id);
|
||||
}
|
||||
|
||||
export function advancePhase(id: string, phase: DiagnosisPhase): void {
|
||||
const d = diagnoses.get(id);
|
||||
if (!d) throw new Error(`Diagnosis not found: ${id}`);
|
||||
d.phase = phase;
|
||||
if (phase === "diagnosis" && d.round === 0) {
|
||||
d.round = 1;
|
||||
}
|
||||
d.updated_at = new Date().toISOString();
|
||||
}
|
||||
|
||||
export function advanceRound(id: string): void {
|
||||
const d = diagnoses.get(id);
|
||||
if (!d) throw new Error(`Diagnosis not found: ${id}`);
|
||||
d.round += 1;
|
||||
d.updated_at = new Date().toISOString();
|
||||
}
|
||||
|
||||
export function setDiagnosisStatus(id: string, status: DiagnosisStatus): void {
|
||||
const d = diagnoses.get(id);
|
||||
if (!d) throw new Error(`Diagnosis not found: ${id}`);
|
||||
d.status = status;
|
||||
d.updated_at = new Date().toISOString();
|
||||
}
|
||||
|
||||
// ─── Action CRUD ──────────────────────────────────────────
|
||||
|
||||
export function recordAction(
|
||||
diagnosisId: string,
|
||||
round: number,
|
||||
type: ActionType,
|
||||
name: string,
|
||||
description: string,
|
||||
params: Record<string, unknown>,
|
||||
result: ActionResult,
|
||||
exitCode?: number,
|
||||
durationMs?: number,
|
||||
artifactId?: string
|
||||
): ActionRecord {
|
||||
const id = randomUUID();
|
||||
const now = new Date().toISOString();
|
||||
const action: ActionRecord = {
|
||||
id,
|
||||
diagnosis_id: diagnosisId,
|
||||
round,
|
||||
type,
|
||||
name,
|
||||
description,
|
||||
parameters: params,
|
||||
result,
|
||||
exit_code: exitCode,
|
||||
duration_ms: durationMs,
|
||||
artifact_id: artifactId,
|
||||
created_at: now,
|
||||
};
|
||||
actions.set(id, action);
|
||||
|
||||
const d = diagnoses.get(diagnosisId);
|
||||
if (d) {
|
||||
d.actions.push(id);
|
||||
d.updated_at = now;
|
||||
}
|
||||
|
||||
return action;
|
||||
}
|
||||
|
||||
// ─── Observation CRUD ─────────────────────────────────────
|
||||
|
||||
export function addObservation(
|
||||
actionId: string,
|
||||
extraction: ExtractionMethod,
|
||||
signal: string,
|
||||
value: string | number | boolean | null,
|
||||
sourceExcerpt?: string,
|
||||
details?: Record<string, unknown>
|
||||
): ObservationRecord {
|
||||
const id = randomUUID();
|
||||
const now = new Date().toISOString();
|
||||
const obs: ObservationRecord = {
|
||||
id,
|
||||
action_id: actionId,
|
||||
extraction,
|
||||
signal,
|
||||
value,
|
||||
source_excerpt: sourceExcerpt,
|
||||
details,
|
||||
created_at: now,
|
||||
};
|
||||
observations.set(id, obs);
|
||||
|
||||
const action = actions.get(actionId);
|
||||
if (action) {
|
||||
const d = diagnoses.get(action.diagnosis_id);
|
||||
if (d) {
|
||||
d.observation_ids.push(id);
|
||||
d.updated_at = now;
|
||||
}
|
||||
}
|
||||
|
||||
return obs;
|
||||
}
|
||||
|
||||
// ─── Evidence CRUD ────────────────────────────────────────
|
||||
|
||||
export function addEvidence(
|
||||
observationIds: string[],
|
||||
claim: string,
|
||||
scope: string,
|
||||
confirms: string,
|
||||
doesNotProve: string,
|
||||
prerequisites: string[]
|
||||
): EvidenceRecord {
|
||||
const id = randomUUID();
|
||||
const now = new Date().toISOString();
|
||||
const ev: EvidenceRecord = {
|
||||
id,
|
||||
observation_ids: observationIds,
|
||||
claim,
|
||||
scope,
|
||||
confirms,
|
||||
does_not_prove: doesNotProve,
|
||||
prerequisites,
|
||||
created_at: now,
|
||||
};
|
||||
evidences.set(id, ev);
|
||||
|
||||
// 挂到第一个 Observation 所属的 Diagnosis
|
||||
const firstObs = observations.get(observationIds[0] ?? "");
|
||||
if (firstObs) {
|
||||
const action = actions.get(firstObs.action_id);
|
||||
if (action) {
|
||||
const d = diagnoses.get(action.diagnosis_id);
|
||||
if (d) {
|
||||
d.evidence_ids.push(id);
|
||||
d.updated_at = now;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ev;
|
||||
}
|
||||
|
||||
// ─── Hypothesis CRUD ──────────────────────────────────────
|
||||
|
||||
export function addHypothesis(
|
||||
diagnosisId: string,
|
||||
layer: string,
|
||||
claim: string,
|
||||
confidence: number,
|
||||
supportingEvidenceIds: string[],
|
||||
contradictingEvidenceIds: string[]
|
||||
): HypothesisRecord {
|
||||
const id = randomUUID();
|
||||
const now = new Date().toISOString();
|
||||
const hyp: HypothesisRecord = {
|
||||
id,
|
||||
diagnosis_id: diagnosisId,
|
||||
layer,
|
||||
claim,
|
||||
confidence,
|
||||
supporting_evidence_ids: supportingEvidenceIds,
|
||||
contradicting_evidence_ids: contradictingEvidenceIds,
|
||||
ruled_out: false,
|
||||
conclusion: "insufficient_evidence",
|
||||
updated_at: now,
|
||||
};
|
||||
hypotheses.set(id, hyp);
|
||||
|
||||
const d = diagnoses.get(diagnosisId);
|
||||
if (d) {
|
||||
d.hypothesis_ids.push(id);
|
||||
d.updated_at = now;
|
||||
}
|
||||
|
||||
return hyp;
|
||||
}
|
||||
|
||||
export function updateHypothesisConclusion(id: string, conclusion: ConclusionLevel): void {
|
||||
const h = hypotheses.get(id);
|
||||
if (!h) throw new Error(`Hypothesis not found: ${id}`);
|
||||
h.conclusion = conclusion;
|
||||
if (conclusion === "ruled_out") {
|
||||
h.ruled_out = true;
|
||||
}
|
||||
h.updated_at = new Date().toISOString();
|
||||
}
|
||||
|
||||
// ─── Artifact CRUD ────────────────────────────────────────
|
||||
|
||||
export function saveArtifact(
|
||||
actionId: string,
|
||||
content: string,
|
||||
mimeType = "text/plain"
|
||||
): ArtifactRecord {
|
||||
const id = randomUUID();
|
||||
const now = new Date().toISOString();
|
||||
const art: ArtifactRecord = {
|
||||
id,
|
||||
action_id: actionId,
|
||||
mime_type: mimeType,
|
||||
size_bytes: Buffer.byteLength(content, "utf8"),
|
||||
content,
|
||||
truncated: false,
|
||||
checksum: "TODO",
|
||||
created_at: now,
|
||||
};
|
||||
artifacts.set(id, art);
|
||||
return art;
|
||||
}
|
||||
|
||||
// ─── Report Generation ────────────────────────────────────
|
||||
|
||||
export function generateReport(diagnosisId: string): DiagnosisReport | null {
|
||||
const d = diagnoses.get(diagnosisId);
|
||||
if (!d) return null;
|
||||
|
||||
const hypList = d.hypothesis_ids.map((hId) => hypotheses.get(hId)!).filter(Boolean);
|
||||
const ruledOut = hypList.filter((h) => h.ruled_out).map((h) => h.claim);
|
||||
const active = hypList.filter((h) => !h.ruled_out);
|
||||
const highest = active.reduce((best, h) => (h.confidence > (best?.confidence ?? 0) ? h : best), null as HypothesisRecord | null);
|
||||
|
||||
return {
|
||||
diagnosis_id: d.id,
|
||||
target_id: d.target_id,
|
||||
target_status: "verified", // TODO: 从 Target Registry 获取
|
||||
phase: d.phase,
|
||||
round: d.round,
|
||||
status: d.status,
|
||||
hypotheses: hypList,
|
||||
ruled_out: ruledOut,
|
||||
highest_confidence_layer: highest?.layer ?? null,
|
||||
next_steps: [],
|
||||
};
|
||||
}
|
||||
193
src/core/types.ts
Normal file
193
src/core/types.ts
Normal file
@ -0,0 +1,193 @@
|
||||
/**
|
||||
* RDK Diagnose — 核心类型定义
|
||||
*
|
||||
* 所有诊断相关的状态、Action 和报告类型。
|
||||
* 不依赖 Pi Runtime 或 SSH Transport 类型。
|
||||
*/
|
||||
|
||||
// ─── Target ───────────────────────────────────────────────
|
||||
|
||||
export type TargetStatus = "unverified" | "verified" | "conflict";
|
||||
|
||||
export interface TransportConfig {
|
||||
type: "ssh";
|
||||
host: string;
|
||||
user: string;
|
||||
port?: number;
|
||||
}
|
||||
|
||||
export interface ExpectedContext {
|
||||
product: string;
|
||||
transport: TransportConfig;
|
||||
permissions: { read_only: boolean };
|
||||
attached_devices?: { type: string; model: string }[];
|
||||
}
|
||||
|
||||
export interface Target {
|
||||
id: string;
|
||||
status: TargetStatus;
|
||||
transport: TransportConfig;
|
||||
expected: ExpectedContext;
|
||||
observed_product_id?: string;
|
||||
profile_id?: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
// ─── Diagnosis ────────────────────────────────────────────
|
||||
|
||||
export type DiagnosisPhase = "preparation" | "diagnosis";
|
||||
export type DiagnosisStatus = "in_progress" | "awaiting_user_action" | "completed" | "abandoned";
|
||||
|
||||
export interface Diagnosis {
|
||||
id: string;
|
||||
target_id: string;
|
||||
phase: DiagnosisPhase;
|
||||
round: number;
|
||||
status: DiagnosisStatus;
|
||||
symptom: string;
|
||||
invocation: "preflight" | "failure_diagnosis" | "post_change_verification";
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
// ─── Action ───────────────────────────────────────────────
|
||||
|
||||
export type ActionType = "ssh_command" | "manual_check" | "system_inspection";
|
||||
export type ActionResult = "success" | "failure" | "timeout" | "policy_blocked" | "manual_pending";
|
||||
|
||||
export interface Action {
|
||||
id: string;
|
||||
diagnosis_id: string;
|
||||
round: number;
|
||||
type: ActionType;
|
||||
name: string;
|
||||
description: string;
|
||||
parameters: Record<string, unknown>;
|
||||
result: ActionResult;
|
||||
exit_code?: number;
|
||||
duration_ms?: number;
|
||||
artifact_id?: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
// ─── Observation ──────────────────────────────────────────
|
||||
|
||||
export type ExtractionMethod = "deterministic" | "model_extracted" | "manual_reported";
|
||||
|
||||
export interface Observation {
|
||||
id: string;
|
||||
action_id: string;
|
||||
extraction: ExtractionMethod;
|
||||
signal: string;
|
||||
value: string | number | boolean | null;
|
||||
raw_excerpt?: string;
|
||||
source_excerpt?: string;
|
||||
details?: Record<string, unknown>;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
// ─── Evidence ─────────────────────────────────────────────
|
||||
|
||||
export interface Evidence {
|
||||
id: string;
|
||||
observation_ids: string[];
|
||||
claim: string;
|
||||
scope: string;
|
||||
confirms: string;
|
||||
does_not_prove: string;
|
||||
prerequisites: string[];
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
// ─── Hypothesis ───────────────────────────────────────────
|
||||
|
||||
export type ConclusionLevel = "confirmed" | "highly_suspected" | "insufficient_evidence" | "ruled_out";
|
||||
|
||||
export interface Hypothesis {
|
||||
id: string;
|
||||
diagnosis_id: string;
|
||||
layer: string;
|
||||
claim: string;
|
||||
confidence: number; // 0-1
|
||||
supporting_evidence_ids: string[];
|
||||
contradicting_evidence_ids: string[];
|
||||
ruled_out: boolean;
|
||||
conclusion: ConclusionLevel;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
// ─── Artifact ─────────────────────────────────────────────
|
||||
|
||||
export interface Artifact {
|
||||
id: string;
|
||||
action_id: string;
|
||||
mime_type: string;
|
||||
size_bytes: number;
|
||||
content: string;
|
||||
truncated: boolean;
|
||||
checksum: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
// ─── Diagnosis Report ─────────────────────────────────────
|
||||
|
||||
export interface DiagnosisReport {
|
||||
diagnosis_id: string;
|
||||
target_id: string;
|
||||
target_status: TargetStatus;
|
||||
phase: DiagnosisPhase;
|
||||
round: number;
|
||||
status: DiagnosisStatus;
|
||||
hypotheses: Hypothesis[];
|
||||
ruled_out: string[];
|
||||
highest_confidence_layer: string | null;
|
||||
resolution?: {
|
||||
type: "confirmed" | "highly_suspected" | "insufficient_evidence";
|
||||
layer: string;
|
||||
claim: string;
|
||||
confidence: number;
|
||||
};
|
||||
verification_plan?: string[];
|
||||
next_steps: string[];
|
||||
}
|
||||
|
||||
// ─── Profile & Capability ─────────────────────────────────
|
||||
|
||||
export interface ProductProfile {
|
||||
id: string;
|
||||
name: string;
|
||||
soc: string;
|
||||
board: string;
|
||||
revision?: string;
|
||||
transports: string[];
|
||||
default_permissions: { read_only: boolean };
|
||||
}
|
||||
|
||||
export interface PeripheralProfile {
|
||||
id: string;
|
||||
model: string;
|
||||
interface: string;
|
||||
expected_sensors: number;
|
||||
expected_addresses?: number[];
|
||||
init_prerequisites: string[];
|
||||
success_indicators: string[];
|
||||
}
|
||||
|
||||
export interface CapabilityPlugin {
|
||||
id: string;
|
||||
name: string;
|
||||
supported_products: string[];
|
||||
supported_peripherals: string[];
|
||||
inspectors: InspectorDefinition[];
|
||||
}
|
||||
|
||||
export interface InspectorDefinition {
|
||||
name: string;
|
||||
description: string;
|
||||
command_template: string;
|
||||
timeout_ms: number;
|
||||
risk_level: "safe" | "controlled" | "dangerous";
|
||||
prerequisites?: string[];
|
||||
applicable_when: Record<string, unknown>;
|
||||
}
|
||||
180
src/parsers/camera.ts
Normal file
180
src/parsers/camera.ts
Normal file
@ -0,0 +1,180 @@
|
||||
/**
|
||||
* Camera Sensor Detection Parser
|
||||
*
|
||||
* 对 Camera 初始化日志、i2cdetect 输出、设备树进行确定性解析。
|
||||
* 只提取"看到了什么",不输出 Root Cause 或修复建议。
|
||||
*/
|
||||
|
||||
import { execSsh, type SshConfig } from "../transports/ssh.js";
|
||||
|
||||
// ─── 日志解析 ─────────────────────────────────────────────
|
||||
|
||||
export interface CameraLogSummary {
|
||||
sensor_count: number | null;
|
||||
expected_sensor_count: number | null;
|
||||
sensor_ids: string[];
|
||||
errors: string[];
|
||||
warnings: string[];
|
||||
detection_phase: "unknown" | "not_started" | "in_progress" | "completed" | "failed";
|
||||
raw_excerpt: string;
|
||||
}
|
||||
|
||||
export function parseCameraInitLog(log: string): CameraLogSummary {
|
||||
const lines = log.split("\n");
|
||||
const errors: string[] = [];
|
||||
const warnings: string[] = [];
|
||||
const sensorIds: string[] = [];
|
||||
let sensorCount: number | null = null;
|
||||
let expectedSensorCount: number | null = null;
|
||||
let detectionPhase: CameraLogSummary["detection_phase"] = "unknown";
|
||||
|
||||
for (const line of lines) {
|
||||
if (/error|fail|timeout|no ack/i.test(line)) {
|
||||
errors.push(line.trim());
|
||||
}
|
||||
if (/warn/i.test(line) && !/error|fail/i.test(line)) {
|
||||
warnings.push(line.trim());
|
||||
}
|
||||
const idMatch = line.match(/(GS130W|SC132GS|SC\d+[A-Z]*)/i);
|
||||
if (idMatch) {
|
||||
sensorIds.push(idMatch[0]);
|
||||
}
|
||||
|
||||
// 分别匹配 detected 和 expected
|
||||
const detectedMatch = line.match(/(?:detected|found)\s+(\d+)\s+sensors?/i);
|
||||
if (detectedMatch && detectedMatch[1]) {
|
||||
sensorCount = parseInt(detectedMatch[1], 10);
|
||||
}
|
||||
const expectedMatch = line.match(/expected\s+(\d+)/i);
|
||||
if (expectedMatch && expectedMatch[1]) {
|
||||
expectedSensorCount = parseInt(expectedMatch[1], 10);
|
||||
}
|
||||
|
||||
if (/starting sensor detection/i.test(line)) {
|
||||
detectionPhase = "in_progress";
|
||||
}
|
||||
if (/sensor detection (?:completed|done)/i.test(line)) {
|
||||
detectionPhase = "completed";
|
||||
}
|
||||
if (/sensor detection failed/i.test(line)) {
|
||||
detectionPhase = "failed";
|
||||
}
|
||||
}
|
||||
|
||||
const excerpt = log.length > 2000 ? log.slice(-2000) : log;
|
||||
|
||||
return {
|
||||
sensor_count: sensorCount,
|
||||
expected_sensor_count: expectedSensorCount,
|
||||
sensor_ids: [...new Set(sensorIds)],
|
||||
errors,
|
||||
warnings,
|
||||
detection_phase: detectionPhase,
|
||||
raw_excerpt: excerpt,
|
||||
};
|
||||
}
|
||||
|
||||
// ─── i2cdetect 解析 ───────────────────────────────────────
|
||||
|
||||
export interface I2cDetectResult {
|
||||
bus: string;
|
||||
detected_addresses: number[];
|
||||
raw_excerpt: string;
|
||||
}
|
||||
|
||||
export function parseI2cDetect(raw: string, bus: string): I2cDetectResult {
|
||||
const detected: number[] = [];
|
||||
const lines = raw.split("\n");
|
||||
|
||||
for (const line of lines) {
|
||||
const match = line.match(/^\s*(\d{2}):\s*(.*)/);
|
||||
if (match) {
|
||||
const prefix = match[1] ?? "";
|
||||
const cells = (match[2] ?? "").trim().split(/\s+/);
|
||||
const base = parseInt(prefix, 16);
|
||||
for (let i = 0; i < cells.length; i++) {
|
||||
const cell = cells[i] ?? "";
|
||||
if (/^[0-9a-f]{2}$/i.test(cell)) {
|
||||
detected.push(base + i);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
bus,
|
||||
detected_addresses: detected,
|
||||
raw_excerpt: raw.slice(0, 2000),
|
||||
};
|
||||
}
|
||||
|
||||
// ─── 设备树解析 ───────────────────────────────────────────
|
||||
|
||||
export interface DeviceTreeSummary {
|
||||
camera_nodes: string[];
|
||||
i2c_buses: string[];
|
||||
status_ok: string[];
|
||||
status_disabled: string[];
|
||||
raw_excerpt: string;
|
||||
}
|
||||
|
||||
export function parseCameraDeviceTree(raw: string): DeviceTreeSummary {
|
||||
const lines = raw.split("\n");
|
||||
const cameraNodes: string[] = [];
|
||||
const i2cBuses: string[] = [];
|
||||
const statusOk: string[] = [];
|
||||
const statusDisabled: string[] = [];
|
||||
|
||||
for (const line of lines) {
|
||||
if (/camera|sensor|mipi|csi/i.test(line)) {
|
||||
cameraNodes.push(line.trim());
|
||||
}
|
||||
if (/i2c/i.test(line)) {
|
||||
i2cBuses.push(line.trim());
|
||||
}
|
||||
if (/\bokay\b/i.test(line) && /status/i.test(line)) {
|
||||
statusOk.push(line.trim());
|
||||
}
|
||||
if (/\bdisabled\b/i.test(line) && /status/i.test(line)) {
|
||||
statusDisabled.push(line.trim());
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
camera_nodes: cameraNodes,
|
||||
i2c_buses: i2cBuses,
|
||||
status_ok: statusOk,
|
||||
status_disabled: statusDisabled,
|
||||
raw_excerpt: lines.slice(0, 100).join("\n"),
|
||||
};
|
||||
}
|
||||
|
||||
// ─── Sensor 映射解析 ──────────────────────────────────────
|
||||
|
||||
export interface SensorMapping {
|
||||
device_path: string;
|
||||
sensor_name: string | null;
|
||||
bus: string | null;
|
||||
address: string | null;
|
||||
driver: string | null;
|
||||
}
|
||||
|
||||
export function parseSensorMapping(raw: string): SensorMapping[] {
|
||||
const mappings: SensorMapping[] = [];
|
||||
const lines = raw.split("\n");
|
||||
|
||||
for (const line of lines) {
|
||||
const parts = line.trim().split(/\s+/);
|
||||
if (parts.length >= 2) {
|
||||
mappings.push({
|
||||
device_path: parts[0] ?? "",
|
||||
sensor_name: parts[1] ?? null,
|
||||
bus: parts[2] ?? null,
|
||||
address: parts[3] ?? null,
|
||||
driver: parts[4] ?? null,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return mappings;
|
||||
}
|
||||
17
src/profiles/rdk-s100.ts
Normal file
17
src/profiles/rdk-s100.ts
Normal file
@ -0,0 +1,17 @@
|
||||
/**
|
||||
* RDK S100 Product Profile
|
||||
*
|
||||
* 声明式 Profile,不执行 Inspector。
|
||||
* 提供 S100 的预期身份、SoC、板型、默认权限和已知外设。
|
||||
*/
|
||||
|
||||
import type { ProductProfile } from "../core/types.js";
|
||||
|
||||
export const rdkS100Profile: ProductProfile = {
|
||||
id: "rdk-s100",
|
||||
name: "RDK S100",
|
||||
soc: "D-Robotics S100",
|
||||
board: "RDK S100",
|
||||
transports: ["ssh"],
|
||||
default_permissions: { read_only: true },
|
||||
};
|
||||
19
src/profiles/registry.ts
Normal file
19
src/profiles/registry.ts
Normal file
@ -0,0 +1,19 @@
|
||||
/**
|
||||
* Product Profile Registry
|
||||
*
|
||||
* 维护所有已注册的 Product Profile。
|
||||
* 首次使用时,根据 Observed Device Context 匹配 Profile。
|
||||
*/
|
||||
|
||||
import type { ProductProfile } from "../core/types.js";
|
||||
import { rdkS100Profile } from "./rdk-s100.js";
|
||||
|
||||
const profiles: ProductProfile[] = [rdkS100Profile];
|
||||
|
||||
export function getProfile(id: string): ProductProfile | undefined {
|
||||
return profiles.find((p) => p.id === id);
|
||||
}
|
||||
|
||||
export function listProfiles(): ProductProfile[] {
|
||||
return profiles;
|
||||
}
|
||||
65
src/targets/registry.ts
Normal file
65
src/targets/registry.ts
Normal file
@ -0,0 +1,65 @@
|
||||
/**
|
||||
* Target Registry
|
||||
*
|
||||
* 管理 Target 的创建、查询和状态转换。
|
||||
* Target 只保存连接引用、Expected Context、Policy 和非证据性注册元数据。
|
||||
* Observed Device Context 保存在 Diagnosis 中,不写入 Target。
|
||||
*/
|
||||
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type { Target, TransportConfig, ExpectedContext, TargetStatus } from "../core/types.js";
|
||||
|
||||
export interface TargetRecord {
|
||||
id: string;
|
||||
status: TargetStatus;
|
||||
transport: TransportConfig;
|
||||
expected: ExpectedContext;
|
||||
observed_product_id?: string;
|
||||
profile_id?: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
const targets = new Map<string, TargetRecord>();
|
||||
|
||||
export function createTarget(transport: TransportConfig, expected: ExpectedContext): TargetRecord {
|
||||
const id = randomUUID();
|
||||
const now = new Date().toISOString();
|
||||
const record: TargetRecord = {
|
||||
id,
|
||||
status: "unverified",
|
||||
transport,
|
||||
expected,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
};
|
||||
targets.set(id, record);
|
||||
return record;
|
||||
}
|
||||
|
||||
export function getTarget(id: string): TargetRecord | undefined {
|
||||
return targets.get(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新 Target 状态:
|
||||
* - unverified → verified 或 conflict
|
||||
* - 不允许从 verified 退回 unverified
|
||||
*/
|
||||
export function updateTargetStatus(id: string, status: TargetStatus, observedProductId?: string): TargetRecord {
|
||||
const t = targets.get(id);
|
||||
if (!t) throw new Error(`Target not found: ${id}`);
|
||||
t.status = status;
|
||||
t.updated_at = new Date().toISOString();
|
||||
if (observedProductId !== undefined) {
|
||||
t.observed_product_id = observedProductId;
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
export function setTargetProfile(id: string, profileId: string): void {
|
||||
const t = targets.get(id);
|
||||
if (!t) throw new Error(`Target not found: ${id}`);
|
||||
t.profile_id = profileId;
|
||||
t.updated_at = new Date().toISOString();
|
||||
}
|
||||
116
src/transports/ssh.ts
Normal file
116
src/transports/ssh.ts
Normal file
@ -0,0 +1,116 @@
|
||||
/**
|
||||
* SSH Transport
|
||||
*
|
||||
* 使用 Node.js child_process.spawn() 以参数数组安全调用系统 ssh。
|
||||
* shell: false,参数严格校验,禁止拼接 Shell 命令。
|
||||
*/
|
||||
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
export interface SshResult {
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
exitCode: number | null;
|
||||
durationMs: number;
|
||||
}
|
||||
|
||||
export interface SshConfig {
|
||||
type: "ssh";
|
||||
host: string;
|
||||
user: string;
|
||||
port?: number;
|
||||
}
|
||||
|
||||
const SSH_DEFAULTS = {
|
||||
port: 22,
|
||||
connectTimeoutSec: 10,
|
||||
};
|
||||
|
||||
function validateSshParam(value: string, label: string): void {
|
||||
if (!/^[a-zA-Z0-9._-]+$/.test(value)) {
|
||||
throw new Error(`Invalid SSH ${label}: "${value}". Only alphanumeric, dots, hyphens, and underscores allowed.`);
|
||||
}
|
||||
}
|
||||
|
||||
export async function execSsh(config: SshConfig, command: string, timeoutMs = 15_000): Promise<SshResult> {
|
||||
validateSshParam(config.host, "host");
|
||||
validateSshParam(config.user, "user");
|
||||
|
||||
const port = config.port ?? SSH_DEFAULTS.port;
|
||||
const start = Date.now();
|
||||
|
||||
const args = [
|
||||
"-o", "BatchMode=yes",
|
||||
"-o", `ConnectTimeout=${SSH_DEFAULTS.connectTimeoutSec}`,
|
||||
"-o", "StrictHostKeyChecking=accept-new",
|
||||
"-p", String(port),
|
||||
`${config.user}@${config.host}`,
|
||||
command,
|
||||
];
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const proc = spawn("ssh", args, {
|
||||
shell: false,
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
timeout: timeoutMs,
|
||||
});
|
||||
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
|
||||
proc.stdout.on("data", (data: Buffer) => {
|
||||
stdout += data.toString();
|
||||
});
|
||||
|
||||
proc.stderr.on("data", (data: Buffer) => {
|
||||
stderr += data.toString();
|
||||
});
|
||||
|
||||
proc.on("close", (exitCode) => {
|
||||
const durationMs = Date.now() - start;
|
||||
resolve({ stdout, stderr, exitCode, durationMs });
|
||||
});
|
||||
|
||||
proc.on("error", (err) => {
|
||||
const durationMs = Date.now() - start;
|
||||
resolve({
|
||||
stdout: "",
|
||||
stderr: `SSH spawn error: ${err.message}`,
|
||||
exitCode: -1,
|
||||
durationMs,
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function checkConnection(config: SshConfig): Promise<{
|
||||
reachable: boolean;
|
||||
errorType: "none" | "alias_not_found" | "network_unreachable" | "host_key_failed" | "auth_failed" | "service_unavailable" | "command_failed" | "unknown";
|
||||
result: SshResult;
|
||||
}> {
|
||||
const result = await execSsh(config, "true", 15_000);
|
||||
|
||||
if (result.exitCode === 0) {
|
||||
return { reachable: true, errorType: "none", result };
|
||||
}
|
||||
|
||||
const stderr = result.stderr.toLowerCase();
|
||||
|
||||
if (stderr.includes("could not resolve hostname") || stderr.includes("name or service not known")) {
|
||||
return { reachable: false, errorType: "alias_not_found", result };
|
||||
}
|
||||
if (stderr.includes("connection timed out") || stderr.includes("operation timed out") || stderr.includes("no route to host")) {
|
||||
return { reachable: false, errorType: "network_unreachable", result };
|
||||
}
|
||||
if (stderr.includes("host key verification failed") || stderr.includes("remote host identification has changed")) {
|
||||
return { reachable: false, errorType: "host_key_failed", result };
|
||||
}
|
||||
if (stderr.includes("permission denied") || stderr.includes("authentication failed") || stderr.includes("publickey")) {
|
||||
return { reachable: false, errorType: "auth_failed", result };
|
||||
}
|
||||
if (stderr.includes("connection refused") || stderr.includes("connection closed by remote host")) {
|
||||
return { reachable: false, errorType: "service_unavailable", result };
|
||||
}
|
||||
|
||||
return { reachable: false, errorType: "unknown", result };
|
||||
}
|
||||
194
tests/helpers/verify-s100.ts
Normal file
194
tests/helpers/verify-s100.ts
Normal file
@ -0,0 +1,194 @@
|
||||
/**
|
||||
* S100 真机验证脚本
|
||||
*
|
||||
* 跑通完整诊断链路:
|
||||
* Target → SSH → Device Context → 系统检查 → Camera 检查
|
||||
*
|
||||
* 用法: npx tsx tests/helpers/verify-s100.ts
|
||||
*/
|
||||
|
||||
import { checkConnection, execSsh, type SshConfig } from "../../src/transports/ssh.js";
|
||||
import { collectDeviceContext } from "../../src/context/collector.js";
|
||||
import { createTarget, getTarget, updateTargetStatus, setTargetProfile } from "../../src/targets/registry.js";
|
||||
import {
|
||||
createDiagnosis,
|
||||
getDiagnosis,
|
||||
advancePhase,
|
||||
recordAction,
|
||||
addObservation,
|
||||
addEvidence,
|
||||
addHypothesis,
|
||||
saveArtifact,
|
||||
generateReport,
|
||||
} from "../../src/core/diagnosis.js";
|
||||
import {
|
||||
parseCameraInitLog,
|
||||
parseI2cDetect,
|
||||
parseCameraDeviceTree,
|
||||
parseSensorMapping,
|
||||
} from "../../src/parsers/camera.js";
|
||||
import { getProfile } from "../../src/profiles/registry.js";
|
||||
|
||||
const CONFIG: SshConfig = {
|
||||
type: "ssh",
|
||||
host: "rdk-s100",
|
||||
user: "root",
|
||||
};
|
||||
|
||||
async function main() {
|
||||
console.log("╔══════════════════════════════════════╗");
|
||||
console.log("║ RDK Diagnose — S100 真机验证 ║");
|
||||
console.log("╚══════════════════════════════════════╝\n");
|
||||
|
||||
// ── Step 1: SSH 连接检查 ──
|
||||
console.log("1. SSH 连接检查...");
|
||||
const { reachable, errorType, result } = await checkConnection(CONFIG);
|
||||
console.log(` ${reachable ? "✅ 连接正常" : "❌ 连接失败: " + errorType}`);
|
||||
console.log(` 耗时: ${result.durationMs}ms\n`);
|
||||
|
||||
if (!reachable) {
|
||||
console.log("❌ 连接失败,终止验证。");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// ── Step 2: 创建 Target & Diagnosis ──
|
||||
console.log("2. 创建 Target & Diagnosis...");
|
||||
const target = createTarget(CONFIG, {
|
||||
product: "rdk-s100",
|
||||
transport: CONFIG,
|
||||
permissions: { read_only: true },
|
||||
});
|
||||
const diag = createDiagnosis({
|
||||
target_id: target.id,
|
||||
symptom: "验证系统诊断链路",
|
||||
invocation: "failure_diagnosis",
|
||||
});
|
||||
console.log(` Target: ${target.id}`);
|
||||
console.log(` Diagnosis: ${diag.id}\n`);
|
||||
|
||||
// ── Step 3: 采集设备身份 ──
|
||||
console.log("3. 采集设备身份...");
|
||||
const ctx = await collectDeviceContext(CONFIG);
|
||||
console.log(` 产品: ${ctx.product ?? "未识别"}`);
|
||||
console.log(` SoC: ${ctx.soc ?? "未知"}`);
|
||||
console.log(` 板型: ${ctx.board ?? "未知"}`);
|
||||
console.log(` 内核: ${ctx.kernel_version ?? "未知"}`);
|
||||
console.log(` 主机名: ${ctx.hostname ?? "未知"}\n`);
|
||||
|
||||
const action1 = recordAction(diag.id, diag.round, "system_inspection", "identify_target", "采集设备身份", {}, "success");
|
||||
const obs1 = addObservation(action1.id, "deterministic", "device.identity", ctx.product ?? "unknown", ctx.raw_uname ?? undefined);
|
||||
|
||||
const matched = ctx.product === "rdk-s100";
|
||||
if (ctx.product) {
|
||||
updateTargetStatus(target.id, matched ? "verified" : "conflict", ctx.product);
|
||||
if (matched) {
|
||||
setTargetProfile(target.id, "rdk-s100");
|
||||
advancePhase(diag.id, "diagnosis");
|
||||
}
|
||||
}
|
||||
addEvidence([obs1.id], `设备识别为 ${ctx.product ?? "未知"}`, "设备树采集", matched ? "产品匹配 S100" : "产品不匹配", "不证明外设状态", []);
|
||||
console.log(` ${matched ? "✅ 产品匹配" : "⚠️ 产品不匹配"}\n`);
|
||||
|
||||
// ── Step 4: 系统信息 ──
|
||||
console.log("4. 系统信息...");
|
||||
const [cpu, mem, disk] = await Promise.all([
|
||||
execSsh(CONFIG, "cat /proc/cpuinfo | grep -E 'processor|Hardware' | head -5", 5000),
|
||||
execSsh(CONFIG, "free -h | head -3", 5000),
|
||||
execSsh(CONFIG, "df -h / | tail -1", 5000),
|
||||
]);
|
||||
console.log(` CPU: ${cpu.stdout.split('\n').filter(l => l.includes('Hardware'))[0]?.trim() ?? "N/A"}`);
|
||||
console.log(` Memory: ${mem.stdout.split('\n')[1]?.trim() ?? "N/A"}`);
|
||||
console.log(` Disk: ${disk.stdout.trim()}\n`);
|
||||
|
||||
const action2 = recordAction(diag.id, diag.round, "system_inspection", "inspect_system", "采集系统信息", {}, "success");
|
||||
saveArtifact(action2.id, [cpu.stdout, mem.stdout, disk.stdout].join("\n---\n"));
|
||||
|
||||
// ── Step 5: I2C 总线 ──
|
||||
console.log("5. I2C 总线...");
|
||||
const i2cList = await execSsh(CONFIG, "i2cdetect -l 2>/dev/null", 5000);
|
||||
const busCount = i2cList.stdout.split("\n").filter((l: string) => l.includes("i2c-")).length;
|
||||
console.log(` 总线数: ${busCount}`);
|
||||
console.log(` ${i2cList.stdout.split('\n').slice(0, 5).join('\n ')}\n`);
|
||||
|
||||
const action3 = recordAction(diag.id, diag.round, "ssh_command", "list_i2c_buses", "列出 I2C 总线", {}, "success");
|
||||
addObservation(action3.id, "deterministic", "i2c.bus_count", busCount, i2cList.stdout.slice(0, 500));
|
||||
|
||||
// ── Step 6: 设备节点 ──
|
||||
console.log("6. 设备节点...");
|
||||
const devNodes = await execSsh(CONFIG, "ls -la /dev/video* /dev/media* /dev/v4l* 2>/dev/null || echo 'No video devices'", 5000);
|
||||
const hasVideo = devNodes.stdout.includes("video") && !devNodes.stdout.includes("No video");
|
||||
console.log(` ${hasVideo ? "✅ 有 video 设备" : "⚠️ 无 video 设备"}\n`);
|
||||
|
||||
const action4 = recordAction(diag.id, diag.round, "ssh_command", "inspect_device_nodes", "检查设备节点", {}, "success");
|
||||
addObservation(action4.id, "deterministic", "device_nodes.video_devices", hasVideo, devNodes.stdout.slice(0, 500));
|
||||
|
||||
if (hasVideo) {
|
||||
// Camera 映射
|
||||
const mapping = await execSsh(CONFIG, "for dev in /dev/video*; do [ -e \"$dev\" ] && echo \"$dev $(cat /sys/class/video4linux/$(basename $dev)/name 2>/dev/null)\"; done", 5000);
|
||||
const sensors = parseSensorMapping(mapping.stdout);
|
||||
console.log(` 映射: ${sensors.length} 个设备`);
|
||||
sensors.forEach((s) => console.log(` ${s.device_path} → ${s.sensor_name ?? "未知"}`));
|
||||
}
|
||||
|
||||
// ── Step 7: Camera 初始化日志 ──
|
||||
console.log("\n7. Camera 初始化日志...");
|
||||
const camLog = await execSsh(CONFIG, "dmesg | grep -iE 'camera|sensor|mipi|csi|v4l|i2c.*0x|gs130w|sc132' | tail -30", 10000);
|
||||
const logSummary = parseCameraInitLog(camLog.stdout);
|
||||
console.log(` 检测阶段: ${logSummary.detection_phase}`);
|
||||
console.log(` Sensor 数: ${logSummary.sensor_count ?? "N/A"} / 预期: ${logSummary.expected_sensor_count ?? "N/A"}`);
|
||||
console.log(` Sensor ID: ${logSummary.sensor_ids.join(", ") || "无"}`);
|
||||
console.log(` 错误: ${logSummary.errors.length} | 警告: ${logSummary.warnings.length}`);
|
||||
|
||||
if (logSummary.errors.length > 0) {
|
||||
console.log(` 前 5 条错误:`);
|
||||
logSummary.errors.slice(0, 5).forEach((e) => console.log(` ${e}`));
|
||||
}
|
||||
console.log();
|
||||
|
||||
const action5 = recordAction(diag.id, diag.round, "ssh_command", "camera_read_init_log", "读取 Camera 初始化日志", {}, "success");
|
||||
saveArtifact(action5.id, camLog.stdout);
|
||||
const obs5 = addObservation(action5.id, "deterministic", "camera.init_log",
|
||||
logSummary.sensor_count ?? "unknown", camLog.stdout.slice(0, 1000),
|
||||
{ sensor_count: logSummary.sensor_count, expected: logSummary.expected_sensor_count, phase: logSummary.detection_phase, errors: logSummary.errors.length }
|
||||
);
|
||||
|
||||
if (logSummary.sensor_count !== null && logSummary.expected_sensor_count !== null) {
|
||||
const mismatch = logSummary.sensor_count < logSummary.expected_sensor_count;
|
||||
addEvidence([obs5.id],
|
||||
mismatch ? `检测到 ${logSummary.sensor_count}/${logSummary.expected_sensor_count} 个 Sensor` : `Sensor 数量匹配`,
|
||||
"本次启动日志", mismatch ? "数量不符" : "数量正常", "不直接证明硬件损坏", []);
|
||||
}
|
||||
|
||||
// ── Step 8: I2C 探测 (如果有 Camera) ──
|
||||
if (busCount > 0) {
|
||||
console.log("8. I2C Bus 1 探测...");
|
||||
const i2cProbe = await execSsh(CONFIG, "sudo i2cdetect -r -y 1 2>/dev/null || echo 'probe failed'", 15000);
|
||||
const i2cResult = parseI2cDetect(i2cProbe.stdout, "1");
|
||||
const hasDevices = i2cResult.detected_addresses.length > 0;
|
||||
console.log(` ${hasDevices ? `检测到 ${i2cResult.detected_addresses.length} 个设备: ${i2cResult.detected_addresses.map((a) => '0x' + a.toString(16)).join(', ')}` : "⚠️ 无设备响应"}\n`);
|
||||
|
||||
const action6 = recordAction(diag.id, diag.round, "ssh_command", "camera_probe_i2c", "I2C 目标探测", { bus: "1" }, "success");
|
||||
const addrStr = i2cResult.detected_addresses.map((a) => `0x${a.toString(16)}`).join(", ");
|
||||
addObservation(action6.id, "deterministic", "camera.i2c_probe", hasDevices ? addrStr : "none", i2cProbe.stdout.slice(0, 1000));
|
||||
}
|
||||
|
||||
// ── Step 9: 报告 ──
|
||||
console.log("9. 诊断报告...");
|
||||
const report = generateReport(diag.id);
|
||||
if (report) {
|
||||
console.log(` Phase: ${report.phase} / Round: ${report.round}`);
|
||||
console.log(` Status: ${report.status}`);
|
||||
console.log(` Hypotheses: ${report.hypotheses.length}`);
|
||||
console.log(` Ruled out: ${report.ruled_out.join(", ") || "无"}`);
|
||||
console.log(` Highest confidence layer: ${report.highest_confidence_layer ?? "N/A"}`);
|
||||
}
|
||||
|
||||
console.log("\n╔══════════════════════════════════════╗");
|
||||
console.log("║ ✅ 验证完成 ║");
|
||||
console.log("╚══════════════════════════════════════╝");
|
||||
}
|
||||
|
||||
main().catch((e) => {
|
||||
console.error("❌ 验证失败:", e.message);
|
||||
process.exit(1);
|
||||
});
|
||||
71
tests/smoke.test.ts
Normal file
71
tests/smoke.test.ts
Normal file
@ -0,0 +1,71 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { createTarget, getTarget } from "../src/targets/registry.js";
|
||||
import { createDiagnosis, getDiagnosis, recordAction, addObservation, addEvidence, addHypothesis, generateReport } from "../src/core/diagnosis.js";
|
||||
import { parseCameraInitLog, parseI2cDetect, parseCameraDeviceTree } from "../src/parsers/camera.js";
|
||||
import { getProfile, listProfiles } from "../src/profiles/registry.js";
|
||||
|
||||
describe("Smoke tests", () => {
|
||||
it("creates a Target and Diagnosis", () => {
|
||||
const target = createTarget(
|
||||
{ type: "ssh", host: "192.168.1.100", user: "root" },
|
||||
{ product: "rdk-s100", transport: { type: "ssh", host: "192.168.1.100", user: "root" }, permissions: { read_only: true } }
|
||||
);
|
||||
expect(target.status).toBe("unverified");
|
||||
|
||||
const diag = createDiagnosis({ target_id: target.id, symptom: "摄像头不工作", invocation: "failure_diagnosis" });
|
||||
expect(diag.phase).toBe("preparation");
|
||||
expect(diag.round).toBe(0);
|
||||
});
|
||||
|
||||
it("records Action → Observation → Evidence → Hypothesis", () => {
|
||||
const target = createTarget(
|
||||
{ type: "ssh", host: "192.168.1.100", user: "root" },
|
||||
{ product: "rdk-s100", transport: { type: "ssh", host: "192.168.1.100", user: "root" }, permissions: { read_only: true } }
|
||||
);
|
||||
const diag = createDiagnosis({ target_id: target.id, symptom: "摄像头不工作", invocation: "failure_diagnosis" });
|
||||
|
||||
const action = recordAction(diag.id, 1, "ssh_command", "test", "测试", {}, "success", 0, 100);
|
||||
const obs = addObservation(action.id, "deterministic", "test.signal", true, "test excerpt");
|
||||
const ev = addEvidence([obs.id], "测试证据", "scope", "proves", "does not prove", []);
|
||||
const hyp = addHypothesis(diag.id, "bus_interface", "I2C 通信失败", 0.5, [ev.id], []);
|
||||
|
||||
expect(hyp.confidence).toBe(0.5);
|
||||
expect(hyp.conclusion).toBe("insufficient_evidence");
|
||||
|
||||
const report = generateReport(diag.id);
|
||||
expect(report).not.toBeNull();
|
||||
expect(report!.hypotheses.length).toBe(1);
|
||||
});
|
||||
|
||||
it("parses camera init log", () => {
|
||||
const log = "sensor detection started\ncamera: detected 1 sensors, expected 2\nsensor GS130W found\nsensor detection failed\nerror: timeout on i2c bus 1";
|
||||
const summary = parseCameraInitLog(log);
|
||||
expect(summary.sensor_count).toBe(1);
|
||||
expect(summary.expected_sensor_count).toBe(2);
|
||||
expect(summary.sensor_ids).toContain("GS130W");
|
||||
expect(summary.errors.length).toBe(2);
|
||||
expect(summary.detection_phase).toBe("failed");
|
||||
});
|
||||
|
||||
it("parses i2cdetect output", () => {
|
||||
const raw = " 0 1 2 3 4 5 6 7 8 9 a b c d e f\n00: -- -- -- -- -- -- -- -- -- -- -- -- --\n10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --\n20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --\n30: -- -- -- -- -- -- -- -- -- -- -- -- 3c -- -- --\n40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --";
|
||||
const result = parseI2cDetect(raw, "1");
|
||||
expect(result.bus).toBe("1");
|
||||
expect(result.detected_addresses).toContain(0x3c);
|
||||
});
|
||||
|
||||
it("parses camera device tree", () => {
|
||||
const raw = "/proc/device-tree/__symbols__/camera0\n/proc/device-tree/__symbols__/camera1\n/proc/device-tree/i2c@ff120000/camera@3c:status = \"okay\"\n/proc/device-tree/i2c@ff120000/sensor@1a:status = \"disabled\"";
|
||||
const summary = parseCameraDeviceTree(raw);
|
||||
expect(summary.camera_nodes.length).toBe(4);
|
||||
expect(summary.status_ok.length).toBe(1);
|
||||
expect(summary.status_disabled.length).toBe(1);
|
||||
});
|
||||
|
||||
it("has S100 profile", () => {
|
||||
const profile = getProfile("rdk-s100");
|
||||
expect(profile).toBeDefined();
|
||||
expect(profile!.soc).toBe("D-Robotics S100");
|
||||
expect(listProfiles().length).toBe(1);
|
||||
});
|
||||
});
|
||||
21
tsconfig.json
Normal file
21
tsconfig.json
Normal file
@ -0,0 +1,21 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"noImplicitOverride": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"allowImportingTsExtensions": true,
|
||||
"types": ["vitest/globals", "node"],
|
||||
"lib": ["ES2022"]
|
||||
},
|
||||
"include": ["extensions/**/*.ts", "src/**/*.ts", "tests/**/*.ts"]
|
||||
}
|
||||
13
vitest.config.ts
Normal file
13
vitest.config.ts
Normal file
@ -0,0 +1,13 @@
|
||||
import { defineConfig } from "vitest/config";
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
globals: true,
|
||||
environment: "node",
|
||||
include: ["tests/**/*.test.ts"],
|
||||
mockReset: true,
|
||||
restoreMocks: true,
|
||||
clearMocks: true,
|
||||
testTimeout: 10000,
|
||||
},
|
||||
});
|
||||
Loading…
x
Reference in New Issue
Block a user