Core 新增 next_action 状态与 validateNextAction(deny-only:eligibility/风险/重复/轮次上限);InspectorDefinition 加 tool 字段桥接语义名与工具名 Extension 补 3 个状态工具(add_evidence/update_hypothesis/record_manual_check)、增强 get(eligible+next_action+hypotheses)与 close(resolution 落 Diagnosis)、3 个只读 Camera inspector 接线 validateNextAction SKILL.md 改写为驱动循环;脚本化 Journey 降级为向后兼容;ADR-0002 + 文档注记 typecheck 零错误 + vitest 188/188(30 文件)
13 KiB
Architecture
Status: Accepted target architecture for the Pi diagnosis product; implementation proceeds by vertical slices.
Last reviewed: 2026-08-20
Owners: Project maintainers
This document is the compact architecture map for the Pi diagnosis product. Detailed behavior, scope, schemas, tools, safety policy, and acceptance criteria are defined in docs/MVP_DESIGN.md. Update this map when component ownership, dependency direction, state ownership, or a public contract changes.
1. Purpose and Scope
The system is an independent Pi Package that diagnoses RDK S100 Camera bring-up failures through controlled SSH Inspectors. It turns current-device output into traceable Observation, Evidence, Hypothesis, Next Action, and a machine-readable Diagnosis Report.
In Scope
- Pi CLI / Pi Runtime package, Skill, Extension, and semantic Tools.
- SSH Target registration, connection preparation, and S100 identity resolution.
- S100 + GS130W / dual SC132GS Sensor detection and Camera control-path diagnosis.
- Deterministic parsing, evidence-constrained model reasoning, persistence, and recovery.
Out of Scope
- Coding, Fix, Build, Deploy, and general active fault reproduction. A single policy-controlled Camera launch probe is allowed only when no usable initialization log exists.
- Arbitrary remote Shell, automatic system writes, and serial control.
- Real support for S100P, X5, other products, or non-Camera capabilities.
- Full ROS/TROS business diagnosis, MIPI image-quality diagnosis, dynamic plugin loading, and runtime knowledge learning.
2. External Context
| Actor or system | Relationship | Interface or contract |
|---|---|---|
| Developer | Describes target, expected hardware, and symptom; approves risky checks or performs physical actions | Pi natural-language session and structured reports |
| Pi Runtime | Loads the package and runs Skill/Tool loop with the selected model | Pi Package manifest, Extension API, Skill, TypeBox Tool schemas |
| System OpenSSH | Executes fixed, bounded remote Inspector commands | spawn() argument arrays with shell: false |
| RDK S100 | Current target device and source of Observations | SSH; no board-side Agent or project runtime |
| Future Coding Agent | Potential consumer after MVP | Stable Diagnosis Report; not part of MVP acceptance |
3. Major Components
The locations below reflect the current Camera vertical slice; (target) marks a component that is still target-only.
| Component | Responsibility | Must not own | Location |
|---|---|---|---|
| Pi Extension | Register Tools, adapt Pi calls, assemble dependencies, associate Pi sessions with Diagnosis IDs | Domain reasoning, product facts, arbitrary Shell | extensions/rdk-diagnose.ts |
| Diagnosis Skill | Guide model behavior, knowledge use, Evidence/Hypothesis updates, reporting, and stop conditions | Direct state-file edits or unrestricted commands | skills/rdk-diagnose/SKILL.md |
| Diagnosis Core | Orchestrate Preparation and Diagnosis, validate actions and state transitions, persist reports | S100, Camera, or GS130W special cases | src/core/ |
| Target and Context | Persist connection references and Expected Context; resolve Observed Device Context and conflicts | Product knowledge or diagnostic behavior | src/targets/, src/context/ |
| Product Registry | Resolve declarative board/SoC/interface facts | Pi Tools, Shell templates, diagnosis state machine | src/profiles/ |
| Peripheral Registry | Provide declarative external-device expectations and prerequisites | Inspector execution | (target) src/profiles/ |
| Capability Registry | Provide eligible Inspectors, Parsers, risk policy, evidence prerequisites, and verification semantics | Product-specific facts or generic Core policy | src/capabilities/camera/ (gating being wired into Core validation — ADR-0002) |
| SSH Transport | Execute only validated fixed command templates and classify transport errors | Model-authored commands or business conclusions | src/transports/ssh.ts |
| Knowledge Router | Select the minimum read-only knowledge bundle for target, symptom, and layer | Current-device Evidence or runtime knowledge mutation | knowledge/ (route map lives in the Extension) |
| Persistence | Store Target, append-only Diagnosis events, snapshots, and redacted Artifacts | SSH secrets or mutable historical records | src/persistence/ |
| Policy / Evidence Gate | Enforce risk, references, prerequisites, confidence transitions, and conclusion thresholds | Free-form diagnosis generation | src/core/evidence-gate.ts |
4. Dependency Direction
Pi Runtime
→ Pi Extension / Composition Root
→ Diagnosis Core
→ contracts owned by Core
← Product / Peripheral / Capability implementations
← SSH Transport / Persistence / Knowledge implementations
Rules:
- Pi-specific types stop at the Extension boundary; Core and Diagnosis Report do not depend on Pi session formats.
- Core depends on interfaces and stable domain contracts, not concrete S100, GS130W, Camera, SSH, or filesystem implementations.
- Product and Peripheral Profiles are declarative. They do not register Tools, own state machines, or inject Shell commands.
- Capability Plugin owns domain Inspectors and Parsers but consumes product/peripheral context rather than duplicating it.
- Infrastructure implements ports owned by inner modules. It does not create Evidence or Root Cause conclusions.
- Cross-module changes use stable IDs and validated schemas; shared code must have one clear owner.
5. Primary Runtime Flows
Preparation Flow
- Pi receives an SSH target, expected product/peripheral, and symptom.
- Core atomically creates an
unverifiedTarget and apreparation / round 0Diagnosis. - SSH Preparation performs applicable safe host-side checks and records Action, Observation, and Evidence without consuming the formal round limit.
- Identity Inspector creates Observed Device Context; resolver compares it with Expected Context.
- A conflict stops Profile activation. A verified supported target activates Product, Peripheral, Capability, and Knowledge routes, then enters
diagnosis / round 1.
Evidence-driven Diagnosis Flow
- Capability returns eligible Inspectors for the symptom and current context.
- The model proposes one information-gaining Next Action.
- Core validates applicability, prerequisites, duplication, risk, and round limit.
- Inspector executes through the Transport and stores redacted raw output as an Artifact.
- Parser produces a Normalized Signal; Core creates a factual Observation. Unknown formats may use a source-quoted model candidate subject to validation.
- The model creates Evidence, updates Hypothesis, and proposes the next action; Evidence Gate validates the transition.
- Core persists the event and snapshot, then continues, pauses, or closes with a structured report.
For Camera initialization evidence, existing ROS and mipi_cam logs are preferred. Core classifies their relevance from Target identity, boot time, PID linkage, executable, and launch parameters; stale logs cannot prove current state. When no current or explicitly selected failure-run log exists, Capability may propose the registered one-shot Camera launch probe; Core must validate Target policy, current process state, ownership, timeout, and cleanup before execution.
Recovery Flow
- User resumes with a Diagnosis ID.
- Persistence restores the snapshot and append-only history.
- Core revalidates connection and identity, retains prior Evidence/Hypothesis, and avoids unexplained repetition.
- A changed environment or completed user action may justify rerunning the relevant Inspector with an explicit reason.
6. State Ownership
| State | Source of truth | Writer | Lifecycle |
|---|---|---|---|
| Target transport, Expected Context, policy, verification status | targets/<target-id>/target.json |
Target Registry through Core | Reused across Diagnoses; no credentials |
| Observed Device Context | Diagnosis state and events | Context resolver through Core | Re-collected for each Diagnosis/resume |
| Action, Observation, Evidence, Hypothesis | Diagnosis append-only events plus snapshot | Core state APIs after validation | Immutable records; corrections append new records |
| Raw Inspector output | Redacted/truncated Artifact | Inspector execution pipeline | Owned by one Diagnosis Action |
| Product/Peripheral facts | Versioned Profiles in package | Maintainers | Reference expectation, never current Evidence |
| Diagnostic knowledge | Versioned files under knowledge/ |
Maintainers after review | Runtime read-only; cases are not current Evidence |
Persistent files never contain passwords, private keys, Tokens, or unredacted secrets.
7. Public Contracts
- Pi Tool names use the
rdk_diag_prefix and strict TypeBox schemas. - Inspector results distinguish
observed,unavailable,error, andblocked. - Stable domain contracts include Target, Device Context, Action, Observation, Evidence, Hypothesis, Next Action, and Diagnosis Report.
- Profile, Capability, and Knowledge resources carry stable IDs and versions in persisted state.
- Breaking schema changes require an explicit migration or a new version; do not silently reinterpret persisted records.
8. Cross-cutting Constraints
- Host implementation is TypeScript ESM; tests use Vitest.
- The S100 does not run Node.js or a project daemon.
- Remote execution uses fixed semantic Inspectors, strict input validation, timeouts, output limits, and
shell: false. - Diagnose is observational by default. Exceptions are the separately approved controlled I2C target probe and the policy-controlled one-shot Camera launch probe; neither is Fix.
- Current-device Evidence outranks Profiles, knowledge, historical cases, and model prior.
- Formal Diagnosis executes at most five counted Inspectors per round; Preparation is bounded by eligibility and information gain rather than that round count.
- Runtime knowledge is read-only. Confirmed findings become reviewable candidates before durable knowledge changes.
9. Guard Chain and Architectural Invariants
The deterministic guard chain between a model decision and system action is monotonic and fail-closed: each guard may deny or raise the required approval level, but no later guard may turn a rejection into an approval. Guards are order-independent for the final allow/deny result, and the strictest applicable outcome wins.
- Guards are deny-only. Schema validation, approval checks, identity checks, and Evidence Gate may block an action or conclusion; none of them may re-allow what an earlier guard denied.
- Safety boundaries fail closed: missing policy, approval, identity, or evidence coverage stops the flow instead of continuing best-effort.
- Core contains no branches for
rdk-s100,gs130w, orcamera; verify through tests and review. - No Pi Tool accepts an arbitrary command or file path; verify registered Tool schemas and command templates.
- Existing-log Camera diagnosis never starts a process; the one-shot launch probe is blocked unless policy, identity, no-existing-process, timeout, and cleanup invariants all hold.
- Every Observation references a completed Action; every Evidence references Observation and states
proves,does_not_prove, scope, and prerequisites. - Expected and Observed contexts remain separate; a product conflict prevents Profile activation.
- One empty I2C scan cannot confirm hardware damage; high-confidence hardware root cause requires the corroboration defined in
docs/MVP_DESIGN.md. - Pi process/session termination does not erase a Diagnosis; recovery by Diagnosis ID preserves history.
10. Known Gaps and Risks
- Pi Package loading, Extension API compatibility, and exact peer version still require a Technical Spike.
- Real S100 command and log formats must be recorded before Parsers can be considered reliable.
- Model-generated Evidence may fail schemas or semantic boundaries; the MVP Gate must reject invalid transitions safely.
- I2C probe approvals live in an in-memory singleton for the MVP; approval IDs are recorded in Action parameters but the approval object does not survive a Pi process restart. Recovery fails closed (blocked). Move approval state into the persisted store before the second capability slice.
- The Camera vertical slice is implemented; other capabilities and the Peripheral Profile remain target-only.
- The scripted Journey and the model-driven loop coexist for now; see ADR-0002.
11. Change Protocol
Update this document when component responsibilities, dependency direction, state ownership, public contracts, or primary runtime flows change. Update docs/MVP_DESIGN.md when MVP scope or acceptance changes. Create an ADR for a consequential, cross-cutting, persistent, or expensive-to-reverse decision with realistic alternatives.