diff --git a/CLAUDE.md b/CLAUDE.md index 3dbf488..9e70b71 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -88,7 +88,7 @@ No requirement is complete when only the happy-path demo works. Required failure - Each feature must name the student-visible journey and visible result it enables. - Preserve host key, non-root, path containment, atomic idempotency, cancellation, high-risk deny and verifier boundaries. - The consumer desktop product must not require root daemon installation, dedicated system users, containers, Capability Broker, multi-tenant services, relay, multi-Agent orchestration or a community skill registry. -- Camera/BPU may use reviewed official templates on a personal development board. GPIO/PWM/servos/motors remain unavailable until a separate safe hardware kit and acceptance suite exist. +- Camera/BPU may use reviewed official templates on a personal development board. GPIO/PWM/servos/motors remain unavailable until a separate safe hardware kit and acceptance suite exist; the `lekiwi-base` chassis pack satisfies that condition under ADR-017 (bounded discovery auto, motion always per-run human approval; all other actuators stay unavailable). - Prefer a direct implementation over an adapter/factory/registry until a second concrete implementation is required. - Project reuse is a local DIY Project Pack (`draft → verified-local → shareable`), not a six-stage enterprise publishing workflow. - Saving a work may also create a local Skill Candidate (`draft → enabled`). The Pack remains source/execution truth; the Candidate references Pack/Run/Capability and never copies code, manifests or verifiers or grants tools. Do not implement this before S3. diff --git a/docs/01-product-requirements.md b/docs/01-product-requirements.md index 278dc40..3960bce 100644 --- a/docs/01-product-requirements.md +++ b/docs/01-product-requirements.md @@ -213,7 +213,7 @@ Alpha 用于证明完整桌面垂直切片,只能说“正在构建替代产 - `CFR-023`:相同 request id 的重试不能产生重复 run;同一设备默认只有一个写运行。 - `CFR-024`:运行必须支持流式状态、超时、取消、进程树清理和部分证据保存。 - `CFR-025`:所有 starter project 必须声明可见产物和 required verifier;模型文本、stdout 的 PASS 和 exit 0 均不能单独判定成功。 -- `CFR-026`:Agent 计划需要系统级安装、刷机、网络修改或重启时不得直接执行;产品可以跳转到对应的人控维护流程。GPIO/PWM/执行器在安全工装缺失时仍硬拒绝。 +- `CFR-026`:Agent 计划需要系统级安装、刷机、网络修改或重启时不得直接执行;产品可以跳转到对应的人控维护流程。GPIO/PWM/执行器在安全工装缺失时仍硬拒绝;已声明的审核工装包提供有界探查(自动)与有界运动(人工逐次批准,ADR-017)。 - `CFR-027`:Camera/BPU 首版只使用经审核的官方 API 模板和已验证参数;任意直接硬件路径和额外 shell 参数不成为模型工具输入。 ### 8.4 DIY Project Pack diff --git a/docs/03-domain-model-and-protocol.md b/docs/03-domain-model-and-protocol.md index ace418e..b6011e7 100644 --- a/docs/03-domain-model-and-protocol.md +++ b/docs/03-domain-model-and-protocol.md @@ -122,6 +122,30 @@ inventory_delta: `targets` 是版本化枚举,不接受路径、命令或 probe ID。Host 选择实际 `ProbePlan`;Agent 不能控制 argv。盘点为 R0 只读活动,但仍受 actor/device、超时、输出大小、敏感信息清洗和审计约束。刷新产生新快照而不修改旧快照;影响 capability、identity、OS/runtime 或设备节点的 delta 必须使旧 ExecutionPlan 失效。 +### 2.2.2 FixtureDeclaration(安全工装声明) + +物理输出能力(舵机/电机总线)不由探针授予——探针对这类总线保持零交互(AT-002),VID:PID 枚举也不得推断产品命名。能力来自人工声明的工装,工装引用配件注册表中的配件包(数据,ADR-017/018;能力 ID 为通用族 `base.scan` / `base.velocity.bounded`,包只能引用不能铸造): + +```yaml +schema_version: "1.0" +fixture_id: "fix-..." +pack_id: "lekiwi-base" # 必须是代码内审核包常量 +pack_version: "1.0.0" +device_id: "dev-..." +serial_node: "/dev/ttyACM0" +kill_method: "manual 12V power switch" +orientation: "elevated-wheels-free" +declared_by: {kind: "user", id: "..."} # 仅 USER;agent 声明被模型拒绝 +declared_at: "..." +``` + +规则: + +- 声明、撤销只在人工权限面(`fixture.declare/remove`);Agent 面只可读 `fixture.list`; +- Host 仅当 `serial_node` 出现在当前快照 `peripherals.serial_nodes`(观察事实)时,把包能力以 `evidence: [{kind: "fixture", value: fixture_id}]` 叠加进快照,并写入 `/capabilities/` 观察; +- 叠加产生新内容寻址快照 → 旧 plan 失效;撤工装或刷新盘点后节点不在场 → 能力消失(fail-closed); +- 审核包是代码常量(舵机 ID、参数包络、运动学常数、断电方法、出处引证),新增包是规范评审变更,不是运行时配置。 + ### 2.3 CapabilityDescriptor ```yaml @@ -140,7 +164,7 @@ evidence: [{kind: "device_node", value: "/dev/video0"}] limitations: [] ``` -能力 ID 描述意图而非底层命令。调用方不能通过参数把一个只读能力变成任意 shell。`internal_device_resources` 只供受信插件/策略判断,不代表 run 用户获得对应节点;MVP 硬件能力必须为 `brokered`。 +能力 ID 描述意图而非底层命令。调用方不能通过参数把一个只读能力变成任意 shell。`internal_device_resources` 只供受信插件/策略判断,不代表 run 用户获得对应节点;MVP 硬件能力必须为 `brokered`。`evidence.kind` 取值包括 `probe`(探针证据)、`device_node`(设备节点)与 `fixture`(人工工装声明,§2.2.2);审核模板可以声明有界数值参数,宿主在计划前按包络校验,物化为运行源文件之一进入摘要绑定,工装绑定参数(端口/舵机 ID/包络)只能由宿主从生效工装注入。 ### 2.4 RunManifest diff --git a/docs/05-security-and-safety.md b/docs/05-security-and-safety.md index d8587d3..3f77c62 100644 --- a/docs/05-security-and-safety.md +++ b/docs/05-security-and-safety.md @@ -10,7 +10,7 @@ - RDK 不应保存生产密钥、重要个人文件或不可恢复数据; - 只导入自己信任或能审阅的源码; -- GPIO、舵机、电机等物理输出在产品明确支持前不可用; +- GPIO、舵机、电机等物理输出在产品明确支持前不可用;已支持的工装包(如 LeKiwi 底盘)也只提供有界探查与逐次审批的运动; - 烧录和系统维护在产品的独立人控流程中完成,不经过 Agent 自动执行。 最重要的边界不是“桌面产品能否做”,而是“谁发起、经过哪个权限平面”:用户可以直接操作自己的设备;Pi Agent 只能调用受控工具,用户在终端或烧录向导中的权限不会继承给 Agent。 @@ -29,7 +29,7 @@ | 假成功 | required verifier 独立判断,模型/exit/stdout 不能覆盖 | | 路径/产物逃逸 | 限定 root、realpath、拒绝链接/设备文件、摘要校验 | | 外部作品带恶意内容 | 作为 draft 导入,展示源码,拒绝系统修改和未知 binary | -| 物理动作伤害设备/人员 | GPIO/PWM/舵机/电机/继电器默认 unavailable | +| 物理动作伤害设备/人员 | GPIO/PWM/继电器等默认 unavailable;舵机/电机仅审核工装包内的有界能力,且运动恒需人工逐次批准(ADR-017) | | 图片隐私泄露 | 默认本地保存,分享前提示并清除原始敏感画面 | | 人工终端权限被 Agent 借用 | 终端/文件/烧录独立进程与会话,不注册 Pi tool,不共享确认状态 | | 烧错板型或镜像 | 读取设备身份、板型/镜像匹配、摘要校验、数据清除提示和最终用户确认 | @@ -40,10 +40,11 @@ | 等级 | Agent 示例 | Agent 默认行为 | 人工产品流程 | |---|---|---|---| -| R0 只读观察 | 系统信息、温度、USB 枚举 | 自动允许 | 可直接查看 | +| R0 只读观察 | 系统信息、温度、USB 枚举、已声明工装的配件总线探查 | 自动允许 | 可直接查看 | | R1 项目运行 | 产品目录内写代码、普通 Python 进程 | 低风险模式可自动,有限额/取消 | 可手动运行/终止 | | R2 审核模板 | USB 单帧、固定 BPU 推理 | 只允许内置模板和验证参数 | 可从项目运行 | -| R2 物理输出 | GPIO/PWM/CAN/舵机/电机 | unavailable | 当前产品也不可用 | +| R2 物理输出 | 已登记配件包内的有界运动(首个:LeKiwi 底盘;包为数据,ADR-017/018) | 审核模板 + 参数包络(含产品绝对上限),恒需人工逐次批准 | 批准后方可运行 | +| R2 物理输出(未开通) | GPIO/PWM/CAN 写、机械臂、继电器、供电 | unavailable | 当前产品也不可用 | | R3 系统变更 | apt、systemd、网络、重启 | 不直接执行;跳转人控流程 | 仅已实现的确定性流程,预览并确认 | | R4 不可逆/危险 | flash、分区、电压、频率、电源 | 硬拒绝 | 仅烧录向导开放;其他仍不可用 | @@ -162,9 +163,9 @@ Manifest 和模型不能降低风险级别。 ## 9. 物理输出能力 -GPIO、PWM、CAN 写、舵机、电机、机械臂、继电器和供电能力在当前产品中不可用。模型、Project Pack、CLI 或协议 replay 都不能绕过。 +GPIO、PWM、CAN 写、机械臂、继电器和供电能力在当前产品中不可用。舵机/电机总线中,只有已登记配件包经人工工装声明开通的有界能力可用(首个:LeKiwi 底盘,ADR-017/018;配件知识是数据:内置审核层 + 本机用户层,同模型同绝对上限);未开通部分模型、Project Pack、CLI 或协议 replay 都不能绕过。 -未来每个物理输出能力必须先具备: +每个物理输出能力开通前必须先具备: - 指定开发板、引脚、电压域和接线图; - 限流/保护工装和版本 ID; @@ -174,6 +175,8 @@ GPIO、PWM、CAN 写、舵机、电机、机械臂、继电器和供电能力在 - 正常、取消、崩溃和接错线验收; - Capability Broker 或经 ADR 证明等价的权限边界。 +LeKiwi 底盘(`lekiwi-base`)按上述清单开通的范围与残余风险见 ADR-017/018:能力只来自人工工装声明(探针保持对总线零交互),探查类(总线只读发现)能力在场即自动,运动类恒为审核模板 + 人工逐次批准,验收时底盘架空且急停(拔电池连接器)随手可及。 + ## 10. Artifact 与 Project Pack - Artifact 路径必须来自声明清单,拒绝绝对路径、`..`、symlink、设备文件和恶意 archive; @@ -221,7 +224,7 @@ Agent 遇到系统变更或烧录请求时说明自己不会直接执行,并 - timeout/cancel 不留子孙进程; - source/snapshot 变化使旧 Plan 失效; - verifier error/fail 不会变 passed; -- GPIO/舵机/电机从所有入口不可达;R3/R4 从 Agent 入口不可达; +- GPIO/PWM/继电器与未开通的舵机/电机能力从所有入口不可达;已开通工装包的运动能力只有「审核模板 + 人工逐次批准」一条路径(ADR-017);R3/R4 从 Agent 入口不可达; - Project Pack 导出不包含凭据、设备身份或绝对路径。 - 人工终端/文件/串口/烧录不存在于 Pi tool 列表,且 Agent 不能复用人控确认; - fake 烧录的板型/摘要/确认/取消/失败恢复通过,真实烧录只有受控 HIL 才能记录通过; diff --git a/docs/adrs/ADR-017-lekiwi-chassis-bounded-capability.md b/docs/adrs/ADR-017-lekiwi-chassis-bounded-capability.md new file mode 100644 index 0000000..d773499 --- /dev/null +++ b/docs/adrs/ADR-017-lekiwi-chassis-bounded-capability.md @@ -0,0 +1,42 @@ +# ADR-017:LeKiwi 底盘有界能力——审核工装声明与审核模板(消费级 Broker 等价) + +状态:Accepted +日期:2026-08-25 + +## 背景 + +ADR-006 规定硬件能力经「按 Run 授权的 Broker」暴露;ADR-012 修订后,消费级 MVP 的 Camera/BPU 可先用审核模板 + 普通非 root 用户,不引入 Broker 进程,但 **GPIO/PWM/舵机/电机、共享设备、无人值守仍必须使用 Broker 或经新 ADR 证明等价的硬件边界**。 + +用户的 S100P 接入了 LeKiwi 开源底盘(Feetech STS3215×3,速度模式,独立 12V 供电),产品需要能验收并使用它。完整 Capability Broker(SDK + 短时 socket/票据)在消费级首版成本过高;而「整类永久禁用」又使底盘永远无法验收。产品 owner 决定按 ADR-012 §5 的条件(明确硬件包、接线、参数包络、超时、安全复位)**逐项开放**,并确认两条产品规则: + +1. Agent 对板子与配件的事实探查自动发起(连接后即发起),无需审批; +2. 一切运动类操作——现在的底盘、将来的机械臂或其他配件——一律人工逐次审批。 + +## 决策 + +为 `lekiwi-base` 一项建立**审核工装声明 + 审核模板 + 逐次审批**的有界通道,并论证其在本场景下与 Broker 等价: + +1. **能力来源是工装声明,不是探针。** 探针保持对电机/舵机总线零交互(AT-002 判词不变),VID:PID 枚举不推断产品命名。人(USER actor,仅人工权限面)声明一个**代码内审核包**(`lekiwi-base@1.0.0`:舵机 ID 7/8/9、速度包络 ±0.10 m/s、±30°/s、≤3 s、运动学常量、12V 手动断电、架空姿态);宿主仅在声明的串口节点是快照**观察事实**时,把包能力以 `kind=fixture` 证据叠加进快照。未声明/节点未观察/包未审核 → 无能力(默认拒绝不变)。新增审核包属于规范评审变更,不是运行时配置。 +2. **探查与运动分级。** `base.scan.lekiwi`(R0 只读):总线 PING 与寄存器回读,零写指令;能力在场即 Agent 自动发起,用于核实配件事实(谁在线、供电电压、温度)。`base.velocity.lekiwi`(R2 设备 IO 有界):只能经审核模板以包络内参数执行,策略恒为 REQUIRE_APPROVAL,人工逐次批准,单次消费;本 ADR 同时把该能力列入默认 r2_allowlist——allowlist 只表示「可计划、需审批」,不构成执行授权。 +3. **执行通道只有审核模板。** 运动程序是评审过的一键模板(无模型代码参与):宿主先验包络 → `params.json` 与源码同进 source digest/票据绑定 → 板端程序用同一包络常量二次校验 → 运动前逐舵机确认在场与速度模式 → 到时/取消/信号即写零速 → **回读 Present_Velocity 独立确认停转**,验证器(`json.assert`/`json.range`)在宿主侧对回读证据判定。模型不能提供工装绑定参数(端口/舵机 ID/包络),也不能自批。 +4. **物理层兜底。** 工装硬性要求:验收与演示时底盘架空(轮子不接地)、急停方式为直接拔电池连接器(实测该装配无 12V 开关,2026-08-26 真机确认),连接器随手可及。进程被 SIGKILL 时舵机保持末次指令速度直至断电——该残余风险由物理工装兜底并如实记录,不由软件假装消除;无法确认清理时 `cleanup_unconfirmed` 冻结设备。 + +## 等价性论证与残余风险 + +- **代码来源受控**:触达总线的只有审核模板源码;模型生成的程序没有该能力通道(能力不在其可达集合,且模板物化不经过模型)。等价于 Broker「未声明能力不可达」在本场景的效果。 +- **参数边界三层强制**:宿主计划前、板端程序内、宿主验证器(对回读值),任一层失效不放宽另两层。 +- **授权链**:工装声明(人)→ 能力在场(观察事实)→ R2 审批(人,单次、绑 plan/设备/有效期)→ 启动时策略复评 + 票据绑定能力。模型与 external_agent 均不能决定审批。 +- **残余风险(如实声明)**:a) 执行用户本就在 `dialout` 组,OS 层不能阻止人工终端程序直接开串口——与 Camera 的 video 组同一水位,符合 ADR-012「不宣称隔离恶意代码」的消费级边界;b) SIGKILL 残转由架空 + 手动断电兜底;c) 本等价**仅覆盖单用户、单设备、个人板、人在场**的消费级场景;共享实验室、无人值守、多设备或不可信代码仍必须回到 ADR-006 Broker,本 ADR 不是其 fallback。 +- 范围锁定:仅 `lekiwi-base`。GPIO、PWM、CAN 写、机械臂、继电器、供电控制维持不可用;未来配件按同一模式另立审核包与验收,运动类一律人工逐次审批。 + +## 结果 + +优点:底盘可被产品正式验收与使用;探查自动化满足「连接即知配件」;运动保持人控;全部机制复用既有策略/审批/验证管线,无新常驻组件。 + +代价:能力开通依赖工装声明步骤(人一次声明);SIGKILL 残转风险需物理工装兜底并写入台位规范;模板参数化扩展了模板机制(有界参数 + 两相运行)。 + +## 对既有决策的影响 + +- ADR-006:Broker 仍是执行器在共享/无人值守/多设备场景的目标边界;本 ADR 是消费级单用户在场景内的等价证明,不改变其地位。 +- ADR-012 §5:本 ADR 即其「逐项开放」的首次执行;消费级约束中「GPIO/PWM/舵机/电机在安全硬件套件与验收套件存在前不可用」对 `lekiwi-base` 而言条件已满足,其余维持。 +- docs/05 §9 清单:lekiwi-base 的七项前置(板/引脚与接线、保护工装与版本、参数上限、timeout/finalizer/独立安全终态、人工急停、四类验收、等价权限边界)由本 ADR、`HIL_LAB_SPEC` LeKiwi 工装节、AT-032/AT-033 与审核包常量共同满足。 diff --git a/docs/adrs/ADR-018-accessory-knowledge-as-data.md b/docs/adrs/ADR-018-accessory-knowledge-as-data.md new file mode 100644 index 0000000..763a7c6 --- /dev/null +++ b/docs/adrs/ADR-018-accessory-knowledge-as-data.md @@ -0,0 +1,34 @@ +# ADR-018:配件知识数据化——机制是代码,配件是数据 + +状态:Accepted +日期:2026-08-26 + +## 背景 + +ADR-017 打开了 LeKiwi 底盘的有界能力,但配件知识以 Python 常量形式写死在 `rdk_agent_core.fixtures.REVIEWED_PACKS`,能力 ID 与模板名携带产品名(`base.scan.lekiwi`、`lekiwi-move`)。RDK 的配件本质是**可更换的**:同一块板今天接 LeKiwi,明天可以接别的底盘或机械臂。产品应当具备检查配件信息、操作配件、推荐潜在配件、记住连接过的配件这四种**能力**,而具体配件的知识不应成为产品代码的一部分。 + +## 决策 + +1. **配件注册表是数据,不是代码。** `AccessoryPack`(舵机表、运动包络、运动学、总线协议、需求事实、出处)以 JSON 存放:内置层随产品发布(`rdk_agent_host/data/accessory-packs/`),本机层存于状态目录(`accessory-packs/`)。两层共用同一 pydantic 模型校验;"审核"发生在内置数据入库评审,形态从代码变为数据。 +2. **能力族是受控集合,配件只能引用不能铸造。** `base.scan`(R0 探查)与 `base.velocity.bounded`(R2 有界运动)由核心建模(`KNOWN_PACK_CAPABILITIES`);包数据引用这些 ID,任何包不能铸造新能力。 +3. **协议驱动与配件解耦。** 模板内联的 Feetech STS 驱动是协议层代码,服务一切 `bus_protocol=feetech-sts` 的包;轮角、轮径、包络等配件事实由宿主从声明的包注入 `params.json`,程序内不再携带任何配件常数。 +4. **安全线不因数据化放宽**(修订 ADR-017 的实现方式,机制不变): + - 包络有**模型绝对上限**(`MotionEnvelope` 的 `le=`),内置包与用户包同等受限; + - 每个包必须有出处(`source`:厂商数据/人工实测/人工填写); + - 能力仍只经**人工工装声明**(观察事实门控)+ 策略默认拒绝; + - 运动仍为 R2,逐次人工审批、单次消费; + - VID:PID 永不推断产品身份或关联配件包(AT-002 不变); + - 用户包不得覆盖内置包 ID。 +5. **用户自建包是产品能力的一部分。** 个人用户接入注册表之外的配件时,填写包数据(含出处)并经工装声明与逐次审批即可使用;残余风险水位与"用户运行自己的代码"同级,由绝对上限、声明、审批三层控制,并在能力限制文本中展示出处。共享/无人值守场景不适用该放宽(见 ADR-006/012 边界)。 + +## 结果 + +优点:接入新配件=新增一份数据记录,无需改代码;能力命名通用,与仿真侧 `base.velocity.bounded` 对齐;注册表天然支撑推荐(设备事实 × 包需求)与记忆(工装/台账持久化)。 + +代价:内置包数据需要与代码同等级别的评审纪律(契约测试校验模型一致性);用户包的包络正确性依赖用户如实填写——产品上限是最后防线,不是正确性保证。 + +## 对既有决策的影响 + +- ADR-017 的目标与安全结论不变;其"审核包是代码常量"的实现方式由本 ADR 替换; +- ADR-012 §5"逐项开放"继续适用:每一类新物理输出(位置模式、机械臂等)仍需独立的包数据、工装前置与验收; +- AT-032/033 成为"配件包有界能力"的通用验收套件,LeKiwi 是首个实例;新增 AT-038 覆盖注册表与数据边界。 diff --git a/docs/testing/ACCEPTANCE_TESTS.md b/docs/testing/ACCEPTANCE_TESTS.md index f6df416..1ef72ef 100644 --- a/docs/testing/ACCEPTANCE_TESTS.md +++ b/docs/testing/ACCEPTANCE_TESTS.md @@ -334,6 +334,36 @@ 证据与代码)。新仿真系统的验收自 AT-034 起编号(AT-032/033 为底盘能力验收), 规范见 `docs/adrs/ADR-019-rdk-sim-v2-circuit-level-device-design-simulation.md`。 +## AT-032 配件总线探查(有界、零写) `[MVP]` + +对应:ADR-017/018(探查类能力在场即自动;配件知识为数据,首个实例 lekiwi-base)、CFR-026/027、SEC-005。AT-002 判词不变:盘点探针对舵机总线零交互——探查是经审核模板的运行,不是盘点。 + +前置:真机段需已登记的配件工装(当前实例:`lekiwi-base`)、串口节点在快照中可观察、底盘 12V 供电。 + +步骤: + +1. **工装门控(可自动化)**:无工装声明时 `base-scan` 不可运行(输入拒绝);声明的串口节点不在快照观察事实中时能力不激活;非审核包/版本不符拒绝;非 USER actor 声明拒绝(协议面 agent 调用 `fixture.declare` → PROTOCOL_VIOLATION);撤销工装后能力立即消失; +2. **探查运行(真机)**:工装在场后以 agent 角色自动运行 `base-scan`;产物 `bus_scan.json` 记录每个应答舵机的型号/电压/温度/位置/模式;验证器断言 `ok=true` 且 `write_commands_sent=0`; +3. **失败语义(真机)**:关闭 12V 重复扫描 → 运行失败、退出码区分「全无应答」与「部分声明舵机缺失」,错误语义可读(供电未开),不降级断言。 + +通过:门控各负例全部拒绝;在场探查自动完成且零写指令(产物自证 + 审核源码核对);12V 未开的失败被如实记录为失败而非 unknown/passed。 + +## AT-033 配件有界运动(逐次审批 + 安全终态) `[MVP]` + +对应:ADR-017/018、CFR-024/025/026/027、SEC-005/006。 + +前置:AT-032 通过;底盘**架空(轮子不接地)**、急停=拔电池连接器(该装配无 12V 开关)且随手可及、现场有人。 + +步骤: + +1. **包络三层(可自动化)**:越界参数(速度/时长超包络)在宿主计划前拒绝;篡改 `params.json` 越界值时板端程序二次拒绝;验证器对回读值做 `json.range` 判定;工装绑定参数(端口/舵机 ID/包络)由用户或模型提供时被拒; +2. **审批链(可自动化)**:运动模板计划产生 `approval_required`;无批准启动被拒;模型/external_agent 自批被拒(APPROVAL_FORGERY_BLOCKED);人工批准后启动成功且审批单次消费——同一审批第二次启动被拒;不同设备/过期审批不可用; +3. **正常运动(真机)**:`vx=0.05 m/s、duration=1000ms` 等小包络参数批准执行:轮按时长转动、到时自停;`motion.json` 记录指令值、各轮 raw、终速回读;`stop_confirmed=true`、`max_abs_final_velocity` 在容差内;验证器全过; +4. **取消与超时(真机)**:运动中途 `run.cancel` → 轮立即停转、`cleanup=confirmed`;构造超时长参数被包络拒绝(不由超时兜底); +5. **失败与残余风险记录(真机)**:12V 未开时运动运行失败且未产生运动(运动前逐舵机在场检查);进程在运动中被杀的残转风险由工装物理防护兜底,证据记录该场景的处置(断电演练一次)。 + +通过:三层包络各自独立拦截;审批链负例全拒、正例单次消费;正常/取消路径轮都回到零速且由回读独立确认(不信任程序自报);失败语义如实;真机证据入 `docs/testing/evidence/LEKIWI-CHASSIS.md`,未架空/无人值守时不运行并记 `blocked`。 + ## AT-034 2WD 小车电路仿真判据 golden `[MVP]` 对应:ADR-019 §3.1/§5,CFR-025。 @@ -370,3 +400,16 @@ 通过:虚拟板 DeviceSnapshot 与真快照字段同构(board/OS/资源/BPU/USB/video,available 能力均有 observed observation 覆盖),model 字符串无 NUL 且 provenance 可溯;mock 接口内外携带"标注 mock:结果不计为真实验证"limitation;report 按 仿真/真机/未知 分列,无出身 run 归未知;不存在任何把仿真结果升级为真机验证的路径。 +## AT-038 配件注册表与数据边界 `[MVP]` + +对应:ADR-018、AT-002 判词、CFR-010/014。 + +步骤: + +1. **内置注册表(可自动化)**:内置包为数据文件且经同一 `AccessoryPack` 模型校验(契约测试);缺出处、未知能力族、越绝对上限的内置文件加载即失败关闭; +2. **用户包边界(可自动化)**:用户包与内置包同模型同上限——包络越上限、缺出处、未知能力族在模型层拒绝;用户包不得覆盖内置包 ID;内置包不可被本机删除; +3. **产品身份不推断(可自动化)**:快照 VID:PID/串口事实不产生任何包关联或产品命名(AT-002 判词);推荐只输出「可声明/缺什么」,能力仅经人工声明出现; +4. **记忆与推荐(可自动化)**:连接过的配件事实(VID:PID/串口)入账册并可跨盘点查询;设备事实满足包需求时推荐为可声明状态,声明后为已激活,撤销后回落。 + +通过:各负例全部拒绝;注册表数据与模型零漂移(契约测试);推荐与账册只含事实不含推断。 + diff --git a/docs/testing/CURRENT_HARDWARE_BASELINE.md b/docs/testing/CURRENT_HARDWARE_BASELINE.md index 7892d1d..4aedeff 100644 --- a/docs/testing/CURRENT_HARDWARE_BASELINE.md +++ b/docs/testing/CURRENT_HARDWARE_BASELINE.md @@ -1,8 +1,8 @@ -# 当前硬件基线:RDK S100P + LeKiwi 底盘/相机(舵机未上电) +# 当前硬件基线:RDK S100P + LeKiwi 底盘/相机 -状态:Baseline v0.6 -记录日期:2026-08-12(2026-08-25 修订:按 probe_set 1.2.0 真机盘点证据更新外设现状) -事实来源:用户提供的内容属于未验证 hint;板型、版本与外设字段以 Inventory Engine 只读盘点(含证据)为准。外设现状证据:`docs/testing/evidence/PROBE-SET-1.2.0-ACCESSORY.md`(快照 `sha256:83b16d45…`) +状态:Baseline v0.7 +记录日期:2026-08-12(2026-08-25 修订:按 probe_set 1.2.0 真机盘点证据更新外设现状;ADR-017 开通 `lekiwi-base` 有界能力) +事实来源:用户提供的内容属于未验证 hint;板型、版本与外设字段以 Inventory Engine 只读盘点(含证据)为准。外设现状证据:`docs/testing/evidence/PROBE-SET-1.2.0-ACCESSORY.md`(快照 `sha256:83b16d45…`);底盘能力开通依据 `docs/adrs/ADR-017-lekiwi-chassis-bounded-capability.md`;配件知识数据化(注册表/用户包/通用能力族)见 `docs/adrs/ADR-018-accessory-knowledge-as-data.md`。 ## 1. 已确认事实 @@ -13,7 +13,7 @@ | DeviceTransport | `direct + ssh-stdio` | 已注册并核验 host key | | 相机 | USB 相机 `1e45:0209` 已连接 | 探针实测;`camera.snapshot.usb=available`(真机快照链路见 AT-013) | | 底盘 | LeKiwi 底盘驱动板 `1a86:55d3`(USB-CDC → `/dev/ttyACM0`)已连接 | 探针实测(`peripherals.usb_devices` / `serial_nodes`);**只读枚举事实,非「底盘可用」声明** | -| 舵机 | LeKiwi 三舵机 12V 未上电、PING 无应答 | 未实测;无安全工装前保持 unavailable | +| 舵机 | LeKiwi 三轮舵机 STS3215(ID 7/8/9,速度模式,独立 12V 供电) | 人工工装声明 + 注册表数据包 `lekiwi-base@1.0.0`(ADR-017/018);是否应答以探查模板实测为准 | | GPIO 工装 | 未提供 | 视为没有,相关 capability 禁用 | | RDK OS | 4.0.5-Beta | 探针实测 | | Kernel | 6.1.158-rt58-DR-…(aarch64) | 探针实测 | @@ -31,11 +31,13 @@ - run workspace、stdout/stderr、JSON/file artifact、verifier; - 超时、取消、进程树清理和安全断链恢复; - 使用固定摘要静态输入的 S100P 兼容 BPU 官方/受审核样例; -- USB 相机真机快照(AT-013,相机已连接)。 +- USB 相机真机快照(AT-013,相机已连接); +- LeKiwi 底盘有界能力(ADR-017,AT-032/AT-033):已声明 `lekiwi-base` 工装时的总线只读探查(自动),以及架空姿态、急停=拔电池连接器(该装配无 12V 开关)、人工逐次批准下的有界速度运动; ## 3. 当前禁止或阻塞 -- 舵机、PWM、电机、机械臂、继电器动作:舵机 12V 未上电且无安全工装,禁止(含对电机/舵机总线的 PING/写指令,探针保持零交互); +- PWM、机械臂、继电器、供电控制动作:无安全工装,禁止; +- 舵机/电机总线:仅 `lekiwi-base` 审核包范围内按 ADR-017 开放(探查零写、运动逐次审批、架空 + 急停拔电池连接器);包外舵机(如机械臂 ID 1–6)、位置模式、越包络参数一律拒绝;盘点探针对总线保持零交互(AT-002); - GPIO loopback:无工装,禁止; - MIPI/GMSL Camera:无相机和扩展工装,禁止; - Flash、bootloader/partition、电压/频率/thermal limit、远程电源控制:始终禁止; diff --git a/docs/testing/HIL_LAB_SPEC.md b/docs/testing/HIL_LAB_SPEC.md index d5d4866..bc37fec 100644 --- a/docs/testing/HIL_LAB_SPEC.md +++ b/docs/testing/HIL_LAB_SPEC.md @@ -1,8 +1,8 @@ # RDK Agent 硬件在环实验室规范 -状态:Baseline v0.7,当前台位适用 S100P 只读/BPU/USB Camera 子集 +状态:Baseline v0.8,当前台位适用 S100P 只读/BPU/USB Camera/LeKiwi 底盘有界子集 -> GPIO/舵机/执行器和企业设备池不属于当前台位。日常只执行 ADR-012/013、CAT-001–006 和 `CURRENT_HARDWARE_BASELINE.md` 允许的低风险真机项目。CAT-010 真实烧录必须使用单独标记的可恢复测试板和人工值守流程,不能由 Agent 或普通 CI 在当前工作板上执行。 +> GPIO、机械臂等执行器和企业设备池不属于当前台位。LeKiwi 底盘仅按 §5.1 工装与 ADR-017 的有界范围进入台位(探查零写、运动逐次审批)。日常只执行 ADR-012/013、CAT-001–006 和 `CURRENT_HARDWARE_BASELINE.md` 允许的低风险真机项目。CAT-010 真实烧录必须使用单独标记的可恢复测试板和人工值守流程,不能由 Agent 或普通 CI 在当前工作板上执行。 ## 1. 目的 @@ -14,9 +14,9 @@ - RDK S100P 裸板(记录资产 ID,报告中只存序列号 hash); - 非端侧主机经网线 direct 连接,Host 到设备链路可控断开; -- 当前无相机、舵机和 GPIO 工装;USB 摄像头已购买但尚未到货。 +- 相机:USB 相机已连接(`1e45:0209`);底盘:LeKiwi 已连接并按 §5A 工装进入台位;无 GPIO 工装。 -稳定电源/散热、串口恢复通道、可控电源和物理标签的实际情况尚未确认,首次 HIL 盘点时记录;缺少恢复前置时,相应故障注入用例必须 blocked,不能假定具备。USB 摄像头到货后,台位增加 USB 摄像头、固定光照和测试卡。用于 BPU 的固定摘要模型与静态输入不依赖摄像头,可先准备。带保护的 GPIO loopback 小板仅属于 Preview;舵机不属于当前台位。 +稳定电源/散热、串口恢复通道、可控电源和物理标签的实际情况尚未确认,首次 HIL 盘点时记录;缺少恢复前置时,相应故障注入用例必须 blocked,不能假定具备。USB 相机与 LeKiwi 底盘已接入台位(分别见 §5、§5A)。用于 BPU 的固定摘要模型与静态输入不依赖摄像头,可先准备。带保护的 GPIO loopback 小板仅属于 Preview;机械臂等其他执行器不属于当前台位。 ## 3. 设备镜像与基线 @@ -52,6 +52,19 @@ S5 烧录 HIL 另需:专用可恢复设备、稳定电源、已验证串口/ - 隐私区域不放人脸/屏幕/敏感纸张; - cancellation 后通过独立 reopen 测试确认资源释放。 +## 5A. LeKiwi 底盘工装(ADR-017) + +独立风险评估与硬件安全控制(满足 §9 对新增项目的要求): + +- 工装声明:测试前必须由真人经人工权限面登记 `lekiwi-base` 工装(`rdkctl fixture declare`),且串口节点在盘点快照中可观察;未声明 → 能力不存在; +- 姿态:底盘必须架空(轮子悬空、不接地、不接触人或物); +- 供电:舵机走独立 12V;该装配无 12V 开关,急停=拔电池连接器,连接器必须随手可及;断电演练在首次运动验收后排期执行; +- 参数包络:线速度 ±0.10 m/s、角速度 ±30°/s、单次时长 ≤3 s(审核包常量;越界在宿主、板端、验证器三层拒绝); +- 每次运动前人工批准(单次消费);同一批准不得复用; +- 探查类(总线只读发现)无需批准,但零写指令由审核源码与产物自证; +- 残余风险如实记录:进程被强杀时轮保持末次指令速度直至 12V 断电,由架空 + 手动断电兜底;不声称软件能消除该风险; +- 测试后门禁补充:确认三轮终速回读为零、无残转、舵机温度无异常上升;无法确认即 `cleanup_unconfirmed` 冻结。 + ## 6. BPU 工装/数据 - 模型、输入、标签、预期输出均记录 SHA-256 和来源许可证; @@ -83,7 +96,7 @@ S5 烧录 HIL 另需:专用可恢复设备、稳定电源、已验证串口/ ## 9. 人工安全与禁止项 -自动 HIL 永不:刷机、改 bootloader/partition、改电压/频率/thermal limit、远程切主电源、驱动电机/机械臂/继电器负载、操作未评审 CAN 总线、热插拔 MIPI、短接输出或电源引脚。若未来增加任何项目,必须独立风险评估、硬件安全控制和新版规范,不得靠普通 run approval 临时开放。 +自动 HIL 永不:刷机、改 bootloader/partition、改电压/频率/thermal limit、远程切主电源、驱动 §5A 范围外的电机/机械臂/继电器负载、操作未评审 CAN 总线、热插拔 MIPI、短接输出或电源引脚。LeKiwi 底盘有界运动仅按 §5A 工装与逐次人工批准执行。若未来再增加任何项目,必须独立风险评估、硬件安全控制和新版规范,不得靠普通 run approval 临时开放。 ## 10. 故障处理 diff --git a/docs/testing/TRACEABILITY.md b/docs/testing/TRACEABILITY.md index 9030ab0..cf3338a 100644 --- a/docs/testing/TRACEABILITY.md +++ b/docs/testing/TRACEABILITY.md @@ -18,6 +18,7 @@ | CSEC-009–010 | CAT-009/010 | S1/S5/S6 | | CSEC-011–012 | CAT-006A/006B/009 | S1/S6 | | CNFR-001–003 | CAT-001/002/006 可用性研究 | S1/S3 | +| CFR-026/027(工装化执行器,ADR-017) | AT-032/AT-033;复用 AT-002/009/010 | S3 | | CNFR-004–010 | 自动化/真机/Pi 升级契约 | S0–S3 | | CNFR-011–012 | CAT-011/012 | S6 | | CNFR-013–014 | CAT-006A/006B | S1/S3 | @@ -62,6 +63,9 @@ M0 验收以 `docs/06` §4.3 出口门禁与正式 AT 编号的 Fake 变体为 | AT-015/016 | ScriptedModel 闭环 + 工具/CLI 同服务等价 | `packages/rdk-agent-pi/test/slice.test.ts` | | AT-021–025 | Fake 变体通过(AT-023 自动 compaction 真机段除外,M1 补) | `TestAT021ToolSurface`…`TestAT025CredentialPrivacy`、TS slice | | AT-028–031(已迁出) | 旧仿真系统(ADR-016)整体迁至 `rdk-sim-webots-legacy` 归档;新仿真验收见 ADR-019(AT-034+) | 归档仓库 `tests/` | +| ADR-017 / AT-032–033 | 配件包有界能力(首个实例 LeKiwi):工装声明(人审、观察节点门控、撤销即失效)+ 有界模板(探查自动、运动逐次审批、单次消费)+ 三层包络 + 安全终态回读验证 | `test_core_fixtures.py`、`test_host_fixtures_templates.py`;真机证据 `docs/testing/evidence/LEKIWI-CHASSIS.md` | +| ADR-018 / AT-038 | 配件知识数据化:内置/用户双层注册表(同模型、绝对上限、出处必填、不覆盖内置)+ 通用能力族(`base.scan`/`base.velocity.bounded`)+ 账册与推荐 | `test_host_accessory_registry.py`、契约测试 | + ## SIM-R1 虚拟 RDK 仿真切片实现追踪(2026-08-26) @@ -77,6 +81,7 @@ M0 验收以 `docs/06` §4.3 出口门禁与正式 AT 编号的 Fake 变体为 独立测试复测(2026-08-27):AT-034..037 **全部通过**,753 tests 全绿、core 分支覆盖 96.27%;D1–D4 修复核验无回归。证据:`docs/testing/evidence/sim-r1/SIM-R1-TEST-REPORT.md`。 + ## 功能需求 | 需求 | 主要验收 | 备注 | @@ -125,8 +130,8 @@ M0 验收以 `docs/06` §4.3 出口门禁与正式 AT 编号的 Fake 变体为 | SEC-002 | AT-005 | | SEC-003 | AT-001, AT-005, AT-008 | | SEC-004 | AT-009 | -| SEC-005 | AT-009, AT-020 | -| SEC-006 | AT-006, AT-013, AT-020 | +| SEC-005 | AT-009, AT-020, AT-032, AT-033 | +| SEC-006 | AT-006, AT-013, AT-020, AT-033 | | SEC-007 | AT-011–012 | | SEC-008 | AT-009, AT-017, security suite | | SEC-009 | AT-007–008, AT-011 | @@ -138,4 +143,4 @@ M0 验收以 `docs/06` §4.3 出口门禁与正式 AT 编号的 Fake 变体为 ## MVP 门禁覆盖 -MVP 必须通过 AT-001 至 AT-016 和 AT-021 至 AT-026 中所有标注 `[MVP]` 的用例,包括 S100P 静态输入真实 BPU 推理(AT-014)和 USB 摄像头到货后的真实相机链路(AT-013)。摄像头到货前,AT-013 以 `blocked` 且 `reason_code=external_dependency` 记录,不阻塞 M0–M3 或 M4a 非相机工程,但不得据此宣布完整 MVP。AT-017–020、AT-027 是 Preview 门禁。当前无舵机,它不属于本地门禁;若 GPIO 工装尚未完成,AT-020 不影响 MVP,但 GPIO capability 必须保持不可用/拒绝,不能以 mock 声称支持。 +MVP 必须通过 AT-001 至 AT-016 和 AT-021 至 AT-026 中所有标注 `[MVP]` 的用例,包括 S100P 静态输入真实 BPU 推理(AT-014)和 USB 摄像头到货后的真实相机链路(AT-013)。摄像头到货前,AT-013 以 `blocked` 且 `reason_code=external_dependency` 记录,不阻塞 M0–M3 或 M4a 非相机工程,但不得据此宣布完整 MVP。AT-017–020、AT-027 是 Preview 门禁。GPIO 工装若未完成,AT-020 不影响 MVP,但 GPIO capability 必须保持不可用/拒绝,不能以 mock 声称支持。LeKiwi 底盘的有界能力(ADR-017)由 AT-032/AT-033 验收:fake 半区随门禁常跑,真机段需工装在场(架空 + 12V 手动断电)才记录 `passed`,否则 `blocked`。 diff --git a/docs/testing/evidence/LEKIWI-CHASSIS.md b/docs/testing/evidence/LEKIWI-CHASSIS.md new file mode 100644 index 0000000..d0b10ab --- /dev/null +++ b/docs/testing/evidence/LEKIWI-CHASSIS.md @@ -0,0 +1,56 @@ +# LeKiwi 底盘有界能力 真机验收证据(ADR-017 / AT-032 / AT-033) + +状态:**验收通过**(机制 + 真总线全链路;断电演练按用户决定记 `not_run`,留待下次) +日期:2026-08-25 → 2026-08-26 + +> 2026-08-26 追记:ADR-018 配件知识数据化(注册表/通用能力族/账册/推荐)已合入本分支(`5ce136e`、`3986031`),机制半区门禁全绿。真机复跑(验证纯数据驱动链路复现 16/16)因板子链路中断暂未执行,列为本证据的唯一未决项。 +分支/提交:`codex/lekiwi-chassis`(worktree /tmp/rdk-lekiwi,rebase 于 b548dab 之上) +设备:S100P `dev-a8c54ad11e5d41c2`(sunrise@192.168.127.10,en8 直连);状态目录 `/tmp/rdk-s1c-gui-state` +驱动:`scripts/drive_lekiwi_hil.py`(幂等:清场旧工装 + 对账僵尸 run,可重复执行) +工件:本目录 `bus_scan.json`(run-f702545f43fb3a0e)、`motion.json`(run-347217eda9263fa6)、`hil-steps.json` + +## 1. 物理前置与事实(含验收中的事实修正) + +- 底盘架空(用户现场确认)、急停方式=**拔电池连接器**——实测该装配**没有 12V 开关**(早期记录"12V 手动开关"有误,已按事实修正:fixtures/ADR-017/AT-033/HIL §5A/基线)。 +- LeKiwi 驱动板 `1a86:55d3` → `/dev/ttyACM0`(sysfs 核对无误),相机 `1e45:0209` 同在场。 +- 底盘电池曾完全无电 → 舵机总线静默 + 板子供电塌陷重启各一次;充电后恢复。 + +## 2. 通过项(全部经生产路径:AgentApplicationService + SSH connector + 板上 UserProcessBackend) + +| 项 | 结果 | +|---|---| +| Agent 面调 `fixture.declare` | 拒绝(仅人工面) | +| 工装声明/撤销/再声明 | 能力随声明出现、随撤销消失 | +| 探查模板 `lekiwi-scan` | **passed**:7/8/9 全应答,型号 777、电压 11.4V、温度 33–35°C、速度模式、静止速度回读 0、`write_commands_sent=0` 自证 | +| 包络越界 `vx=9.9` | 宿主计划前拒绝 | +| 运动模板无批准/伪造批准 | 均拒绝;人工批准后启动;审批单次消费 | +| **有界运动 `lekiwi-move`** | **passed**:指令 [-565,0,+565] raw(vx=0.05 m/s)→ 用户目击轮子转约 1s → 到时自停 → 6 次采样收敛、终速三轮全 0、`stop_confirmed=true`(run-347217eda9263fa6) | +| 运动中途取消 | 实际运动中 `run.cancel` 落地:`cancelled` + cleanup=confirmed | + +## 3. 验收中揪出并修复的缺陷(随本切片提交) + +1. **Feetech 状态帧解析错误(真机决定性证据)**:STS 的 LEN 把 ERR 与 CHK 都算在内,原解析把 CHK 当长度外字节,所有真实应答被判"校验失败"。逐字节证据:ID 7 每次 PING 都回 `07 02 00 f6`(~(7+2+0)=0xf6,合法应答帧)。修正后读/写/停止全部受益。 +2. **STS PING 应答不带型号**(LEN=2 的裸 ACK)→ ping 返回 0,型号改从 REG_MODEL 读(777)。 +3. **串口未拉 DTR/RTS**:pyserial 默认拉高,裸 termios 不拉;部分 USB-CDC 适配器用其使能收发器(本例最终不是根因,但保留修正)。 +4. **停止确认单次采样不稳**:半双工读回偶发解析毛刺(-30k 级假值,超出包络物理上限 ~1400 raw)。改为 6 次采样、连续两次全在容差内才确认;超 4096 的值按毛刺重采。静止回读恒为 0 证明编码为标准补码。 +5. **审批消费早于租约检查**:写租约冲突会白烧单次人工审批 → 租约检查前置(回归测试)。 +6. **宿主侧僵尸租约**:宿主在等待窗后退出留非终态记录 → 驱动脚本启动前经 `run_status` 对账;产品级自动对账列为后续。 + +## 4. Not run / 后续 + +| 项 | 状态 | +|---|---| +| 断电演练(运动途中拔电池) | `not_run`(用户决定下次做);预期行为:总线读失败 → 程序退出码 4 → run fail-closed;舵机失电即自由态 | +| GUI:设备卡渲染 `peripherals`、模板参数表单 | 未做(后续切片) | +| 产品级模板运行宿主中断自动对账 | 未做 | + +## 5. 残余风险(如实记录) + +- 进程被 SIGKILL 时轮保持末次指令速度直至断电——由架空 + 拔电池连接器兜底(ADR-017),软件不假装消除。 +- 执行用户在 `dialout` 组,OS 层不阻止人工终端直接开串口——与 camera/video 组同水位(不宣称恶意代码隔离)。 + +## 6. 环境事故记录(不影响验收结论) + +- `/tmp/rdk-s1c-gui-state/known_hosts` 曾丢失 → 按注册指纹核验(一致)后重建; +- macOS 对 Documents 目录访问权限中途被系统回收(全树 EPERM),git 提交短暂受阻;已做全量 tar 备份(/tmp/rdk-lekiwi-backup-*.tar.gz); +- 板 RTC 每次断电重置(宿主 `_host_stamp` 已规避新鲜度判定)。 diff --git a/docs/testing/evidence/lekiwi-chassis/bus_scan.json b/docs/testing/evidence/lekiwi-chassis/bus_scan.json new file mode 100644 index 0000000..f9d313b --- /dev/null +++ b/docs/testing/evidence/lekiwi-chassis/bus_scan.json @@ -0,0 +1,66 @@ +{ + "ok": true, + "port": "/dev/ttyACM0", + "write_commands_sent": 0, + "declared_servo_ids": [ + 7, + 8, + 9 + ], + "declared_missing": [], + "responding": [ + 7, + 8, + 9 + ], + "servos": { + "7": { + "model": 777, + "present": true, + "operating_mode": 1, + "position": 3012, + "velocity_raw": 0, + "voltage_v": 11.4, + "temperature_c": 33 + }, + "8": { + "model": 777, + "present": true, + "operating_mode": 1, + "position": 170, + "velocity_raw": 0, + "voltage_v": 11.4, + "temperature_c": 33 + }, + "9": { + "model": 777, + "present": true, + "operating_mode": 1, + "position": 2009, + "velocity_raw": 0, + "voltage_v": 11.4, + "temperature_c": 35 + } + }, + "probe_log": [ + { + "id": 7, + "model": 0, + "rx_bytes": 6, + "hex_tail": "ffff070200f6" + }, + { + "id": 8, + "model": 0, + "rx_bytes": 6, + "hex_tail": "007283ffff07030021d4ffff080200f5" + }, + { + "id": 9, + "model": 0, + "rx_bytes": 6, + "hex_tail": "007282ffff08030021d3ffff090200f4" + } + ], + "baud_sweep": {} +} \ No newline at end of file diff --git a/docs/testing/evidence/lekiwi-chassis/hil-steps.json b/docs/testing/evidence/lekiwi-chassis/hil-steps.json new file mode 100644 index 0000000..9808b97 --- /dev/null +++ b/docs/testing/evidence/lekiwi-chassis/hil-steps.json @@ -0,0 +1,183 @@ +{ + "at": [ + "AT-032", + "AT-033" + ], + "adr": "ADR-017", + "device": "dev-a8c54ad11e5d41c2", + "host": "sunrise@192.168.127.10", + "state_dir": "/tmp/rdk-s1c-gui-state", + "recorded_at": "2026-08-26T03:32:41.691388+00:00", + "steps": [ + { + "step": "fixture-leftover-removed", + "fixture_id": "fix-15737bebab6e465a" + }, + { + "step": "agent-fixture-declare-refused", + "ok": true, + "error": { + "code": "RDK-PROTO-001", + "message": "unknown method 'fixture.declare'", + "retryable": false, + "details": null + } + }, + { + "step": "inventory-refresh", + "ok": true, + "capabilities": [ + "system.info", + "bpu.inference.static", + "can.enumerate", + "serial.enumerate", + "usb.enumerate", + "camera.snapshot.usb" + ] + }, + { + "step": "fixture-declare", + "ok": true, + "fixture_id": "fix-d1e31f002f75499b", + "activated": true + }, + { + "step": "capabilities-after-fixture", + "ok": true, + "capabilities": [ + "system.info", + "bpu.inference.static", + "can.enumerate", + "serial.enumerate", + "usb.enumerate", + "camera.snapshot.usb", + "base.scan.lekiwi", + "base.velocity.lekiwi" + ] + }, + { + "step": "template-list", + "ok": true, + "lekiwi_scan": { + "name": "lekiwi-scan", + "title": "底盘探查(LeKiwi)", + "description": "只读探查底盘舵机总线:谁在线、电压、温度、模式(零写指令)。需要已登记的 lekiwi-base 工装。", + "requires": [ + "base.scan.lekiwi" + ], + "missing": [], + "runnable": true, + "fixture_pack": "lekiwi-base", + "parameters": [] + }, + "lekiwi_move": { + "name": "lekiwi-move", + "title": "底盘微动(LeKiwi)", + "description": "按包络限时移动底盘(全向速度模式),到时自动停止并回读确认。每次运行需人工批准;验收时轮子必须架空。", + "requires": [ + "base.velocity.lekiwi" + ], + "missing": [], + "runnable": true, + "fixture_pack": "lekiwi-base", + "parameters": [ + { + "name": "vx", + "unit": "m/s", + "min": -0.1, + "max": 0.1, + "description": "前后速度(正=前)" + }, + { + "name": "vy", + "unit": "m/s", + "min": -0.1, + "max": 0.1, + "description": "横移速度(正=左)" + }, + { + "name": "omega_deg_s", + "unit": "deg/s", + "min": -30.0, + "max": 30.0, + "description": "旋转速度(正=逆时针)" + }, + { + "name": "duration_ms", + "unit": "ms", + "min": 100.0, + "max": 3000.0, + "description": "运动时长,到时自动停" + } + ] + } + }, + { + "step": "scan-run", + "ok": true, + "state": "succeeded", + "outcome": "passed", + "cleanup": "confirmed", + "run_id": "run-f702545f43fb3a0e" + }, + { + "step": "envelope-rejected", + "ok": true, + "error": { + "code": "RDK-INV-001", + "message": "parameter vx=9.9 outside envelope [-0.1, 0.1] m/s", + "retryable": false, + "details": null + } + }, + { + "step": "motion-gated", + "ok": true, + "status": "approval_required", + "approval_id": "appr-77196de023534bc6", + "plan_id": "sha256:16b09813d3dfd75b56ace1715305f7efb368839491621b170eb9064c4424cb5d" + }, + { + "step": "bogus-approval-refused", + "ok": true + }, + { + "step": "approval-decided", + "ok": true + }, + { + "step": "motion-run", + "ok": true, + "state": "succeeded", + "outcome": "passed", + "run_id": "run-347217eda9263fa6" + }, + { + "step": "approval-single-use", + "ok": true + }, + { + "step": "motion-cancelled", + "ok": true, + "run_id": "run-8005dddf9d6a9780", + "state_after_cancel": "cancelled", + "cleanup": "confirmed" + }, + { + "step": "fixture-remove", + "ok": true, + "capabilities": [ + "system.info", + "bpu.inference.static", + "can.enumerate", + "serial.enumerate", + "usb.enumerate", + "camera.snapshot.usb" + ] + }, + { + "step": "fixture-redeclare", + "ok": true + } + ] +} \ No newline at end of file diff --git a/docs/testing/evidence/lekiwi-chassis/motion.json b/docs/testing/evidence/lekiwi-chassis/motion.json new file mode 100644 index 0000000..50e7013 --- /dev/null +++ b/docs/testing/evidence/lekiwi-chassis/motion.json @@ -0,0 +1,65 @@ +{ + "ok": true, + "port": "/dev/ttyACM0", + "commanded": { + "vx": 0.05, + "vy": 0.0, + "omega_deg_s": 0.0, + "duration_ms": 1000 + }, + "envelope": { + "max_linear_m_s": 0.1, + "max_angular_deg_s": 30.0, + "max_duration_ms": 3000 + }, + "servo_ids": [ + 7, + 8, + 9 + ], + "config_writes": [], + "wheel_raw": [ + -565, + 0, + 565 + ], + "final_velocity_raw": { + "7": 0, + "8": 0, + "9": 0 + }, + "max_abs_final_velocity": 0, + "stop_confirmed": true, + "stop_samples": [ + { + "7": -29868, + "8": 0, + "9": 150 + }, + { + "7": -30668, + "8": 0, + "9": 0 + }, + { + "7": -31418, + "8": 0, + "9": 0 + }, + { + "7": -32218, + "8": 0, + "9": 0 + }, + { + "7": 0, + "8": 0, + "9": 0 + }, + { + "7": 0, + "8": 0, + "9": 0 + } + ] +} \ No newline at end of file diff --git a/packages/pi-rdk-agent/skills/rdk-develop/SKILL.md b/packages/pi-rdk-agent/skills/rdk-develop/SKILL.md index 0fd4a10..1dbca99 100644 --- a/packages/pi-rdk-agent/skills/rdk-develop/SKILL.md +++ b/packages/pi-rdk-agent/skills/rdk-develop/SKILL.md @@ -149,6 +149,33 @@ Model Zoo `https://developer.d-robotics.cc/model_zoo_doc/model_zoo_intro`. - 非 root 开发用户:cpufreq 等部分 sysfs 读会 EACCES,属正常;程序不要依赖 这些路径,温度用 `/sys/class/thermal/thermal_zone*/temp`。 +## Accessories: knowledge is data, motion is gated (ADR-017/018) + +Accessory knowledge lives in the registry (shipped + user packs), not in your +assumptions. `rdk_accessory_registry` tells you which packs are active / +ready to declare / missing facts for this device; `rdk_accessory_history` +tells you which accessories were ever observed (raw facts). Recommend from the +registry — NEVER infer a product from USB VID:PID. Declared accessory packs +add template capabilities to the snapshot. Use `rdk_template_list` / +`rdk_template_run` / `rdk_template_start` — never write your own bus code: + +1. **Auto-discovery** — after Inspect, if the snapshot shows the accessory + scan capability `base.scan`, run the `base-scan` template AUTOMATICALLY: + it is read-only (zero writes on the bus) and confirms accessory facts + (which servos answer, supply voltage). A scan reporting missing servos + usually means the accessory power is off — report it as a fact, don't + retry endlessly. +2. **Motion always stops at a human** — motion templates (`base-move`) return + `status: approval_required` with an approval id. Present it to the human + and STOP. After the human approves, call `rdk_template_start` with the + planId/approvalId. Never loop or retry motion without a fresh human + approval; one approval = one run. +3. **Envelope** — motion parameters are bounded (velocity/duration) by the + accessory pack. Values outside the envelope are rejected before planning; + never try to widen them. +4. **New accessories** — if an observed device is not in the registry, say + so; creating a user accessory pack is a human action, not yours. + ## Never - Never request, handle, or repeat credentials, tokens, or private keys. diff --git a/packages/rdk-agent-desktop/src/renderer/App.tsx b/packages/rdk-agent-desktop/src/renderer/App.tsx index 3fc9301..5da7b92 100644 --- a/packages/rdk-agent-desktop/src/renderer/App.tsx +++ b/packages/rdk-agent-desktop/src/renderer/App.tsx @@ -421,9 +421,19 @@ function Workbench() { try { const rid = `${name}-${Date.now()}`; const rec = (await api.template.run(name, deviceId, rid)) as Record; - setTemplateResult( - `${name} → ${typeof rec.state === "string" ? rec.state : "run"} / ${typeof rec.outcome === "string" ? rec.outcome : "…"}`, - ); + if (rec.status === "approval_required") { + setTemplateResult( + `${name} → 需要批准才能运动(审批号 ${String(rec.approval_id ?? "…")})。` + + "批准后运行:rdkctl template start --plan-id " + + `${String(rec.plan_id ?? "…")} --approval-id ${String(rec.approval_id ?? "…")}`, + ); + setApprovals(parseApprovals(await api.task.approvals())); + } else { + const run = (rec.run ?? rec) as Record; + setTemplateResult( + `${name} → ${typeof run.state === "string" ? run.state : "run"} / ${typeof run.outcome === "string" ? run.outcome : "…"}`, + ); + } } catch (err) { setError(`一键运行失败:${describeError(err)}`); } finally { diff --git a/packages/rdk-agent-pi/src/config.ts b/packages/rdk-agent-pi/src/config.ts index b8a8acf..13b3469 100644 --- a/packages/rdk-agent-pi/src/config.ts +++ b/packages/rdk-agent-pi/src/config.ts @@ -44,6 +44,12 @@ export const RDK_TOOL_ALLOWLIST = [ "rdk_pack_save", "rdk_pack_list", "rdk_pack_run", + "rdk_template_list", + "rdk_template_run", + "rdk_template_start", + "rdk_fixture_list", + "rdk_accessory_registry", + "rdk_accessory_history", ] as const; export type RdkToolName = (typeof RDK_TOOL_ALLOWLIST)[number]; diff --git a/packages/rdk-agent-pi/src/tools.ts b/packages/rdk-agent-pi/src/tools.ts index fa8a333..2e92425 100644 --- a/packages/rdk-agent-pi/src/tools.ts +++ b/packages/rdk-agent-pi/src/tools.ts @@ -440,5 +440,103 @@ export function createRdkTools(client: RdkHostClient): RdkToolDefinition[] { request_id: str(args, "requestId"), }), }, + // -- reviewed templates (ADR-017; deterministic, no model code) -- + { + name: "rdk_template_list", + label: "List one-click templates", + description: + "List reviewed one-click templates for a device with runnable flag and " + + "missing capabilities. Fixture-bound templates (accessory bus " + + "scan/motion) become runnable only after a human declares an accessory " + + "fixture.", + parameters: Type.Object({ deviceId: Type.String() }, { additionalProperties: false }), + execute: async (args) => call("template.list")({ device_id: str(args, "deviceId") }), + }, + { + name: "rdk_template_run", + label: "Run a reviewed template", + description: + "Run a deterministic reviewed template — no model-authored code. R0 " + + "templates (accessory discovery, e.g. base-scan) run automatically. " + + "Motion templates (e.g. base-move) return status approval_required " + + "with an approvalId: present it to the human and STOP; after the human " + + "approves, call rdk_template_start. Only bounded numeric params; " + + "fixture-bound values (port/servo ids/envelope) are injected host-side " + + "and cannot be supplied here.", + parameters: Type.Object( + { + name: Type.String(), + deviceId: Type.String(), + requestId: Type.String(), + params: Type.Optional(Type.Record(Type.String(), Type.Number())), + }, + { additionalProperties: false }, + ), + execute: async (args) => + call("template.run")({ + name: str(args, "name"), + device_id: str(args, "deviceId"), + request_id: str(args, "requestId"), + params: (args["params"] as Record | undefined) ?? {}, + }), + }, + { + name: "rdk_template_start", + label: "Start an approved template run", + description: + "Second phase of a motion template run: start it after the human " + + "approved it. Consumes the single-use approval; policy re-evaluates.", + parameters: Type.Object( + { + planId: Type.String(), + approvalId: Type.String(), + requestId: Type.String(), + }, + { additionalProperties: false }, + ), + execute: async (args) => + call("template.start")({ + plan_id: str(args, "planId"), + approval_id: str(args, "approvalId"), + request_id: str(args, "requestId"), + }), + }, + { + name: "rdk_fixture_list", + label: "List declared fixtures", + description: + "Read-only list of human-declared safe hardware fixtures (ADR-017). " + + "Declaring/removing fixtures is human-only; there is no such tool here.", + parameters: Type.Object( + { deviceId: Type.Optional(Type.String()) }, + { additionalProperties: false }, + ), + execute: async (args) => call("fixture.list")({ device_id: optStr(args, "deviceId") }), + }, + // -- accessories as data (ADR-018; read-only facts for the agent) -- + { + name: "rdk_accessory_registry", + label: "Accessory registry & recommendations", + description: + "Read-only accessory knowledge (ADR-018): every known accessory pack " + + "(shipped or user-created) with its status for this device — active " + + "(declared fixture), ready (device facts present, can be declared by " + + "the human) or missing_facts (what the board still lacks). Recommend " + + "from this list; NEVER infer product identity from USB VID:PID.", + parameters: Type.Object({ deviceId: Type.String() }, { additionalProperties: false }), + execute: async (args) => + call("accessory.registry")({ device_id: str(args, "deviceId") }), + }, + { + name: "rdk_accessory_history", + label: "Remembered accessories", + description: + "Read-only memory of accessories ever observed on this device " + + "(ADR-018): raw VID:PID / serial-node facts with first/last seen, " + + "plus which packs were declared. Facts only — no product naming.", + parameters: Type.Object({ deviceId: Type.String() }, { additionalProperties: false }), + execute: async (args) => + call("accessory.history")({ device_id: str(args, "deviceId") }), + }, ]; } diff --git a/packages/rdk-agent-pi/test/config.test.ts b/packages/rdk-agent-pi/test/config.test.ts index 596bb36..0721b03 100644 --- a/packages/rdk-agent-pi/test/config.test.ts +++ b/packages/rdk-agent-pi/test/config.test.ts @@ -60,6 +60,14 @@ test("allowlist is the spec tool surface (docs/08 §5)", () => { "rdk_pack_save", "rdk_pack_list", "rdk_pack_run", + // ADR-017: reviewed fixture-bound templates (accessory discovery + motion + // gated by human approval) and read-only fixture listing. + "rdk_template_list", + "rdk_template_run", + "rdk_template_start", + "rdk_fixture_list", + "rdk_accessory_registry", + "rdk_accessory_history", ]; assert.deepEqual([...RDK_TOOL_ALLOWLIST], expected); }); diff --git a/packages/rdk-agent-surface/package-lock.json b/packages/rdk-agent-surface/package-lock.json index 06c3d26..d1aa4e4 100644 --- a/packages/rdk-agent-surface/package-lock.json +++ b/packages/rdk-agent-surface/package-lock.json @@ -14,7 +14,7 @@ "zod": "3.25.76" }, "bin": { - "rdk-agent": "dist/cli.js" + "rdk-agent": "dist/bin.js" }, "devDependencies": { "@earendil-works/pi-coding-agent": "0.84.1", diff --git a/packages/rdk-agent-surface/test/packageEntry.test.ts b/packages/rdk-agent-surface/test/packageEntry.test.ts index ad03a81..18016b7 100644 --- a/packages/rdk-agent-surface/test/packageEntry.test.ts +++ b/packages/rdk-agent-surface/test/packageEntry.test.ts @@ -26,6 +26,8 @@ test("public barrel re-exports the reviewed surface", () => { "TaskService", "buildTaskService", "defaultRealModelDotEnvPath", + "listSkills", + "readSkill", "resolveRealModelConfig", "writeRealModelDotEnv", ].sort(), diff --git a/packages/rdk_agent_cli/src/rdk_agent_cli/rdkctl.py b/packages/rdk_agent_cli/src/rdk_agent_cli/rdkctl.py index 021bcbe..098577c 100644 --- a/packages/rdk_agent_cli/src/rdk_agent_cli/rdkctl.py +++ b/packages/rdk_agent_cli/src/rdk_agent_cli/rdkctl.py @@ -215,6 +215,48 @@ def build_parser() -> argparse.ArgumentParser: export.add_argument("--device-id", default="virtual-rdk-001") export.add_argument("--spec", required=True, help="DeviceSpec JSON path") export.add_argument("--request-id", required=True) + # Safe hardware fixtures (ADR-017): human authority plane only. + fixture = sub.add_parser("fixture") + fixture_sub = fixture.add_subparsers(dest="command", required=True) + fdeclare = fixture_sub.add_parser("declare") + fdeclare.add_argument("--device-id", required=True) + fdeclare.add_argument("--pack", required=True) + fdeclare.add_argument("--serial-node", required=True) + flist = fixture_sub.add_parser("list") + flist.add_argument("--device-id", default=None) + fremove = fixture_sub.add_parser("remove") + fremove.add_argument("--fixture-id", required=True) + + # Accessories as data (ADR-018): registry/recommend/history are R0 facts; + # user pack create/remove stay on the human authority plane. + accessory = sub.add_parser("accessory") + accessory_sub = accessory.add_subparsers(dest="command", required=True) + arec = accessory_sub.add_parser("recommend") + arec.add_argument("--device-id", required=True) + ahist = accessory_sub.add_parser("history") + ahist.add_argument("--device-id", required=True) + apack = accessory_sub.add_parser("pack") + apack_sub = apack.add_subparsers(dest="pack_command", required=True) + apcreate = apack_sub.add_parser("create") + apcreate.add_argument("--json-file", required=True) + apremove = apack_sub.add_parser("remove") + apremove.add_argument("--pack-id", required=True) + + # Reviewed templates (ADR-017): deterministic one-click runs. R2 motion + # templates stop at a pending approval; start consumes the human decision. + template = sub.add_parser("template") + template_sub = template.add_subparsers(dest="command", required=True) + ttlist = template_sub.add_parser("list") + ttlist.add_argument("--device-id", required=True) + ttrun = template_sub.add_parser("run") + ttrun.add_argument("--name", required=True) + ttrun.add_argument("--device-id", required=True) + ttrun.add_argument("--request-id", default=None) + ttrun.add_argument("--param", action="append", default=[], help="name=value (numeric)") + ttstart = template_sub.add_parser("start") + ttstart.add_argument("--plan-id", required=True) + ttstart.add_argument("--approval-id", required=True) + ttstart.add_argument("--request-id", default=None) return parser @@ -381,6 +423,57 @@ def _dispatch(args: argparse.Namespace, service: AgentApplicationService) -> Any args.device_id, spec_path=Path(args.spec), request_id=args.request_id ) } + if args.area == "fixture": + if args.command == "declare": + return service.declare_fixture( + args.device_id, args.pack, args.serial_node, actor=_human_actor(args) + ) + if args.command == "list": + return {"fixtures": service.list_fixtures(args.device_id)} + if args.command == "remove": + service.remove_fixture(args.fixture_id) + return {"fixture_id": args.fixture_id, "removed": True} + if args.area == "accessory": + if args.command == "recommend": + return {"packs": service.recommend_accessories(args.device_id)} + if args.command == "history": + return service.accessory_history(args.device_id) + if args.command == "pack": + if args.pack_command == "create": + payload = json.loads(Path(args.json_file).read_text(encoding="utf-8")) + pack = service.create_accessory_pack(payload, actor=_human_actor(args)) + return {"pack": pack, "created": True} + if args.pack_command == "remove": + service.remove_accessory_pack(args.pack_id) + return {"pack_id": args.pack_id, "removed": True} + if args.area == "template": + if args.command == "list": + return {"templates": service.list_templates(args.device_id)} + if args.command == "run": + params: dict[str, float] = {} + for item in args.param: + name, sep, value = item.partition("=") + if not sep or not name: + raise RDKError( + ErrorCode.INPUT_INVALID, f"--param expects name=value, got {item!r}" + ) + try: + params[name] = float(value) + except ValueError as exc: + raise RDKError( + ErrorCode.INPUT_INVALID, f"--param {name} must be numeric" + ) from exc + request_id = args.request_id or new_id("req") + return service.run_template( + args.name, args.device_id, request_id=request_id, params=params + ) + if args.command == "start": + request_id = args.request_id or new_id("req") + return { + "run": service.start_template( + plan_id=args.plan_id, approval_id=args.approval_id, request_id=request_id + ) + } raise RDKError(ErrorCode.INPUT_INVALID, f"unknown command {args.area} {args.command}") diff --git a/packages/rdk_agent_core/src/rdk_agent_core/accessories.py b/packages/rdk_agent_core/src/rdk_agent_core/accessories.py new file mode 100644 index 0000000..d3b184f --- /dev/null +++ b/packages/rdk_agent_core/src/rdk_agent_core/accessories.py @@ -0,0 +1,266 @@ +"""Accessory knowledge as data (ADR-018). + +The agent's accessory capabilities — inspect, operate, recommend, remember — +live in DATA, not in product-specific code: + +- ``AccessoryPack``: one reviewed or user-created accessory record (servo + ids, motion envelope, kinematics, bus protocol, requirements, provenance). + Shipped packs are JSON files validated by this model; user packs live in + the state dir and are validated by the SAME model with the same absolute + ceilings. Adding an accessory never changes product code. +- ``AccessorySighting``: raw observed facts (VID:PID / serial node) that let + the product remember which accessories were ever connected. Facts only — + product identity is never inferred from VID:PID (AT-002); it comes from a + human fixture declaration (``rdk_agent_core.fixtures``). + +Safety lines (ADR-018, docs/05 §9): every envelope value needs provenance +(``source``); ``MotionEnvelope`` carries absolute model ceilings that no +pack — shipped or user — can exceed; motion capabilities stay R2 and always +require a human fixture declaration plus per-run approval. +""" + +from __future__ import annotations + +from datetime import datetime +from enum import Enum +from typing import Protocol, cast + +from pydantic import Field, field_validator, model_validator + +from .base import DomainModel, validate_tz_aware +from .capabilities import ( + AccessMode, + CapabilityDescriptor, + CapabilityEvidence, + CapabilityMode, + CapabilityStatus, + ConcurrencyRule, + RiskLevel, +) +from .device import DeviceSnapshot, Observation, ObservationStatus + + +class PackOrigin(str, Enum): + REVIEWED = "reviewed" # shipped with the product, reviewed at release + USER = "user" # created locally; same model, same ceilings + + +class BusProtocol(str, Enum): + """Controlled enum: selects the protocol driver, never a product.""" + + FEETECH_STS = "feetech-sts" + + +#: Generic capability ids granted by accessory packs (pack data references +#: these; the set itself is modeled here, not in pack data). +BASE_SCAN_CAPABILITY = "base.scan" +BASE_VELOCITY_CAPABILITY = "base.velocity.bounded" + +#: Reviewed physical-output capabilities that are PLANNABLE by default: they +#: reach REQUIRE_APPROVAL and only run after a human decision per run +#: (ADR-017/018). Being allowlisted is never an execution grant. +DEFAULT_R2_ALLOWLIST: tuple[str, ...] = (BASE_VELOCITY_CAPABILITY,) + + +class FixtureDeclarationLike(Protocol): + """Structural view of fixtures.FixtureDeclaration (avoids circular import).""" + + fixture_id: str + device_id: str + pack_id: str + pack_version: str + serial_node: str + + +class MotionEnvelope(DomainModel): + """Hard motion bounds for one accessory pack (ADR-012 §5 parameter envelope). + + The ``le=`` constraints are PRODUCT ABSOLUTE CEILINGS: no pack, shipped or + user-created, may exceed them. Enforced three times: host-side before + planning, inside the reviewed template program, and by the host verifier + over read-back evidence. + """ + + max_linear_m_s: float = Field(gt=0.0, le=0.5) + max_angular_deg_s: float = Field(gt=0.0, le=120.0) + max_duration_ms: int = Field(gt=0, le=10_000) + + +class AccessoryRequirements(DomainModel): + """Device facts an accessory needs, for recommendation (never for grants). + + Matching these against a snapshot only produces "could attach" advice; + capabilities only appear through a human fixture declaration (ADR-018). + """ + + serial_bus: bool = False # at least one observed serial node + camera: bool = False # at least one observed video node + can_bus: bool = False + lerobot: bool = False # LeRobot ecosystem installed on the board + + +class AccessoryPack(DomainModel): + """One accessory record — data, not code (ADR-018).""" + + pack_id: str = Field(min_length=1, max_length=64) + pack_version: str = Field(min_length=1, max_length=32) + origin: PackOrigin = PackOrigin.REVIEWED + description: str = Field(default="", max_length=512) + bus_protocol: BusProtocol = BusProtocol.FEETECH_STS + capabilities: tuple[str, ...] = Field(min_length=1, max_length=8) + servo_ids: tuple[int, ...] = Field(min_length=1, max_length=16) + envelope: MotionEnvelope + #: Kinematics constants with provenance in ``source``. + wheel_radius_m: float = Field(gt=0.0, le=1.0) + base_radius_m: float = Field(gt=0.0, le=2.0) + max_raw_wheel_speed: int = Field(gt=0, le=32767) + #: Omniwheel mounting angles (deg, one per wheel servo, same order as + #: ``servo_ids``). Accessory-specific fact, provenance in ``source``. + wheel_angles_deg: tuple[float, float, float] = Field(min_length=3, max_length=3) + #: Where every fact comes from (vendor data, human measurement, human + #: entry). Required for shipped and user packs alike — an envelope + #: without provenance is not a reviewed envelope. + source: str = Field(min_length=1, max_length=512) + requirements: AccessoryRequirements = Field(default_factory=AccessoryRequirements) + + @field_validator("capabilities") + @classmethod + def _known_capabilities(cls, value: tuple[str, ...]) -> tuple[str, ...]: + unknown = sorted(set(value) - set(KNOWN_PACK_CAPABILITIES)) + if unknown: + raise ValueError(f"unknown pack capabilities: {unknown}") + return value + + +#: Capability ids a pack may grant, with their descriptor shape. Keeping the +#: set here means pack data can never mint new capabilities. +KNOWN_PACK_CAPABILITIES: dict[str, dict[str, object]] = { + BASE_SCAN_CAPABILITY: { + "risk": RiskLevel.R0_READ_OBSERVE, + "mode": CapabilityMode.READ, + "concurrency": ConcurrencyRule.SHARED, + "limitations": ["bounded bus discovery; zero write commands"], + }, + BASE_VELOCITY_CAPABILITY: { + "risk": RiskLevel.R2_DEVICE_IO_BOUNDED, + "mode": CapabilityMode.WRITE, + "concurrency": ConcurrencyRule.EXCLUSIVE, + "limitations": [ + "velocity mode only; bounded envelope enforced host-side, in the " + "reviewed template, and by safe-state verification", + "acceptance requires wheels elevated and the kill method reachable", + ], + }, +} + + +def build_pack_capabilities( + pack: AccessoryPack, fixture_id: str, serial_node: str +) -> list[CapabilityDescriptor]: + evidence = [CapabilityEvidence(kind="fixture", value=fixture_id)] + limitations_common = [ + f"accessory pack {pack.pack_id}@{pack.pack_version} ({pack.origin.value})", + f"serial node {serial_node}", + f"provenance: {pack.source}", + ] + out: list[CapabilityDescriptor] = [] + for cap_id in pack.capabilities: + shape = KNOWN_PACK_CAPABILITIES[cap_id] + risk = shape["risk"] + assert isinstance(risk, RiskLevel) + out.append( + CapabilityDescriptor( + id=cap_id, + status=CapabilityStatus.AVAILABLE, + risk=risk, + mode=shape["mode"], # type: ignore[arg-type] + concurrency=shape["concurrency"], # type: ignore[arg-type] + access=AccessMode.BROKERED, + internal_device_resources=[serial_node], + evidence=list(evidence), + limitations=[*cast(list[str], shape["limitations"]), *limitations_common], + ) + ) + return out + + +def apply_fixture_overlay( + snapshot: DeviceSnapshot, + declaration: FixtureDeclarationLike, + pack: AccessoryPack | None, +) -> DeviceSnapshot: + """Overlay the declared pack's capabilities onto a snapshot. + + Preconditions (all fail-closed, no capability on mismatch): + + - the pack exists in the registry and the declared version matches; + - the declared serial node is an OBSERVED peripheral fact of this snapshot; + - the declaration was made by a USER actor (fixture model enforces). + + Returns a new snapshot with recomputed content id when capabilities are + injected — so old plans bound to the previous snapshot invalidate + (docs/03 §2.5). Returns the input unchanged when there is nothing new. + """ + + if declaration.device_id != snapshot.device_id: + return snapshot + if pack is None or pack.pack_id != declaration.pack_id: + return snapshot + if pack.pack_version != declaration.pack_version: + return snapshot + if declaration.serial_node not in snapshot.peripherals.serial_nodes: + return snapshot + + existing = {cap.id for cap in snapshot.capabilities} + wanted = set(pack.capabilities) + if wanted <= existing: + return snapshot + + capabilities = [cap for cap in snapshot.capabilities if cap.id not in wanted] + observations = dict(snapshot.observations) + for cap in build_pack_capabilities(pack, declaration.fixture_id, declaration.serial_node): + capabilities.append(cap) + observations[f"/capabilities/{cap.id}"] = Observation( + status=ObservationStatus.OBSERVED, + probe_id=None, + evidence_ref=f"fixture:{declaration.fixture_id}", + ) + return snapshot.model_copy( + update={"capabilities": capabilities, "observations": observations} + ).with_computed_id() + + +class AccessorySighting(DomainModel): + """One remembered raw accessory fact for a device (facts only, ADR-018). + + Product identity is deliberately absent: VID:PID must never become + product naming (AT-002). Association with a pack happens only through a + human fixture declaration. + """ + + device_id: str = Field(min_length=1, max_length=128) + kind: str = Field(pattern=r"^(usb|serial)$") # usb = VID:PID fact + value: str = Field(min_length=1, max_length=128) + first_seen_at: datetime + last_seen_at: datetime + + @field_validator("first_seen_at", "last_seen_at") + @classmethod + def _tz(cls, value: datetime) -> datetime: + result = validate_tz_aware(value) + assert result is not None + return result + + @model_validator(mode="after") + def _ordered(self) -> AccessorySighting: + if self.last_seen_at < self.first_seen_at: + raise ValueError("last_seen_at before first_seen_at") + return self + + +class AccessoryLedger(DomainModel): + """Per-device accessory memory: raw sightings + declared pack references.""" + + device_id: str = Field(min_length=1, max_length=128) + sightings: list[AccessorySighting] = Field(default_factory=list, max_length=256) + declared_packs: list[str] = Field(default_factory=list, max_length=64) diff --git a/packages/rdk_agent_core/src/rdk_agent_core/fixtures.py b/packages/rdk_agent_core/src/rdk_agent_core/fixtures.py new file mode 100644 index 0000000..51ce6b4 --- /dev/null +++ b/packages/rdk_agent_core/src/rdk_agent_core/fixtures.py @@ -0,0 +1,84 @@ +"""Safe hardware fixture declarations (ADR-017, knowledge moved to data by ADR-018). + +Physical-output capabilities (chassis motion, and later arms) are never +granted by probes — probes keep zero interaction with actuator buses +(AT-002) and VID:PID enumeration must never be turned into product naming. +Instead a HUMAN declares an accessory pack (data in the accessory registry, +``rdk_agent_core.accessories``) against an observed serial node; the host +overlays the pack's capabilities onto the device snapshot with fixture +evidence (``accessories.apply_fixture_overlay``). Default-deny policy does +the rest: + +- ``base.scan`` (R0 read-observe): bounded bus discovery, zero writes. + Agent-initiated automatically once available (accessory fact finding). +- ``base.velocity.bounded`` (R2 device-io-bounded): bounded velocity motion. + Always REQUIRE_APPROVAL -> human decides per run (docs/05 §3/§9). + +Packs themselves are DATA (shipped JSON + user records), never code +constants — see ``rdk_agent_core.accessories`` and ADR-018. +""" + +from __future__ import annotations + +from datetime import datetime + +from pydantic import Field, field_validator, model_validator + +# Re-exported for the many call sites that discuss fixture-granted ids. +from .accessories import ( + BASE_SCAN_CAPABILITY, + BASE_VELOCITY_CAPABILITY, + DEFAULT_R2_ALLOWLIST, + AccessoryPack, + MotionEnvelope, + apply_fixture_overlay, +) + +__all__ = [ + "BASE_SCAN_CAPABILITY", + "BASE_VELOCITY_CAPABILITY", + "DEFAULT_R2_ALLOWLIST", + "AccessoryPack", + "FixtureDeclaration", + "MotionEnvelope", + "apply_fixture_overlay", +] +from .base import ActorKind, ActorRef, DomainModel, new_id, validate_tz_aware + + +class FixtureDeclaration(DomainModel): + """A human-declared accessory attachment on a registered device. + + The declaration alone never executes anything: it only lets the host + overlay the declared pack's capabilities onto snapshots whose observed + peripherals contain the declared serial node (docs/03 §2.2.2, ADR-017). + The pack itself is resolved against the accessory registry (ADR-018). + """ + + fixture_id: str = Field(default_factory=lambda: new_id("fix"), min_length=1, max_length=128) + pack_id: str = Field(min_length=1, max_length=64) + pack_version: str = Field(min_length=1, max_length=32) + device_id: str = Field(min_length=1, max_length=128) + serial_node: str = Field(min_length=1, max_length=128, pattern=r"^/dev/[A-Za-z0-9_.-]+$") + kill_method: str = Field( + default="unplug the battery connector (this assembly has no 12V switch)", + max_length=256, + ) + orientation: str = Field(default="elevated-wheels-free", max_length=64) + declared_by: ActorRef + declared_at: datetime + + @field_validator("declared_at") + @classmethod + def _tz(cls, value: datetime) -> datetime: + result = validate_tz_aware(value) + assert result is not None + return result + + @model_validator(mode="after") + def _declared_by_user(self) -> FixtureDeclaration: + """Fixtures are human authority; agents cannot declare them (ADR-017).""" + + if self.declared_by.kind is not ActorKind.USER: + raise ValueError("fixture declarations require a human (user) actor") + return self diff --git a/packages/rdk_agent_core/src/rdk_agent_core/schema_gen.py b/packages/rdk_agent_core/src/rdk_agent_core/schema_gen.py index 99e42ef..ef6724e 100644 --- a/packages/rdk_agent_core/src/rdk_agent_core/schema_gen.py +++ b/packages/rdk_agent_core/src/rdk_agent_core/schema_gen.py @@ -16,6 +16,7 @@ from pathlib import Path from pydantic import BaseModel +from .accessories import AccessoryPack from .approvals import ApprovalRecord from .capabilities import ( CapabilityDescriptor, @@ -37,6 +38,7 @@ from .device_spec import ( PartInstance, Provenance, ) +from .fixtures import FixtureDeclaration from .frames import ( ArtifactDescriptor, EventRecord, @@ -68,6 +70,8 @@ SCHEMA_MODELS: dict[str, type[BaseModel]] = { "capability-descriptor": CapabilityDescriptor, "verification-result": VerificationResult, "approval-record": ApprovalRecord, + "accessory-pack": AccessoryPack, + "fixture-declaration": FixtureDeclaration, "run-ticket": RunTicket, "agent-task": AgentTask, "checkpoint": Checkpoint, diff --git a/packages/rdk_agent_device/src/rdk_agent_device/probes.py b/packages/rdk_agent_device/src/rdk_agent_device/probes.py index f14e2d1..2276170 100644 --- a/packages/rdk_agent_device/src/rdk_agent_device/probes.py +++ b/packages/rdk_agent_device/src/rdk_agent_device/probes.py @@ -26,10 +26,12 @@ from rdk_agent_core.device import ( InventoryMeta, Observation, ObservationStatus, + PeripheralsBlock, ProbeError, ResourcesBlock, SoftwareBlock, SystemBlock, + UsbDevice, ) from rdk_agent_core.inventory import ( InventoryProfile, @@ -210,7 +212,16 @@ def execute_inventory( resources = ResourcesBlock(disk_free_bytes=facts.disk_free_bytes) usb_result = results.get("fake.usb@1") + peripherals = PeripheralsBlock() if usb_result is not None and observe("/usb/devices", usb_result): + devices: list[UsbDevice] = [] + for entry in facts.usb_devices: + vid_pid, _, description = entry.partition(" ") + vendor_id, _, product_id = vid_pid.partition(":") + devices.append( + UsbDevice(vendor_id=vendor_id, product_id=product_id, description=description) + ) + peripherals = PeripheralsBlock(usb_devices=devices) status = CapabilityStatus.AVAILABLE if facts.usb_devices else CapabilityStatus.UNAVAILABLE capabilities.append( CapabilityDescriptor( @@ -290,6 +301,7 @@ def execute_inventory( system=system, resources=resources, software=software, + peripherals=peripherals, capabilities=capabilities, probe_errors=probe_errors, inventory=InventoryMeta( diff --git a/packages/rdk_agent_host/src/rdk_agent_host/accessory_registry.py b/packages/rdk_agent_host/src/rdk_agent_host/accessory_registry.py new file mode 100644 index 0000000..678e7d5 --- /dev/null +++ b/packages/rdk_agent_host/src/rdk_agent_host/accessory_registry.py @@ -0,0 +1,101 @@ +"""Accessory registry: shipped packs + user packs, both data (ADR-018). + +Two layers, one model: + +- SHIPPED packs: JSON under ``data/accessory-packs/``, validated by + ``AccessoryPack`` at load; reviewed at release time (the review happens on + the data, not on code). Origin must be ``reviewed``. +- USER packs: per-machine records in the state dir + (``FileAccessoryPackStore``), same model, same absolute ceilings; they may + never shadow a shipped pack id and their ``source`` (provenance) is + required by the model itself. + +Knowledge of an accessory never grants anything by itself: capabilities +appear only through a human fixture declaration overlaid on observed device +facts, and R2 motion still requires per-run approval (ADR-017). +""" + +from __future__ import annotations + +from pathlib import Path + +from rdk_agent_core.accessories import AccessoryPack, PackOrigin +from rdk_agent_core.errors import ErrorCode, RDKError + +from .stores import AccessoryPackStore + +SHIPPED_PACKS_DIR = Path(__file__).parent / "data" / "accessory-packs" + + +def load_shipped_packs(directory: Path = SHIPPED_PACKS_DIR) -> dict[str, AccessoryPack]: + """Load and validate every shipped accessory pack (fail-closed).""" + + packs: dict[str, AccessoryPack] = {} + for path in sorted(directory.glob("*.json")): + try: + pack = AccessoryPack.model_validate_json(path.read_text(encoding="utf-8")) + except Exception as exc: # pydantic ValidationError or IO + raise RDKError( + ErrorCode.INPUT_INVALID, + f"shipped accessory pack {path.name} is invalid: {exc}", + ) from exc + if pack.origin is not PackOrigin.REVIEWED: + raise RDKError( + ErrorCode.INPUT_INVALID, + f"shipped accessory pack {pack.pack_id!r} must have origin=reviewed", + ) + if pack.pack_id in packs: + raise RDKError( + ErrorCode.INPUT_INVALID, + f"duplicate shipped accessory pack id {pack.pack_id!r}", + ) + packs[pack.pack_id] = pack + return packs + + +class AccessoryRegistry: + """Merged view: shipped packs plus this machine's user packs.""" + + def __init__(self, shipped: dict[str, AccessoryPack], user_store: AccessoryPackStore) -> None: + self._shipped = dict(shipped) + self._users = user_store + + def get(self, pack_id: str) -> AccessoryPack | None: + pack = self._shipped.get(pack_id) + if pack is not None: + return pack + return self._users.get(pack_id) + + def shipped(self) -> list[AccessoryPack]: + return sorted(self._shipped.values(), key=lambda p: p.pack_id) + + def user_packs(self) -> list[AccessoryPack]: + return sorted(self._users.list_all(), key=lambda p: p.pack_id) + + def all(self) -> list[AccessoryPack]: + return self.shipped() + self.user_packs() + + def create_user_pack(self, pack: AccessoryPack) -> AccessoryPack: + """Register a user-created pack (human plane). + + Fail-closed rules: the id must not shadow a shipped pack, and the + record is forced to origin=user. Model ceilings (envelope bounds, + provenance requirement) were already enforced by validation. + """ + + if pack.pack_id in self._shipped: + raise RDKError( + ErrorCode.INPUT_INVALID, + f"pack id {pack.pack_id!r} is a shipped pack; user packs may not shadow it", + ) + user_pack = pack.model_copy(update={"origin": PackOrigin.USER}) + self._users.save(user_pack) + return user_pack + + def remove_user_pack(self, pack_id: str) -> None: + if pack_id in self._shipped: + raise RDKError( + ErrorCode.INPUT_INVALID, + f"pack {pack_id!r} is shipped and cannot be removed on this machine", + ) + self._users.remove(pack_id) diff --git a/packages/rdk_agent_host/src/rdk_agent_host/application.py b/packages/rdk_agent_host/src/rdk_agent_host/application.py index 096ecab..4216211 100644 --- a/packages/rdk_agent_host/src/rdk_agent_host/application.py +++ b/packages/rdk_agent_host/src/rdk_agent_host/application.py @@ -34,9 +34,11 @@ from pathlib import Path from time import monotonic, sleep from typing import Any +from rdk_agent_core.accessories import AccessoryLedger, AccessoryPack, AccessorySighting from rdk_agent_core.approvals import ApprovalDecision, ApprovalRecord from rdk_agent_core.base import ActorKind, ActorRef, new_id, utcnow from rdk_agent_core.canonical import content_digest +from rdk_agent_core.capabilities import CapabilityStatus from rdk_agent_core.device import ( DeviceRegistration, DeviceSnapshot, @@ -45,6 +47,7 @@ from rdk_agent_core.device import ( ) from rdk_agent_core.errors import ErrorCode, RDKError from rdk_agent_core.events import EventKind +from rdk_agent_core.fixtures import FixtureDeclaration, apply_fixture_overlay from rdk_agent_core.frames import ArtifactDescriptor, EventRecord from rdk_agent_core.inventory import ( InventoryDelta, @@ -75,6 +78,7 @@ from rdk_agent_core.tasks import ( from rdk_agent_core.tickets import RunTicket, sign_ticket from rdk_agent_core.verification import VerificationResult, aggregate_outcome +from .accessory_registry import AccessoryRegistry, load_shipped_packs from .config import HostConfig from .connector import StdioDeviceConnector from .known_hosts import ( @@ -86,9 +90,15 @@ from .known_hosts import ( ) from .packs import InMemoryPackStore, PackStore, StagedSource from .stores import ( + AccessoryLedgerStore, + AccessoryPackStore, ApprovalStore, EventStore, + FixtureStore, IdempotencyStore, + InMemoryAccessoryLedgerStore, + InMemoryAccessoryPackStore, + InMemoryFixtureStore, InMemoryRegistrationStore, PlanStore, RegistrationStore, @@ -202,6 +212,9 @@ class AgentApplicationService: verifications: VerificationStore, registrations: RegistrationStore | None = None, packs: PackStore | None = None, + fixtures: FixtureStore | None = None, + accessory_packs: AccessoryPackStore | None = None, + accessory_ledgers: AccessoryLedgerStore | None = None, clock: Callable[[], datetime] = utcnow, ) -> None: self._config = config @@ -216,6 +229,11 @@ class AgentApplicationService: self._verifications = verifications self._registrations = registrations or InMemoryRegistrationStore() self._packs = packs or InMemoryPackStore() + self._fixtures = fixtures or InMemoryFixtureStore() + self._accessories = AccessoryRegistry( + load_shipped_packs(), accessory_packs or InMemoryAccessoryPackStore() + ) + self._ledgers = accessory_ledgers or InMemoryAccessoryLedgerStore() self._clock = clock self._policy = PolicyEngine() self._actor = ActorRef(kind=ActorKind.AGENT, id=AGENT_ACTOR_ID) @@ -233,6 +251,22 @@ class AgentApplicationService: snapshot.captured_at = self._clock() return snapshot + def _fixture_overlay(self, snapshot: DeviceSnapshot) -> DeviceSnapshot: + """Overlay the device's active declared fixture (ADR-017). + + Probes never touch actuator buses (AT-002), so fixture capabilities + enter snapshots only here: a human declaration whose serial node is an + observed fact of THIS snapshot. No declaration / unobserved node / + unreviewed pack -> snapshot unchanged (default-deny holds). + """ + + declaration = self._fixtures.active_for_device(snapshot.device_id) + if declaration is None: + return snapshot + return apply_fixture_overlay( + snapshot, declaration, self._accessories.get(declaration.pack_id) + ) + def inventory_device( self, device_id: str, @@ -255,8 +289,10 @@ class AgentApplicationService: if owned: connector.close() snapshot = self._host_stamp(snapshot) + snapshot = self._fixture_overlay(snapshot) previous = self._snapshots.latest(device_id) self._snapshots.save(snapshot) + self._remember_accessories(snapshot) self._events.append( device_id, EventKind.POLICY_ENFORCED, @@ -317,7 +353,9 @@ class AgentApplicationService: else InventoryReason.USER_REQUEST, ) snapshot = self._host_stamp(snapshot) + snapshot = self._fixture_overlay(snapshot) self._snapshots.save(snapshot) + self._remember_accessories(snapshot) finally: connector.close() else: @@ -344,6 +382,269 @@ class AgentApplicationService: raise RDKError(ErrorCode.INPUT_INVALID, f"unknown device {device_id!r}") self._registrations.delete(device_id) + # -- fixtures (safe hardware packs, ADR-017) ------------------------------- + + def declare_fixture( + self, + device_id: str, + pack_id: str, + serial_node: str, + *, + actor: ActorRef, + ) -> dict[str, Any]: + """Human-plane declaration of a reviewed fixture (ADR-017). + + Agents cannot call this (human plane only). The FixtureDeclaration + model rejects non-USER actors fail-closed. The stored snapshot is + re-overlaid immediately so pack capabilities become usable without a + new inventory — still gated on the serial node being an observed fact. + """ + + pack = self._accessories.get(pack_id) + if pack is None: + raise RDKError( + ErrorCode.INPUT_INVALID, + f"unknown accessory pack {pack_id!r}; known packs: " + f"{sorted(p.pack_id for p in self._accessories.all())}", + ) + declaration = FixtureDeclaration( + pack_id=pack.pack_id, + pack_version=pack.pack_version, + device_id=device_id, + serial_node=serial_node, + declared_by=actor, + declared_at=self._clock(), + ) + self._fixtures.save(declaration) + ledger = self._ledgers.get(device_id) + if ledger is not None and pack.pack_id not in ledger.declared_packs: + ledger.declared_packs.append(pack.pack_id) + self._ledgers.save(ledger) + activated = False + snapshot = self._snapshots.latest(device_id) + if snapshot is not None: + overlaid = apply_fixture_overlay(snapshot, declaration, pack) + if overlaid is not snapshot: + self._snapshots.save(overlaid) + activated = True + self._events.append( + device_id, + EventKind.POLICY_ENFORCED, + { + "action": "fixture.declare", + "fixture_id": declaration.fixture_id, + "pack": f"{pack.pack_id}@{pack.pack_version}", + "serial_node": serial_node, + "activated": activated, + }, + ) + return {"fixture": declaration, "activated": activated} + + def list_fixtures(self, device_id: str | None = None) -> list[FixtureDeclaration]: + if device_id is None: + return self._fixtures.list_all() + return self._fixtures.for_device(device_id) + + def remove_fixture(self, fixture_id: str) -> None: + declaration = self._fixtures.get(fixture_id) + if declaration is None: + raise RDKError(ErrorCode.INPUT_INVALID, f"unknown fixture {fixture_id!r}") + self._fixtures.remove(fixture_id) + ledger = self._ledgers.get(declaration.device_id) + still_declared = any( + d.pack_id == declaration.pack_id + for d in self._fixtures.for_device(declaration.device_id) + ) + if ( + ledger is not None + and not still_declared + and declaration.pack_id in ledger.declared_packs + ): + ledger.declared_packs.remove(declaration.pack_id) + self._ledgers.save(ledger) + snapshot = self._snapshots.latest(declaration.device_id) + if snapshot is not None: + rebuilt = self._strip_fixture_capabilities(snapshot, fixture_id) + active = self._fixtures.active_for_device(declaration.device_id) + if active is not None: + rebuilt = apply_fixture_overlay( + rebuilt, active, self._accessories.get(active.pack_id) + ) + if rebuilt is not snapshot: + self._snapshots.save(rebuilt) + self._events.append( + declaration.device_id, + EventKind.POLICY_ENFORCED, + {"action": "fixture.remove", "fixture_id": fixture_id}, + ) + + @staticmethod + def _strip_fixture_capabilities(snapshot: DeviceSnapshot, fixture_id: str) -> DeviceSnapshot: + """Drop capabilities granted by ``fixture_id`` (fail-closed removal).""" + + keep = [] + dropped: list[str] = [] + for cap in snapshot.capabilities: + if any(ev.kind == "fixture" and ev.value == fixture_id for ev in cap.evidence): + dropped.append(cap.id) + continue + keep.append(cap) + if not dropped: + return snapshot + observations = { + path: obs + for path, obs in snapshot.observations.items() + if path not in {f"/capabilities/{cap_id}" for cap_id in dropped} + } + return snapshot.model_copy( + update={"capabilities": keep, "observations": observations} + ).with_computed_id() + + # -- accessories: remember and recommend (ADR-018) ------------------------- + + def _remember_accessories(self, snapshot: DeviceSnapshot) -> None: + """Record raw accessory facts (VID:PID / serial nodes) in the ledger. + + Facts only: no product naming, no pack association (AT-002, ADR-018). + """ + + now = self._clock() + ledger = self._ledgers.get(snapshot.device_id) or AccessoryLedger( + device_id=snapshot.device_id + ) + facts: list[tuple[str, str]] = [ + ("usb", f"{d.vendor_id}:{d.product_id}") + for d in snapshot.peripherals.usb_devices + if d.vendor_id and d.product_id + ] + facts += [("serial", node) for node in snapshot.peripherals.serial_nodes] + index = {(s.kind, s.value): s for s in ledger.sightings} + changed = False + for kind, value in facts: + sighting = index.get((kind, value)) + if sighting is None: + ledger.sightings.append( + AccessorySighting( + device_id=snapshot.device_id, + kind=kind, + value=value, + first_seen_at=now, + last_seen_at=now, + ) + ) + changed = True + elif sighting.last_seen_at < now: + sighting.last_seen_at = now + changed = True + if changed: + self._ledgers.save(ledger) + + def accessory_history(self, device_id: str) -> dict[str, Any]: + """What accessories this device ever showed (facts) and which packs + were declared against it.""" + + ledger = self._ledgers.get(device_id) + if ledger is None: + return {"device_id": device_id, "sightings": [], "declared_packs": []} + return { + "device_id": device_id, + "sightings": [ + { + "kind": s.kind, + "value": s.value, + "first_seen_at": s.first_seen_at, + "last_seen_at": s.last_seen_at, + } + for s in ledger.sightings + ], + "declared_packs": list(ledger.declared_packs), + } + + def recommend_accessories(self, device_id: str) -> list[dict[str, Any]]: + """Registry x device facts: which packs are active / ready to declare + / missing facts. Advice only — capabilities need a human declaration + (ADR-018, CFR-014 style "what's missing").""" + + snapshot = self._snapshots.latest(device_id) + declared = {d.pack_id for d in self._fixtures.for_device(device_id)} + available: set[str] = ( + { + c.id + for c in snapshot.capabilities + if c.status in (CapabilityStatus.AVAILABLE, CapabilityStatus.DEGRADED) + } + if snapshot is not None + else set() + ) + out: list[dict[str, Any]] = [] + for pack in self._accessories.all(): + missing: list[str] = [] + req = pack.requirements + if req.serial_bus and not (snapshot is not None and snapshot.peripherals.serial_nodes): + missing.append("serial_bus") + if req.camera and "camera.snapshot.usb" not in available: + missing.append("camera") + if req.can_bus and not (snapshot is not None and snapshot.peripherals.can_interfaces): + missing.append("can_bus") + if req.lerobot and not (snapshot is not None and snapshot.software.lerobot_version): + missing.append("lerobot") + if pack.pack_id in declared and set(pack.capabilities) <= available: + status = "active" + elif not missing: + status = "ready" + else: + status = "missing_facts" + out.append( + { + "pack_id": pack.pack_id, + "pack_version": pack.pack_version, + "origin": pack.origin.value, + "description": pack.description, + "bus_protocol": pack.bus_protocol.value, + "status": status, + "missing_facts": missing, + } + ) + return out + + def create_accessory_pack(self, payload: dict[str, Any], *, actor: ActorRef) -> AccessoryPack: + """Human-plane: register a user-created accessory pack (ADR-018). + + Model validation enforces the absolute ceilings and provenance; the + registry rejects shadowing shipped ids and forces origin=user. + """ + + if actor.kind is not ActorKind.USER: + raise RDKError( + ErrorCode.INPUT_INVALID, "accessory pack creation requires a human actor" + ) + try: + pack = AccessoryPack.model_validate(payload) + except Exception as exc: + raise RDKError(ErrorCode.INPUT_INVALID, f"invalid accessory pack: {exc}") from exc + created = self._accessories.create_user_pack(pack) + self._events.append( + "accessories", + EventKind.POLICY_ENFORCED, + {"action": "accessory.pack.create", "pack_id": created.pack_id}, + ) + return created + + def remove_accessory_pack(self, pack_id: str) -> None: + for declaration in self._fixtures.list_all(): + if declaration.pack_id == pack_id: + raise RDKError( + ErrorCode.INPUT_INVALID, + f"pack {pack_id!r} is in use by fixture {declaration.fixture_id!r}; " + "remove the fixture first", + ) + self._accessories.remove_user_pack(pack_id) + self._events.append( + "accessories", + EventKind.POLICY_ENFORCED, + {"action": "accessory.pack.remove", "pack_id": pack_id}, + ) + def list_registrations(self) -> list[DeviceRegistration]: return self._registrations.list() @@ -891,26 +1192,9 @@ class AgentApplicationService: details={"run_id": run_id}, ) - if plan.approval_required: - if approval_id is None: - record.state = RunState.AWAITING_APPROVAL - self._runs.save(record) - raise RDKError( - ErrorCode.APPROVAL_REQUIRED, - f"plan {plan_id} requires human approval before start", - details={"run_id": run_id, "plan_id": plan_id}, - ) - # Atomic cross-process single-use consumption: the store serializes - # read→check→write under a per-approval lock (docs/05 §7, S1 收口). - self._approvals.consume_approval( - approval_id, - run_id=run_id, - plan_id=plan_id, - device_id=device_id, - now=self._clock(), - ) - # AT-004: one active write run per device (single write lease, §6 docs/05). + # Checked BEFORE approval consumption so a lease conflict never burns a + # single-use human approval. for active in self._runs.list_active(device_id): if active.run_id != run_id and active.state not in (RunState.AWAITING_APPROVAL,): record.state = RunState.REJECTED @@ -927,6 +1211,38 @@ class AgentApplicationService: details={"run_id": run_id, "holder": active.run_id}, ) + if plan.approval_required: + if approval_id is None: + record.state = RunState.AWAITING_APPROVAL + self._runs.save(record) + raise RDKError( + ErrorCode.APPROVAL_REQUIRED, + f"plan {plan_id} requires human approval before start", + details={"run_id": run_id, "plan_id": plan_id}, + ) + # Atomic cross-process single-use consumption: the store serializes + # read→check→write under a per-approval lock (docs/05 §7, S1 收口). + # A failed consumption must not leave a non-terminal record holding + # the device write lease: reject the record fail-closed. + try: + self._approvals.consume_approval( + approval_id, + run_id=run_id, + plan_id=plan_id, + device_id=device_id, + now=self._clock(), + ) + except RDKError: + record.state = RunState.REJECTED + record.finished_at = self._clock() + record.error = RDKError( + ErrorCode.POLICY_DENIED, + "approval is not usable for this start", + details={"run_id": run_id, "approval_id": approval_id}, + ).to_body() + self._runs.save(record) + raise + ticket = sign_ticket( RunTicket( run_id=run_id, @@ -1728,6 +2044,17 @@ class AgentApplicationService: "requires": t.requires, "missing": missing, "runnable": not missing, + "fixture_capability": t.fixture_capability, + "parameters": [ + { + "name": p.name, + "unit": p.unit, + "min": p.min_value, + "max": p.max_value, + "description": p.description, + } + for p in t.parameters + ], } ) return out @@ -1866,30 +2193,72 @@ class AgentApplicationService: finally: connector.close() - def run_template(self, name: str, device_id: str, *, request_id: str) -> RunRecord: - """Materialize a reviewed template and run it deterministically.""" + def run_template( + self, + name: str, + device_id: str, + *, + request_id: str, + params: dict[str, float] | None = None, + ) -> dict[str, Any]: + """Materialize a reviewed template and run it deterministically. + + ALLOW (R0/R1) templates start immediately. REQUIRE_APPROVAL (R2, + ADR-017 motion) returns the pending approval instead of starting: + the human decides, then ``start_template`` consumes the approval. + Either way the full plan→policy→start pipeline is used — templates + never bypass policy. + """ from rdk_agent_core.policy import PolicyOutcome - from .templates import build_manifest, get_template + from .templates import build_manifest, get_template, render_params_json template = get_template(name) if template is None: raise RDKError(ErrorCode.INPUT_INVALID, f"unknown template {name!r}") + declaration = None + pack = None + if template.fixture_capability: + # Latest declaration whose accessory pack grants the capability. + for candidate in self._fixtures.for_device(device_id): + candidate_pack = self._accessories.get(candidate.pack_id) + if ( + candidate_pack is not None + and candidate.pack_version == candidate_pack.pack_version + and template.fixture_capability in candidate_pack.capabilities + ): + declaration, pack = candidate, candidate_pack + params_json = render_params_json(template, declaration, pack, dict(params or {})) + manifest = build_manifest(template) workspace_id = f"tpl-{name}-{request_id}" self.set_workspace_binding(workspace_id, device_id) workspace = self.workspace(workspace_id) workspace.write(template.source_relpath, template.source) - plan, decision = self.plan_run( - device_id, build_manifest(template), workspace_id=workspace_id + workspace.write("params.json", params_json) + plan, decision = self.plan_run(device_id, manifest, workspace_id=workspace_id) + if decision.outcome is PolicyOutcome.ALLOW: + record = self.start_run(request_id=request_id, plan_id=plan.plan_id) + return {"status": "started", "plan_id": plan.plan_id, "run": record} + if decision.outcome is PolicyOutcome.REQUIRE_APPROVAL: + pending = next(r for r in self._approvals.for_plan(plan.plan_id) if r.pending) + return { + "status": "approval_required", + "plan_id": plan.plan_id, + "approval_id": pending.approval_id, + "expires_at": pending.expires_at, + } + raise RDKError( + ErrorCode.POLICY_DENIED, + f"template {name!r} not allowed: {'; '.join(decision.reasons)}", + details={"category": "TEMPLATE_POLICY", "reasons": decision.reasons}, ) - if decision.outcome is not PolicyOutcome.ALLOW: - raise RDKError( - ErrorCode.POLICY_DENIED, - f"template {name!r} not allowed: {'; '.join(decision.reasons)}", - details={"category": "TEMPLATE_POLICY", "reasons": decision.reasons}, - ) - return self.start_run(request_id=request_id, plan_id=plan.plan_id) + + def start_template(self, *, plan_id: str, approval_id: str, request_id: str) -> RunRecord: + """Start an approved template run (ADR-017 second phase). Policy is + re-evaluated and the single-use approval consumed at start.""" + + return self.start_run(request_id=request_id, plan_id=plan_id, approval_id=approval_id) def run_pack( self, @@ -1928,7 +2297,10 @@ def build_application_service(config: HostConfig) -> AgentApplicationService: from .packs import FilePackStore from .stores import ( EventStore, + FileAccessoryLedgerStore, + FileAccessoryPackStore, FileApprovalStore, + FileFixtureStore, FileIdempotencyStore, FilePlanStore, FileRegistrationStore, @@ -1956,4 +2328,7 @@ def build_application_service(config: HostConfig) -> AgentApplicationService: verifications=FileVerificationStore(config.state_dir), registrations=FileRegistrationStore(config.state_dir), packs=FilePackStore(config.state_dir), + fixtures=FileFixtureStore(config.state_dir), + accessory_packs=FileAccessoryPackStore(config.state_dir), + accessory_ledgers=FileAccessoryLedgerStore(config.state_dir), ) diff --git a/packages/rdk_agent_host/src/rdk_agent_host/config.py b/packages/rdk_agent_host/src/rdk_agent_host/config.py index 9173479..3775fef 100644 --- a/packages/rdk_agent_host/src/rdk_agent_host/config.py +++ b/packages/rdk_agent_host/src/rdk_agent_host/config.py @@ -9,6 +9,7 @@ from collections.abc import Mapping from dataclasses import dataclass, field from pathlib import Path +from rdk_agent_core.fixtures import DEFAULT_R2_ALLOWLIST from rdk_agent_core.policy import ProjectPolicy from rdk_agent_core.tickets import FAKE_DEVICE_TICKET_KEY @@ -19,6 +20,13 @@ DEFAULT_RESPONSE_TIMEOUT_S = 30.0 DEFAULT_RUN_WAIT_WINDOW_S = 2.0 +def _default_project_policy() -> ProjectPolicy: + """Reviewed physical-output capabilities (ADR-017) are plannable by + default; they still require a human approval decision per run.""" + + return ProjectPolicy(r2_allowlist=list(DEFAULT_R2_ALLOWLIST)) + + @dataclass(frozen=True) class HostConfig: state_dir: Path @@ -28,7 +36,7 @@ class HostConfig: sim_command: tuple[str, ...] = ("rdk-agent-sim", "serve") device_id: str = "fake-001" ticket_key: bytes = FAKE_DEVICE_TICKET_KEY - project_policy: ProjectPolicy = field(default_factory=ProjectPolicy) + project_policy: ProjectPolicy = field(default_factory=_default_project_policy) response_timeout_s: float = DEFAULT_RESPONSE_TIMEOUT_S run_wait_window_s: float = DEFAULT_RUN_WAIT_WINDOW_S #: The ssh/ssh-keyscan binaries (OpenSSH). known_hosts is product-owned. @@ -72,16 +80,17 @@ class HostConfig: wait = float(wait_raw) if wait_raw else DEFAULT_RUN_WAIT_WINDOW_S key_raw = source.get("RDK_TICKET_KEY") ticket_key = binascii.unhexlify(key_raw.strip()) if key_raw else FAKE_DEVICE_TICKET_KEY - r2_allowlist = [ + extra = [ item.strip() for item in source.get("RDK_R2_ALLOWLIST", "").split(",") if item.strip() ] + r2_allowlist = list(dict.fromkeys([*DEFAULT_R2_ALLOWLIST, *extra])) return cls( state_dir=state_dir, device_command=command, sim_command=sim_command, device_id=source.get("RDK_DEVICE_ID", "fake-001"), ticket_key=ticket_key, - project_policy=ProjectPolicy(r2_allowlist=r2_allowlist), + project_policy=ProjectPolicy(r2_allowlist=r2_allowlist), # defaults merged above response_timeout_s=timeout, run_wait_window_s=wait, ssh_binary=source.get("RDK_SSH_BINARY", "ssh"), diff --git a/packages/rdk_agent_host/src/rdk_agent_host/data/accessory-packs/lekiwi-base.json b/packages/rdk_agent_host/src/rdk_agent_host/data/accessory-packs/lekiwi-base.json new file mode 100644 index 0000000..33b1cc8 --- /dev/null +++ b/packages/rdk_agent_host/src/rdk_agent_host/data/accessory-packs/lekiwi-base.json @@ -0,0 +1,26 @@ +{ + "schema_version": "1.0", + "pack_id": "lekiwi-base", + "pack_version": "1.0.0", + "origin": "reviewed", + "description": "LeKiwi three-omniwheel base (SIGRobotics-UIUC): Feetech STS3215 wheel servos in velocity mode, independent 12V supply; kill = unplug the battery connector (this assembly has no 12V switch). Wheels must be elevated (chassis airborne) for acceptance runs.", + "bus_protocol": "feetech-sts", + "capabilities": ["base.scan", "base.velocity.bounded"], + "servo_ids": [7, 8, 9], + "envelope": { + "max_linear_m_s": 0.1, + "max_angular_deg_s": 30.0, + "max_duration_ms": 3000 + }, + "wheel_radius_m": 0.05, + "base_radius_m": 0.125, + "max_raw_wheel_speed": 3000, + "wheel_angles_deg": [240.0, 0.0, 120.0], + "source": "LeRobot lekiwi robot definition (huggingface/lerobot, Apache-2.0): Motor ids 7/8/9 sts3215 velocity mode, wheel_radius 0.05, base_radius 0.125, raw cap 3000; JUXI LeKiwi tutorial (juxitech.feishu.cn/wiki/A2orwQ9xzidMCjk10SVcAAWVnhd): 12V servo supply, omniwheel servos need no calibration; real-device acceptance 2026-08-26 (docs/testing/evidence/LEKIWI-CHASSIS.md).", + "requirements": { + "serial_bus": true, + "camera": false, + "can_bus": false, + "lerobot": false + } +} diff --git a/packages/rdk_agent_host/src/rdk_agent_host/frames.py b/packages/rdk_agent_host/src/rdk_agent_host/frames.py index 28961a8..4e1e204 100644 --- a/packages/rdk_agent_host/src/rdk_agent_host/frames.py +++ b/packages/rdk_agent_host/src/rdk_agent_host/frames.py @@ -228,6 +228,45 @@ class PackRunParams(DomainModel): task_id: str | None = Field(default=None, max_length=128) +class TemplateListParams(DomainModel): + device_id: str = Field(min_length=1, max_length=128) + + +class TemplateRunParams(DomainModel): + """Run a reviewed template. Bounded numeric params only; fixture-bound + values (port/servo ids/envelope) are injected host-side (ADR-017). R2 + templates return a pending approval instead of starting.""" + + name: str = Field(min_length=1, max_length=128) + device_id: str = Field(min_length=1, max_length=128) + request_id: str = Field(min_length=1, max_length=128) + params: dict[str, float] = Field(default_factory=dict, max_length=16) + + +class TemplateStartParams(DomainModel): + """Second phase of an R2 template run: consume the human approval.""" + + plan_id: str = Field(min_length=1, max_length=256) + approval_id: str = Field(min_length=1, max_length=128) + request_id: str = Field(min_length=1, max_length=128) + + +class FixtureListParams(DomainModel): + device_id: str | None = Field(default=None, max_length=128) + + +class AccessoryRegistryParams(DomainModel): + """Registry x device facts: accessory recommendations (ADR-018). R0 facts.""" + + device_id: str = Field(min_length=1, max_length=128) + + +class AccessoryHistoryParams(DomainModel): + """Remembered accessory facts for a device (ADR-018). R0 facts.""" + + device_id: str = Field(min_length=1, max_length=128) + + AGENT_METHODS: dict[str, type[DomainModel] | None] = { "agent.ping": AgentPingParams, "device.list": DeviceListParams, @@ -255,6 +294,14 @@ AGENT_METHODS: dict[str, type[DomainModel] | None] = { "pack.save": PackSaveParams, "pack.list": PackListParams, "pack.run": PackRunParams, + # Reviewed templates (ADR-017): agent may list/run; R2 motion templates + # still require a human approval decision before template.start. + "template.list": TemplateListParams, + "template.run": TemplateRunParams, + "template.start": TemplateStartParams, + "fixture.list": FixtureListParams, + "accessory.registry": AccessoryRegistryParams, + "accessory.history": AccessoryHistoryParams, "workspace.list": WorkspaceListParams, "workspace.read": WorkspaceReadParams, "workspace.write": WorkspaceWriteParams, diff --git a/packages/rdk_agent_host/src/rdk_agent_host/human_frames.py b/packages/rdk_agent_host/src/rdk_agent_host/human_frames.py index d86c8c5..3a1b94b 100644 --- a/packages/rdk_agent_host/src/rdk_agent_host/human_frames.py +++ b/packages/rdk_agent_host/src/rdk_agent_host/human_frames.py @@ -8,6 +8,8 @@ allowlist mirrors the Pi tool surface and must never carry trust decisions from __future__ import annotations +from typing import Any + from pydantic import Field from rdk_agent_core.base import DomainModel @@ -97,14 +99,33 @@ class ApprovalDecideParams(DomainModel): reason: str = Field(default="", max_length=512) -class TemplateListParams(DomainModel): +class FixtureDeclareParams(DomainModel): + """Human-only: declare a reviewed safe hardware fixture (ADR-017). + + Agents cannot declare fixtures (registry gap -> PROTOCOL_VIOLATION). + Only reviewed packs are accepted; the serial node must later be observed + in a snapshot before any pack capability becomes available. + """ + device_id: str = Field(min_length=1, max_length=128) + pack_id: str = Field(min_length=1, max_length=64) + serial_node: str = Field(min_length=1, max_length=128) -class TemplateRunParams(DomainModel): - name: str = Field(min_length=1, max_length=128) - device_id: str = Field(min_length=1, max_length=128) - request_id: str = Field(min_length=1, max_length=128) +class FixtureRemoveParams(DomainModel): + fixture_id: str = Field(min_length=1, max_length=128) + + +class AccessoryPackCreateParams(DomainModel): + """Register a user-created accessory pack (ADR-018). The payload is + validated against AccessoryPack host-side (same model and absolute + ceilings as shipped packs; provenance required).""" + + pack: dict[str, Any] + + +class AccessoryPackRemoveParams(DomainModel): + pack_id: str = Field(min_length=1, max_length=64) #: method -> request params model for the human authority plane. @@ -125,8 +146,10 @@ HUMAN_METHODS: dict[str, type[DomainModel]] = { "flash.status": FlashStatusParams, "flash.cancel": FlashCancelParams, "approval.decide": ApprovalDecideParams, - "template.list": TemplateListParams, - "template.run": TemplateRunParams, + "fixture.declare": FixtureDeclareParams, + "fixture.remove": FixtureRemoveParams, + "accessory.pack.create": AccessoryPackCreateParams, + "accessory.pack.remove": AccessoryPackRemoveParams, } __all__ = ["HUMAN_METHODS"] + [name for name in dir() if name.endswith("Params")] diff --git a/packages/rdk_agent_host/src/rdk_agent_host/server.py b/packages/rdk_agent_host/src/rdk_agent_host/server.py index 9cd7550..8599178 100644 --- a/packages/rdk_agent_host/src/rdk_agent_host/server.py +++ b/packages/rdk_agent_host/src/rdk_agent_host/server.py @@ -30,6 +30,8 @@ from .config import HostConfig from .flashing_service import FlashingService, build_fake_flashing_service from .frames import ( AGENT_METHODS, + AccessoryHistoryParams, + AccessoryRegistryParams, AgentPingParams, ApprovalListParams, ApprovalRequestParams, @@ -40,6 +42,7 @@ from .frames import ( DeviceInspectParams, DeviceInventoryParams, DeviceListParams, + FixtureListParams, PackListParams, PackRunParams, PackSaveParams, @@ -56,6 +59,9 @@ from .frames import ( TaskReconcileParams, TaskReportParams, TaskShowParams, + TemplateListParams, + TemplateRunParams, + TemplateStartParams, WorkspaceCheckpointParams, WorkspaceDiffParams, WorkspaceExecParams, @@ -66,12 +72,16 @@ from .frames import ( ) from .human_frames import ( HUMAN_METHODS, + AccessoryPackCreateParams, + AccessoryPackRemoveParams, ApprovalDecideParams, DeviceAuthCheckParams, DeviceDiscoverParams, DeviceOnboardKeyParams, DeviceRegisterParams, DeviceUnregisterParams, + FixtureDeclareParams, + FixtureRemoveParams, FlashCancelParams, FlashConfirmParams, FlashImagesParams, @@ -82,8 +92,6 @@ from .human_frames import ( HostkeyShowParams, SerialPortsParams, SerialTailParams, - TemplateListParams, - TemplateRunParams, ) from .serial_console import SerialConsole, discover_serial_ports @@ -237,7 +245,40 @@ class AgentStdioServer: if isinstance(params, TemplateListParams): return {"templates": service.list_templates(params.device_id)} if isinstance(params, TemplateRunParams): - return service.run_template(params.name, params.device_id, request_id=params.request_id) + return service.run_template( + params.name, + params.device_id, + request_id=params.request_id, + params=params.params, + ) + if isinstance(params, TemplateStartParams): + return service.start_template( + plan_id=params.plan_id, + approval_id=params.approval_id, + request_id=params.request_id, + ) + if isinstance(params, FixtureListParams): + return {"fixtures": service.list_fixtures(params.device_id)} + if isinstance(params, FixtureDeclareParams): + return service.declare_fixture( + params.device_id, + params.pack_id, + params.serial_node, + actor=self._human_actor, + ) + if isinstance(params, FixtureRemoveParams): + service.remove_fixture(params.fixture_id) + return {"fixture_id": params.fixture_id, "removed": True} + if isinstance(params, AccessoryRegistryParams): + return {"packs": service.recommend_accessories(params.device_id)} + if isinstance(params, AccessoryHistoryParams): + return service.accessory_history(params.device_id) + if isinstance(params, AccessoryPackCreateParams): + pack = service.create_accessory_pack(params.pack, actor=self._human_actor) + return {"pack": pack, "created": True} + if isinstance(params, AccessoryPackRemoveParams): + service.remove_accessory_pack(params.pack_id) + return {"pack_id": params.pack_id, "removed": True} if isinstance(params, DeviceInventoryParams): snapshot, delta = service.inventory_device( params.device_id, diff --git a/packages/rdk_agent_host/src/rdk_agent_host/stores.py b/packages/rdk_agent_host/src/rdk_agent_host/stores.py index 68b0a91..18298dd 100644 --- a/packages/rdk_agent_host/src/rdk_agent_host/stores.py +++ b/packages/rdk_agent_host/src/rdk_agent_host/stores.py @@ -21,10 +21,12 @@ from pathlib import Path from typing import Protocol, TypeVar from pydantic import BaseModel +from rdk_agent_core.accessories import AccessoryLedger, AccessoryPack from rdk_agent_core.approvals import ApprovalRecord from rdk_agent_core.device import DeviceRegistration, DeviceSnapshot from rdk_agent_core.errors import ErrorCode, RDKError from rdk_agent_core.events import EventKind +from rdk_agent_core.fixtures import FixtureDeclaration from rdk_agent_core.plans import ExecutionPlan from rdk_agent_core.redaction import redact_value from rdk_agent_core.runs import RunManifest, RunRecord @@ -78,6 +80,17 @@ class ApprovalStore(Protocol): ) -> ApprovalRecord: ... +class FixtureStore(Protocol): + """Human-declared safe hardware fixtures (ADR-017).""" + + def save(self, declaration: FixtureDeclaration) -> None: ... + def get(self, fixture_id: str) -> FixtureDeclaration | None: ... + def list_all(self) -> list[FixtureDeclaration]: ... + def for_device(self, device_id: str) -> list[FixtureDeclaration]: ... + def active_for_device(self, device_id: str) -> FixtureDeclaration | None: ... + def remove(self, fixture_id: str) -> None: ... + + class TaskStore(Protocol): def save(self, task: AgentTask) -> None: ... def get(self, task_id: str) -> AgentTask | None: ... @@ -86,6 +99,24 @@ class TaskStore(Protocol): def get_checkpoint(self, checkpoint_id: str) -> Checkpoint | None: ... +class AccessoryPackStore(Protocol): + """User-created accessory packs (ADR-018): same model and absolute + ceilings as shipped packs, stored per machine.""" + + def save(self, pack: AccessoryPack) -> None: ... + def get(self, pack_id: str) -> AccessoryPack | None: ... + def list_all(self) -> list[AccessoryPack]: ... + def remove(self, pack_id: str) -> None: ... + + +class AccessoryLedgerStore(Protocol): + """Accessory memory per device (ADR-018): raw sightings (facts only) + plus declared pack references.""" + + def save(self, ledger: AccessoryLedger) -> None: ... + def get(self, device_id: str) -> AccessoryLedger | None: ... + + class IdempotencyStore(Protocol): """docs/03 §7, AT-004: atomic claim/complete per actor+operation+request. @@ -317,6 +348,84 @@ class FileApprovalStore: os.close(fd) +class FileFixtureStore: + """One JSON per fixture declaration under ``fixtures/`` (ADR-017).""" + + def __init__(self, root: Path) -> None: + self._dir = root / "fixtures" + self._dir.mkdir(parents=True, exist_ok=True) + + def save(self, declaration: FixtureDeclaration) -> None: + _write_json_atomic( + self._dir / f"{declaration.fixture_id}.json", + declaration.model_dump_json(indent=2), + ) + + def get(self, fixture_id: str) -> FixtureDeclaration | None: + result = _read_model(self._dir / f"{fixture_id}.json", FixtureDeclaration) + return result + + def list_all(self) -> list[FixtureDeclaration]: + declarations: list[FixtureDeclaration] = [] + for path in sorted(self._dir.glob("*.json")): + declaration = _read_model(path, FixtureDeclaration) + if declaration is not None: + declarations.append(declaration) + return declarations + + def for_device(self, device_id: str) -> list[FixtureDeclaration]: + return sorted( + (d for d in self.list_all() if d.device_id == device_id), + key=lambda d: d.declared_at, + ) + + def active_for_device(self, device_id: str) -> FixtureDeclaration | None: + declarations = self.for_device(device_id) + return declarations[-1] if declarations else None + + def remove(self, fixture_id: str) -> None: + (self._dir / f"{fixture_id}.json").unlink(missing_ok=True) + + +class FileAccessoryPackStore: + """One JSON per user accessory pack under ``accessory-packs/`` (ADR-018).""" + + def __init__(self, root: Path) -> None: + self._dir = root / "accessory-packs" + self._dir.mkdir(parents=True, exist_ok=True) + + def save(self, pack: AccessoryPack) -> None: + _write_json_atomic(self._dir / f"{pack.pack_id}.json", pack.model_dump_json(indent=2)) + + def get(self, pack_id: str) -> AccessoryPack | None: + return _read_model(self._dir / f"{pack_id}.json", AccessoryPack) + + def list_all(self) -> list[AccessoryPack]: + packs: list[AccessoryPack] = [] + for path in sorted(self._dir.glob("*.json")): + pack = _read_model(path, AccessoryPack) + if pack is not None: + packs.append(pack) + return packs + + def remove(self, pack_id: str) -> None: + (self._dir / f"{pack_id}.json").unlink(missing_ok=True) + + +class FileAccessoryLedgerStore: + """One JSON per device under ``accessories/`` (ADR-018).""" + + def __init__(self, root: Path) -> None: + self._dir = root / "accessories" + self._dir.mkdir(parents=True, exist_ok=True) + + def save(self, ledger: AccessoryLedger) -> None: + _write_json_atomic(self._dir / f"{ledger.device_id}.json", ledger.model_dump_json(indent=2)) + + def get(self, device_id: str) -> AccessoryLedger | None: + return _read_model(self._dir / f"{device_id}.json", AccessoryLedger) + + class FileTaskStore: def __init__(self, root: Path) -> None: self._dir = root / "tasks" @@ -673,6 +782,61 @@ class InMemoryApprovalStore: return record +class InMemoryFixtureStore: + def __init__(self) -> None: + self._data: dict[str, FixtureDeclaration] = {} + + def save(self, declaration: FixtureDeclaration) -> None: + self._data[declaration.fixture_id] = declaration + + def get(self, fixture_id: str) -> FixtureDeclaration | None: + return self._data.get(fixture_id) + + def list_all(self) -> list[FixtureDeclaration]: + return list(self._data.values()) + + def for_device(self, device_id: str) -> list[FixtureDeclaration]: + return sorted( + (d for d in self._data.values() if d.device_id == device_id), + key=lambda d: d.declared_at, + ) + + def active_for_device(self, device_id: str) -> FixtureDeclaration | None: + declarations = self.for_device(device_id) + return declarations[-1] if declarations else None + + def remove(self, fixture_id: str) -> None: + self._data.pop(fixture_id, None) + + +class InMemoryAccessoryPackStore: + def __init__(self) -> None: + self._data: dict[str, AccessoryPack] = {} + + def save(self, pack: AccessoryPack) -> None: + self._data[pack.pack_id] = pack + + def get(self, pack_id: str) -> AccessoryPack | None: + return self._data.get(pack_id) + + def list_all(self) -> list[AccessoryPack]: + return list(self._data.values()) + + def remove(self, pack_id: str) -> None: + self._data.pop(pack_id, None) + + +class InMemoryAccessoryLedgerStore: + def __init__(self) -> None: + self._data: dict[str, AccessoryLedger] = {} + + def save(self, ledger: AccessoryLedger) -> None: + self._data[ledger.device_id] = ledger + + def get(self, device_id: str) -> AccessoryLedger | None: + return self._data.get(device_id) + + class InMemoryTaskStore: def __init__(self) -> None: self._tasks: dict[str, AgentTask] = {} diff --git a/packages/rdk_agent_host/src/rdk_agent_host/templates.py b/packages/rdk_agent_host/src/rdk_agent_host/templates.py index 9a7b360..3e300b0 100644 --- a/packages/rdk_agent_host/src/rdk_agent_host/templates.py +++ b/packages/rdk_agent_host/src/rdk_agent_host/templates.py @@ -6,14 +6,27 @@ which makes these flows faster, cheaper and immune to model variance. Each template declares its capability requirements; ``suggest`` hard-filters by the device's observed snapshot capabilities (never guesses), explaining what is missing when a template cannot run (CFR-014 "为什么能做 / 还缺什么"). + +Parameterized templates (ADR-017): a template may declare bounded numeric +parameters. The host validates them against the reviewed envelope BEFORE +planning, materializes them as ``params.json`` next to the source (both enter +the source digest → run ticket binding), and the reviewed program re-validates +every value on-device (defense in depth). Fixture-bound values (port, servo +ids, envelope, kinematics) are injected by the host from the declared fixture +— never typed by users or models. """ # ruff: noqa: RUF001 # Chinese user-facing strings use full-width punctuation from __future__ import annotations +import json + from pydantic import Field +from rdk_agent_core.accessories import AccessoryPack from rdk_agent_core.base import DomainModel +from rdk_agent_core.errors import ErrorCode, RDKError +from rdk_agent_core.fixtures import FixtureDeclaration from rdk_agent_core.runs import ( ArtifactSpec, CapabilityRequirement, @@ -86,6 +99,510 @@ capability + lab fixture (hard-denied otherwise).""" print("gpio fixture required") ''' +# --------------------------------------------------------------------------- +# Feetech STS servo bus driver shared by the LeKiwi templates (reviewed code). +# Protocol framing per the Feetech SCS/STS serial spec as implemented by +# LeRobot's feetech bus (huggingface/lerobot, Apache-2.0); register addresses +# from LeRobot STS_SMS_SERIES_CONTROL_TABLE: Model_Number 3, Torque_Enable 40, +# Operating_Mode 33, Goal_Velocity 46, Present_Position 56, Present_Velocity +# 58, Present_Voltage 62 (0.1 V), Present_Temperature 63 (deg C). STS3215 +# Operating_Mode: 0 position, 1 constant-velocity (per the STS3215 manual). +# stdlib only (termios 1 Mbaud) — no packages are installed on the board. +# --------------------------------------------------------------------------- +_FEETECH_DRIVER = ''' +import fcntl, json, math, os, select, signal, sys, termios, time + +BAUD = termios.B1000000 +STEPS_PER_DEG = 4096.0 / 360.0 +REG_MODEL = (3, 2) +REG_OP_MODE = (33, 1) +REG_TORQUE = (40, 1) +REG_GOAL_VEL = (46, 2) +REG_PRESENT_POS = (56, 2) +REG_PRESENT_VEL = (58, 2) +REG_VOLTAGE = (62, 1) +REG_TEMP = (63, 1) +MODE_VELOCITY = 1 +OP_TIMEOUT_S = 0.3 +MAX_RETRIES = 2 +STOP_SETTLE_S = 0.15 +STOP_SAMPLES = 6 +STOP_TOLERANCE_RAW = 10 # ~0.9 deg/s read-back noise tolerance +STOP_GLITCH_LIMIT = 4096 # above any envelope-reachable wheel speed + + +class BusError(RuntimeError): + pass + + +class Bus: + """Half-duplex Feetech bus over a USB-CDC serial node (1 Mbaud, 8N1).""" + + def __init__(self, port, baud=BAUD): + self.fd = os.open(port, os.O_RDWR | os.O_NOCTTY) + self.raw_rx = 0 # bytes seen on the wire, parseable or not + self.recent = b"" # rolling raw capture for diagnostics + attrs = termios.tcgetattr(self.fd) + attrs[0] = 0 + attrs[1] = 0 + attrs[2] = termios.CS8 | termios.CLOCAL | termios.CREAD + attrs[3] = 0 + attrs[4] = baud + attrs[5] = baud + attrs[6][termios.VMIN] = 0 + attrs[6][termios.VTIME] = 1 + termios.tcsetattr(self.fd, termios.TCSANOW, attrs) + termios.tcflush(self.fd, termios.TCIOFLUSH) + # Assert DTR + RTS: many USB-CDC bus-servo adapters gate their TTL + # transceiver on these modem lines. pyserial (used by LeRobot) asserts + # both on open; a bare termios open leaves them low and the bus stays + # silent even when every servo is powered. + try: + fcntl.ioctl(self.fd, 0x5416, 0x002 | 0x004) # TIOCMBIS, DTR|RTS + except OSError: + pass # node without modem lines — keep going + + def set_speed(self, baud): + attrs = termios.tcgetattr(self.fd) + attrs[4] = baud + attrs[5] = baud + termios.tcsetattr(self.fd, termios.TCSANOW, attrs) + termios.tcflush(self.fd, termios.TCIOFLUSH) + self.raw_rx = 0 + self.recent = b"" + + def close(self): + try: + os.close(self.fd) + except OSError: + pass + + def _frame(self, servo_id, inst, params): + length = len(params) + 2 + body = bytes([servo_id, length, inst]) + bytes(params) + checksum = (~(servo_id + length + inst + sum(params))) & 0xFF + return b"\\xff\\xff" + body + bytes([checksum]) + + def _read_bytes(self, count, deadline): + buf = b"" + while len(buf) < count: + remaining = deadline - time.monotonic() + if remaining <= 0: + raise BusError("timeout waiting for bus response") + ready, _, _ = select.select([self.fd], [], [], min(remaining, 0.05)) + if ready: + chunk = os.read(self.fd, count - len(buf)) + if not chunk: + raise BusError("bus closed") + self.raw_rx += len(chunk) + self.recent = (self.recent + chunk)[-128:] + buf += chunk + return buf + + def _response(self, servo_id, deadline): + # Locate the frame header; tolerate leading noise bytes. + while True: + head = self._read_bytes(2, deadline) + if head == b"\\xff\\xff": + break + ident, length = self._read_bytes(2, deadline) + if ident != servo_id: + raise BusError(f"unexpected responder id {ident}") + if length < 2 or length > 64: + raise BusError(f"implausible frame length {length}") + # Status frame: FF FF ID LEN [ERR params...] CHK — LEN counts the + # ERR and CHK bytes themselves (Feetech / Dynamixel-protocol 1.0). + body = self._read_bytes(length, deadline) + checksum = body[-1] + expected = (~(ident + length + sum(body[:-1]))) & 0xFF + if checksum != expected: + raise BusError("checksum mismatch") + error = body[0] + if error & 0x01: + raise BusError(f"servo reported instruction error 0x{error:02x}") + return body[1:-1] + + def transact(self, servo_id, inst, params, retries=MAX_RETRIES): + frame = self._frame(servo_id, inst, params) + last = None + for _ in range(retries + 1): + try: + termios.tcflush(self.fd, termios.TCIFLUSH) + os.write(self.fd, frame) + termios.tcdrain(self.fd) + return self._response(servo_id, time.monotonic() + OP_TIMEOUT_S) + except BusError as exc: + last = exc + raise BusError(f"servo {servo_id} inst {inst} failed: {last}") + + def ping(self, servo_id): + """Model number when the reply carries one, else 0 for a bare ACK; + None only when the servo does not answer at all.""" + + try: + data = self.transact(servo_id, 0x01, b"") + except BusError: + return None + if len(data) >= 2: + return int.from_bytes(data[:2], "little") + return 0 # STS-series ping ACK carries no model payload + + def read(self, servo_id, reg): + addr, size = reg + data = self.transact(servo_id, 0x02, bytes([addr, size])) + if len(data) < size: + raise BusError(f"short read from servo {servo_id}") + value = int.from_bytes(data[:size], "little") + if size == 2 and value >= 0x8000: + value -= 0x10000 # signed registers (velocity) + return value + + def write(self, servo_id, reg, value): + addr, size = reg + raw = value.to_bytes(size, "little", signed=value < 0) + self.transact(servo_id, 0x03, bytes([addr]) + raw) + + +def load_params(): + with open("params.json", encoding="utf-8") as fh: + return json.load(fh) + + +def validate_common(params): + port = params.get("port") + servo_ids = params.get("servo_ids") + if not isinstance(port, str) or not port.startswith("/dev/"): + raise SystemExit("params: invalid port") + if ( + not isinstance(servo_ids, list) + or not servo_ids + or len(servo_ids) > 16 + or not all(isinstance(i, int) and 1 <= i <= 253 for i in servo_ids) + ): + raise SystemExit("params: invalid servo_ids") + return port, servo_ids +''' + +_LEKIWI_SCAN_SOURCE = ( + '''#!/usr/bin/env python3 +"""base-scan: bounded READ-ONLY discovery of an accessory servo bus. + +Reviewed template (ADR-017/018; pack facts injected by the host from the +declared accessory pack). Zero write commands: PING and +register reads only (AT-032). Exit codes: 0 all declared servos answer; +2 some declared servos missing; 3 nothing answers (12V supply likely off). +""" +''' + + _FEETECH_DRIVER + + """ +SCAN_RANGE = range(1, 13) # bounded sweep; LeKiwi wheels 7-9, optional arm 1-6 +# Read-only diagnostic: if nothing answers at the pack baud, try other common +# Feetech rates and report raw wire bytes so RX-path faults become visible. +FALLBACK_BAUDS = ( + (500000, termios.B500000), + (230400, termios.B230400), + (115200, termios.B115200), + (57600, termios.B57600), +) + + +def sweep(bus, ids): + found = {} + for sid in ids: + model = bus.ping(sid) + if model is not None: + found[sid] = model + return found, bus.raw_rx + + +def main(): + params = load_params() + port, servo_ids = validate_common(params) + bus = Bus(port) + servos = {} + baud_sweep = {} + probe_log = [] + try: + for sid in sorted(set(servo_ids) | set(SCAN_RANGE)): + before = bus.raw_rx + model = bus.ping(sid) + rx = bus.raw_rx - before + if rx or model is not None: + probe_log.append( + { + "id": sid, + "model": model, + "rx_bytes": rx, + "hex_tail": bus.recent[-16:].hex(), + } + ) + if model is None: + continue + entry = {"model": model, "present": True} + for key, reg in ( + ("model", REG_MODEL), + ("operating_mode", REG_OP_MODE), + ("position", REG_PRESENT_POS), + ("velocity_raw", REG_PRESENT_VEL), + ("voltage_v", REG_VOLTAGE), + ("temperature_c", REG_TEMP), + ): + try: + value = bus.read(sid, reg) + except BusError: + value = None + if value is None: + continue # keep ping-provided default where one exists + if key == "voltage_v": + value = round(value / 10.0, 1) + entry[key] = value + servos[str(sid)] = entry + if not servos: + baud_sweep["1000000"] = {"responding": [], "raw_rx_bytes": bus.raw_rx} + for rate, constant in FALLBACK_BAUDS: + bus.set_speed(constant) + found, raw = sweep(bus, sorted(set(servo_ids) | set(SCAN_RANGE))) + baud_sweep[str(rate)] = {"responding": sorted(found), "raw_rx_bytes": raw} + if found: + break # first answering rate is enough evidence + finally: + bus.close() + declared_missing = [i for i in servo_ids if str(i) not in servos] + ok = not declared_missing + result = { + "ok": ok, + "port": port, + "write_commands_sent": 0, + "declared_servo_ids": servo_ids, + "declared_missing": declared_missing, + "responding": sorted(int(k) for k in servos), + "servos": servos, + "probe_log": probe_log, + "baud_sweep": baud_sweep, + } + with open("bus_scan.json", "w", encoding="utf-8") as fh: + json.dump(result, fh, indent=2) + print(f"bus scan: responding={result['responding']} missing={declared_missing}") + if baud_sweep: + print(f"bus scan: no servo at pack baud; sweep={baud_sweep}") + if ok: + return 0 + return 3 if not servos else 2 + + +sys.exit(main()) +""" +) + +_LEKIWI_MOVE_SOURCE = ( + '''#!/usr/bin/env python3 +"""base-move: bounded omnidirectional velocity motion for a wheeled base. + +Reviewed template (ADR-017/018; pack facts injected by the host from the +declared accessory pack). Envelope checked here AND by +the host (params.json is host-generated from the pack data). Kinematics: +wheel mounting angles from the pack, minus 90 deg offset, +wheel radius / base radius / raw cap from the pack. Safe state: zero +Goal_Velocity on every wheel, confirmed by Present_Velocity read-back. +Exit codes: 0 moved and stopped confirmed; 2 envelope violation; 3 bus +unavailable (no motion attempted); 4 stop not confirmed (inspect the base). +""" +''' + + _FEETECH_DRIVER + + ''' +SEGMENT_S = 0.05 + + +def degps_to_raw(degps): + raw = int(round(degps * STEPS_PER_DEG)) + return max(-32768, min(32767, raw)) + + +def body_to_wheel_raw(vx, vy, omega_deg_s, kin): + """Three-omniwheel inverse kinematics; wheel mounting angles come from + the accessory pack data (params.json), never from this program.""" + + wheel_radius = kin["wheel_radius_m"] + base_radius = kin["base_radius_m"] + max_raw = kin["max_raw"] + omega_rad = math.radians(omega_deg_s) + raws = [] + for angle_deg in kin["wheel_angles_deg"]: + angle = math.radians(angle_deg - 90.0) + linear = math.cos(angle) * vx + math.sin(angle) * vy + base_radius * omega_rad + angular_deg_s = (linear / wheel_radius) * (180.0 / math.pi) + raws.append(angular_deg_s) + peak = max(abs(r) * STEPS_PER_DEG for r in raws) + if peak > max_raw: + scale = max_raw / peak + raws = [r * scale for r in raws] + return [degps_to_raw(r) for r in raws] + + +def main(): + params = load_params() + port, servo_ids = validate_common(params) + motion = params.get("motion") or {} + envelope = params.get("envelope") or {} + kin = params.get("kinematics") or {} + try: + vx = float(motion["vx"]) + vy = float(motion["vy"]) + omega = float(motion["omega_deg_s"]) + duration_ms = int(motion["duration_ms"]) + max_linear = float(envelope["max_linear_m_s"]) + max_angular = float(envelope["max_angular_deg_s"]) + max_duration = int(envelope["max_duration_ms"]) + kin_values = ( + float(kin["wheel_radius_m"]), + float(kin["base_radius_m"]), + int(kin["max_raw"]), + ) + wheel_angles = [float(a) for a in kin["wheel_angles_deg"]] + if len(wheel_angles) != len(servo_ids): + print("params: wheel_angles_deg must match servo_ids length") + return 2 + kin["wheel_angles_deg"] = wheel_angles + except (KeyError, TypeError, ValueError): + print("params: malformed motion/envelope/kinematics") + return 2 + # Defense in depth: the host validated these too; refuse anyway. + if not (abs(vx) <= max_linear and abs(vy) <= max_linear and abs(omega) <= max_angular): + print(f"envelope violation: vx={vx} vy={vy} omega={omega}") + return 2 + if not (100 <= duration_ms <= max_duration): + print(f"envelope violation: duration_ms={duration_ms}") + return 2 + kin = { + "wheel_radius_m": kin_values[0], + "base_radius_m": kin_values[1], + "max_raw": kin_values[2], + "wheel_angles_deg": wheel_angles, + } + + bus = Bus(port) + config_writes = [] + stop_state = {"done": False} + + def stop(reason): + if stop_state["done"]: + return + stop_state["done"] = True + for sid in servo_ids: + for _ in range(MAX_RETRIES + 1): + try: + bus.write(sid, REG_GOAL_VEL, 0) + break + except BusError: + continue + print(f"stop: wrote zero velocity to wheels ({reason})") + + def handle_signal(signum, _frame): + stop(f"signal {signum}") + raise SystemExit(120 + signum) + + exit_code = 4 + result = { + "ok": False, + "port": port, + "commanded": {"vx": vx, "vy": vy, "omega_deg_s": omega, "duration_ms": duration_ms}, + "envelope": { + "max_linear_m_s": max_linear, + "max_angular_deg_s": max_angular, + "max_duration_ms": max_duration, + }, + "servo_ids": servo_ids, + "config_writes": config_writes, + "wheel_raw": [], + "final_velocity_raw": {}, + "max_abs_final_velocity": None, + "stop_confirmed": False, + } + try: + signal.signal(signal.SIGTERM, handle_signal) + signal.signal(signal.SIGINT, handle_signal) + # Every declared wheel must answer before any motion. + for sid in servo_ids: + if bus.ping(sid) is None: + print(f"servo {sid} does not answer; aborting before motion (12V?)") + return 3 + mode = bus.read(sid, REG_OP_MODE) + if mode != MODE_VELOCITY: + bus.write(sid, REG_TORQUE, 0) + bus.write(sid, REG_OP_MODE, MODE_VELOCITY) + config_writes.append({"servo": sid, "action": "operating_mode=velocity"}) + torque = bus.read(sid, REG_TORQUE) + if torque != 1: + bus.write(sid, REG_TORQUE, 1) + config_writes.append({"servo": sid, "action": "torque_enable"}) + raws = body_to_wheel_raw(vx, vy, omega, kin) + result["wheel_raw"] = raws + for sid, raw in zip(servo_ids, raws): + bus.write(sid, REG_GOAL_VEL, raw) + deadline = time.monotonic() + duration_ms / 1000.0 + while time.monotonic() < deadline: + time.sleep(SEGMENT_S) + stop("duration elapsed") + # Stop confirmation by convergence: two consecutive samples of every + # wheel inside tolerance. Envelope-bound reasoning: the largest wheel + # command this template can emit is ~1400 raw at full envelope, so any + # read-back above STOP_GLITCH_LIMIT cannot be real wheel speed — it is + # a half-duplex parse artifact and gets re-sampled, never failed on. + samples = [] + consecutive_ok = 0 + stop_confirmed = False + for _ in range(STOP_SAMPLES): + time.sleep(STOP_SETTLE_S) + sample = {} + for sid in servo_ids: + try: + sample[sid] = bus.read(sid, REG_PRESENT_VEL) + except BusError: + sample[sid] = None + samples.append(sample) + usable = [abs(v) for v in sample.values() if v is not None] + if len(usable) != len(servo_ids): + consecutive_ok = 0 + continue + if max(usable) <= STOP_TOLERANCE_RAW: + consecutive_ok += 1 + if consecutive_ok >= 2: + stop_confirmed = True + break + elif max(usable) <= STOP_GLITCH_LIMIT: + consecutive_ok = 0 + # above glitch limit: keep prior consecutive count, re-sample + result["stop_samples"] = samples + finals = samples[-1] if samples else {} + result["final_velocity_raw"] = finals + readable = [abs(v) for v in finals.values() if v is not None] + if readable and len(readable) == len(servo_ids): + result["max_abs_final_velocity"] = max(readable) + result["stop_confirmed"] = stop_confirmed + result["ok"] = stop_confirmed + exit_code = 0 if stop_confirmed else 4 + return exit_code + finally: + stop("finalizer") + with open("motion.json", "w", encoding="utf-8") as fh: + json.dump(result, fh, indent=2) + bus.close() + + +sys.exit(main()) +''' +) + + +class TemplateParameter(DomainModel): + """One bounded numeric input (ADR-017). Host validates before planning.""" + + name: str = Field(min_length=1, max_length=64, pattern=r"^[a-z][a-z0-9_]*$") + unit: str = Field(default="", max_length=32) + min_value: float + max_value: float + description: str = Field(default="", max_length=256) + class Template(DomainModel): name: str = Field(min_length=1, max_length=128) @@ -97,6 +614,15 @@ class Template(DomainModel): artifact_name: str = Field(min_length=1, max_length=128) artifact_path: str = Field(min_length=1, max_length=256) assert_path: str = Field(min_length=1, max_length=256) + #: Bounded user parameters (ADR-017). Empty for zero-input templates. + parameters: list[TemplateParameter] = Field(default_factory=list, max_length=16) + #: Generic fixture capability this template is bound to (None = none). + #: The host resolves the device's active declaration whose accessory pack + #: (data, ADR-018) grants this capability, and injects port/servo + #: ids/envelope/kinematics from that pack. + fixture_capability: str | None = Field(default=None, max_length=64) + #: Additional verifiers beyond the shared exit-ok/exit-recorded pair. + extra_verifiers: list[VerifierSpec] = Field(default_factory=list) TEMPLATES: list[Template] = [ @@ -133,6 +659,115 @@ TEMPLATES: list[Template] = [ artifact_path="blink.json", assert_path="ok", ), + Template( + name="base-scan", + title="底盘探查(配件总线)", + description=( + "只读探查底盘舵机总线:谁在线、电压、温度、模式(零写指令)。" + "需要已声明的配件包(工装)。" + ), + requires=["base.scan"], + source_relpath="base_scan.py", + source=_LEKIWI_SCAN_SOURCE, + artifact_name="bus_scan.json", + artifact_path="bus_scan.json", + assert_path="ok", + fixture_capability="base.scan", + extra_verifiers=[ + VerifierSpec( + id="scan-ok", + type="json.assert", + config={"artifact": "bus_scan.json", "path": "ok", "equals": True}, + ), + VerifierSpec( + id="scan-zero-writes", + type="json.assert", + config={"artifact": "bus_scan.json", "path": "write_commands_sent", "equals": 0}, + ), + ], + ), + Template( + name="base-move", + title="底盘微动(配件包络)", + description=( + "按已声明配件包的包络限时移动底盘(全向速度模式),到时自动停止并回读确认。" + "每次运行需人工批准;验收时轮子必须架空。" + ), + requires=["base.velocity.bounded"], + source_relpath="base_move.py", + source=_LEKIWI_MOVE_SOURCE, + artifact_name="motion.json", + artifact_path="motion.json", + assert_path="stop_confirmed", + parameters=[ + TemplateParameter( + name="vx", + unit="m/s", + min_value=-0.5, + max_value=0.5, + description="前后速度(正=前);实际以配件包包络为准", + ), + TemplateParameter( + name="vy", + unit="m/s", + min_value=-0.5, + max_value=0.5, + description="横移速度(正=左);实际以配件包包络为准", + ), + TemplateParameter( + name="omega_deg_s", + unit="deg/s", + min_value=-120.0, + max_value=120.0, + description="旋转速度(正=逆时针);实际以配件包包络为准", + ), + TemplateParameter( + name="duration_ms", + unit="ms", + min_value=100, + max_value=10000.0, + description="运动时长,到时自动停;实际以配件包包络为准", + ), + ], + fixture_capability="base.velocity.bounded", + extra_verifiers=[ + VerifierSpec( + id="stop-confirmed", + type="json.assert", + config={"artifact": "motion.json", "path": "stop_confirmed", "equals": True}, + ), + VerifierSpec( + id="final-velocity-zero", + type="json.range", + config={ + "artifact": "motion.json", + "path": "max_abs_final_velocity", + "min": 0, + "max": 10, + }, + ), + VerifierSpec( + id="commanded-vx-in-envelope", + type="json.range", + config={ + "artifact": "motion.json", + "path": "commanded.vx", + "min": -0.5, + "max": 0.5, + }, + ), + VerifierSpec( + id="commanded-duration-in-envelope", + type="json.range", + config={ + "artifact": "motion.json", + "path": "commanded.duration_ms", + "min": 100, + "max": 10000, + }, + ), + ], + ), ] @@ -153,7 +788,7 @@ def build_manifest(t: Template) -> RunManifest: name=t.artifact_name, path=t.artifact_path, media_type="application/json", - required=False, + required=bool(t.fixture_capability), ) ], verifiers=[ @@ -166,5 +801,137 @@ def build_manifest(t: Template) -> RunManifest: type="json.assert", config={"artifact": "result.json", "path": "exit_code", "equals": 0}, ), + *t.extra_verifiers, ], ) + + +#: params.json keys the host fills from the declared fixture; users/models can +#: never supply them (ADR-017). +FIXTURE_RESERVED_KEYS = ("port", "servo_ids", "envelope", "kinematics") + + +def validate_template_params(template: Template, user_params: dict[str, float]) -> dict[str, float]: + """Envelope-check user parameters (ADR-017): every declared parameter is + required, numeric and within the reviewed bounds. Anything else rejects + before planning.""" + + reserved = set(user_params) & set(FIXTURE_RESERVED_KEYS) + if reserved: + raise RDKError( + ErrorCode.INPUT_INVALID, + f"parameters {sorted(reserved)} are fixture-bound and cannot be supplied", + ) + known = {p.name: p for p in template.parameters} + unknown = sorted(set(user_params) - set(known)) + if unknown: + raise RDKError(ErrorCode.INPUT_INVALID, f"unknown template parameters: {unknown}") + missing = sorted(set(known) - set(user_params)) + if missing: + raise RDKError(ErrorCode.INPUT_INVALID, f"missing template parameters: {missing}") + out: dict[str, float] = {} + for name, spec in known.items(): + value = user_params[name] + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise RDKError(ErrorCode.INPUT_INVALID, f"parameter {name} must be a number") + if not (spec.min_value <= float(value) <= spec.max_value): + raise RDKError( + ErrorCode.INPUT_INVALID, + f"parameter {name}={value} outside envelope " + f"[{spec.min_value}, {spec.max_value}] {spec.unit}".rstrip(), + ) + out[name] = float(value) + return out + + +def fixture_params( + template: Template, declaration: FixtureDeclaration, pack: AccessoryPack | None +) -> dict[str, object]: + """Fixture-bound params.json values; host-only, never user input.""" + + if ( + template.fixture_capability is None + or pack is None + or template.fixture_capability not in pack.capabilities + or pack.pack_id != declaration.pack_id + or pack.pack_version != declaration.pack_version + ): + raise RDKError( + ErrorCode.INPUT_INVALID, + f"template {template.name!r} is not bound to the declared accessory pack", + ) + return { + "port": declaration.serial_node, + "servo_ids": list(pack.servo_ids), + "envelope": { + "max_linear_m_s": pack.envelope.max_linear_m_s, + "max_angular_deg_s": pack.envelope.max_angular_deg_s, + "max_duration_ms": pack.envelope.max_duration_ms, + }, + "kinematics": { + "wheel_radius_m": pack.wheel_radius_m, + "base_radius_m": pack.base_radius_m, + "max_raw": pack.max_raw_wheel_speed, + "wheel_angles_deg": list(pack.wheel_angles_deg), + }, + } + + +def _check_pack_envelope(pack: AccessoryPack, motion: dict[str, float]) -> None: + """Pack-level envelope gate (ADR-018): template params are bounded by the + product ceilings; the declared pack's own envelope is tighter or equal and + is enforced here before planning, and again in-program and by verifiers.""" + + env = pack.envelope + checks = ( + ("vx", abs(motion.get("vx", 0.0)), env.max_linear_m_s, "m/s"), + ("vy", abs(motion.get("vy", 0.0)), env.max_linear_m_s, "m/s"), + ("omega_deg_s", abs(motion.get("omega_deg_s", 0.0)), env.max_angular_deg_s, "deg/s"), + ) + for name, value, limit, unit in checks: + if value > limit: + raise RDKError( + ErrorCode.INPUT_INVALID, + f"parameter {name}={motion.get(name)} outside envelope " + f"[-{limit}, {limit}] {unit} of pack {pack.pack_id}", + ) + duration = int(motion.get("duration_ms", 0)) + if duration > env.max_duration_ms: + raise RDKError( + ErrorCode.INPUT_INVALID, + f"parameter duration_ms={duration} outside envelope " + f"[100, {env.max_duration_ms}] ms of pack {pack.pack_id}", + ) + + +def render_params_json( + template: Template, + declaration: FixtureDeclaration | None, + pack: AccessoryPack | None, + user_params: dict[str, float], +) -> str: + payload: dict[str, object] = {} + if template.fixture_capability is not None: + if declaration is None or pack is None: + raise RDKError( + ErrorCode.INPUT_INVALID, + f"template {template.name!r} requires a declared accessory pack " + f"granting {template.fixture_capability!r}; none is active for this device", + ) + payload.update(fixture_params(template, declaration, pack)) + motion = validate_template_params(template, user_params) + if motion: + _check_pack_envelope(pack, motion) + payload["motion"] = { + "vx": motion.get("vx", 0.0), + "vy": motion.get("vy", 0.0), + "omega_deg_s": motion.get("omega_deg_s", 0.0), + "duration_ms": int(motion.get("duration_ms", 0)), + } + else: + if user_params: + raise RDKError( + ErrorCode.INPUT_INVALID, + f"template {template.name!r} takes no parameters", + ) + return json.dumps(payload, indent=2, sort_keys=True) diff --git a/packages/rdk_agent_host/src/rdk_agent_host/verifiers.py b/packages/rdk_agent_host/src/rdk_agent_host/verifiers.py index 1f03547..a2f4445 100644 --- a/packages/rdk_agent_host/src/rdk_agent_host/verifiers.py +++ b/packages/rdk_agent_host/src/rdk_agent_host/verifiers.py @@ -6,6 +6,8 @@ M0 verifier types: - ``json.assert``: assert a JSON artifact field equals a value (config: ``{artifact, path, equals}``; ``path`` is a dotted key). +- ``json.range``: assert a numeric JSON artifact field lies in ``[min, max]`` + (config: ``{artifact, path, min, max}``; ADR-017 envelope/safe-state checks). - ``exit_code.zero``: assert the run's recorded process exit code is 0. """ @@ -27,6 +29,7 @@ from rdk_agent_core.verification import ( VERIFIER_VERSIONS = { "json.assert": "1.0.0", + "json.range": "1.0.0", "exit_code.zero": "1.0.0", "encoder.stopped": "1.0.0", "gripper.closed": "1.0.0", @@ -190,6 +193,60 @@ def run_verifier( ], ) + # json.range: numeric field within [min, max] (ADR-017 envelope and + # safe-state read-back checks; host-side judgment over device evidence). + if spec.type == "json.range": + artifact_name = str(spec.config.get("artifact", "")) + path = str(spec.config.get("path", "")) + low = float(spec.config.get("min", 0.0)) + high = float(spec.config.get("max", 0.0)) + content = fetch_artifact(artifact_name) + if content is None: + return finish( + VerificationStatus.NOT_RUN, + [ + AssertionResult( + id=f"{spec.id}.evidence", + status=AssertionStatus.NOT_RUN, + expected=f"artifact {artifact_name!r} present", + actual="missing", + ) + ], + ) + try: + payload = json.loads(content.decode("utf-8")) + actual = _dig(payload, path) + if isinstance(actual, bool) or not isinstance(actual, (int, float)): + raise ValueError(f"non-numeric value {actual!r}") + except (json.JSONDecodeError, UnicodeDecodeError, KeyError, ValueError) as exc: + return finish( + VerificationStatus.ERROR, + [ + AssertionResult( + id=f"{spec.id}.parse", + status=AssertionStatus.ERROR, + expected=f"numeric JSON at {path!r}", + actual=type(exc).__name__ + if not str(exc).startswith("non-numeric") + else str(exc), + evidence_refs=[f"artifact:{artifact_name}"], + ) + ], + ) + ok = low <= float(actual) <= high + return finish( + VerificationStatus.PASS if ok else VerificationStatus.FAIL, + [ + AssertionResult( + id=f"{spec.id}.range", + status=AssertionStatus.PASS if ok else AssertionStatus.FAIL, + expected=f"{low} <= {path} <= {high}", + actual=str(actual), + evidence_refs=[f"artifact:{artifact_name}"], + ) + ], + ) + # json.assert artifact_name = str(spec.config.get("artifact", "")) path = str(spec.config.get("path", "")) diff --git a/schemas/accessory-pack.schema.json b/schemas/accessory-pack.schema.json new file mode 100644 index 0000000..1391bbf --- /dev/null +++ b/schemas/accessory-pack.schema.json @@ -0,0 +1,204 @@ +{ + "$defs": { + "AccessoryRequirements": { + "description": "Device facts an accessory needs, for recommendation (never for grants).\n\nMatching these against a snapshot only produces \"could attach\" advice;\ncapabilities only appear through a human fixture declaration (ADR-018).", + "properties": { + "camera": { + "default": false, + "title": "Camera", + "type": "boolean" + }, + "can_bus": { + "default": false, + "title": "Can Bus", + "type": "boolean" + }, + "lerobot": { + "default": false, + "title": "Lerobot", + "type": "boolean" + }, + "schema_version": { + "default": "1.0", + "pattern": "^\\d+\\.\\d+$", + "title": "Schema Version", + "type": "string" + }, + "serial_bus": { + "default": false, + "title": "Serial Bus", + "type": "boolean" + } + }, + "title": "AccessoryRequirements", + "type": "object" + }, + "BusProtocol": { + "description": "Controlled enum: selects the protocol driver, never a product.", + "enum": [ + "feetech-sts" + ], + "title": "BusProtocol", + "type": "string" + }, + "MotionEnvelope": { + "description": "Hard motion bounds for one accessory pack (ADR-012 \u00a75 parameter envelope).\n\nThe ``le=`` constraints are PRODUCT ABSOLUTE CEILINGS: no pack, shipped or\nuser-created, may exceed them. Enforced three times: host-side before\nplanning, inside the reviewed template program, and by the host verifier\nover read-back evidence.", + "properties": { + "max_angular_deg_s": { + "exclusiveMinimum": 0.0, + "maximum": 120.0, + "title": "Max Angular Deg S", + "type": "number" + }, + "max_duration_ms": { + "exclusiveMinimum": 0, + "maximum": 10000, + "title": "Max Duration Ms", + "type": "integer" + }, + "max_linear_m_s": { + "exclusiveMinimum": 0.0, + "maximum": 0.5, + "title": "Max Linear M S", + "type": "number" + }, + "schema_version": { + "default": "1.0", + "pattern": "^\\d+\\.\\d+$", + "title": "Schema Version", + "type": "string" + } + }, + "required": [ + "max_linear_m_s", + "max_angular_deg_s", + "max_duration_ms" + ], + "title": "MotionEnvelope", + "type": "object" + }, + "PackOrigin": { + "enum": [ + "reviewed", + "user" + ], + "title": "PackOrigin", + "type": "string" + } + }, + "$id": "https://rdk.dev/schemas/accessory-pack.schema.json", + "description": "One accessory record \u2014 data, not code (ADR-018).", + "properties": { + "base_radius_m": { + "exclusiveMinimum": 0.0, + "maximum": 2.0, + "title": "Base Radius M", + "type": "number" + }, + "bus_protocol": { + "$ref": "#/$defs/BusProtocol", + "default": "feetech-sts" + }, + "capabilities": { + "items": { + "type": "string" + }, + "maxItems": 8, + "minItems": 1, + "title": "Capabilities", + "type": "array" + }, + "description": { + "default": "", + "maxLength": 512, + "title": "Description", + "type": "string" + }, + "envelope": { + "$ref": "#/$defs/MotionEnvelope" + }, + "max_raw_wheel_speed": { + "exclusiveMinimum": 0, + "maximum": 32767, + "title": "Max Raw Wheel Speed", + "type": "integer" + }, + "origin": { + "$ref": "#/$defs/PackOrigin", + "default": "reviewed" + }, + "pack_id": { + "maxLength": 64, + "minLength": 1, + "title": "Pack Id", + "type": "string" + }, + "pack_version": { + "maxLength": 32, + "minLength": 1, + "title": "Pack Version", + "type": "string" + }, + "requirements": { + "$ref": "#/$defs/AccessoryRequirements" + }, + "schema_version": { + "default": "1.0", + "pattern": "^\\d+\\.\\d+$", + "title": "Schema Version", + "type": "string" + }, + "servo_ids": { + "items": { + "type": "integer" + }, + "maxItems": 16, + "minItems": 1, + "title": "Servo Ids", + "type": "array" + }, + "source": { + "maxLength": 512, + "minLength": 1, + "title": "Source", + "type": "string" + }, + "wheel_angles_deg": { + "maxItems": 3, + "minItems": 3, + "prefixItems": [ + { + "type": "number" + }, + { + "type": "number" + }, + { + "type": "number" + } + ], + "title": "Wheel Angles Deg", + "type": "array" + }, + "wheel_radius_m": { + "exclusiveMinimum": 0.0, + "maximum": 1.0, + "title": "Wheel Radius M", + "type": "number" + } + }, + "required": [ + "pack_id", + "pack_version", + "capabilities", + "servo_ids", + "envelope", + "wheel_radius_m", + "base_radius_m", + "max_raw_wheel_speed", + "wheel_angles_deg", + "source" + ], + "title": "AccessoryPack", + "type": "object" +} diff --git a/schemas/fixture-declaration.schema.json b/schemas/fixture-declaration.schema.json new file mode 100644 index 0000000..d49aedc --- /dev/null +++ b/schemas/fixture-declaration.schema.json @@ -0,0 +1,112 @@ +{ + "$defs": { + "ActorKind": { + "enum": [ + "user", + "agent", + "external_agent", + "device", + "supervisor", + "system" + ], + "title": "ActorKind", + "type": "string" + }, + "ActorRef": { + "properties": { + "id": { + "maxLength": 128, + "minLength": 1, + "title": "Id", + "type": "string" + }, + "kind": { + "$ref": "#/$defs/ActorKind" + }, + "schema_version": { + "default": "1.0", + "pattern": "^\\d+\\.\\d+$", + "title": "Schema Version", + "type": "string" + } + }, + "required": [ + "kind", + "id" + ], + "title": "ActorRef", + "type": "object" + } + }, + "$id": "https://rdk.dev/schemas/fixture-declaration.schema.json", + "description": "A human-declared accessory attachment on a registered device.\n\nThe declaration alone never executes anything: it only lets the host\noverlay the declared pack's capabilities onto snapshots whose observed\nperipherals contain the declared serial node (docs/03 \u00a72.2.2, ADR-017).\nThe pack itself is resolved against the accessory registry (ADR-018).", + "properties": { + "declared_at": { + "format": "date-time", + "title": "Declared At", + "type": "string" + }, + "declared_by": { + "$ref": "#/$defs/ActorRef" + }, + "device_id": { + "maxLength": 128, + "minLength": 1, + "title": "Device Id", + "type": "string" + }, + "fixture_id": { + "maxLength": 128, + "minLength": 1, + "title": "Fixture Id", + "type": "string" + }, + "kill_method": { + "default": "unplug the battery connector (this assembly has no 12V switch)", + "maxLength": 256, + "title": "Kill Method", + "type": "string" + }, + "orientation": { + "default": "elevated-wheels-free", + "maxLength": 64, + "title": "Orientation", + "type": "string" + }, + "pack_id": { + "maxLength": 64, + "minLength": 1, + "title": "Pack Id", + "type": "string" + }, + "pack_version": { + "maxLength": 32, + "minLength": 1, + "title": "Pack Version", + "type": "string" + }, + "schema_version": { + "default": "1.0", + "pattern": "^\\d+\\.\\d+$", + "title": "Schema Version", + "type": "string" + }, + "serial_node": { + "maxLength": 128, + "minLength": 1, + "pattern": "^/dev/[A-Za-z0-9_.-]+$", + "title": "Serial Node", + "type": "string" + } + }, + "required": [ + "pack_id", + "pack_version", + "device_id", + "serial_node", + "declared_by", + "declared_at" + ], + "title": "FixtureDeclaration", + "type": "object" +} diff --git a/scripts/drive_lekiwi_hil.py b/scripts/drive_lekiwi_hil.py new file mode 100644 index 0000000..f2fb811 --- /dev/null +++ b/scripts/drive_lekiwi_hil.py @@ -0,0 +1,465 @@ +#!/usr/bin/env python3 +"""LeKiwi chassis real-device acceptance (AT-032/AT-033, ADR-017). + +Drives the PRODUCTION path on the real S100P + LeKiwi base: + + human plane: device.inspect --refresh full, fixture.declare/remove, + approval.decide + agent plane: template.list, template.run (scan auto / motion gated), + template.start, fixture.declare MUST be refused + +Fixture preconditions (HIL_LAB_SPEC §5A): chassis elevated (wheels free), +12V supply with a manual switch at hand, operator present. + +Env: + RDK_DEVICE_HOST board ssh target (default sunrise@192.168.127.10) + RDK_DEVICE_ID registered device id (default dev-a8c54ad11e5d41c2) + RDK_TICKET_KEY hex HMAC key — must match the board's ~/.rdk/ticket_key + RDK_STATE_DIR product state dir (default /tmp/rdk-s1c-gui-state) + RDK_LEKIWI_EVIDENCE output dir (default docs/testing/evidence/lekiwi-chassis) +""" + +from __future__ import annotations + +import json +import os +import sys +import threading +import time +from datetime import datetime, timezone +from pathlib import Path + +from rdk_agent_core.base import ActorKind, ActorRef +from rdk_agent_core.frames import make_request +from rdk_agent_host.application import AGENT_ACTOR_ID, AgentApplicationService +from rdk_agent_host.config import HostConfig +from rdk_agent_host.server import AgentStdioServer +from rdk_agent_host.ssh_connector import SshDeviceConnector +from rdk_agent_host.stores import ( + EventStore, + FileApprovalStore, + FileFixtureStore, + FileIdempotencyStore, + FilePlanStore, + FileRegistrationStore, + FileRunStore, + FileSnapshotStore, + FileTaskStore, + FileVerificationStore, +) + +HOST = os.environ.get("RDK_DEVICE_HOST", "sunrise@192.168.127.10") +DEVICE_ID = os.environ.get("RDK_DEVICE_ID", "dev-a8c54ad11e5d41c2") +STATE_DIR = Path(os.environ.get("RDK_STATE_DIR", "/tmp/rdk-s1c-gui-state")) +EVIDENCE_DIR = Path(os.environ.get("RDK_LEKIWI_EVIDENCE", "docs/testing/evidence/lekiwi-chassis")) + +RESULTS: list[dict] = [] + + +def record(step: str, **fields: object) -> None: + entry = {"step": step, **fields} + RESULTS.append(entry) + print(json.dumps(entry, ensure_ascii=False), flush=True) + + +def build_service() -> AgentApplicationService: + key_raw = os.environ.get("RDK_TICKET_KEY", "") + if not key_raw: + raise SystemExit( + "RDK_TICKET_KEY (hex) is required — read it from the board's ~/.rdk/ticket_key" + ) + ticket_key = bytes.fromhex(key_raw.strip()) + config = HostConfig( + state_dir=STATE_DIR, + device_command=("true",), # unused: SSH connector injected below + device_id=DEVICE_ID, + ticket_key=ticket_key, + response_timeout_s=45.0, + run_wait_window_s=120.0, + ) + connector = SshDeviceConnector( + host=HOST, + device_id=DEVICE_ID, + known_hosts=config.known_hosts, + actor=ActorRef(kind=ActorKind.AGENT, id=AGENT_ACTOR_ID), + response_timeout_s=45.0, + helper_profile="s100-exec", + ) + return AgentApplicationService( + config=config, + connector=connector, + runs=FileRunStore(STATE_DIR), + snapshots=FileSnapshotStore(STATE_DIR), + plans=FilePlanStore(STATE_DIR), + approvals=FileApprovalStore(STATE_DIR), + tasks=FileTaskStore(STATE_DIR), + idempotency=FileIdempotencyStore(STATE_DIR), + events=EventStore(STATE_DIR), + verifications=FileVerificationStore(STATE_DIR), + registrations=FileRegistrationStore(STATE_DIR), + fixtures=FileFixtureStore(STATE_DIR), + ) + + +def call(server: AgentStdioServer, method: str, payload: dict): + return server.handle(make_request(method, payload)) + + +def payload_of(frame) -> dict: + return frame.payload if isinstance(frame.payload, dict) else {} + + +def fetch_artifact(service: AgentApplicationService, run_id: str, name: str) -> str | None: + try: + _descriptor, content = service.read_artifact(run_id, name) + except Exception: + return None + return content.decode("utf-8", errors="replace") + + +def main() -> int: + EVIDENCE_DIR.mkdir(parents=True, exist_ok=True) + service = build_service() + agent = AgentStdioServer(service, role="agent") + human = AgentStdioServer(service, role="human") + fixture_id: str | None = None + + # 0. Clean slate for reruns: drop leftover fixture declarations and + # reconcile any non-terminal host-side run records against device truth + # (an abandoned wait window must not keep holding the write lease). + for old in service.list_fixtures(DEVICE_ID): + service.remove_fixture(old.fixture_id) + record("fixture-leftover-removed", fixture_id=old.fixture_id) + for zombie in service._runs.list_active(DEVICE_ID): + reconciled = service.run_status(zombie.run_id) + record( + "zombie-run-reconciled", + run_id=zombie.run_id, + state=reconciled.state.value, + cleanup=reconciled.cleanup.state.value if reconciled.cleanup else None, + ) + + # 1. Agent plane must NOT declare fixtures (human-only authority). + denied = call( + agent, + "fixture.declare", + {"device_id": DEVICE_ID, "pack_id": "lekiwi-base", "serial_node": "/dev/ttyACM0"}, + ) + record( + "agent-fixture-declare-refused", + ok=denied.error is not None and denied.error.code == "RDK-PROTO-001", + error=denied.error.model_dump(mode="json") if denied.error else None, + ) + + # 2. Fresh inventory (human plane), chassis capabilities absent pre-fixture. + inspected = call(human, "device.inspect", {"device_id": DEVICE_ID, "refresh": "full"}) + snap = payload_of(inspected).get("snapshot") or {} + caps_before = [c["id"] for c in snap.get("capabilities", [])] + record("inventory-refresh", ok=inspected.error is None, capabilities=caps_before) + + # 3. Human declares the reviewed fixture. + declared = call( + human, + "fixture.declare", + {"device_id": DEVICE_ID, "pack_id": "lekiwi-base", "serial_node": "/dev/ttyACM0"}, + ) + decl_payload = payload_of(declared) + fixture = decl_payload.get("fixture") or {} + fixture_id = fixture.get("fixture_id") + record( + "fixture-declare", + ok=declared.error is None and decl_payload.get("activated") is True, + fixture_id=fixture_id, + activated=decl_payload.get("activated"), + ) + if declared.error is not None or not decl_payload.get("activated"): + return finish(2) + + # 4. Capabilities visible after declaration. + cached = call(human, "device.inspect", {"device_id": DEVICE_ID}) + caps_after = [ + c["id"] for c in (payload_of(cached).get("snapshot") or {}).get("capabilities", []) + ] + record( + "capabilities-after-fixture", + ok="base.scan" in caps_after and "base.velocity.bounded" in caps_after, + capabilities=caps_after, + ) + + # 5. Agent lists templates; scan runnable, move requires fixture capability. + listed = call(agent, "template.list", {"device_id": DEVICE_ID}) + templates = {t["name"]: t for t in payload_of(listed).get("templates", [])} + record( + "template-list", + ok=templates.get("base-scan", {}).get("runnable") is True + and templates.get("base-move", {}).get("runnable") is True, + base_scan=templates.get("base-scan"), + base_move=templates.get("base-move"), + ) + + # 6. Automatic discovery: agent runs base-scan (R0, zero writes). + scanned = call( + agent, + "template.run", + { + "name": "base-scan", + "device_id": DEVICE_ID, + "request_id": f"hil-scan-{int(time.time())}", + }, + ) + scan_payload = payload_of(scanned) + scan_run = scan_payload.get("run") or {} + scan_artifact = None + if scan_run.get("run_id"): + scan_artifact = fetch_artifact(service, scan_run["run_id"], "bus_scan.json") + (EVIDENCE_DIR / "bus_scan.json").write_text(scan_artifact or "", encoding="utf-8") + record( + "scan-run", + ok=scanned.error is None + and scan_payload.get("status") == "started" + and scan_run.get("state") == "succeeded" + and scan_run.get("outcome") == "passed", + state=scan_run.get("state"), + outcome=scan_run.get("outcome"), + cleanup=(scan_run.get("cleanup") or {}).get("state"), + run_id=scan_run.get("run_id"), + ) + if scan_artifact: + scan_data = json.loads(scan_artifact) + record( + "scan-facts", + responding=scan_data.get("responding"), + declared_missing=scan_data.get("declared_missing"), + write_commands_sent=scan_data.get("write_commands_sent"), + ) + + # 7. Motion without approval is gated (and envelope violations reject early). + bad_env = call( + agent, + "template.run", + { + "name": "base-move", + "device_id": DEVICE_ID, + "request_id": f"hil-move-bad-{int(time.time())}", + "params": {"vx": 9.9, "vy": 0.0, "omega_deg_s": 0.0, "duration_ms": 500}, + }, + ) + record( + "envelope-rejected", + ok=bad_env.error is not None, + error=bad_env.error.model_dump(mode="json") if bad_env.error else None, + ) + + gated = call( + agent, + "template.run", + { + "name": "base-move", + "device_id": DEVICE_ID, + "request_id": f"hil-move-1-{int(time.time())}", + "params": {"vx": 0.05, "vy": 0.0, "omega_deg_s": 0.0, "duration_ms": 1000}, + }, + ) + gated_payload = payload_of(gated) + approval_id = gated_payload.get("approval_id") + plan_id = gated_payload.get("plan_id") + record( + "motion-gated", + ok=gated.error is None and gated_payload.get("status") == "approval_required", + status=gated_payload.get("status"), + approval_id=approval_id, + plan_id=plan_id, + ) + if not approval_id: + return finish(3) + + # 8. Start with a bogus approval must fail. + bogus = call( + agent, + "template.start", + { + "plan_id": plan_id, + "approval_id": "appr-nonexistent", + "request_id": f"hil-move-bogus-{int(time.time())}", + }, + ) + record("bogus-approval-refused", ok=bogus.error is not None) + + # 9. Human approves; agent starts; wheels move then stop (safe-state read-back). + decided = call( + human, + "approval.decide", + { + "approval_id": approval_id, + "approve": True, + "reason": "HIL: elevated, 12V switch at hand", + }, + ) + record("approval-decided", ok=decided.error is None) + started = call( + agent, + "template.start", + { + "plan_id": plan_id, + "approval_id": approval_id, + "request_id": f"hil-move-start-{int(time.time())}", + }, + ) + move_run = started.payload if hasattr(started.payload, "get") else {} + if hasattr(move_run, "model_dump"): + move_run = move_run.model_dump(mode="json") + move_artifact = None + if isinstance(move_run, dict) and move_run.get("run_id"): + move_artifact = fetch_artifact(service, move_run["run_id"], "motion.json") + (EVIDENCE_DIR / "motion.json").write_text(move_artifact or "", encoding="utf-8") + record( + "motion-run", + ok=started.error is None + and isinstance(move_run, dict) + and move_run.get("state") == "succeeded" + and move_run.get("outcome") == "passed", + state=move_run.get("state") if isinstance(move_run, dict) else None, + outcome=move_run.get("outcome") if isinstance(move_run, dict) else None, + run_id=move_run.get("run_id") if isinstance(move_run, dict) else None, + ) + if move_artifact: + motion = json.loads(move_artifact) + record( + "motion-safe-state", + stop_confirmed=motion.get("stop_confirmed"), + max_abs_final_velocity=motion.get("max_abs_final_velocity"), + wheel_raw=motion.get("wheel_raw"), + config_writes=motion.get("config_writes"), + ) + + # 10. Single-use approval: a second start with the same approval is refused. + reuse = call( + agent, + "template.start", + { + "plan_id": plan_id, + "approval_id": approval_id, + "request_id": f"hil-move-reuse-{int(time.time())}", + }, + ) + record("approval-single-use", ok=reuse.error is not None) + + # 11. Cancel mid-motion: wheels stop, cleanup confirmed. + gated2 = call( + agent, + "template.run", + { + "name": "base-move", + "device_id": DEVICE_ID, + "request_id": f"hil-move-cancel-{int(time.time())}", + "params": {"vx": 0.05, "vy": 0.0, "omega_deg_s": 0.0, "duration_ms": 2500}, + }, + ) + gated2_payload = payload_of(gated2) + approval2 = gated2_payload.get("approval_id") + plan2 = gated2_payload.get("plan_id") + if approval2: + call( + human, + "approval.decide", + {"approval_id": approval2, "approve": True, "reason": "HIL cancel case"}, + ) + holder: dict = {} + + def start_in_thread() -> None: + frame = call( + agent, + "template.start", + { + "plan_id": plan2, + "approval_id": approval2, + "request_id": f"hil-move-cancel-start-{int(time.time())}", + }, + ) + holder["frame"] = frame + + worker = threading.Thread(target=start_in_thread, daemon=True) + worker.start() + run_id = None + deadline = time.monotonic() + 20.0 + while run_id is None and time.monotonic() < deadline: + for rec in service._runs.list_active(DEVICE_ID): + if rec.plan_id == plan2: + run_id = rec.run_id + time.sleep(0.1) + cancelled_state = None + if run_id is not None: + time.sleep(0.7) # let the wheels actually spin first + cancelled = service.cancel_run(run_id, reason="HIL cancel case") + cancelled_state = cancelled.state.value + worker.join(timeout=30.0) + final = service.run_status(run_id) if run_id else None + cancel_artifact = fetch_artifact(service, run_id, "motion.json") if run_id else None + if cancel_artifact: + (EVIDENCE_DIR / "motion_cancelled.json").write_text(cancel_artifact, encoding="utf-8") + record( + "motion-cancelled", + ok=run_id is not None + and cancelled_state in ("cancelled", "cleanup_unconfirmed") + and final is not None, + run_id=run_id, + state_after_cancel=final.state.value if final else None, + cleanup=(final.cleanup.state.value if final and final.cleanup else None), + ) + if cancel_artifact: + cancelled_motion = json.loads(cancel_artifact) + record( + "cancel-safe-state", + stop_confirmed=cancelled_motion.get("stop_confirmed"), + max_abs_final_velocity=cancelled_motion.get("max_abs_final_velocity"), + ) + else: + record("motion-cancelled", ok=False, error="second gating failed") + + # 12. Remove fixture -> capabilities drop immediately (then restore it). + removed = call(human, "fixture.remove", {"fixture_id": fixture_id}) + cached2 = call(human, "device.inspect", {"device_id": DEVICE_ID}) + caps_removed = [ + c["id"] for c in (payload_of(cached2).get("snapshot") or {}).get("capabilities", []) + ] + record( + "fixture-remove", + ok=removed.error is None and "base.velocity.bounded" not in caps_removed, + capabilities=caps_removed, + ) + redeclared = call( + human, + "fixture.declare", + {"device_id": DEVICE_ID, "pack_id": "lekiwi-base", "serial_node": "/dev/ttyACM0"}, + ) + record( + "fixture-redeclare", + ok=redeclared.error is None and payload_of(redeclared).get("activated") is True, + ) + + return finish(0) + + +def finish(code: int) -> int: + summary = { + "at": ["AT-032", "AT-033"], + "adr": "ADR-017", + "device": DEVICE_ID, + "host": HOST, + "state_dir": str(STATE_DIR), + "recorded_at": datetime.now(timezone.utc).isoformat(), + "steps": RESULTS, + } + (EVIDENCE_DIR / "hil-steps.json").write_text( + json.dumps(summary, indent=2, ensure_ascii=False), encoding="utf-8" + ) + failures = [r for r in RESULTS if r.get("ok") is False] + print(f"\n== {len(RESULTS) - len(failures)}/{len(RESULTS)} steps ok ==") + if failures: + print("failed steps:", [r["step"] for r in failures]) + return 1 if code == 0 else code + return code + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/acceptance/test_fake_variants.py b/tests/acceptance/test_fake_variants.py index 14f5b53..15fc2e1 100644 --- a/tests/acceptance/test_fake_variants.py +++ b/tests/acceptance/test_fake_variants.py @@ -330,6 +330,15 @@ class TestAT021ToolSurface: "pack.save", "pack.list", "pack.run", + # ADR-017: reviewed templates are agent-reachable; R2 motion stops + # at a human approval decision (template.start consumes it). + "template.list", + "template.run", + "template.start", + "fixture.list", + # ADR-018: accessory knowledge is data; registry/history are R0 facts. + "accessory.registry", + "accessory.history", "workspace.list", "workspace.read", "workspace.write", @@ -344,6 +353,12 @@ class TestAT021ToolSurface: "approval.reject", "device.flash", "sudo.run", + # ADR-017: fixture declarations stay human-only. + "fixture.declare", + "fixture.remove", + # ADR-018: user accessory packs are created/removed by humans only. + "accessory.pack.create", + "accessory.pack.remove", } assert not (set(AGENT_METHODS) & forbidden) diff --git a/tests/unit/test_core_fixtures.py b/tests/unit/test_core_fixtures.py new file mode 100644 index 0000000..8466cdf --- /dev/null +++ b/tests/unit/test_core_fixtures.py @@ -0,0 +1,158 @@ +"""Fixture declaration + accessory-pack overlay rules (ADR-017/018, docs/03 §2.2.2).""" + +from __future__ import annotations + +from datetime import datetime, timezone + +import pytest +from rdk_agent_core.accessories import ( + BASE_SCAN_CAPABILITY, + BASE_VELOCITY_CAPABILITY, + AccessoryPack, + BusProtocol, + MotionEnvelope, + PackOrigin, + apply_fixture_overlay, +) +from rdk_agent_core.base import ActorKind, ActorRef +from rdk_agent_core.capabilities import CapabilityStatus, RiskLevel +from rdk_agent_core.device import DeviceSnapshot, PeripheralsBlock +from rdk_agent_core.fixtures import FixtureDeclaration + +USER = ActorRef(kind=ActorKind.USER, id="ops") +AGENT = ActorRef(kind=ActorKind.AGENT, id="pi-agent") +NOW = datetime(2026, 8, 25, 7, 0, tzinfo=timezone.utc) + + +def make_pack(**overrides: object) -> AccessoryPack: + base: dict[str, object] = { + "pack_id": "lekiwi-base", + "pack_version": "1.0.0", + "origin": PackOrigin.REVIEWED, + "bus_protocol": BusProtocol.FEETECH_STS, + "capabilities": (BASE_SCAN_CAPABILITY, BASE_VELOCITY_CAPABILITY), + "servo_ids": (7, 8, 9), + "envelope": MotionEnvelope( + max_linear_m_s=0.1, max_angular_deg_s=30.0, max_duration_ms=3000 + ), + "wheel_radius_m": 0.05, + "base_radius_m": 0.125, + "max_raw_wheel_speed": 3000, + "wheel_angles_deg": (240.0, 0.0, 120.0), + "source": "test provenance", + } + base.update(overrides) + return AccessoryPack(**base) # type: ignore[arg-type] + + +def make_snapshot( + *, serial_nodes: list[str] | None = None, device_id: str = "dev-1" +) -> DeviceSnapshot: + return DeviceSnapshot( + device_id=device_id, + captured_at=NOW, + peripherals=PeripheralsBlock(serial_nodes=serial_nodes or ["/dev/ttyACM0"]), + ).with_computed_id() + + +def make_declaration(**overrides: object) -> FixtureDeclaration: + base: dict[str, object] = { + "pack_id": "lekiwi-base", + "pack_version": "1.0.0", + "device_id": "dev-1", + "serial_node": "/dev/ttyACM0", + "declared_by": USER, + "declared_at": NOW, + } + base.update(overrides) + return FixtureDeclaration(**base) # type: ignore[arg-type] + + +class TestFixtureDeclaration: + def test_user_actor_required(self) -> None: + for actor in (AGENT, ActorRef(kind=ActorKind.EXTERNAL_AGENT, id="mcp")): + with pytest.raises(ValueError, match="human"): + make_declaration(declared_by=actor) + + def test_serial_node_must_be_device_path(self) -> None: + for bad in ("ttyACM0", "../etc/passwd", "/etc/ttyACM0"): + with pytest.raises(ValueError): + make_declaration(serial_node=bad) + + +class TestAccessoryPackModel: + def test_envelope_bounds_are_model_enforced(self) -> None: + """Absolute ceilings hold for ANY pack, shipped or user (ADR-018).""" + with pytest.raises(ValueError): + MotionEnvelope(max_linear_m_s=5.0, max_angular_deg_s=30.0, max_duration_ms=1000) + with pytest.raises(ValueError): + MotionEnvelope(max_linear_m_s=0.1, max_angular_deg_s=30.0, max_duration_ms=999_999) + with pytest.raises(ValueError): + make_pack( + envelope=MotionEnvelope( + max_linear_m_s=0.5, max_angular_deg_s=30.0, max_duration_ms=10_000 + ), + wheel_radius_m=3.0, + ) + + def test_provenance_required(self) -> None: + with pytest.raises(ValueError): + make_pack(source="") + + def test_unknown_capability_rejected(self) -> None: + with pytest.raises(ValueError): + make_pack(capabilities=("base.scan", "chassis.turbo")) + + def test_user_origin_forced_fields_still_validated(self) -> None: + pack = make_pack(origin=PackOrigin.USER) + assert pack.origin is PackOrigin.USER + + +class TestFixtureOverlay: + def test_overlay_injects_capabilities_with_fixture_evidence(self) -> None: + snapshot = make_snapshot() + declaration = make_declaration() + overlaid = apply_fixture_overlay(snapshot, declaration, make_pack()) + + assert overlaid.snapshot_id != snapshot.snapshot_id + scan = overlaid.capability(BASE_SCAN_CAPABILITY) + move = overlaid.capability(BASE_VELOCITY_CAPABILITY) + assert scan is not None and move is not None + assert scan.status is CapabilityStatus.AVAILABLE + assert scan.risk is RiskLevel.R0_READ_OBSERVE + assert move.status is CapabilityStatus.AVAILABLE + assert move.risk is RiskLevel.R2_DEVICE_IO_BOUNDED + assert scan.evidence[0].kind == "fixture" + assert scan.evidence[0].value == declaration.fixture_id + # Snapshot validator already enforced /capabilities/ observations. + assert overlaid.observations[f"/capabilities/{BASE_SCAN_CAPABILITY}"].evidence_ref == ( + f"fixture:{declaration.fixture_id}" + ) + + def test_overlay_requires_observed_serial_node(self) -> None: + snapshot = make_snapshot(serial_nodes=["/dev/ttyUSB0"]) + overlaid = apply_fixture_overlay(snapshot, make_declaration(), make_pack()) + assert overlaid is snapshot + assert overlaid.capability(BASE_VELOCITY_CAPABILITY) is None + + def test_overlay_requires_device_match(self) -> None: + snapshot = make_snapshot(device_id="dev-other") + assert apply_fixture_overlay(snapshot, make_declaration(), make_pack()) is snapshot + + def test_overlay_requires_matching_pack(self) -> None: + snapshot = make_snapshot() + pack = make_pack() + assert ( + apply_fixture_overlay(snapshot, make_declaration(pack_version="9.9.9"), pack) + is snapshot + ) + assert apply_fixture_overlay(snapshot, make_declaration(pack_id="nope"), pack) is snapshot + assert apply_fixture_overlay(snapshot, make_declaration(), None) is snapshot + + def test_overlay_is_idempotent(self) -> None: + declaration = make_declaration() + pack = make_pack() + once = apply_fixture_overlay(make_snapshot(), declaration, pack) + twice = apply_fixture_overlay(once, declaration, pack) + assert twice is once + assert [c.id for c in twice.capabilities].count(BASE_SCAN_CAPABILITY) == 1 diff --git a/tests/unit/test_host_accessories.py b/tests/unit/test_host_accessories.py new file mode 100644 index 0000000..8d2d63c --- /dev/null +++ b/tests/unit/test_host_accessories.py @@ -0,0 +1,199 @@ +"""Accessory ledger, recommendation and user-pack flows (ADR-018, AT-038).""" + +from __future__ import annotations + +from datetime import datetime, timezone +from pathlib import Path + +import pytest +from rdk_agent_core.accessories import ( + BASE_SCAN_CAPABILITY, + BASE_VELOCITY_CAPABILITY, + PackOrigin, +) +from rdk_agent_core.base import ActorKind, ActorRef +from rdk_agent_core.errors import ErrorCode, RDKError +from rdk_agent_device.probes import FakeFacts +from rdk_agent_host.application import AgentApplicationService +from rdk_agent_host.config import HostConfig +from rdk_agent_host.stores import ( + EventStore, + InMemoryAccessoryLedgerStore, + InMemoryAccessoryPackStore, + InMemoryApprovalStore, + InMemoryFixtureStore, + InMemoryIdempotencyStore, + InMemoryPlanStore, + InMemoryRunStore, + InMemorySnapshotStore, + InMemoryTaskStore, + InMemoryVerificationStore, +) + +NOW = datetime(2026, 8, 26, 9, 0, tzinfo=timezone.utc) +LATER = datetime(2026, 8, 26, 10, 0, tzinfo=timezone.utc) +USER = ActorRef(kind=ActorKind.USER, id="ops") +AGENT = ActorRef(kind=ActorKind.AGENT, id="pi-agent") + +CHASSIS_FACTS = FakeFacts(usb_devices=["1a86:55d3 QinHeng USB Single Serial"]) + + +@pytest.fixture +def service(tmp_path: Path, connector_factory): # type: ignore[no-untyped-def] + state_dir = tmp_path / "state" + state_dir.mkdir(parents=True, exist_ok=True) + config = HostConfig(state_dir=state_dir, device_command=("true",), run_wait_window_s=5.0) + return AgentApplicationService( + config=config, + connector=connector_factory(facts=CHASSIS_FACTS, clock=lambda: NOW), # type: ignore[arg-type] + runs=InMemoryRunStore(), + snapshots=InMemorySnapshotStore(), + plans=InMemoryPlanStore(), + approvals=InMemoryApprovalStore(), + tasks=InMemoryTaskStore(), + idempotency=InMemoryIdempotencyStore(), + events=EventStore(state_dir), + verifications=InMemoryVerificationStore(), + fixtures=InMemoryFixtureStore(), + accessory_packs=InMemoryAccessoryPackStore(), + accessory_ledgers=InMemoryAccessoryLedgerStore(), + clock=lambda: NOW, + ) + + +class TestAccessoryLedger: + def test_inventory_records_raw_facts_only(self, service: AgentApplicationService) -> None: + service.inventory_device("fake-001") + history = service.accessory_history("fake-001") + assert history["device_id"] == "fake-001" + values = [s["value"] for s in history["sightings"]] + assert "1a86:55d3" in values + # Facts only: no product naming ever enters the ledger. + for sighting in history["sightings"]: + assert sighting["kind"] in ("usb", "serial") + + def test_ledger_remembers_after_unplug(self, service: AgentApplicationService) -> None: + service.inventory_device("fake-001") + # Accessory unplugged: re-inventory with empty usb facts. + service._connector._server.facts = FakeFacts(usb_devices=[]) # type: ignore[attr-defined] + service.inventory_device("fake-001") + history = service.accessory_history("fake-001") + assert "1a86:55d3" in [s["value"] for s in history["sightings"]] + + def test_declared_packs_tracked(self, service: AgentApplicationService) -> None: + service.inventory_device("fake-001") + # lekiwi-base requires a serial bus fact; give the snapshot one. + snapshot = service._snapshots.latest("fake-001") + extended = snapshot.model_copy( + update={ + "peripherals": snapshot.peripherals.model_copy( + update={"serial_nodes": ["/dev/ttyACM0"]} + ) + } + ).with_computed_id() + service._snapshots.save(extended) + service.declare_fixture("fake-001", "lekiwi-base", "/dev/ttyACM0", actor=USER) + assert service.accessory_history("fake-001")["declared_packs"] == ["lekiwi-base"] + fixture_id = service.list_fixtures("fake-001")[-1].fixture_id + service.remove_fixture(fixture_id) + assert service.accessory_history("fake-001")["declared_packs"] == [] + + +class TestRecommendation: + def test_missing_facts_then_ready_then_active(self, service: AgentApplicationService) -> None: + service.inventory_device("fake-001") + recs = {r["pack_id"]: r for r in service.recommend_accessories("fake-001")} + lekiwi = recs["lekiwi-base"] + assert lekiwi["status"] == "missing_facts" + assert lekiwi["missing_facts"] == ["serial_bus"] + + snapshot = service._snapshots.latest("fake-001") + extended = snapshot.model_copy( + update={ + "peripherals": snapshot.peripherals.model_copy( + update={"serial_nodes": ["/dev/ttyACM0"]} + ) + } + ).with_computed_id() + service._snapshots.save(extended) + recs = {r["pack_id"]: r for r in service.recommend_accessories("fake-001")} + assert recs["lekiwi-base"]["status"] == "ready" + + service.declare_fixture("fake-001", "lekiwi-base", "/dev/ttyACM0", actor=USER) + recs = {r["pack_id"]: r for r in service.recommend_accessories("fake-001")} + assert recs["lekiwi-base"]["status"] == "active" + + def test_recommendation_never_infers_from_vidpid( + self, service: AgentApplicationService + ) -> None: + """VID:PID facts alone must never activate or name a pack.""" + service.inventory_device("fake-001") + for rec in service.recommend_accessories("fake-001"): + assert rec["status"] != "active" + + +class TestUserPacks: + def _payload(self, pack_id: str = "my-base") -> dict[str, object]: + return { + "pack_id": pack_id, + "pack_version": "0.1.0", + "origin": "reviewed", # forced to user host-side + "bus_protocol": "feetech-sts", + "capabilities": [BASE_SCAN_CAPABILITY, BASE_VELOCITY_CAPABILITY], + "servo_ids": [1, 2], + "envelope": { + "max_linear_m_s": 0.05, + "max_angular_deg_s": 20.0, + "max_duration_ms": 1000, + }, + "wheel_radius_m": 0.04, + "base_radius_m": 0.1, + "max_raw_wheel_speed": 2000, + "wheel_angles_deg": [240.0, 0.0, 120.0], + "source": "human entry; measured with a ruler", + } + + def test_agent_actor_rejected(self, service: AgentApplicationService) -> None: + with pytest.raises(RDKError): + service.create_accessory_pack(self._payload(), actor=AGENT) + + def test_create_and_recommend(self, service: AgentApplicationService) -> None: + pack = service.create_accessory_pack(self._payload(), actor=USER) + assert pack.origin is PackOrigin.USER + ids = [r["pack_id"] for r in service.recommend_accessories("fake-001")] + assert "my-base" in ids + + def test_invalid_payload_rejected(self, service: AgentApplicationService) -> None: + bad = self._payload() + bad["envelope"] = { + "max_linear_m_s": 99.0, # above absolute ceiling + "max_angular_deg_s": 20.0, + "max_duration_ms": 1000, + } + with pytest.raises(RDKError) as exc: + service.create_accessory_pack(bad, actor=USER) + assert exc.value.code is ErrorCode.INPUT_INVALID + + def test_cannot_shadow_shipped_id(self, service: AgentApplicationService) -> None: + with pytest.raises(RDKError): + service.create_accessory_pack(self._payload("lekiwi-base"), actor=USER) + + def test_shipped_pack_not_removable(self, service: AgentApplicationService) -> None: + with pytest.raises(RDKError): + service.remove_accessory_pack("lekiwi-base") + + def test_in_use_pack_not_removable(self, service: AgentApplicationService) -> None: + service.inventory_device("fake-001") + snapshot = service._snapshots.latest("fake-001") + extended = snapshot.model_copy( + update={ + "peripherals": snapshot.peripherals.model_copy( + update={"serial_nodes": ["/dev/ttyACM0"]} + ) + } + ).with_computed_id() + service._snapshots.save(extended) + service.create_accessory_pack(self._payload(), actor=USER) + service.declare_fixture("fake-001", "my-base", "/dev/ttyACM0", actor=USER) + with pytest.raises(RDKError): + service.remove_accessory_pack("my-base") diff --git a/tests/unit/test_host_accessory_registry.py b/tests/unit/test_host_accessory_registry.py new file mode 100644 index 0000000..bee18fe --- /dev/null +++ b/tests/unit/test_host_accessory_registry.py @@ -0,0 +1,113 @@ +"""Accessory registry: shipped data + user packs (ADR-018, AT-038).""" + +from __future__ import annotations + +from pathlib import Path + +import pytest +from pydantic import ValidationError +from rdk_agent_core.accessories import ( + BASE_SCAN_CAPABILITY, + BASE_VELOCITY_CAPABILITY, + AccessoryPack, + BusProtocol, + MotionEnvelope, + PackOrigin, +) +from rdk_agent_core.errors import ErrorCode, RDKError +from rdk_agent_host.accessory_registry import AccessoryRegistry, load_shipped_packs +from rdk_agent_host.stores import InMemoryAccessoryPackStore + + +def make_user_pack(pack_id: str = "my-base", **overrides: object) -> AccessoryPack: + base: dict[str, object] = { + "pack_id": pack_id, + "pack_version": "0.1.0", + "origin": PackOrigin.USER, + "bus_protocol": BusProtocol.FEETECH_STS, + "capabilities": (BASE_SCAN_CAPABILITY, BASE_VELOCITY_CAPABILITY), + "servo_ids": (1, 2), + "envelope": MotionEnvelope( + max_linear_m_s=0.05, max_angular_deg_s=20.0, max_duration_ms=1000 + ), + "wheel_radius_m": 0.04, + "base_radius_m": 0.1, + "max_raw_wheel_speed": 2000, + "wheel_angles_deg": (240.0, 0.0, 120.0), + "source": "human entry; measured with a ruler", + } + base.update(overrides) + return AccessoryPack(**base) # type: ignore[arg-type] + + +class TestShippedRegistry: + def test_shipped_packs_load_and_validate(self) -> None: + packs = load_shipped_packs() + assert "lekiwi-base" in packs + pack = packs["lekiwi-base"] + assert pack.origin is PackOrigin.REVIEWED + assert pack.source # provenance present + assert pack.envelope.max_linear_m_s <= 0.5 # within absolute ceilings + + def test_invalid_shipped_file_fails_closed(self, tmp_path: Path) -> None: + (tmp_path / "broken.json").write_text('{"pack_id": "x"}', encoding="utf-8") + with pytest.raises(RDKError) as exc: + load_shipped_packs(tmp_path) + assert exc.value.code is ErrorCode.INPUT_INVALID + + def test_shipped_pack_must_be_reviewed(self, tmp_path: Path) -> None: + pack = make_user_pack("odd") + (tmp_path / "odd.json").write_text(pack.model_dump_json(), encoding="utf-8") + with pytest.raises(RDKError): + load_shipped_packs(tmp_path) + + def test_duplicate_shipped_id_fails(self, tmp_path: Path) -> None: + pack = make_user_pack("dup", origin=PackOrigin.REVIEWED) + (tmp_path / "a.json").write_text(pack.model_dump_json(), encoding="utf-8") + (tmp_path / "b.json").write_text(pack.model_dump_json(), encoding="utf-8") + with pytest.raises(RDKError): + load_shipped_packs(tmp_path) + + +class TestUserPacks: + def registry(self) -> AccessoryRegistry: + return AccessoryRegistry(load_shipped_packs(), InMemoryAccessoryPackStore()) + + def test_create_user_pack_forces_origin(self) -> None: + registry = self.registry() + created = registry.create_user_pack( + make_user_pack(origin=PackOrigin.REVIEWED) # host overrides this + ) + assert created.origin is PackOrigin.USER + assert registry.get("my-base") is not None + + def test_user_pack_cannot_shadow_shipped_id(self) -> None: + registry = self.registry() + with pytest.raises(RDKError) as exc: + registry.create_user_pack(make_user_pack("lekiwi-base")) + assert exc.value.code is ErrorCode.INPUT_INVALID + + def test_shipped_pack_cannot_be_removed(self) -> None: + registry = self.registry() + with pytest.raises(RDKError): + registry.remove_user_pack("lekiwi-base") + + def test_user_pack_envelope_ceilings_model_enforced(self) -> None: + """The absolute ceilings hold for user packs too — validation rejects + before the registry ever sees the record.""" + with pytest.raises(ValidationError): + make_user_pack( + envelope=MotionEnvelope( + max_linear_m_s=9.9, max_angular_deg_s=20.0, max_duration_ms=1000 + ) + ) + + def test_user_pack_requires_provenance(self) -> None: + with pytest.raises(ValidationError): + make_user_pack(source="") + + def test_merged_view(self) -> None: + registry = self.registry() + registry.create_user_pack(make_user_pack()) + ids = [p.pack_id for p in registry.all()] + assert ids == ["lekiwi-base", "my-base"] diff --git a/tests/unit/test_host_fixtures_templates.py b/tests/unit/test_host_fixtures_templates.py new file mode 100644 index 0000000..658ae02 --- /dev/null +++ b/tests/unit/test_host_fixtures_templates.py @@ -0,0 +1,313 @@ +"""Fixture declarations + reviewed template flows (ADR-017, AT-032/AT-033 fake half). + +Real-bus behavior is accepted on hardware (docs/testing/evidence/LEKIWI-CHASSIS.md); +here the fake device exercises the policy/approval/overlay plumbing end-to-end: + +- fixture declaration is human-only, reviewed-pack only, observed-node gated; +- overlay activates capabilities on stored snapshots and drops on removal; +- base-scan (R0) auto-runs once available; base-move (R2) stops at a + pending approval and only starts after a human decision (single-use). +""" + +from __future__ import annotations + +from datetime import datetime, timezone +from pathlib import Path + +import pytest +from rdk_agent_core.accessories import ( + BASE_SCAN_CAPABILITY, + BASE_VELOCITY_CAPABILITY, +) +from rdk_agent_core.approvals import ApprovalDecision +from rdk_agent_core.base import ActorKind, ActorRef +from rdk_agent_core.device import DeviceSnapshot +from rdk_agent_core.errors import ErrorCode, RDKError +from rdk_agent_host.application import AgentApplicationService +from rdk_agent_host.config import HostConfig +from rdk_agent_host.stores import ( + EventStore, + InMemoryApprovalStore, + InMemoryFixtureStore, + InMemoryIdempotencyStore, + InMemoryPlanStore, + InMemoryRunStore, + InMemorySnapshotStore, + InMemoryTaskStore, + InMemoryVerificationStore, +) +from rdk_agent_host.templates import ( + get_template, + render_params_json, + validate_template_params, +) + +NOW = datetime(2026, 8, 25, 7, 0, tzinfo=timezone.utc) +USER = ActorRef(kind=ActorKind.USER, id="ops") +AGENT = ActorRef(kind=ActorKind.AGENT, id="pi-agent") + + +@pytest.fixture +def service(tmp_path: Path, connector_factory): # type: ignore[no-untyped-def] + state_dir = tmp_path / "state" + state_dir.mkdir(parents=True, exist_ok=True) + config = HostConfig(state_dir=state_dir, device_command=("true",), run_wait_window_s=5.0) + return AgentApplicationService( + config=config, + connector=connector_factory(facts=None, clock=lambda: NOW), # type: ignore[arg-type] + runs=InMemoryRunStore(), + snapshots=InMemorySnapshotStore(), + plans=InMemoryPlanStore(), + approvals=InMemoryApprovalStore(), + tasks=InMemoryTaskStore(), + idempotency=InMemoryIdempotencyStore(), + events=EventStore(state_dir), + verifications=InMemoryVerificationStore(), + fixtures=InMemoryFixtureStore(), + clock=lambda: NOW, + ) + + +def _snapshot_with_serial( + service: AgentApplicationService, device_id: str = "fake-001" +) -> DeviceSnapshot: + """Inventory the fake device, then re-save a copy whose observed + peripherals contain the chassis serial node (the fake has no serial probe).""" + + snapshot, _ = service.inventory_device(device_id) + extended = snapshot.model_copy( + update={ + "peripherals": snapshot.peripherals.model_copy( + update={"serial_nodes": [*snapshot.peripherals.serial_nodes, "/dev/ttyACM0"]} + ) + } + ).with_computed_id() + service._snapshots.save(extended) + return extended + + +class TestDeclareFixture: + def test_declaration_activates_capabilities_on_observed_node( + self, service: AgentApplicationService + ) -> None: + _snapshot_with_serial(service) + result = service.declare_fixture("fake-001", "lekiwi-base", "/dev/ttyACM0", actor=USER) + assert result["activated"] is True + stored = service._snapshots.latest("fake-001") + assert stored is not None + assert stored.capability(BASE_SCAN_CAPABILITY) is not None + assert stored.capability(BASE_VELOCITY_CAPABILITY) is not None + + def test_declaration_without_observed_node_stays_dormant( + self, service: AgentApplicationService + ) -> None: + _snapshot_with_serial(service) + result = service.declare_fixture("fake-001", "lekiwi-base", "/dev/ttyUSB9", actor=USER) + assert result["activated"] is False + stored = service._snapshots.latest("fake-001") + assert stored is not None + assert stored.capability(BASE_VELOCITY_CAPABILITY) is None + + def test_agent_actor_rejected(self, service: AgentApplicationService) -> None: + _snapshot_with_serial(service) + with pytest.raises(ValueError, match="human"): + service.declare_fixture("fake-001", "lekiwi-base", "/dev/ttyACM0", actor=AGENT) + + def test_unknown_pack_rejected(self, service: AgentApplicationService) -> None: + with pytest.raises(RDKError) as exc: + service.declare_fixture("fake-001", "death-star", "/dev/ttyACM0", actor=USER) + assert exc.value.code is ErrorCode.INPUT_INVALID + + def test_remove_fixture_drops_capabilities(self, service: AgentApplicationService) -> None: + _snapshot_with_serial(service) + declared = service.declare_fixture("fake-001", "lekiwi-base", "/dev/ttyACM0", actor=USER) + fixture_id = declared["fixture"].fixture_id + service.remove_fixture(fixture_id) + stored = service._snapshots.latest("fake-001") + assert stored is not None + assert stored.capability(BASE_VELOCITY_CAPABILITY) is None + assert stored.capability(BASE_SCAN_CAPABILITY) is None + + def test_refreshed_inventory_without_node_drops_capability( + self, service: AgentApplicationService + ) -> None: + """Fail-closed: a fresh inventory replaces the snapshot; when the + declared node is not observed in the new facts the capability goes.""" + + _snapshot_with_serial(service) + service.declare_fixture("fake-001", "lekiwi-base", "/dev/ttyACM0", actor=USER) + snapshot, _ = service.inventory_device("fake-001") # fake has no serial nodes + assert snapshot.capability(BASE_VELOCITY_CAPABILITY) is None + + +class TestTemplateParams: + def test_envelope_violation_rejected(self) -> None: + template = get_template("base-move") + assert template is not None + with pytest.raises(RDKError) as exc: + validate_template_params( + template, {"vx": 5.0, "vy": 0.0, "omega_deg_s": 0.0, "duration_ms": 1000} + ) + assert exc.value.code is ErrorCode.INPUT_INVALID + + def test_reserved_fixture_keys_rejected(self) -> None: + template = get_template("base-move") + assert template is not None + with pytest.raises(RDKError): + validate_template_params(template, {"port": 1.0}) # type: ignore[dict-item] + + def test_unknown_and_missing_params_rejected(self) -> None: + template = get_template("base-move") + assert template is not None + with pytest.raises(RDKError): + validate_template_params(template, {"nope": 1.0}) + with pytest.raises(RDKError): + validate_template_params(template, {"vx": 0.0}) + + def test_render_injects_fixture_values_and_motion(self) -> None: + import json + + template = get_template("base-move") + assert template is not None + from rdk_agent_core.fixtures import FixtureDeclaration + + declaration = FixtureDeclaration( + pack_id="lekiwi-base", + pack_version="1.0.0", + device_id="fake-001", + serial_node="/dev/ttyACM0", + declared_by=USER, + declared_at=NOW, + ) + from rdk_agent_host.accessory_registry import load_shipped_packs + + pack = load_shipped_packs()["lekiwi-base"] + payload = json.loads( + render_params_json( + template, + declaration, + pack, + {"vx": 0.05, "vy": 0.0, "omega_deg_s": 0.0, "duration_ms": 1000}, + ) + ) + assert payload["port"] == "/dev/ttyACM0" + assert payload["servo_ids"] == [7, 8, 9] + assert payload["motion"]["vx"] == 0.05 + assert payload["envelope"]["max_linear_m_s"] == pytest.approx(0.10) + + def test_fixture_template_without_declaration_rejected(self) -> None: + template = get_template("base-scan") + assert template is not None + with pytest.raises(RDKError) as exc: + render_params_json(template, None, None, {}) + assert exc.value.code is ErrorCode.INPUT_INVALID + + +class TestTemplateRuns: + def test_scan_requires_declared_fixture(self, service: AgentApplicationService) -> None: + _snapshot_with_serial(service) + with pytest.raises(RDKError) as exc: + service.run_template("base-scan", "fake-001", request_id="req-scan-0") + assert exc.value.code is ErrorCode.INPUT_INVALID + + def test_scan_starts_without_approval(self, service: AgentApplicationService) -> None: + """R0 accessory discovery is automatic once the fixture is declared.""" + + _snapshot_with_serial(service) + service.declare_fixture("fake-001", "lekiwi-base", "/dev/ttyACM0", actor=USER) + result = service.run_template("base-scan", "fake-001", request_id="req-scan-1") + assert result["status"] == "started" + assert result["run"].run_id + + def test_move_requires_approval_then_starts_single_use( + self, service: AgentApplicationService + ) -> None: + _snapshot_with_serial(service) + service.declare_fixture("fake-001", "lekiwi-base", "/dev/ttyACM0", actor=USER) + + gated = service.run_template( + "base-move", + "fake-001", + request_id="req-move-1", + params={"vx": 0.05, "vy": 0.0, "omega_deg_s": 0.0, "duration_ms": 500}, + ) + assert gated["status"] == "approval_required" + approval_id = gated["approval_id"] + plan_id = gated["plan_id"] + + # Start without approval is refused. + with pytest.raises(RDKError) as exc: + service.start_template( + plan_id=plan_id, approval_id="appr-bogus", request_id="req-move-2" + ) + assert exc.value.code is ErrorCode.INPUT_INVALID + + # Human approves; start consumes the approval exactly once. + service.decide_approval( + approval_id, + decision=ApprovalDecision.APPROVED, + approver=USER, + reason="bench elevated, 12V switch at hand", + ) + record = service.start_template( + plan_id=plan_id, approval_id=approval_id, request_id="req-move-3" + ) + assert record.run_id + approval = service._approvals.get(approval_id) + assert approval is not None and approval.consumed_at is not None + + # Single-use: the same approval cannot open a second run. + with pytest.raises(RDKError) as exc: + service.start_template( + plan_id=plan_id, approval_id=approval_id, request_id="req-move-4" + ) + assert exc.value.code is ErrorCode.POLICY_DENIED + + def test_move_envelope_rejected_before_plan(self, service: AgentApplicationService) -> None: + _snapshot_with_serial(service) + service.declare_fixture("fake-001", "lekiwi-base", "/dev/ttyACM0", actor=USER) + with pytest.raises(RDKError) as exc: + service.run_template( + "base-move", + "fake-001", + request_id="req-move-9", + params={"vx": 9.9, "vy": 0.0, "omega_deg_s": 0.0, "duration_ms": 500}, + ) + assert exc.value.code is ErrorCode.INPUT_INVALID + + def test_lease_conflict_does_not_burn_approval(self, service: AgentApplicationService) -> None: + """A blocked start (exclusive write lease held) must reject BEFORE + consuming the single-use human approval.""" + + from rdk_agent_core.runs import RunRecord, RunState + + _snapshot_with_serial(service) + service.declare_fixture("fake-001", "lekiwi-base", "/dev/ttyACM0", actor=USER) + # A non-terminal run holds the device write lease. + service._runs.save( + RunRecord( + run_id="run-holder", + request_id="req-holder", + plan_id="sha256:holder", + device_id="fake-001", + state=RunState.RUNNING, + created_at=NOW, + ) + ) + gated = service.run_template( + "base-move", + "fake-001", + request_id="req-move-lease", + params={"vx": 0.05, "vy": 0.0, "omega_deg_s": 0.0, "duration_ms": 500}, + ) + approval_id = gated["approval_id"] + service.decide_approval( + approval_id, decision=ApprovalDecision.APPROVED, approver=USER, reason="test" + ) + with pytest.raises(RDKError) as exc: + service.start_template( + plan_id=gated["plan_id"], approval_id=approval_id, request_id="req-move-lease-2" + ) + assert exc.value.code is ErrorCode.POLICY_DENIED + approval = service._approvals.get(approval_id) + assert approval is not None and approval.consumed_at is None diff --git a/tests/unit/test_human_surface.py b/tests/unit/test_human_surface.py index 3340c7d..81dd720 100644 --- a/tests/unit/test_human_surface.py +++ b/tests/unit/test_human_surface.py @@ -445,8 +445,9 @@ def test_template_run_executes_health_card_on_fake( {"name": "health-card", "device_id": "fake-001", "request_id": "tpl-1"}, ) assert ran.error is None, ran.error - assert ran.payload["state"] == "succeeded" - assert ran.payload["outcome"] == "passed" + assert ran.payload["status"] == "started" + assert ran.payload["run"]["state"] == "succeeded" + assert ran.payload["run"]["outcome"] == "passed" def test_template_run_unknown_template_rejected( @@ -462,12 +463,30 @@ def test_template_run_unknown_template_rejected( assert ran.error.code == ErrorCode.INPUT_INVALID -def test_agent_role_cannot_run_templates(human_service: AgentApplicationService) -> None: - server = AgentStdioServer(human_service) +def test_agent_role_can_run_templates_but_not_declare_fixtures( + human_service: AgentApplicationService, +) -> None: + """ADR-017: templates are agent-reachable (R0 auto-runs; R2 motion stops + at a human approval), but fixture declarations stay human-only.""" + + human_service.inventory_device("fake-001") + agent_server = AgentStdioServer(human_service) ran = _call( - server, + agent_server, "template.run", {"name": "health-card", "device_id": "fake-001", "request_id": "tpl-3"}, ) - assert ran.error is not None - assert ran.error.code == ErrorCode.PROTOCOL_VIOLATION + assert ran.error is None + assert ran.payload["status"] == "started" + + declared = _call( + agent_server, + "fixture.declare", + { + "device_id": "fake-001", + "pack_id": "lekiwi-base", + "serial_node": "/dev/ttyACM0", + }, + ) + assert declared.error is not None + assert declared.error.code == ErrorCode.PROTOCOL_VIOLATION