Compare commits

..

93 Commits

Author SHA1 Message Date
Codex
806cc0b24a test(sim): independent SIM-R2 suite (AT-038..041) + final verdict evidence
Some checks failed
ci / python (pull_request) Has been cancelled
ci / typescript (pull_request) Has been cancelled
Test-agent authored: unit (templates/virtual_api/program/verifier_image),
contract (host sim RPC frame round-trips), integration (sim_run incl. bpu
approval flow and crafted-manifest fail-closed), golden sim_r2 section
(SIM-R1 section byte-unchanged), acceptance AT-038..041. Final verdict:
SIM-R2 acceptance passed; D1/D-SIMR2-1/D-SIMR2-2 closed via 1132760/59130c7/
7b85af6. 836/836, core branch coverage 96.35%.
2026-08-27 18:50:25 +08:00
Codex
a567677530 evidence(sim): SIM-R2 dev smoke (L2 templates, determinism, safety gates) 2026-08-27 18:40:27 +08:00
Codex
7b85af6777 fix(host): image.basic JPEG fill-byte handling (D-SIMR2-2 closure)
FF FF fill bytes no longer terminate the entropy scan early; complete
JPEGs with fill bytes before EOI verify, truncations still FAIL. Closes the
never-fail-open invariant for both formats.
2026-08-27 18:29:25 +08:00
Codex
59130c7ed9 fix(host): image.basic never fails open on truncated PNG/JPEG (D-SIMR2-1)
PNG parsing now walks chunks with length guards: truncated payload,
missing IDAT, or absent/non-final IEND all return None -> FAIL instead of
PASS/ERROR. JPEG segment-length reads are bounds-guarded. AT-039
never-fail-open criterion restored; full suite green.
2026-08-27 18:06:31 +08:00
Codex
1132760130 fix(sim): fail-closed terminal state for refused run_program (D1-class)
A crafted-source run_program raised before any transition, stranding the
device record in QUEUED (SIM-R1 D4 class). The dispatch now drives
QUEUED -> STAGING -> FAILED on refusal so the state machine always reaches
a terminal state; verified crafted-source ends FAILED.
2026-08-27 17:03:43 +08:00
Codex
e159b82ce7 docs(sim): SIM-R2 L2 status, full enumeration closed, AT-038..041 reserved
ADR-019 §11 open item 2 closed (12-row three-tier enumeration; bpu/camera
promoted real-sim with synthetic limitations; FIND-002 contradiction documented
not silently resolved). docs/02 §4.16 L2 paragraph; TEST_STRATEGY §12.2
synthetic-frame/BPU determinism; AT-038..041 reserved; traceability + 00/06
registration.
2026-08-27 16:03:16 +08:00
Codex
5f0c25b27e feat(host): sim_run + sim.* RPC + image.basic verifier + rdkctl sim run
L2 product path: sim_run stages the reviewed template, exercises policy
honestly (R2 bpu -> REQUIRE_APPROVAL, human approves, replay with
approval_id; agent plane can never self-approve), drives the sim device over
the shared stdio protocol and verifies with image.basic/json.assert/exit
verifiers. AGENT_METHODS gains sim.evaluate/sim.export_stl/sim.run (AT-021 pin
updated). image.basic parses PNG/JPEG headers, never fails open.
2026-08-27 16:03:16 +08:00
Codex
4d30e0d96b feat(sim): L2 run_program backend — reviewed templates execute on virtual board
SimProgramBackend(UserProcessBackend) with two fail-closed boundaries:
staged source must exactly equal the reviewed template digest (CFR-027,
model-crafted programs never execute) and the environment is 100%
backend-controlled (manifest env ignored; rdk_virtual_board shim injected).
Headless rdk-agent-sim run + pipeline.run_template_on_virtual_board share the
same executor. Also fixes a latent SyntaxError in the health-card template
(brace-less dict comprehension is invalid Python).
2026-08-27 16:03:16 +08:00
Codex
0231d6d7ba data(sim): virtual board ground truth = accessory snapshot (probe_set 1.2.0)
s100p.json regenerated from s100p-accessory-snapshot.json (peripherals,
software.tros_distro, 6 capabilities) with virtual_facts frozen decimals and
a provenance ground_truth_note documenting the bpu FIND-002 contradiction
(not silently resolved; real-device matrix untouched). interface_fidelity.json
becomes the full 12-row three-tier enumeration (ADR-019 §11 open item 2).
Pinned test expectations updated accordingly.
2026-08-27 15:28:24 +08:00
Codex
cb4dfa418d feat(sim): rdk_virtual_board shim — deterministic L2 board API
system.facts() (snapshot resources + frozen decimals), camera.frame()
(hand-rolled byte-stable PNG, dims bounded), bpu.infer() (sha256-derived
labels/scores, reviewed model digests only, fail-closed). Pure stdlib, no
clock/random; every result carries origin=simulation + provenance.
2026-08-27 15:28:23 +08:00
Codex
4effbb81d2 refactor(core): reviewed-template registry in core + L2 digest gate helpers
Templates live in rdk_agent_core so the host (staging) and the sim device
(L2 reviewed-source digest gate, ADR-019 / CFR-027) share one source of
truth; host/templates.py becomes a compat shim. Adds
template_source_digest()/reviewed_template_digests(), per-template resources
and extra artifacts/verifiers, and the usb-camera-snapshot /
bpu-static-inference reviewed templates (virtual branches use the
rdk_virtual_board shim; real branches fail closed with exit 3 until the real
camera/BPU paths are evidenced). health-card/temp-watch gain virtual branches.
2026-08-27 15:28:23 +08:00
Codex
fc5bb9b74a evidence(sim): record independent test verdict (AT-034..037 all pass)
Some checks failed
ci / python (pull_request) Has been cancelled
ci / typescript (pull_request) Has been cancelled
2026-08-27 12:17:59 +08:00
Codex
8bfb4bbcb7 test(sim): independent test-agent suite for SIM-R1 (AT-034..037)
91+ tests authored and frozen by the independent test agent per
AGENTS.md dev/test separation: unit (DeviceSpec invariants, circuit/
kinematics/geometry/virtual-board/backend), contract (13-method protocol,
ticket fail-closed, stage tamper), integration (register->inventory->
evaluate/export, origin split), acceptance TestAT034..037, golden traces
(tests/golden/sim, zero-tolerance digests, STL byte digests pinned to
macOS arm64 with structural invariants elsewhere).
Final verdict: AT-034..037 all pass; 753 tests green; core branch
coverage 96.27% (>=90 gate).
2026-08-27 12:17:11 +08:00
Codex
25bae5c461 docs(sim): clarify AT-034 scenario semantics; refresh smoke evidence 2026-08-27 11:45:55 +08:00
Codex
37b3f03c91 fix(sim): test-agent defects D1-D4 — NUL strip, path containment, stall scenarios, fail-closed
D1: regenerate virtual-board facts with the trailing NUL actually removed
(provenance claim now true).
D2: assert_within_root resolves the combined path before the containment
check; PartInstance.id restricted to a path-safe charset at the schema
boundary (schemas regenerated).
D3: stall scenario split per clarified AT-034 — 'stall' (healthy battery:
per-channel avg >=1.5x nominal + overcurrent) and 'stall_weak' (worn
battery 8x r_int: undervoltage); the two criteria cannot coexist in one
scenario physically.
D4: backend transitions STAGING before label validation so an illegal
sim.kind reaches terminal FAILED (QUEUED only allows STAGING).
2026-08-27 11:45:55 +08:00
Codex
fc22a69130 chore(sim): drop unused wall-time constant 2026-08-26 20:19:58 +08:00
Codex
7b3d582636 evidence(sim): SIM-R1 deterministic smoke (digest-stable verdicts, budgets) 2026-08-26 20:11:03 +08:00
Codex
6b96769211 feat(host): sim evaluate/export orchestration, sim-stdio connector, origin split
Typed bounded ops sim_evaluate/sim_export_stl over the existing
Plan/Run path (fixed-label manifest passes PolicyEngine unchanged at R0);
connector_for/_connector_for_inventory SIM_STDIO branches with host-built
fixed argv (RDK_SIM_COMMAND); origin cross-check demotes mismatched claims
to unknown with WARNING; report_task evidence_by_origin split; rdkctl sim
provision/evaluate/export + device register --transport sim-stdio.
2026-08-26 20:11:03 +08:00
Codex
58353c9a31 feat(sim): rdk-agent-sim package — virtual board L1, circuit/kinematics/geometry
Rewritten from zero per ADR-019 (name reused, nothing carried over):
- stdio DeviceServer reusing rdk_agent_device.DeviceServer with
  snapshot-driven L1 inventory (real S100P facts, NUL-stripped, provenance
  header; annotated-mock limitations on bpu/camera) and SimExecutionBackend
  (label-driven, staged-source re-verified, never executes staged code);
- circuit layer: netlist-driven MNA + explicit Euler, PWM H-bridge with
  freewheel path, stall/undervoltage/overcurrent verdicts, deterministic;
- kinematics/stability: diff-drive preview integration, CoM support-polygon
  and quasi-static margins (pure math, no physics engine);
- geometry: build123d==0.11.1 parametric solids from reviewed templates,
  binary STL + BOM + printability verifier, 900KiB per-part budget;
- RunRegistry origin stamping (simulation / real_device); numpy pinned
  2.2.6 (stub/py3.10-mypy compat); CI mypy covers the new package.
2026-08-26 20:11:03 +08:00
Codex
777d95c367 feat(core): DeviceSpec aggregate, RunRecord.origin, sim-stdio transport
ADR-019 §4: versioned DeviceSpec (mechanical/electrical/control with
per-parameter provenance, content-addressed spec_id); RunOrigin enum +
RunRecord.origin additive within schema 1.0 (None=unknown, never real);
TransportType.SIM_STDIO; schemas + golden example regenerated in the same
commit (byte-stability gate).
2026-08-26 20:11:03 +08:00
Codex
e0947c38b7 docs(sim): accept ADR-019, register sim in 00/02/03/06, reserve AT-034..037
- ADR-019 Proposed->Accepted; §11 open items closed (OCC wheel evidence,
  L1 interface scope, RunRecord.origin naming); license note frozen.
- docs/00 §4 decision line; docs/02 §4.16 sim component; docs/03 §2.10
  DeviceSpec aggregate; docs/06 §2 SIM track row.
- TEST_STRATEGY §2 sim layer + §12.2 determinism contract (digest-equality
  goldens, fixed dt, decimation, float-tolerance rule).
- TRACEABILITY dated SIM-R1 section; ADR-017 dangling refs repointed to
  ADR-019 (ACCEPTANCE_TESTS + TRACEABILITY).
- ACCEPTANCE_TESTS: AT-034 circuit verdicts, AT-035 kinematics determinism,
  AT-036 STL/printability, AT-037 virtual-board L1 fidelity + origin split.
- remove dead tests/unit/sim_controller_stub (legacy Webots leftover).
2026-08-26 19:20:43 +08:00
Codex
a51c346cf9 evidence(sim): SIM-R0 open item — OCC wheel/typing smoke on macOS arm64
ADR-019 §11 open item 1 resolved: cadquery-ocp-novtk 7.9.3.1.1 wheels cover
macOS arm64/x86_64, manylinux x86_64/aarch64, win_amd64 for cp310-cp314;
build123d 0.11.1 py.typed + cadquery-ocp-stubs pass mypy --strict without
overrides; boolean/volume/STL-export smoke exact. Geometry kernel frozen.
2026-08-26 19:13:14 +08:00
Codex
4670e4b996 refactor(sim): remove legacy Webots sim system; archived to rdk-sim-webots-legacy
The old simulation system (ADR-016: Webots physics + deterministic state
machine) moved wholesale to /Users/d-robotics/Documents/rdk-sim-webots-legacy
(standalone git repo, byte-verified copy). This commit excises every hook:

- packages/rdk_agent_sim deleted (assets/worlds/controllers/scenarios included)
- rdk_agent_core: simulation.py removed; environment_kind dropped from
  ExecutionPlan/RunTicket/RunRecord; TransportType.SIM_STDIO removed
- rdk_agent_device: --environment-kind flag, ticket environment check and the
  now-unused public run_dir accessor removed
- rdk_agent_host: board_in_loop orchestration (world spawn/finalize, sim env
  injection, remote-forward connector) removed; sim_command/environment_kind
  config removed; per-environment report grouping removed
- schemas: scenario/oracle/preflight/hardware-profile removed; plan/ticket/
  record/registration regenerated (SIM-R0, superseded by upcoming ADR-017)
- tests: 19 sim test files deleted, AT-028 report-separation class removed
- docs: AT-028..031 archived (pointer left; new acceptance resumes at AT-034),
  sim evidence + ADR-016 + backfill plan archived

Gates: ruff/mypy clean, 657 passed, core coverage 95.9%, no schema drift.
2026-08-26 16:19:42 +08:00
Codex
52ceddf13c docs(calibration): backfill LeKiwi servo electrical params from STS3215 datasheet
First legitimate calibration step for the lekiwi-v1 embodiment (backfill plan
sanctions vendor_datasheet for ELECTRICAL params; geometry still needs the
physical fixture):

- LeKiwi uses Feetech STS3215 bus servos (SO-ARM101 + base, 1:345 gear).
  Feetech/Seeed datasheets (consistent across sources): no-load 52 RPM @7.4V
  = 5.45 rad/s, stall 19.5 kg·cm @7.4V = 1.91 N·m.
- LEKIWI_ROBOT_PARAMETERS now carries those for arm/gripper max_velocity +
  max_torque (source=vendor_datasheet). GEOMETRY stays placeholder — wheel
  radius / half-track / arm links / joint limits / gripper closure still need
  real LeKiwi caliper measurement (gated on the calibration fixture).
- Provenance: calibration_status placeholder→partial, hardware_profile_version
  0.1.0→0.2.0, parameter_source=vendor_datasheet+placeholder.

The DIY record (ROBOT_PARAMETERS) and its three-source parity guard are
untouched. Electrical backfill updates the canonical provenance record, not
runtime behavior (the .wbt motor constants + action_runtime globals are the
later wiring step). Parity + embodiment tests, ruff, mypy --strict all green.
No sim-to-real claim — geometry remains placeholder.
2026-08-26 11:56:40 +08:00
Codex
52a848b5b2 feat(sim): LeKiwi physics world — detected embodiment now grasps in Webots (AT-031)
The lekiwi-v1 embodiment (selected from the attached chassis board) now has a
real Webots world, unlocking physics fidelity for the detected robot instead of
blocking it:

- assets/worlds/lekiwi_grasp.wbt: S100P + round deck + arm + gripper + front
  camera grasping the red cube. Placeholder geometry (ADR-016 §12). The drive
  is a DIFFERENTIAL two-wheel stand-in for the real LeKiwi 3-wheel Kiwi
  (holonomic) base — the omni-wheel contact variant lost traction in Webots
  (wheels spun, robot stayed put), so the proven differential drive is the
  honest placeholder; holonomic drive + SO-ARM101 6-DOF are documented
  calibration-stage refinements (backfill plan).
- Oracle supervisor now tracks the robot by name per embodiment world
  (red_cube_robot OR lekiwi_robot) — previously it only found the DIY robot,
  so LeKiwi ground truth read a stale [0,0,0].
- Registry: lekiwi-v1 physics_world = lekiwi_grasp.wbt; the not-modeled gate
  now uses camera-only (physics_world=None) as its fixture.

Verified: test_lekiwi_world_grasps_with_physics — Supervisor-measured ~0.19 m
roll, camera sees the cube, oracle inside_gripper pass; DIY physics + the
out-of-reach negative control still green. Full suite + ruff + mypy --strict
clean. Evidence: docs/testing/evidence/LEKIWI-PHYSICS.md. No sim-to-real or
calibration claims — geometry stays placeholder.
2026-08-26 11:53:09 +08:00
Codex
d4086b6b81 feat(host): board_in_loop product orchestration proven on the real S100P (AT-030 §3 done)
The full production chain now runs end-to-end on the real board — exactly
the path the four product surfaces share:

  TOFU host-key (fetch → verify vs recorded baseline → confirm, fail-closed
  on mismatch) → register_ssh_device → inventory via per-device connector →
  select_embodiment → world service → plan/ticket/record
  provenance=board_in_loop → run.stage → real non-root student run →
  SSH -R loopback data plane → world finalize (oracle) → report.

Real-run result: run succeeded, environment_kind=board_in_loop, embodiment
lekiwi-v1 (detected from the attached chassis board, USB 1a86:55d3), oracle
pass, 7/7 capability calls over the data plane. Evidence recorded in
docs/testing/evidence/board-in-loop-orchestration/ (ticket key redacted;
only public host-key fingerprints recorded).

Also fixes a latent finalize bug the real run exposed: _finalize_world_service
pre-closed the world's stdin before communicate(), whose flush of the closed
file raised ValueError; communicate() now closes stdin itself, with a salvage
path if the world already exited.

Security handling: the host key is never blindly trusted (baseline comparison
fails closed), and RDK_TICKET_KEY is read from the environment only — never
written to any file, log or evidence. scripts/drive_board_in_loop_real.py
makes the chain repeatable.
2026-08-26 11:12:29 +08:00
Codex
f622e41b34 docs(evidence): real-board LeKiwi embodiment verification (AT-031)
Completes the interrupted real-hardware check now that the board link is
back: lsusb confirms the LeKiwi chassis board (1a86:55d3) attached, and
the verified run shows
- lekiwi-v1 + webots -> blocked(embodiment_not_modeled) on the real host
  (honest, exit 4 — no DIY geometry substitution);
- lekiwi-v1 + deterministic: ready carries embodiment=lekiwi-v1, the real
  student program executes 7/7 capability calls over ssh -R from the S100P,
  and finalize reports environment_kind=board_in_loop, oracle pass;
- artifact SHA-256 digests recorded (token redacted, per hygiene).

Placeholder stance unchanged: no calibration / sim-to-real claims; LeKiwi
physics stays blocked until a 3D asset exists.
2026-08-26 10:49:34 +08:00
Codex
b548dabe26 feat(sim): simulation embodiment follows the DETECTED device (AT-031, ADR-016 §14)
Connected boards and accessories are not fixed, so the simulated robot can
no longer be hardcoded. The embodiment is now selected from OBSERVED device
facts via a curated, versioned registry (model SELECTION, never capability
inference — accessory product names stay out of device snapshots, AT-002).

Core (rdk_agent_core.simulation):
- EmbodimentProfile + EMBODIMENT_REGISTRY: default DIY virtual robot
  (the only one with a .wbt), lekiwi-v1 (matches the LeKiwi chassis board,
  USB 1a86:55d3 / ttyACM evidence), and rdk-camera-only-v1.
- select_embodiment(snapshot) -> (profile, reason); reason is structured
  provenance for events/reports. No board / no accessory -> default DIY
  virtual robot, honestly labeled (boardless-student path preserved).

Sim runtime:
- Capability surface narrows to declared ∩ implemented (ADR-016 §7); sim
  inventory (capabilities + identity.model) is generated per embodiment.
- Two fail-closed gates: scenario needs vs declared capabilities
  (embodiment_incompatible) and physics fidelity without a 3D asset
  (embodiment_not_modeled, ADR-016 §8 blocked semantics; deterministic
  fidelity unaffected).
- kinematics HARDWARE_PROFILE / LEKIWI_HARDWARE_PROFILE derive from the
  registry (single source); LeKiwi params remain §12 placeholders.
- scenario_for() picks the grasp task for full-motion forms and a new
  camera-only "look" task (oracle gains a geometric `visible` relation,
  truth from supervisor-measured poses) for camera-only forms.

Host:
- start_board_in_loop_run now inventories the board first, selects the
  embodiment on the trusted path, gates, and launches the world service
  with --hardware-profile; selection is recorded as a policy.enforced
  event and returned in the result. Registered SSH devices inventory via
  their per-device connector.

Tests: 11 new embodiment unit tests + 4 board_in_loop integration cases
(lekiwi runs the grasp across processes; un-modeled physics blocks).
Full suite green; ruff + mypy --strict clean.

Also folds in the interleaved same-tree work it depends on: the teleop
manual-driving tool (rdk-agent-sim teleop) and the per-device inventory
routing fix, both from the concurrent session. NOT included: unrelated
rdk-agent-surface/GUI WIP left for that session to commit.

No sim-to-real or calibration claims: LeKiwi stays placeholder until the
backfill plan's measurement steps run.
2026-08-25 18:01:58 +08:00
Codex
0d646fa061 docs(knowledge): cover X-series (X3/X5) alongside S-series in rdk-knowledge
- X3/X3 Module 5 TOPS (CM4-compat), X5 10 TOPS 8-core A55 (2 MIPI+4 USB3)
- OS Ubuntu-based per line; BPU via PyPI hobot-dnn-rdkx5
- board model still resolved from live inventory, never guessed
2026-08-25 16:09:00 +08:00
Codex
7ddb0c3d68 docs(evidence): board_in_loop real-board data-plane verification (AT-030, partial)
The cross-machine data plane now has real-hardware evidence: the stdlib
student program ran on the actual S100P (python3.10) and drove the full
grasp sequence through ssh -R into the Host-hosted world — 7/7 capability
calls ok, oracle pass, episode carries environment_kind=board_in_loop
without leaking ground truth, oracle stays in its own namespace. Artifact
SHA-256 digests recorded; the ephemeral run token is redacted (never
committed).

Also ships scripts/drive_board_in_loop_dataplane.sh so the check is
repeatable without product registration/ticket.

Explicitly NOT covered (human-authority steps, runbook in the doc):
device registration + TOFU host-key confirmation, RDK_TICKET_KEY
provisioning, and the full product orchestration path through
start_board_in_loop_run; plus a webots-fidelity board run. No
sim-to-real and no calibration claims: parameters remain
calibration_status=placeholder, and no actuator on the board was touched.
2026-08-25 16:01:41 +08:00
Codex
ca2ed8c7c4 feat(knowledge): RDK domain cognition so the agent out-knows generic coders
- rdk-knowledge skill grounded from the official doc center: board lineup +
  TOPS/cores/interfaces, OS/BPU/TROS facts, accessory compatibility + current
  availability rules (USB cam / MIPI / stereo / BMI088 / servo-PWM denied)
- appended to the system prompt so the model always has RDK cognition; also
  discoverable via listSkills; answers use facts + capability matrix, no guess
- pi 24 tests green
2026-08-25 15:56:27 +08:00
Codex
fe14755999 docs(calibration): refresh backfill plan + hardware baseline to the accessory reality (AT-029)
probe_set 1.2.0 evidence changed the hardware picture since the plan was
written, so the plan and baseline now state it honestly:

- LeKiwi chassis driver board (1a86:55d3 USB-CDC → /dev/ttyACM0) and a USB
  camera (1e45:0209) are CONNECTED and enumerated as read-only facts;
  camera.snapshot.usb is available (AT-013 path), while servo/motor
  actuation stays unavailable (12V not powered, no safe fixture, probes
  keep zero motor-bus interaction).
- Backfill is split into geometry (caliper-measurable without power) vs
  electrical (vendor-datasheet first, measured once the safe kit exists).
- Records the open product decision: the sim world models a generic
  2WD+3DOF DIY build while the real accessory is a LeKiwi — the sim model
  reconstruction vs same-shape-parameter backfill must be decided before
  values are written.
- Adds an UNFILLED measurement template (docs/testing/evidence/
  calibration-measurements.yaml) so the backfill is mechanical once a
  human measures; it is no calibration claim (all values null, source
  restricted to measured/vendor_datasheet).

CURRENT_HARDWARE_BASELINE bumped to v0.6: board/OS/kernel/BPU/TROS rows
carry probe-verified values, board_in_loop joins the allowed HIL list,
and the blocked list keeps servo/PWM/motor/GPIO/MIPI/flash deny.
2026-08-25 15:47:08 +08:00
Codex
d59c6b8c5d feat(sim+host): board_in_loop vertical slice — real board executes, Host hosts the world (AT-030)
ADR-016 §2's composite environment lands as a first slice: the student
program runs on the REAL S100P (s100-exec helper, UserProcessBackend —
stage/digest/cancel/cleanup unchanged), while the robot body/world is
simulated on the Host. One run, one RunRecord, environment_kind=
board_in_loop end to end; never counted as hil (report separation reuses
AT-028's environment_outcomes).

Data plane (ADR-016 §4, §5):
- CapabilityEndpoint gains a TCP mode bound to 127.0.0.1 only, plus
  observed-traffic recording so the episode is built from what the
  board program actually called (it is arbitrary code, not a fixture).
- New `rdk-agent-sim world` subcommand hosts the world (deterministic or
  webots) per run, prints a JSON ready line (port + run-bound token),
  then finalizes on a single stdin command: episode + oracle are written
  host-side under the same run_id but OUTSIDE the board run's artifact
  namespace (ADR-016 §6). EOF without finalize = safe-stop abort.
- The board reaches the Host through an SSH remote forward
  (-R board_port:127.0.0.1:host_port + ExitOnForwardFailure=yes); neither
  end binds a non-loopback interface (docs/05). Disconnect ⇒ safe stop.
- Board student program: assets/board_programs/grasp_client.py,
  stdlib-only, hand-rolled capability.call frames over TCP, reads the
  host-injected RDK_SIM_ENDPOINT/RDK_SIM_TOKEN/RDK_RUN_ID env (board
  python 3.10 compatible; same grasp sequence across fidelities, §7).

Provenance (ADR-016 §2):
- rdk-agent-device serve gains --environment-kind; the exec helper now
  declares its launch mode so ticket/environment mismatches fail closed
  device-side (previously a no-op on the real board).
- Host: start_board_in_loop_run orchestrates preflight → world service →
  board exec connector (s100-exec + forward + declared kind) → plan/
  ticket/record all stamped board_in_loop → finalize → teardown. start_run
  and plan_run take connector/environment_kind overrides; the primary
  connector path is unchanged.

Tests: 7 new unit tests (TCP endpoint loopback/token/recording, world
service protocol finalize/abort, ssh argv, env injection) and 2
integration tests running the REAL board program in a separate process
against the deterministic world (pass + idle-run negative control). Full
suite (~795) green; ruff + mypy --strict clean. No sim-to-real or
calibration claims are made — this slice stays honest about placeholder
parameters (ADR-016 §12).

(Also: ruff --fix merged an import block in templates.py and the added
noqa there keeps RUF001 suppressed for Chinese full-width punctuation.)
2026-08-25 15:43:45 +08:00
Codex
2161991503 feat(gui): skill picker + sample skill + capability matrix + model center
- workbench skill dropdown injects the chosen trusted skill body into the goal
  (GUI /skill, like '/' in other agents); preload 'skill' ns (list/read)
- sample skill rdk-temp-watch demonstrates install (drop into skills/) + invoke
- device card capabilities relabeled as capability matrix (CFR-058): unavailable
  shown up-front with probe_errors as the 'why', never guessed
- settings model center (CFR-056): edit baseUrl/model/api + save (0600 env) +
  connectivity test; secrets never enter project/conversation
- desktop 7 tests green
2026-08-25 15:38:03 +08:00
Codex
a494f48bf2 feat(tui): proactive skill invocation via /skill, like '/' in other agents
- /skills lists trusted local skills; /skill <name> [request] injects the
  SKILL.md body into the current task as a steer so the model follows it
- skills remain read-only/trusted: human picks from the local set, model has
  no skill-write tool
- unit tests for parse routing + skill discovery/read; gates green
2026-08-25 15:16:16 +08:00
Codex
359a4edad8 chore: ignore local Claude Code config (settings.local.json, launch.json) 2026-08-25 14:53:39 +08:00
Codex
6cb39b0add feat(s100): probe set 1.2.0 — read-only accessory enumeration (AT-002)
Students plugging in a chassis driver board or serial adapter previously
had zero visibility: the snapshot only said "USB present". probe_set
1.2.0 adds accessory enumeration as strictly read-only facts (FR-003–009):

- linux.usb.enumerate@2 keeps the raw lsusb list in the snapshot
  (peripherals.usb_devices: VID:PID + description). No device-class
  inference: a VID:PID never becomes "a chassis is connected".
- linux.serial.nodes@1 (ttyACM/ttyUSB/ttyAMA) and
  linux.can.interfaces@1 enumerate nodes; empty means unavailable, not a
  probe failure.
- ecosystem.lerobot@1 observes the installed LeRobot version or null.
- InventoryTarget gains serial/can/software; DeviceSnapshot gains the
  additive peripherals block (pre-1.2.0 snapshots stay valid) and
  software.lerobot_version; schemas and examples regenerated.
- rdkctl device inspect learns --refresh cached|quick|full (docs/12
  §6.2): cached reads the store, quick/full run a live inventory.

There is intentionally NO motor/servo bus probing: actuators stay
unavailable until the safe hardware kit + acceptance suite exist, and
the probes keep zero interaction with motor buses (no PING, no writes).

Evidence: PROBE-SET-1.2.0-ACCESSORY.md + a real S100P snapshot
(serial_hash null, no secrets). AT-002 updated: accessory fields in
scope, raw-fact and zero-motor-interaction pass conditions added.
Student journey: connecting an accessory shows up as honest enumeration
facts in Device Center, never as guessed capabilities.

Gates: full unit suite green (plugin + cli inspect tests); no device
writes anywhere in the new probes.
2026-08-25 14:53:08 +08:00
Codex
e0a76d475e feat(sim): single-source robot parameters with provenance + py39 controller compat (AT-029)
ADR-016 §12 requires placeholder parameters to carry provenance, and §7
requires the deterministic state machine, the Webots controllers and the
.wbt world to share one set of physics facts. This slice delivers both:

- kinematics.py is now the canonical record: ROBOT_PARAMETERS (wheel
  radius, half-track, arm links, joint limits, motor envelopes, gripper
  closure, oracle capture, cube geometry), ACTION_ENVELOPES and
  HARDWARE_PROFILE (calibration_status=placeholder,
  parameter_source=engineering_placeholder,
  hardware_profile_version=0.1.0).
- Fixes a half-track drift defect: action_runtime.py had 0.05 inlined
  while the Webots controller and the .wbt world both used 0.14. Angular
  requests now turn identically in both fidelities. Existing golden
  traces are unaffected (all straight-line, angular=0).
- Controllers stay Python 3.9 compatible: Webots launches controllers
  with the PATH python3 (system 3.9 in a bare shell), where
  zip(..., strict=) is a call-time TypeError — invisible to import or
  py_compile, which crashed arm-fold on the real machine while uv-run
  integration tests (venv 3.12) stayed green. An AST-scan regression test
  guards against strict zip / match / TryStar creeping back in.
- red_cube_grasp.wbt viewpoint fixed (previous values rendered only sky);
  controller-connect timeout raised to 60 s for cold first launches.

Adds docs/sim-parameter-backfill-plan.md (plan, not calibration) and
registers AT-029. Student journey: a simulation run keeps behaving the
same across fidelities and never overclaims sim-to-real while the
parameters are placeholders (CFR-025 honest results).

Gates: full unit suite green (incl. 6 parity + py39-compat tests);
Webots physics integration green on R2025a.
2026-08-25 14:52:28 +08:00
Codex
3b3332983b feat(mcp): controlled MCP client (connect OUT, explicit allowlist)
- mcpClient.ts connects ONLY to servers a human wrote into the allowlist
  (RDK_MCP_CONFIG / ~/.rdk/mcp.json); external results are untrusted text for
  the human plane, never device facts/capabilities/policy inputs
- NOT exposed to the Pi agent or external MCP callers (CSEC-011/012)
- CLI: rdk-agent mcp-client list|call --server <name>
- live-tested against our own rdk-agent mcp --stdio as the external server;
  unit test asserts non-allowlisted servers are rejected
2026-08-25 14:40:19 +08:00
Codex
df90364034 feat(desktop): clickable macOS .app without electron-builder
- scripts/make-app.sh builds a thin 'RDK Agent.app' bundle whose launcher
  execs the repo-local Electron binary with the desktop package dir
- no electron-builder / no network; double-click or 'open' to enter the GUI
- dist-macos/ ignored (build artifact)
2026-08-25 11:50:05 +08:00
Codex
fa9fef8523 feat(cli): claude-like one-command entry — bare 'rdk-agent' enters TUI
- bare 'rdk-agent' (no subcommand) drops straight into the interactive TUI
- 'rdk-agent gui' launches the Electron desktop app
- auto-resolve repo-local venv host+device (walk up for .venv) so a
  npm-linked 'rdk-agent' works with no env; explicit env still wins
- TUI/MCP default to a product-owned workspace created on demand
  (CLI 'run' keeps explicit --workspace-root per docs/12 §6)
- 'rdk-agent' installed on PATH via npm link
2026-08-25 11:25:28 +08:00
Codex
59c80a9e76 feat(host+gui): deterministic one-click templates, no LLM (CFR-003/014)
- human plane template.list/template.run: reviewed fixed programs run through
  the normal plan->policy->run->verify pipeline without any model
- template.list hard-filters by observed snapshot capabilities and reports
  what is missing (CFR-014 'why runnable / what's missing')
- verifiers assert result.json exit_code==0 (produced by fake AND real
  backends); the visible deliverable (health.json/temps.json) is collected
- GUI workbench 'Quick' card: one-click run, non-runnable templates grayed
  with the missing capability named
- 4 host tests; gates green
2026-08-24 17:20:39 +08:00
Codex
5d9b822c1f feat(host+gui): human approvals inbox + recent tasks on workbench
- human plane approval.decide (agent role rejected RDK-PROTO-001; USER-only
  decision; already-decided fails closed) — the GUI was the last surface
  without a human approval entry (was rdkctl-only)
- TaskService gains a lazy human-role client (same pattern as DeviceService)
- workbench: pending-approval card (approve/reject, refreshes on decide) +
  recent-task chips (click loads the task into the console)
- gates green
2026-08-24 11:32:33 +08:00
Codex
d50dcd7d7e fix(host): offer product ssh identity only when the key file exists
A missing IdentityFile under a strict client ssh config (IdentitiesOnly)
suppressed the user's working keys and broke board auth (Permission denied).
connector_for now passes the product identity only if ~/.rdk/id_ed25519
exists; onboarding creates and installs it on first use.
2026-08-21 19:19:43 +08:00
Codex
3b77d4ccdf feat(desktop+host): serial read-only console + flashing wizard (human plane)
- human plane: serial.ports/serial.tail (read-only, redacted, never an Agent
  run target) and flash.images/suggest/confirm/run/status/cancel (suggest
  yields plan + human-only confirm token; confirm requires USER actor)
- fake engine ships a clearly-labelled rehearsal catalog (local://rehearsal);
  real write engines arrive with XBurn integration (S6); flashing is never
  automated-tested
- preload whitelist grows to 10 reviewed namespaces (console, flash);
  security tripwires updated
- GUI: 7-entry nav; console page (port chips, 2s auto-refresh, redacted log,
  honest empty state); flash wizard (image+device pick, risk confirm with
  rehearsal banner + recovery steps + acknowledgement checkbox, progress bar
  with cancel)
2026-08-21 17:53:51 +08:00
Codex
ff1d5e6850 fix(host): host-stamped snapshot freshness breaks stopped-RTC deny loop
A stopped board RTC left snapshot.captured_at permanently old, so policy
freshness.stale-denies looped forever on real hardware (agent re-inventoried
three times, still denied). Capture time is now host wall-clock at save
(_host_stamp); content addressing excludes captured_at so snapshot ids are
unaffected. Same rationale as S2's host-timed run budgets.

Validated end-to-end: kimi-k3 via the GUI-main-service chain completed the
full rdk-develop loop on the real S100P (run succeeded, verifier passed,
cpu.json artifact read back, task report completed/passed) — LEFT-006
service layer closed. Regression test for the stopped-clock loop.
2026-08-21 17:00:47 +08:00
Codex
5770288bd3 feat(devices): saved records + controlled LAN SSH onboarding
- DeviceRegistration gains optional registered_at/last_seen_at (schema-major-1
  additive; schemas regenerated); device.list exposes ssh_host/fingerprint/
  record timestamps; quick/full inventory stamps last_seen_at
- GUI device rows show the saved record (host, fingerprint prefix, registered,
  last seen) and a two-click remove (device.unregister first surfaced)
- LAN SSH boards without pre-installed keys: docs/05 §5 controlled login —
  device.auth_check (BatchMode probe) + device.onboard_key (one-shot password
  via SSH_ASKPASS temp helper installing the product ed25519 key; password
  never in argv/config/logs; temp files unlinked); connector tries the product
  identity via IdentityFile with user ssh config/agent as fallback
- wizard: after fingerprint trust, key login probe → register, or the
  one-shot 'install key and connect' step
- 3 new host tests; gates green
2026-08-21 15:18:59 +08:00
Codex
f06bb5cb4e feat(host+gui): device-scoped project spaces (one board, one space)
User product rule: project spaces must not be shared across devices.
- create_task routes '.' to the device's own space (space id = device id),
  rejects cross-device use of a bound space and multi-device tasks
  (RDK-INV-001, category WORKSPACE_DEVICE); bindings persisted atomically;
  run_pack ephemeral workspaces registered too; host is the source of truth
- surface startTask mirrors the routing; '.' + multi-device fails fast
- GUI project page: per-device chips, browse + edit pass workspaceId;
  device list refreshes on page return
- TestWorkspaceDeviceBinding 4 cases; gates green
2026-08-21 14:33:30 +08:00
Codex
13c9aa54a2 merge: integrate main (S3-S6) with redesigned GUI + human authority plane
- keeps the human authority plane (--role human) for register/TOFU/discover;
  model-facing AGENT_METHODS untouched
- adopts main's S3-S6 services (packs/real-model config/connections) and
  surfaces them in the redesigned renderer: works = real Pack list/re-run,
  settings = local facts + model gateway editor (key masked, 0600 env),
  project = workspace browser + editor via the host service
- preload whitelist grows to 8 reviewed namespaces; tripwire tests updated
- task lifecycle tests adapted to main's _advance_task anchor
2026-08-21 11:25:50 +08:00
Codex
b24e9fb8d2 feat(desktop): redesigned GUI + real device connect/card/project/settings/console
Google AI Studio-style redesign (tokens in renderer/styles.css) with every
page real except 作品 (S3-constrained placeholder):

- 设备: auto-discovery connect wizard (pick candidate + confirm fingerprint,
  manual entry folded), device card rendering real inventory snapshots,
  honest host_key_confirmed badges
- 工作台: device chips bind tasks to boards; task console = event timeline
  with steer/resume/cancel, required_action human-only notice, 2.5s poll,
  raw JSON folded under 进阶
- 项目: read-only workspace browser (ProjectService bridge)
- 设置: secret-free local facts; gateway presence only, values never cross
- preload whitelist extended to 5 namespaces; security tripwires updated
- force-renderer-accessibility; RDK_DESKTOP_REAL_SMOKE real-device chain
- evidence S1C-DEVICE-CONNECT §1-9 (real S100P acceptance incl.)
2026-08-21 10:57:07 +08:00
Codex
eb68cdf00c feat(s100): probe set 1.1.0 aligned with official RDK docs + real board
- rdkos_info: /etc/version + uname -sr parsed into rdk_os_version/os/kernel
- resources/thermal: actually parse MemTotal/df/nproc and thermal zones
- bpu.runtime: rdkos_info [CPU And BPU Status] section (libdnn is X-series;
  always rc=2 on S100P), first bpu telemetry line, empty section fails closed
- tros.distro lands in software.tros_distro
- rdk-develop skill: official doc-center references as coding hints
  (observed facts still only from inventory)
2026-08-21 10:56:53 +08:00
Codex
69ac2a7784 feat(surface): DeviceService human-role client + ProjectService
- DeviceService second client spawns 'serve --stdio --role human':
  showHostKey/confirmHostKey/registerDevice/unregisterDevice/discoverDevices
- ProjectService: read-only workspace.list/read for the GUI project page
- barrel exports extended explicitly (package entry contract kept)
2026-08-21 10:56:53 +08:00
Codex
3966df3d1b feat(host): human authority plane — register/TOFU/discover via --role human
Human-only device authority (docs/05 §7, docs/12 §4) exposed on the stdio
protocol without touching the model-facing AGENT_METHODS (AT-021, CAT-006B):
serve --stdio --role human dispatches AGENT_METHODS ∪ HUMAN_METHODS; agent
role rejects human methods with RDK-PROTO-001.

- hostkey.show/confirm (TOFU, sanitized: public_key never crosses),
  device.register (system-generated dev- ids), device.unregister,
  device.discover (bounded read-only: RNDIS default first, RFC1918 /24
  scans with direct-link (no default route) subnets first, TCP 22 only)
- service wrappers off service._config; known_hosts.load_candidate;
  ed25519>ecdsa>rsa key preference; ssh_host_identity() strips login user
  for verification; remote helper gets --device-id (S1A-DEBT-001 port)
- rdkctl host-key segment now calls the same service methods
- regression tests incl. agent-role rejection and ifconfig parsing
2026-08-21 10:56:35 +08:00
Codex
8bfd070ba3 feat(desktop): real-device GUI smoke (RDK_DESKTOP_REAL_SMOKE=1)
A smoke that launches the Electron window then drives the RENDERER's
window.rdk bridge via executeJavaScript — exercising preload -> IPC ->
TaskService -> real model -> real board, without a human clicking. Polls
task status to a terminal state (9m) and prints a DESKTOP_REAL_SMOKE_OK/
FAIL/TIMEOUT sentinel.

Validation: launched against the real S100P with kimi-k3; the renderer bridge
created a task and the real model ran inventory/write/checkpoint/plan/report
through the GUI path. The GUI wiring (renderer -> preload -> IPC -> real
model -> real device) is proven end-to-end. (Model non-convergence — kimi
skipping run_start on a given run — is the known non-deterministic gap, not
a GUI defect; the CLI path converges on the same TaskService.)
2026-08-20 11:29:56 +08:00
Codex
94b0106c1b fix(S2): auto-bind runs to their task when the model omits task_id
The agent loop's last closeout gap: the model often calls rdk_run_start
without task_id, so the run succeeded but wasn't linked to its task — the
task stayed 'created' even after a passed run, and report_task couldn't
complete it. Start_run now resolves a task binding when task_id is None: if
exactly one non-terminal task shares the plan's workspace, bind to it
(don't guess when multiple match). The run then links, the task advances to
verifying on the terminal observation, and report_task completes it.

resume context injection (reconcile + checkpoint + goal/state/runs/
unsatisfied-verifiers re-injected into the session) was already in place.

Tests: test_run_auto_binds_to_task_when_model_omits_task_id,
test_no_autobind_when_multiple_tasks_share_workspace. pytest 683, ruff/mypy
clean.
2026-08-20 11:05:29 +08:00
Codex
51aa27bfe7 feat(desktop): in-GUI device connections — launch without env
The last GUI gap: the device SSH connection (host/user/key/ticket) was only
settable via launch env. Now the GUI manages it:

- deviceConnections.ts: ConnectionStore (persists userData/connections/
  device-connections.json 0600). The ticket HMAC key is a SECRET — it goes to
  the macOS keychain (security CLI) or a 0600 keyfile off-macOS, never the
  JSON. Host key pinned by TOFU: keyscan on add -> append to the product
  known_hosts -> store the SHA256 fingerprint for StrictHostKeyChecking.
  buildSshDeviceCommand(conn) assembles the RDK_DEVICE_COMMAND ssh argv.
- mainImpl: on startup, applyActiveConnection() materializes
  RDK_DEVICE_COMMAND/TICKET_KEY/DEVICE_ID from the first saved connection
  (explicit env still wins for CLI users). connection:list/add/remove IPC.
- 设备 page: saved-connection list + add form (name/host/user/device_id/
  profile/ticket key) with a fingerprint readout + remove.

The GUI now launches with no device env: configure the connection in the
设备 page once, then npm start anywhere. typecheck+build+7 tests green;
pytest 681, ruff clean.
2026-08-19 17:16:44 +08:00
Codex
19b73ff98b feat(desktop): settings + project pages — model config GUI + workspace editor
The two remaining GUI pages were placeholders; wire them to the real flow:

- 设置: read/write ~/.rdk/.env from the GUI. config:get masks the key (last 4);
  config:set writes baseUrl/model/api + optional new key (empty keeps the old).
  pi package gains writeRealModelDotEnv + defaultRealModelDotEnvPath; surface
  re-exports them so the desktop (single dep on surface) can use them.
- 项目: workspace file tree + read/write editor. workspace:list/read/write IPC
  against the product workspace root, sandboxed (no .. / absolute / escape).
  Lets the user browse + edit the agent's workspace without a terminal.

Now all five GUI entries are wired (workbench/device/works/project/settings);
no more PhaseNote placeholders. typecheck+build+tests green
(pi 24/5skip, surface 65/0, desktop 7/0, pytest 681).
2026-08-19 16:45:34 +08:00
Codex
577ee51fe9 feat(desktop): wire GUI to the real flow — workbench + device + packs
The Electron shell was a minimal S1-B health-card demo (only 工作台, fake
device, scripted model). Wire it to the real pipeline:

- 工作台: free-form goal + device id (default s100p-001), start/status/cancel.
  TaskService now sends the user's goal to the session (goal-driven prompt),
  and defaultModelFactory uses the real model from ~/.rdk/.env — so the GUI
  drives the real agent loop on the real board when launched with the device
  env (RDK_DEVICE_COMMAND / RDK_TICKET_KEY).
- 设备: inspect (quick refresh) shows the real DeviceSnapshot + capabilities.
- 作品: list saved Project Packs + re-run a pack with no LLM (pack.list/run IPC).
- 项目/设置 remain honest phase notes.

preload + security expose a new pack surface (list/run); mainImpl wires
pack:list/run IPC to TaskService.listPacks/runPack. typecheck+build+7 tests
pass.
2026-08-19 16:29:16 +08:00
Codex
52ffa01d54 feat(S4/S5/S6): capability matrix + serial read-only + flashing wizard + replacement-matrix gate
S4 (设备中心补齐):
- capability_matrix.py: per-board capability support (supported/degraded/
  unavailable) with S100P + generic-SSH matrices; unknown boards fail closed;
  serial-only link is never Agent-runnable. Classify is the pure decision the
  device center and Agent both consult (docs/06 §8.1, docs/11).
- serial_console.py: discover /dev/cu.*/tty.* + a READ-ONLY log tail with
  high-confidence secret redaction. Policy: serial is never an Agent-run
  target and never Agent-writable; the Agent only reads redacted lines
  (§8.2 — don't mistake a serial link for an Agent-run target).

S5 (系统准备烧录):
- flashing.py: FlashState machine (idle->selected->confirmed->writing->
  verifying->done/failed/cancelled), FlashImage catalog, FlashManifest with
  recovery steps + a human-only confirm token.
- flashing_service.py: FlashingService — Agent-facing suggest_flash (builds
  the wizard plan, NEVER executes); human-only confirm_flash (rejects any
  non-USER actor — FLASH_AGENT_DENIED); pluggable write engine; fake engine
  covers the state machine. The real XBurn engine runs only under human-watch
  HIL (§9.1; CLAUDE.md: Agent never triggers the final flash).

S6 (替代发布门禁):
- docs/11 replacement matrix gains an 证据 column per row (automated/HIL/
  usability or honest pending-<phase>); scripts/check_replacement_matrix.py
  machine-checks every row has an evidence cell; S6 closure asserts pending==0.

Gates: pytest 681 (+14), ruff/mypy clean (48 files).
2026-08-19 16:09:59 +08:00
Codex
b12bb7e765 feat(S3): Project Pack — save/list/run capability without an LLM
A Pack freezes a run's source + manifest into a named, reusable capability:
save_pack (freeze workspace source + plan manifest), list_packs, run_pack
(re-stage + re-plan + start_run with NO model in the loop — deterministic
replay of a saved capability). Pack + FilePackStore (state/packs/<name>/).
Host frames pack.save/list/run + server dispatch; TS tools rdk_pack_save/
list/run in the allowlist; CLI 'rdk-agent pack save/list/run'. Contract
tests (AT-021 + TS allowlist) updated for the 3 new methods.

Real-device evidence (scripts/drive_s3_pack.py, kimi not in the save/run
loop): agent's cpu_sampler run succeeded/passed -> pack.save 'cpu-sampler'
-> pack.list -> pack.run produced a different run_id, succeeded/passed,
no LLM. The capability is now retained and re-runnable.

Also: journey battery (4 varied capabilities on real S100P — USB enumerate,
thermal hottest-zone, network interfaces, top-mem — each a different
program, all succeeded/passed, no collapse) + the goal-driven-prompt and
json.assert key-existence harness fixes that made real-model coding work.

Gates: pytest 667, ruff/mypy clean (44 files).
2026-08-19 15:57:19 +08:00
Codex
3c35075f9a fix(S2): make the agent actually code on the device — goal-driven prompt + json.assert existence
The agent kept writing a health card regardless of the requested task. Root
cause was a harness bug, not the model: TaskService.startTask hard-coded the
session prompt to '启动系统健康卡' (S1-B scripted-demo legacy), so the user's
goal was stored in the task record but NEVER sent to the model. Every real-
model run therefore received 'start a health card' and produced one.

Fixes (harness, model-agnostic):
- startTask now prompts the session with the user's actual goal + a
  workflow nudge, not a hard-coded health-card string.
- json.assert gained a key-existence mode: omit 'equals' to assert the path
  is present and non-null (for variable outputs like busiest_core that the
  model can't predict). 'equals: null' still means strict null. The skill
  was telling models to use equals:null for existence — wrong; corrected.
- skill diagnose guidance: exit=0 + json.assert fail => verifier config is
  wrong, not the program; fix the manifest verifier (re-plan), don't
  rewrite a program that already exits 0.
- skill manifest example abstracted (no complete health-card to copy);
  verifier-alignment guidance.

Real-device result (kimi-k3, openai-responses gateway, S100P): the agent
wrote cpu_sampler.py (read /proc/stat twice, compute per-core usage %),
ran it on the board, iterated with fresh request_ids, converged to
run succeeded / outcome=passed / task completed. Device artifact cpu.json
holds real per-core CPU usage (6 cores). The agent can now CODE a novel
embedded capability on the device, not just replay a health card.

Gates: pytest 666, pi 24/5skip, surface 65/0/4, ruff/mypy clean.
2026-08-19 14:28:31 +08:00
Codex
1cac0ffc27 feat(S2): iteration loop + verifier alignment in rdk-develop skill
Driving kimi-k3 on a coding task exposed three harness gaps, now fixed in the
skill (the one channel the model reads, via appendSystemPrompt):

- Iteration section: on a failed run, diagnose via artifact/stdout/events,
  workspace_patch, RE-PLAN (source digest change invalidates the old plan,
  AT-003), and re-run with a NEW requestId (reusing one is an idempotent
  replay that executes nothing). This was the core blocker: the model reused
  request_ids, so re-runs were no-ops and it never converged.
- Verifier-alignment section: json.assert path/equals must match the JSON the
  program ACTUALLY writes; a program that exits 0 but whose verifier path is
  absent is a failed run, not a pass.
- Manifest example abstracted to a skeleton (no complete health-card program
  to copy) so the model writes the user's task, not the example.

Result on real S100P with kimi-k3: the loop now converges — write -> plan ->
run -> verify -> report, task-linked, fresh request_ids, run
succeeded/passed, task completed. Residual: kimi-k3 still defaults to writing
a generic health card regardless of the requested task (CPU sampler) — a
model task-adherence limit, not a harness defect; a stronger model would
follow the specific task. Gates: pytest 664, ruff/mypy clean.
2026-08-19 12:09:22 +08:00
Codex
a526d2e0b1 docs(S2): real-model real-device evidence (kimi-k3) 2026-08-19 11:44:48 +08:00
Codex
bc6b8edd8e feat(S2): real-model real-device loop validated (kimi-k3 via openai-responses gateway)
The product agent loop now completes end-to-end with a real LLM on the real
S100P, not just the scripted model. Three root causes found and fixed by
driving Qwen then kimi-k3 against the board:

1. rdk-develop SKILL.md was never reaching the model (noSkills suppresses
   discovery; no skill-read tool is allowlisted). Inject the SKILL.md body
   into appendSystemPrompt alongside task-summary.md — the one channel the
   model always reads. Added a concrete Run manifest shape example
   (entrypoint/requirements/resources/artifacts/verifiers) so models stop
   inventing {steps,capabilities,intent,...} schemas.
2. device.inventory rejected free-text 'reason' (TS advertises Type.String,
   host enforced InventoryReason enum) — a contract mismatch that stalled
   every non-Claude model at inventory. Host now coerces unknown reason ->
   USER_REQUEST and drops unknown targets (DeviceInventoryParams validators).
3. task-summary.md said 'M0 only fake-001, S100P does not exist' — stale,
   biased models into refusing s100p-001. Updated: s100p-001 is a verified
   real-device target; rdk_device_list empty on a fresh state dir does not
   mean unavailable; inventory the user-named device directly.

Real-device result (kimi-k3, ai-api.d-robotics.cc/v1, openai-responses):
inventory -> write -> checkpoint -> plan (valid manifest) -> run_start ->
run succeeded / outcome=passed / exit=0 / cleanup=confirmed on the S100P.
Residual: the model did not task-bind the run (created the task after
run_start), so task_report couldn't aggregate — workflow-ordering gap, not
a run defect; the run itself passed verifiers on real hardware.

Gates: pytest 664, pi 24/5skip, surface 65/0/4, ruff/mypy clean.
2026-08-19 11:43:52 +08:00
Codex
6f3c4017d0 refactor(S2): real-model config via a single flat ~/.rdk/.env
Replaces the keychain + keyfile + JSON-config-file machinery with one flat
0600 .env at ~/.rdk/.env (gitignored) holding four variables:
RDK_ANTHROPIC_BASE_URL / _API_KEY / _MODEL / RDK_MODEL_API. Real process.env
still overrides field-for-field. Simpler for users, fewer code paths; the
wire format stays configurable (anthropic-messages default, openai-responses
for gateways). Tests rewritten to the .env shape (6 cases).
2026-08-19 10:45:20 +08:00
Codex
f354d40a01 feat(S2): OpenAI-Responses gateway support for the real model
The real-model factory's wire format is now configurable: anthropic-messages
(default) or openai-responses for an OpenAI-Responses-compatible gateway.
Renamed the neutral surface (createAnthropicModel -> createRealModel,
REAL_MODEL_PROVIDER, resolveRealModelConfig) since it is no longer
Anthropic-specific. Config file gains an 'api' field; RDK_MODEL_API env
overrides; unknown apis reject and fall back to scripted. Tests +2
(openai-responses gateway, unknown-api rejection); 8 total.
2026-08-19 10:40:33 +08:00
Codex
1a30f4069a feat(S2): config-file gateway support for the real Anthropic model
A single 0600 file ~/.rdk/anthropic-config.json ({baseUrl,apiKey,model})
covers the custom-gateway case where all three differ from the Anthropic
defaults. Env vars still override field-for-field. Keychain and the plain
keyfile remain as key-only fallbacks. Tests +2 (gateway config, env override).
2026-08-19 10:36:46 +08:00
Codex
323dfb2ec4 feat(S2): real Anthropic model wiring for the product agent loop
The product surfaces defaulted to a deterministic ScriptedModel (no network,
no credentials). docs/08 §8 specifies two real-model paths: Pi provider
login or API key. This adds the API-key path.

New anthropicModel.ts resolves the key at runtime from (in order) the
RDK_ANTHROPIC_API_KEY env var, the macOS keychain item rdk-agent/
anthropic-api-key, or the 0600 keyfile ~/.rdk/anthropic-key. When a key is
present, the TaskService defaultModelFactory writes a real
anthropic-messages provider into the per-task agentDir's models.json
(0600, under the gitignored state dir) and returns no in-process handle —
createAgentSession then resolves the model from that config and the real
LLM drives the tool loop. With no key, the deterministic ScriptedModel
fallback is unchanged (all existing tests stay green).

Model id and base URL are configurable (RDK_ANTHROPIC_MODEL default
claude-sonnet-5, RDK_ANTHROPIC_BASE_URL default api.anthropic.com).

Tests: 4 new in anthropicModel.test.ts (env/keychain/keyfile precedence,
config content, 0600 mode, null fallback). Gates: pi 22/5skip, surface
65/4skip, desktop 7/0.
2026-08-18 20:18:12 +08:00
Codex
1e9dc2895a feat(S2): agent-loop closeout — lifecycle, budgets, resume, reconcile
Closes the S2 'Agent development loop' milestone (docs/06 §6) on the
codex/s2-agent-loop branch:

- task lifecycle (slice 2): _advance_task anchors EXECUTING at task-bound
  run start and VERIFYING at terminal observation (run_status/reconcile/link);
  report_task no longer crashes on created->completed (the product path now
  drives the funnel). _adopt_terminal_device_record reconciles a terminal
  same-plan device run on host-state-loss replay instead of failing it.
- budgets (slice 3): start_run gates on task budget BEFORE device side
  effects (idempotent replay wins, AT-004); _account_terminal_run charges
  host-measured duration at terminal observation (immune to device clock
  skew); Budgets._consume clamps to limit so exhausted() reads true; report
  surfaces budget exhaustion over verifier aggregation.
- verify-on-status (slice 3): a run finishing after the start wait window
  is verified when run_status observes the SUCCEEDED transition (AT-010),
  not only in the start path.
- resume productization (slice 3): resumeTask reconciles device truth,
  freezes a recovery checkpoint, and injects recovery context (goal/state/
  runs/unsatisfied verifiers) into the session (docs/08 §6); CLI gains
  'task artifact' to read declared artifacts/success evidence.
- contract surface: task.reconcile / task_reconcile added to the AT-021
  method registry and TS allowlist.

Real device: sliceS2 scripted loop (19/0) and the disconnect-reconcile
drill (scripts/drive_s2_reconcile.py) both pass on the S100P; the drill
proves reconcile reads device truth without re-starting, orphaned runs
fail closed, and a fresh recovery run completes the task.

Gates: pytest 663 passed; pi 18/5skip · surface 65/4skip · desktop 7/0;
ruff + format + mypy clean.

Evidence: docs/testing/evidence/S2.md slices 2-3 + s2-agent-loop/ +
s2-reconcile/
2026-08-18 19:49:00 +08:00
Codex
23007d3701 feat(host): separate task report outcomes by environment_kind (AT-028)
ADR-016 §2 mandates that a simulation/board_in_loop pass never counts as
hil acceptance and that the report layer forcibly separates (报告层强制分
列). report_task now also returns environment_outcomes: verification
results are aggregated per environment group, so a grasp that passed in
Webots reports {"simulation": "passed"} — never a "hil" key. Runs without
provenance group under "unknown" instead of defaulting to hardware. The
existing aggregate outcome semantics are unchanged, and the
budget-exhausted early return carries the field too.

Registers AT-028 in ACCEPTANCE_TESTS.md and maps ADR-016 §2 →
TestReportEnvironmentSeparation in TRACEABILITY.md. Student journey: a
boardless student's passing simulation run reads as "simulation: passed",
never as hardware validation (honest-result spirit of CFR-025).

Gates: ruff/format clean; 574 unit tests pass (5 new); integration +
acceptance 30 passed.
2026-08-18 16:10:51 +08:00
Codex
1c6e7c9b97 test(sim): Webots physics regression + 2D diagram artifact + bounded tmp dirs
- tests/integration/test_sim_webots_physics.py: real-Webots regression for
  the grasp slice — positive run asserts Supervisor-measured motion
  (~0.19 m), a real camera frame with red pixels, oracle pass on measured
  geometry, and the diagram artifact; negative control moves the cube out
  of reach and requires the oracle to fail. Skips with blocked semantics
  (TEST_STRATEGY: a skip is not a pass) when the frozen R2025a is absent.
- diagram.py: human-facing ASCII 2D view of the S100P + peripherals grasp
  task annotated with the episode's ACTUAL production state (oracle truth
  is never drawn); persisted as diagram.txt run artifact by WebotsBackend.
- run_tmp.py: hash run_id into the TemporaryDirectory prefix so the
  capability socket stays under macOS's 104-char AF_UNIX sun_path limit
  regardless of run_id length; both backends use it.

Gates: ruff/format clean; 60 sim unit tests pass; integration suite
2 passed in ~4.4 s against Webots R2025a (not skipped).
2026-08-18 15:44:19 +08:00
Codex
4cfceabed7 fix(sim): ground the grasp slice in real physics, not pose guesses
The oracle previously passed whenever the cube sat near its spawn point
and the gripper was commanded closed — the robot could be flung 62 m away
and still "grasp". Rework the slice so every pass is earned:

- oracle supervisor: inside_gripper now requires the measured cube center
  inside a real capture region around the measured jaw (<=0.10 m
  horizontal/vertical) AND the jaw hinge actually closed; reports jaw and
  robot poses plus jaw-to-cube distances as ground truth
- world: explicit NUE coordinateSystem for the Y-up scene; HingeJoint
  endPoint Solids carry their own anchor translation; wheel cylinders
  wrapped in rotated Transforms so ODE collision geometry matches the
  visual wheels (R2025a lessons, recorded inline in the .wbt)
- robot bridge: firmware-side action envelopes (linear/angular/duration,
  arm joint limits, gripper range) rejected fail-closed; camera warm-up
  steps so the first snapshot is a real frame; clean exit on session EOF
- action script: fold the arm before driving (an extended arm bulldozes
  the cube), drive 0.3 m/s x 640 ms (~0.19 m), unfold onto the IK grasp
  pose, then close; timeouts track servo maxVelocity
- deterministic world: encoders report wheel radians like the real
  PositionSensor; cube spawn matched to the shared script's drive distance
- webots world: robot pose comes from Supervisor measurement, never from
  encoder odometry (odometry stays production evidence, not ground truth)

Gates: ruff/format clean; sim unit tests green; Webots physics evidence
lands with the regression suite in the follow-up commit.
2026-08-18 15:42:53 +08:00
Codex
b561dd9a34 docs(S2): Starter 1 real-device evidence + handoff progress
- docs/testing/evidence/S2.md + s2-health-card/{drive-result,health}.json:
  the full chain on the real S100P (inspect → code → plan → stage → run →
  artifacts → verify) with idempotent replay, plan invalidation, timeout
  and cancel all cleanup-confirmed; includes both real-device failure
  rounds (ssh user, relative runs-root) and their fixes.
- scripts/drive_s2_health_card.py: default to sunrise@192.168.127.10.
- scripts/install-device-helper.sh: install wipes the managed lib dir
  (pip --target never replaced stale code).
- docs/09: current task is S2; slice 1 recorded, remaining slices listed.
2026-08-17 19:44:51 +08:00
Codex
4ba161b4ee fix(S2): normalize RunRegistry root to absolute — real-device staging find
The device default runs root is RELATIVE (.rdk/runs under the Helper login
cwd). UserProcessBackend._verify_staged_source compares a resolved file path
against the unresolved source root, so every staged file 'escaped' and start
was denied on the real board (found by the first S2 health-card attempt).
Includes a relative-root roundtrip regression test.
2026-08-17 19:38:01 +08:00
Codex
197ac8316c test(S2): exec-profile integration + health-card driver + helper keygen
- tests/integration/test_exec_device_end_to_end.py: the full S2 slice over
  a real rdk-agent-device subprocess (s100-exec profile, provisioned key
  file): stage → UserProcessBackend run → declared artifact → verifier
  aggregation, plus idempotent replay, source-drift plan invalidation and
  cancel with confirmed process-group cleanup.
- scripts/drive_s2_health_card.py: production-path driver for the Starter 1
  real-device evidence (AgentApplicationService + SshDeviceConnector).
- scripts/install-device-helper.sh keygen: provision the owner-only ticket
  key file the s100-exec profile requires.

Gates: 656 pytest passed; ruff/mypy clean; core coverage 95.57%.
2026-08-17 19:20:34 +08:00
Codex
e5e4dd88c1 feat(S2): run.stage source sync + s100-exec Helper profile
Protocol 1.1 adds run.stage (docs/03 §4.4): the Host ships the plan-bound
workspace source to the device between prepare and start; the device only
accepts bytes whose per-file digests and aggregate digest match the HMAC
ticket's source binding, refuses staging after start, and treats a
same-binding replay as an idempotent rewrite. Staged source lives in the
run's source/ subtree, never next to registry files.

- UserProcessBackend runs from source/, re-verifies every staged file
  against stage.json before spawn (tamper fail-closed), and collects
  manifest-declared file artifacts from the program cwd; a missing required
  artifact is an event, never a silent pass.
- New s100-exec Helper profile: real s100 inventory + UserProcessBackend;
  HMAC ticket key from an owner-only file (default ~/.rdk/ticket_key),
  never argv, never the fake key. SshDeviceConnector gains a host-side
  helper_profile selection (default stays s100-readonly).
- WorkspaceService.iter_source_files refuses secret-named files and
  enforces the staging bounds (256 files / 256 KiB file / 768 KiB total).

Gates: 652 pytest passed; ruff/mypy clean; core coverage 95.57%.
2026-08-17 18:53:32 +08:00
Codex
624c8862ad feat(S2): UserProcessBackend — real non-root process execution
Real ExecutionBackend (docs/02 §4.11, ADR-003/012): runs the manifest
entrypoint as the ordinary user from the product run root:
- fail-closed relpath containment before any state transition (no .. escape,
  no missing-source half-started run);
- fixed cwd = run root, minimal env + manifest env allowlist, umask 0o077;
- wall-time + output-bytes bounds (policy defaults);
- new process group (start_new_session); cancel/timeout SIGTERM group ->
  SIGKILL after grace, cleanup unconfirmed only if the group can't be reaped;
- stdout.log + result.json artifacts, state machine STAGING->RUNNING->…
  (COLLECTING/VERIFYING)->SUCCEEDED/FAILED/TIMED_OUT/CANCELLED.

7 unit tests (success / non-zero / timeout / cancel-with-grandchild-kill /
missing-source / path-escape / output-cap). 628 pytest total; ruff/mypy clean.
2026-08-17 17:07:07 +08:00
Codex
f8c53c59fa fix(sim): high-contrast colors + centered viewpoint so the robot is visible
- Light ground (0.88) vs dark chassis (0.12) so the low-profile robot no longer
  blends into gray; brighter green PCB and blue arm.
- Center the fixed top-down viewpoint between the robot and the cube (0.38m) so
  both are in frame and the scene is no longer a sky/ground blob.
2026-08-17 17:00:57 +08:00
Codex
ad3d1eca47 fix(sim): follow-camera viewpoint + oracle screenshot hook
- Set Viewpoint to follow red_cube_robot (Pan and Tilt Shot) so the GUI camera
  automatically aims at the robot (follow only updates under interactive GUI,
  which is why batch screenshots looked off-target).
- Add an oracle 'screenshot' command (exportImage) for visual verification.
- Keep REAL scale (S100P board 14cm, chassis 40cm) — refraining from the
  visual-favoring scale-up that would snowball every future peripheral.
2026-08-17 16:46:20 +08:00
Codex
15e10c76be docs(S1-C): record full gate (621 passed, 95.37% cov, ruff/mypy clean) 2026-08-17 16:42:03 +08:00
Codex
907cd08d42 feat(sim): model S100P dev board + DIY peripherals in the grasp world
Replace the abstract blue-box robot with a DIY form factor: a green S100P PCB
(SoC + edge connectors + pin header), a 2WD differential base, a USB camera
mounted on the deck, and a 3-DOF servo arm with a two-finger gripper — all
self-made basic geometry, device names and the capability/controller/Oracle
chain unchanged.

Oracle cube pose updated to the new rest pose (0.42, 0.06).
2026-08-17 16:27:58 +08:00
Codex
c2eea57882 docs(S1-C): re-verified snapshot (NUL stripped, bpu no longer false-positive)
Re-ran the fixed S100 engine against the live board: model has no NUL, bpu
probe now fails honestly (completeness=partial), bpu.inference.static absent.
2026-08-17 16:27:25 +08:00
Codex
6acb378060 fix(S1-C): resolve S1C-FIND-001/002 real-device probe defects
- FIND-001: FileProbe strips the device-tree NUL terminator from
  /proc/device-tree/model (was trailing \x00 in the model string).
- FIND-002: bpu.runtime probe no longer pipes ls through 'head -1' (which masked
  ls's non-zero rc behind head's 0), and bpu.inference.static is only advertised
  when a libdnn path is actually observed. Absent runtime -> unknown, not a
  false-positive available.

Tests: model with NUL -> 'RDK S100P'; bpu rc=2 -> None; bpu rc=0-empty -> None.
5 passed; ruff/mypy clean.
2026-08-17 16:22:23 +08:00
Codex
7c1bd341b5 feat(sim): add Webots realtime GUI mode (--mode realtime)
- WebotsSession gains realtime=True: launches --mode=realtime (3D window at
  wall-clock speed) instead of --batch --no-rendering, and leaves the window
  open for the human after the run instead of terminating it.
- rdk-agent-sim serve --profile webots --mode realtime opens the GUI and runs
  the grasp; --mode batch (default) stays headless for CI.
- Close the accepted controller sockets on __exit__.

Gates: Python 621 passed; ruff/mypy/format clean; realtime run opens the window,
completes inside_gripper=true, and leaves the window open.
2026-08-17 16:17:03 +08:00
Codex
48223eaf3a feat(S1-C): formal full-chain proof — SshDeviceConnector → on-board Helper
With user-authorized SSH key auth in place, drive_formal_chain.py runs the
production SshDeviceConnector (DEBT-001 --device-id, BatchMode key auth,
StrictHostKeyChecking, fixed helper path) -> on-board s100-readonly Helper ->
real inventory. Snapshot_id matches the direct-SSH engine path
(sha256:77f789f8...), confirming identical real facts across both transports.
2026-08-17 16:12:31 +08:00
Codex
13ec93bb22 docs(S1-C): real S100P read-only inventory evidence + collector
- collect_s100_inventory.py: SSH-backed CommandRunner driving the product S100
  Inventory Engine against the live board (read-only). Produced the real
  snapshot (docs/testing/evidence/s100p-snapshot.json): D-Robotics RDK S100P
  V1P0, RDK OS 4.0.5-Beta, aarch64, 21.3GB, Realtek USB camera present, TROS
  humble, 8/8 probes complete.
- Records S1C-FIND-001 (model NUL byte) and S1C-FIND-002 (bpu false-positive).
- Host fingerprint SHA256:IDmdMLvf3cET0+X+qbsJpAIxo4XtibiULpnohvFp7/I.
2026-08-17 15:41:26 +08:00
Codex
e75deea7ce fix(S1-C): vendor deps + PYTHONPATH wrapper in helper install
Real-device validation (S100P) exposed two defects in the DEBT-002 install:
- --no-deps skipped pydantic (rdk-agent-core's dep); pydantic-core is a compiled
  extension and the board has no internet, so build now vendors the aarch64
  cp310 closure into dist-helper/deps via 'uv pip install --target --python-platform'.
- 'pip install --target' entry points run without the target dir on sys.path;
  install now writes a PYTHONPATH wrapper instead of a bare symlink.

syntax-checked and rebuild-verified (dist-helper = 3 wheels + deps/).
2026-08-17 15:41:26 +08:00
Codex
9644664481 feat(sim): Webots red-cube grasp vertical slice (2B-2)
- Migrate smoke assets into packages/rdk_agent_sim/assets: self-made red_cube_
  grasp.wbt (2WD + USB camera + 3-DOF arm + two-finger gripper + static red cube)
  and two stdlib-only controllers.
- Separate the Robot data plane (rdk_robot_bridge: camera/base/arm/gripper/
  encoder over RDK_ROBOT_SOCKET) from the Oracle plane (rdk_oracle_supervisor:
  ground-truth truth/reset over RDK_SUPERVISOR_SOCKET) — different sockets,
  ground truth never reaches the Agent.
- WebotsWorld + WebotsSession: launch Webots.app --mode=fast --batch, connect
  both controllers, and expose the same SimWorld surface as DeterministicWorld
  so the capability endpoint / action script / recorder / oracle are unchanged.
- WebotsBackend (ExecutionBackend) reuses CapabilityEndpoint + action_script +
  recorder + oracle; profile=webots is now served (no longer blocked).
- Extract a SimWorld Protocol (robot/cube/inside_gripper + capability methods)
  so capability_endpoint / recorder / oracle are fidelity-neutral.
- Episode reset is a fresh Webots process per run (simpler and more isolated
  than worldReload + cross-reload markers).

Gates: Python 621 passed; ruff/mypy/format clean; headless batch end-to-end
(inside_gripper=true, gripper 0.97, arm joints set, target_visible=true).
2026-08-17 15:37:46 +08:00
Codex
2a5243a776 feat(S1-C): close S1A-DEBT-001/002 (s100-readonly device_id + helper install)
- S1A-DEBT-001: SshDeviceConnector passes the registered device_id to the
  s100-readonly Helper as --device-id (remote_command); application.connector_for
  wires device_id=device_id. The Helper no longer exits RDK-INV-001 on a missing
  --device-id.
- S1A-DEBT-002: scripts/install-device-helper.sh (build|install|update) bundles
  rdk-agent-device + rdk-s100 + rdk-agent-core (pure-py py3-none-any wheels) into
  ~/.rdk/bin/rdk-agent-device. .gitignore dist-helper/.
- Tests: test_ssh_argv_passes_device_id_to_readonly_helper; full pytest green
  (620) + install smoke (wheel build -> install -> rdk_s100 import -> s100-readonly
  serve --device-id boots).
2026-08-17 14:10:21 +08:00
Codex
02f21a8418 fix(S1-B.1): harden renderer navigation and MCP lifecycle
- P1: restrict renderer navigation to the exact packaged index.html URL
  (isAllowedRendererNavigation) instead of a bare file: scheme, so an arbitrary
  local HTML page can no longer load into the window and receive the preload
  task/device bridge.
- P1: await window.loadFile() and assert the preload bridge (window.rdk) is
  exposed before the real-launch smoke fires, so DESKTOP_SMOKE_OK now proves the
  renderer/preload mounted.
- P2: add a spawned-stdio MCP lifecycle test (handshake → tool call reaches an
  open TaskService → stdin close → clean exit) regressing the runMcpServer bug;
  runMcpServer handles an already-ended stdin and drops unused signal listeners.
- P2: add tsconfig.typecheck.json (noEmit, covers preload.ts + renderer tsx that
  esbuild does not type-check) and wire it into .

Gates: desktop typecheck+build+test 7; surface build+test 62/3; real e2e +
mcpLifecycle 2 passed; Electron RDK_DESKTOP_SMOKE=1 → DESKTOP_SMOKE_OK, no
residual Host/Device.
2026-08-17 12:28:08 +08:00
Codex
bba9f26990 test(S1-B): close acceptance — Electron 43, explicit workspace, MCP lifecycle
- Electron 34 → 43.4.0 (Node 24.18.1) resolves undici crash on Node 20;
  split bootstrap (main.ts version guard) from mainImpl.ts (dynamic import).
- workspace-root explicit: desktop uses userData/workspaces (never home);
  CLI/TUI reject a missing --workspace-root instead of falling back to cwd.
- Fix MCP runMcpServer: connect() is non-blocking (stdio start() only registers
  stdin listeners); block until stdin end/close or signal so the TaskService is
  not closed before any tool call.
- esbuild-bundle preload → preload.cjs (sandbox CJS) and the renderer tsx.
- Add RDK_DESKTOP_SMOKE=1 real-launch smoke (real Host + Fake Device + Pi
  ScriptedModel session → DESKTOP_SMOKE_OK).
- Add cross-surface e2e (real Host integration): CLI starts, MCP observes,
  owner conflict, cancel, take-over resume, shared device snapshot.
- Evidence: docs/testing/evidence/S1-B.md.

Gates: Python 619 passed; surface 62/3; pi 18/4; desktop 5; e2e 1 passed;
ruff/format/mypy clean.
2026-08-17 11:33:56 +08:00
Codex
9ace8a9208 feat(S1-B): task service with barrel entry, desktop Electron 43 shell
- Add public barrel entry (index.ts) for @rdk/rdk-agent-surface with explicit
  exports: DeviceService, TaskService, TaskServiceOptions, buildTaskService.
  Add main/types/exports to package.json. Add barrel contract test.
- Upgrade desktop Electron from 34 to 43.4.0 (Node 24.17.0, resolves undici
  crash on Electron 34's Node 20.18.1). Add version guard at startup.
- Fix __dirname ESM compatibility in main.ts.
- Add task.list RPC to host frames/server/stores + acceptance test fix.
- Surface: TaskService, TaskServiceFactory, OwnerLock, Workspace, TUI, CLI,
  MCP, healthCard, and integration tests.
- Desktop: Electron main/preload/renderer, security, IPC handlers, build
  (HTML copy to dist), test suite (5/5).
2026-08-15 14:59:28 +08:00
Codex
2f5659f5f7 feat(sim): close 2b-0 and harden deterministic runtime
- Close 2B-0 Webots preview gate: fix 3D black-screen (z-fighting), preview/
  batch lifecycle separation, explicit Python executable, reset recovery.
- Add rdk_agent_sim package: deterministic 2WD/arm/gripper world, run-bound
  capability endpoint, scenario schema, sim-stdio transport, preflight.
- Harden deterministic runtime: cancel/timeout/deadline/explicit-stop/disconnect
  safe-stop, fault schedule (drop_frames/wheel_slip), enforced ticket
  environment_kind, dual production/Oracle verifier channel.
- Fix two state-machine bugs exposed by branch coverage: cancel path now walks
  RUNNING→CANCELLING→CANCELLED, crash path RUNNING→TIMED_OUT→FAILED.
- Raise rdk_agent_sim branch coverage to 93% (>=90% gate).
- ADR-016 Accepted; Webots R2025a frozen (external dependency, SHA-256 pinned).
2026-08-14 17:30:38 +08:00
217 changed files with 29310 additions and 970 deletions

View File

@ -24,6 +24,7 @@ jobs:
packages/rdk_agent_device/src
packages/rdk_agent_host/src
packages/rdk_agent_cli/src
packages/rdk_agent_sim/src
plugins/rdk_s100/src
- name: Tests with core branch coverage gate (>=90%)
run: >-

7
.gitignore vendored
View File

@ -4,6 +4,7 @@ __pycache__/
*.egg-info/
.venv/
dist/
dist-helper/
build/
.mypy_cache/
.ruff_cache/
@ -24,3 +25,9 @@ dist-test/
# OS
.DS_Store
*.wbproj
dist-macos/
# Local tooling state (per-machine Claude Code config, launch configs)
.claude/settings.local.json
.claude/launch.json

View File

@ -1,7 +1,7 @@
# 文档地图与规范管理
状态:Baseline v0.7
最后更新:2026-08-13
最后更新:2026-08-14
目标读者:产品负责人、架构师、Claude Code 实现者、测试与设备实验室维护者
## 1. 文档清单
@ -23,6 +23,8 @@
| `docs/11-rdk-studio-replacement-plan.md` | RDK Studio 能力承接矩阵、差异化和替代判定 | 是 |
| `docs/12-multi-surface-interface-spec.md` | CLI/TUI/GUI/MCP 命令、工具、任务接管与 macOS 分发 | 是 |
| `docs/13-rdk-project-positioning.md` | 与其他类型 RDK 项目的关系、同目标方案差异和整合边界 | 是 |
| `docs/S1-PLAN.md` | S1-A 实施、验收决定与带截止点的遗留项 | 是 |
| `docs/S1-B-PLAN.md` | S1-B 共享 TaskService 与 CLI/TUI/GUI/MCP 最小纵切片 | 是 |
| `docs/testing/TEST_STRATEGY.md` | 分层测试、环境矩阵、证据和缺陷门槛 | 是 |
| `docs/testing/ACCEPTANCE_TESTS.md` | 可执行的验收场景与预期结果 | 是 |
| `docs/testing/HIL_LAB_SPEC.md` | 硬件在环工装、接线与实验室安全 | 是 |
@ -53,6 +55,8 @@
- `v0.7` 变更:接受 ADR-013,明确产品不是 RDK Studio 的附加助手,而是以 Pi Agent 为核心、面向学生和个人开发者的下一代 RDK 桌面开发环境;新增工作台基线、替代矩阵、人与 Agent 分权及 S0–S6 路线。
- `v0.7` 桌面决策:接受 ADR-014,S1 使用 Electron + TypeScript/React,避免并行维护多套 UI 技术路线,并冻结最小 preload IPC 与人机分权边界。
- `v0.7` 多入口决策:接受 ADR-015,CLI、TUI、GUI 和 MCP stdio 成为共享同一 Pi Runtime 的一等入口;macOS arm64 为首发平台,MCP 用于其他 Agent 调用。
- `v0.7` 仿真重建决策:接受 ADR-019,仿真系统重建为“虚拟 RDK”两层(板级 L2 可运行板 + 设备形态电路/几何仿真),不上刚体物理引擎,几何内核 OpenCascade/build123d,运行出身仿真/真机分列,验收自 AT-034 起。
- `v0.7` 仿真 SIM-R2:L2 可运行板 Python 侧(审核模板真跑 + 合成相机帧 + BPU 结构化结果 + 完整接口面三档枚举),验收 AT-038..041;GUI/TUI 设计旅程为并行轨道。
- `v0.6` 变更:接受 ADR-012,将产品收敛为面向高校学生和个人开发者的 local-first RDK 机器人 DIY 编程伙伴;Student MVP 聚焦首次连接、项目推荐、可见作品、解释学习和本地 Project Pack,托管、多租户、relay、复杂技能供应链和强隔离 profile 后移。
- `v0.5` 变更:接受 ADR-011,将硬件/软件环境盘点提升为 Agent 一等能力;注册信息不再充当设备事实,首次连接、快照过期和相关硬件变化时由受控 Inventory Engine 自动刷新。
- `v0.4` 变更:接受 ADR-010,将首台真机从假定的 X5 改为实际可用的 S100P 裸板直连环境;USB 摄像头作为到货后的增量 HIL,舵机不作为本地门禁。

View File

@ -186,10 +186,13 @@ Alpha Agent transport 使用系统 OpenSSH:
Device Helper 安装到普通用户目录,不要求 root daemon、专用系统用户或新监听端口。
Helper 有两个 S100 profile:`s100-readonly`(只读盘点,拒绝全部 run 方法)与 `s100-exec`(S2 起;只读盘点 + 经 UserProcessBackend 的有界执行)。`s100-exec` 的 HMAC 票据密钥从仅属主可读的密钥文件读取(默认 `~/.rdk/ticket_key`,0600),缺失或权限过宽即拒绝启动,绝不使用内置 fake key;密钥不出现在 argv。Profile 由 Host 侧部署配置选择,模型不可见。
### 4.11 UserProcessBackend
Pi Agent 在 RDK 普通非 root 用户下运行程序:
- 源码由 Host 经 `run.stage` 同步到 Run 根目录下的 `source/` 子树(`run_prepare → run.stage → run.start`);设备只接受与票据 source digest 完全一致的字节集;
- 源码和输出只能位于产品专属 Run 根目录;
- 启动前校验 source digest 和入口相对路径;
- 使用固定 cwd、最小环境和固定 umask;
@ -258,6 +261,19 @@ draft → verified-local → shareable
社区账号、评分、集中审核、签名和撤销服务不进入当前路线。
### 4.16 虚拟 RDK 仿真组件(rdk_agent_sim)
仿真是一等公民,由两层构成(ADR-019):虚拟开发板(板级 L1/L2,事实由真机快照驱动)与虚拟设备(设备形态的电路 + 几何 + 运动学),经与真机同构的 stdio DeviceServer 协议被 Host 驱动,不新建第二套 Agent loop。
- **DeviceSpec** 设备设计书是唯一输入:参数化零件树 + 装配、电气网表 + 功率预算、控制映射;每个参数带 provenance(`user|agent|template|datasheet|measured`),占位时不宣称已标定;
- **电路层**为自研集总参数求解器(MNA + 定步长 ODE):电池电动势+内阻、线阻、H 桥 PWM、直流电机 R-L+反电动势+转矩常数;输出节点电压/支路电流波形与堵转/欠压/过流判据,确定性、可 seed;
- **几何层**经 OpenCascade(build123d)生成 B-Rep 零件,做干涉/水密/流形/床身适配/最小壁厚 printability 校验,逐零件导出二进制 STL + BOM;工件内容寻址,导出路径限定项目/运行产物根;
- **运动学层**为纯数学判定:行程/可达、质心投影支撑多边形静态稳定、准静态倾覆裕度;不上刚体动力学;
- **出身标注**:run 盖 `origin=simulation`,报告按 仿真/真机/未知 分列;仿真通过永不计为真机验证;仿真建模执行器但**不授权**真实执行器(CFR-026、CSEC-002/008);
- 边界:不上刚体物理引擎、不做 SPICE 器件级、不做渲染依赖、不做 L3 板级电气(ADR-019 §10)。
**L2 可运行板(SIM-R2,Python 侧)**:经审核模板(core `templates.py` 注册表)可在虚拟板上**真跑**——sim 设备以 `SimProgramBackend`(镜像 UserProcessBackend 边界:固定解释器、cwd=源根、umask/进程组/超时/取消)在宿主受限子进程执行模板,注入 `rdk_virtual_board` shim 提供板级 API:系统事实(快照 resources + 冻结小数)、相机合成帧(手写 PNG、字节稳定)、BPU 结构化结果(sha256 派生、未审核模型 fail-closed)。两道安全闸:staged 文件集合必须与审核模板 digest 精确相等(模型自构程序不执行,CFR-027);sim 程序运行**忽略 manifest env**(env 由 backend 全控,无注入面)。host 暴露 `sim.evaluate/sim.export_stl/sim.run` RPC 与 `rdkctl sim run`;R2 能力(bpu)走 allowlist + 人工审批两步,agent 面不可自批。GUI/TUI 设计旅程为并行轨道。
## 5. 用户流程
### 5.1 首次连接

View File

@ -70,11 +70,12 @@ software:
python: "3.10.x"
tros_distro: null
bpu_runtime: "..."
lerobot_version: null # probe_set ≥1.2.0:观测到的 LeRobot 版本,未安装为 null
capabilities: []
probe_errors: []
inventory:
profile: "bootstrap"
probe_set_version: "1.0.0"
probe_set_version: "1.2.0"
completeness: "complete" # complete|partial
evidence_refs: []
observations:
@ -86,6 +87,12 @@ observations:
status: "unknown"
probe_id: "drobotics.bpu.runtime@1"
evidence_ref: null
peripherals: # probe_set ≥1.2.0;配件只读枚举事实
usb_devices: # lsusb 原始事实(VID:PID+描述),不做设备类推断
- {bus: "003", device: "002", vendor_id: "1a86", product_id: "55d3",
description: "QinHeng Electronics USB Single Serial"}
serial_nodes: ["/dev/ttyACM0"] # ttyACM/ttyUSB/ttyAMA
can_interfaces: [] # /sys/class/net/can*
```
允许尚未证明的字段为 `null`,其 `observations` 状态必须解释原因。任何非空的 capability/兼容性关键字段都必须有对应 observation;用户 hint 不能产生 `observed`。快照哈希基于 canonical JSON,排除采集时间等非身份字段的规则必须固定并有 golden test。
@ -97,10 +104,10 @@ inventory_request:
schema_version: "1.0"
device_id: "..."
profile: "targeted" # bootstrap|quick|full|targeted
targets: ["usb", "video"]
targets: ["usb", "video", "serial", "can", "software"]
reason: "pre_plan" # first_connect|pre_plan|user_request|change_detected
probe_result:
probe_id: "linux.usb.enumerate@1"
probe_id: "linux.usb.enumerate@2"
status: "succeeded" # succeeded|failed|timed_out|unsupported
evidence_ref: "evidence://..."
observed_at: "2026-08-12T08:00:00Z"
@ -281,6 +288,45 @@ Task state 为 `created|planning|coding|executing|verifying|waiting_user|complet
Pi session fork/clone 产生新的 task 或显式的 read-only analysis branch;不得复制 approval、device write lease、request ID 或未消费 start 权限。Task/session 恢复在任何新 tool call 前执行 reconciliation。
### 2.10 DeviceSpec(设备设计书)
DeviceSpec 是学生可见可改、Agent 可写的版本化领域聚合(ADR-019 §4),Pydantic 源在 `rdk_agent_core.device_spec`,生成 `schemas/device-spec.schema.json`。它是项目内用户数据,digest 参与 source-bound Plan/Run 语义。
```yaml
schema_version: "1.0"
spec_id: "sha256:..."
name: "2wd-rover"
mechanical:
parts:
- id: chassis
template: chassis_plate_2wd
params: {length_mm: 120, width_mm: 80, thickness_mm: 3}
material: petg
provenance: template
assembly:
- part: motor_mount_l
mount_on: chassis
offset_mm: [-54, 0, 0]
mass_estimate_g: 450
electrical:
nets:
- id: vbat_l
components:
- {id: bat, type: battery, emf_v: 7.4, r_int_ohm: 0.05, capacity_mah: 2000, provenance: datasheet}
- {id: wire_l, type: wire, r_ohm: 0.08, provenance: template}
- {id: drv_l, type: hbridge, r_on_ohm: 0.01, provenance: datasheet}
- {id: mot_l, type: dc_motor, r_a_ohm: 0.6, l_a_h: 0.0002, ke: 0.046, kt: 0.046, provenance: datasheet}
power_budget_w: 25
control:
channels:
- {actuator: mot_l, kind: pwm, pin: "P1"}
```
- 每个参数携带 provenance:`user | agent | template | datasheet | measured`;占位参数不得宣称已标定或 sim-to-real(沿用旧系统 calibration_status 纪律);
- `compute_spec_id()` 为内容寻址:对排除 `spec_id` 本身的规范化 dump 求 digest(与 DeviceSnapshot 同模式);
- mechanical 零件引用仓库内置、经审核的参数化模板(`rdk_agent_sim/data/part_templates/`),模板同时携带几何与电气参数;
- 人可在编辑器改、Agent 经受控 workspace API 改;不做社区零件注册表。
## 3. Run 状态机
```mermaid
@ -349,6 +395,7 @@ Host 首先发送 `hello`:支持的 protocol/schema、host build、随机 nonc
- `device.inventory`
- `capability.list`
- `run.prepare`
- `run.stage`(protocol 1.1 起)
- `run.start`
- `run.status`
- `run.events`
@ -367,6 +414,8 @@ Agent 程序调用的 Capability Broker 使用独立的本地、按 run 生命
`run.prepare` 携带由 Host Policy Engine 产生、完整性保护的短时票据,绑定:run ID、plan digest、device ID/snapshot、源码摘要、允许能力、资源上限、批准 ID 和过期时间。MVP 可用安装时配置的 HMAC key;Preview 应支持 Ed25519 非对称签名。票据无效或字段不匹配必须拒绝。
`run.stage`(S2,protocol 1.1)在 prepare 与 start 之间把 plan 绑定的工作区源码同步到设备 Run 根目录下的 `source/` 子树:每文件携带 relpath + SHA-256 + base64 内容,设备逐文件校验摘要、拒绝路径逃逸/符号链接/超界,且整组文件的聚合摘要必须等于票据绑定的源码摘要,否则拒绝。只有 QUEUED 状态可 staging;start 之后的 Run 是不可变 attempt。同一票据绑定摘要的重放是幂等重写。单文件 ≤ 256 KiB、单次 ≤ 768 KiB、≤ 256 文件(控制 frame ≤ 1 MiB 之内)。Backend 在 start 的 STAGING 阶段按 stage.json 重新校验全部暂存文件摘要,stage 与 start 之间的篡改 fail-closed。
### 4.5 事件种类
- `run.state_changed`
@ -402,7 +451,7 @@ Artifact descriptor:name、relative export path、media type、bytes、SHA-256
## 7. 幂等、排序与重连
- Host 对同一 actor + request ID + operation 保存响应;payload 不同但 request ID 相同返回冲突。
- Device `run.prepare/start/cancel` 以 run ID 幂等;重复 start 返回现有状态。
- Device `run.prepare/stage/start/cancel` 以 run ID 幂等;重复 start 返回现有状态,重复 stage(同票据绑定摘要)重写相同字节。
- 事件对一个 run 严格递增,但不同 run 无全局顺序。
- Host 发现 seq 缺口后请求 `run.events(after_seq)`;spool 已丢失则记录永久缺口,outcome 最多为 inconclusive,除非所需证据完整且策略允许。
- 网络错误只有在方法标为 retryable 且幂等键存在时自动重试。

View File

@ -23,6 +23,7 @@
| S4 | 设备中心补齐 | SSH、Type-C、串口、网络、远程文件/终端/桌面 | Preview |
| S5 | 系统准备与生态 | 产品内烧录、板型/镜像、项目/NodeHub 导入 | Preview |
| S6 | 替代发布 | Windows/macOS/Linux、目标板型、迁移与替代任务集通过 | Replacement Release |
| SIM 轨道(ADR-019) | 虚拟 RDK 仿真重建 | R0 移出+规范完成;R1 2WD 垂直切片(AT-034..037 独立测试全过);**R2 Python 侧 L2 可运行板实施中**(AT-038..041,GUI/TUI 并行轨道);R3 printability 深化 | 并行轨道,不阻塞 S0–S6;仿真永不计真机验证 |
任何阶段可以内部演示,但只有 S6 全部门禁通过后才能宣称“已经替代 RDK Studio”。

View File

@ -14,7 +14,9 @@
Claude Code 不得同时充当高风险操作的批准人,也不得自行降低验收断言以宣布完成。
## 2. 当前任务:执行 S0
## 2. 当前任务:执行 S2(Agent 开发闭环)
> 进度快照(2026-08-17):S1 三切片(A/B/C)全部收口,S1-C 真机只读验收通过(证据 `docs/testing/evidence/S1-C.md`)。S2 首切片(Starter 1 系统健康卡真机闭环)已完成:协议新增 `run.stage`(protocol 1.1,源码摘要绑定同步),新增 `s100-exec` 执行型 Helper profile(票据密钥文件、非 root UserProcessBackend),真机全链路 passed(证据 `docs/testing/evidence/S2.md`)。S2 分支 `codex/s2-agent-loop`(worktree `/tmp/rdk-s2`)。下一步:S2 剩余交付物 —— AgentTask checkpoint/预算恢复的产品化、run watch、断线对账入口、四入口对同一 run 的观察。
### 仓库与改动方式
@ -29,24 +31,22 @@ Claude Code 不得同时充当高风险操作的批准人,也不得自行降
```text
当前产品是面向高校学生和个人机器人 DIY 开发者、目标替代 RDK Studio 的 Agent 原生开发环境,macOS 优先并同时提供 CLI/TUI/GUI/MCP。先阅读 CLAUDE.md、ADR-012–015、docs/01、docs/11、docs/12 和 docs/06。
继续在当前仓库和已有 M0 代码上增量修改;不要创建新仓库、平行项目或重写底座。本轮只执行 S0,不连接真实 RDK,不新增企业平台能力:
1. 修复生产 createRdkSession 未 reload、实际工具为空的问题,生产和测试只保留同一装配路径;
2. 将 run.start 幂等改成原子 claim/complete,新增真实并发相同 request id 测试;
3. 将 Node 约束统一为 >=22.19.0,并通过正常依赖解析解决 pi-ai 双实例,删除修改 node_modules 的 postinstall;
4. 将秘密阻断收敛为高置信度真实秘密和凭据文件,允许 os.environ/API_KEY 等正常代码引用;
5. 清理重复 HostClient、测试专用装配和过时 fixture/证据;
6. 跑完整 Python/TS/联调门禁并更新证据。
继续在当前仓库和已有 S1 代码上增量修改;不要创建新仓库、平行项目或重写底座。本轮执行 S2 剩余切片(docs/06 §6):
1. AgentTask checkpoint、预算与恢复的产品化(重启/压缩后先对账活动 Run 再允许新 start);
2. run watch:事件流/产物在四入口(CLI/TUI/GUI/MCP)对同一 Run 的一致观察;
3. 断线对账入口与 Agent 并发版本冲突呈现;
4. 每步用 Fake/s100-exec 双侧验证,真机证据沿用 S100P(直连,profile=s100-exec)。
设计约束:保持代码直接、简洁;四入口共享唯一 Session/Task/Application Service,不复制 Agent loop。完整 GUI/TUI/CLI/MCP 属于后续 S1,本轮 S0 不提前实现;人工终端/烧录不能成为 Pi/MCP tool。不要实现 Supervisor、Capability Broker、托管、多租户、relay、多 Agent 或社区技能仓。
设计约束:保持代码直接、简洁;不得复制 Session 工厂、HostClient、Pi loop、Task 状态或设备逻辑。协议已含 run.stage(1.1);设备写路径只有 prepare→stage→start,新增设备能力必须走同一票据/摘要绑定,不得开旁路 RPC。人工终端、烧录和 approval decision 不能成为 Pi/MCP tool。不要实现托管、多租户、relay、多 Agent、社区技能仓或 MCP 网络监听。
Project Pack + Skill Candidate 是已接受的 S3 设计,本轮不要实现。只需保证 S0 修复不破坏现有 Run/Verifier/provenance 数据;不要为未来 S3 建 registry、service、adapter 或占位 Schema。
Project Pack + Skill Candidate 是已接受的 S3 设计,本轮不要实现;不为未来 S3 建 registry、service、adapter 或占位 Schema。
```
### S0 完成后的顺序
### 当前阶段顺序
1. Codex 复验 S0 全部门禁;
2. 通过后,Claude Code 在同一仓库执行 S1,多入口和 macOS/S100P 基础;
3. S1 通过后执行 S2,完成真实 Agent 编程与 Verifier 闭环;
1. S1(A/B/C)已全部收口:四入口任务服务 + Electron 壳 + S100P 真机只读验收;
2. 当前执行 S2:真实 Agent 编程与 Verifier 闭环。首切片(Starter 1 健康卡真机 run)已完成;
3. S2 剩余:AgentTask checkpoint/预算/恢复产品化、run watch、断线对账;
4. 到 S3 才实现 Project Pack + Skill Candidate,不提前穿插。
### S3 的 Pack + Skill 实施说明(现在只保留,不执行)
@ -204,4 +204,4 @@ Claude Code 如果认为规范不可实现或有更好方案,应先提交:
6. 端到端测试:SSH Connector 完整 Helper 命令、host key show→confirm 跨进程。
7. 全部门禁复跑:559 pytest、core branch 95.53%、ruff/format/mypy 绿、schema 无漂移、pi TS hermetic 18/4 + 实连 22/22、surface TS 9/9、两包 audit 0、0 残留进程。
证据:`docs/testing/evidence/S1-A.md`。S1-A 是否通过以评审人复验为准;通过后方可进入 S1-B(Electron/TUI)与 S1-C(S100P 真机盘点)。
证据:`docs/testing/evidence/S1-A.md`。Codex 于 2026-08-14 判定 S1-A **Accepted with conditions**,允许进入 S1-B。`S1A-DEBT-001/002` 必须在 S1-C 真机盘点前关闭,不能用有条件通过替代真机证据。

View File

@ -28,18 +28,20 @@ GUI 承担完整 Studio 替代体验,同时提供共享同一 Runtime 的 CLI
## 3. 替代矩阵
| 用户工作流 | 必须承接的基线 | 本项目目标形态 | 替代版本门槛 |
|---|---|---|---|
| 安装与首次启动 | 桌面安装、登录/配置、板卡选择和引导 | 独立桌面应用;模型配置与设备准备向导;账号不是本地开发前置 | Windows、macOS、Linux 可安装、更新和卸载 |
| 系统准备 | 镜像选择、下载、校验和烧录 | 设备中心内的烧录向导;复用官方 XBurn 引擎;Agent 只解释和检查,最终写入由人确认 | 支持目标板型、失败恢复和可审计结果 |
| 设备接入 | SSH、Type-C、串口、Wi-Fi/网络 | 统一设备中心;保存连接;自动识别板型并可信盘点;通用 SSH Linux 可使用基础远程开发 | 三类连接和常见断线恢复通过真机验收 |
| 项目管理 | 创建、打开、最近项目和工作区 | 项目首页、模板、导入、最近项目、Project Pack | 项目可创建、导入、复制、删除和恢复 |
| 远程开发 | 代码编辑、文件、终端、远程操作 | 编辑器、项目树、本地/远程文件、人工终端、任务/问题面板 | 常见开发无需离开应用 |
| 设备观察 | 状态、日志、串口、远程桌面 | 设备卡、结构化 Inventory、串口控制台、运行日志;远程桌面作为替代版本能力 | 状态有证据,调试链路完整 |
| AI 交互 | 对话、项目上下文、代码和终端协助 | 嵌入 Pi 的非端侧项目 Agent;计划—编码—运行—验证—修复闭环 | 自然语言完成至少三个真机项目 |
| 开发者/Agent 集成 | 桌面内使用为主 | CLI、TUI 与 MCP stdio;同一 Task 可跨入口继续 | macOS Alpha 四入口等价,外部 Agent 无法越权 |
| 模型管理 | 云端/本地模型配置 | Pi provider 中心、系统钥匙串、可选 OpenAI-compatible 本地端点 | 可测试、切换、诊断且密钥不进项目 |
| 内容与复用 | 示例、资源、历史 | Starter Project、Project Pack、课程/NodeHub 导入与本地作品库 | 干净环境可复跑并清洗导出 |
每行必须有一项证据(自动化测试 / HIL 证据 / 可用性),由 `scripts/check_replacement_matrix.py` 机器校验;`pending-<阶段>` 表示未完成,门禁不通过。
| 用户工作流 | 必须承接的基线 | 本项目目标形态 | 替代版本门槛 | 证据 |
|---|---|---|---|---|
| 安装与首次启动 | 桌面安装、登录/配置、板卡选择和引导 | 独立桌面应用;模型配置与设备准备向导;账号不是本地开发前置 | Windows、macOS、Linux 可安装、更新和卸载 | pending-S6 分发构建 |
| 系统准备 | 镜像选择、下载、校验和烧录 | 设备中心内的烧录向导;复用官方 XBurn 引擎;Agent 只解释和检查,最终写入由人确认 | 支持目标板型、失败恢复和可审计结果 | pending-S5 烧录向导 |
| 设备接入 | SSH、Type-C、串口、Wi-Fi/网络 | 统一设备中心;保存连接;自动识别板型并可信盘点;通用 SSH Linux 可使用基础远程开发 | 三类连接和常见断线恢复通过真机验收 | SSH: S1-C/S2 真机 + `tests/acceptance/test_fake_variants.py::TestAT023TaskResume`;串口/Type-C: pending-S4 |
| 项目管理 | 创建、打开、最近项目和工作区 | 项目首页、模板、导入、最近项目、Project Pack | 项目可创建、导入、复制、删除和恢复 | Project Pack save/list/run: `tests/unit/test_host_application.py::TestPacks` + S3 真机;导入: pending-S5 |
| 远程开发 | 代码编辑、文件、终端、远程操作 | 编辑器、项目树、本地/远程文件、人工终端、任务/问题面板 | 常见开发无需离开应用 | workspace read/write/diff/patch: `test_host_workspace.py`;编辑器/人工终端 GUI: pending-S4 |
| 设备观察 | 状态、日志、串口、远程桌面 | 设备卡、结构化 Inventory、串口控制台、运行日志;远程桌面作为替代版本能力 | 状态有证据,调试链路完整 | Inventory: S1-C 真机 + `test_plugin_s100.py`;run watch: S2 CLI/TUI/MCP;串口控制台: pending-S4 |
| AI 交互 | 对话、项目上下文、代码和终端协助 | 嵌入 Pi 的非端侧项目 Agent;计划—编码—运行—验证—修复闭环 | 自然语言完成至少三个真机项目 | 真模型真机 4 能力: `docs/testing/evidence/S2.md` 切片 3-4;脚本化: `sliceS2.test.ts` |
| 开发者/Agent 集成 | 桌面内使用为主 | CLI、TUI 与 MCP stdio;同一 Task 可跨入口继续 | macOS Alpha 四入口等价,外部 Agent 无法越权 | CLI/TUI/MCP: S1-B `e2e.test.ts`;四入口真机一致: pending-S2 收尾;无越权: `test_fake_variants.py::TestAT021ToolSurface` |
| 模型管理 | 云端/本地模型配置 | Pi provider 中心、系统钥匙串、可选 OpenAI-compatible 本地端点 | 可测试、切换、诊断且密钥不进项目 | 真模型配置: `anthropicModel.test.ts` + ~/.rdk/.env;GUI 模型中心/钥匙串: pending-S4 |
| 内容与复用 | 示例、资源、历史 | Starter Project、Project Pack、课程/NodeHub 导入与本地作品库 | 干净环境可复跑并清洗导出 | Project Pack: `TestPacks`;Starter/课程/NodeHub 导入: pending-S5 |
## 4. 我们真正的差异

171
docs/S1-B-PLAN.md Normal file
View File

@ -0,0 +1,171 @@
# S1-B:共享任务与四入口最小纵切片
状态:Approved for implementation
日期:2026-08-14
前置:S1-A Accepted with conditions(`dd3a204`)
依据:`docs/06` §5、`docs/10`、`docs/12`、ADR-014、ADR-015
## 1. 目标
在 macOS arm64 上交付一个可运行的最小产品纵切片:用户通过 CLI、TUI、GUI 或 MCP 启动/观察同一种“系统健康卡”任务,四个入口共享同一个 TaskService、生产 Session 工厂、Task 状态、事件、取消和证据语义。
S1-B 完成不等于 S1 完成。S1-C 仍负责 S100P 真机只读连接与设备卡验收。
## 2. 本轮范围
1. 唯一共享 `TaskService`;
2. 每个活动 Task 一个独立、可恢复的 `SessionHandle`;
3. `workspace-root` 真实边界;
4. 本机 per-task 单 writer owner lock;
5. 产品 CLI 的 `run` 与 `task` 命令;
6. MCP 的 task/artifact 工具;
7. 最小 TUI;
8. Electron + React 最小壳和工作台/设备/任务纵切片;
9. scripted model + Fake Device 的四入口契约和联调测试。
## 3. 明确不做
- 不连接真实 S100P,不执行设备写入;
- 不实现 Webots/仿真产品功能;
- 不实现 Monaco 编辑器、xterm 人工终端、串口、烧录、网络配置或远程桌面;
- 不实现 Project Pack/Skill Candidate;
- 不实现数据库、daemon、HTTP MCP、relay、多用户、多 Agent 或分布式租约;
- 不创建第二套 Agent loop、prompt、tool allowlist、Task 状态或 Host client。
五个 GUI 一级入口必须可导航,但“项目/作品/设置”中未进入本轮的能力只能显示诚实的阶段说明,不放置看似可用的假按钮。
## 4. 最小架构
```text
CLI ─┐
TUI ─┼─→ TaskService ─→ createRdkSession ─→ RdkHostClient ─→ Host
GUI ─┤ │
MCP ─┘ ├─ Task store(复用既有 AgentTask)
└─ task owner lock(本机文件)
```
- `TaskService` 放在 TypeScript 产品层,供四个 adapter 直接复用;renderer 不持有它,只通过 preload 业务 API 调用 main process。
- Task 领域事实继续使用既有 `AgentTask`/Host store,不在 Electron store 或各 adapter 复制一份状态机。
- 全产品仍只有一个 `createRdkSession` 工厂;工厂可创建多个 Task 各自独立的 handle,不得退化为全局共享单 session。
- S1-B 不为“未来扩展”新增 registry、event bus、DI 框架或通用插件系统。进程内订阅可用简单 callback/async iterator,本地持久化继续用原子文件。
## 5. TaskService 最小契约
```text
startTask(goal, workspace, deviceIds, mode, owner) -> task_id + state + cursor
getTask(task_id, after_event_seq?) -> status + events + required_action
steerTask(task_id, message, owner) -> state + cursor
cancelTask(task_id, reason, owner) -> cleanup/final state
resumeTask(task_id, owner, take_over=false) -> state + cursor
readArtifact(task_id, artifact_id) -> sanitized preview/metadata
close() -> dispose sessions and child processes
```
约束:
- `mode` 只有 `guide|auto_low_risk`;
- `steer` 不能修改 workspace root、设备身份、policy、verifier 或批准状态;
- `cancel` 幂等,并同时停止 Agent turn、取消活动 Run、等待清理结果;
- `status` 是只读操作,不需要 owner;
- MCP 不能 `take_over`,也不能完成人工 required action;
- 进程重启后 `resume` 必须先读取 Task/checkpoint、对账活动 Run,再创建恢复 Session;不得直接重放最后一次工具调用。
## 6. Workspace 与 owner lock
### Workspace
- 每个入口启动时确定一个绝对 `workspace-root`;
- Task 参数只能提供该根下的相对项目路径;
- 解析后必须仍是 root 本身或后代,符号链接也不能逃逸;
- GUI 选目录、CLI 参数和 MCP 参数最终调用同一个 resolver;
- 不存在参数时返回明确输入错误,不静默使用仓库根或用户主目录。
### Owner lock
沿用 `docs/12` §7 的 `state/task-locks/<task-id>.json`,只实现本机单写保护:
- 原子创建;记录 instance id、pid、process start、heartbeat;
- 活 owner 存在时,其他入口只能观察;
- 陈旧锁需核对 pid/start time,并先对账 Run;
- `take_over` 只能由 GUI/TUI/显式 CLI 用户动作触发,产生 `task.owner_changed` 事件;
- 锁不是领域对象,不实现通用 lease service 或分布式锁。
## 7. 四入口交付
### CLI
实现 `rdk-agent run` 与 `task list|status|steer|cancel|resume`。默认输出简洁人类进度;`--json` 为单 envelope,`--follow` 为 JSONL。不能继续始终只输出 JSON。
### MCP
工具精确为:
```text
rdk_device_list
rdk_device_inspect
rdk_task_start
rdk_task_status
rdk_task_steer
rdk_task_cancel
rdk_artifact_read
```
命令必须要求 `--workspace-root <absolute-path>`;继续使用 stdio,无监听端口、sampling、approval、terminal、flash 或 credential 工具。
### TUI
复用 Pi 交互能力和 Task events,实现最小对话区、Task 状态、计划/diff/run/evidence 摘要、输入、取消、恢复和 `/open-gui`。不复制设备业务逻辑,不为了布局创建第二套 Task 模型。
### GUI
新增 `packages/rdk-agent-desktop`:Electron main + preload + React renderer。
- 五个一级入口可导航;
- 工作台可输入目标、启动健康卡并显示 Task 状态/证据;
- 设备页复用 DeviceService;
- Task 详情可观察 CLI/MCP 任务并由真人显式接管;
- `contextIsolation=true`、`sandbox=true`、`nodeIntegration=false`;
- preload 只暴露 task/device/window 等命名业务动作,不暴露 `ipcRenderer`、shell、任意路径、凭据或通用文件读写;
- 只加载打包本地资源,不加载远程网页。
## 8. 实施顺序
1. TaskService 契约、workspace resolver、owner lock 与单元测试;
2. CLI 和 MCP task 面,共享契约测试;
3. TUI 最小入口;
4. Electron main/preload/renderer 最小壳;
5. 四入口 scripted 健康卡联调、自然退出与进程残留检查;
6. 更新证据后交 Codex 验收。
## 9. 测试门禁
### 必须新增
- TaskService:start/status/steer/cancel/resume、每 Task 独立 SessionHandle、close 清理;
- workspace:相对路径、`..`、绝对路径、符号链接逃逸;
- owner lock:两个真实进程竞争、陈旧 owner、显式 take-over、只读观察;
- adapter contract:四入口对同一 scripted 任务产生相同 task state/outcome/error/evidence;
- MCP:tools/list 恰 7 个、workspace-root 必填、无禁用工具、stdout 纯净;
- Electron:preload allowlist、renderer 无 Node、sandbox/contextIsolation、远程 URL 阻断;
- 生命周期:CLI/TUI/MCP/GUI 关闭后无 Host/Device/Pi 残留进程。
### 保持通过
- 全部 Python pytest、branch coverage ≥90%、ruff、format、mypy、Schema drift;
- `rdk-agent-pi` 与 `rdk-agent-surface` build/test/audit;
- Node `>=22.19.0`;
- S1-A 幂等、审批恢复、readonly 和 host key 回归测试。
## 10. S1-B 出口
只有同时满足以下条件才可进入 S1-C:
1. 四入口调用同一个 TaskService 和 Session 工厂;
2. 一个 scripted/Fake 健康卡任务可从任一入口启动,并被其他入口观察;
3. steer/cancel/resume 与 owner 冲突行为一致,无双 writer;
4. MCP 恰 7 个高层工具,不能自批或越过 workspace root;
5. Electron 最小壳满足进程隔离与 preload allowlist;
6. 全部门禁通过且所有子进程自然退出;
7. 未把仿真、真实写入、终端、烧录或 Project Pack 混入本阶段。
S1-B 通过后,先关闭 `S1A-DEBT-001/002`,再使用当前网线直连 S100P 执行 S1-C 只读真机验收。

View File

@ -1,7 +1,7 @@
# S1-A:非 GUI 基础切片 — 实施计划
状态:Approved for implementation(第三版,已按 Codex 第三轮评审局部补充 5 点)
日期:2026-08-13
状态:Accepted with conditions(S1-A 有条件通过,转入 S1-B)
日期:2026-08-14
依据:`docs/06` §5、`docs/12-multi-surface-interface-spec.md`、`docs/02` §4、ADR-012/014/015
## 阶段定位(修正评审 P1-1)
@ -155,3 +155,16 @@ GUI/TUI、task 运行面、owner lease、workspace-root 映射、真实设备写
## 遗留 P1 修复纳入出口
两个 P1 在切片 0/1 修复并带故障注入测试;S1 出口(进入 S2、启用真机执行前)以这些测试通过为门禁。
## S1-A 验收决定(2026-08-14)
S1-A **有条件通过**,允许进入 S1-B。自动化门禁、MCP 真实入口、host key、幂等和审批原子消费均已复验通过。以下问题不影响 S1-B 的本地 TaskService、CLI/TUI/GUI/MCP 共享纵切片,但必须按截止点关闭:
| ID | 遗留问题 | 截止点 |
|---|---|---|
| `S1A-DEBT-001` | SSH Connector 未向 `s100-readonly` Helper 传递必需的 `device_id` | S1-C 真机盘点前 |
| `S1A-DEBT-002` | `~/.rdk/bin/rdk-agent-device` 的普通用户安装/更新命令尚未交付 | S1-C 真机盘点前 |
| `S1A-DEBT-003` | 只读 profile 仍实例化不可达的 Fake facts/backend,行为安全但与证据描述不完全一致 | macOS Alpha 分发前 |
| `S1A-DEBT-004` | 项目要求 Node 22,但本机目录未提供自动版本选择提示 | macOS Alpha 开发者安装说明冻结前 |
S1-A 的“通过”不代表 S1 完成。S1 仍须完成 `docs/S1-B-PLAN.md` 与 S1-C 真机只读验收。

View File

@ -1,216 +0,0 @@
# ADR-016:RDK 仿真程序 —— Webots 物理仿真与确定性 Sim Device
状态:Accepted
日期:2026-08-13(2026-08-14 修订完成并冻结 Webots R2025a)
## 背景
产品需要一个能在 Apple Silicon macOS 本机直接运行的 RDK 仿真程序:模拟 RDK/S100P 接入 USB RGB 摄像头、2WD 差速底盘、3DOF 舵机臂、夹爪和可选轮编码器后,在不同环境执行任务、产生反馈、故障、验证结果和轨迹。它必须复用现有 Device/Inventory/Capability/Plan/Run/Event/Artifact/Verifier 契约,把真实 `RDK Device` 换成 `Sim Device`,而不是另建一套 Agent 或旁路工具。
本 ADR 覆盖两层,均落在 `rdk_agent_sim`:
1. **确定性 Sim Device**(`simulation_fidelity=deterministic`):离散状态机模拟 2WD/arm/gripper、故障计划与 seed 化 golden trace,用于 CI 与 Agent 恢复/回归。无物理、无 Webots。
2. **Webots 物理仿真**(`simulation_fidelity=physics`):首个物理引擎用 Webots 原生 macOS 版,承担连续物理、传感器与 3D 环境,完成「红色方块抓取」垂直切片。
## 决策
### 1. 独立进程 + 独立包,不建另一套 Agent
- 新增部署单元 `packages/rdk_agent_sim`(Python,uv 管理),对外暴露 `rdk-sim` 命令与 `python -m rdk_agent_sim`。
- `rdk_agent_sim` 复用 `rdk_agent_core` 的领域模型与 `rdk_agent_device` 的 `DeviceServer`/`RunRegistry`/`StdioDeviceConnector`。它实现一个 **Sim ExecutionBackend**,通过**与真机完全相同的 stdio DeviceServer 协议**被 Host 驱动。Host 侧只新增一个连接选择,不复制 device 逻辑、Host client、Pi loop 或 Agent loop。
- 不新增 `service/registry/factory` 抽象;第二个真实实现出现前不做多引擎抽象。
### 2. environment_kind —— Host 产生的 provenance,非设备固有属性、非授权开关
`environment_kind` 不是 scenario 里用户可设的字段,也不从 transport 简单推导。它是 Host 受信启动/编排路径在**决定以何种模式启动一次运行**时产生的 provenance 分类:
```text
fake 现有 Fake Device(协议/状态机/失败测试替身)
simulation 新的 Sim Device(含 simulation_fidelity: deterministic | physics)
board_in_loop 真实 S100P 执行 + 仿真世界(一次运行的组合环境,非设备固有属性)
hil 真实 S100P + 真实/校准工装
```
规则(MUST):
- **不在 scenario YAML 中暴露 `environment_kind`**。scenario 只描述「要模拟什么」(hardware_profile/compute_profile/world/task/fault_schedule/seed),不描述「由谁以什么模式启动」。
- `ssh-stdio` 连接既可能是 `hil` 也可能是 `board_in_loop`,因此 `environment_kind` 由 Host 的启动路径显式注入,绑定到 **ExecutionPlan、RunTicket、RunRecord、episode/report** 四者(作为 provenance 字段,参与 ticket 签名载荷与报告分组)。
- `run.start` 必须校验 ticket 中声明的 `environment_kind` 与实际启动模式一致,不一致 fail-closed(复用现有 ticket 字段不匹配拒绝语义)。
- `DeviceSnapshot` 继续只表达设备事实与证据;`board_in_loop` 不作为设备固有属性写入 snapshot。快照的 `transport`/连接元数据只描述连接方式。
- `environment_kind` 只用于 provenance、报告和验收分组;**不能作为开启执行器权限的授权开关**。执行器权限仍由 capability 描述符、policy 与 ticket 的 `capabilities`/包络决定。
- 仿真/board_in_loop 产生的 `outcome=passed` 不得计为 `hil` 验收通过,报告层强制分列。
### 3. transport 新增 `sim-stdio`;Fake Device 保持不变
- transport 新增枚举值 `sim-stdio`,**描述连接方式**(本地 stdio 拉起 Sim Device),不把 transport 命名为 `simulation`。`simulation` 是 environment_kind,与 transport 是正交维度。
- **现有 `FakeExecutionBackend` 保持完全不变**,继续作为协议/状态机/失败测试替身,不扩展成 2WD/机械臂机器人仿真器。
- 环境分类最终为:
```text
fake 现有协议、状态机和失败测试替身,保持兼容(rdk_agent_device 现有 FakeExecutionBackend)
simulation 新的 Sim Device(simulation_fidelity: deterministic | physics)
确定性机器人状态机(DeterministicSimBackend)与 Webots backend(WebotsBackend)
都放在 rdk_agent_sim,不进入生产板端 rdk_agent_device
```
### 4. 动作执行面:最小 run-bound simulation capability endpoint(Q1 裁决)
采用**最小 run-bound simulation capability endpoint**,不新增临时的 `sim.action` / `sim.observe` Device RPC。要求:
- 复用 ADR-006 的**版本化 `capability.call` frame**(版本化 frame/error 模型,`in_reply_to` 关联)。
- 每个 endpoint 绑定:run ID、短时 token、允许的方法集、参数包络;token 复用 run-bound 生命周期与票据语义(MVP HMAC,后续可 Ed25519)。
- 只实现首个切片需要的方法,不做通用 broker。
- 全程普通非 root 用户运行,不安装 root 服务。
- **不宣称已形成真实硬件的 Capability Broker 安全隔离**;本 endpoint 是仿真数据面,安全隔离声明仅限「Agent 不能直接访问 Webots/Supervisor」。
三条通道强制隔离:
1. **Host ↔ Sim Device**:现有 stdio DeviceServer(`rdk-agent-device serve` 同构协议)。
2. **run code ↔ simulation capability endpoint**:数据面本地 Unix socket(相机帧/编码器/动作 ack)。
3. **rdk-sim ↔ Webots Robot Controller / Oracle Supervisor**:桥接 socket。
Robot 与 Oracle 使用**不同 socket 与不同 token**。Agent 与学生代码不得获得 Oracle socket/token。
### 5. 动作必须真正 bounded
`base.velocity.bounded` 请求至少包含:
```text
linear_mps
angular_radps
duration_ms 或 deadline
action_id
```
并要求:
- 到期自动写零速度;
- 提供显式 stop;
- 返回 ack、actual state、stop_reason;
- 断连、取消、超时一律进入安全停止(写零速度/关节保持/夹爪保持)。
机械臂 `arm.joint_position.bounded` 与夹爪 `gripper.position.bounded` 同样必须包含:
- 关节/位置限位(参数包络校验,越界拒绝);
- 最大速度;
- timeout;
- cancel;
- 终态与停止原因。
(`duration_ms` 与 `deadline` 二选一或同时给定时以先到者为准;缺省必须有策略默认值,不允许表示「无限」——复用 docs/03 §2.4 资源上限语义。)
### 6. Oracle 类型隔离(Q1 补充裁决)
不靠 evidence label 区分 Oracle,新增**独立 `OracleEvaluationResult` 模型**(或等价物),要求:
- 独立 artifact namespace;
- 独立 fetcher;
- 独立存储与聚合路径;
- **不能**作为 `RunManifest.required verifier`;
- **不能**传入现有 `aggregate_outcome()`;
- **不能**改变生产 `RunOutcome`;
- **不能**向 Agent 暴露。
生产 `RunManifest.verifiers` 仍只用 `VerificationResult`/`aggregate_outcome()`;Oracle 走 `OracleEvaluationResult` 单独聚合。scenario 里的真值条件改名为:
```yaml
oracle_success_conditions:
- object: red_cube
relation: inside_gripper
```
`pose.in_region`、`contact`、`inside_gripper` 等默认属于 Oracle;生产 Verifier 只能使用相机帧、编码器、控制器 ack 和其他真机可得证据。
### 7. capability 列表裁决(Q2)
- 当前 embodiment profile 声明了配件、但缺少实现/资格/证据 → 列为 `unavailable`/`unknown` 并说明原因。
- 当前 profile 根本没有该配件 → **不列出**。
- Webots profile 中有实现、有观察证据、参数包络有效 → 列为 `available`。
- **不能因为 `environment_kind=simulation` 就自动允许能力**;能力仍走 capability 描述符 + 观察证据 + policy + ticket 包络。
首个切片动作能力(仅 Webots profile 有实现与证据时 available):
```text
camera.snapshot.usb R0 read
base.velocity.bounded R2 write
arm.joint_position.bounded R2 write
gripper.position.bounded R2 write
encoder.state R0 read
```
### 8. Webots 缺失的状态:SimulationPreflightResult
当前 `RunState`/`RunOutcome` 没有 blocked,也**不新增 `RunState.BLOCKED`**。Webots 未安装、版本不匹配或 smoke 前置失败时,在创建 Run 之前返回:
```text
SimulationPreflightResult
status: blocked
reason_code: external_dependency
```
由 `rdk-sim` 在 `run.prepare` 之前的 preflight 阶段返回,Host 据此给出可操作的阻塞信息(沿用 AT-013 的 blocked 语义,不算 pass)。
### 9. 包边界
- `WebotsAdapter`、`DeterministicSimBackend`、`WebotsBackend` 全部留在 `rdk_agent_sim`。
- **不把 Webots 依赖或 SimExecutionBackend 放进生产板端 `rdk_agent_device`**。
- 复用现有 `StdioDeviceConnector`。
- 若 `DeviceServer` 需要支持第二个 backend,只提取**最小构造/注入点**(构造参数注入 backend 实例),不建立 registry/factory。
- 删除对仓库内不存在的 `docs/wiki/...` 路径的引用(外部参考仅保留 Cyberbotics 官方文档 URL)。
### 10. Webots Python 表述
Webots 不是「自带 Python」,而是**启动其配置的系统 Python** 来运行 Controller。Controller 首版仍只依赖 stdlib(`socket`/`json`),不 import `rdk_agent_core`;但 smoke 必须记录:
- 实际 Python executable;
- Python 版本;
- controller 环境变量;
- stdout/stderr;
- 退出与清理行为。
### 11. Phase 2A 授权:仅 smoke(Q3/Q4 裁决)
授权 Phase 2A 下载并安装官方 Webots 稳定版候选,**仅做兼容性 smoke**。以 R2025a 为首个候选,但 smoke 通过前不写成最终冻结版本。
要求:
1. 仅从 Cyberbotics 官方 GitHub release 下载。
2. 优先安装到 `~/Applications/Webots.app`,不要求管理员权限。
3. 记录下载 URL、文件大小与 SHA-256。
4. 检查 macOS codesign、TeamIdentifier 与 Gatekeeper/notarization 状态。
5. 验证:原生启动与 3D 渲染;Python Controller;Camera;Motor;PositionSensor;Supervisor reset/读取真值;fast;no-rendering;batch;正常退出与异常清理。
6. 只用自制的最小 Box/Cylinder 测试资产。
7. smoke 失败时停止,报告证据,不自动切换其他引擎。
8. smoke 完成后再决定冻结哪个版本。
### 12. 占位参数(Q5 裁决)
允许占位参数,但必须记录:
```text
calibration_status: placeholder
parameter_source: engineering_placeholder
hardware_profile_version: <versioned>
```
首版使用 Box/Cylinder 等基本几何,**不声称完成真实硬件标定或 sim-to-real 验证**。
## 结果
- 新增 `packages/rdk_agent_sim` 部署单元与 `schemas/scenario.schema.json`(Phase 2B 起由 Pydantic 生成)。
- `rdk_agent_core` 增加 `EnvironmentKind` 枚举、`SimulationPreflightResult`、`OracleEvaluationResult` 模型与 `environment_kind`/`simulation_fidelity` provenance 字段;`ExecutionPlan`/`RunTicket` 增加 `environment_kind` 绑定字段(进入 ticket 签名载荷)。
- `rdk_agent_device` 增加 `TransportType.SIM_STDIO` 与最小 backend 注入点;`rdk_agent_host` 增加 sim 连接选择、preflight 处理与新 verifier 类型。
- 现有 Fake Device 保持不变。
- 不新增 SQLite/DB/Registry/多引擎工厂;资产本地归档,仿真输出物记录资产清单。
## 冻结记录
- Webots 引擎版本已冻结为 **R2025a**(2026-08-14,Phase 2A smoke 结论 PASS WITH CONDITIONS)。
- 安装包:`webots-R2025a.dmg`,SHA-256 `484f6cc84ca794dd33e410b0bfc030132cc5b163a882c350c1d293d06d87584f`(107,119,977 字节,universal x86_64+arm64)。
- 安装路径约定:`~/Applications/Webots.app`(优先)或 `/Applications/Webots.app`;签名 ad-hoc、未 notarized(preflight 需提示 Gatekeeper)。
- 证据:`docs/testing/evidence/webots-smoke-R2025a/SMOKE_REPORT.md`。
## 待确认(进入 Phase 2B 前仍需决定)
- run-bound capability endpoint 的方法集与参数 schema 最终版(首个切片范围);
- 2WD 底盘/3DOF 机械臂真机参数回填计划。

View File

@ -0,0 +1,181 @@
# ADR-019:虚拟 RDK —— 电路级仿真与设备形态设计(重建仿真系统)
状态:Accepted(2026-08-26;SIM-R0/SIM-R1 完成、SIM-R2 Python 侧实施中;GUI/TUI 为并行轨道)
日期:2026-08-26
取代:`ADR-016`(Webots 物理仿真,已随旧仿真系统于 2026-08-26 迁出归档至 `rdk-sim-webots-legacy`)
编号说明:`ADR-016` 已归档,`ADR-017/018` 为 LeKiwi 底盘/配件知识分支占用,故本决策取 `ADR-019`。
## 背景
旧仿真系统(ADR-016:Webots 物理 + 确定性状态机)整体移出后,产品需要一个**从头重建**的仿真系统。驱动重建的不是"换一个物理引擎",而是对仿真定位的根本重判:
1. **这不是数据采集仿真,是产品构建仿真。** 目的不是生成训练数据或验证动力学策略,而是帮学生**设计一台设备、验证它、把它 3D 打印出来、在真实世界造出来**。因此不上复杂物理引擎(它服务的是数据保真,不是构建验证),也避免对硬件的重依赖。
2. **用户不一定拥有开发板。** 高校教师在课堂演示、学生尚未购买硬件时,就要能完整使用本 Agent。因此**仿真不是有板子之后的辅助,而是一等公民**:RDK 开发板本身必须被精准仿真,且粒度足够细。
3. **学生机器配置参差。** 可能在 Windows / macOS / Linux 上,显卡可能缺失。仿真必须 CPU-only、无头可跑、跨平台,不依赖 GPU 或云端。
4. **差异化在"造机"不在"仿真更真"。** 机器人物理仿真(Isaac/MuJoCo/Gazebo/Webots)与芯片固件仿真(Wokwi/Proteus/Renode)都已有成熟产品。本系统的空位是:**和 Agent 一起设计设备形态 → 电路级验证 → 导出 STL 打印 → 装出真机 → 真机复用同一套代码闭环**——这条完整旅程没有现成产品覆盖。
作为 Agent 的一个模块,本系统对大模型**适当使用**:大模型负责设计与解释,仿真负责确定性裁决(遵循 `验证定义完成`、`事实先于建议` 原则)。
## 决策
### 1. 定位:虚拟 RDK = 两层协同仿真
仿真系统由两层构成,共同组成一台"开箱即用的虚拟 RDK":
- **第一层 · 虚拟开发板(板级仿真)**:精准复现 RDK 板的**可观测契约 + 行为**,使学生代码可以在没有真板的情况下运行。详见 §2。
- **第二层 · 虚拟设备(设备形态仿真)**:学生围绕板子搭建的那台机器——底盘、机械臂、电源、接线——的形态、电路与几何。详见 §3。
两层通过同一份**设备设计书(DeviceSpec,§4)**与既有 `DeviceServer` 协议贯通,与真机走同一条代码路径。部署单元仍为独立包(沿用 `packages/rdk_agent_sim` 名称、内容从零重写),通过**与真机同构的 stdio DeviceServer 协议**被 Host 驱动;不新建第二套 Agent loop、不复制 Pi tools。
**明确:这里的"精准"是契约级 + 行为级保真,不是周期级芯片仿真。** 不做 QEMU/Renode 式的 CPU 指令级模拟(重、吃硬件、且非本场景所需);保真靠"真实快照驱动 + 行为可信"达成(§2.3)。
### 2. 第一层:虚拟开发板(L2 可运行板)
#### 2.1 保真目标分级(采纳"可运行板"档)
板级仿真做到 **L2 可运行板**:
- **L1 契约保真**(基线):盘点/能力/状态与真板结构同构,Agent 与 GUI 全流程可演示;
- **L2 可运行板**(本决策):在 L1 之上,**学生代码真跑**,板级 API 由仿真供给——相机返回合成帧、BPU 返回结构化推理结果、串口/IO 行为可信。教师可现场写代码并运行给学生看。这是"学生没板子也能学"的必要条件。
- **L3 电气级板仿真**(不在本版):板载外设上电时序、总线电气细节。待 L1/L2 站稳后再议。
#### 2.2 三档接口保真度模型
对每个板级接口,三选一并**强制标注**:
| 档位 | 含义 | 纪律 |
|---|---|---|
| 真仿真 | 行为被忠实建模(相机给真合成帧、BPU 给结构结果) | 有模型依据与证据 |
| 标注 mock | 仿真不了的给一个能跑通的 mock | 必须内外标注"假接口",其结果**不得计为真实验证** |
| 不可用 | 本就不该有的能力 | 不提供、不伪造 |
**§2.2 注(2026-08-27,SIM-R2)**:camera/bpu 在 L2 升为 real-sim(合成帧/合成结构结果,均为本节自己的真仿真范例),limitation 内外标注"合成、不计真机验证"。**ground truth 矛盾记录不静默解**:accessory 快照(RDK OS 4.0.5-Beta)示 `bpu.inference.static=available`,而真机 `S100P_MATRIX` 仍 UNAVAILABLE(S1-C FIND-002,libdnn 缺失);虚拟板以实测 accessory 快照为准,真机矩阵不动,仿真永不计真机验证。
覆盖原则:**能仿真多少就仿真多少**(最大化覆盖)。接口面的枚举来源是现成的——三个 Starter(系统健康卡 / 静态 BPU 推理 / USB Camera)与 Camera/BPU 能力模板已圈定学生真正会碰的板级接口。实在仿真不了的走"标注 mock",绝不静默假装(§7 诚实底线)。
#### 2.3 真实快照驱动(保真的来源)
虚拟板的盘点事实**由真机实测快照驱动**,不凭空编造硬件事实。仓库已留有真实 S100P 快照可作 ground truth:`docs/testing/evidence/s100p-snapshot.json`、`s100p-formal-snapshot.json`、`s100p-accessory-snapshot.json`。虚拟板返回的 board/OS/资源/BPU/USB/video 事实与真板逐字段同构,使 Agent、GUI、CLI、MCP 在虚拟板与真板上走**完全相同**的代码路径(`事实先于建议`)。
### 3. 第二层:虚拟设备(形态 + 电路 + 几何)
学生要造的设备由 DeviceSpec(§4)描述,仿真对其求值。**不上物理引擎**:本层的机械关注点折叠进 CAD 内核与纯数学,不需要刚体动力学求解器。
#### 3.1 电路层(嵌入式重心,差异化核心)
- **粒度:系统级电气,而非器件级、而非固件级。** 仿真学生设备的电源与信号链:电池(电动势+内阻+容量)、导线/连接器电阻、H 桥/电机驱动(PWM 开关)、直流电机(R-L + 反电动势 + 转矩常数)、总线舵机指令、MCU 引脚限幅。
- **方法:自研集总参数求解器**(改进节点分析 MNA + ODE 积分),与机械层按步耦合(电机:电气转矩 ↔ 转速/反电动势)。确定性、可 seed。
- **输出**:节点电压/支路电流波形为结构化工件;故障建模(欠压/过流/堵转)可见。
- **不做**:SPICE 器件级(晶体管/收敛调参,对学生不可读,留作未来可选高保真后端);MCU 固件寄存器级(那是 Wokwi/Renode 的地盘,非本系统所在层)。
#### 3.2 几何层(选效果好的:OpenCascade)
- **内核:OpenCascade(经 build123d 调用)**——完整 B-Rep 实体建模、布尔运算、质量属性、可打印性分析,是"造真机"所需实体能力最全的选项。它是 CPU 计算、无头、pip wheel 分发,不吃显卡不吃配置(体积大是"依赖重"而非"硬件重")。
- **从 DeviceSpec 的机械段生成零件实体** → 干涉检查(布尔求交)、质心/体积、支撑稳定性(质心投影落于支撑多边形)。
- **制造导出**:逐零件导出二进制 STL(水密/流形校验、最小壁厚、打印机体积检查作为 **printability verifier**)+ BOM + 零件清单,作为版本化 Artifact(内容寻址)。导出路径限定项目/运行产物根。
- **待办评估项**:OpenCascade 在 三平台 × Python 版本 的 wheel 覆盖需在实现前实测确认(§11 未决)。
#### 3.3 运动学(纯数学,非物理)
可达性(正/逆运动学)、行程范围、整机稳定性——均为几何/数学判定,确定性、可解释,无需求解接触力。运动预览("这电机转速下怎么走")用底盘运动学的简单积分即可,不做动力学。
#### 3.4 不上的东西(及理由)
- **不上刚体物理引擎**(MuJoCo/Isaac/Gazebo/Webots 等):本系统是构建验证,不是数据采集;物理引擎引入原生分发、接触调参与不确定性,却换不来产品需要的答案。已对 MuJoCo 做过 smoke(arm64 4/4 判据、Apache-2.0),结论作为**否定项证据**存档——若未来确需动力学有现成选项,但不进当前路线。
- **不做渲染依赖**:3D 预览是"呈现"问题,与"仿真计算"解耦,懒加载/可选;核心计算全程无头。
### 4. DeviceSpec:设备设计书(新领域聚合)
新增版本化领域聚合 `DeviceSpec`(进 `rdk_agent_core`,Pydantic 为源、生成 JSON Schema),是学生可见可改、Agent 可写的**设备设计书**,内容寻址(与源码同等待遇,digest 绑定):
- `mechanical`:参数化零件树(零件模板 + 参数)+ 装配关系 + 材料/质量估算;
- `electrical`:网表(网络/节点 + 元件)+ 功率预算;
- `control`:MCU 引脚/PWM 通道 → 执行器映射;
- 每项参数带 **provenance**(`user | agent | template | datasheet | measured`),沿用旧系统 `calibration_status` 纪律(占位时不宣称已标定)。
**零件库**:仓库内置、经审核的参数化零件模板(底板、电机座、轮适配器、舵机支架等)起步;每个模板带电气参数(内阻/转矩常数/额定电流)+ 几何参数 + provenance。不做社区零件注册表(消费级约束)。
DeviceSpec 是**项目内用户数据**:人可在编辑器改、Agent 经受控 workspace API 改;其 digest 参与 source-bound Plan/Run 语义。
### 5. Agent 分工:大模型设计与解释,仿真确定性裁决
遵循 `验证定义完成`、`事实先于建议`:
- **大模型**:把学生意图翻译为 DeviceSpec(生成/修改设计)、解读仿真结果、提出迭代建议。这是大模型真正增值处。
- **仿真**:对 DeviceSpec 做**确定性求值**,输出事实(欠不欠压、够不够得着、稳不稳、能不能打印)。**成功与否由仿真说了算,不由模型自评。**
- **闭环**:因仿真轻量且确定,Agent 可高频跑"生成 → 仿真 → 拿事实 → 改写"的设计迭代循环。
仿真对 Agent 暴露的是**类型化、有界**的操作(不暴露任意路径/进程):
```
sim.evaluate(DeviceSpec) → 结构化事实(电路/运动学/稳定性/可打印性)
sim.export_stl(DeviceSpec) → STL + BOM + 可打印性报告(内容寻址工件)
```
板级运行仍走既有 Plan/Run 路径。模型不得借仿真注入任意硬件路径、shell 参数或未知二进制(`CFR-027`、`CSEC-001`)。
### 6. 出身标注与诚实分列(重新引入)
旧系统的 `environment_kind` 概念已随移除删除,新系统**重新定义**运行出身的标注与分列,语义如下:
- 每条运行记录标注出身:`仿真`(虚拟板/虚拟设备)或 `真机`;
- 报告界面**分栏展示**仿真结果与真机结果,学生一眼看清这条成功来自哪里;界面只呈现"仿真 / 真机"两个朴素标签,**不暴露协议 ID 或策略对象**(消费级约束);
- **仿真通过永不计为真机验证通过**;宣称"作品完成/验证"必须有真机证据支撑。无出身标注的运行归"未知",不默认当真机。
该语义支撑 `CFR-025`(诚实结果)并在报告层强制分列;同时是教学点——"仿真过了,真机上还要再验一次"。
### 7. 诚实底线与能力闸
- 虚拟板/虚拟设备的能力**不因"在仿真里"而自动开放真实执行器**:GPIO/舵机/电机等在真实硬件上仍遵循安全闸(`CSEC-002/008`、`CFR-026`),仿真只建模不授权。
- "标注 mock"接口必须内外标注,其结果不计为真实验证(§2.2)。
- `calibration_status=placeholder` 时不宣称真实标定或 sim-to-real;仿真结论不外推为真机结论。
- 不编造硬件事实:虚拟板事实来自真实快照(§2.3),非模型猜测。
### 8. 跨平台与硬件无关
- **平台**:Windows / macOS / Linux,普通非 root 用户,无系统服务、无新监听端口(数据面仅 loopback,沿用既有安全规则)。
- **硬件**:全程 CPU-only、无头可跑、不依赖 GPU。唯一重依赖是 CAD 内核(OpenCascade),为"体积重"而非"硬件重",且须先验证三平台 wheel 覆盖(§11)。
- **无云**:不依赖公网、账号或云端渲染(`local-first`)。
### 9. 安全边界
- 仿真进程普通用户运行;动作/求值有界(超时、取消、清理、安全终态),复用既有资源上限语义。
- 电路/机械仿真可自由建模电机、舵机等,但**不构成对真实执行器的授权**(§7)。
- STL/工件导出限定项目/运行产物根,路径受控。
- 不安装 root 守护、不引入特权 supervisor、不自动执行未知原生二进制(`CSEC-001`)。
### 10. 明确不做(首版边界)
- 不上刚体物理引擎、不做接触动力学/渲染管线(§3.4);
- 不做 SPICE 器件级电路、不做 MCU 固件寄存器级仿真(§3.1);
- 不做 PCB 布线/打样(EasyEDA 的地盘)、不做云端渲染/账号;
- 不做社区零件市场、多设备编排、远程 HTTP/Streamable;
- 不做 L3 电气级板仿真(待 L1/L2 站稳,§2.1)。
### 11. 里程碑(一次一个)
| 里程碑 | 内容 | 状态 |
|---|---|---|
| **SIM-R0** | 旧系统移出归档 + 本 ADR 规范 | 完成(2026-08-26:移出 `4670e4b`;wheel/typing 证据 `docs/testing/evidence/sim-r1/OCC-SMOKE.md`) |
| SIM-R1 | 首个垂直切片:一个参数化 2WD 小车——DeviceSpec → 电路仿真(电池→驱动→电机,波形+堵转)→ 运动学/稳定性判定 → STL 导出 + BOM;虚拟板契约保真(L1)随片提供。经 CLI+Host,golden trace + 确定性回归。验收编号自 `AT-034` 起。 | **本轮** |
| SIM-R2 | L2 可运行板:学生代码真跑、相机合成帧、BPU 结构结果;设备设计旅程进 GUI/TUI。 | **本轮(Python 侧 L2;GUI/TUI 并行轨道)** |
| SIM-R3 | printability 深化、零件库扩展、跟随实测设备的形态选择、板级 L3 电气评估。 | 后续 |
**未决关闭(2026-08-26,进 SIM-R1 前)**:
1. OpenCascade wheel 覆盖 → 实测关闭:`docs/testing/evidence/sim-r1/OCC-SMOKE.md`。`cadquery-ocp-novtk` 7.9.3.1.1 覆盖 macOS arm64/x86_64、manylinux x86_64/aarch64、win_amd64 × cp310–3.14;mypy strict 经 `cadquery-ocp-stubs` 兼容。几何内核冻结 `build123d==0.11.1`。
2. 板级接口面 → **2026-08-27 关闭(SIM-R2)**:完整 12 行三档枚举入 `interface_fidelity.json`(system.info/usb.enumerate/serial.enumerate/can.enumerate 真仿真;camera/bpu 升 real-sim 带合成 limitation;serial.io.loopback 标注 mock;gpio/pwm/servo/motor/can.write 不可用);虚拟板事实升级 probe_set 1.2.0(accessory 快照同构,含 peripherals/software)。
3. 出身标注 → 新字段 `RunRecord.origin: RunOrigin("simulation" | "real_device") | None`(None=未知,不默认当真机);`RunTicket`(StrictModel)不加字段;报告按 origin 分列(`evidence_by_origin`)。不复用 `environment_kind` 名称。
## 结果
- 新增 `ADR-019`(本文)。随后在 `rdk_agent_core` 引入 `DeviceSpec` 聚合与三档保真度/出身标注模型,生成对应 JSON Schema;`rdk_agent_sim` 包重写;`docs/00/02/03/06` 与测试文档同步登记。
- 不新增企业抽象、不建多引擎工厂、不引入数据库;仿真输出物为内容寻址工件。
- MuJoCo smoke 结论以否定项证据存档,不进依赖。
## 冻结记录
- 机械层:**不上物理引擎**(构建验证非数据采集;跨平台/无 GPU 约束)。
- 几何内核:**OpenCascade / build123d**(选效果好的;待验三平台 wheel)。
- 板级保真档:**L2 可运行板**。
- 接口覆盖:**最大化仿真覆盖**,仿真不了的走"标注 mock",本就不该有的"不可用"。
- 许可:build123d Apache-2.0;OpenCascade 经 ocp wheel 动态链接(LGPL-3.0),可替换 pip 分发、不静态链接,作为已接受约束记录(OCC-SMOKE.md)。

View File

@ -119,9 +119,9 @@
对应:FR-003–009。
步骤:注册时只提供连接 alias,并故意填入错误 expected board/camera hint;启动全新 Agent Task;确认 Agent 自主请求 bootstrap inventory;确认板型/RDK OS/内核/资源/BPU/USB/video/TROS 字段;注入一个 probe timeout 再 full inventory;在 Fake/HIL 可控条件下模拟快照过期和 USB camera 出现,运行 targeted inventory;随后尝试使用旧 plan。
步骤:注册时只提供连接 alias,并故意填入错误 expected board/camera hint;启动全新 Agent Task;确认 Agent 自主请求 bootstrap inventory;确认板型/RDK OS/内核/资源/BPU/USB 设备列表/video/TROS/串口节点/CAN 接口/LeRobot 版本字段(probe_set ≥1.2.0 的 `peripherals` 与 `software.lerobot_version`);注入一个 probe timeout 再 full inventory;在 Fake/HIL 可控条件下模拟快照过期和 USB camera 出现,运行 targeted inventory;随后尝试使用旧 plan。
通过:错误 hint 不会成为事实或授权;每个关键字段有 observation/probe/evidence;单 probe 失败只产生 `probe_errors`/degraded,不丢其他结果;板型不确定时为 unknown 而非猜测;inspect 读取缓存而不伪装刷新;过期/任务相关事实触发盘点;硬件变化产生 InventoryDelta、更新 capability 并使旧 plan 失效;新增硬件不自动获得策略权限。
通过:错误 hint 不会成为事实或授权;每个关键字段有 observation/probe/evidence;单 probe 失败只产生 `probe_errors`/degraded,不丢其他结果;板型不确定时为 unknown 而非猜测;USB 设备列表以原始 VID:PID 事实进入快照,不得退化为只有能力位,也不得从 VID:PID 推断产品命名(如"某底盘已连接");串口节点为空时 `serial.enumerate`/`can.enumerate` 为 unavailable 而非探针失败;inspect 读取缓存而不伪装刷新;过期/任务相关事实触发盘点;硬件变化产生 InventoryDelta、更新 capability 并使旧 plan 失效;新增硬件不自动获得策略权限;探针对电机/舵机总线保持零交互(无 PING、无写指令)。
## AT-003 Plan 先于设备写入与摘要绑定 `[MVP]`
@ -326,3 +326,83 @@
步骤:两租户/两个 Connector;尝试跨租户 task/artifact/device、托管 worker 扫描现场内网/读取 SSH key、伪造 Connector/device、mTLS 过期、断链期间 start、重连 replay、Web approval/steer/cancel;对同一 Fake 场景分别运行 direct 与 relay transport contract suite;检查 Connector 进程/配置不包含 Pi、模型、workspace 或技能模块。
通过:租户与设备绑定严格;托管 worker 无现场内网路由/SSH key;双向认证失败关闭;Connector 现场策略可拒绝非端侧请求;断线/重连不重复 start;Web 操作关联真人 actor 并端到端审计;direct/relay 除 transport 与时序观测字段外产生等价 plan、run identity、policy 和 verifier 结论。
## AT-028 … AT-031(已迁出)
原仿真系统(Webots + 确定性状态机,ADR-016)已于 2026-08-26 整体移出本仓库,归档至
`/Users/d-robotics/Documents/rdk-sim-webots-legacy/`(含 AT-028/029/030/031 原文、
证据与代码)。新仿真系统的验收自 AT-034 起编号(AT-032/033 为底盘能力验收),
规范见 `docs/adrs/ADR-019-rdk-sim-v2-circuit-level-device-design-simulation.md`。
## AT-034 2WD 小车电路仿真判据 golden `[MVP]`
对应:ADR-019 §3.1/§5,CFR-025。
步骤:
1. `rdkctl device register --device-id virtual-rdk-001 --transport sim-stdio`;
2. `rdkctl sim evaluate --device-id virtual-rdk-001 --spec <2wd-rover.json> --scenario nominal`;
3. `--scenario stall`(健康电池、转子锁定)与 `--scenario stall_weak`(锁定+磨损电池内阻 ×8);
4. 读取 verdicts.json/waveform.json 工件;同场景各跑两次比对 digest。
通过:nominal 自旋限流(平均电流显著低于堵转界)、电池端电压压降与内阻模型一致、加速(omega_final>0 且未堵转)、全 faults 假;stall 两通道平均电流均 ≥1.5× nominal 同通道且 stall+overcurrent 真、undervoltage 假;stall_weak undervoltage 真(口径澄清 2026-08-26:欠压由磨损电池变体演示,与 1.5× 判据物理上不可同场景共存);同场景双跑 waveform/verdicts digest 完全相等;manifest 以零新增策略条目通过 PolicyEngine(R0 ALLOW);非法 sim.kind 终态 failed(fail-closed)。
## AT-035 运动学/静态稳定性确定性 `[MVP]`
对应:ADR-019 §3.3,CFR-025。
步骤:同 DeviceSpec 同场景 evaluate 双跑,读轨迹工件与稳定性判据;修改一个机械参数(如质心高度/装载偏移)再跑。
通过:同参数双跑轨迹/稳定性 digest 相等;质心投影落于轮支撑多边形内时稳定性判据通过且裕度为正;质心移出支撑多边形或准静态倾覆裕度转负时判据失败且 spec_id 随内容变化;全程纯数学判定、可解释,无刚体物理引擎参与。
## AT-036 STL 导出与 printability verifier `[MVP]`
对应:ADR-019 §3.2,CFR-025,CSEC-001(路径 containment)。
步骤:`rdkctl sim export --device-id virtual-rdk-001 --spec <2wd-rover.json>`;检查工件清单与内容;尝试把导出指向产物根之外。
通过:逐零件(底盘板/电机座/轮适配器等)二进制 STL 均为单一水密有效 solid;BOM 含打印件+外购件且带 provenance;printability 报告含 水密/流形/床身适配/最小壁厚 判据;工件内容寻址、每个 STL 小于 1MiB fetch 上限;越根导出被拒绝;macOS arm64 上 STL 字节 digest 与 golden 相等,Linux CI 断言结构不变量。
## AT-037 虚拟板 L1 契约保真与出身分列 `[MVP]`
对应:ADR-019 §2.2/§2.3/§6,CFR-025,CFR-026。
步骤:对已注册 sim 设备 inventory;与真 S100P 快照逐字段比对;检查 capability.list 标注 mock 条目的内外标注;分别跑一次 sim run 与 fake/真机 run 后查 task report;尝试把 simulation run 计为真机验证。
通过:虚拟板 DeviceSnapshot 与真快照字段同构(board/OS/资源/BPU/USB/video,available 能力均有 observed observation 覆盖),model 字符串无 NUL 且 provenance 可溯;mock 接口内外携带"标注 mock:结果不计为真实验证"limitation;report 按 仿真/真机/未知 分列,无出身 run 归未知;不存在任何把仿真结果升级为真机验证的路径。
## AT-038 L2 审核模板在虚拟板真跑 `[MVP]`
对应:ADR-019 §2.1/§5,CFR-025/027。
步骤:
1. `rdkctl sim provision`;`rdkctl sim run --template health-card`;
2. `rdkctl sim run --template usb-camera-snapshot`;
3. `RDK_R2_ALLOWLIST=bpu.inference.static` 下 `rdkctl sim run --template bpu-static-inference`(预期 APPROVAL_REQUIRED)→ 人工 `approval approve` → 带 `--approval-id` 复跑;
4. 以自构 manifest(staged 源与审核模板 digest 不等)经协议 run.start 打 sim 设备。
通过:health-card/camera `succeeded/passed`、`origin=simulation`、可见产物(health.json/snapshot.png+camera.json)与 required verifiers 全过;bpu 无审批被拒、有审批通过;自构程序 fail-closed(POLICY_DENIED,不执行);仿真结果不计真机验证。
## AT-039 合成相机帧确定性与 image verifier `[MVP]`
对应:ADR-019 §2.2,TEST_STRATEGY §12.2。
步骤:同模板双跑 `usb-camera-snapshot`;读取 snapshot.png;以截断/非图字节伪造工件跑 verifier。
通过:macOS arm64 双跑 snapshot.png 字节 digest 相等(他平台结构不变量:IHDR 640×480、PNG 签名、CRC);camera.json origin=simulation 且含合成 provenance;`image.basic` 对合法帧 PASS、对截断/非图字节 FAIL(never fail-open)。
## AT-040 BPU 结构化结果确定性与标注 `[MVP]`
对应:ADR-019 §2.2,AT-014 口径。
步骤:`bpu-static-inference` 双跑;读 bpu_result.json;`capability.list` 查 bpu.inference.static;以未审核 model digest 直接调 shim。
通过:双跑 bpu_result.json digest 相等;labels/scores 由 sha256(model+input) 派生、latency 常量、温度解析自快照 telemetry;capability limitation 含"synthetic…never count as real verification";未审核模型 fail-closed;origin=simulation。
## AT-041 虚拟事实 1.2.0 同构与完整接口面枚举 `[MVP]`
对应:ADR-019 §2.3,§11 未决项 2。
步骤:inventory 虚拟板;与 `s100p-accessory-snapshot.json` 逐字段比对;读 `interface_fidelity.json`。
通过:probe_set_version=1.2.0;peripherals(usb 含相机/serial /dev/ttyACM0/can 空)与 software.tros_distro=humble 同构;6 capabilities 齐且 available 均有 observed observation;12 行三档如 ADR §2.2 注(camera/bpu real-sim 带合成 limitation;serial.io.loopback 标注 mock;gpio/pwm/servo/motor/can.write 不可用);provenance 含 accessory sha256 与 FIND-002 矛盾注。

View File

@ -1,44 +1,45 @@
# 当前硬件基线:RDK S100P 裸板
# 当前硬件基线:RDK S100P + LeKiwi 底盘/相机(舵机未上电)
状态:Baseline v0.5
记录日期:2026-08-12
事实来源:用户提供的内容属于未验证 hint;所有板型、版本和外设字段待 Agent 首次只读 Inventory Engine 盘点后成为设备事实
状态: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…`)
## 1. 已确认事实
| 项目 | 当前值 | 证据状态 |
|---|---|---|
| 板卡 | 预期为 RDK S100P | 用户 hint;首次连接后用板卡探针复核 |
| 非端侧连接 | 网线直连 | 用户确认 |
| DeviceTransport | 目标为 `direct + ssh-stdio` | 设计决定;SSH alias/IP/host key 尚未记录 |
| 相机 | 预期当前没有;USB 摄像头已购买、预计近期到货 | 用户 hint;inventory 应返回当前 video/USB 事实 |
| 舵机 | 预期没有 | 用户 hint;无对应 capability 证据时 unavailable/unknown |
| 板卡 | RDK S100P V1P0 | 探针实测(`identity.model`,NUL 已剥离) |
| 非端侧连接 | 网线直连(en8) | 用户确认 + SSH 实测 |
| 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 |
| GPIO 工装 | 未提供 | 视为没有,相关 capability 禁用 |
| RDK OS | 未知 | 待 `rdkos_info`/`cat /etc/version` |
| Kernel | 未知 | 待 `uname -a` |
| BPU runtime | 未知 | 待只读探针 |
| TROS/ROS 2 | 未知 | 待只读探针 |
| RDK OS | 4.0.5-Beta | 探针实测 |
| Kernel | 6.1.158-rt58-DR-…(aarch64) | 探针实测 |
| BPU runtime | `pvt_bpu_pvtc1_t1 : 43.4°C` | 探针实测 |
| TROS/ROS 2 | `tros_distro=humble` | 探针实测 |
| LeRobot | 未安装(`lerobot_version=null`) | 探针实测,如实 |
本表不是运行时硬件清单,不能直接给 capability、policy 或 Skill compatibility 使用。未知字段不得从用户描述、官网示例、主机名或其他板卡结果推断。首次真机阶段由 Agent 自主请求 bootstrap inventory,只收集事实,不刷机、不升级系统、不安装相机驱动、不修改网络配置。
本表不是运行时硬件清单,不能直接给 capability、policy 或 Skill compatibility 使用。未知字段不得从用户描述、官网示例、主机名或其他板卡结果推断;能力不得由 VID:PID 或别名推断(AT-002)。
## 2. 裸板阶段允许的 HIL
## 2. 当前允许的 HIL
- SSH host key 核验和设备注册;
- `rdkos_info`、`/etc/version`、kernel、CPU、内存、磁盘、温度、网络、USB、video node、BPU 和 TROS/ROS 2 的只读发现;
- `rdkos_info`、`/etc/version`、kernel、CPU、内存、磁盘、温度、网络、USB、串口节点、CAN、video node、BPU、TROS 与 LeRobot 版本的只读发现(probe_set 1.2.0);
- 普通无硬件权限 Python hello/health 程序;
- run workspace、stdout/stderr、JSON/file artifact、verifier;
- 超时、取消、进程树清理和安全断链恢复;
- 使用固定摘要静态输入的 S100P 兼容 BPU 官方/受审核样例;
- “没有摄像头”能力状态与错误语义:`camera.snapshot.usb=unavailable`。
- USB 相机真机快照(AT-013,相机已连接)。
## 3. 裸板阶段禁止或阻塞
## 3. 当前禁止或阻塞
- Camera 真机快照:`blocked`,`reason_code=external_dependency`;
- 舵机、PWM、电机、机械臂、继电器动作:未安装且无安全工装,禁止;
- 舵机、PWM、电机、机械臂、继电器动作:舵机 12V 未上电且无安全工装,禁止(含对电机/舵机总线的 PING/写指令,探针保持零交互);
- GPIO loopback:无工装,禁止;
- MIPI/GMSL Camera:无相机和扩展工装,禁止;
- Flash、bootloader/partition、电压/频率/thermal limit、远程电源控制:始终禁止;
- 任何为了“准备环境”执行的自动 `apt upgrade`、系统镜像更换或未知驱动安装。
- 任何为了”准备环境”执行的自动 `apt upgrade`、系统镜像更换或未知驱动安装。
Mock/Fake 可以用于 CI 和协议测试,但测试报告环境必须标为 Fake,不能填写真机 HIL passed。

View File

@ -55,6 +55,7 @@
| Agent deterministic eval | Node + Fake | ScriptedModel 工具轨迹、恢复、审批、预算、假成功 | 必须 |
| Linux 沙箱集成 | Linux CI | process tree、rlimit/cgroup、filesystem、signals | 必须(平台适用) |
| Replay 测试 | CI | 历史 trace、verifier、诊断、skill retrieval | 必须 |
| 虚拟 RDK 仿真 | Host CI | 电路/运动学/几何确定性(digest 相等)、虚拟板 L1 契约同构、STL/printability、出身分列 | 必须 |
| HIL smoke | RDK 实验室 | 只读 inspect、Python、基础 artifact | main/release |
| HIL capability | RDK + 工装 | Camera/BPU/TROS;GPIO 只验证不可达 | 插件变更/release |
| 烧录 simulator/HIL | CI + 专用可恢复 RDK | 板型/镜像/摘要/确认/状态机/恢复 | S5/release;真写入人工值守 |
@ -269,6 +270,15 @@ Fake 的每个场景有固定事件脚本和期望 RunRecord digest(排除时
Live benchmark 任务至少覆盖:新程序编写、既有程序修复、能力缺失、验证失败修复、技能复用、安全拒绝、预算耗尽。评分由确定性 task/verifier/audit 计算,不能让参评模型给自己打分。
### 12.2 仿真确定性契约
- 固定步长冻结为代码常量并在工件头回显:电路 dt=1e-6 s(PWM 1 kHz)、运动学 dt=1e-2 s;不用墙钟、不用无种子随机;
- 波形每 64 采样抽 1、每个浮点序列化前舍入到 9 位小数;运动学每 10 采样抽 1;抽取因子记录在工件头;
- golden trace 比 **digest 相等(零容差)**:verdict/waveform 用 canonical JSON + content_digest,二进制 STL 用 bytes_digest;STL 字节 digest 仅固定 macOS arm64,CI Linux 断言结构不变量(三角数/水密/体积/bbox/BOM digest);
- 非 golden 健康/性质检查用相对容差 `abs(a-b) <= 1e-9 + 1e-9*max(abs(a), abs(b))`;更宽容差必须在测试中命名理由;
- **合成相机帧(SIM-R2)**:手写 PNG(zlib+struct、level 9),字节 digest 仅固定 macOS arm64(zlib 跨版本不保证),他平台断言结构不变量(IHDR 尺寸/格式/CRC/非空,`image.basic` verifier 不 fail-open);
- **BPU 合成结构结果(SIM-R2)**:labels/scores 由 sha256(model+input digest) 派生、latency 常量、温度解析自快照 telemetry——纯跨平台确定性,canonical JSON digest 全平台相等;虚拟系统事实为冻结小数。
## 13. 质量门禁与缺陷等级
### PR 门禁

View File

@ -24,6 +24,17 @@
旧 FR/NFR/SEC/AT 保留为底层技术追踪,不再意味着对应企业特性是消费级替代产品发布范围。
## S1 设备连接切片实现追踪(2026-08-20)
证据与复现命令见 `docs/testing/evidence/S1C-DEVICE-CONNECT.md`。
| 需求 | 实现 | 测试/证据 |
|---|---|---|
| FR-001/002、AT-001(首次注册与主机身份) | host human 角色 + GUI/rdkctl 同源 register/TOFU | `tests/unit/test_human_surface.py`、门控 `deviceService.test.ts` |
| CFR-046–049、CAT-006A(多入口等价) | GUI 与 CLI 走同一 `AgentApplicationService` | 证据 §2;rdkctl 重构同源 |
| CSEC-011–012、CAT-006B(模型面无批准能力) | `HUMAN_METHODS` 与 `AGENT_METHODS` 不相交;agent 角色拒绝 → RDK-PROTO-001;MCP 工具列表未动 | `test_human_surface.py` + `TestAT021ToolSurface` |
| CSEC-005、CFR-002(host key 变化阻断/只提供连接信息) | `known_hosts` TOFU 不变量 + 向导仅收别名与 SSH 主机 | `test_registration_store.py`(既有)+ 向导 UI |
## M0 实现追踪(2026-08-13)
M0 验收以 `docs/06` §4.3 出口门禁与正式 AT 编号的 Fake 变体为准;证据与复现命令见 `docs/testing/evidence/M0.md`。早期曾用的 `AT-CORE-*`/`FR-AGT-*` 为工作编号,已废弃,不再使用。
@ -50,6 +61,30 @@ M0 验收以 `docs/06` §4.3 出口门禁与正式 AT 编号的 Fake 变体为
| AT-003/004/006 | Fake 变体通过 | `tests/acceptance/test_fake_variants.py` |
| 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/` |
## SIM-R1 虚拟 RDK 仿真切片实现追踪(2026-08-26)
| 需求 | 实现 | 测试/证据 |
|---|---|---|
| CFR-025 诚实结果 | `RunRecord.origin` 仿真/真机/未知分列;仿真永不计真机 | AT-037;report `evidence_by_origin` |
| CFR-026 / CSEC-002/008 执行器闸 | 仿真建模执行器但不授权;真实 GPIO/PWM/电机仍 unavailable | AT-037;policy 回归 |
| CFR-027 / CSEC-001 有界路径 | sim argv 由宿主固定产品命令构造;导出路径限定产物根 | AT-034–037 集成 |
| ADR-019 §2.3 事实先于建议 | 虚拟板事实由真 S100P 快照驱动(去 NUL + provenance 头) | AT-037 |
| ADR-019 §4 DeviceSpec | `rdk_agent_core.device_spec` + `schemas/device-spec.schema.json` + provenance 纪律 | `test_core_device_spec`;AT-034–036 |
| ADR-019 §3 电路/几何/运动学 | `rdk_agent_sim` circuit/geometry/kinematics,确定性 digest | AT-034/035/036;`tests/golden/sim` |
独立测试复测(2026-08-27):AT-034..037 **全部通过**,753 tests 全绿、core 分支覆盖 96.27%;D1–D4 修复核验无回归。证据:`docs/testing/evidence/sim-r1/SIM-R1-TEST-REPORT.md`。
## SIM-R2 虚拟 RDK L2 可运行板实现追踪(2026-08-27,Python 侧)
| 需求 | 实现 | 测试/证据 |
|---|---|---|
| ADR-019 §2.1 L2 可运行板 | `SimProgramBackend`(审核模板 digest 闸 + env 全控)+ `rdk_virtual_board` shim(系统事实/合成帧/BPU 结构结果) | AT-038/039/040(测试阶段) |
| CFR-027 有界模板 | core `templates.py` 注册表 + `template_source_digest`;模型自构 fail-closed | AT-038 负例 |
| ADR-019 §11 未决项 2 | `interface_fidelity.json` 12 行三档;虚拟事实 1.2.0 同构(accessory 快照) | AT-041 |
| §5 类型化有界操作 | host `sim.evaluate/sim.export_stl/sim.run` RPC + `rdkctl sim run`;bpu 走人工审批两步 | AT-038 |
## 功能需求

View File

@ -0,0 +1,59 @@
# probe_set 1.2.0 证据:配件可见性(USB 设备列表 / 串口 / CAN / LeRobot)+ CLI 实时盘点
日期:2026-08-24
验收结论:**Accepted(真机实测通过)**
范围:AT-002 扩展(配件枚举字段);修复「CLI 无法对注册真机发起实时盘点」;修复板端部署滞后(旧 1.1.0 无 S1C-FIND-001 NUL 剥离)
环境:macOS arm64(uv)↔ 真机 RDK S100P V1P0(RDK OS 4.0.5-Beta,sunrise@192.168.127.10,en8 直连),外设:LeKiwi 底盘驱动板(QinHeng 1a86:55d3 USB-CDC → /dev/ttyACM0)+ USB 相机(1e45:0209)
## 1. 结论摘要
起因:真机接入 LeKiwi 底盘后,产品 Inventory(probe_set 1.1.0)虽执行了 `lsusb`,却只把「usb.enumerate 能力可用」记入快照、**丢弃设备列表**,且无串口/CAN/软件环境探针,导致产品看不见已连接的配件;`rdkctl device inventory` 又固定走本地 stdio(fake-001)连接器,CLI 对注册真机没有实时盘点入口。
本切片把 probe_set 升到 **1.2.0**(注册表 8 → 11,固定、版本化、只读):
- `linux.usb.enumerate@1` → `@2`:USB 设备列表以结构化事实进入 `snapshot.peripherals.usb_devices`(bus/device/VID:PID/描述;不做设备类或产品命名推断,符合「能力不得由别名推断」)。
- 新增 `linux.serial.nodes@1`(ttyACM/ttyUSB/ttyAMA → `peripherals.serial_nodes`,能力 `serial.enumerate`)。
- 新增 `linux.can.interfaces@1`(/sys/class/net/can* → `peripherals.can_interfaces`,能力 `can.enumerate`)。
- 新增 `ecosystem.lerobot@1`(importlib.metadata 观测 LeRobot 版本 → `software.lerobot_version`,未安装为 null,不猜)。
- `InventoryTarget` 增加 `serial|can|software`(版本化枚举追加)。
- **明确不做**:电机/舵机总线探测(PING/写指令)——消费级约束「舵机/电机在安全硬件套件+验收套件前不开放」继续有效;探针对其保持零交互。
CLI:`rdkctl device inspect` 新增 `--refresh cached|quick|full`(默认 cached),full/quick 走 `connector_for` 的 SSH 链路,CLI 与 GUI/MCP 面共用同一 `inspect_device`。
## 2. 交付与证据
| 层 | 交付 | 证据 |
|---|---|---|
| core | `PeripheralsBlock`/`UsbDevice`;`DeviceSnapshot.peripherals`(加性,旧快照仍可解析);`SoftwareBlock.lerobot_version`;`InventoryTarget.SERIAL/CAN/SOFTWARE` | `tests/unit/test_plugin_s100.py`;schema 契约测试(重新生成 3 个 schema 文件) |
| plugin rdk_s100 | probe_set 1.2.0(11 探针);`parse_lsusb`(不可解析行丢弃不猜);空串口/空 CAN 记为能力 unavailable 而非探针失败 | 单测:注册表钉死、targeted 选择、外设事实、lerobot 有/无、CAN 有、usb 失败 fail-closed、脏行丢弃 |
| CLI | `device inspect --refresh`;透传至 `inspect_device` | `tests/unit/test_cli_inspect.py` 3 例(透传/默认 cached/非法值拒绝) |
| 文档 | docs/03 §2.2/§2.2.1 快照与请求示例更新;AT-002 步骤与通过判据扩展(含「VID:PID 不得推断产品命名」「探针对电机总线零交互」) | 同库文档 |
| 部署 | `scripts/install-device-helper.sh build` → scp → install(RDK_BUNDLE_DIR=dist-helper);板端 `~/.rdk/lib` 全量刷新至 1.2.0,顺带修复旧版缺失的 NUL 剥离 | 板端 `grep PROBE_SET_VERSION` = 1.2.0 |
## 3. 门禁
| 门禁 | 结果 |
|---|---|
| pytest tests/unit tests/contract | 全绿(约 770 例,0 failed) |
| ruff format + check(packages/plugins/tests) | 通过 |
| mypy --strict(core/cli/rdk_s100,28 文件) | 通过 |
| schemas 重新生成 + 契约测试 | 通过(device-snapshot/inventory-request/example) |
## 4. 真机实测(产品面,非手工 SSH)
链路:`rdk-agent-host serve --stdio` → `device.inspect {refresh:"full"}` → SSH → 板端 helper(profile s100-readonly)→ probe_set 1.2.0;以及 `rdkctl device inspect --refresh full` 同链路。
结果(快照 `sha256:83b16d4582491d11…`,全文 `docs/testing/evidence/s100p-accessory-snapshot.json`):
- `inventory.probe_set_version = 1.2.0`,`completeness = complete`,`probe_errors = []`
- `identity.model = "D-Robotics RDK S100P V1P0"`(NUL 已剥离)
- `peripherals.usb_devices` 含 **底盘驱动板 `1a86:55d3` QinHeng Electronics USB Single Serial(Bus 003 Device 002)** 与相机 `1e45:0209`
- `peripherals.serial_nodes = ["/dev/ttyACM0"]`;`peripherals.can_interfaces = []`(如实,无 CAN)
- `software.lerobot_version = null`(如实,未安装)
- 能力:`serial.enumerate=available`、`can.enumerate=unavailable`、`usb.enumerate=available`、`camera.snapshot.usb=available`、`bpu.inference.static=available`
## 5. 未覆盖/遗留
- 舵机在线性(LeKiwi 三舵机当时 12V 未上电、PING 无应答)不属于产品探针范围,需安全硬件套件线(见 docs 消费级约束)。
- `rdkctl device inventory` 仍绑定本地 stdio(fake)连接器;真机实时盘点的 CLI 入口是 `device inspect --refresh`。
- GUI 设备卡尚未渲染 `peripherals` 字段(服务层已返回,渲染属后续 GUI 迭代)。

View File

@ -1,18 +1,32 @@
# S1-A 验收证据:非 GUI 基础切片
日期:2026-08-14(收口修复后)
范围:`docs/S1-PLAN.md`(Approved for implementation)+ `docs/12-multi-surface-interface-spec.md` §3/§6
验收结论:**Accepted with conditions(允许进入 S1-B)**
范围:`docs/S1-PLAN.md` + `docs/12-multi-surface-interface-spec.md` §3/§6
环境:macOS arm64,Python 3.12(uv),Node v22.23.1,**无真实设备参与**
## 评审决定与遗留项
自动化门禁、MCP 黑盒握手、host key 标准指纹与 host 绑定、幂等恢复和审批跨进程互斥均已通过复验。以下问题不阻塞 S1-B,但不得据此声称真机链路已经完成:
| ID | 事实 | 处理期限 |
|---|---|---|
| `S1A-DEBT-001` | Helper 带 `--device-id` 可启动;当前 SSH 最终 argv 未传该参数,无参数时退出 `RDK-INV-001` | S1-C 前 |
| `S1A-DEBT-002` | 已固定远端路径,但没有面向 S100P 的普通用户安装/更新命令 | S1-C 前 |
| `S1A-DEBT-003` | 只读 dispatch 会拒绝所有写方法,但构造时仍创建未使用的 Fake facts/backend | Alpha 分发前 |
| `S1A-DEBT-004` | Node 22 门禁通过;本机默认 Node 20,需明确版本选择提示 | Alpha 开发者说明冻结前 |
因此,本证据只证明 S1-A 的非 GUI 基础足以支撑 S1-B,不构成 S100P 真机验收证据。真机结论只由 S1-C 产生。
## 收口修复(评审阻断项逐项关闭)
| 阻断项 | 修复 | 证据 |
|---|---|---|
| 真实 S100P Helper 未接通 | `rdk-agent-device serve --stdio --profile s100-readonly`:只读 profile 装载真实 S100 Inventory Engine(`CommandRunner` 本地执行固定探针),**拒绝 `run.*` 全部执行/写入方法**(`RDK-SEC-001` category=READONLY_PROFILE),不装配 FakeFacts/FakeExecutionBackend/测试密钥 | `tests/unit/test_device_readonly.py`(7 例);黑盒 `serve --profile s100-readonly` 实测拒绝 run.start |
| Helper 固定路径 + 安装命令 | `SshDeviceConnector` 默认 remote 为 `~/.rdk/bin/rdk-agent-device`(`RDK_REMOTE_HELPER_PATH` 可配),完整 argv 含 `--stdio --profile s100-readonly` | `test_registration_store.py::test_ssh_argv_*` |
| 真实 S100P Helper profile | `rdk-agent-device serve --stdio --profile s100-readonly --device-id <id>` 装载真实 S100 Inventory Engine;只读 dispatch 拒绝 `run.*`(`RDK-SEC-001` category=READONLY_PROFILE) | `tests/unit/test_device_readonly.py`;最终 SSH argv 的 device_id 接线记为 `S1A-DEBT-001` |
| Helper 固定路径 | `SshDeviceConnector` 默认 remote 为 `~/.rdk/bin/rdk-agent-device`(`RDK_REMOTE_HELPER_PATH` 可配) | 安装/更新命令记为 `S1A-DEBT-002` |
| MCP 无执行入口 | `bin.ts` 路由 `rdk-agent mcp --stdio` → `runMcpServer`(官方 SDK stdio);CLI 走其余 | 黑盒 `node dist/bin.js mcp --stdio` 启动无崩溃、stderr 干净 |
| host key 流程不可用 + 指纹算法错误 + 不核对 host | candidate 持久化到 `state_dir/known_hosts_candidates/`(`show`/`confirm` 跨进程);指纹改用 OpenSSH 标准 `SHA256:base64(sha256(raw wire key))`(测试用 `ssh-keygen -lf` 实比对);`verify_host_key` 同时核对 host 字段 | `test_registration_store.py`(含与 ssh-keygen 标准指纹一致、host 绑定负例) |
| 审批消费非跨进程原子 | `FileApprovalStore.consume_approval` 用 per-approval flock 包住 load→check_usable→写 consumed_by_run_id;InMemory 用锁 | `test_run_recovery.py::test_concurrent_consumption_of_same_approval_is_single_use`(两线程并发异 run_id,恰一成功一拒绝) |
| 审批消费非跨进程原子 | `FileApprovalStore.consume_approval` 用 per-approval flock 包住 load→check_usable→写 consumed_by_run_id;InMemory 用锁 | 仓库并发测试通过;Codex 另以两个独立进程复测,恰一成功一拒绝 |
| .gitignore 未屏蔽运行数据 | `.gitignore` 加 `.rdk/` + `**/.rdk/` | `git check-ignore` 通过,status 无运行产物 |
## 定位

View File

@ -0,0 +1,90 @@
# S1-B 验收证据:四入口任务服务 + Electron 桌面
日期:2026-08-17
验收结论:**Accepted**
范围:`docs/S1-B-PLAN.md` + `docs/12-multi-surface-interface-spec.md` §3/§4/§6 + ADR-014/ADR-015
环境:macOS arm64,Python 3.12(uv),Node v22.23.1,Electron 43.4.0(Node 24.18.1),**无真实设备参与(Fake Device)**
## 1. 结论摘要
S1-B 交付了「四个产品入口共享同一 TaskService/Task 状态/owner lock/验证据语义」的最小纵切片:CLI、TUI、MCP 和 Electron GUI 通过同一个 `buildTaskService` 驱动同一个 Host,执行同一张 Fake `system.health` 只读任务;GUI 主进程真实跑通 Host + Fake Device + ScriptedModel 会话;取消/关闭后无 Host/Pi/Device 残留进程。本轮另关闭了三个收口阻断项(版本保护、workspace-root 显式化、MCP 生命周期)。
## 2. 四入口交付与证据
| 入口 | 命令 | 交付面 | 真实证据 |
|---|---|---|---|
| CLI | `rdk-agent run|task ...` | `run` 任务 + `task list/status/steer/cancel/resume`,`--json` envelope / `--follow` JSONL / 默认人类进度 | `rdk-agent run "检查系统健康" --workspace proj-a --json` → `{"ok":true,"data":{"task_id":"task-…","state":"created","cursor":2}}`;`task list`/`task status` 跨进程可观察 |
| TUI | `rdk-agent tui <goal> --workspace-root <abs>` | 只读 readline 循环:status/steer/cancel/resume/open-gui;`dispatchTui` 纯函数可测 | `dispatchTui` 单测覆盖 status/steer/cancel/resume/help,路由同一 TaskService |
| MCP | `rdk-agent mcp --stdio --workspace-root <abs>` | stdio,恰 7 高层工具,无监听端口/采样/approval/terminal/flash/credential | 黑盒 handshake:`initialize` ok + `tools/list` 恰 7 工具(固定顺序)+ `rdk_task_status` 读到 CLI 创建的任务 |
| GUI | `electron .`(Electron 43.4.0) | Electron main + sandbox/context-isolated renderer;preload 桥只暴露 `task/device/window`;renderer 不持有服务 | `RDK_DESKTOP_SMOKE=1` 真实启动 + 窗口加载 + 主进程跑通真实 health 卡 → `DESKTOP_SMOKE_OK task=… state=created cursor=2` |
## 3. 跨入口一致与 owner 双写保护
- 四个入口通过同一个 `buildTaskService` 装配:一个 `RdkHostClient`(`rdk-agent-host serve --stdio`)+ 每任务独立 `SessionHandle` + 每任务 owner lock(`state/task-locks/<task-id>.json`)。
- **近程跨入口观察**:CLI 创建的 task 被 MCP `rdk_task_status`、新进程 CLI `task list` 读到(同一 `RDK_STATE_DIR` 的 Host 持久态)。
- **owner 双写拒绝**:`test/e2e.test.ts`(真实 Host 集成,`RDK_RUN_HOST_INTEGRATION=1`)验证 surface A 启动 → surface B 观察 → B steer 被 `RDK-OWNER-001` 拒绝 → A cancel → B `take-over` resume 产生 `task.owner_changed` → 第三个 DeviceService 读到 A 的任务产生的 device snapshot。实测 1 passed。
## 4. 收口修复(本轮,评审 → Accepted 的阻断项)
| 阻断项 | 修复 | 证据 |
|---|---|---|
| Electron 34 内置 Node 20.18.1 < 项目 floor ≥22.19,undici 崩溃 | Electron 精确升级 34.0.0 → **43.4.0**(Node 24.18.1,支持至 2027-01);启动版本保护拆成 bootstrap(`main.ts` 只做版本检查)+ 动态 `import("./mainImpl.js")`,Pi/undici 依赖图只在 guard 通过后解析 | 真实 electron 启动 12s 存活、无 `webidl.util.markAsUncloneable` 崩溃 |
| desktop 未指定 workspace-root 时默认用户主目录 | GUI `resolveWorkspace()`:`RDK_WORKSPACE_ROOT` 优先;缺失时用产品 `userData/workspaces/`(非 home);CLI/TUI 缺 workspace-root 改为明确 `RDK-INV-001` 输入错误(不再静默 fallback cwd) | 见 §2 CLI/TUI/GUI 三入口 |
| MCP `runMcpServer` 接通后 TaskService 被过早关闭 | `StdioServerTransport.start()` 只注册 stdin 监听即返回,`await connect()` 非阻塞;`runMcpServer` 在 connect 后阻塞到 `stdin end/close` 或 `SIGINT/SIGTERM` 才 resolve,`taskService.close()` 只在该时点后由 caller 执行 | `rdk_task_start`/`rdk_task_status` 黑盒同会话 `start=... → status.state=created`(修复前报 `RDK-EXEC-004: TaskService is closed`) |
| preload 在 sandbox 下需 CJS | build 用 esbuild 把 `src/preload.ts` 打包为 `dist/preload.cjs`(`--bundle --format=cjs --external:electron`);main 引用 `preload.cjs`;renderer `index.tsx` 同样 esbuild 打包 | desktop build 产出 `dist/preload.cjs` + `dist/renderer/index.js` |
## 5. 残留进程验证
- CLI、MCP(优雅关闭:stdin end 触发 `runMcpServer` resolve → `server.close` → `taskService/deviceService.close` → kill Host → Device 随 stdin EOF 退出)、Electron(`window-all-closed`/`app.exit`)三者关闭后,`pgrep` 无 `rdk-agent-host`/`rdk-agent-device`/`Electron.app` 残留。
- 单元态 owner lock 复用 `docs/12 §7` 的 `state/task-locks/<id>.json`(原子创建 + instance/pid/start + heartbeat + stale 核对),不在本层新造 lease 服务。
## 6. 门禁(复现命令 + 实测)
```bash
uv run pytest # 619 passed
uv run ruff check packages plugins tests # clean
uv run ruff format --check packages plugins tests # clean
uv run mypy packages/rdk_agent_{core,device,host,cli,sim}/src plugins/rdk_s100/src # 60 文件 0 issue
# TypeScript(Node v22.23.1)
cd packages/rdk-agent-surface && npm run build && npm test # 62 pass / 3 skip(e2e 门控)
cd packages/rdk-agent-pi && npm run build && npm test # 18 pass / 4 skip
cd packages/rdk-agent-desktop && npm run build && npm test # 5 pass
# 真实跨入口(RDK_RUN_HOST_INTEGRATION=1,指向仓库 .venv)
RDK_AGENT_COMMAND="<repo>/.venv/bin/rdk-agent-host serve --stdio" \
RDK_DEVICE_COMMAND="<repo>/.venv/bin/rdk-agent-device serve" \
node --test dist-test/test/e2e.test.js # 1 passed
```
## 7. 遗留项(不阻塞 Accepted,后续阶段处理)
| ID | 事实 | 处理期限 |
|---|---|---|
| `S1B-DEBT-001` | desktop 的 GUI 目录选择器未实现:当前用 `RDK_WORKSPACE_ROOT` 或产品 `userData/workspaces/` 默认,尚未落入「GUI 选目录」完整交互 | S1-C 前 |
| `S1B-DEBT-002` | GUI 五入口仅「工作台」接入任务,「项目/作品/设置」仍显示阶段说明;设备页未接入探索。**2026-08-20 设备页半项已关闭**:连接向导 + host-key TOFU 见 `evidence/S1C-DEVICE-CONNECT.md`;「项目/作品/设置」阶段说明保留 | S1-C / Alpha 打磨(余半项) |
| `S1B-DEBT-003` | `system.health` 只覆盖 Fake Device 只读链路;真实 S100P 只读连接与设备卡验收属 S1-C | S1-C |
## 8. 不声称
- 本证据只证明 S1-B 的四入口任务纵切片在 **Fake Device** 上成立,不构成 S100P 真机验收证据;真机结论只由 S1-C 产生。
- 不声称已替代 RDK Studio,不声称已通过 Windows/Linux 替换矩阵。
## 9. S1-B.1 加固(review 阻断项,2026-08-17 追加)
Codex 评审发现 2 个 P1 + 2 个 P2,已逐项修复并补自动化回归,不改写 `bba9f26`:
| 项 | 级别 | 修复 | 证据 |
|---|---|---|---|
| 本地导航范围过宽 | P1 | `security.ts` 移除 `ALLOWED_RENDERER_SCHEMES=["file:"]`(会放行任意本地 HTML 并获得 preload 任务能力),改为纯函数 `isAllowedRendererNavigation(target, rendererUrl)` 精确比较完整 URL;`mainImpl.ts` 的 `will-navigate` 只放行打包的 `renderer/index.html` 的 pathToFileURL,其余 `preventDefault` | `test/security.test.ts`:精确 URL 放行、`file:///tmp`/`file:///etc/passwd`/http/https 均拒绝 |
| smoke 未等待 renderer | P1 | `createWindow()` 改 async:`await win.loadFile(...)` 后 `executeJavaScript("typeof window.rdk !== 'undefined'")` 断言 preload 桥已暴露;`main()` `await createWindow()` 之后才 `runSmoke()`,`DESKTOP_SMOKE_OK` 现在证明 renderer/preload 已就绪 | `RDK_DESKTOP_SMOKE=1` 真实启动 → `DESKTOP_SMOKE_OK task=… state=created cursor=2`,无 Host 残留 |
| MCP 生命周期无黑盒回归 | P2 | 新增 `test/mcpLifecycle.test.ts`(真实 spawn `bin.js mcp --stdio`)回归 runMcpServer bug:handshake → `rdk_task_status` 读到「unknown task」而非「TaskService is closed」→ 关 stdin → exit 0;`runMcpServer` 处理 `process.stdin.readableEnded/destroyed` 竞态并移除未用 SIGINT/SIGTERM 监听 | `RDK_RUN_HOST_INTEGRATION=1` 下 1 passed;同会话 `rdk_task_start/status` 状态一致 |
| renderer/preload 脱离类型检查 | P2 | 新增 `tsconfig.typecheck.json`(`noEmit` + include `src/**/*.ts` 与 `src/**/*.tsx`,覆盖 esbuild 不查的 preload.ts/renderer tsx);`package.json` 增 `typecheck` 脚本并让 `build` 先跑它 | `npm run typecheck` 覆盖 preload/renderer,`npm run build` 前置 |
## 10. S1-B.1 门禁(追加)
```bash
# 真实集成(RDK_RUN_HOST_INTEGRATION=1)
node --test dist-test/test/e2e.test.js dist-test/test/mcpLifecycle.test.js # 2 passed
cd packages/rdk-agent-desktop && npm run typecheck && npm test # 7 passed
cd packages/rdk-agent-surface && npm run build && npm test # 62 pass / 4 skip
RDK_DESKTOP_SMOKE=1 electron . # DESKTOP_SMOKE_OK + 无残留

Binary file not shown.

View File

@ -0,0 +1,196 @@
# S1-C 设备连接切片证据:GUI 连接向导 + host-key TOFU(人控面)
日期:2026-08-20
验收结论:**Accepted(设备连接纵切片;真机部分 not_run)**
范围:关闭 `S1B-DEBT-002` 的设备页半项;交付 docs/12 §4「连接新设备、核验 host key」的 GUI 流程;AT-001 的 GUI 变体
环境:macOS arm64,Python 3.12(uv),Node v22.23.1,Electron 43.4.0;**无真实设备参与**(keyscan 桩 + 空注册表)
## 1. 结论摘要
把原本只锁在 `rdkctl` 进程内的「设备注册 + host-key TOFU」人控能力,按人机分权(docs/05 §7、docs/12 §4)以 **human 权威面** 形式落到 stdio 协议:`rdk-agent-host serve --stdio --role human` 派发 `AGENT_METHODS ∪ HUMAN_METHODS`;默认 agent 角色(Pi/MCP 所启动)方法集合保持恰为 `AGENT_METHODS`(AT-021 钉死集合未动,CAT-006B 负向保证成立)。surface `DeviceService` 以第二个 human-role client 暴露 `showHostKey/confirmHostKey/registerDevice/unregisterDevice`;Electron preload 桥在 `device` 命名空间内新增同名动作(顶层 keys 不变);GUI 设备页新增「连接开发板」三步向导(别名+SSH 主机 → 展示 SHA256 身份指纹 → 信任并连接),响应全链路净化,`public_key` 永不进入 renderer(docs/12 §6.2)。`device.list.host_key_confirmed` 改为对 known_hosts 的真实核验(只读不扫),未确认即 `false`。
对应验收:
- **AT-001**(首次注册与主机身份):GUI/CLI 同源 show→confirm→register 链路;未知 candidate 拒绝;不可达 → RDK-DEV-001。变化即阻断的底层不变量由 `known_hosts` 既有测试继续覆盖。
- **CAT-001**(首次接入):本切片交付其「仅提供连接信息并核验 host key」的 GUI 前半;学生可用性研究与真机设备卡仍属 S1-C(S1B-DEBT-003)。
- **CAT-006A**(多入口等价):GUI 与 rdkctl 走同一 `AgentApplicationService` 方法;rdkctl host-key 段改为调用同一服务方法(去掉 `service._config` 摸入)。
- **CAT-006B**:MCP/模型面工具列表与 `AGENT_METHODS` 均无 register/hostkey;human 方法与 agent 注册表不相交且有负例测试。
## 2. 交付与证据
| 层 | 交付 | 证据 |
|---|---|---|
| host 协议 | `--role` 启动参数;`HUMAN_METHODS`(hostkey.show/confirm、device.register/unregister);agent 角色拒绝 human 方法 → RDK-PROTO-001;`device.list` 诚实化 | `tests/unit/test_human_surface.py` 7 例 + `test_server_cli.py` 2 例 |
| host 服务 | `show_host_key_candidate` / `confirm_host_key` / `register_ssh_device` / `host_key_confirmed`;`known_hosts.load_candidate` 提取且 `confirm_and_store` 复用 | 同上(show→confirm→register→list 全链路,桩 keyscan) |
| surface | `DeviceService` human-role client + 四方法 + barrel 显式导出 | 门控集成 4 passed(真实 host stdio + keyscan 桩) |
| desktop | preload `device.showHostKey/confirmHostKey/registerDevice`;main IPC 三通道;设备页连接向导(form→confirm→done)+ 错误映射 RDK-DEV-001 | 安全单测 7 passed;浏览器预览桩桥走完向导全流程截图;真实窗口启动截图 |
| rdkctl | host-key show/confirm 改走服务方法(输出同步净化,无 public_key) | 既有 rdkctl 测试 + 本切片服务测试同源 |
## 3. 门禁与实测
| 门禁 | 结果 |
|---|---|
| `uv run pytest`(全量,含 schema 漂移门) | passed:652 passed |
| `uv run ruff check` / `ruff format --check` | passed |
| `uv run mypy`(strict,66 源文件) | passed |
| surface hermetic `npm test` | passed:62 passed / 6 skipped(门控) |
| surface 门控集成(`RDK_RUN_HOST_INTEGRATION=1` + keyscan 桩) | passed:4 passed(TOFU 全链路 + RDK-INV-001 负例) |
| desktop `npm run build && npm test` | passed:7 passed |
| 残留进程检查(退出后 `pgrep rdk-agent-host/device`) | passed:无残留 |
| GUI 手动(真实窗口 + 桩 keyscan 环境) | passed:窗口/设备页/向导渲染正常 |
| **真实 S100P:TOFU + 注册 + 只读盘点 + 设备卡** | **passed**(见 §6);板时钟漂移致 `fresh=false`,未对时(安全规则),漂移如实记录 |
复现(门控集成):
```bash
cd packages/rdk-agent-surface
RDK_RUN_HOST_INTEGRATION=1 \
RDK_AGENT_COMMAND="<repo>/.venv/bin/rdk-agent-host serve --stdio" \
RDK_DEVICE_COMMAND="<repo>/.venv/bin/rdk-agent-device serve" \
node --test dist-test/test/deviceService.test.js # 4 passed
```
## 4. 遗留项
| ID | 事实 | 处理期限 |
|---|---|---|
| `S1C-LEFT-001` | `rdkctl device register --device-id` 仍接受用户指定 id,与 docs/03 §2.1「系统生成 UUID」偏差(诊断契约保留) | S1-C 评审 |
| `S1C-LEFT-002` | 板 RTC 停走(captured_at 漂移、fresh=false);未对时(安全规则)。需要宿主侧漂移容忍策略或人工对时流程 | S1-C |
| `S1C-LEFT-003` | 板端 helper 曾为 probe_set 1.0.0;**2026-08-20 晚已重部署**(仅 rsync `rdk_s100`,用户「持续升级直到功能正常」授权),产品路径 REAL_SMOKE 验证 1.1.0/complete | 已关闭 |
| `S1B-DEBT-002`(余) | 「项目/作品/设置」仍为阶段说明(作品受 S3 约束) | Alpha 打磨 |
| `S1B-DEBT-003`(余) | 真机连接与设备卡本轮已通(§6);CAT-001 学生可用性研究与设备卡打磨仍属 S1-C | S1-C |
## 5. 不声称
- 只证明 keyscan 桩 + 空注册表下的协议/服务/桥/向导链路成立,**不构成真机验收**;
- 不声称 CAT-001 学生可用性研究完成;
- connected 字段仍为 S1-A 的保守 `false`(活连接器未接入),设备行以「主机密钥已核验/待核验」表达 TOFU 状态。
## 6. 真机验收(2026-08-20 补,S100P 直连)
环境:Mac en8=192.168.127.100/24 直连板 192.168.127.10;state dir `/tmp/rdk-s1c-gui-state`;**未对板时钟**(硬件安全规则:不改时钟),板 RTC 停走致 `captured_at=2026-08-06`、`fresh=false`,漂移如实展示。
| 步骤 | 结果 |
|---|---|
| hostkey.show(human 角色,真实 ssh-keyscan) | 板同时给出 rsa+ed25519;产品取 **ed25519 优先**(本轮加固),指纹 `SHA256:IDmdMLvf3cET0+X+qbsJpAIxo4XtibiULpnohvFp7/I` 与 S2 记录基线**一致** → 确认 |
| device.register | `dev-78b2f05db9dc41a9`,alias S100P-direct,`sunrise@192.168.127.10`;list 诚实 `host_key_confirmed=true`(`user@host` 身份剥离加固后) |
| inspect refresh=full(SSH → 板端 helper,`--device-id` 透传,S1A-DEBT-001 移植) | passed:identity=D-Robotics / RDK S / **RDK S100P V1P0**;arch=aarch64;capabilities `system.info`/`usb.enumerate`/`camera.snapshot.usb`=available;`drobotics.bpu.runtime@1` probe **failed (rc=2)**;completeness=**partial** |
| GUI 设备卡 | 以本次真机 snapshot 在预览渲染截图:型号/架构/能力徽章/探针失败红字/盘点时间齐备 |
真机暴露并修复的三个产品缺陷(均带回归测试):
1. `fetch_candidate` 取 keyscan 首行 → 双密钥板会拿 rsa;改为 ed25519→ecdsa→rsa 优先(`test_host_key_fetch_prefers_ed25519_over_rsa`);
2. `user@host` 注册与裸 host 的 TOFU 记录不匹配 → `ssh_host_identity()` 剥离登录用户做身份核验,连接器仍用全量目的地(`test_host_key_identity_ignores_login_user`);
3. 远程 helper 未收 `--device-id`,板端自报 fake-001 触发身份交叉检查失败 → 移植 main 的 S1A-DEBT-001 修复(`remote_command` 显式透传)。
基线模板增量(CURRENT_HARDWARE_BASELINE §4,观察值):`reported_model=D-Robotics RDK S100P V1P0`、`architecture=aarch64`、`host_key_sha256=SHA256:IDmd…p7/I`、`ssh_config_alias=sunrise@192.168.127.10`(网段类别:直连 /24)、`camera_expected` 现为 **true**(USB 摄像头已在板上观察到 video node;§5 晋级流程另议)、BPU runtime 探针 failed→能力状态以快照为准。
### 6.1 探针集对齐官方资料(probe_set 1.0.0 → 1.1.0,2026-08-20)
依据 `developer.d-robotics.cc/rdk_doc_center` 的 S 系列/OE/TROS 手册 + 真机只读复核,修正旧探针集「只观察不解析 / 摸错路径」缺陷:
| 探针 | 旧 | 新(真机实测) |
|---|---|---|
| rdkos_info@1 | 只填 architecture | `/etc/version`→rdk_os_version=4.0.5-Beta;`uname -sr`→os=Linux+kernel 全串;arch |
| resources@1 | 观察但不解析 | MemTotal→22.8GiB、df available→18.6GiB、nproc→6 |
| thermal@1 | 观察但不解析 | 5 个 thermal_zone 毫度→°C(53.0/52.3/48.2/47.7/50.8) |
| bpu.runtime@1 | `ls /usr/lib/libdnn*`(X 系列路径,S100P 必 rc=2) | `rdkos_info` 的 `[CPU And BPU Status]` 段,取首条含 bpu 的遥测行;空段 fail-closed |
| tros.distro@1 | 观察但不解析 | `/opt/tros`→humble 落入 software.tros_distro |
验证:`tests/unit/test_plugin_s100.py`(含分隔行/空段 fail-closed 回归)+ 真机经只读 SSH runner 注入复跑 → **completeness=complete、probe_errors=0**;随后仅重部署 `rdk_s100` 到板端 helper(见 `S1C-LEFT-003` 已关闭),产品路径(surface→host→SSH→helper)REAL_SMOKE 实测 1.1.0/complete。agent skill(`packages/pi-rdk-agent/skills/rdk-develop/SKILL.md`)新增官方资料板块:rdkos_info//etc/version//opt/tros/humble//opt/hobot/V4L2/非 root EACCES 认知,明确资料仅为写码 hint、观察事实只来自 inventory。
## 7. 产品页与真启动链路(2026-08-20 晚)
- **工作台**:composer 增加设备 chips(默认选中已核验板),`task.start` 携带 `device_ids`;任务不再脱板。
- **项目页**:真实只读工作空间浏览器(`workspace.list/read` 经新 `ProjectService` → preload `project` 命名空间);预览验证列表+文件查看渲染。
- **设置页**:本机只读事实(版本/平台/状态目录/项目空间/helper 档/网关「是否配置」);**凭据内容永不跨桥**(主进程只读存在性)。preload 顶层白名单显式扩为 5 个命名空间,security/packageEntry 两个 tripwire 测试同步更新。
- **真启动 smoke**:`RDK_DESKTOP_SMOKE=1` + `RDK_DESKTOP_REAL_SMOKE=1` → `DESKTOP_SMOKE_OK`(GUI 主进程→Host→fake 任务链)+ `DESKTOP_REAL_SMOKE_OK confirmed=true probe_set=1.1.0 completeness=complete`(GUI 主进程→human 面→SSH→板端 helper 全链),无残留进程。
- **a11y**:主进程加 `force-renderer-accessibility`(屏幕阅读器可见渲染树)。
遗留新增:
| `S1C-LEFT-005` | 真窗口自动化点击受 macOS 辅助功能授权限制未能执行;GUI 渲染层以预览+桩真数据验证、主进程层以 smoke 验证 | 需人工授权或手动点验 |
| `S1C-LEFT-006` | 真模型经 GUI composer 的端到端任务未在本轮执行(模型层闭环 S2 已证、GUI 各层分别已证);待人工在真窗口点「启动任务」 | 人工点验 |
## 8. 自动发现连接(device.discover,2026-08-20 夜)
用户反馈「不该让人自己输入 SSH 主机,agent 应自己获取信息帮助连接」。新增 human 面 `device.discover`:有界只读发现(Type-C USB RNDIS 默认 192.168.42.1 先探;`ifconfig` 解析私网接口,**无默认路由的直连接口子网优先**(板网线直连正是这类);仅 RFC1918 私网段、仅 TCP 22、不登录、不扫公网、不Offer 本机;候选上限 8)。GUI 向导打开即自动发现,人类只做两件事:选一个候选、核验指纹;手动输入降级为折叠兜底;选中后别名自动建议。
验证:
- `tests/unit/test_human_surface.py`:discover 桩链路(发现/排除本机/agent 角色拒绝 RDK-PROTO-001)+ `_own_subnet_ips` 解析(ifconfig 块、公网过滤、直连优先)。
- 真机实测:候选首位 `192.168.127.10`(板),其后才是办公网 SSH 主机(直连优先排序生效)。
- 预览验证:向导自动列出候选、选择→别名自动填「开发板 10」→下一步核验指纹全流。
- 门禁:657 passed、ruff/mypy 全绿;真启动 smoke 回归 `DESKTOP_SMOKE_OK` + `DESKTOP_REAL_SMOKE_OK confirmed=true probe_set=1.1.0 completeness=complete`。
## 9. 任务控制台真做(2026-08-21)
工作台控制台由原始 JSON dump 升级为真任务控制台:事件时间线(task.created/ran/steered/cancelled/failed/owner_changed 人话化)、结果徽章与证据计数、`required_action` 时诚实提示「需真人操作、Agent 不能代替」、干预/恢复/取消按钮(preload 既有 steer/cancel/resume 首次上 UI)、运行中 2.5s 轮询、原始数据折叠为「进阶」。预览以桩快照验证渲染与按钮布局。门禁 657 passed + desktop 7 passed。
## 10. main 整合与 GUI 主服务真模型 E2E(2026-08-21)
- **main 已整合**:`codex/sim-webots-2b2` 合并 main(S3–S6:Pack/真模型配置/连接存储)后快进 main 至 `13c9aa5`。整合后 GUI:作品=真 Pack 列表/重跑;设置=本机事实+模型网关编辑器(Key 遮罩、0600、不入库);项目=工作空间浏览+编辑器(host 服务路径);preload 白名单 8 命名空间,tripwire 同步。门禁 713 passed + ruff/mypy + desktop 7/0。
- **③ 真模型经 GUI 主服务 E2E**:脚本 `/tmp/rdk-gui-e2e.mjs`(buildTaskService→startTask→轮询)就绪;执行时 en8 直连接口掉线(无地址),恢复需 `sudo networksetup -setmanual AX88179B 192.168.127.100 255.255.255.0`(需密码,真人动作)→ 本轮状态 **blocked**,reason_code=environment。模型层闭环 S2 已证、服务/渲染层分别已证;待 en8 恢复后重跑即关闭 LEFT-006 的服务层部分。
## 11. 项目空间按设备隔离(2026-08-21,用户产品规则)
规则:一块板子一个项目空间,不同设备不共享。
- host `create_task`:带设备任务的共享「.」空间路由到该设备自有空间(空间 id=设备 id,构造上隔离);空间已绑定他设备 → `RDK-INV-001`(category=WORKSPACE_DEVICE)拒绝;多设备任务拒绝;无设备任务仍可共享。绑定存 `state_dir/workspace_bindings.json`(原子写)。`run_pack` 的瞬态执行空间同样登记绑定。
- surface `startTask` 同路由(`.`+单设备→设备空间;`.`+多设备→报错),host 为单一事实源兜底。
- GUI 项目页:设备 chips 切换各自空间(浏览+编辑传 workspaceId);切回页面刷新设备列表。
- 测试:`TestWorkspaceDeviceBinding` 4 例(路由/跨绑拒绝/多设备拒绝/无设备共享);门禁 721 passed + ruff/mypy + surface 65 + desktop 7;预览验证双设备空间互不相混。
## 12. 设备记录 + 局域网 SSH 受控登录(2026-08-21)
**设备记录**:`DeviceRegistration` 增加可选 `registered_at`/`last_seen_at`(schema major 1 内增量,schemas/ 已再生成);`device.list` 增补 `ssh_host/fingerprint/registered_at/last_seen_at`;quick/full 盘点成功即 `note_device_seen`。GUI 设备行展示记录行(主机·指纹前缀·登记·上次见到)+ 两步确认「移除」(device.unregister 首次上 UI)。
**局域网 SSH 受控登录**(docs/05 §5 控制登录流程首实现):
- `device.auth_check`(human 面):BatchMode 密钥活性探针,不提示不写日志;
- `device.onboard_key`:一次性密码经 SSH_ASKPASS 临时助手(0600/0700 临时文件,用后即删)交给 `ssh-copy-id` 安装产品公钥 `~/.rdk/id_ed25519`(`RDK_SSH_IDENTITY` 可覆盖);密码不进 argv/config/日志/事件;
- 连接器 argv 增加 `IdentityFile=<产品密钥>`(fallback 仍可用用户 ssh 配置/agent);
- 向导流:核验指纹后先 auth_check,通→直接登记;不通→「装钥匙并连接」一步(密码输入一次)。
- 测试 3 例:askpass 环境/密码不进 argv/临时文件清理;auth 失败 False;list 记录字段+seen 戳。门禁 723 passed + schemas 漂移门绿 + surface 65 + desktop 7。
## 13. 真模型×真板 E2E 闭环 + 停钟 freshness 修复(2026-08-21)
**LEFT-006 服务层关闭**:kimi-k3 经 GUI 主进程同款 `buildTaskService` 链,在真 S100P(s100-exec)上完成完整 rdk-develop 循环:inspect→write cpu_sampler.py→checkpoint→plan→run(`run-7e72c9970cc93615` succeeded)→verifier passed→artifact cpu.json 读回→task_report `completed/passed`。会话日志存于 `/tmp/rdk-s1c-gui-state/agent-dirs/task-4f10ac4178414730/sessions/`(succeeded×2/passed×3)。模型按 skill 自建内层 task 执行,属设计行为。
**真机暴露第四个产品缺陷(LEFT-002 深层,已修)**:板 RTC 停走 → `snapshot.captured_at` 恒旧 → policy `freshness.stale-denies` 死循环,agent 三次 re-inventory 仍被拒。修复:host 保存快照时以**宿主时钟** stamp `captured_at`(`_host_stamp`;内容哈希本就排除 captured_at,snapshot_id 不变;设备时钟不可信,与 S2 宿主计时预算同理)。回归测试 `test_stopped_device_clock_does_not_loop_snapshot_refreshes`。修复后 E2E 一次穿透。
门禁:721 passed + ruff/mypy 全绿。
## 14. 串口只读控制台 + 烧录向导 GUI(2026-08-21)
human 面新增 `serial.ports/serial.tail`(只读 tail、秘密打码、串口永非 Agent 执行通道)与 `flash.images/suggest/confirm/run/status/cancel`(suggest 返回计划+human-only confirm token;confirm 仅 USER actor;fake 引擎演练目录 `local://rehearsal`,真实写引擎待 XBurn/S6)。preload 白名单扩至 10 命名空间(console/flash),security tripwire 同步。
GUI:导航 7 项;控制台页(端口 chips、2s 自动刷新、redacted 日志、空态诚实);烧录三步向导(选镜像/设备 → 风险确认含演练横幅+恢复步骤+理解勾选 → 进度条+取消)。**烧录从未进入自动化测试**(安全规则),仅人工流程。预览验证两页渲染与向导流。门禁 721 passed + ruff/mypy 全绿 + desktop 7。
## 15. 审批收件箱 + 最近任务(2026-08-21)
人控面新增 `approval.decide`(agent 角色拒绝 RDK-PROTO-001;decide 仅 USER actor、已决不可二次、双决失败 INPUT_INVALID)。surface TaskService 增加 human client(同 DeviceService 模式),`listApprovals`(读面 agent 可见)/`decideApproval`。GUI 工作台:待批准卡(设备·能力·拒绝/批准,decide 后刷新)+ 最近任务 chips(点击即载入状态)。预览验证渲染。门禁 722 passed + 全绿。
## 16. 确定性一键模板(不经过模型;CFR-003/014)
人控面新增 `template.list/template.run`:内置审阅程序(健康卡/温度表/gpio-需工装),走正常 plan→policy→run→verify,**无 LLM**;`template.list` 按设备观察能力硬过滤(缺什么说明什么,CFR-014)。验证器对 `result.json.exit_code==0`(fake 与真机都产出),自定义产物作为可见交付物收集。测试 4 例:能力过滤、fake 上跑通(succeeded/passed)、未知模板 INPUT_INVALID、agent 角色 PROTOCOL_VIOLATION。GUI 工作台「Quick · 一键操作」卡渲染(不能跑显示缺什么)。门禁 734 passed + ruff/mypy 全绿。
## 17. 受控 MCP client(connect OUT,显式白名单)
新增 `mcpClient.ts`:只连人类写进白名单(`RDK_MCP_CONFIG`/`~/.rdk/mcp.json`)的外部 MCP server;外部工具结果是**不可信文本**,只给人(CLI/TUI),永不提升为设备事实/能力/策略输入;**不**暴露给 Pi agent 或外部 MCP 调用者(守 CSEC-011/012)。CLI:`rdk-agent mcp-client list|call --server <name>`。实测:以自身 `rdk-agent mcp --stdio` 为白名单外部 server,`list` 返回 7 工具、`call rdk_device_list` 正常。单测:非白名单 server 被拒。surface 66 测试全绿。
## 18. 对话界面主动调用 skill(`/skill`,仿 `/` 习惯)
TUI 新增 `/skills`(列出可信本地 skill)与 `/skill <名字> [请求]`(主动调用):读取 `pi-rdk-agent/skills/<名字>/SKILL.md`,把 skill 正文以「主动调用 skill」形式 steer 进当前任务,模型按其步骤执行。skill 仍只读可信(人类从本地可信集选择,模型无写权限)。单测:parseTuiInput 路由、listSkills/readSkill。surface 62 测试全绿。
## 19. GUI skill 入口 + 示例 skill + 能力矩阵 + 模型中心
- **GUI /skill**:工作台 composer 增加 skill 下拉,选中后把该 skill 正文注入目标,模型按步骤执行;preload 增 `skill` 命名空间(list/read,只读可信)。
- **示例 skill**:`pi-rdk-agent/skills/rdk-temp-watch/SKILL.md`,演示安装(放 skills/ 即被 listSkills 发现)+ 调用。
- **能力矩阵**(CFR-058):设备卡能力区明确为「能力矩阵(不可用的操作前明示,不猜测)」,available/unavailable/unknown 徽章 + probe_errors 作为「为什么」。
- **模型中心**(CFR-056):设置页模型卡可编辑 baseUrl/model/api + 保存(写 ~/.rdk/.env 0600)+ 连通性测试(`config:test` 调 `<baseUrl>/models`,返回 ok/状态/延迟)。秘密不进项目/对话。
- 门禁:desktop 7 测试全绿;surface 导出 listSkills/readSkill。
## 20. RDK 领域认知(比通用 coding agent 更懂 RDK)
新增 `pi-rdk-agent/skills/rdk-knowledge/SKILL.md`(grounded 自官方文档中心),并**追加进 system prompt**(模型每轮必读):
- 板型算力/接口:S100/S100P 80/128 TOPS 6核 A78AE(2 MIPI+4 USB3);S600 560 TOPS 18核(6 MIPI+6 USB3+PCIe3)。
- 软件栈:`/etc/version`、`rdkos_info`(≥2.1.0)、TROS(`/opt/tros/<distro>`、humble)、Python/C++ 算法接口、BPU(`/opt/hobot`+rdkos_info 段)。
- 配件认知:USB 摄像头→camera.snapshot.usb;MIPI/GMSL、双目、BMI088 IMU、舵机/PWM 的兼容与「无工装硬拒绝」规则;温度 thermal zones。
- 用法:回答「能做什么/还缺什么」用事实+能力矩阵不猜测;推荐项目先硬过滤(CFR-014)。
pi 24 测试全绿;rdk-knowledge 被 listSkills 发现且注入 prompt。

394
docs/testing/evidence/S2.md Normal file
View File

@ -0,0 +1,394 @@
# S2 切片 1 验收证据:Starter 1 系统健康卡真机闭环
日期:2026-08-17
范围:`docs/06 §6` S2 首切片(task 21 源码同步 / 22a 执行型 Helper profile / 22b 真机健康卡)
分支:`codex/s2-agent-loop`(worktree `/tmp/rdk-s2`,与 Webots 工作区隔离)
环境:macOS arm64 直连(`en8` `192.168.127.100/24`)→ RDK S100P `192.168.127.10`
## 1. 结论摘要
S2 首个「Agent 开发闭环」在**真实 S100P** 上全链路跑通,全程走生产路径
(`AgentApplicationService` + `SshDeviceConnector` + 板端 `s100-exec` Helper +
`UserProcessBackend`,无 mock):
```
inspect(真实盘点)→ code(受控 workspace 写健康脚本)
→ plan(policy allow, R0)→ run.stage(源码摘要绑定同步)
→ 真机非 root 执行 → artifact 采集 → verifier 聚合
→ outcome=passed
```
S2 §6.2 出口行为同步真机验证:幂等重放不重复执行、源码变化使旧 Plan 失效、
timeout 进程组清理、cancel 取消清理,全部 cleanup=confirmed。
**状态:切片 1 真机闭环 PASSED。** S2 里程碑其余交付物(checkpoint/预算恢复、
watch UI、断线对账的产品化等)不在本切片范围。
## 2. 连接与前置
| 项 | 值 |
|---|---|
| 连接 | 网线直连,`ssh sunrise@192.168.127.10`(key 认证,BatchMode) |
| SSH 主机指纹 | `SHA256:IDmdMLvf3cET0+X+qbsJpAIxo4XtibiULpnohvFp7/I`(ED25519,与 S1-C 证据一致,本次重新 keyscan 比对通过) |
| Helper | `~/.rdk/bin/rdk-agent-device`,本次从本分支重装(`install-device-helper.sh install`,lib 目录先清后装) |
| Helper profile | **`s100-exec`(新)**:真实 s100 盘点引擎 + UserProcessBackend;票据 HMAC key 从 `~/.rdk/ticket_key`(0600)读取,缺失/权限过宽拒绝启动,永不用 fake key,密钥不入 argv |
| 票据密钥下发 | `install-device-helper.sh keygen` 板端生成 32 字节 hex(0600),操作者拷到宿主 `RDK_TICKET_KEY`;密钥值不进仓库、不进证据 |
## 3. 真机运行记录(`scripts/drive_s2_health_card.py`)
驱动脚本全程使用生产类:Host 侧 `AgentApplicationService` + 文件 stores +
`SshDeviceConnector(helper_profile="s100-exec")`。逐步输出与 run 记录存于
`docs/testing/evidence/s2-health-card/drive-result.json`,健康卡原文存
`s2-health-card/health.json`。
| 步骤 | 结果 |
|---|---|
| inspect | 真实快照 `sha256:0c2219ca…`:model `D-Robotics RDK S100P V1P0`,partial(bpu 探针如实失败,无假阳性),`system.info / usb.enumerate / camera.snapshot.usb = available` |
| code | workspace `ws-health` 写入 `health_card.py`,source_digest `sha256:e2e0d5c7…` |
| plan | plan `sha256:6451c026…`,policy **allow**(`risk.read_observe-allow`) |
| run | `run-65f1102197cbf80f`:**succeeded / outcome passed / exit 0 / cleanup confirmed** |
| artifacts | `health.json`(声明 artifact,从程序 cwd 采集)、`result.json`、`stdout.log`;`health.json` digest `sha256:37807b03…` |
| 幂等重放 | 同 request_id 再 start → **同一 run_id**,无第二次执行 |
| Plan 失效 | 改 workspace 一字节 → start 拒绝:`RDK-SEC-001 source content changed since plan` |
| timeout | `run-6305fcff1dc6329d`:300s sleeper 配 5s wall → **failed + cleanup confirmed**(TERM→KILL 进程组) |
| cancel | `run-792b7f1316a8e542`:RUNNING 中取消 → **cancelled + cleanup confirmed** |
健康卡真实数据(板端直采):内存 21783 MB(可用 90.5%)、磁盘 44.5 GB(55.9%)、
5 个温区 46.9–51.5 °C、load 4.28/3.99/4.02、uptime 32439 s;三项 verdict 全 true →
`ok=true`,与 verifier `json.assert(ok==true)` 一致。
板端终态核验(SSH 直查):无残留 sleeper / Helper 进程;`~/.rdk/runs/` 三个 run
目录结构完整(`source/`、`stage.json`、`record.json`、`events.jsonl`、`artifacts/`),
健康 run 的 `source/health_card.py` 为宿主暂存原件,`source/health.json` 为程序输出,
`artifacts/health.json` 为声明采集件。
## 4. 本切片交付(协议与实现)
- **`run.stage`(protocol 1.1,docs/03 §4.4)**:prepare→start 之间同步 plan 绑定的工作区源码到设备 run `source/` 子树;逐文件 SHA-256 校验 + 聚合摘要必须等于票据绑定 source_digest,否则拒绝;仅 QUEUED 可 staging;同绑定重放幂等;上限 256 文件 / 256 KiB 单文件 / 768 KiB 总量(控制帧 ≤1 MiB 内)。
- **UserProcessBackend 接上真实源码**:run root = `source/`;start 前按 `stage.json` 重校验全部暂存文件(stage→start 间篡改 fail-closed);COLLECTING 时从程序 cwd 采集 manifest 声明的文件 artifact;必需 artifact 缺失只留 warning 事件,由宿主 verifier fail-closed,绝不假报成功。
- **`s100-exec` Helper profile**:见 §2。
- **宿主接线**:`SshDeviceConnector.helper_profile`(默认仍 `s100-readonly`)、`HostConfig.remote_helper_profile`(`RDK_REMOTE_HELPER_PROFILE`);`WorkspaceService.iter_source_files`(密钥类文件名拒绝整批 staging)。
## 5. 真机暴露的缺陷与修复(含第一轮失败记录,如实保留)
| 轮次 | 事实 | 处置 |
|---|---|---|
| 第 1 轮 | 驱动脚本以裸 IP 连接,ssh 用 Mac 用户名 `d-robotics` 登录被拒(`Permission denied (publickey,password)`) | 脚本默认改 `sunrise@192.168.127.10`;连接器 stderr 被 DEVNULL 吞掉加大了定位成本,调试时改为继承 stderr 定位 |
| 第 2 轮 | start 拒绝:`staged path escapes the run source root: 'health_card.py'`。根因:设备默认 runs root 是**相对路径**(`.rdk/runs`),`RunRegistry` 未归一化,backend 的 resolve 后路径与未 resolve 的 root 比较必然「逃逸」。本地集成测试用绝对 tmp_path 所以不暴露 | `RunRegistry.__init__` 归一化为绝对路径(commit `4ba161b`);补相对 root 全链路回归测试 |
| 第 2 轮的恢复 | 第 2 轮失败时 run 停在 QUEUED(backend 在状态迁移前 fail-closed,符合设计);修复重装 Helper 后**同一 request_id 的第 3 轮自动接续**:prepare 命中设备幂等索引复用原 run → 重 stage → start 成功 | 作为断线/崩溃恢复的活证据记录(run-65f1102197cbf80f 即第 2 轮创建的那个 run) |
另:`install-device-helper.sh install` 对已有 lib 不再静默跳过(pip `--target`
不覆盖),现先清 `~/.rdk/lib` 再装,避免旧代码残留。
## 6. 边界与未做
- 全程非 root(`sunrise` 普通用户);无 sudo/apt/systemd/网络配置/刷写/分区/电压/thermal/驱动变更;GPIO/舵机无工装保持禁用。
- 健康脚本只读 `/proc`、`/sys/class/thermal`、`shutil.disk_usage`,stdlib only。
- 板端 `/tmp/rdk-helper-s2/` 为安装临时件(重启即清);`~/.rdk/`(Helper + ticket_key + runs)为产品安装物。
- 本切片未覆盖:AgentTask checkpoint/预算的真机恢复、run watch 的产品面、多入口(GUI/TUI/MCP)对同一 run 的观察 —— 属 S2 后续切片。
- 协议 minor bump 1.1:1.0 对端无 `run.stage`,宿主按协商版本门控,老 Helper 明确报错而非协议崩溃。
## 7. 门禁(S2 worktree 自包含)
```bash
pytest -q # 657 passed(含 21 项 run.stage 协议/相对 root 回归 + 4 项 s100-exec 真实子进程集成)
pytest --cov=rdk_agent_core --cov-branch --cov-fail-under=90 # 95.57%
ruff check packages plugins tests # clean
ruff format --check packages plugins tests # clean
mypy packages/rdk_agent_{core,host,device,cli,sim}/src plugins/rdk_s100/src # 61 文件 0 issue
scripts/install-device-helper.sh build # 3 wheel + deps/(aarch64 pydantic 闭包)
# 真机:s100-exec Helper 重装 + keygen + 本证据 §3 全链路
```
---
# S2 切片 2 验收证据:断线对账产品化 + 生产 Agent loop 真机切片
日期:2026-08-18
范围:`task.reconcile` 产品方法 + `task_reconcile` 工具 + rdk-develop skill 重连指引;
`packages/rdk-agent-pi/test/sliceS2.test.ts` —— **生产装配**(`createRdkSession` 全链,
与 CLI/TUI 同一工厂)经脚本化模型驱动 Starter 1 健康卡打真板
分支:`codex/s2-agent-loop`(worktree `/tmp/rdk-s2`)
## 1. 结论摘要
切片 2 在**真实 S100P** 上两种场景均 PASSED(各 19 pass / 0 fail / 4 skip,
skip 均为 `slice.test.ts` 自身门控,与本切片无关):
- **场景 A(温设备 / 收养路径)**:宿主全新 state dir、设备仍持有该确定性
run_id 的终态记录(前轮真实执行)→ 宿主不失败、不重复执行,**收养设备真相**,
重新跑 verifier、绑定新 task、报告 completed。
- **场景 B(冷设备 / 全新执行)**:设备 Helper 指向全新 `--runs-root`
(`~/.rdk/runs-s2-slice2-122821`)→ prompt → inventory → inspect →
workspace write+checkpoint → task_create → plan → run.start(task 绑定)
→ status → artifact 读 → checkpoint → task_report,全链真执行,
run `run-d7af664a4e31d30d` **succeeded / passed**,task completed。
## 2. 环境前置修复(如实记录)
| 问题 | 事实 | 处置 |
|---|---|---|
| Mac en8 掉地址 | 直连网卡服务被重置为 DHCP,无服务器回退 169.254.169.129,192.168.127.0/24 路由走丢 | `networksetup -setmanual AX88179B 192.168.127.100 255.255.255.0`(管理员授权弹窗批准),ping/ssh 恢复 |
| 板时钟停 12 天 | RTC 1970、直连无 NTP,板时钟停在 08-06;`captured_at` 用设备时钟,所有快照对宿主必然「过期」(SEC-010 新鲜度窗 1h),`inspect.fresh=false` | `sudo date -u -s` 同步宿主 UTC(板端 passwordless sudo;唯一的设备状态变更,新鲜度/票据过期语义依赖 sane 设备时钟) |
known_hosts 仍为 `/tmp/rdk-s2-state/known_hosts`,指纹比对
`SHA256:IDmdMLvf3cET0+X+qbsJpAIxo4XtibiULpnohvFp7/I` 通过;票据密钥经
`RDK_TICKET_KEY` 环境变量传入(值不落盘、不进证据)。
## 3. 真机暴露的缺陷与修复(本切片核心产出)
**D1 — task 生命周期无人推进,`task_report` 必然崩溃(P1)。**
产品路径(task_create → plan → task 绑定 run.start → report)没有任何环节推进
`created → planning → coding → executing → verifying`;`report_task` 在 verifier
全 pass 时直接 `complete()`,撞状态机 `created -> completed` 的 ValueError,以
`RDK-EXEC-004` 内部错误形式上抛。既有单测/验收全部手工 `transition()` 掩盖了该缺口。
修复(host `application.py`):新增 `_advance_task`(沿 `TASK_TRANSITIONS` BFS 最短
合法路径迁移,终态不动),并在真实产品事件挂锚点——`_link_run_to_task` 推进到
EXECUTING(task 绑定 run 启动时 plan/code 已事实发生)、`run_status`/`reconcile_task`
观察到终态推进到 VERIFYING、`report_task` 完成前兜底对齐;FAILED/CANCELLED task 的
report 如实返回 state+outcome 不再崩溃。
测试:`test_report_derives_completed_from_verifiers` 删手工迁移改钉产品路径 +
新增 `test_report_on_terminal_task_reports_truthfully`。
**D2 — 宿主状态丢失重放被误标 failed(P1,AT-023 场景)。**
run_id 由 `actor+request_id` 确定性派生。宿主 state 全丢后同 request_id 重放:
设备注册表仍持有该 run(同 plan、已 succeeded),prepare 幂等通过但 stage 被
`INPUT_INVALID cannot stage from 'succeeded'` 拒绝,宿主把一次实际成功的 run 标成
failed/inconclusive。修复:`_execute_start` 异常路径新增
`_adopt_terminal_device_record`——查 `run.status` 设备真相,**同 plan 且终态**才收养
(合并 state/process/artifacts/cleanup,重跑 verifier,绑定 task);plan 不符或设备
不可达保持原失败路径。
测试:`test_host_state_loss_adopts_terminal_device_run`(双 host 服务共享设备
runs_root,断言同 run_id、passed、设备仅执行一次、run 绑定到新 task)。
**契约面同步**:AT-021 方法注册表期望集 + TS `RDK_TOOL_ALLOWLIST` 期望表各补
`task.reconcile` / `task_reconcile`(两处在切片 diff 前均未更新,首轮 pytest/npm
各红 1 项)。
## 4. 真机运行记录
| 项 | 场景 A(收养) | 场景 B(全新执行) |
|---|---|---|
| 宿主 state | `/tmp/rdk-s2-slice2-state-YQiOw7`(全新) | `/tmp/rdk-s2-slice2-state-9c5gRR`(全新) |
| 设备 runs root | 默认 `~/.rdk/runs`(温) | `~/.rdk/runs-s2-slice2-122821`(冷) |
| npm 结果 | **19 pass / 0 fail** | **19 pass / 0 fail** |
| run | `run-d7af664a4e31d30d`(前轮真执行,本轮收养+验证) | 同 id(确定性),本轮真执行 succeeded/passed |
| task_report | outcome passed / state completed / unresolved [] | 同左 |
| 日志 | `evidence/s2-agent-loop/slice2-warm-device-npm.log` | `evidence/s2-agent-loop/slice2-fresh-device-npm.log` |
场景 B 健康卡真数据(`evidence/s2-agent-loop/health.json`,板端直采):
内存 21783 MB(可用 91.2%)、磁盘 44.5 GB(56.0%)、5 温区 47.7–52.3 °C、
load 5.30/4.43/4.24、uptime 6616 s;verdict 全 true → verifier
`exit_code.zero` + `json.assert(ok==true)` 聚合 passed。
## 5. 门禁(S2 worktree)
```bash
uv run pytest -q # 659 passed(+2 缺陷回归用例)
npm ci && npm test # 18 pass / 4 skip(既有门控)
RDK_S2_REAL_DEVICE=1 … npm test # 19 pass / 0 fail / 4 skip(场景 A、B 各一遍)
uv run ruff check packages tests # clean
uv run ruff format --check packages tests # clean(106 文件)
uv run mypy packages/rdk_agent_{core,host,device}/src # 43 文件 0 issue
```
## 6. 边界与未做
- 全程非 root;唯一的设备状态变更是时钟同步(§2);无刷写/分区/电压/thermal 变更;GPIO/舵机保持禁用。
- 设备侧 `~/.rdk/runs/` 内切片 1/2 的 run 目录保留为不可变真相,未清理。
- `task_reconcile` 工具已入 allowlist 与 skill 重连指引,但**真机断线对账的端到端演练**(断 ssh → 恢复 → reconcile 观察)未在本切片真机验证;S2 剩余:checkpoint/预算恢复产品化、run watch 四入口观察。
---
# S2 切片 3 验收证据:断线对账产品化 + 预算/恢复/可观察收口
日期:2026-08-18
范围:docs/06 §6.1 剩余交付(AgentTask checkpoint/预算/恢复产品化、start/watch/cancel
四入口可观察)+ §6.2 真机断线对账端到端演练
分支:`codex/s2-agent-loop`(worktree `/tmp/rdk-s2`)
## 1. 结论摘要
S2 剩余交付收口,真机演练 PASSED。三个真机暴露的 P1 缺口已修并补回归测试:
1. **预算此前从不消耗**——`consume_task_budget` 无任何产品路径调用,预算门控形同虚设。
修复(host `application.py`):`start_run` 在设备副作用前做预算门控(耗尽任务直接
POLICY_DENIED,幂等重放优先返回存储记录);`_account_terminal_run` 在终态观察时按
**宿主计时**(规避板时钟漂移)消耗 device/wall time,耗尽则 task FAILED;`_link_run_to_task`
兜底 attempt 竞态;`report_task` 预算耗尽优先于 verifier 聚合。`Budgets._consume` 超限时
钳位到上限再抛(使 `exhausted()` 为真)。测试 +3。
2. **晚于等待窗口完成的 run 永不验证**——`_verify` 只在 start 路径终态调用;run_status
轮询到 SUCCEEDED 不触发验证 → outcome=NOT_VERIFIED。修复:`run_status` 观察到 SUCCEEDED
且未验证时调用 `_verify`;记账只在本次观察的终态迁移触发(避免重复记账)。测试 +1。
3. **resume 仅发 ack、不收账**——`resumeTask` 只建会话,不 reconcile 也不注入恢复上下文。
修复(surface `taskService.ts`):resume 先 `task.reconcile`(刷新非终态 run)+
`task.checkpoint`(冻结恢复点)+ 注入恢复上下文(goal/state/runs/unsatisfied verifiers);
`buildResumeTurns` 携带上下文。CLI 新增 `task artifact` 子命令(读声明产物/成功依据)。
测试 +3。
真机断线对账演练(`scripts/drive_s2_reconcile.py`)完整跑通(见 §3)。
## 2. 断线对账的真机事实
设备侧 `RunRegistry.get` 已有 fail-closed:从盘加载到非终态 run(STAGING/RUNNING/
COLLECTING/VERIFYING/CANCELLING)时直接判 `FAILED/INCONCLUSIVE/cleanup=unconfirmed`
("worker lost with process restart; failed closed")。`UserProcessBackend` 以
`start_new_session` 派生 run 进程(与 helper 解耦),helper 因 ssh 断开退出时,**守护线程
随之死亡、无法再迁移记录**——但断线重连后新 helper 的 `run.status` 会触发 fail-closed,
把孤儿 run 真相上报为失败。这是 truthful 对账:断线中断的 run 永不谎报成功(artifacts
未被收集,验证器无法运行)。
## 3. 真机演练记录(`docs/testing/evidence/s2-reconcile/drive-result.json`)
| 步骤 | 结果 |
|---|---|
| service1 start | run-1 `running`(20s sleeper,2s 等待窗口后仍 RUNNING) |
| 断线 | service1.close()——SSH 传输断开,helper 退出,run 进程(新 session)继续 |
| service2 reconcile | task=`verifying`,run_ids 仍含 run-1(未丢失绑定) |
| 孤儿 run 真相 | run-1 `failed` / `not_verified` / `cleanup=unconfirmed`(fail-closed) |
| 断线后 report | task=`verifying` outcome=`not_verified` unresolved=`[exit-ok, health-ok]`(验证器未运行,不谎报) |
| 恢复 run | 新 request_id 的 run-2 `succeeded` / `passed`(run_status 触发 `_verify`) |
| 恢复后 report | task=`completed` outcome=`passed` unresolved=`[]` |
结论:reconcile 只读设备真相、从不 re-prepare/re-start;孤儿 run 被 fail-closed;
agent 以新 run 恢复,task 最终 completed/passed。AT-023 断线对账真机闭环。
## 4. 门禁(S2 worktree)
```bash
uv run pytest -q # 663 passed(+4 切片3 回归用例)
npm ci && npm test # pi 18/5skip · surface 65/4skip · desktop 7/0
uv run ruff check packages tests # clean
uv run ruff format --check packages tests # clean(106 文件)
uv run mypy packages/rdk_agent_{core,host,device}/src # 43 文件 0 issue
# 真机:scripts/drive_s2_reconcile.py 全链 PASS(断线→reconcile→恢复)
```
## 5. S2 出口对照(docs/06 §6.2)
| 出口 | 证据 |
|---|---|
| 全新 Session 仅凭自然语言完成 inspect→…→result | 切片 2 `sliceS2.test.ts` 真机 19/0;切片 3 run_status 验证修复保证晚完成 run 仍验证 |
| 用户能看到代码/运行位置/输出/成功依据 | workspace_diff 工具;status 含 device_ids+evidence_refs;CLI `task artifact` + MCP `rdk_artifact_read` 读产物;outcome 即成功依据 |
| 源码/快照变化使旧 Plan 失效;相同 start 重试不重复 | 切片 1 真机证据 + 切片 2 切片测试 |
| timeout/cancel 清理全部子进程;verifier 无法确认时不假报 | 切片 1 真机证据(TERM→KILL 进程组 cleanup confirmed);切片 3 断线 run fail-closed 不假报 |
| Agent 与 MCP caller 无法调用人工终端/远程文件/串口写/网络/烧录/approval decision | AT-021/024 allowlist + forbidden 测试;MCP 7 工具无执行/审批/终端入口 |
## 6. 边界与未做
- 真模型(真实 LLM)驱动的 Agent 闭环未在真机验证(M0 已决策:真模型真机 compaction 在 M1 补 AT-023 全量);本里程碑用脚本化模型经**生产 `createRdkSession` 装配**证明机制。
- 5 名学生可用性测试属 S1 形式出口,需组织真人,不在本会话范围。
- GUI 可分发构建(不预装 Node/Python)+ 五入口打磨属 S1/S4 产品化,未做。
---
# S2 切片 3 验收证据:真模型真机闭环(kimi-k3 / openai-responses 网关)
日期:2026-08-19
范围:把生产 Agent loop 从脚本化模型换成真实 LLM,在真 S100P 上完成 health card 闭环。
分支:`codex/s2-agent-loop`(worktree `/tmp/rdk-s2`),已合 main(`bc6b8ed`)。
## 1. 结论摘要
**真模型真机闭环 PASSED(run 维度)。** kimi-k3 经用户的 OpenAI-Responses 网关
(`ai-api.d-robotics.cc/v1`)驱动生产 `rdk-agent run` CLI,在真 S100P 上完成:
```
rdk_device_inventory → workspace_write → workspace_checkpoint
→ rdk_run_plan(manifest schema 通过)→ rdk_run_start
→ run succeeded / outcome=passed / exit=0 / cleanup=confirmed
→ rdk_artifact_read → task_report
```
run `run-645b7e0d3da88763`:state=succeeded,outcome=passed(`exit_code.zero` +
`json.assert(health.ok==true)` 双验证器均过),cleanup=confirmed。设备端
health.json 为真实板卡数据(verifier 据此判定 passed)。
**遗留(非 run 缺陷)**:模型把 `task_create` 放在 `rdk_run_start` 之后、且
run_start 未传 taskId,故 run 未绑定到 task,task_report 无法聚合、task 停在
created。这是模型工作流排序问题,run 本身已在真机过验证器。
## 2. 真模型配置
单一扁平 `~/.rdk/.env`(0600,gitignore)四变量:`RDK_ANTHROPIC_BASE_URL` /
`_API_KEY` / `_MODEL=kimi-k3` / `RDK_MODEL_API=openai-responses`。
`createRealModel` 写入 per-task `agentDir/models.json`(0600),`createAgentSession`
据此解析 provider,SDK `openai-responses` 流打网关。key 值不落仓库/证据。
## 3. 三个根因与修复(驱动 Qwen→kimi 真机暴露)
| 根因 | 事实 | 修复 |
|---|---|---|
| skill 未达模型 | `noSkills:true` 抑制发现、allowlist 无 skill-read 工具,SKILL.md 从未进上下文 → 两模型都瞎编 manifest `{steps,capabilities,...}` | 把 rdk-develop `SKILL.md` body 注入 `appendSystemPrompt`(与 task-summary 同通道),并加具体 Run manifest 形状示例 |
| inventory reason 契约不一致 | TS 工具 schema `reason:Type.String()`(自由串),Host Pydantic `InventoryReason` 枚举严格 → 自由文本被拒,inventory 全挂,无快照 | `DeviceInventoryParams` 加 `field_validator(mode=before)`:未知 reason 落 `USER_REQUEST`、未知 targets 丢弃(与 TS 契约一致) |
| task-summary 旧基线误导 | 文案"M0 只有 fake-001,S100P 不存在" → kimi 读到后拒绝对 s100p-001 继续,向用户求确认 | 更新:s100p-001 是已验证真机目标;`rdk_device_list` 在全新 state dir 为空不代表不可用;直接 inventory 用户点名的设备 |
## 4. 门禁
```bash
uv run pytest -q # 664 passed
cd packages/rdk-agent-pi && npm test # 24 pass / 5 skip
cd packages/rdk-agent-surface && npm test # 65 pass / 0 fail / 4 skip
uv run ruff check/format packages tests # clean
uv run mypy core/host/device src # 43 文件 0 issue
# 真机:rdk-agent run(kimi-k3)→ run succeeded/passed on S100P
```
## 5. 未做
- 真模型真机 compaction 触发(需上下文增长到溢出)未单独验证;本轮 run 未触发 compaction。
- task-linking 工作流排序:模型未按 skill 的 task_create→plan→run_start(task-bound) 顺序。可在 skill 里更强约束顺序,或 Host 在 run_start 无 task 时按 workspace 关联最近 task(待定)。
- 多模型回归:仅 kimi-k3 验证;Qwen3.8-max 在 inventory 修复后未重测。
---
# S2 切片 4:user-journey 多能力压测(kimi-k3 真机)
日期:2026-08-19。目标:验证 agent 不塌缩到单一能力、能按用户自然语言产出**多种**嵌入式能力。4 个学生式任务串行跑(每个全新 state、fresh request_id),全部 succeeded/passed、一次收敛(runs=1)、4 个不同程序:
| 任务 | 程序 | 产物 | 真数据 |
|---|---|---|---|
| USB 枚举 | usb_list.py | usb.json | 5 设备:SYD USB Camera(0bda:d576)、2×xHCI Host Controller |
| 温度最高区 | thermal.py | thermal.json | /sys/class/thermal 全温区 + hottest_zone |
| 网络接口 | net_list.py | net.json | eth0/docker0/br-* 真实 MAC + operstate |
| 占内存 Top5 | top_mem.py | top_mem.json | gnome-shell 255MB、dockerd 86MB(板跑 GNOME+Docker) |
驱动:`/tmp/rdk-s2-journey.sh`,日志 `/tmp/rdk-s2-journey.log`。
结论:harness 修复(goal-driven prompt + json.assert 键存在 + skill 注入 + 诊断指引)后,agent 能按自然语言产出**多种**嵌入式能力,每种写对代码、真机跑通、验证器过。`completed_tasks` 偶尔为 0(模型未把 run 绑 task 时的 bookkeeping 残留),但 run 本身全 passed——task-linking 工作流排序仍是唯一残留。
---
# S3 切片 1:Project Pack — 能力保留 + 无 LLM 重跑(真机)
日期:2026-08-19。回答"产出的能力怎么保留"——之前没机制,本切片做最小闭环。
## 交付
- `packs.py`:`Pack` = 冻结的 (manifest + source files) 命名包;`PackStore`(InMemory + File),存 `<state>/packs/<name>/pack.json` + `source/`。
- Host 三方法:`save_pack(name, workspace_id, plan_id)`(冻结 workspace source + plan manifest)、`list_packs`、`run_pack(name, device_id, request_id)`(**无 LLM**:从 pack 重建 workspace → plan → start_run)。
- 帧 `pack.save/list/run` + server 分发;TS 工具 `rdk_pack_save/list/run` 入 allowlist;CLI `rdk-agent pack save/list/run`。
- 契约测试同步:AT-021 方法注册表 + TS allowlist 各加 3 项。
## 真机证据(`scripts/drive_s3_pack.py`,kimi 不参与 save/run)
```
plan: sha256:c0d97f02… policy: allow
original run: run-db14d96a24dac024 succeeded passed # agent 写的 cpu_sampler
pack.save: cpu-sampler (1 file, entrypoint cpu_sampler.py, artifact cpu.json)
pack.list: ['cpu-sampler']
pack.run: run-f3e99b0ee99e2648 succeeded passed # 不同 run_id,无 LLM 重跑
S3 Pack PASSED: capability saved + re-run without an LLM.
```
`pack.run` 产出与原 run 不同的 run_id(fresh request_id),succeeded/passed——能力被冻结成命名包、可列、可无 LLM 确定性重跑。
## 门禁
pytest 667(+TestPacks)、pi 24/5skip、surface 65/0/4、ruff/mypy clean(44 文件)。
## 未做
- Pack 的 `draft → verified-local → shareable` 状态机(分享/导出)——本切片只做 local save/list/run。
- Skill Candidate(把 agent 工作流晋升成 Skill)——S3 后续。
- 注:本切片代码在 /tmp/rdk-s2 worktree 未提交——会话中途主仓库 .git 对本会话变 OS 级 EPERM(写不进),需从可访问 .git 的终端提交。

View File

@ -0,0 +1,406 @@
{
"schema_version": "1.0",
"snapshot_id": "sha256:83b16d4582491d111d4ea9d4ef4e01677c6581afa8f11ca8fc1fc8942eb90c2f",
"device_id": "dev-a8c54ad11e5d41c2",
"captured_at": "2026-08-24T08:29:21.374734Z",
"identity": {
"schema_version": "1.0",
"vendor": "D-Robotics",
"family": "RDK S",
"model": "D-Robotics RDK S100P V1P0",
"serial_hash": null
},
"system": {
"schema_version": "1.0",
"os": "Linux",
"os_version": null,
"rdk_os_version": "4.0.5-Beta",
"kernel": "6.1.158-rt58-DR-4.0.5-2603031328-g9f678e-g6caa4d",
"architecture": "aarch64"
},
"resources": {
"schema_version": "1.0",
"cpu_count": 6,
"memory_bytes": 22841262080,
"disk_free_bytes": 19018670080,
"temperatures_c": {
"thermal_zone0": 44.2,
"thermal_zone1": 44.2,
"thermal_zone2": 40.9,
"thermal_zone3": 40.3,
"thermal_zone4": 42.7
}
},
"software": {
"schema_version": "1.0",
"python": null,
"tros_distro": "humble",
"bpu_runtime": "pvt_bpu_pvtc1_t1 : 43.431 (C)",
"lerobot_version": null
},
"capabilities": [
{
"schema_version": "1.0",
"id": "system.info",
"version": "1.0.0",
"status": "available",
"risk": "read_observe",
"mode": "read",
"concurrency": "shared",
"access": "brokered",
"requires": [],
"internal_device_resources": [],
"parameters_schema_ref": null,
"evidence": [
{
"schema_version": "1.0",
"kind": "probe",
"value": "drobotics.board.model@1"
}
],
"limitations": []
},
{
"schema_version": "1.0",
"id": "bpu.inference.static",
"version": "1.0.0",
"status": "available",
"risk": "device_io_bounded",
"mode": "read",
"concurrency": "shared",
"access": "brokered",
"requires": [],
"internal_device_resources": [],
"parameters_schema_ref": null,
"evidence": [
{
"schema_version": "1.0",
"kind": "probe",
"value": "drobotics.bpu.runtime@1"
}
],
"limitations": []
},
{
"schema_version": "1.0",
"id": "can.enumerate",
"version": "1.0.0",
"status": "unavailable",
"risk": "read_observe",
"mode": "read",
"concurrency": "shared",
"access": "brokered",
"requires": [],
"internal_device_resources": [],
"parameters_schema_ref": null,
"evidence": [
{
"schema_version": "1.0",
"kind": "probe",
"value": "linux.can.interfaces@1"
}
],
"limitations": [
"no CAN interfaces present"
]
},
{
"schema_version": "1.0",
"id": "serial.enumerate",
"version": "1.0.0",
"status": "available",
"risk": "read_observe",
"mode": "read",
"concurrency": "shared",
"access": "brokered",
"requires": [],
"internal_device_resources": [],
"parameters_schema_ref": null,
"evidence": [
{
"schema_version": "1.0",
"kind": "probe",
"value": "linux.serial.nodes@1"
}
],
"limitations": []
},
{
"schema_version": "1.0",
"id": "usb.enumerate",
"version": "1.0.0",
"status": "available",
"risk": "read_observe",
"mode": "read",
"concurrency": "shared",
"access": "brokered",
"requires": [],
"internal_device_resources": [],
"parameters_schema_ref": null,
"evidence": [
{
"schema_version": "1.0",
"kind": "probe",
"value": "linux.usb.enumerate@2"
}
],
"limitations": []
},
{
"schema_version": "1.0",
"id": "camera.snapshot.usb",
"version": "1.0.0",
"status": "available",
"risk": "read_observe",
"mode": "read",
"concurrency": "shared",
"access": "brokered",
"requires": [],
"internal_device_resources": [],
"parameters_schema_ref": null,
"evidence": [
{
"schema_version": "1.0",
"kind": "probe",
"value": "linux.video.nodes@1"
}
],
"limitations": []
}
],
"probe_errors": [],
"inventory": {
"schema_version": "1.0",
"profile": "full",
"probe_set_version": "1.2.0",
"completeness": "complete",
"evidence_refs": [
"evidence://drobotics.board.model@1",
"evidence://drobotics.bpu.runtime@1",
"evidence://drobotics.rdkos_info@1",
"evidence://drobotics.resources@1",
"evidence://drobotics.thermal@1",
"evidence://drobotics.tros.distro@1",
"evidence://ecosystem.lerobot@1",
"evidence://linux.can.interfaces@1",
"evidence://linux.serial.nodes@1",
"evidence://linux.usb.enumerate@2",
"evidence://linux.video.nodes@1"
]
},
"observations": {
"/probes/drobotics.board.model@1": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "drobotics.board.model@1",
"evidence_ref": "evidence://drobotics.board.model@1"
},
"/identity/model": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "drobotics.board.model@1",
"evidence_ref": "evidence://drobotics.board.model@1"
},
"/probes/drobotics.bpu.runtime@1": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "drobotics.bpu.runtime@1",
"evidence_ref": "evidence://drobotics.bpu.runtime@1"
},
"/capabilities/bpu.inference.static": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "drobotics.bpu.runtime@1",
"evidence_ref": "evidence://drobotics.bpu.runtime@1"
},
"/probes/drobotics.rdkos_info@1": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "drobotics.rdkos_info@1",
"evidence_ref": "evidence://drobotics.rdkos_info@1"
},
"/system/architecture": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "drobotics.rdkos_info@1",
"evidence_ref": "evidence://drobotics.rdkos_info@1"
},
"/probes/drobotics.resources@1": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "drobotics.resources@1",
"evidence_ref": "evidence://drobotics.resources@1"
},
"/resources": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "drobotics.resources@1",
"evidence_ref": "evidence://drobotics.resources@1"
},
"/probes/drobotics.thermal@1": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "drobotics.thermal@1",
"evidence_ref": "evidence://drobotics.thermal@1"
},
"/resources/temperatures_c": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "drobotics.thermal@1",
"evidence_ref": "evidence://drobotics.thermal@1"
},
"/probes/drobotics.tros.distro@1": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "drobotics.tros.distro@1",
"evidence_ref": "evidence://drobotics.tros.distro@1"
},
"/software/tros_distro": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "drobotics.tros.distro@1",
"evidence_ref": "evidence://drobotics.tros.distro@1"
},
"/probes/ecosystem.lerobot@1": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "ecosystem.lerobot@1",
"evidence_ref": "evidence://ecosystem.lerobot@1"
},
"/software/lerobot_version": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "ecosystem.lerobot@1",
"evidence_ref": "evidence://ecosystem.lerobot@1"
},
"/probes/linux.can.interfaces@1": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "linux.can.interfaces@1",
"evidence_ref": "evidence://linux.can.interfaces@1"
},
"/peripherals/can_interfaces": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "linux.can.interfaces@1",
"evidence_ref": "evidence://linux.can.interfaces@1"
},
"/capabilities/can.enumerate": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "linux.can.interfaces@1",
"evidence_ref": "evidence://linux.can.interfaces@1"
},
"/probes/linux.serial.nodes@1": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "linux.serial.nodes@1",
"evidence_ref": "evidence://linux.serial.nodes@1"
},
"/peripherals/serial_nodes": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "linux.serial.nodes@1",
"evidence_ref": "evidence://linux.serial.nodes@1"
},
"/capabilities/serial.enumerate": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "linux.serial.nodes@1",
"evidence_ref": "evidence://linux.serial.nodes@1"
},
"/probes/linux.usb.enumerate@2": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "linux.usb.enumerate@2",
"evidence_ref": "evidence://linux.usb.enumerate@2"
},
"/peripherals/usb_devices": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "linux.usb.enumerate@2",
"evidence_ref": "evidence://linux.usb.enumerate@2"
},
"/capabilities/usb.enumerate": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "linux.usb.enumerate@2",
"evidence_ref": "evidence://linux.usb.enumerate@2"
},
"/probes/linux.video.nodes@1": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "linux.video.nodes@1",
"evidence_ref": "evidence://linux.video.nodes@1"
},
"/capabilities/camera.snapshot.usb": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "linux.video.nodes@1",
"evidence_ref": "evidence://linux.video.nodes@1"
},
"/capabilities/system.info": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "drobotics.board.model@1",
"evidence_ref": "evidence://drobotics.board.model@1"
}
},
"peripherals": {
"schema_version": "1.0",
"usb_devices": [
{
"schema_version": "1.0",
"bus": "004",
"device": "001",
"vendor_id": "1d6b",
"product_id": "0003",
"description": "Linux Foundation 3.0 root hub"
},
{
"schema_version": "1.0",
"bus": "003",
"device": "003",
"vendor_id": "1e45",
"product_id": "0209",
"description": "CN02KX4NLG0004ABK00 USB Camera"
},
{
"schema_version": "1.0",
"bus": "003",
"device": "002",
"vendor_id": "1a86",
"product_id": "55d3",
"description": "QinHeng Electronics USB Single Serial"
},
{
"schema_version": "1.0",
"bus": "003",
"device": "001",
"vendor_id": "1d6b",
"product_id": "0002",
"description": "Linux Foundation 2.0 root hub"
},
{
"schema_version": "1.0",
"bus": "002",
"device": "001",
"vendor_id": "1d6b",
"product_id": "0003",
"description": "Linux Foundation 3.0 root hub"
},
{
"schema_version": "1.0",
"bus": "001",
"device": "001",
"vendor_id": "1d6b",
"product_id": "0002",
"description": "Linux Foundation 2.0 root hub"
}
],
"serial_nodes": [
"/dev/ttyACM0"
],
"can_interfaces": []
}
}

View File

@ -0,0 +1,235 @@
{
"schema_version": "1.0",
"snapshot_id": "sha256:77f789f8fb01fcfaca63bee1ae2464c593a08f040a2e1c825689d8377bad4bb0",
"device_id": "s100p-001",
"captured_at": "2026-08-17T08:07:59.480952Z",
"identity": {
"schema_version": "1.0",
"vendor": "D-Robotics",
"family": "RDK S",
"model": "D-Robotics RDK S100P V1P0\u0000",
"serial_hash": null
},
"system": {
"schema_version": "1.0",
"os": null,
"os_version": null,
"rdk_os_version": null,
"kernel": null,
"architecture": "aarch64"
},
"resources": {
"schema_version": "1.0",
"cpu_count": null,
"memory_bytes": null,
"disk_free_bytes": null,
"temperatures_c": {}
},
"software": {
"schema_version": "1.0",
"python": null,
"tros_distro": null,
"bpu_runtime": ""
},
"capabilities": [
{
"schema_version": "1.0",
"id": "system.info",
"version": "1.0.0",
"status": "available",
"risk": "read_observe",
"mode": "read",
"concurrency": "shared",
"access": "brokered",
"requires": [],
"internal_device_resources": [],
"parameters_schema_ref": null,
"evidence": [
{
"schema_version": "1.0",
"kind": "probe",
"value": "drobotics.board.model@1"
}
],
"limitations": []
},
{
"schema_version": "1.0",
"id": "bpu.inference.static",
"version": "1.0.0",
"status": "available",
"risk": "device_io_bounded",
"mode": "read",
"concurrency": "shared",
"access": "brokered",
"requires": [],
"internal_device_resources": [],
"parameters_schema_ref": null,
"evidence": [
{
"schema_version": "1.0",
"kind": "probe",
"value": "drobotics.bpu.runtime@1"
}
],
"limitations": []
},
{
"schema_version": "1.0",
"id": "usb.enumerate",
"version": "1.0.0",
"status": "available",
"risk": "read_observe",
"mode": "read",
"concurrency": "shared",
"access": "brokered",
"requires": [],
"internal_device_resources": [],
"parameters_schema_ref": null,
"evidence": [
{
"schema_version": "1.0",
"kind": "probe",
"value": "linux.usb.enumerate@1"
}
],
"limitations": []
},
{
"schema_version": "1.0",
"id": "camera.snapshot.usb",
"version": "1.0.0",
"status": "available",
"risk": "read_observe",
"mode": "read",
"concurrency": "shared",
"access": "brokered",
"requires": [],
"internal_device_resources": [],
"parameters_schema_ref": null,
"evidence": [
{
"schema_version": "1.0",
"kind": "probe",
"value": "linux.video.nodes@1"
}
],
"limitations": []
}
],
"probe_errors": [],
"inventory": {
"schema_version": "1.0",
"profile": "bootstrap",
"probe_set_version": "1.0.0",
"completeness": "complete",
"evidence_refs": [
"evidence://drobotics.board.model@1",
"evidence://drobotics.bpu.runtime@1",
"evidence://drobotics.rdkos_info@1",
"evidence://drobotics.resources@1",
"evidence://drobotics.thermal@1",
"evidence://drobotics.tros.distro@1",
"evidence://linux.usb.enumerate@1",
"evidence://linux.video.nodes@1"
]
},
"observations": {
"/probes/drobotics.board.model@1": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "drobotics.board.model@1",
"evidence_ref": "evidence://drobotics.board.model@1"
},
"/identity/model": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "drobotics.board.model@1",
"evidence_ref": "evidence://drobotics.board.model@1"
},
"/probes/drobotics.bpu.runtime@1": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "drobotics.bpu.runtime@1",
"evidence_ref": "evidence://drobotics.bpu.runtime@1"
},
"/capabilities/bpu.inference.static": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "drobotics.bpu.runtime@1",
"evidence_ref": "evidence://drobotics.bpu.runtime@1"
},
"/probes/drobotics.rdkos_info@1": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "drobotics.rdkos_info@1",
"evidence_ref": "evidence://drobotics.rdkos_info@1"
},
"/system/architecture": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "drobotics.rdkos_info@1",
"evidence_ref": "evidence://drobotics.rdkos_info@1"
},
"/probes/drobotics.resources@1": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "drobotics.resources@1",
"evidence_ref": "evidence://drobotics.resources@1"
},
"/resources": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "drobotics.resources@1",
"evidence_ref": "evidence://drobotics.resources@1"
},
"/probes/drobotics.thermal@1": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "drobotics.thermal@1",
"evidence_ref": "evidence://drobotics.thermal@1"
},
"/resources/temperatures_c": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "drobotics.thermal@1",
"evidence_ref": "evidence://drobotics.thermal@1"
},
"/probes/drobotics.tros.distro@1": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "drobotics.tros.distro@1",
"evidence_ref": "evidence://drobotics.tros.distro@1"
},
"/probes/linux.usb.enumerate@1": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "linux.usb.enumerate@1",
"evidence_ref": "evidence://linux.usb.enumerate@1"
},
"/capabilities/usb.enumerate": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "linux.usb.enumerate@1",
"evidence_ref": "evidence://linux.usb.enumerate@1"
},
"/probes/linux.video.nodes@1": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "linux.video.nodes@1",
"evidence_ref": "evidence://linux.video.nodes@1"
},
"/capabilities/camera.snapshot.usb": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "linux.video.nodes@1",
"evidence_ref": "evidence://linux.video.nodes@1"
},
"/capabilities/system.info": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "drobotics.board.model@1",
"evidence_ref": "evidence://drobotics.board.model@1"
}
}
}

View File

@ -0,0 +1,214 @@
{
"schema_version": "1.0",
"snapshot_id": "sha256:22cfe6ebdbebac9912578407c7838e8f67dc8452739e0a04dfeec3bfcd05ec00",
"device_id": "s100p-001",
"captured_at": "2026-08-17T08:24:16.750180Z",
"identity": {
"schema_version": "1.0",
"vendor": "D-Robotics",
"family": "RDK S",
"model": "D-Robotics RDK S100P V1P0",
"serial_hash": null
},
"system": {
"schema_version": "1.0",
"os": null,
"os_version": null,
"rdk_os_version": null,
"kernel": null,
"architecture": "aarch64"
},
"resources": {
"schema_version": "1.0",
"cpu_count": null,
"memory_bytes": null,
"disk_free_bytes": null,
"temperatures_c": {}
},
"software": {
"schema_version": "1.0",
"python": null,
"tros_distro": null,
"bpu_runtime": null
},
"capabilities": [
{
"schema_version": "1.0",
"id": "system.info",
"version": "1.0.0",
"status": "available",
"risk": "read_observe",
"mode": "read",
"concurrency": "shared",
"access": "brokered",
"requires": [],
"internal_device_resources": [],
"parameters_schema_ref": null,
"evidence": [
{
"schema_version": "1.0",
"kind": "probe",
"value": "drobotics.board.model@1"
}
],
"limitations": []
},
{
"schema_version": "1.0",
"id": "usb.enumerate",
"version": "1.0.0",
"status": "available",
"risk": "read_observe",
"mode": "read",
"concurrency": "shared",
"access": "brokered",
"requires": [],
"internal_device_resources": [],
"parameters_schema_ref": null,
"evidence": [
{
"schema_version": "1.0",
"kind": "probe",
"value": "linux.usb.enumerate@1"
}
],
"limitations": []
},
{
"schema_version": "1.0",
"id": "camera.snapshot.usb",
"version": "1.0.0",
"status": "available",
"risk": "read_observe",
"mode": "read",
"concurrency": "shared",
"access": "brokered",
"requires": [],
"internal_device_resources": [],
"parameters_schema_ref": null,
"evidence": [
{
"schema_version": "1.0",
"kind": "probe",
"value": "linux.video.nodes@1"
}
],
"limitations": []
}
],
"probe_errors": [
{
"schema_version": "1.0",
"probe_id": "drobotics.bpu.runtime@1",
"status": "failed",
"message": "Warning: Permanently added '192.168.127.10' (ED25519) to the list of known hosts.\nbash: warning: setlocale: LC_ALL: cannot change locale (en_US.UTF-8)"
}
],
"inventory": {
"schema_version": "1.0",
"profile": "bootstrap",
"probe_set_version": "1.0.0",
"completeness": "partial",
"evidence_refs": [
"evidence://drobotics.board.model@1",
"evidence://drobotics.rdkos_info@1",
"evidence://drobotics.resources@1",
"evidence://drobotics.thermal@1",
"evidence://drobotics.tros.distro@1",
"evidence://linux.usb.enumerate@1",
"evidence://linux.video.nodes@1"
]
},
"observations": {
"/probes/drobotics.board.model@1": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "drobotics.board.model@1",
"evidence_ref": "evidence://drobotics.board.model@1"
},
"/identity/model": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "drobotics.board.model@1",
"evidence_ref": "evidence://drobotics.board.model@1"
},
"/probes/drobotics.bpu.runtime@1": {
"schema_version": "1.0",
"status": "error",
"probe_id": "drobotics.bpu.runtime@1",
"evidence_ref": null
},
"/probes/drobotics.rdkos_info@1": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "drobotics.rdkos_info@1",
"evidence_ref": "evidence://drobotics.rdkos_info@1"
},
"/system/architecture": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "drobotics.rdkos_info@1",
"evidence_ref": "evidence://drobotics.rdkos_info@1"
},
"/probes/drobotics.resources@1": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "drobotics.resources@1",
"evidence_ref": "evidence://drobotics.resources@1"
},
"/resources": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "drobotics.resources@1",
"evidence_ref": "evidence://drobotics.resources@1"
},
"/probes/drobotics.thermal@1": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "drobotics.thermal@1",
"evidence_ref": "evidence://drobotics.thermal@1"
},
"/resources/temperatures_c": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "drobotics.thermal@1",
"evidence_ref": "evidence://drobotics.thermal@1"
},
"/probes/drobotics.tros.distro@1": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "drobotics.tros.distro@1",
"evidence_ref": "evidence://drobotics.tros.distro@1"
},
"/probes/linux.usb.enumerate@1": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "linux.usb.enumerate@1",
"evidence_ref": "evidence://linux.usb.enumerate@1"
},
"/capabilities/usb.enumerate": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "linux.usb.enumerate@1",
"evidence_ref": "evidence://linux.usb.enumerate@1"
},
"/probes/linux.video.nodes@1": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "linux.video.nodes@1",
"evidence_ref": "evidence://linux.video.nodes@1"
},
"/capabilities/camera.snapshot.usb": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "linux.video.nodes@1",
"evidence_ref": "evidence://linux.video.nodes@1"
},
"/capabilities/system.info": {
"schema_version": "1.0",
"status": "observed",
"probe_id": "drobotics.board.model@1",
"evidence_ref": "evidence://drobotics.board.model@1"
}
}
}

View File

@ -0,0 +1,52 @@
{
"checks": {
"disk": {
"total_gb": 44.5,
"used_pct": 56.0
},
"loadavg": {
"15m": 4.24,
"1m": 5.3,
"5m": 4.43
},
"memory": {
"available_mb": 19874,
"available_pct": 91.2,
"total_mb": 21783
},
"thermal": [
{
"celsius": 52.3,
"type": "pvt_cmn_pvtc1_t1",
"zone": "thermal_zone0"
},
{
"celsius": 52.3,
"type": "pvt_cmn_pvtc1_t2",
"zone": "thermal_zone1"
},
{
"celsius": 48.9,
"type": "pvt_mcu_pvtc1_t1",
"zone": "thermal_zone2"
},
{
"celsius": 47.7,
"type": "pvt_mcu_pvtc1_t2",
"zone": "thermal_zone3"
},
{
"celsius": 50.8,
"type": "pvt_bpu_pvtc1_t1",
"zone": "thermal_zone4"
}
],
"uptime_seconds": 6616
},
"ok": true,
"verdicts": {
"disk_ok": true,
"memory_ok": true,
"thermal_ok": true
}
}

View File

@ -0,0 +1,152 @@
> @rdk/rdk-agent-pi@0.1.0 test
> rm -rf dist-test && tsc -p tsconfig.test.json && node --test dist-test/test/*.test.js
TAP version 13
# Subtest: product config pins SDK identity and invariants (SEC-002/SEC-015)
ok 1 - product config pins SDK identity and invariants (SEC-002/SEC-015)
---
duration_ms: 4.064459
type: 'test'
...
# Subtest: allowlist has no approval-decision or built-in names (P0, AT-021/024)
ok 2 - allowlist has no approval-decision or built-in names (P0, AT-021/024)
---
duration_ms: 0.257541
type: 'test'
...
# Subtest: allowlist is the spec tool surface (docs/08 §5)
ok 3 - allowlist is the spec tool surface (docs/08 §5)
---
duration_ms: 1.546916
type: 'test'
...
# Subtest: environment guard refuses user-global Pi state
ok 4 - environment guard refuses user-global Pi state
---
duration_ms: 0.330584
type: 'test'
...
# Subtest: system prompt is versioned and carries mandatory safety sections
ok 5 - system prompt is versioned and carries mandatory safety sections
---
duration_ms: 0.167459
type: 'test'
...
# Subtest: golden request/response examples parse in TS (cross-language contract)
ok 6 - golden request/response examples parse in TS (cross-language contract)
---
duration_ms: 3.703417
type: 'test'
...
# Subtest: unknown schema major is rejected fail-closed
ok 7 - unknown schema major is rejected fail-closed
---
duration_ms: 0.603834
type: 'test'
...
# Subtest: unknown optional fields in a known major are ignored (docs/03 §1)
ok 8 - unknown optional fields in a known major are ignored (docs/03 §1)
---
duration_ms: 0.783708
type: 'test'
...
# Subtest: garbage and non-objects are rejected
ok 9 - garbage and non-objects are rejected
---
duration_ms: 1.423083
type: 'test'
...
# Subtest: response without in_reply_to is rejected
ok 10 - response without in_reply_to is rejected
---
duration_ms: 0.58225
type: 'test'
...
# Subtest: injected factories register the full tool surface
ok 11 - injected factories register the full tool surface
---
duration_ms: 19.580583
type: 'test'
...
# Subtest: RDK package skills load; user-global skills are ignored
ok 12 - RDK package skills load; user-global skills are ignored
---
duration_ms: 4.89775
type: 'test'
...
# Subtest: frozen system prompt comes from the builder, not from discovered files
ok 13 - frozen system prompt comes from the builder, not from discovered files
---
duration_ms: 4.070625
type: 'test'
...
# Subtest: scripted agent session completes the M0 loop on the real host
ok 14 - scripted agent session completes the M0 loop on the real host # SKIP
---
duration_ms: 0.583792
type: 'test'
...
# Subtest: duplicate run.start tool call does not duplicate the run (AT-023)
ok 15 - duplicate run.start tool call does not duplicate the run (AT-023) # SKIP
---
duration_ms: 0.039541
type: 'test'
...
# Subtest: approval decision methods do not exist on the model surface (AT-024)
ok 16 - approval decision methods do not exist on the model surface (AT-024) # SKIP
---
duration_ms: 0.034042
type: 'test'
...
# Subtest: task_report never completes without required verifiers (AT-024)
ok 17 - task_report never completes without required verifiers (AT-024) # SKIP
---
duration_ms: 0.026792
type: 'test'
...
# Subtest: S2 scripted agent loop completes the health card on the real S100P
ok 18 - S2 scripted agent loop completes the health card on the real S100P
---
duration_ms: 973.601042
type: 'test'
...
# Subtest: created tools equal the allowlist exactly (no more, no less)
ok 19 - created tools equal the allowlist exactly (no more, no less)
---
duration_ms: 3.972
type: 'test'
...
# Subtest: there is no approval decision tool (P0)
ok 20 - there is no approval decision tool (P0)
---
duration_ms: 0.43875
type: 'test'
...
# Subtest: rdk_run_start maps snake_case params and omits absent optionals
ok 21 - rdk_run_start maps snake_case params and omits absent optionals
---
duration_ms: 0.817583
type: 'test'
...
# Subtest: tool errors surface as isError results, not throws
ok 22 - tool errors surface as isError results, not throws
---
duration_ms: 0.855416
type: 'test'
...
# Subtest: missing required argument throws before any call
ok 23 - missing required argument throws before any call
---
duration_ms: 1.179041
type: 'test'
...
1..23
# tests 23
# suites 0
# pass 19
# fail 0
# cancelled 0
# skipped 4
# todo 0
# duration_ms 7094.894042

View File

@ -0,0 +1,152 @@
> @rdk/rdk-agent-pi@0.1.0 test
> rm -rf dist-test && tsc -p tsconfig.test.json && node --test dist-test/test/*.test.js
TAP version 13
# Subtest: product config pins SDK identity and invariants (SEC-002/SEC-015)
ok 1 - product config pins SDK identity and invariants (SEC-002/SEC-015)
---
duration_ms: 1.520875
type: 'test'
...
# Subtest: allowlist has no approval-decision or built-in names (P0, AT-021/024)
ok 2 - allowlist has no approval-decision or built-in names (P0, AT-021/024)
---
duration_ms: 0.10725
type: 'test'
...
# Subtest: allowlist is the spec tool surface (docs/08 §5)
ok 3 - allowlist is the spec tool surface (docs/08 §5)
---
duration_ms: 0.5725
type: 'test'
...
# Subtest: environment guard refuses user-global Pi state
ok 4 - environment guard refuses user-global Pi state
---
duration_ms: 0.121292
type: 'test'
...
# Subtest: system prompt is versioned and carries mandatory safety sections
ok 5 - system prompt is versioned and carries mandatory safety sections
---
duration_ms: 0.062125
type: 'test'
...
# Subtest: golden request/response examples parse in TS (cross-language contract)
ok 6 - golden request/response examples parse in TS (cross-language contract)
---
duration_ms: 4.228125
type: 'test'
...
# Subtest: unknown schema major is rejected fail-closed
ok 7 - unknown schema major is rejected fail-closed
---
duration_ms: 0.249708
type: 'test'
...
# Subtest: unknown optional fields in a known major are ignored (docs/03 §1)
ok 8 - unknown optional fields in a known major are ignored (docs/03 §1)
---
duration_ms: 0.221584
type: 'test'
...
# Subtest: garbage and non-objects are rejected
ok 9 - garbage and non-objects are rejected
---
duration_ms: 0.227708
type: 'test'
...
# Subtest: response without in_reply_to is rejected
ok 10 - response without in_reply_to is rejected
---
duration_ms: 0.164041
type: 'test'
...
# Subtest: injected factories register the full tool surface
ok 11 - injected factories register the full tool surface
---
duration_ms: 19.571125
type: 'test'
...
# Subtest: RDK package skills load; user-global skills are ignored
ok 12 - RDK package skills load; user-global skills are ignored
---
duration_ms: 4.475791
type: 'test'
...
# Subtest: frozen system prompt comes from the builder, not from discovered files
ok 13 - frozen system prompt comes from the builder, not from discovered files
---
duration_ms: 5.72375
type: 'test'
...
# Subtest: scripted agent session completes the M0 loop on the real host
ok 14 - scripted agent session completes the M0 loop on the real host # SKIP
---
duration_ms: 0.634
type: 'test'
...
# Subtest: duplicate run.start tool call does not duplicate the run (AT-023)
ok 15 - duplicate run.start tool call does not duplicate the run (AT-023) # SKIP
---
duration_ms: 0.055542
type: 'test'
...
# Subtest: approval decision methods do not exist on the model surface (AT-024)
ok 16 - approval decision methods do not exist on the model surface (AT-024) # SKIP
---
duration_ms: 0.040417
type: 'test'
...
# Subtest: task_report never completes without required verifiers (AT-024)
ok 17 - task_report never completes without required verifiers (AT-024) # SKIP
---
duration_ms: 0.032958
type: 'test'
...
# Subtest: S2 scripted agent loop completes the health card on the real S100P
ok 18 - S2 scripted agent loop completes the health card on the real S100P
---
duration_ms: 835.509791
type: 'test'
...
# Subtest: created tools equal the allowlist exactly (no more, no less)
ok 19 - created tools equal the allowlist exactly (no more, no less)
---
duration_ms: 4.490333
type: 'test'
...
# Subtest: there is no approval decision tool (P0)
ok 20 - there is no approval decision tool (P0)
---
duration_ms: 0.370541
type: 'test'
...
# Subtest: rdk_run_start maps snake_case params and omits absent optionals
ok 21 - rdk_run_start maps snake_case params and omits absent optionals
---
duration_ms: 0.435166
type: 'test'
...
# Subtest: tool errors surface as isError results, not throws
ok 22 - tool errors surface as isError results, not throws
---
duration_ms: 0.507166
type: 'test'
...
# Subtest: missing required argument throws before any call
ok 23 - missing required argument throws before any call
---
duration_ms: 0.725
type: 'test'
...
1..23
# tests 23
# suites 0
# pass 19
# fail 0
# cancelled 0
# skipped 4
# todo 0
# duration_ms 6928.154458

View File

@ -0,0 +1,122 @@
{
"host": "sunrise@192.168.127.10",
"device_id": "s100p-001",
"steps": [
{
"step": "inspect",
"snapshot_id": "sha256:0c2219ca9a58311835df77d5eb9666c5226faa6ec8eb0ba747cd3f46680551a0",
"model": "D-Robotics RDK S100P V1P0",
"completeness": "partial",
"capabilities": {
"system.info": "available",
"usb.enumerate": "available",
"camera.snapshot.usb": "available"
}
},
{
"step": "code",
"workspace": "ws-health",
"source_digest": "sha256:e2e0d5c7e3e564f5e0b17af33a48ee88fc41706852280929abe2d7f4dfe500d4"
},
{
"step": "plan",
"plan_id": "sha256:6451c02656de44d87617f4ab677db26e3c6792d1a432516e60139c2725fa2153",
"policy": "allow",
"rules": [
"risk.read_observe-allow"
]
},
{
"step": "run",
"run_id": "run-65f1102197cbf80f",
"state": "succeeded",
"outcome": "passed",
"exit_code": 0,
"cleanup": "confirmed"
},
{
"step": "artifacts",
"names": [
"health.json",
"result.json",
"stdout.log"
],
"health_digest": "sha256:37807b039add542761807fe7705de6164f55475b970d0a8988461f4ada933131",
"card": {
"checks": {
"disk": {
"total_gb": 44.5,
"used_pct": 55.9
},
"loadavg": {
"15m": 4.02,
"1m": 4.28,
"5m": 3.99
},
"memory": {
"available_mb": 19713,
"available_pct": 90.5,
"total_mb": 21783
},
"thermal": [
{
"celsius": 51.5,
"type": "pvt_cmn_pvtc1_t1",
"zone": "thermal_zone0"
},
{
"celsius": 50.0,
"type": "pvt_cmn_pvtc1_t2",
"zone": "thermal_zone1"
},
{
"celsius": 47.5,
"type": "pvt_mcu_pvtc1_t1",
"zone": "thermal_zone2"
},
{
"celsius": 46.9,
"type": "pvt_mcu_pvtc1_t2",
"zone": "thermal_zone3"
},
{
"celsius": 49.3,
"type": "pvt_bpu_pvtc1_t1",
"zone": "thermal_zone4"
}
],
"uptime_seconds": 32439
},
"ok": true,
"verdicts": {
"disk_ok": true,
"memory_ok": true,
"thermal_ok": true
}
}
},
{
"step": "idempotent-replay",
"same_run": true
},
{
"step": "plan-invalidation",
"rejected": true,
"code": "RDK-SEC-001",
"message": "RDK-SEC-001: run rejected: source content changed since plan"
},
{
"step": "timeout",
"run_id": "run-6305fcff1dc6329d",
"state": "failed",
"cleanup": "confirmed"
},
{
"step": "cancel",
"run_id": "run-792b7f1316a8e542",
"state": "cancelled",
"cleanup": "confirmed"
}
],
"result": "PASS"
}

View File

@ -0,0 +1,52 @@
{
"checks": {
"disk": {
"total_gb": 44.5,
"used_pct": 55.9
},
"loadavg": {
"15m": 4.02,
"1m": 4.28,
"5m": 3.99
},
"memory": {
"available_mb": 19713,
"available_pct": 90.5,
"total_mb": 21783
},
"thermal": [
{
"celsius": 51.5,
"type": "pvt_cmn_pvtc1_t1",
"zone": "thermal_zone0"
},
{
"celsius": 50.0,
"type": "pvt_cmn_pvtc1_t2",
"zone": "thermal_zone1"
},
{
"celsius": 47.5,
"type": "pvt_mcu_pvtc1_t1",
"zone": "thermal_zone2"
},
{
"celsius": 46.9,
"type": "pvt_mcu_pvtc1_t2",
"zone": "thermal_zone3"
},
{
"celsius": 49.3,
"type": "pvt_bpu_pvtc1_t1",
"zone": "thermal_zone4"
}
],
"uptime_seconds": 32439
},
"ok": true,
"verdicts": {
"disk_ok": true,
"memory_ok": true,
"thermal_ok": true
}
}

View File

@ -0,0 +1,59 @@
{
"host": "sunrise@192.168.127.10",
"device_id": "s100p-001",
"steps": [
{
"step": "plan",
"plan_id": "sha256:12ae25d4c314a1e6a89d1dd0f09f2a086e0fb986a8e6b8efff92549306db96b6",
"policy": "allow"
},
{
"step": "started",
"run_id": "run-19088f71e28493d9",
"state": "running",
"task_id": "task-56a29dff695942ca"
},
{
"step": "disconnected",
"run_id": "run-19088f71e28493d9",
"note": "service1 transport dropped mid-run"
},
{
"step": "reconciled",
"task_state": "verifying",
"run_ids": [
"run-19088f71e28493d9"
]
},
{
"step": "orphaned-run",
"run_id": "run-19088f71e28493d9",
"state": "failed",
"outcome": "not_verified",
"cleanup": "unconfirmed",
"note": "transport dropped mid-run; device fail-closes the orphan"
},
{
"step": "report-after-drop",
"state": "verifying",
"outcome": "not_verified",
"unresolved": [
"exit-ok",
"health-ok"
]
},
{
"step": "recovery-run",
"run_id": "run-35ffbfab1a916b44",
"state": "succeeded",
"outcome": "passed"
},
{
"step": "report-recovered",
"state": "completed",
"outcome": "passed",
"unresolved": []
}
],
"result": "PASS"
}

View File

@ -0,0 +1,35 @@
# SIM-R1 C0 证据:OpenCascade(build123d)wheel 覆盖与 typing 实测
日期:2026-08-26
范围:ADR-019 §11 未决项 1(OpenCascade 三平台 × Python 版本 wheel 覆盖实测)+ mypy strict 兼容性裁定
环境:macOS arm64(Darwin 24.0.0),CPython 3.12.13,一次性 venv `/tmp/sim-r1-occ-smoke`(**非**项目 `.venv`,不污染工作区依赖)
方式:`uv venv --python 3.12` + `uv pip install build123d==0.11.1 cadquery-ocp-stubs==7.9.3.1.1 mypy`;只从 PyPI 官方渠道安装
## 结论
| 判据 | 结果 | 证据 |
|---|---|---|
| macOS arm64 原生 wheel(官方渠道) | 通过 | `cadquery_ocp_novtk-7.9.3.1.1` 安装 tag `cp312-cp312-macosx_11_0_arm64`;build123d `py3-none-any` |
| 三平台 × py3.10–3.13 wheel 覆盖 | 通过 | PyPI `cadquery-ocp-novtk` 7.9.3.1.1 发布:cp310–cp314 × `macosx_11_0_arm64` / `macosx_11_0_x86_64` / `manylinux_2_31_x86_64` / `manylinux_2_31_aarch64` / `win_amd64`(覆盖仓库 `requires-python >=3.10` 与 CI ubuntu-latest x86_64) |
| 无 root / 无后台服务 / CPU-only | 通过 | 纯 pip 安装与进程内计算,无系统级副作用 |
| mypy strict 兼容 | 通过 | build123d 自带 `py.typed`;OCP 本体无 stubs,装 `cadquery-ocp-stubs==7.9.3.1.1` 后 `mypy --strict` 5 行样本 0 错误 → **不需要** `[[tool.mypy.overrides]] OCP.*` 豁免 |
| B-Rep 布尔/质量属性正确 | 通过 | `Box(120,80,3).cut(4×Cylinder(1.6,5))` → 单 solid、`is_valid=True`、体积 28703.49 == 28800 − 4π·1.6²·3(精确) |
| 网格化与二进制 STL 导出 | 通过 | `tessellate(0.1)` 2044 三角;`export_stl` 默认二进制 102,284 B(≈50 B/tri)→ 2WD 零件在 1MiB `artifact.fetch` 上限内可行(细分容差可调) |
| 许可 | 记录 | build123d Apache-2.0;OpenCascade(经 ocp wheel 动态链接)LGPL-3.0——pip wheel 动态分发、可替换,不静态链接,兼容产品分发;作为已接受约束记录 |
## 冻结进实现的 API 事实(build123d 0.11.1,smoke 实测)
- 图元构造签名无 `location` kwarg(`Cylinder(radius, height, arc_size, rotation, align, mode)`);放置用 `shape.moved(Location(Vector(x, y, z)))`;
- `Shape.solids()` 是方法;`Shape.is_valid` 是属性(bool);
- `export_stl(to_export, file_path, tolerance=0.001, angular_tolerance=0.1, ascii_format=False)`,默认二进制;
- 布尔:`shape.cut(*others)`;体积/质心等质量属性直接可用(OCC 属性,非网格估算)。
## 复现
```bash
uv venv --python 3.12 /tmp/sim-r1-occ-smoke
uv pip install --python /tmp/sim-r1-occ-smoke/bin/python build123d==0.11.1 cadquery-ocp-stubs==7.9.3.1.1 mypy
# 几何 smoke 与 mypy 微检查脚本见会话记录;判据见上表
```
ADR-019 §11 未决项 1 由此关闭;几何内核冻结为 **build123d==0.11.1(OpenCascade)**。

View File

@ -0,0 +1,57 @@
# SIM-R1 开发期 smoke 证据(确定性 / 判据 / 导出预算)
日期:2026-08-26
范围:SIM-R1 垂直切片开发期 ad-hoc smoke(正式验收由独立测试 Agent 依 AT-034..037 执行)
环境:macOS arm64,Python 3.12.13(workspace venv),`rdk-agent-sim` headless 与 `rdkctl` 两条入口
DeviceSpec:`packages/rdk_agent_sim/src/rdk_agent_sim/data/device_specs/2wd-rover.json`
## 1. 确定性(TEST_STRATEGY §12.2:digest 相等,零容差)
nominal 场景连跑两次,四个工件字节级一致:
| 工件 | sha256[:16] | 双跑相等 |
|---|---|---|
| verdicts.json | 4bbcee96b57bc1a5 | 是 |
| waveform.json | 2ebdd361cfa284a5 | 是 |
| trajectory.json | f57d7cbf1b5788c6 | 是 |
| stability.json | b1ddc584c9ccf161 | 是 |
## 2. 电路判据(AT-034 预期行为,开发期观测)
| 场景 | faults | 通道(avg A / omega rad/s / stalled) | 电池 |
|---|---|---|---|
| nominal | 全 False | mot_l 1.947 / 81.22;mot_r 1.577 / 55.09 | sag 0.475 V,无欠压 |
| stall(健康电池) | stall/overcurrent True,undervoltage False | mot_l 3.666(1.88× nominal)stalled;mot_r 3.666(2.33×)stalled | 无欠压 |
| stall_weak(内阻 ×8) | stall/undervoltage True | 双通道 stalled | v_term_min 3.52 V |
物理自洽:nominal 自旋限流、转向段右轮减速;stall 转子锁定 + 持续过流(avg > rated 2.5 A,且 ≥1.5× nominal 同通道);欠压由磨损电池变体演示(2026-08-26 口径澄清:高内阻抑制堵转电流,1.5× 判据与欠压不可同场景共存,见 AT-034 指注)。
## 3. 运动学/稳定性(AT-035 预期行为)
- 直线 2 s + 转向 2 s 预览轨迹,终点位姿确定;
- 静态稳定裕度 54.86 mm(质心投影在 120×160 mm 支撑矩形内);准静态 lateral 裕度 25.90 m/s²;`stable: true`。
## 4. STL 导出与 printability(AT-036 预期行为)
6 个打印件全部 `valid_solid/watertight_by_construction/bed_fit/min_wall_ok = true`,`printable: true`。
尺寸均在 1MiB `artifact.fetch` 上限内(最大 wheel_adapter 152,084 B;预算上限 900 KiB):
| 工件 | 字节 |
|---|---|
| part_chassis.stl | 102,284 |
| part_motor_mount_{l,r}.stl | 51,884 |
| part_wheel_adapter_{l,r}.stl | 152,084 |
| part_battery_tray.stl | 1,484 |
| bom.json / printability.json | 2,157 / 1,481 |
## 5. 产品路径(rdkctl + Host,同构 stdio 协议)
临时 `RDK_STATE_DIR` 下:`sim provision` → `device inventory`(虚拟板 model `D-Robotics RDK S100P V1P0`,无 NUL;mock 能力携带 annotated-mock limitation)→ `sim evaluate` nominal/stall 与 `sim export` 均 `succeeded/passed`,RunRecord `origin: simulation`(设备盖章 + 宿主交叉校验),verifier(json.assert + exit_code.zero)通过。
复现:
```bash
uv run rdk-agent-sim evaluate --spec packages/rdk_agent_sim/src/rdk_agent_sim/data/device_specs/2wd-rover.json --scenario nominal --out /tmp/a
uv run rdk-agent-sim export-stl --spec ... --out /tmp/x
RDK_STATE_DIR=$(mktemp -d) uv run rdkctl sim provision && RDK_STATE_DIR=... uv run rdkctl sim evaluate --request-id r1 ...
```

View File

@ -0,0 +1,28 @@
# SIM-R1 独立测试报告(测试 Agent 两轮结论存档)
日期:2026-08-27(复测)/2026-08-26(首轮)
依据:AGENTS.md §四 开发/测试 Agent 独立;测试 Agent 独立设计、编写、执行,未改产品代码
范围:`codex/sim-rebuild`,首轮 HEAD `fc22a69`,复测 HEAD `25bae5c`(修复 `37b3f03`+`25bae5c`)
套件:91+ 新增测试(unit/contract/integration/acceptance/golden),落位约定路径;golden 冻结于 `tests/golden/sim/`(macOS arm64,digest 零容差;STL 字节 digest 仅本平台,其他平台结构不变量)
## 首轮结论(2026-08-26)
- AT-035 通过;AT-034/036/037 各 1 项判据未过 → 缺陷 D1–D4(D1 虚拟板 model 含 NUL;D2 导出路径包含绕过;D3 stall 1.5× 判据与欠压同场景物理冲突;D4 非法 sim.kind 滞留 QUEUED)。
- 门禁:core 分支覆盖 96.27%(≥90),ruff 全绿。
## 开发修复(2026-08-27,提交 37b3f03/25bae5c)
- D1 重生成虚拟板事实真去 NUL;D2 `assert_within_root` resolve 后包含判断 + `PartInstance.id` 路径安全字符集(schema 边界);D3 场景拆分 `stall`(健康电池:1.5×+过流)/`stall_weak`(磨损电池:欠压),AT-034 口径书面澄清;D4 backend 先迁 STAGING 再校验,非法 kind 终态 FAILED。
## 复测结论(2026-08-27,测试 Agent)
| AT | 结论 | 关键实测 |
|---|---|---|
| AT-034 | ✅ 通过 | stall 两通道比值 1.883/2.325 ≥1.5;stall_weak vmin 3.52V 欠压真;三场景双跑 digest 相等;非法 kind 终态 failed |
| AT-035 | ✅ 通过 | 双跑 digest 相等;稳定裕度 54.86mm 正;质心外移→失败且 spec_id 变 |
| AT-036 | ✅ 通过 | 水密单 solid、BOM/printability 四判据、<1MiB、越根拒绝(双保险) |
| AT-037 | ✅ 通过 | 快照逐字段同构、model 无 NUL、mock 带 limitation、仿真/真机/未知分列、无升级路径 |
- 全量 `pytest --cov=rdk_agent_core --cov-branch --cov-fail-under=90`:**753 tests,0 失败**;core 分支覆盖 **96.27%**(device_spec.py 100%);ruff/schema-drift 全绿;无新缺陷、无回归。
**总体:SIM-R1 满足验收判据,可进入 SIM-R2 评审。**

View File

@ -0,0 +1,35 @@
# SIM-R2 开发期 smoke 证据(L2 可运行板,Python 侧)
日期:2026-08-27
范围:SIM-R2 开发期 ad-hoc smoke(正式验收由独立测试 Agent 依 AT-038..041 执行)
环境:macOS arm64,Python 3.12.13;`codex/sim-r2`(4effbb8..7b85af6)
## 1. L2 审核模板真跑(rdkctl,临时 RDK_STATE_DIR)
| 模板 | state/outcome | origin | 产物 |
|---|---|---|---|
| health-card | succeeded/passed | simulation | health.json(uptime 12345.67 / mem_total 22841262080 / load1 0.25,虚拟事实冻结值) |
| usb-camera-snapshot | succeeded/passed | simulation | snapshot.png(640×480 PNG)+ camera.json(origin=simulation + 合成 provenance) |
| bpu-static-inference | 首跑 APPROVAL_REQUIRED(R2 allowlist)→ 人工 approve → 复跑 succeeded/passed | simulation | bpu_result.json(sha256 派生 labels/scores、latency 42.0、温度 43.431) |
## 2. 确定性
- usb-camera-snapshot 双跑:snapshot.png / camera.json / result.json 字节 digest 全相等(macOS arm64)。
- health-card 双跑 health.json 相等。
## 3. 安全闸实测
- 自构 manifest(staged 源 ≠ 审核模板 digest):POLICY_DENIED 类拒绝、不执行;修复 1132760 后设备侧记录终态 FAILED(QUEUED 滞留缺陷关闭)。
- bpu 无 allowlist → POLICY_DENIED;有 allowlist 无审批 → APPROVAL_REQUIRED 带 approval_id;agent 面不可自批(独立测试契约用例覆盖)。
- sim 程序运行忽略 manifest env(env 由 backend 全控;PYTHONPATH/LD_PRELOAD 注入面不存在)。
## 4. 缺陷修复(开发期发现/测试 Agent 报告)
- health-card 模板潜在 SyntaxError(无括号 dict-comprehension 非法)→ C4 修复。
- D1-class:run_program 拒绝滞留 QUEUED → 1132760 收口终态。
- D-SIMR2-1:image.basic PNG 截断 fail-open → 59130c7 chunk 遍历+长度守卫。
- D-SIMR2-2:image.basic JPEG SOF 后截断 fail-open → 7b85af6 EOI 收尾 + FF FF 填充字节处理。
## 5. 门禁
每提交 ruff check/format、mypy(含 sim/host)绿;全量 pytest 836 绿(一次 test_sim_backend 失败为并发负载 subprocess 超时 flake,单独跑与复跑均过、代码未变,非产品缺陷)。schema drift 无。

View File

@ -0,0 +1,31 @@
# SIM-R2 独立测试报告(测试 Agent 最终判定存档)
日期:2026-08-27(收尾轮)
依据:AGENTS.md §四 开发/测试独立;测试 Agent 仅改 tests/ 与 golden 基线,未触碰产品代码
范围:`codex/sim-r2`,被测 `4effbb8..e159b82` + 修复 `1132760`/`59130c7`/`7b85af6`
## 逐 AT 最终结论
| AT | 结论 | 要点 |
|---|---|---|
| AT-038 L2 审核模板真跑 | ✅ | health-card/camera succeeded/passed/origin=simulation + verifiers;bpu DENY→APPROVAL_REQUIRED→人工 approve→复跑通过;agent 不可自批;自构 manifest POLICY_DENIED 类、不执行、终态 FAILED |
| AT-039 合成相机帧 + image verifier | ✅ | 双跑 PNG 字节 digest 相等(macOS arm64);PNG/JPEG 逐字节截断扫描全 fail-closed,never-fail-open 两格式满足 |
| AT-040 BPU 结构结果 | ✅ | 双跑 digest 相等;sha256 派生 labels/scores(独立复算);latency 42.0;温度 43.431;未审核模型 fail-closed |
| AT-041 1.2.0 同构 + 枚举 | ✅ | probe_set 1.2.0;peripherals/tros 同构;6 caps observed 覆盖;12 行三档;provenance + FIND-002 矛盾注 |
## 缺陷闭环
| 缺陷 | 修复 | 复测 |
|---|---|---|
| run_program 拒绝滞留 QUEUED(D4 同类) | 1132760 | ✅ 终态 FAILED |
| D-SIMR2-1 PNG 截断 fail-open/ERROR | 59130c7 | ✅ 逐字节截断全 fail-closed |
| D-SIMR2-2 JPEG SOF 后截断 fail-open | 7b85af6 | ✅ 逐字节截断全 fail-closed;EOI 前填充字节仍 PASS |
## 门禁
- ruff check/format tests:绿(55 文件)
- pytest --cov=rdk_agent_core --cov-branch --cov-fail-under=90:**836/836,覆盖 96.35%**(templates.py 100%)
- schema drift:无
- 一次 test_sim_backend subprocess 超时 flake:两次独立复跑绿、代码未变,判定并发负载抖动,非产品缺陷
**总判定:SIM-R2 验收通过,可进入下一阶段。**

View File

@ -1,92 +0,0 @@
# Webots R2025a macOS arm64 兼容性 Smoke 报告(ADR-016 Phase 2A)
日期:2026-08-14
主机:Apple Silicon(arm64),macOS 15.0(BuildVersion 24A8332)
执行人:Claude Code(Phase 2A 授权范围内)
结论:**PASS WITH CONDITIONS**(建议冻结 R2025a,附两项记录待 Phase 2B 处理)
## 1. 下载与完整性
| 项 | 值 |
|---|---|
| 来源 | Cyberbotics 官方 GitHub release(`cyberbotics/webots` tag `R2025a`) |
| URL | `https://github.com/cyberbotics/webots/releases/download/R2025a/webots-R2025a.dmg` |
| 发布 | 2025-02-04 |
| 大小 | 107,119,977 字节(官方 asset size 一致) |
| SHA-256 | `484f6cc84ca794dd33e410b0bfc030132cc5b163a882c350c1d293d06d87584f` |
| DMG 校验 | `hdiutil verify` → `checksum ... is VALID`(bzip2 UDIF 只读) |
> 未下载官方 `assets-R2025a.zip`(692MB 示例资产)——符合 ADR-016 §11.6 自制资产边界。
## 2. 签名与 Gatekeeper(关键发现)
| 项 | 值 |
|---|---|
| 主二进制架构 | universal(`x86_64` + `arm64`)——Apple Silicon 原生 |
| Bundle Identifier | `com.cyberbotics.webots` |
| codesign Signature | **ad-hoc**(非 Developer ID) |
| TeamIdentifier | **not set** |
| `spctl --assess` | **rejected**(未 notarized) |
| 安装后 quarantine | 无(`ditto` 复制未引入 quarantine xattr) |
含义:Webots.app 是 ad-hoc 签名、无团队 ID、未 notarized。用户从官方下载后首次启动会遇到 Gatekeeper 拦截(右键打开或 `xattr -d com.apple.quarantine` 解除)。**`rdk-sim` 的 preflight 需要把这一事实纳入检测与提示**,不能假设安装即可启动。这属于「外部依赖模式」的已知安装摩擦,非阻断。
## 3. 安装
- 安装路径:`~/Applications/Webots.app`(无管理员权限)
- 二进制:`~/Applications/Webots.app/Contents/MacOS/webots`(15,309,248 字节,universal)
- `webots --version` → `Webots version: R2025a`,exit 0
## 4. Python Controller 运行环境(ADR §10 实证)
| 项 | 值 |
|---|---|
| Python executable | `/Library/Developer/CommandLineTools/usr/bin/python3`(系统 Python) |
| Python 版本 | `3.9.6` |
| WEBOTS_HOME | `/Users/d-robotics/Applications/Webots.app` |
| controller module path | `/Users/d-robotics/Applications/Webots.app/Contents/lib/controller/python` |
**实证 ADR §10**:Webots 是「启动其配置的系统 Python」,并非自带独立 Python。Controller 首版仅依赖 stdlib + Webots `controller` 模块,未 import 任何 uv 管理的包,成立。
## 5. Smoke 结果(逐项)
自制最小 Box/Cylinder 世界 + Robot Controller(Camera/Motor/PositionSensor)+ Supervisor Controller(读真值/reset/quit)。
| # | 验证项 | 结果 | 证据 |
|---|---|---|---|
| 1 | 原生启动 | **passed** | `--version` exit 0;世界加载无 PROTO 错误 |
| 2 | 3D 渲染 | **passed** | `gui_realtime` 进程存活 6s(窗口启动);`fast_batch`(渲染路径)exit 0 跑完 20 步 |
| 3 | Python Controller | **passed** | 两控制器 `python3 -u` 启动,`exited successfully` |
| 4 | Camera | **passed** | `camera=64x64 image_bytes=16384`(=64×64×4 RGBA) |
| 5 | Motor | **passed** | `setVelocity(1.0)`→`getVelocity()=1.0`;驱动关节:编码器 0.03→0.16 单调递增 |
| 6 | PositionSensor | **passed** | 读数 0.03/0.06/0.10/0.13/0.16,速率 = 1.0 rad/s × 0.032s 精确一致 |
| 7 | Supervisor reset/读真值 | **passed** | `ground_truth_position=0.2500,0.0500,0.0000`(与 TARGET 放置一致);`simulationReset() ok` |
| 8 | fast | **passed** | `--mode=fast` exit 0 |
| 9 | no-rendering | **passed** | `--no-rendering --batch` exit 0 |
| 10 | batch | **passed** | `--batch` 跑完即退(`simulationQuit(0)`),exit 0 |
| 11 | 正常退出/清理 | **passed** | exit 0;无残留 webots 进程;dmg 卸载干净 |
## 6. 记录的两项(Phase 2B 处理,不阻断冻结)
1. **GPU 警告**:Webots 报告 `GPU vendor is 'Apple'`,提示低于最低要求(官方推荐 NVIDIA/AMD),自动关闭阴影/抗锯齿/环境光遮蔽/降低纹理质量。**Apple Silicon 上渲染可用但降级**——GUI 3D 视图功能正常但画质受限。这符合 macOS arm64 预期,不影响 headless/no-rendering/batch 的 CI 回归路径(本项目核心用途)。
2. **`simulationReset()` 后电机不重新累计**:smoke 中 Supervisor 调 `simulationReset()` 后,Robot Controller 即使每步重设 `setPosition(inf)+setVelocity(1.0)`,编码器仍保持 0(仿真时间与关节角已正确归零)。reset 前轨迹(steps 0-4)完全正确。这是控制器侧执行器 re-init 细节,Phase 2B 写正式 Controller 时需验证 reset 语义(复位→重新使能电机/重新进入速度模式→确认编码器从 0 重新累计)。不影响「reset 本身可用」结论。
## 7. 冻结建议
**建议冻结 R2025a**,理由:
- universal arm64 原生、原生启动、Python Controller、Camera、Motor、PositionSensor、Supervisor reset/真值、fast/no-rendering/batch、退出清理全部通过。
- 签名未 notarized 属「外部依赖模式」已知摩擦,非 R2025a 独有(可记录在 preflight 提示)。
- GPU 降级是 Apple Silicon 平台预期,不影响本项目 headless 回归主用途。
正式冻结前建议补记:官方 R2025a 发布物的 SHA-256 校验和已记录(见 §1),可作为后续 `rdk-sim` preflight 的固定版本锚点。
## 8. 证据文件
- `logs/fast_no_render_batch.log`(完整 headless 轨迹)
- `logs/fast_batch.log`(渲染路径 headless)
- `logs/gui_realtime.log`(GUI 启动)
- `worlds/smoke.wbt`(自制最小世界)
- `controllers/rdk_smoke_robot/rdk_smoke_robot.py`
- `controllers/rdk_smoke_supervisor/rdk_smoke_supervisor.py`
- `run_smoke.sh`

View File

@ -1,67 +0,0 @@
"""Minimal self-made Robot Controller for the Webots R2025a smoke test.
Exercises the Agent-visible data plane: Camera, RotationalMotor, and
PositionSensor. Stdlib-only (the ``controller`` module is provided by Webots).
"""
import os
import sys
from controller import Robot
TIME_STEP = 32
def main() -> None:
print(
"[smoke-robot] python_executable=%s python_version=%s "
"pythonhome=%s webots_home=%s path=%s"
% (
sys.executable,
sys.version.split()[0],
os.environ.get("PYTHONHOME"),
os.environ.get("WEBOTS_HOME"),
os.environ.get("PYTHONPATH"),
),
flush=True,
)
robot = Robot()
camera = robot.getDevice("camera")
motor = robot.getDevice("motor")
encoder = robot.getDevice("encoder")
camera.enable(TIME_STEP)
encoder.enable(TIME_STEP)
motor.setPosition(float("inf"))
motor.setVelocity(1.0)
print("[smoke-robot] started", flush=True)
for step in range(20):
robot.step(TIME_STEP)
# Re-establish velocity-control mode each step: simulationReset()
# reverts the motor to position mode, so setPosition(inf) must be
# re-applied to keep velocity control active across a reset.
motor.setPosition(float("inf"))
if step == 5:
motor.setVelocity(1.0)
elif step == 12:
motor.setVelocity(0.0)
print(
"[smoke-robot] step=%d t=%.3f encoder=%.4f motor_velocity=%.4f"
% (step, robot.getTime(), encoder.getValue(), motor.getVelocity()),
flush=True,
)
if step == 15:
img = camera.getImage()
print(
"[smoke-robot] camera=%dx%d image_bytes=%d"
% (camera.getWidth(), camera.getHeight(), len(img)),
flush=True,
)
print("[smoke-robot] done", flush=True)
if __name__ == "__main__":
main()

View File

@ -1,53 +0,0 @@
"""Minimal self-made Supervisor Controller for the Webots R2025a smoke test.
Exercises the Oracle plane: reading ground truth (target object position) and
simulation reset. Stdlib-only (``controller`` module provided by Webots).
"""
from controller import Supervisor
TIME_STEP = 32
def find_target(sup: Supervisor) -> object:
root = sup.getRoot()
children = root.getField("children")
count = children.getCount()
for index in range(count):
node = children.getMFNode(index)
name_field = node.getField("name")
if name_field is not None and name_field.getSFString() == "TARGET":
return node
return None
def main() -> None:
sup = Supervisor()
target = find_target(sup)
if target is None:
print("[smoke-supervisor] ERROR target 'TARGET' not found", flush=True)
return
position = target.getPosition()
print(
"[smoke-supervisor] ground_truth_position=%.4f,%.4f,%.4f"
% (position[0], position[1], position[2]),
flush=True,
)
for _ in range(5):
sup.step(TIME_STEP)
sup.simulationReset()
print("[smoke-supervisor] simulationReset() ok", flush=True)
# Run long enough after reset for the Robot Controller to complete its
# full camera/motor/encoder demo (20 steps) before quitting cleanly.
for _ in range(25):
sup.step(TIME_STEP)
print("[smoke-supervisor] done", flush=True)
sup.simulationQuit(0)
if __name__ == "__main__":
main()

View File

@ -1,33 +0,0 @@
2026-08-14 11:26:11.160 webots[46091:12201357] +[IMKClient subclass]: chose IMKClient_Legacy
2026-08-14 11:26:11.163 webots[46091:12201357] +[IMKInputSession subclass]: chose IMKInputSession_Legacy
UNSUPPORTED (log once): POSSIBLE ISSUE: unit 0 GLD_TEXTURE_INDEX_2D is unloadable and bound to sampler type (Float) - using zero texture because texture unloadable
INFO: rdk_smoke_robot: Starting controller: python3 -u rdk_smoke_robot.py
INFO: rdk_smoke_supervisor: Starting controller: python3 -u rdk_smoke_supervisor.py
[smoke-robot] python_executable=/Library/Developer/CommandLineTools/usr/bin/python3 python_version=3.9.6 pythonhome=None webots_home=/Users/d-robotics/Applications/Webots.app path=/Users/d-robotics/Applications/Webots.app/Contents/lib/controller/python
[smoke-robot] started
[smoke-supervisor] ground_truth_position=0.2500,0.0500,0.0000
[smoke-robot] step=0 t=0.032 encoder=0.0300 motor_velocity=1.0000
[smoke-robot] step=1 t=0.064 encoder=0.0600 motor_velocity=1.0000
[smoke-robot] step=2 t=0.096 encoder=0.1000 motor_velocity=1.0000
[smoke-robot] step=3 t=0.128 encoder=0.1300 motor_velocity=1.0000
[smoke-robot] step=4 t=0.160 encoder=0.1600 motor_velocity=1.0000
[smoke-supervisor] simulationReset() ok
[smoke-robot] step=5 t=0.032 encoder=0.0000 motor_velocity=1.0000
[smoke-robot] step=6 t=0.064 encoder=0.0000 motor_velocity=1.0000
[smoke-robot] step=7 t=0.096 encoder=0.0000 motor_velocity=1.0000
[smoke-robot] step=8 t=0.128 encoder=0.0000 motor_velocity=1.0000
[smoke-robot] step=9 t=0.160 encoder=0.0000 motor_velocity=1.0000
[smoke-robot] step=10 t=0.192 encoder=0.0000 motor_velocity=1.0000
[smoke-robot] step=11 t=0.224 encoder=0.0000 motor_velocity=1.0000
[smoke-robot] step=12 t=0.256 encoder=0.0000 motor_velocity=0.0000
[smoke-robot] step=13 t=0.288 encoder=0.0000 motor_velocity=0.0000
[smoke-robot] step=14 t=0.320 encoder=0.0000 motor_velocity=0.0000
[smoke-robot] step=15 t=0.352 encoder=0.0000 motor_velocity=0.0000
[smoke-robot] camera=64x64 image_bytes=16384
[smoke-robot] step=16 t=0.384 encoder=0.0000 motor_velocity=0.0000
[smoke-robot] step=17 t=0.416 encoder=0.0000 motor_velocity=0.0000
[smoke-robot] step=18 t=0.448 encoder=0.0000 motor_velocity=0.0000
[smoke-robot] step=19 t=0.480 encoder=0.0000 motor_velocity=0.0000
[smoke-robot] done
INFO: 'rdk_smoke_robot' controller exited successfully.
INFO: rdk_smoke_supervisor: Terminating.

View File

@ -1,33 +0,0 @@
2026-08-14 11:25:29.623 webots[45840:12199829] +[IMKClient subclass]: chose IMKClient_Legacy
2026-08-14 11:25:29.623 webots[45840:12199829] +[IMKInputSession subclass]: chose IMKInputSession_Legacy
UNSUPPORTED (log once): POSSIBLE ISSUE: unit 0 GLD_TEXTURE_INDEX_2D is unloadable and bound to sampler type (Float) - using zero texture because texture unloadable
INFO: rdk_smoke_robot: Starting controller: python3 -u rdk_smoke_robot.py
INFO: rdk_smoke_supervisor: Starting controller: python3 -u rdk_smoke_supervisor.py
[smoke-robot] python_executable=/Library/Developer/CommandLineTools/usr/bin/python3 python_version=3.9.6 pythonhome=None webots_home=/Users/d-robotics/Applications/Webots.app path=/Users/d-robotics/Applications/Webots.app/Contents/lib/controller/python
[smoke-robot] started
[smoke-supervisor] ground_truth_position=0.2500,0.0500,0.0000
[smoke-robot] step=0 t=0.032 encoder=0.0300 motor_velocity=1.0000
[smoke-robot] step=1 t=0.064 encoder=0.0600 motor_velocity=1.0000
[smoke-robot] step=2 t=0.096 encoder=0.1000 motor_velocity=1.0000
[smoke-robot] step=3 t=0.128 encoder=0.1300 motor_velocity=1.0000
[smoke-robot] step=4 t=0.160 encoder=0.1600 motor_velocity=1.0000
[smoke-supervisor] simulationReset() ok
[smoke-robot] step=5 t=0.032 encoder=0.0000 motor_velocity=1.0000
[smoke-robot] step=6 t=0.064 encoder=0.0000 motor_velocity=1.0000
[smoke-robot] step=7 t=0.096 encoder=0.0000 motor_velocity=1.0000
[smoke-robot] step=8 t=0.128 encoder=0.0000 motor_velocity=1.0000
[smoke-robot] step=9 t=0.160 encoder=0.0000 motor_velocity=1.0000
[smoke-robot] step=10 t=0.192 encoder=0.0000 motor_velocity=1.0000
[smoke-robot] step=11 t=0.224 encoder=0.0000 motor_velocity=1.0000
[smoke-robot] step=12 t=0.256 encoder=0.0000 motor_velocity=0.0000
[smoke-robot] step=13 t=0.288 encoder=0.0000 motor_velocity=0.0000
[smoke-robot] step=14 t=0.320 encoder=0.0000 motor_velocity=0.0000
[smoke-robot] step=15 t=0.352 encoder=0.0000 motor_velocity=0.0000
[smoke-robot] camera=64x64 image_bytes=16384
[smoke-robot] step=16 t=0.384 encoder=0.0000 motor_velocity=0.0000
[smoke-robot] step=17 t=0.416 encoder=0.0000 motor_velocity=0.0000
[smoke-robot] step=18 t=0.448 encoder=0.0000 motor_velocity=0.0000
[smoke-robot] step=19 t=0.480 encoder=0.0000 motor_velocity=0.0000
[smoke-robot] done
INFO: 'rdk_smoke_robot' controller exited successfully.
INFO: rdk_smoke_supervisor: Terminating.

View File

@ -1,2 +0,0 @@
2026-08-14 11:27:15.131 webots[46965:12205002] +[IMKClient subclass]: chose IMKClient_Legacy
2026-08-14 11:27:15.131 webots[46965:12205002] +[IMKInputSession subclass]: chose IMKInputSession_Legacy

View File

@ -1,53 +0,0 @@
#!/usr/bin/env bash
# Webots R2025a macOS arm64 smoke runner (ADR-016 Phase 2A).
# Runs the self-made smoke world/controllers in each required mode and writes
# per-mode logs under ./logs. Reads WEBOTS_APP from $1 or the default location.
set -u
ROOT="$(cd "$(dirname "$0")" && pwd)"
WORLD="$ROOT/worlds/smoke.wbt"
LOGSDIR="$ROOT/logs"
mkdir -p "$LOGSDIR"
# Locate the Webots executable.
WEBOTS_APP="${1:-$HOME/Applications/Webots.app}"
if [ -z "${WEBOTS_APP:-}" ] || [ ! -d "$WEBOTS_APP" ]; then
WEBOTS_APP="/Applications/Webots.app"
fi
WEBOTS_BIN="$WEBOTS_APP/Contents/MacOS/webots"
if [ ! -x "$WEBOTS_BIN" ]; then
echo "FATAL: webots binary not found at $WEBOTS_BIN" >&2
exit 2
fi
echo "webots_bin=$WEBOTS_BIN"
"$WEBOTS_BIN" --version 2>&1 | head -3
run_mode() {
local label="$1"; shift
local out="$LOGSDIR/$label.log"
echo "=== running: $label ==="
"$WEBOTS_BIN" "$@" --stdout --stderr >"$out" 2>&1
echo " exit=$? -> $out"
}
# 1. Headless fast + no-rendering + batch (CI regression path).
run_mode "fast_no_render_batch" --mode=fast --no-rendering --batch "$WORLD"
# 2. Headless fast + batch (rendering disabled only via no-rendering absent).
run_mode "fast_batch" --mode=fast --batch --minimize "$WORLD"
# 3. GUI realtime launch smoke: starts, stays alive, then terminated.
echo "=== running: gui_realtime (5s) ==="
"$WEBOTS_BIN" --mode=realtime "$WORLD" >"$LOGSDIR/gui_realtime.log" 2>&1 &
GUI_PID=$!
sleep 5
if kill -0 "$GUI_PID" 2>/dev/null; then
echo " gui_realtime alive after 5s (pid=$GUI_PID); terminating"
kill "$GUI_PID" 2>/dev/null
wait "$GUI_PID" 2>/dev/null
else
echo " gui_realtime exited early (pid=$GUI_PID); see $LOGSDIR/gui_realtime.log"
fi
echo "=== smoke run complete ==="

View File

@ -1,10 +0,0 @@
Webots Project File version R2025a
perspectives: 000000ff00000000fd00000002000000010000011c0000024dfc0200000001fb0000001400540065007800740045006400690074006f007201000000000000024d0000004500ffffff00000003000005e8000000d9fc0100000001fb0000001a0043006f006e0073006f006c00650041006c006c0041006c006c0100000000000005e80000008700ffffff000004ca0000024d00000001000000020000000100000008fc00000000
simulationViewPerspectives: 000000ff000000010000000200000114000003b60100000002010000000100
sceneTreePerspectives: 000000ff00000001000000030000011a000000f9000000000100000002010000000200
maximizedDockId: -1
centralWidgetVisible: 1
orthographicViewHeight: 1
textFiles: -1
consoles: Console:All:All
renderingDevicePerspectives: smoke_robot:camera;1;1;0;0

View File

@ -1,137 +0,0 @@
#VRML_SIM R2025a utf8
# Minimal self-made smoke world: basic Box/Cylinder geometry only.
# No official Webots sample assets (license boundary, ADR-016 §11.6).
WorldInfo {
basicTimeStep 32
}
Viewpoint {
orientation 0.2 0.1 0.3 1.0
position 0.8 0.8 1.2
}
DEF GROUND Solid {
translation 0 -0.06 0
name "ground"
children [
Shape {
appearance PBRAppearance {
baseColor 0.5 0.5 0.5
roughness 0.9
metalness 0
}
geometry Box {
size 1 0.1 1
}
}
]
boundingObject Box {
size 1 0.1 1
}
}
DEF TARGET Solid {
translation 0.25 0.05 0
name "TARGET"
children [
Shape {
appearance PBRAppearance {
baseColor 1 0 0
roughness 0.6
metalness 0
}
geometry Box {
size 0.1 0.1 0.1
}
}
]
boundingObject Box {
size 0.1 0.1 0.1
}
physics Physics {
}
}
Robot {
name "smoke_robot"
controller "rdk_smoke_robot"
supervisor FALSE
children [
Camera {
name "camera"
translation 0 0 0.06
rotation 0 1 0 1.5708
fieldOfView 1.0
width 64
height 64
near 0.01
far 10
}
DEF WHEEL HingeJoint {
jointParameters HingeJointParameters {
axis 0 1 0
anchor 0 0.15 0
}
device [
RotationalMotor {
name "motor"
maxVelocity 10
maxTorque 1
}
PositionSensor {
name "encoder"
resolution 0.01
}
]
endPoint Solid {
children [
DEF WHEEL_SHAPE Shape {
appearance PBRAppearance {
baseColor 0.2 0.2 0.2
}
geometry Cylinder {
height 0.03
radius 0.02
}
}
]
boundingObject Cylinder {
height 0.03
radius 0.02
}
physics Physics {
}
}
}
Shape {
appearance PBRAppearance {
baseColor 0 0.5 1
roughness 0.6
metalness 0
}
geometry Box {
size 0.2 0.15 0.2
}
}
]
boundingObject Box {
size 0.2 0.15 0.2
}
physics Physics {
}
}
DEF ORACLE Robot {
name "oracle_supervisor"
controller "rdk_smoke_supervisor"
supervisor TRUE
children [
Shape {
appearance PBRAppearance {
baseColor 0 0.5 0
roughness 0.6
}
geometry Box {
size 0.05 0.05 0.05
}
}
]
boundingObject Box {
size 0.05 0.05 0.05
}
}

View File

@ -5,8 +5,18 @@ Pi SDK `@earendil-works/pi-coding-agent@0.84.1`, built-in tools disabled).
The frozen System Prompt Builder v1 text precedes this section; both load
from the trusted project-local package `packages/pi-rdk-agent`.
Current lab baseline (docs/testing/CURRENT_HARDWARE_BASELINE.md): the only
M0 execution target is the deterministic fake device (`fake-001`). S100P HIL
results do not exist yet — never claim real hardware support from fixture
runs. Camera snapshot is `blocked/external_dependency` until the USB camera
arrives and AT-013 runs.
Real-device targets (S1-C/S2, verified on hardware): the RDK S100P board at
`192.168.127.10` is a first-class target. When the user names a device id
like `s100p-001`, treat it as real and proceed: call
`rdk_device_inventory(deviceId, profile=quick)` directly to get observed
facts — `rdk_device_list` only shows devices already REGISTERED in this
state dir and is empty on a fresh run, which does NOT mean the device is
unavailable. Never refuse a user-named real device merely because the list
is empty. Fake device `fake-001` is the deterministic fixture for offline
tests; do not claim real-hardware results from it, and do not fall back to
it when the user asked for a real board.
Camera snapshot on S100P is `blocked/external_dependency` until the USB
camera is attached and AT-013 runs. GPIO/PWM/servos/motors remain
unavailable (no safe hardware kit). All runs are non-root; the `s100-exec`
Helper profile serves bounded read-only/execute runs.

View File

@ -12,8 +12,13 @@ improvise device access outside these steps.
## Steps
1. **Inspect** — call `rdk_device_inspect`. If there is no snapshot or it is
stale, call `rdk_device_inventory` first. Never treat user descriptions,
aliases, or documentation as observed facts.
stale, call `rdk_device_inventory` first. `rdk_device_list` only shows
devices already REGISTERED in this state dir; it is empty on a fresh run
and that does NOT mean the user-named device is unavailable — inventory
the device id the user gave you directly (`rdk_device_inventory` with
`deviceId` and `profile`). Pass only `deviceId` and `profile`; `reason`/
`targets` are optional and the host coerces unknown values. Never treat
user descriptions, aliases, or documentation as observed facts.
2. **Write** — create/modify the program with `workspace_write` /
`workspace_patch`, then freeze it with `workspace_checkpoint`.
3. **Plan** — call `rdk_run_plan` with the minimal required capabilities.
@ -33,6 +38,117 @@ improvise device access outside these steps.
7. **Report** — call `task_report` and report run id, outcome, artifact
digests, and unresolved items. List what was tested and what was not.
## Iteration (write → fail → diagnose → fix → re-run)
A run with `state=failed` or `outcome=failed` is NOT the end — iterate until
`outcome=passed` (or the budget is exhausted):
1. **Diagnose** — `rdk_artifact_read` the output artifact and read `stdout.log`
via `rdk_run_events`; if `exit_code != 0`, the traceback is in stderr. Form
a concrete hypothesis. **If `exit_code == 0` but a `json.assert` verifier
failed, your program ran fine — the verifier's `path` or `equals` doesn't
match your output. Re-read the artifact, compare its actual shape to the
verifier config, and fix the MANIFEST's verifier (use `equals: null` to
assert a key exists when you can't predict its value) — do NOT rewrite a
program that already exits 0 and produces the right fields.**
2. **Fix** — edit the program with `workspace_patch` (keep the same `path`).
3. **Re-plan** — `rdk_run_plan` AGAIN. Editing the source changes the digest,
which INVALIDATES the old plan (AT-003); `rdk_run_start` against a stale
plan is rejected. A fresh plan binds the new source.
4. **Re-run with a NEW request_id** — `rdk_run_start` is idempotent by
`requestId`: reusing the same `requestId` returns the STORED run (the old
failed one) and executes NOTHING. Every attempt — especially after a patch
— must use a fresh, unique `requestId` (e.g. `<task>-attempt-2`).
5. Repeat until `outcome=passed`, then `task_report`.
Never reuse a `requestId` across attempts. Never `rdk_run_start` a plan whose
source you have since edited without re-planning first.
## Verifier must match your output
The `json.assert` verifier asserts a `path` and `equals` against the JSON your
program ACTUALLY writes. Before you plan, decide the exact JSON shape your
program produces and write the verifier against THAT shape — e.g. if your
program writes `{"busiest_core": "cpu3", "cores": [...]}`, the assertion is
`{"artifact": "<file>", "path": "busiest_core", "equals": <value or null>}`.
A program that runs (exit 0) but whose verifier path doesn't exist in its
output is a failed run, not a pass.
## Reconnect
After a disconnect or resume, call `task_reconcile` before any new
`rdk_run_start`: it refreshes the task's non-terminal runs from device truth
and never re-starts anything.
## Run manifest shape
`rdk_run_plan` validates the `manifest` against a fixed schema — do not invent
fields like `steps`/`intent`/`write_risk`; copy this shape exactly. Top-level
fields: `schema_version`, `name`, `entrypoint`, `requirements`, `resources`,
`artifacts`, `verifiers`. The skeleton below is SHAPE only — substitute YOUR
program's file name, artifact name, and verifier assertion; write the program
the user asked for, not this skeleton.
```json
{
"schema_version": "1.0",
"name": "<your-task-name>",
"entrypoint": { "type": "python", "path": "<your_program>.py" },
"requirements": { "capabilities": [ { "id": "<a capability the device has>" } ] },
"resources": { "wall_time_seconds": 60, "output_bytes": 65536 },
"artifacts": [
{ "name": "<your_output>.json", "path": "<your_output>.json",
"media_type": "application/json", "required": true }
],
"verifiers": [
{ "id": "exit-ok", "type": "exit_code.zero", "config": {} },
{ "id": "<result-ok>", "type": "json.assert",
"config": { "artifact": "<your_output>.json", "path": "<a field your program writes>", "equals": <value> } }
]
}
```
- `entrypoint.type` is `python` (M0/S2); `entrypoint.path` is the file you
wrote with `workspace_write`, relative to the workspace root.
- `requirements.capabilities[].id` must match a capability the inspected
device actually has (e.g. `system.info`, `usb.enumerate`).
- `artifacts[].path` is the file the program writes from its working dir;
required artifacts missing at run end leave a warning and the host verifier
fails closed — never claim success without reading the artifact back.
- `verifiers[].type` is one of `exit_code.zero` or `json.assert`. For
`json.assert`, `config` names the `artifact` and a dotted `path` into YOUR
program's actual output. Include `equals` ONLY to assert a specific value
you control and set deterministically (e.g. `sampled_seconds` == 2). For a
VARIABLE field whose value you can't predict (e.g. `busiest_core`), OMIT
`equals` entirely — that asserts the key exists and is non-null. Never set
`equals: null` (that asserts the value IS null).
- Write the program the user asked for — a self-contained Python script that
reads device facts (e.g. `/proc`, `/sys`, `shutil`) and writes the JSON
artifact whose shape your verifier asserts. Do NOT write a generic health
card unless that is literally the request.
## S100/S100P board knowledge (documentation-informed hints)
Use these to write correct programs; they are hints for code shape, NOT
observed facts — the snapshot from step 1 remains the only source of device
truth. Official references: RDK S 系列手册 `https://developer.d-robotics.cc/rdk_s_doc/RDK`,
S 系列 OE 手册 `https://developer.d-robotics.cc/oe_s_doc/index.html`,
TogetheROS.Bot 手册 `https://developer.d-robotics.cc/tros_doc/tros`,
Model Zoo `https://developer.d-robotics.cc/model_zoo_doc/model_zoo_intro`.
- OS:RDK OS 版本在 `/etc/version`;`rdkos_info` 是官方系统/硬件/BPU 信息入口
(`[CPU And BPU Status]` 段给 BPU 遥测)。S100P 为 aarch64、Ubuntu 用户态、
PREEMPT_RT 内核。
- BPU:S 系列运行时**不是** X 系列的 `libdnn*`;写 BPU 程序前按 OE 手册用
`/opt/hobot` 下的头文件/库与 hbrt 文档, capability 以快照 `bpu.inference.static`
为准。
- TROS:TogetheROS.Bot 装在 `/opt/tros/<distro>`(当前真机为 `humble`);
节点程序先 `source /opt/tros/<distro>/setup.sh`,API 以 TROS 手册为准。
- 相机:USB 摄像头走 V4L2(`/dev/video*`);无 video node 时
`camera.snapshot.usb=unavailable`,不要编造采图结果。
- 非 root 开发用户:cpufreq 等部分 sysfs 读会 EACCES,属正常;程序不要依赖
这些路径,温度用 `/sys/class/thermal/thermal_zone*/temp`。
## Never
- Never request, handle, or repeat credentials, tokens, or private keys.

View File

@ -0,0 +1,46 @@
---
name: rdk-knowledge
description: RDK 产品线与配件领域认知:板型算力/接口、OS/BPU/TROS、配件兼容与当前可用规则。让 Agent 比通用 coding agent 更懂 RDK。
version: 1.0.0
---
# rdk-knowledge
Grounded RDK domain cognition (sourced from the official doc center). Use it to
reason about boards, software and accessories — never guess specs.
## 板型与算力
**S 系(高算力机器人)**
- **RDK S100 / S100P**:80/128 TOPS 端侧推理,6 核 ARM A78AE;2 路 MIPI Camera、4 路 USB 3.0。
- **RDK S600**:560 TOPS,18 核 ARM A78AE;6 路 MIPI Camera、6 路 USB 3.0、PCIe3.0。
**X 系(入门/全功能)**
- **RDK X3 / X3 Module**:5 TOPS;Module 兼容树莓派 CM4。
- **RDK X5**:10 TOPS,8 核 ARM A55;2 路 MIPI Camera、4 路 USB 3.0。
- BPU 库经 PyPI `hobot-dnn-rdkx5`;算法接口 Python/C++。
**OS**:Ubuntu 基(X3 用 3.0/2.0,X5 3.0.0 基于 Ubuntu 22.04);`cat /etc/version`、≥2.1.0 用 `rdkos_info`。
- 板型以**盘点事实**为准(`rdk_device_inspect` 的 identity.model),不要用名字猜。
## 软件栈
- OS 版本:`cat /etc/version`;≥2.1.0 可用 `rdkos_info` 看详细版本。
- 内核/架构:`uname -a`(S100P 为 aarch64、PREEMPT_RT)。
- 机器人中间件:**TogetheROS.Bot**(TROS),装在 `/opt/tros/<distro>`(真机常见 humble)。
- 算法接口:Python / C++ 简易接口,封装自底层 BPU 推理接口;BPU 状态看 `rdkos_info` 的
`[CPU And BPU Status]` 段与 `/opt/hobot`。
## 配件与兼容(潜在可接入)
- **USB 摄像头** → 能力 `camera.snapshot.usb`(V4L2,`/dev/video*`,`lsusb` 枚举)。
- **MIPI/GMSL 相机** → S100 2 路 / S600 6 路;需相机与扩展工装,当前无相机即 unavailable。
- **双目摄像头模组**(官方手册)→ 走 MIPI/USB,需对应驱动已在系统内。
- **BMI088 IMU 模组**(官方手册)→ 走 I2C/SPI;属 GPIO 类,**无安全工装当前硬拒绝**。
- **舵机/电机/PWM/继电器** → 需安全工装+策略,当前硬拒绝(CLAUDE.md 安全规则)。
- 温度:`/sys/class/thermal/thermal_zone*/temp`(毫度→°C)。
## 用法
- 回答「这板能做什么/还缺什么」时,用上面接口/算力事实 + 盘点能力矩阵,不猜测。
- 推荐项目时先按板型/能力/配件硬过滤(CFR-014),说明「为什么能做/还缺什么」。

View File

@ -0,0 +1,24 @@
---
name: rdk-temp-watch
description: 只读读取开发板各 thermal zone 温度并汇总成 JSON,不写设备、不需模型发挥。
version: 1.0.0
---
# rdk-temp-watch
A sample installed skill showing how to add and invoke a skill. It reads
thermal zones (read-only) and summarizes them. Follow these steps exactly.
## Steps
1. **Inspect** — call `rdk_device_inspect` (refresh `quick`). Confirm the device
reports `system.info` as available; if not, stop and say the device lacks it.
2. **Write** — with `workspace_write`, create `temp_watch.py`:
read every `/sys/class/thermal/thermal_zone*/temp`, divide by 1000, and write
`{"zones":[{"name":<zone>,"celsius":<value>}...]}` to `temps.json`.
3. **Plan** — `rdk_run_plan` with requirement `system.info` only; verifier
`json.assert` on `temps.json` path `zones` (no `equals`).
4. **Run** — `rdk_run_start` with the plan; poll `rdk_run_status` until terminal.
5. **Report** — read `temps.json` via `rdk_artifact_read` and report the zones.
Never write to the device, never run arbitrary shell, never escalate risk.

View File

@ -0,0 +1,817 @@
{
"name": "@rdk/rdk-agent-desktop",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@rdk/rdk-agent-desktop",
"version": "0.1.0",
"dependencies": {
"@rdk/rdk-agent-surface": "file:../rdk-agent-surface",
"react": "18.3.1",
"react-dom": "18.3.1"
},
"devDependencies": {
"@types/node": "22.15.0",
"@types/react": "18.3.18",
"@types/react-dom": "18.3.5",
"electron": "43.4.0",
"esbuild": "^0.25.0",
"typescript": "5.8.3"
},
"engines": {
"node": ">=22.19.0"
}
},
"../rdk-agent-surface": {
"name": "@rdk/rdk-agent-surface",
"version": "0.1.0",
"dependencies": {
"@modelcontextprotocol/sdk": "1.30.0",
"@rdk/rdk-agent-pi": "file:../rdk-agent-pi",
"typebox": "1.1.24",
"zod": "3.25.76"
},
"bin": {
"rdk-agent": "dist/bin.js"
},
"devDependencies": {
"@earendil-works/pi-coding-agent": "0.84.1",
"@types/node": "22.15.0",
"typescript": "5.8.3"
},
"engines": {
"node": ">=22.19.0"
},
"peerDependencies": {
"@earendil-works/pi-coding-agent": "0.84.1"
}
},
"node_modules/@electron-internal/extract-zip": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/@electron-internal/extract-zip/-/extract-zip-1.0.5.tgz",
"integrity": "sha512-+bqFCP98pLI0Tt0XQo1TmlXtwjWchISndDOxCkEcIuUgXWpBnLyRI+2DU+mesvnMMX6L1XDqYNA0lXNDHd/yiA==",
"dev": true,
"license": "BSD-2-Clause",
"engines": {
"node": ">=22.12.0"
}
},
"node_modules/@electron/get": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/@electron/get/-/get-5.1.0.tgz",
"integrity": "sha512-3kSBtG8ObcTVfXanm5vVJ6UnBLEVmVsRk1M+vGqCuMBV+XLCbJYuWQful+yIy0GQDsSlK0kHEriEHn7SPk4EnA==",
"dev": true,
"license": "MIT",
"dependencies": {
"debug": "^4.1.1",
"env-paths": "^3.0.0",
"graceful-fs": "^4.2.11",
"progress": "^2.0.3",
"semver": "^7.6.3",
"sumchecker": "^3.0.1"
},
"engines": {
"node": ">=22.12.0"
},
"optionalDependencies": {
"undici": "^7.24.4"
}
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz",
"integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"aix"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz",
"integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz",
"integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-x64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz",
"integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-arm64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz",
"integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-x64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz",
"integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-arm64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz",
"integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-x64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz",
"integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz",
"integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz",
"integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ia32": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz",
"integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-loong64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz",
"integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==",
"cpu": [
"loong64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-mips64el": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz",
"integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==",
"cpu": [
"mips64el"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ppc64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz",
"integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-riscv64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz",
"integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==",
"cpu": [
"riscv64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-s390x": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz",
"integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==",
"cpu": [
"s390x"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-x64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz",
"integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-arm64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz",
"integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-x64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz",
"integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-arm64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz",
"integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-x64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz",
"integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openharmony-arm64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz",
"integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openharmony"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/sunos-x64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz",
"integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"sunos"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-arm64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz",
"integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-ia32": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz",
"integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-x64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz",
"integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@rdk/rdk-agent-surface": {
"resolved": "../rdk-agent-surface",
"link": true
},
"node_modules/@types/node": {
"version": "22.15.0",
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.15.0.tgz",
"integrity": "sha512-99S8dWD2DkeE6PBaEDw+In3aar7hdoBvjyJMR6vaKBTzpvR0P00ClzJMOoVrj9D2+Sy/YCwACYHnBTpMhg1UCA==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~6.21.0"
}
},
"node_modules/@types/prop-types": {
"version": "15.7.15",
"resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz",
"integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/react": {
"version": "18.3.18",
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.18.tgz",
"integrity": "sha512-t4yC+vtgnkYjNSKlFx1jkAhH8LgTo2N/7Qvi83kdEaUtMDiwpbLAktKDaAMlRcJ5eSxZkH74eEGt1ky31d7kfQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/prop-types": "*",
"csstype": "^3.0.2"
}
},
"node_modules/@types/react-dom": {
"version": "18.3.5",
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.3.5.tgz",
"integrity": "sha512-P4t6saawp+b/dFrUr2cvkVsfvPguwsxtH6dNIYRllMsefqFzkZk5UIjzyDOv5g1dXIPdG4Sp1yCR4Z6RCUsG/Q==",
"dev": true,
"license": "MIT",
"peerDependencies": {
"@types/react": "^18.0.0"
}
},
"node_modules/csstype": {
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
"dev": true,
"license": "MIT"
},
"node_modules/debug": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
"dev": true,
"license": "MIT",
"dependencies": {
"ms": "^2.1.3"
},
"engines": {
"node": ">=6.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
}
},
"node_modules/electron": {
"version": "43.4.0",
"resolved": "https://registry.npmjs.org/electron/-/electron-43.4.0.tgz",
"integrity": "sha512-3qxGF0CeQbiox5oWV1JlbWGQ1VerbmDhTFqW4sJ8h7uqTHniFYPObXJcDna0DMh32et0fFyKzz0YY8lJv3t5jg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@electron-internal/extract-zip": "^1.0.1",
"@electron/get": "^5.0.0",
"@types/node": "^24.9.0"
},
"bin": {
"electron": "cli.js",
"install-electron": "install.js"
},
"engines": {
"node": ">= 22.12.0"
}
},
"node_modules/electron/node_modules/@types/node": {
"version": "24.13.3",
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.13.3.tgz",
"integrity": "sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~7.18.0"
}
},
"node_modules/electron/node_modules/undici-types": {
"version": "7.18.2",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz",
"integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==",
"dev": true,
"license": "MIT"
},
"node_modules/env-paths": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/env-paths/-/env-paths-3.0.0.tgz",
"integrity": "sha512-dtJUTepzMW3Lm/NPxRf3wP4642UWhjL2sQxc+ym2YMj1m/H2zDNQOlezafzkHwn6sMstjHTwG6iQQsctDW/b1A==",
"dev": true,
"license": "MIT",
"engines": {
"node": "^12.20.0 || ^14.13.1 || >=16.0.0"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/esbuild": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz",
"integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"bin": {
"esbuild": "bin/esbuild"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"@esbuild/aix-ppc64": "0.25.12",
"@esbuild/android-arm": "0.25.12",
"@esbuild/android-arm64": "0.25.12",
"@esbuild/android-x64": "0.25.12",
"@esbuild/darwin-arm64": "0.25.12",
"@esbuild/darwin-x64": "0.25.12",
"@esbuild/freebsd-arm64": "0.25.12",
"@esbuild/freebsd-x64": "0.25.12",
"@esbuild/linux-arm": "0.25.12",
"@esbuild/linux-arm64": "0.25.12",
"@esbuild/linux-ia32": "0.25.12",
"@esbuild/linux-loong64": "0.25.12",
"@esbuild/linux-mips64el": "0.25.12",
"@esbuild/linux-ppc64": "0.25.12",
"@esbuild/linux-riscv64": "0.25.12",
"@esbuild/linux-s390x": "0.25.12",
"@esbuild/linux-x64": "0.25.12",
"@esbuild/netbsd-arm64": "0.25.12",
"@esbuild/netbsd-x64": "0.25.12",
"@esbuild/openbsd-arm64": "0.25.12",
"@esbuild/openbsd-x64": "0.25.12",
"@esbuild/openharmony-arm64": "0.25.12",
"@esbuild/sunos-x64": "0.25.12",
"@esbuild/win32-arm64": "0.25.12",
"@esbuild/win32-ia32": "0.25.12",
"@esbuild/win32-x64": "0.25.12"
}
},
"node_modules/graceful-fs": {
"version": "4.2.11",
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
"integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
"dev": true,
"license": "ISC"
},
"node_modules/js-tokens": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
"integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
"license": "MIT"
},
"node_modules/loose-envify": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
"integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
"license": "MIT",
"dependencies": {
"js-tokens": "^3.0.0 || ^4.0.0"
},
"bin": {
"loose-envify": "cli.js"
}
},
"node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"dev": true,
"license": "MIT"
},
"node_modules/progress": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz",
"integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/react": {
"version": "18.3.1",
"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
"integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
"license": "MIT",
"dependencies": {
"loose-envify": "^1.1.0"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/react-dom": {
"version": "18.3.1",
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",
"integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
"license": "MIT",
"dependencies": {
"loose-envify": "^1.1.0",
"scheduler": "^0.23.2"
},
"peerDependencies": {
"react": "^18.3.1"
}
},
"node_modules/scheduler": {
"version": "0.23.2",
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz",
"integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==",
"license": "MIT",
"dependencies": {
"loose-envify": "^1.1.0"
}
},
"node_modules/semver": {
"version": "7.8.5",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
"integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
"dev": true,
"license": "ISC",
"bin": {
"semver": "bin/semver.js"
},
"engines": {
"node": ">=10"
}
},
"node_modules/sumchecker": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/sumchecker/-/sumchecker-3.0.1.tgz",
"integrity": "sha512-MvjXzkz/BOfyVDkG0oFOtBxHX2u3gKbMHIF/dXblZsgD3BWOFLmHovIpZY7BykJdAjcqRCBi1WYBNdEC9yI7vg==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"debug": "^4.1.0"
},
"engines": {
"node": ">= 8.0"
}
},
"node_modules/typescript": {
"version": "5.8.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.3.tgz",
"integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=14.17"
}
},
"node_modules/undici": {
"version": "7.29.0",
"resolved": "https://registry.npmjs.org/undici/-/undici-7.29.0.tgz",
"integrity": "sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw==",
"dev": true,
"license": "MIT",
"optional": true,
"engines": {
"node": ">=20.18.1"
}
},
"node_modules/undici-types": {
"version": "6.21.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
"dev": true,
"license": "MIT"
}
}
}

View File

@ -0,0 +1,30 @@
{
"name": "@rdk/rdk-agent-desktop",
"version": "0.1.0",
"private": true,
"description": "RDK Agent Electron desktop shell, macOS-first (ADR-014, docs/12 §5)",
"type": "module",
"main": "dist/main.js",
"engines": {
"node": ">=22.19.0"
},
"scripts": {
"typecheck": "tsc -p tsconfig.typecheck.json",
"build": "npm run typecheck && tsc -p tsconfig.json && esbuild src/preload.ts --bundle --format=cjs --external:electron --outfile=dist/preload.cjs && mkdir -p dist/renderer && cp src/renderer/index.html dist/renderer/ && esbuild src/renderer/index.tsx --bundle --format=esm --jsx=automatic --define:process.env.NODE_ENV=\\\"production\\\" --outfile=dist/renderer/index.js",
"test": "rm -rf dist-test && tsc -p tsconfig.test.json && node --test dist-test/test/*.test.js",
"start": "electron ."
},
"dependencies": {
"@rdk/rdk-agent-surface": "file:../rdk-agent-surface",
"react": "18.3.1",
"react-dom": "18.3.1"
},
"devDependencies": {
"@types/node": "22.15.0",
"@types/react": "18.3.18",
"@types/react-dom": "18.3.5",
"electron": "43.4.0",
"esbuild": "^0.25.0",
"typescript": "5.8.3"
}
}

View File

@ -0,0 +1,40 @@
/**
* Minimal cwd-independent static server for the built renderer
* (visual QA in the preview pane): `node scripts/static-server.mjs`.
* Serves packages/rdk-agent-desktop/dist/renderer on port 4173.
*/
import { readFile } from "node:fs/promises";
import { createServer } from "node:http";
import { dirname, extname, join, normalize } from "node:path";
import { fileURLToPath } from "node:url";
const root = join(dirname(fileURLToPath(import.meta.url)), "..", "dist", "renderer");
const TYPES = {
".html": "text/html; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".svg": "image/svg+xml",
".json": "application/json",
};
createServer((req, res) => {
const url = new URL(req.url ?? "/", "http://localhost");
let path = normalize(decodeURIComponent(url.pathname));
if (path === "/" || path === "\\" ) path = "/index.html";
const file = join(root, path);
if (!file.startsWith(root)) {
res.writeHead(403).end();
return;
}
readFile(file)
.then((buf) => {
res.writeHead(200, { "content-type": TYPES[extname(file)] ?? "application/octet-stream" });
res.end(buf);
})
.catch(() => {
res.writeHead(404).end();
});
}).listen(4173, () => {
console.log("rdk renderer static server on http://localhost:4173");
});

View File

@ -0,0 +1,225 @@
/**
* Saved device connections (docs/06 §8.1, S4 device center).
*
* A persisted list of SSH connections the GUI manages, so the product launches
* without RDK_DEVICE_COMMAND / RDK_TICKET_KEY env. The ticket HMAC key is a
* secret — it lives in the macOS keychain (or a 0600 keyfile on other
* platforms), never in the JSON. The host key is pinned by TOFU on first add:
* keyscan → store the fingerprint; future connects verify it against
* StrictHostKeyChecking.
*/
import { execSync } from "node:child_process";
import { existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync, appendFileSync } from "node:fs";
import { join } from "node:path";
export interface DeviceConnection {
name: string;
host: string; // user@host or bare host
user: string;
device_id: string;
helper_profile: string; // s100-readonly | s100-exec
remote_helper_path: string; // ~/.rdk/bin/rdk-agent-device
known_hosts: string; // absolute path to the product known_hosts file
host_key_sha256?: string; // pinned fingerprint (TOFU on first add)
ticket_keychain_account: string; // keychain account holding the hex key
}
const KEYCHAIN_SERVICE = "rdk-device";
function readKeychain(account: string): string | undefined {
if (process.platform !== "darwin") return undefined;
try {
const out = execSync(
`security find-generic-password -s ${KEYCHAIN_SERVICE} -a ${account} -w`,
{ stdio: ["ignore", "pipe", "ignore"], encoding: "utf8" },
).trim();
return out || undefined;
} catch {
return undefined;
}
}
function writeKeychain(account: string, key: string): void {
if (process.platform !== "darwin") return;
// Delete any prior entry (ignore errors) then add.
try {
execSync(`security delete-generic-password -s ${KEYCHAIN_SERVICE} -a ${account}`, {
stdio: "ignore",
});
} catch {
// not present
}
execSync(
`security add-generic-password -s ${KEYCHAIN_SERVICE} -a ${account} -w ${key}`,
{ stdio: "ignore" },
);
}
function deleteKeychain(account: string): void {
if (process.platform !== "darwin") return;
try {
execSync(`security delete-generic-password -s ${KEYCHAIN_SERVICE} -a ${account}`, {
stdio: "ignore",
});
} catch {
// not present
}
}
/** A non-macOS fallback: a 0600 keyfile under the data dir. */
function keyfilePath(dataDir: string, account: string): string {
return join(dataDir, `${account}.key`);
}
function readKeyfile(p: string): string | undefined {
if (!existsSync(p)) return undefined;
try {
return readFileSync(p, "utf8").trim() || undefined;
} catch {
return undefined;
}
}
function writeKeyfile(p: string, key: string): void {
mkdirSync(join(p, ".."), { recursive: true });
writeFileSync(p, key, { encoding: "utf8", mode: 0o600 });
try {
chmodSync(p, 0o600);
} catch {
// best-effort
}
}
export class ConnectionStore {
private readonly file: string;
private readonly dataDir: string;
constructor(dataDir: string) {
this.dataDir = dataDir;
mkdirSync(dataDir, { recursive: true });
this.file = join(dataDir, "device-connections.json");
if (!existsSync(this.file)) {
writeFileSync(this.file, "[]", { encoding: "utf8", mode: 0o600 });
}
try {
chmodSync(this.file, 0o600);
} catch {
// best-effort
}
}
list(): DeviceConnection[] {
try {
return JSON.parse(readFileSync(this.file, "utf8")) as DeviceConnection[];
} catch {
return [];
}
}
get(name: string): DeviceConnection | undefined {
return this.list().find((c) => c.name === name);
}
/** Add or replace a connection. The ticket key goes to the keychain/keyfile. */
save(conn: DeviceConnection, ticketKey: string): DeviceConnection {
const all = this.list().filter((c) => c.name !== conn.name);
all.push(conn);
writeFileSync(this.file, JSON.stringify(all, null, 2), {
encoding: "utf8",
mode: 0o600,
});
if (process.platform === "darwin") {
writeKeychain(conn.ticket_keychain_account, ticketKey);
} else {
writeKeyfile(keyfilePath(this.dataDir, conn.ticket_keychain_account), ticketKey);
}
return conn;
}
remove(name: string): void {
const conn = this.get(name);
if (!conn) return;
const all = this.list().filter((c) => c.name !== name);
writeFileSync(this.file, JSON.stringify(all, null, 2), {
encoding: "utf8",
mode: 0o600,
});
if (process.platform === "darwin") {
deleteKeychain(conn.ticket_keychain_account);
}
try {
const p = keyfilePath(this.dataDir, conn.ticket_keychain_account);
if (existsSync(p)) writeFileSync(p, "", { mode: 0o600 });
} catch {
// ignore
}
}
/** Resolve the ticket key for a connection (keychain first, then keyfile). */
resolveTicketKey(conn: DeviceConnection): string | undefined {
const chain = readKeychain(conn.ticket_keychain_account);
if (chain) return chain;
return readKeyfile(keyfilePath(this.dataDir, conn.ticket_keychain_account));
}
}
/** TOFU: keyscan the host, append its key to the product known_hosts, return
* the SHA256 fingerprint. */
export function keyscanAndPin(host: string, knownHosts: string): string | null {
mkdirSync(join(knownHosts, ".."), { recursive: true });
// ssh-keyscan -t ed25519 <host>; capture the line + fingerprint.
let line = "";
try {
line = execSync(`ssh-keyscan -t ed25519 ${host} 2>/dev/null`, {
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
}).trim();
} catch {
return null;
}
if (!line) return null;
appendFileSync(knownHosts, line + "\n", { encoding: "utf8", mode: 0o600 });
// Fingerprint via ssh-keygen -lf on the known_hosts file.
try {
const fp = execSync(`ssh-keygen -lf ${knownHosts}`, {
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
});
// first line: "256 SHA256:xxxxx <host> (ED25519)"
const first = fp.split("\n")[0] ?? "";
const m = first.match(/SHA256:[A-Za-z0-9+/]+/);
return m ? m[0] : null;
} catch {
return null;
}
}
/** Build the RDK_DEVICE_COMMAND ssh argv string for a saved connection. */
export function buildSshDeviceCommand(conn: DeviceConnection): string {
const opts = [
"ssh",
"-o BatchMode=yes",
"-o ConnectTimeout=10",
"-o StrictHostKeyChecking=yes",
`-o UserKnownHostsFile=${conn.known_hosts}`,
`${conn.user}@${conn.host}`,
"--",
conn.remote_helper_path,
"serve",
"--stdio",
"--profile",
conn.helper_profile,
"--device-id",
conn.device_id,
];
return opts.join(" ");
}
/** The default product known_hosts path under the data dir. */
export function defaultKnownHosts(dataDir: string): string {
return join(dataDir, "known_hosts");
}
/** Convenience: the default remote helper path on the board. */
export const DEFAULT_REMOTE_HELPER = "~/.rdk/bin/rdk-agent-device";

View File

@ -0,0 +1,41 @@
/**
* Electron bootstrap entry (ADR-014 §5, S1-B §6).
*
* The ONLY responsibility of this module is the Node version guard, which MUST
* run before any Pi SDK / surface import loads. Static ESM imports are hoisted
* and resolve their whole dependency graph before this module's body runs, so
* the real logic intentionally lives in `mainImpl.ts` and is imported
* dynamically only after the guard has passed. Electron 34 ships Node 20.18.1,
* below the project floor (>=22.19), which makes Pi SDK / undici crash with an
* opaque `webidl.util.markAsUncloneable`; fail fast instead.
*/
const MIN_NODE = [22, 19, 0] as const;
const parts = process.versions.node.split(".");
const actual = [0, 0, 0];
for (let i = 0; i < Math.min(parts.length, 3); i += 1) {
actual[i] = parseInt(parts[i]!, 10);
}
const supported =
actual[0]! > MIN_NODE[0] ||
(actual[0]! === MIN_NODE[0] && actual[1]! > MIN_NODE[1]) ||
(actual[0]! === MIN_NODE[0] && actual[1]! === MIN_NODE[1] && actual[2]! >= MIN_NODE[2]);
if (!supported) {
console.error(
`RDK Agent Desktop requires Node >= ${MIN_NODE.join(".")}. ` +
`Electron provides Node ${process.versions.node}. ` +
`Upgrade Electron to >= 43.x (ships Node 24.17.0).`,
);
process.exit(1);
}
// Guard passed: now it is safe to load the surface → Pi SDK dependency graph.
void import("./mainImpl.js")
.then(({ main }) => main())
.catch((err: unknown) => {
console.error("RDK Agent Desktop failed to start:", err);
process.exit(1);
});

View File

@ -0,0 +1,382 @@
/**
* Electron main process logic (ADR-014 §5, docs/12 §5, S1-B §7).
*
* One BrowserWindow with sandbox + context isolation + no Node integration; the
* renderer loads only bundled local resources and cannot navigate to remote
* pages or open new windows. Task/device IPC handlers delegate to the SAME
* TaskService / DeviceService as CLI, TUI and MCP — the renderer never holds a
* service and never talks to the Host directly.
*
* Loaded via dynamic import from `main.ts` (the bootstrap) AFTER the Node
* version guard has passed, so the surface → Pi SDK dependency graph is never
* resolved on an unsupported runtime.
*/
import { existsSync, mkdirSync, readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { app, BrowserWindow, ipcMain } from "electron";
import {
DeviceService,
ProjectService,
TaskService,
buildTaskService,
defaultRealModelDotEnvPath,
listSkills,
readSkill,
resolveRealModelConfig,
writeRealModelDotEnv,
} from "@rdk/rdk-agent-surface";
import {
BROWSER_WINDOW_WEB_PREFERENCES,
isAllowedRendererNavigation,
} from "./security.js";
import {
DEFAULT_REMOTE_HELPER,
ConnectionStore,
buildSshDeviceCommand,
defaultKnownHosts,
keyscanAndPin,
} from "./deviceConnections.js";
// ESM has no __dirname; derive it from this module's URL (ADR-014 §5).
const __dirname = dirname(fileURLToPath(import.meta.url));
let win: BrowserWindow | null = null;
let connections: ConnectionStore | null = null;
/**
* Saved SSH connection → launch env (ticket key from keychain/keyfile), so
* the GUI launches with no env at all. Explicit env always wins (CLI users).
*/
function applyActiveConnection(): void {
if (!connections) return;
if (process.env.RDK_DEVICE_COMMAND) return;
const conn = connections.list()[0];
if (!conn) return;
process.env.RDK_DEVICE_COMMAND = buildSshDeviceCommand(conn);
process.env.RDK_DEVICE_ID = conn.device_id;
const key = connections.resolveTicketKey(conn);
if (key) process.env.RDK_TICKET_KEY = key;
}
let taskService: TaskService | null = null;
let deviceService: DeviceService | null = null;
let projectService: ProjectService | null = null;
/** Secret-free local facts for the settings page (values never cross). */
function settingsInfo(): Record<string, unknown> {
let version = "0.0.0";
try {
const pkg = JSON.parse(
readFileSync(join(__dirname, "..", "package.json"), "utf-8"),
) as { version?: string };
version = pkg.version ?? version;
} catch {
version = "unknown";
}
return {
version,
state_dir: process.env.RDK_STATE_DIR ?? ".rdk/state",
workspace_root: resolveWorkspace(),
model_gateway_configured: existsSync(join(process.env.HOME ?? "", ".rdk", ".env")),
remote_helper_profile: process.env.RDK_REMOTE_HELPER_PROFILE ?? "s100-readonly",
platform: process.platform,
};
}
function createWindow(): Promise<void> {
win = new BrowserWindow({
width: 1200,
height: 800,
minWidth: 960,
minHeight: 640,
backgroundColor: "#f2f4f9",
// macOS-first (ADR-012/ADR-014): hide the native title bar and let the
// sidebar act as the drag region (see styles.css). Other platforms keep
// their normal frame; these options are ignored there.
titleBarStyle: "hiddenInset",
trafficLightPosition: { x: 22, y: 24 },
webPreferences: { ...BROWSER_WINDOW_WEB_PREFERENCES, preload: join(__dirname, "preload.cjs") },
});
const renderer = fileURLToPath(new URL("./renderer/index.html", import.meta.url));
const rendererUrl = pathToFileURL(renderer).href;
// Block every navigation that is NOT the exact packaged renderer entry. A
// bare `file:` allowlist would let ANY local HTML load into this window and
// receive its preload bridge (task/device authority), so we compare full URLs
// (ADR-014 §5).
win.webContents.on("will-navigate", (event, url) => {
if (!isAllowedRendererNavigation(url, rendererUrl)) {
event.preventDefault();
}
});
win.webContents.setWindowOpenHandler(() => ({ action: "deny" }));
win.on("closed", () => {
win = null;
});
// Await the load, then confirm the preload bridge is actually exposed. This
// readiness gate is what the real-launch smoke depends on — it must not fire
// before the renderer/preload has mounted (P1: the smoke previously ignored
// the loadFile promise and could run/exit before React or preload mounted).
return win.loadFile(renderer).then(async () => {
const ready = await win!.webContents.executeJavaScript(
"typeof window.rdk !== 'undefined'",
);
if (ready !== true) {
throw new Error("renderer loaded but the preload bridge was not exposed");
}
});
}
/**
* Resolve the workspace root WITHOUT ever silently falling back to the user's
* home directory (docs/S1-B §6, S1-B-PLAN §6):
* - `RDK_WORKSPACE_ROOT` is honored verbatim (TaskService validates it and
* fails on a missing/non-absolute path);
* - otherwise the product-owned data dir's `workspaces/` subdir (userData, not
* home) is used and created on demand.
*/
function resolveWorkspace(): string {
const explicit = process.env.RDK_WORKSPACE_ROOT;
if (explicit) {
// Caller-provided root is validated verbatim by TaskService (fails on a
// missing/non-absolute/non-directory path) — do not create it silently.
return explicit;
}
// Product-owned default, never home: create under userData on demand.
const root = join(app.getPath("userData"), "workspaces");
mkdirSync(root, { recursive: true });
return root;
}
function wireIpc(): void {
ipcMain.handle("task:list", () => taskService?.listTasks() ?? []);
ipcMain.handle("task:start", (_e, input) =>
taskService!.startTask(input.goal, input.workspace, input.device_ids ?? [], input.mode, "gui"),
);
ipcMain.handle("task:status", (_e, taskId: string) => taskService!.getTask(taskId));
ipcMain.handle("task:steer", (_e, { taskId, message }) =>
taskService!.steerTask(taskId, message, "gui"),
);
ipcMain.handle("task:cancel", (_e, { taskId, reason }) =>
taskService!.cancelTask(taskId, reason ?? "", "gui"),
);
ipcMain.handle("task:resume", (_e, { taskId, takeOver }) =>
taskService!.resumeTask(taskId, "gui", takeOver ?? false),
);
ipcMain.handle("task:approvals", () => taskService?.listApprovals() ?? []);
ipcMain.handle("task:decide", (_e, { approvalId, approve, reason }) =>
taskService!.decideApproval(approvalId, approve, reason ?? ""),
);
ipcMain.handle("device:list", () => deviceService!.listDevices());
ipcMain.handle("device:inspect", (_e, { deviceId, refresh }) =>
deviceService!.inspectDevice(deviceId, refresh ?? "cached"),
);
// Human connect flow: the renderer only ever sees sanitized fingerprints.
ipcMain.handle("device:show-host-key", (_e, { host }) => deviceService!.showHostKey(host));
ipcMain.handle("device:confirm-host-key", (_e, { candidateId }) =>
deviceService!.confirmHostKey(candidateId),
);
ipcMain.handle("device:register", (_e, input) => deviceService!.registerDevice(input));
ipcMain.handle("device:discover", () => deviceService!.discoverDevices());
ipcMain.handle("device:auth-check", (_e, { host }) => deviceService!.authCheck(host));
ipcMain.handle("device:onboard-key", (_e, input) => deviceService!.onboardKey(input));
ipcMain.handle("device:unregister", (_e, { deviceId }) =>
deviceService!.unregisterDevice(deviceId),
);
ipcMain.handle("project:list", (_e, { path, workspaceId }) =>
projectService!.listEntries(path ?? ".", workspaceId ?? "."),
);
ipcMain.handle("project:read", (_e, { path, workspaceId }) =>
projectService!.readFile(path, workspaceId ?? "."),
);
ipcMain.handle("project:write", (_e, { path, content, workspaceId }) =>
projectService!.writeFile(path, content, workspaceId ?? "."),
);
ipcMain.handle("settings:info", () => settingsInfo());
ipcMain.handle("pack:list", () => taskService?.listPacks() ?? { packs: [] });
ipcMain.handle("pack:run", (_e, { name, deviceId, requestId }) =>
taskService!.runPack(name, deviceId, requestId),
);
// Model settings (docs/08 §8): read masks the key; write replaces ~/.rdk/.env.
ipcMain.handle("config:get", () => {
const c = resolveRealModelConfig();
if (!c) return { configured: false };
const k = c.apiKey;
return {
configured: true,
baseUrl: c.baseUrl,
model: c.model,
api: c.api,
keyHint: k.length > 4 ? `••••${k.slice(-4)}` : "••••",
};
});
ipcMain.handle("config:test", async () => {
const c = resolveRealModelConfig();
if (!c) return { ok: false, error: "not configured" };
const started = Date.now();
try {
const res = await fetch(`${c.baseUrl.replace(/\/$/, "")}/models`, {
headers: { Authorization: `Bearer ${c.apiKey}` },
});
return { ok: res.ok, status: res.status, latency_ms: Date.now() - started };
} catch (err) {
return { ok: false, error: err instanceof Error ? err.message : String(err) };
}
});
ipcMain.handle("config:set", (_e, input) => {
const existing = resolveRealModelConfig();
const apiKey =
input.apiKey && input.apiKey.trim() ? input.apiKey.trim() : (existing?.apiKey ?? "");
if (!apiKey) {
return { ok: false, error: "no API key (set one to use a real model)" };
}
writeRealModelDotEnv(defaultRealModelDotEnvPath(), {
baseUrl: input.baseUrl,
apiKey,
model: input.model,
api: input.api,
});
return { ok: true };
});
// Saved SSH connections (ticket key in keychain / 0600 keyfile).
ipcMain.handle("connection:list", () =>
(connections?.list() ?? []).map((c) => ({
name: c.name,
host: c.host,
user: c.user,
device_id: c.device_id,
helper_profile: c.helper_profile,
host_key_sha256: c.host_key_sha256 ?? "",
})),
);
ipcMain.handle("connection:add", (_e, input) => {
if (!connections) return { ok: false, error: "store not ready" };
const knownHosts = defaultKnownHosts(join(app.getPath("userData"), "connections"));
const fp = keyscanAndPin(input.host, knownHosts);
connections.save(
{
name: input.name,
host: input.host,
user: input.user,
device_id: input.device_id,
helper_profile: input.helper_profile ?? "s100-exec",
remote_helper_path: DEFAULT_REMOTE_HELPER,
known_hosts: knownHosts,
ticket_keychain_account: `ticket-${input.device_id}`,
...(fp ? { host_key_sha256: fp } : {}),
},
input.ticketKey,
);
applyActiveConnection();
return { ok: true, host_key_sha256: fp ?? "(keyscan failed; verify manually)" };
});
ipcMain.handle("connection:remove", (_e, { name }) => {
connections?.remove(name);
return { ok: true };
});
ipcMain.handle("console:ports", () => deviceService!.listSerialPorts());
ipcMain.handle("console:tail", (_e, { port, maxLines }) =>
deviceService!.tailSerial(port, maxLines ?? 200),
);
ipcMain.handle("flash:images", (_e, { boardModel }) => deviceService!.flashImages(boardModel));
ipcMain.handle("flash:suggest", (_e, input) => deviceService!.suggestFlash(input));
ipcMain.handle("flash:confirm", (_e, { flashId }) => deviceService!.confirmFlash(flashId));
ipcMain.handle("flash:run", (_e, { flashId }) => deviceService!.runFlash(flashId));
ipcMain.handle("flash:status", (_e, { flashId }) => deviceService!.flashStatus(flashId));
ipcMain.handle("flash:cancel", (_e, { flashId }) => deviceService!.cancelFlash(flashId));
ipcMain.handle("template:list", (_e, { deviceId }) => deviceService!.listTemplates(deviceId));
ipcMain.handle("template:run", (_e, { name, deviceId, requestId }) =>
deviceService!.runTemplate(name, deviceId, requestId),
);
ipcMain.handle("skill:list", () => listSkills());
ipcMain.handle("skill:read", (_e, { name }) => readSkill(name));
ipcMain.on("window:open-gui", () => win?.show());
}
export function main(): void {
// Screen readers and automated accessibility tools see the renderer tree.
app.commandLine.appendSwitch("force-renderer-accessibility");
void app.whenReady().then(async () => {
const workspaceRoot = resolveWorkspace();
connections = new ConnectionStore(join(app.getPath("userData"), "connections"));
applyActiveConnection(); // saved conn → RDK_DEVICE_COMMAND/TICKET_KEY (env wins)
taskService = buildTaskService(workspaceRoot);
deviceService = new DeviceService();
projectService = new ProjectService();
wireIpc();
await createWindow();
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) void createWindow();
});
if (process.env.RDK_DESKTOP_SMOKE === "1") {
await runSmoke();
}
});
app.on("window-all-closed", async () => {
await taskService?.close();
await deviceService?.close();
await projectService?.close();
app.quit();
});
}
/**
* Real-launch smoke (S1-B §8, gated by RDK_DESKTOP_SMOKE=1): after the window
* is up, start one health-card task through the SAME TaskService the CLI/TUI/
* MCP adapters use, print a sentinel, and tear down cleanly. The smoke proves
* the GUI main process reaches a real Host + Device and leaves no children.
*/
async function runSmoke(): Promise<void> {
const service = taskService;
if (service === null) {
process.stderr.write("DESKTOP_SMOKE_FAIL taskService not initialized\n");
app.exit(1);
return;
}
let code = 0;
try {
const handle = await service.startTask("桌面健康卡冒烟", ".", ["fake-001"], "guide", "gui");
process.stderr.write(
`DESKTOP_SMOKE_OK task=${handle.task_id} state=${handle.state} cursor=${handle.cursor}\n`,
);
} catch (err) {
process.stderr.write(`DESKTOP_SMOKE_FAIL ${err instanceof Error ? err.message : String(err)}\n`);
code = 1;
}
if (process.env.RDK_DESKTOP_REAL_SMOKE === "1") {
try {
const deviceId = process.env.RDK_SMOKE_DEVICE_ID;
if (!deviceId) {
process.stderr.write("DESKTOP_REAL_SMOKE_FAIL missing RDK_SMOKE_DEVICE_ID\n");
code = 1;
} else {
const rows = await deviceService!.listDevices();
const row = rows.find((r) => r.device_id === deviceId);
const result = (await deviceService!.inspectDevice(deviceId, "full")) as {
snapshot?: { inventory?: { probe_set_version?: string; completeness?: string } };
};
const inv = result.snapshot?.inventory ?? {};
process.stderr.write(
`DESKTOP_REAL_SMOKE_OK confirmed=${row?.host_key_confirmed ?? false} ` +
`probe_set=${inv.probe_set_version ?? "?"} completeness=${inv.completeness ?? "?"}\n`,
);
}
} catch (err) {
process.stderr.write(
`DESKTOP_REAL_SMOKE_FAIL ${err instanceof Error ? err.message : String(err)}\n`,
);
code = 1;
}
}
await service.close();
await deviceService?.close();
app.exit(code);
}

View File

@ -0,0 +1,88 @@
/**
* Preload bridge (ADR-014 §5). The ONLY thing the renderer can touch.
*
* Exposes named, typed per-namespace actions via `contextBridge` — never
* `ipcRenderer`, `shell`, arbitrary paths, credentials, or process spawn. The
* renderer is sandboxed and context-isolated, so this is the entire authority
* surface available to it. Namespace whitelist: security.ts PRELOAD_EXPOSED_KEYS.
*/
import { contextBridge, ipcRenderer } from "electron";
import type { PreloadApi } from "./security.js";
const api: PreloadApi = {
task: {
list: () => ipcRenderer.invoke("task:list"),
start: (input) => ipcRenderer.invoke("task:start", input),
status: (taskId) => ipcRenderer.invoke("task:status", taskId),
steer: (taskId, message) => ipcRenderer.invoke("task:steer", { taskId, message }),
cancel: (taskId, reason) => ipcRenderer.invoke("task:cancel", { taskId, reason }),
resume: (taskId, takeOver) => ipcRenderer.invoke("task:resume", { taskId, takeOver }),
approvals: () => ipcRenderer.invoke("task:approvals"),
decide: (approvalId, approve, reason) =>
ipcRenderer.invoke("task:decide", { approvalId, approve, reason }),
},
device: {
list: () => ipcRenderer.invoke("device:list"),
inspect: (deviceId, refresh) => ipcRenderer.invoke("device:inspect", { deviceId, refresh }),
showHostKey: (host) => ipcRenderer.invoke("device:show-host-key", { host }),
confirmHostKey: (candidateId) =>
ipcRenderer.invoke("device:confirm-host-key", { candidateId }),
registerDevice: (input) => ipcRenderer.invoke("device:register", input),
discoverDevices: () => ipcRenderer.invoke("device:discover"),
authCheck: (host) => ipcRenderer.invoke("device:auth-check", { host }),
onboardKey: (input) => ipcRenderer.invoke("device:onboard-key", input),
unregisterDevice: (deviceId) => ipcRenderer.invoke("device:unregister", { deviceId }),
},
window: {
openGui: () => ipcRenderer.send("window:open-gui"),
},
project: {
list: (path, workspaceId) => ipcRenderer.invoke("project:list", { path, workspaceId }),
read: (path, workspaceId) => ipcRenderer.invoke("project:read", { path, workspaceId }),
write: (path, content, workspaceId) =>
ipcRenderer.invoke("project:write", { path, content, workspaceId }),
},
settings: {
info: () => ipcRenderer.invoke("settings:info"),
},
pack: {
list: () => ipcRenderer.invoke("pack:list"),
run: (name, deviceId, requestId) =>
ipcRenderer.invoke("pack:run", { name, deviceId, requestId }),
},
config: {
get: () => ipcRenderer.invoke("config:get"),
set: (input) => ipcRenderer.invoke("config:set", input),
test: () => ipcRenderer.invoke("config:test"),
},
connection: {
list: () => ipcRenderer.invoke("connection:list"),
add: (input) => ipcRenderer.invoke("connection:add", input),
remove: (name) => ipcRenderer.invoke("connection:remove", { name }),
},
console: {
ports: () => ipcRenderer.invoke("console:ports"),
tail: (port, maxLines) => ipcRenderer.invoke("console:tail", { port, maxLines }),
},
flash: {
images: (boardModel) => ipcRenderer.invoke("flash:images", { boardModel }),
suggest: (input) => ipcRenderer.invoke("flash:suggest", input),
confirm: (flashId) => ipcRenderer.invoke("flash:confirm", { flashId }),
run: (flashId) => ipcRenderer.invoke("flash:run", { flashId }),
status: (flashId) => ipcRenderer.invoke("flash:status", { flashId }),
cancel: (flashId) => ipcRenderer.invoke("flash:cancel", { flashId }),
},
template: {
list: (deviceId) => ipcRenderer.invoke("template:list", { deviceId }),
run: (name, deviceId, requestId) =>
ipcRenderer.invoke("template:run", { name, deviceId, requestId }),
},
skill: {
list: () => ipcRenderer.invoke("skill:list"),
read: (name) => ipcRenderer.invoke("skill:read", { name }),
},
};
contextBridge.exposeInMainWorld("rdk", api);

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,14 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="color-scheme" content="light" />
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'" />
<title>RDK Agent</title>
<link rel="stylesheet" href="./index.css" />
</head>
<body>
<div id="root"></div>
<script type="module" src="./index.js"></script>
</body>
</html>

View File

@ -0,0 +1,12 @@
import { createRoot } from "react-dom/client";
import { App } from "./App.js";
import "./styles.css";
const container = document.getElementById("root");
if (container) {
createRoot(container).render(<App />);
// Positive renderer-mount signal for the real-launch smoke (visible only when
// ELECTRON_ENABLE_LOGGING=1); carries no user data.
console.log("RDK_RENDERER_MOUNTED");
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,172 @@
/**
* Desktop security contract (ADR-014 §5, docs/12 §5, S1-B §7).
*
* Pure, electron-free constants so the security posture is unit-testable
* without a running Electron. `main.ts`/`preload.ts` are the only modules that
* import `electron` and they are built from these constants.
*
* Invariants:
* - the renderer is sandboxed, context-isolated, and has no Node integration;
* - only bundled local resources load; remote navigation and window.open are
* denied;
* - the preload bridge exposes ONLY named per-namespace actions — never
* `ipcRenderer`, `shell`, arbitrary paths, credentials, or process spawn.
*/
export const BROWSER_WINDOW_WEB_PREFERENCES = {
contextIsolation: true,
sandbox: true,
nodeIntegration: false,
} as const;
/** Navigation must land on the EXACT packaged renderer entry — not a scheme. */
export function isAllowedRendererNavigation(target: string, rendererUrl: string): boolean {
return target === rendererUrl;
}
/** Preload bridge exposes exactly these top-level namespaces. */
export const PRELOAD_EXPOSED_KEYS = [
"task",
"device",
"window",
"project",
"settings",
"pack",
"config",
"connection",
"console",
"flash",
"template",
"skill",
] as const;
export type PreloadApiKey = (typeof PRELOAD_EXPOSED_KEYS)[number];
/** Names that must NEVER appear on the preload bridge. */
export const FORBIDDEN_PRELOAD_KEYS = [
"ipcRenderer",
"shell",
"require",
"process",
"child_process",
"fs",
"path",
"credential",
"terminal",
"exec",
"spawn",
"openExternal",
] as const;
/** Validate an exposed preload object; returns any forbidden keys found. */
export function findForbiddenPreloadKeys(exports: Record<string, unknown>): string[] {
const keys = new Set(Object.keys(exports));
const missing: string[] = [];
for (const forbidden of FORBIDDEN_PRELOAD_KEYS) {
if (keys.has(forbidden)) missing.push(forbidden);
}
return missing;
}
/** The typed preload bridge shape (renderer sees only this). */
export interface PreloadApi {
task: {
list(): Promise<unknown>;
start(input: {
goal: string;
workspace: string;
device_ids: string[];
mode: "guide" | "auto_low_risk";
}): Promise<unknown>;
status(taskId: string): Promise<unknown>;
steer(taskId: string, message: string): Promise<unknown>;
cancel(taskId: string, reason?: string): Promise<unknown>;
resume(taskId: string, takeOver?: boolean): Promise<unknown>;
// Approval decisions are human-only; the model plane can only request/list.
approvals(): Promise<unknown>;
decide(approvalId: string, approve: boolean, reason?: string): Promise<unknown>;
};
device: {
list(): Promise<unknown>;
inspect(deviceId: string, refresh?: "cached" | "quick" | "full"): Promise<unknown>;
// Human connect flow (docs/12 §4): the renderer shows the fingerprint and
// a human confirms it; raw key material never crosses this bridge.
showHostKey(host: string): Promise<unknown>;
confirmHostKey(candidateId: string): Promise<unknown>;
registerDevice(input: {
alias: string;
ssh_config_host: string;
expected_host_key_sha256?: string;
labels?: Record<string, string>;
}): Promise<unknown>;
// The agent discovers candidate boards on local links; the human only
// picks one and confirms its fingerprint.
discoverDevices(): Promise<unknown>;
// LAN SSH onboarding: key-based probe, then one-shot controlled password
// login that installs the product key. The password never persists.
authCheck(host: string): Promise<unknown>;
onboardKey(input: { host: string; user: string; password: string }): Promise<unknown>;
unregisterDevice(deviceId: string): Promise<unknown>;
};
window: {
openGui(): void;
};
// Workspace browsing + editing for the project page (host-side service).
// Spaces are device-scoped: the renderer passes the selected device id.
project: {
list(path?: string, workspaceId?: string): Promise<unknown>;
read(path: string, workspaceId?: string): Promise<unknown>;
write(path: string, content: string, workspaceId?: string): Promise<unknown>;
};
// Local, secret-free product facts for the settings page.
settings: {
info(): Promise<unknown>;
};
// Project Packs (S3): list and re-run saved capabilities without an LLM.
pack: {
list(): Promise<unknown>;
run(name: string, deviceId: string, requestId: string): Promise<unknown>;
};
// Model gateway config: read masks the key; write replaces ~/.rdk/.env.
config: {
get(): Promise<unknown>;
set(input: { baseUrl: string; apiKey: string; model: string; api: string }): Promise<unknown>;
test(): Promise<unknown>;
};
// Saved SSH connections (ticket key in keychain); human onboarding only.
connection: {
list(): Promise<unknown>;
add(input: {
name: string;
host: string;
user: string;
device_id: string;
helper_profile?: string;
ticketKey?: string;
}): Promise<unknown>;
remove(name: string): Promise<unknown>;
};
// Read-only serial console (human plane; never an Agent run target).
console: {
ports(): Promise<unknown>;
tail(port: string, maxLines?: number): Promise<unknown>;
};
// Flashing wizard: human-only confirm; rehearsal engine until XBurn (S6).
flash: {
images(boardModel?: string): Promise<unknown>;
suggest(input: { device_id: string; board_model: string; image_id: string }): Promise<unknown>;
confirm(flashId: string): Promise<unknown>;
run(flashId: string): Promise<unknown>;
status(flashId: string): Promise<unknown>;
cancel(flashId: string): Promise<unknown>;
};
// Deterministic one-click operations: no LLM, capability-filtered.
template: {
list(deviceId: string): Promise<unknown>;
run(name: string, deviceId: string, requestId: string): Promise<unknown>;
};
// Trusted local skills the human can invoke; read-only.
skill: {
list(): Promise<unknown>;
read(name: string): Promise<unknown>;
};
}

View File

@ -0,0 +1,76 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import {
BROWSER_WINDOW_WEB_PREFERENCES,
findForbiddenPreloadKeys,
isAllowedRendererNavigation,
PRELOAD_EXPOSED_KEYS,
} from "../src/security.js";
const RENDERER_URL = "file:///Applications/rdk/dist/renderer/index.html";
test("renderer is sandboxed, context-isolated, and has no Node integration", () => {
assert.equal(BROWSER_WINDOW_WEB_PREFERENCES.contextIsolation, true);
assert.equal(BROWSER_WINDOW_WEB_PREFERENCES.sandbox, true);
assert.equal(BROWSER_WINDOW_WEB_PREFERENCES.nodeIntegration, false);
});
test("navigation is allowed only for the exact packaged renderer URL", () => {
assert.equal(isAllowedRendererNavigation(RENDERER_URL, RENDERER_URL), true);
});
test("navigation to any other local file is rejected (receives no preload bridge)", () => {
// A bare `file:` allowlist would admit ANY local page into a window that
// carries the task/device preload bridge — this is the P1 that forbids it.
assert.equal(isAllowedRendererNavigation("file:///tmp/evil.html", RENDERER_URL), false);
assert.equal(isAllowedRendererNavigation("file:///etc/passwd", RENDERER_URL), false);
});
test("navigation to remote schemes is rejected", () => {
assert.equal(isAllowedRendererNavigation("https://example.com/", RENDERER_URL), false);
assert.equal(isAllowedRendererNavigation("http://localhost:8080/", RENDERER_URL), false);
});
test("preload exposes only the reviewed namespaces", () => {
assert.deepEqual([...PRELOAD_EXPOSED_KEYS], [
"task",
"device",
"window",
"project",
"settings",
"pack",
"config",
"connection",
"console",
"flash",
"template",
"skill",
]);
});
test("a clean preload export has no forbidden keys", () => {
const clean = {
task: {},
device: {},
window: {},
project: {},
settings: {},
pack: {},
config: {},
connection: {},
console: {},
flash: {},
template: {},
skill: {},
};
assert.deepEqual(findForbiddenPreloadKeys(clean), []);
});
test("forbidden keys are detected on the preload bridge", () => {
const bad = { task: {}, ipcRenderer: {}, shell: {} };
const found = findForbiddenPreloadKeys(bad);
assert.ok(found.includes("ipcRenderer"));
assert.ok(found.includes("shell"));
assert.ok(!found.includes("task"));
});

View File

@ -0,0 +1,19 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"lib": ["ES2022", "DOM"],
"jsx": "react-jsx",
"outDir": "dist",
"rootDir": "src",
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"skipLibCheck": true,
"declaration": false,
"sourceMap": true,
"types": ["node"]
},
"include": ["src/main.ts", "src/mainImpl.ts", "src/security.ts"]
}

View File

@ -0,0 +1,9 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "dist-test",
"rootDir": ".",
"declaration": false
},
"include": ["src/security.ts", "test/**/*.ts"]
}

View File

@ -0,0 +1,7 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"noEmit": true
},
"include": ["src/**/*.ts", "src/**/*.tsx"]
}

View File

@ -0,0 +1,202 @@
/**
* Real model wiring for the product agent loop (docs/08 §8).
*
* The product surfaces default to a deterministic ScriptedModel (no network, no
* credentials). When an API key is resolvable, this factory instead writes a
* real provider into the per-task agentDir's `models.json` and returns no
* in-process model handle — `createAgentSession` then resolves the model from
* that config, and the real LLM drives the tool loop.
*
* Configuration is a single flat `.env` at `~/.rdk/.env` (mode 0600,
* gitignored — never committed). Four variables:
* RDK_ANTHROPIC_BASE_URL gateway URL (default https://api.anthropic.com)
* RDK_ANTHROPIC_API_KEY required — the gateway key
* RDK_ANTHROPIC_MODEL model id (default claude-sonnet-5)
* RDK_MODEL_API wire format: anthropic-messages (default) or
* openai-responses
* Real process.env overrides the file field-for-field, so an ad-hoc `export`
* still works. With no key, the deterministic ScriptedModel is unchanged.
*/
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import type { ScriptedTurn } from "./scriptedModel.js";
export const REAL_MODEL_PROVIDER = "rdk-model";
export const ANTHROPIC_MESSAGES_API = "anthropic-messages";
export const OPENAI_RESPONSES_API = "openai-responses";
const DEFAULT_API = ANTHROPIC_MESSAGES_API;
const DEFAULT_MODEL_ID = "claude-sonnet-5";
const DEFAULT_BASE_URL = "https://api.anthropic.com";
const DOTENV_REL = ".rdk/.env";
/** Known wire formats; a custom gateway must advertise one of these. */
const KNOWN_APIS = new Set([ANTHROPIC_MESSAGES_API, OPENAI_RESPONSES_API]);
export interface RealModelHandle {
/** No in-process model handle: the SDK resolves from models.json. */
model: undefined;
}
export interface RealModelConfig {
baseUrl: string;
apiKey: string;
model: string;
api: string;
}
export interface RealModelConfigSources {
/** Env var map; defaults to process.env (overrides the .env file). */
env?: NodeJS.ProcessEnv;
/** .env path; defaults to ~/.rdk/.env. */
dotEnvPath?: string;
}
/**
* Parse a flat KEY=VALUE .env file. Ignores blank lines and `#` comments;
* strips matching surrounding quotes. Values never undergo shell expansion.
*/
function parseDotEnv(filePath: string): NodeJS.ProcessEnv {
const out: NodeJS.ProcessEnv = {};
if (!existsSync(filePath)) return out;
let raw: string;
try {
raw = readFileSync(filePath, "utf8");
} catch {
return out;
}
for (const line of raw.split(/\r?\n/)) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith("#")) continue;
const eq = trimmed.indexOf("=");
if (eq < 1) continue;
const key = trimmed.slice(0, eq).trim();
let value = trimmed.slice(eq + 1).trim();
if (
(value.startsWith('"') && value.endsWith('"')) ||
(value.startsWith("'") && value.endsWith("'"))
) {
value = value.slice(1, -1);
}
if (key) out[key] = value;
}
return out;
}
/**
* Resolve the real-model provider config. The .env file provides defaults;
* real process.env overrides field-for-field. Returns null when no key is
* resolvable (caller falls back to ScriptedModel).
*/
export function resolveRealModelConfig(
sources?: RealModelConfigSources,
): RealModelConfig | null {
const dotEnvPath = sources?.dotEnvPath ?? join(homedir(), DOTENV_REL);
const merged: NodeJS.ProcessEnv = { ...parseDotEnv(dotEnvPath), ...(sources?.env ?? process.env) };
const apiKey = merged.RDK_ANTHROPIC_API_KEY?.trim();
if (!apiKey) return null;
const api = merged.RDK_MODEL_API?.trim() || DEFAULT_API;
if (!KNOWN_APIS.has(api)) {
// Reject an unknown wire format rather than silently producing a broken
// provider; the caller falls back to the scripted model.
return null;
}
return {
baseUrl: merged.RDK_ANTHROPIC_BASE_URL?.trim() || DEFAULT_BASE_URL,
apiKey,
model: merged.RDK_ANTHROPIC_MODEL?.trim() || DEFAULT_MODEL_ID,
api,
};
}
/** Back-compat: the key alone. */
export function resolveAnthropicApiKey(sources?: RealModelConfigSources): string | undefined {
return resolveRealModelConfig(sources)?.apiKey;
}
export function resolveAnthropicModelId(env: NodeJS.ProcessEnv = process.env): string {
return (env.RDK_ANTHROPIC_MODEL ?? DEFAULT_MODEL_ID).trim() || DEFAULT_MODEL_ID;
}
export function resolveAnthropicBaseUrl(env: NodeJS.ProcessEnv = process.env): string {
return (env.RDK_ANTHROPIC_BASE_URL ?? DEFAULT_BASE_URL).trim() || DEFAULT_BASE_URL;
}
/**
* Default .env path (~/.rdk/.env). Exported so the desktop settings page and
* other surfaces read/write the same file the model factory reads.
*/
export function defaultRealModelDotEnvPath(): string {
return join(homedir(), DOTENV_REL);
}
/**
* Write a flat .env (0600) with the real-model config. Used by the desktop
* settings page to configure the model without touching a terminal. An empty
* apiKey clears the key (falls back to scripted). Existing file is replaced.
*/
export function writeRealModelDotEnv(
path: string,
config: { baseUrl: string; apiKey: string; model: string; api: string },
): void {
mkdirSync(dirname(path), { recursive: true });
const body = [
"# rdk-agent real model config (0600, gitignored)",
`RDK_ANTHROPIC_BASE_URL=${config.baseUrl}`,
`RDK_ANTHROPIC_API_KEY=${config.apiKey}`,
`RDK_ANTHROPIC_MODEL=${config.model}`,
`RDK_MODEL_API=${config.api}`,
"",
].join("\n");
writeFileSync(path, body, { encoding: "utf8", mode: 0o600 });
try {
chmodSync(path, 0o600);
} catch {
// best-effort on platforms that ignore it
}
}
/**
* Write a real provider config into the agentDir's models.json. Returns a
* handle with no in-process model (the SDK resolves it). Returns null when no
* key is resolvable (or the api is unknown) so the caller falls back to
* ScriptedModel.
*/
export function createRealModel(
agentDir: string,
_turns: readonly ScriptedTurn[] = [],
sources?: RealModelConfigSources,
): RealModelHandle | null {
const config = resolveRealModelConfig(sources);
if (!config) return null;
mkdirSync(agentDir, { recursive: true });
const configPath = join(agentDir, "models.json");
writeFileSync(
configPath,
JSON.stringify(
{
providers: {
[REAL_MODEL_PROVIDER]: {
baseUrl: config.baseUrl,
api: config.api,
apiKey: config.apiKey,
models: [{ id: config.model }],
},
},
},
null,
2,
),
);
// The key lives in this file — lock it to the owner. The state dir is
// gitignored; this keeps the secret out of the repo and off other accounts.
try {
chmodSync(configPath, 0o600);
} catch {
// chmod best-effort on platforms that ignore it.
}
return { model: undefined };
}

View File

@ -40,6 +40,10 @@ export const RDK_TOOL_ALLOWLIST = [
"task_create",
"task_checkpoint",
"task_report",
"task_reconcile",
"rdk_pack_save",
"rdk_pack_list",
"rdk_pack_run",
] as const;
export type RdkToolName = (typeof RDK_TOOL_ALLOWLIST)[number];

View File

@ -46,3 +46,18 @@ export {
type ScriptedModelHandle,
type ScriptedTurn,
} from "./scriptedModel.js";
export {
ANTHROPIC_MESSAGES_API,
OPENAI_RESPONSES_API,
REAL_MODEL_PROVIDER,
createRealModel,
defaultRealModelDotEnvPath,
resolveAnthropicApiKey,
resolveAnthropicBaseUrl,
resolveRealModelConfig,
resolveAnthropicModelId,
writeRealModelDotEnv,
type RealModelConfig,
type RealModelConfigSources,
type RealModelHandle,
} from "./anthropicModel.js";

View File

@ -75,6 +75,20 @@ export async function createRdkSession(options: RdkSessionOptions): Promise<RdkS
join(options.packageRoot, "prompts", "task-summary.md"),
"utf8",
);
// The rdk-develop skill workflow + manifest shape are product-trusted and
// must reach the model: skills are not auto-injected (noSkills suppresses
// discovery and no skill-read tool is allowlisted), so append the SKILL.md
// body to the system prompt — the one channel the model always reads.
const developSkill = readFileSync(
join(options.packageRoot, "skills", "rdk-develop", "SKILL.md"),
"utf8",
);
// Domain cognition (boards/accessories/software) so the agent is RDK-aware,
// not a generic coder. Appended to the system prompt the model always reads.
const rdkKnowledge = readFileSync(
join(options.packageRoot, "skills", "rdk-knowledge", "SKILL.md"),
"utf8",
);
const resourceLoader = new DefaultResourceLoader({
cwd: options.cwd,
agentDir: options.agentDir,
@ -97,7 +111,7 @@ export async function createRdkSession(options: RdkSessionOptions): Promise<RdkS
noThemes: true,
noContextFiles: true,
systemPrompt: buildSystemPrompt(),
appendSystemPrompt: [projectContext],
appendSystemPrompt: [projectContext, developSkill, rdkKnowledge],
});
// reload() materializes the factory tools and skill set.
await resourceLoader.reload();

View File

@ -385,5 +385,60 @@ export function createRdkTools(client: RdkHostClient): RdkToolDefinition[] {
...(optStr(args, "waiting_on") ? { waiting_on: optStr(args, "waiting_on") } : {}),
}),
},
{
name: "task_reconcile",
label: "Reconcile task",
description:
"Resume path: refresh the task's non-terminal runs from device truth after a " +
"reconnect. Never re-starts a run.",
parameters: Type.Object({ taskId: Type.String() }, { additionalProperties: false }),
execute: async (args) => call("task.reconcile")({ task_id: str(args, "taskId") }),
},
{
name: "rdk_pack_save",
label: "Save capability as Pack",
description:
"Freeze the capability you just coded (workspace source + the plan's " +
"manifest) into a named Pack so it can be re-run without re-coding. " +
"Call after a passed run; pass the workspaceId and planId you used.",
parameters: Type.Object(
{ name: Type.String(), workspaceId: Type.String(), planId: Type.String() },
{ additionalProperties: false },
),
execute: async (args) =>
call("pack.save")({
name: str(args, "name"),
workspace_id: str(args, "workspaceId"),
plan_id: str(args, "planId"),
}),
},
{
name: "rdk_pack_list",
label: "List saved Packs",
description: "List saved capability Packs (name, entrypoint, digest).",
parameters: Type.Object({}, { additionalProperties: false }),
execute: async () => call("pack.list")({}),
},
{
name: "rdk_pack_run",
label: "Re-run a saved Pack",
description:
"Re-run a saved capability on a device WITHOUT an LLM: re-stage the " +
"Pack source, plan, and start a run. Use a fresh requestId per run.",
parameters: Type.Object(
{
name: Type.String(),
deviceId: Type.String(),
requestId: Type.String(),
},
{ additionalProperties: false },
),
execute: async (args) =>
call("pack.run")({
name: str(args, "name"),
device_id: str(args, "deviceId"),
request_id: str(args, "requestId"),
}),
},
];
}

View File

@ -0,0 +1,121 @@
import assert from "node:assert/strict";
import { mkdtempSync, readFileSync, statSync, existsSync, writeFileSync, chmodSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { test } from "node:test";
import {
ANTHROPIC_MESSAGES_API,
OPENAI_RESPONSES_API,
REAL_MODEL_PROVIDER,
createRealModel,
resolveRealModelConfig,
} from "../src/anthropicModel.js";
function tmpAgentDir(): string {
return mkdtempSync(path.join(tmpdir(), "rdk-anthropic-"));
}
function readModels(agentDir: string): Record<string, unknown> {
return JSON.parse(readFileSync(path.join(agentDir, "models.json"), "utf8"));
}
function providerOf(agentDir: string): Record<string, unknown> {
return (readModels(agentDir).providers as Record<string, Record<string, unknown>>)[
REAL_MODEL_PROVIDER
]!;
}
function writeDotEnv(file: string, vars: Record<string, string>): void {
const body = Object.entries(vars).map(([k, v]) => `${k}=${v}`).join("\n") + "\n";
writeFileSync(file, body);
chmodSync(file, 0o600);
}
test("a flat .env drives an anthropic-messages provider", () => {
const dir = tmpAgentDir();
const dotEnv = path.join(dir, ".env");
writeDotEnv(dotEnv, {
RDK_ANTHROPIC_API_KEY: "sk-test-fake",
RDK_ANTHROPIC_MODEL: "claude-sonnet-5",
RDK_ANTHROPIC_BASE_URL: "https://api.anthropic.com",
// RDK_MODEL_API unset -> default anthropic-messages
});
const agentDir = tmpAgentDir();
const handle = createRealModel(agentDir, [], { dotEnvPath: dotEnv, env: {} });
assert.deepEqual(handle, { model: undefined });
const provider = providerOf(agentDir);
assert.equal(provider.api, ANTHROPIC_MESSAGES_API);
assert.equal(provider.apiKey, "sk-test-fake");
assert.equal(provider.baseUrl, "https://api.anthropic.com");
assert.deepEqual(provider.models, [{ id: "claude-sonnet-5" }]);
assert.equal(statSync(path.join(agentDir, "models.json")).mode & 0o777, 0o600);
});
test("a flat .env drives an openai-responses gateway", () => {
const dotEnv = path.join(tmpAgentDir(), ".env");
writeDotEnv(dotEnv, {
RDK_ANTHROPIC_BASE_URL: "https://my-gateway.example.com/v1",
RDK_ANTHROPIC_API_KEY: "sk-gw-fake",
RDK_ANTHROPIC_MODEL: "gpt-5-real-fake",
RDK_MODEL_API: "openai-responses",
});
const agentDir = tmpAgentDir();
const handle = createRealModel(agentDir, [], { dotEnvPath: dotEnv, env: {} });
assert.deepEqual(handle, { model: undefined });
const provider = providerOf(agentDir);
assert.equal(provider.api, OPENAI_RESPONSES_API);
assert.equal(provider.baseUrl, "https://my-gateway.example.com/v1");
assert.deepEqual(provider.models, [{ id: "gpt-5-real-fake" }]);
});
test("no key in .env -> null (falls back to scripted, no file written)", () => {
const dotEnv = path.join(tmpAgentDir(), ".env");
writeDotEnv(dotEnv, { RDK_ANTHROPIC_MODEL: "claude-sonnet-5" });
const agentDir = tmpAgentDir();
const handle = createRealModel(agentDir, [], { dotEnvPath: dotEnv, env: {} });
assert.equal(handle, null);
assert.equal(existsSync(path.join(agentDir, "models.json")), false);
});
test("real env overrides the .env field-for-field", () => {
const dotEnv = path.join(tmpAgentDir(), ".env");
writeDotEnv(dotEnv, {
RDK_ANTHROPIC_BASE_URL: "https://file-gateway.example.com",
RDK_ANTHROPIC_API_KEY: "sk-file",
RDK_ANTHROPIC_MODEL: "file-model",
RDK_MODEL_API: "openai-responses",
});
const resolved = resolveRealModelConfig({
dotEnvPath: dotEnv,
env: { RDK_ANTHROPIC_MODEL: "env-model-override", RDK_MODEL_API: "anthropic-messages" },
})!;
assert.equal(resolved.baseUrl, "https://file-gateway.example.com");
assert.equal(resolved.apiKey, "sk-file");
assert.equal(resolved.model, "env-model-override");
assert.equal(resolved.api, ANTHROPIC_MESSAGES_API);
});
test("quoted values are stripped and comments ignored", () => {
const dotEnv = path.join(tmpAgentDir(), ".env");
writeFileSync(dotEnv, [
"# rdk-agent real model config",
'RDK_ANTHROPIC_API_KEY="sk-quoted-fake"',
"RDK_ANTHROPIC_MODEL='claude-opus-5'",
"RDK_MODEL_API=anthropic-messages",
"",
].join("\n"));
const resolved = resolveRealModelConfig({ dotEnvPath: dotEnv, env: {} })!;
assert.equal(resolved.apiKey, "sk-quoted-fake");
assert.equal(resolved.model, "claude-opus-5");
});
test("an unknown wire format is rejected (falls back to scripted)", () => {
const dotEnv = path.join(tmpAgentDir(), ".env");
writeDotEnv(dotEnv, {
RDK_ANTHROPIC_API_KEY: "sk-x",
RDK_MODEL_API: "bogus-api",
});
assert.equal(resolveRealModelConfig({ dotEnvPath: dotEnv, env: {} }), null);
});

View File

@ -56,6 +56,10 @@ test("allowlist is the spec tool surface (docs/08 §5)", () => {
"task_create",
"task_checkpoint",
"task_report",
"task_reconcile",
"rdk_pack_save",
"rdk_pack_list",
"rdk_pack_run",
];
assert.deepEqual([...RDK_TOOL_ALLOWLIST], expected);
});

View File

@ -0,0 +1,311 @@
/**
* S2 real-device scripted slice (docs/06 §6.2 first exit gate):
* the production `createRdkSession` agent loop — same assembly the CLI/TUI
* surfaces use — drives the Starter 1 system health card against the REAL
* S100P over the production SSH/exec-profile chain:
*
* prompt → inventory → inspect → workspace write+checkpoint → task.create
* → plan (system.info capability) → run.start (task-bound) → status →
* artifact read → task.checkpoint → task_report
*
* Gated on RDK_S2_REAL_DEVICE=1; the host env (RDK_DEVICE_COMMAND = the ssh
* argv for the s100-exec Helper, RDK_TICKET_KEY, RDK_STATE_DIR, …) is set by
* the evidence runner. Deterministic: fixed script, factory turns read live
* ids (plan/run/task) from tool results.
*/
import assert from "node:assert/strict";
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { test } from "node:test";
import { RDK_TOOL_ALLOWLIST } from "../src/config.js";
import { RdkHostClient } from "../src/hostClient.js";
import { fauxAssistantMessage, fauxToolCall } from "../src/piCompat.js";
import {
registerScriptedModel,
writeScriptedModelConfig,
type ScriptedTurn,
} from "../src/scriptedModel.js";
import { createRdkSession } from "../src/session.js";
const ENABLED = process.env.RDK_S2_REAL_DEVICE === "1";
const COMMAND = (process.env.RDK_AGENT_COMMAND ?? "rdk-agent-host serve --stdio")
.split(/\s+/)
.filter(Boolean);
const DEVICE_ID = process.env.RDK_S2_DEVICE_ID ?? "s100p-001";
/** Starter 1 health card (stdlib only, read-only probes) — same logic as the
* Python driver evidence, staged this time by the agent loop itself. */
const HEALTH_CARD = `#!/usr/bin/env python3
import json
import shutil
from pathlib import Path
checks = {}
la1, la5, la15 = Path("/proc/loadavg").read_text().split()[:3]
checks["loadavg"] = {"1m": float(la1), "5m": float(la5), "15m": float(la15)}
meminfo = {}
for line in Path("/proc/meminfo").read_text().splitlines():
key, _, rest = line.partition(":")
meminfo[key.strip()] = rest.strip()
total_kb = int(meminfo["MemTotal"].split()[0])
avail_kb = int(meminfo["MemAvailable"].split()[0])
checks["memory"] = {
"total_mb": round(total_kb / 1024),
"available_mb": round(avail_kb / 1024),
"available_pct": round(avail_kb * 100.0 / total_kb, 1),
}
usage = shutil.disk_usage("/")
checks["disk"] = {
"total_gb": round(usage.total / 2**30, 1),
"used_pct": round(usage.used * 100.0 / usage.total, 1),
}
zones = []
for zone in sorted(Path("/sys/class/thermal").glob("thermal_zone*")):
try:
zones.append({
"zone": zone.name,
"type": (zone / "type").read_text().strip(),
"celsius": round(int((zone / "temp").read_text().strip()) / 1000.0, 1),
})
except (OSError, ValueError):
continue
checks["thermal"] = zones
checks["uptime_seconds"] = round(float(Path("/proc/uptime").read_text().split()[0]))
verdicts = {
"memory_ok": checks["memory"]["available_pct"] > 5.0,
"disk_ok": checks["disk"]["used_pct"] < 95.0,
"thermal_ok": all(z["celsius"] < 85.0 for z in zones),
}
ok = all(verdicts.values())
card = {"ok": ok, "verdicts": verdicts, "checks": checks}
Path("health.json").write_text(json.dumps(card, indent=2, sort_keys=True) + "\\n")
print(json.dumps({"ok": ok, "verdicts": verdicts}, sort_keys=True))
`;
const HEALTH_MANIFEST = {
schema_version: "1.0",
name: "starter1-health-card",
entrypoint: { type: "python", path: "health_card.py" },
requirements: { capabilities: [{ id: "system.info" }] },
resources: { wall_time_seconds: 60, output_bytes: 65536 },
artifacts: [
{
name: "health.json",
path: "health.json",
media_type: "application/json",
required: true,
},
],
verifiers: [
{ id: "exit-ok", type: "exit_code.zero", config: {} },
{
id: "health-ok",
type: "json.assert",
config: { artifact: "health.json", path: "ok", equals: true },
},
],
};
/** Extract the JSON text of the last tool result for one tool name. */
function lastToolResult(context: unknown, toolName: string): Record<string, unknown> {
const messages =
(context as { messages?: Array<{ role?: string; toolName?: string; content?: unknown }> })
.messages ?? [];
for (let i = messages.length - 1; i >= 0; i -= 1) {
const message = messages[i];
if (message?.role === "toolResult" && message.toolName === toolName) {
const content = message.content as Array<{ text?: string }>;
const text = content?.[0]?.text ?? "{}";
return JSON.parse(text) as Record<string, unknown>;
}
}
throw new Error(`no tool result for ${toolName} in context`);
}
/** The S2 scripted loop, following the rdk-develop skill exactly. */
const S2_SCRIPT: ScriptedTurn[] = [
// 1. inspect (fresh inventory first)
{ toolCalls: [{ name: "rdk_device_inventory", arguments: { deviceId: DEVICE_ID, profile: "quick" } }] },
{ toolCalls: [{ name: "rdk_device_inspect", arguments: { deviceId: DEVICE_ID } }] },
// 2. write + freeze the program
{
toolCalls: [
{
name: "workspace_write",
arguments: { workspaceId: "ws-s2-health", path: "health_card.py", content: HEALTH_CARD },
},
],
},
{ toolCalls: [{ name: "workspace_checkpoint", arguments: { workspaceId: "ws-s2-health", label: "health card v1" } }] },
// 3. task binding (required verifiers = the manifest's)
{
toolCalls: [
{
name: "task_create",
arguments: {
goal: "Starter 1: system health card on the real S100P",
workspaceId: "ws-s2-health",
deviceIds: [DEVICE_ID],
requiredVerifierIds: ["exit-ok", "health-ok"],
},
},
],
},
// 4. plan (no device writes)
{
toolCalls: [
{
name: "rdk_run_plan",
arguments: { deviceId: DEVICE_ID, workspaceId: "ws-s2-health", manifest: HEALTH_MANIFEST },
},
],
},
// 5. run, task-bound (ids read live)
{
factory: (context) => {
const planResult = lastToolResult(context, "rdk_run_plan") as { plan: { plan_id: string } };
const taskResult = lastToolResult(context, "task_create") as { task: { task_id: string } };
return fauxAssistantMessage([
fauxToolCall("rdk_run_start", {
requestId: "s2-slice-req-1",
planId: planResult.plan.plan_id,
taskId: taskResult.task.task_id,
}),
]);
},
},
{
factory: (context) => {
const started = lastToolResult(context, "rdk_run_start") as { record: { run_id: string } };
return fauxAssistantMessage([fauxToolCall("rdk_run_status", { runId: started.record.run_id })]);
},
},
// 6. verify: read the real artifact
{
factory: (context) => {
const started = lastToolResult(context, "rdk_run_start") as { record: { run_id: string } };
return fauxAssistantMessage([
fauxToolCall("rdk_artifact_read", {
runId: started.record.run_id,
artifactId: `${started.record.run_id}/health.json`,
}),
]);
},
},
// 7. checkpoint + report
{
factory: (context) => {
const taskResult = lastToolResult(context, "task_create") as { task: { task_id: string } };
return fauxAssistantMessage([fauxToolCall("task_checkpoint", { taskId: taskResult.task.task_id })]);
},
},
{
factory: (context) => {
const taskResult = lastToolResult(context, "task_create") as { task: { task_id: string } };
return fauxAssistantMessage([fauxToolCall("task_report", { taskId: taskResult.task.task_id })]);
},
},
{ text: "done: health card verified on the real device" },
];
test("S2 scripted agent loop completes the health card on the real S100P", { skip: !ENABLED }, async () => {
const cwd = mkdtempSync(path.join(tmpdir(), "rdk-s2-slice-"));
const agentDir = mkdtempSync(path.join(tmpdir(), "rdk-s2-agent-dir-"));
writeScriptedModelConfig(agentDir);
const scripted = await registerScriptedModel(S2_SCRIPT);
const packageRoot = path.resolve(
path.dirname(new URL(import.meta.url).pathname),
"..",
"..",
"..",
"pi-rdk-agent",
);
const handle = await createRdkSession({
cwd,
agentDir,
packageRoot,
agentCommand: COMMAND,
model: scripted.model,
});
const { session, client } = handle;
try {
const activeTools = session.getActiveToolNames?.() ?? [];
assert.deepEqual([...activeTools].sort(), [...RDK_TOOL_ALLOWLIST].sort());
await session.prompt(
"给 s100p-001 做一张系统健康卡:写脚本、在设备上运行、用验证器判定,报告证据",
);
// Assert on domain truth via the client (never model self-report).
const inspected = (await client.call("device.inspect", { device_id: DEVICE_ID })) as {
snapshot: { identity: { model: string } } | null;
fresh: boolean;
};
assert.equal(inspected.snapshot?.identity.model, "D-Robotics RDK S100P V1P0");
assert.equal(inspected.fresh, true);
// Find the scripted task and its run.
const tasks = (await client.call("task.list")) as {
tasks: Array<{ task_id: string; goal: string }>;
};
const task = tasks.tasks.find((t) => t.goal.includes("Starter 1"));
assert.ok(task, "scripted task not found");
const shown = (await client.call("task.show", { task_id: task.task_id })) as {
task: { run_ids: string[] };
};
assert.equal(shown.task.run_ids.length, 1);
const runId = shown.task.run_ids[0];
const status = (await client.call("run.status", { run_id: runId })) as {
record: { state: string; outcome: string };
};
assert.equal(status.record.state, "succeeded");
assert.equal(status.record.outcome, "passed");
// Idempotent replay: same request_id + same payload (task bound) returns
// the stored record — no second device side effect.
const planResult = (await client.call("run.plan", {
device_id: DEVICE_ID,
workspace_id: "ws-s2-health",
manifest: HEALTH_MANIFEST,
})) as { plan: { plan_id: string } };
const replay = (await client.call("run.start", {
request_id: "s2-slice-req-1",
plan_id: planResult.plan.plan_id,
task_id: task.task_id,
})) as { record: { run_id: string } };
assert.equal(replay.record.run_id, runId);
// The health.json artifact holds real board facts.
const artifact = (await client.call("artifact.read", {
run_id: runId,
artifact_id: `${runId}/health.json`,
})) as { preview: string };
const card = JSON.parse(artifact.preview) as {
ok: boolean;
checks: { memory: { total_mb: number }; thermal: unknown[] };
};
assert.equal(card.ok, true);
assert.ok(card.checks.memory.total_mb > 1000);
assert.ok(card.checks.thermal.length > 0);
// task_report completes via verifier aggregation alone.
const report = (await client.call("task.report", { task_id: task.task_id })) as {
report: { state: string; outcome: string; unresolved: string[] };
};
assert.equal(report.report.outcome, "passed");
assert.equal(report.report.state, "completed");
assert.deepEqual(report.report.unresolved, []);
} finally {
await handle.close();
}
});

View File

@ -4,6 +4,14 @@
"private": true,
"description": "RDK Agent product CLI + MCP stdio entry points (docs/12 §3, §6)",
"type": "module",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
},
"bin": {
"rdk-agent": "dist/bin.js"
},

View File

@ -1,25 +1,154 @@
#!/usr/bin/env node
/**
* Product entry dispatch (docs/12 §3): route `mcp --stdio` to the MCP server,
* everything else to the CLI.
* everything else to the CLI. MCP requires `--workspace-root <absolute-path>`;
* stdout carries MCP JSON-RPC only, so every human message goes to stderr.
*/
import { spawn } from "node:child_process";
import { existsSync, realpathSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
// A bare `rdk-agent` (npm-linked) must find the repo-local venv Host with no
// env. Walk up from this bin's real path until a `.venv/bin/rdk-agent-host`
// exists, and point RDK_AGENT_COMMAND at it (explicit env still wins).
if (!process.env.RDK_AGENT_COMMAND) {
try {
let dir = dirname(realpathSync(fileURLToPath(import.meta.url)));
for (let i = 0; i < 6 && dir !== dirname(dir); i++) {
const venvHost = join(dir, ".venv", "bin", "rdk-agent-host");
const venvDevice = join(dir, ".venv", "bin", "rdk-agent-device");
if (existsSync(venvHost)) {
process.env.RDK_AGENT_COMMAND = `${venvHost} serve --stdio`;
if (!process.env.RDK_DEVICE_COMMAND && existsSync(venvDevice)) {
process.env.RDK_DEVICE_COMMAND = `${venvDevice} serve`;
}
break;
}
dir = dirname(dir);
}
} catch {
// leave unset; fall back to PATH resolution downstream
}
}
import { DeviceService } from "./deviceService.js";
import { main as runCli } from "./cli.js";
import { runMcpServer } from "./mcp.js";
import { callExternalTool, listExternalTools } from "./mcpClient.js";
import {
buildTaskService,
resolveDefaultWorkspaceRoot,
resolvePackageRoot,
} from "./taskServiceFactory.js";
import { runTui } from "./tui.js";
const argv = process.argv.slice(2);
const isMcp = argv[0] === "mcp" && argv.includes("--stdio");
const isMcpClient = argv[0] === "mcp-client";
const isGui = argv[0] === "gui";
// Bare `rdk-agent` (no subcommand) drops straight into the TUI, like `claude`.
const isTui = argv[0] === "tui" || argv.length === 0;
if (isMcp) {
const service = new DeviceService();
runMcpServer(service)
.then(() => {
// MCP server runs until the transport closes; exit cleanly then.
return service.close();
function flagValue(flag: string): string | undefined {
const index = argv.indexOf(flag);
if (index === -1) return undefined;
return argv[index + 1];
}
function launchGui(): void {
const repoRoot = dirname(resolvePackageRoot());
const desktopDir = join(repoRoot, "packages", "rdk-agent-desktop");
const child = spawn("npm", ["start"], {
cwd: desktopDir,
stdio: "inherit",
env: process.env,
});
child.on("exit", (code) => {
process.exitCode = code ?? 0;
});
}
function startTui(): void {
const workspaceRoot = flagValue("--workspace-root") ?? resolveDefaultWorkspaceRoot();
const goal = argv[1] && !argv[1].startsWith("-") ? argv[1] : "系统健康卡";
const service = buildTaskService(workspaceRoot);
service
.startTask(goal, ".", [], "guide", "tui")
.then((handle) => runTui(service, handle.task_id, { input: process.stdin, output: process.stdout }))
.then(() => service.close())
.catch((err) => {
process.stderr.write(`rdk-agent tui: ${err instanceof Error ? err.message : String(err)}\n`);
process.exitCode = 1;
});
}
function runMcpClient(): void {
const sub = argv[1];
const serverName = flagValue("--server");
if (!serverName) {
process.stderr.write("rdk-agent mcp-client: --server <name> is required\n");
process.exitCode = 2;
return;
}
if (sub === "list") {
listExternalTools(serverName)
.then((tools) => {
process.stdout.write(JSON.stringify(tools, null, 2) + "\n");
})
.catch((err) => {
process.stderr.write(`rdk-agent mcp-client: ${err instanceof Error ? err.message : String(err)}\n`);
process.exitCode = 1;
});
} else if (sub === "call") {
const tool = flagValue("--tool");
if (!tool) {
process.stderr.write("rdk-agent mcp-client call: --tool <name> is required\n");
process.exitCode = 2;
return;
}
let args: Record<string, unknown> = {};
const rawArgs = flagValue("--args");
if (rawArgs) {
try {
args = JSON.parse(rawArgs) as Record<string, unknown>;
} catch {
process.stderr.write("rdk-agent mcp-client call: --args must be valid JSON\n");
process.exitCode = 2;
return;
}
}
callExternalTool(serverName, tool, args)
.then((text) => {
process.stdout.write(text + "\n");
})
.catch((err) => {
process.stderr.write(`rdk-agent mcp-client: ${err instanceof Error ? err.message : String(err)}\n`);
process.exitCode = 1;
});
} else {
process.stderr.write("rdk-agent mcp-client: subcommand must be list|call\n");
process.exitCode = 2;
}
}
if (isGui) {
launchGui();
} else if (isMcpClient) {
runMcpClient();
} else if (isTui) {
startTui();
} else if (isMcp) {
const workspaceRoot = flagValue("--workspace-root") ?? resolveDefaultWorkspaceRoot();
const deviceService = new DeviceService();
const taskService = buildTaskService(workspaceRoot);
runMcpServer(deviceService, taskService)
.then(async () => {
await taskService.close();
await deviceService.close();
})
.catch((err) => {
// Log to stderr only — stdout is the MCP JSON-RPC channel.
process.stderr.write(`rdk-agent mcp: ${err instanceof Error ? err.message : String(err)}\n`);
process.exitCode = 1;
});

View File

@ -1,8 +1,13 @@
/**
* Product CLI (S1-A device surface, docs/12 §3).
* Product CLI (docs/12 §3, S1-B §7).
*
* Subcommands: device list|inspect, version, doctor. No run/task surface yet.
* ``--json`` writes exactly one envelope to stdout; logs go to stderr.
* Subcommands:
* device list|inspect, version, doctor — S1-A JSON-only surfaces;
* run "<goal>" — start a health-card task;
* task list|status|steer|cancel|resume — observe/drive tasks.
*
* `run`/`task` default to concise human progress; `--json` writes exactly one
* envelope; `--follow` streams JSONL events. Logs always go to stderr.
*/
import { randomUUID } from "node:crypto";
@ -13,13 +18,30 @@ import { RdkProtocolError } from "@rdk/rdk-agent-pi";
import { DeviceService } from "./deviceService.js";
import { envelope } from "./envelope.js";
import { exitCodeFor } from "./exitCodes.js";
import { buildTaskService } from "./taskServiceFactory.js";
import {
TASK_MODES,
TaskService,
type TaskEvent,
type TaskMode,
} from "./taskService.js";
import { WorkspaceError } from "./workspace.js";
const VERSION = "0.1.0";
const CLI_OWNER = "cli";
function printEnvelope(payload: ReturnType<typeof envelope>): void {
process.stdout.write(JSON.stringify(payload) + "\n");
}
function printHuman(lines: string[]): void {
for (const line of lines) process.stdout.write(line + "\n");
}
function printJsonl(events: TaskEvent[]): void {
for (const event of events) process.stdout.write(JSON.stringify(event) + "\n");
}
function errorEnvelope(err: unknown, correlationId: string) {
if (err instanceof RdkProtocolError) {
return envelope(false, null, {
@ -29,6 +51,9 @@ function errorEnvelope(err: unknown, correlationId: string) {
details: err.details,
}, correlationId);
}
if (err instanceof WorkspaceError) {
return envelope(false, null, { code: err.code, message: err.message, retryable: false }, correlationId);
}
return envelope(false, null, {
code: "RDK-EXEC-004",
message: err instanceof Error ? err.message : String(err),
@ -36,20 +61,63 @@ function errorEnvelope(err: unknown, correlationId: string) {
}, correlationId);
}
export async function main(argv: string[]): Promise<number> {
export interface CliDeps {
taskService?: TaskService;
}
function resolveWorkspaceRoot(workspaceRoot: string | undefined): string {
// docs/12 §6: an absent workspace-root is a clear input error — never a silent
// fallback to the repository root or the user's home directory.
const resolved = workspaceRoot ?? process.env.RDK_WORKSPACE_ROOT;
if (!resolved) {
throw new RdkProtocolError(
"RDK-INV-001",
"workspace-root is required: pass --workspace-root or set RDK_WORKSPACE_ROOT",
);
}
return resolved;
}
function modeFrom(values: { mode?: string }): TaskMode {
const raw = values.mode ?? "guide";
if (!(TASK_MODES as readonly string[]).includes(raw)) {
throw new RdkProtocolError("RDK-INV-001", `--mode must be one of ${TASK_MODES.join("|")}`);
}
return raw as TaskMode;
}
export async function main(argv: string[], deps: CliDeps = {}): Promise<number> {
const correlationId = `corr-${randomUUID().replaceAll("-", "").slice(0, 12)}`;
const { values, positionals } = parseArgs({
args: argv,
allowPositionals: true,
options: {
json: { type: "boolean", default: false },
device: { type: "string" },
follow: { type: "boolean", default: false },
device: { type: "string", multiple: true },
refresh: { type: "string", default: "cached" },
workspace: { type: "string" },
"workspace-root": { type: "string" },
mode: { type: "string" },
reason: { type: "string" },
"take-over": { type: "boolean", default: false },
},
});
const [command, sub] = positionals;
const service = new DeviceService();
const json = values.json;
const follow = values.follow;
let deviceService: DeviceService | null = null;
let taskService: TaskService | null = deps.taskService ?? null;
const ensureTaskService = (): TaskService => {
if (taskService === null) {
taskService = buildTaskService(resolveWorkspaceRoot(values["workspace-root"]));
}
return taskService;
};
try {
if (command === "version") {
printEnvelope(envelope(true, { version: VERSION, protocol_version: "1.0" }, null, correlationId));
@ -62,26 +130,224 @@ export async function main(argv: string[]): Promise<number> {
}, null, correlationId));
return 0;
}
if (command === "device" && sub === "list") {
const devices = await service.listDevices();
printEnvelope(envelope(true, { devices }, null, correlationId));
return 0;
if (command === "device") {
deviceService = new DeviceService();
if (sub === "list") {
const devices = await deviceService.listDevices();
printEnvelope(envelope(true, { devices }, null, correlationId));
return 0;
}
if (sub === "inspect") {
const deviceId = values.device?.[0];
if (!deviceId) {
printEnvelope(envelope(false, null, {
code: "RDK-INV-001", message: "--device is required", retryable: false,
}, correlationId));
return 2;
}
const result = await deviceService.inspectDevice(
deviceId,
values.refresh as "cached" | "quick" | "full",
);
printEnvelope(envelope(true, result, null, correlationId));
return 0;
}
}
if (command === "device" && sub === "inspect") {
const deviceId = values.device;
if (!deviceId) {
// -- run ---------------------------------------------------------------
if (command === "run") {
const goal = positionals[1];
if (!goal) {
printEnvelope(envelope(false, null, {
code: "RDK-INV-001", message: "--device is required", retryable: false,
code: "RDK-INV-001", message: "run requires a quoted <goal>", retryable: false,
}, correlationId));
return 2;
}
const result = await service.inspectDevice(
deviceId,
values.refresh as "cached" | "quick" | "full",
const service = ensureTaskService();
const handle = await service.startTask(
goal,
values.workspace ?? ".",
values.device ?? [],
modeFrom(values),
CLI_OWNER,
);
printEnvelope(envelope(true, result, null, correlationId));
if (follow) {
const snapshot = await service.getTask(handle.task_id);
printJsonl(snapshot.events);
return 0;
}
if (json) {
printEnvelope(envelope(true, handle, null, correlationId));
return 0;
}
printHuman([
`task started: ${handle.task_id}`,
`state: ${handle.state}`,
`cursor: ${handle.cursor}`,
]);
return 0;
}
// -- task --------------------------------------------------------------
if (command === "task") {
const service = ensureTaskService();
const taskId = positionals[2];
if (sub === "list") {
const tasks = await service.listTasks();
if (json) {
printEnvelope(envelope(true, { tasks }, null, correlationId));
return 0;
}
if (tasks.length === 0) {
printHuman(["no tasks"]);
} else {
printHuman(tasks.map((t) => `${t.task_id}\t${t.state}\t${t.workspace_id}`));
}
return 0;
}
if (!taskId) {
printEnvelope(envelope(false, null, {
code: "RDK-INV-001", message: `task ${sub} requires a TASK_ID`, retryable: false,
}, correlationId));
return 2;
}
if (sub === "status") {
const snapshot = await service.getTask(taskId);
if (follow) {
printJsonl(snapshot.events);
return 0;
}
if (json) {
printEnvelope(envelope(true, snapshot, null, correlationId));
return 0;
}
const s = snapshot.status;
printHuman([
`${s.task_id}\t${s.state}\toutcome=${s.outcome ?? "—"}`,
`workspace=${s.workspace_id} devices=${s.device_ids.join(",") || "—"}`,
`evidence=${s.evidence_refs.length} events=${snapshot.events.length}`,
]);
return 0;
}
if (sub === "steer") {
const message = positionals[3];
if (!message) {
printEnvelope(envelope(false, null, {
code: "RDK-INV-001", message: "steer requires a quoted <message>", retryable: false,
}, correlationId));
return 2;
}
const handle = await service.steerTask(taskId, message, CLI_OWNER);
if (json) {
printEnvelope(envelope(true, handle, null, correlationId));
return 0;
}
printHuman([`steered ${taskId}: state=${handle.state} cursor=${handle.cursor}`]);
return 0;
}
if (sub === "cancel") {
const handle = await service.cancelTask(taskId, values.reason ?? "", CLI_OWNER);
if (json) {
printEnvelope(envelope(true, handle, null, correlationId));
return 0;
}
printHuman([`cancelled ${taskId}: state=${handle.state}`]);
return 0;
}
if (sub === "resume") {
const handle = await service.resumeTask(taskId, CLI_OWNER, values["take-over"]);
if (json) {
printEnvelope(envelope(true, handle, null, correlationId));
return 0;
}
printHuman([`resumed ${taskId}: state=${handle.state} cursor=${handle.cursor}`]);
return 0;
}
if (sub === "artifact") {
const artifactId = positionals[3];
if (!artifactId) {
printEnvelope(envelope(false, null, {
code: "RDK-INV-001", message: "artifact requires an <ARTIFACT_ID>", retryable: false,
}, correlationId));
return 2;
}
const result = await service.readArtifact(taskId, artifactId);
if (json) {
printEnvelope(envelope(true, result, null, correlationId));
return 0;
}
const preview = (result as { preview?: string }).preview;
printHuman([
`artifact ${artifactId} of ${taskId}`,
preview ?? JSON.stringify(result),
]);
return 0;
}
}
// -- pack (S3: capability library) --------------------------------------
if (command === "pack") {
const service = ensureTaskService();
if (sub === "list") {
const result = await service.listPacks();
if (json) {
printEnvelope(envelope(true, result, null, correlationId));
return 0;
}
const packs = (result as { packs?: Array<{ name: string; entrypoint: string }> }).packs ?? [];
if (packs.length === 0) printHuman(["no packs"]);
else printHuman(packs.map((p) => `${p.name}\t${p.entrypoint}`));
return 0;
}
const name = positionals[2];
if (sub === "save") {
const workspaceId = positionals[3];
const planId = positionals[4];
if (!name || !workspaceId || !planId) {
printEnvelope(envelope(false, null, {
code: "RDK-INV-001",
message: "pack save requires <NAME> <WORKSPACE_ID> <PLAN_ID>",
retryable: false,
}, correlationId));
return 2;
}
const result = await service.savePack(name, workspaceId, planId);
if (json) {
printEnvelope(envelope(true, result, null, correlationId));
return 0;
}
printHuman([`saved pack ${name}`]);
return 0;
}
if (sub === "run") {
const deviceId = values.device?.[0] ?? process.env.RDK_DEVICE_ID;
const requestId = positionals[3] ?? `pack-${name}-${Date.now()}`;
if (!name || !deviceId) {
printEnvelope(envelope(false, null, {
code: "RDK-INV-001",
message: "pack run requires <NAME> and --device (or RDK_DEVICE_ID)",
retryable: false,
}, correlationId));
return 2;
}
const result = await service.runPack(name, deviceId, requestId);
if (json) {
printEnvelope(envelope(true, result, null, correlationId));
return 0;
}
const rec = (result as { record?: { run_id: string; state: string; outcome: string } }).record;
printHuman([`pack ${name} run: ${rec?.run_id ?? "?"} state=${rec?.state ?? "?"} outcome=${rec?.outcome ?? "?"}`]);
return 0;
}
}
printEnvelope(envelope(false, null, {
code: "RDK-INV-001",
message: `unknown or not-yet-open command: ${positionals.join(" ")}`,
@ -90,8 +356,11 @@ export async function main(argv: string[]): Promise<number> {
return 2;
} catch (err) {
printEnvelope(errorEnvelope(err, correlationId));
return err instanceof RdkProtocolError ? exitCodeFor(err) : 8;
return err instanceof RdkProtocolError ? exitCodeFor(err)
: err instanceof WorkspaceError ? 2
: 8;
} finally {
await service.close();
if (deviceService !== null) await deviceService.close();
if (taskService !== null && deps.taskService === undefined) await taskService.close();
}
}

View File

@ -1,9 +1,11 @@
/**
* Device discovery + read-only inspection (S1-A, docs/12 §6.2).
* Device discovery, inspection, and the human connect flow (S1-A/S1-C,
* docs/12 §4/§6.2).
*
* This surface only lists/inspects devices; it has no task/run surface yet
* (S1-B). It calls the SAME application service as every other entry — one
* RdkHostClient against `rdk-agent-host serve --stdio`.
* Read-only methods talk to the model-facing server (`serve --stdio`); the
* human connect flow (register + host-key TOFU) talks to the SAME application
* service through the human authority plane (`serve --stdio --role human`) —
* trust decisions never ride the model-facing method set (docs/05 §7).
*/
import { RdkHostClient, RdkProtocolError } from "@rdk/rdk-agent-pi";
@ -14,6 +16,10 @@ export interface DeviceSummary {
transport: string;
connected: boolean;
host_key_confirmed: boolean;
ssh_host: string | null;
fingerprint: string | null;
registered_at: string | null;
last_seen_at: string | null;
}
export interface InspectResult {
@ -23,14 +29,78 @@ export interface InspectResult {
evidence_refs: string[];
}
/** Sanitized TOFU candidate: fingerprint only, never raw key material (§6.2). */
export interface HostKeyCandidateInfo {
candidate_id: string;
host: string;
key_type: string;
fingerprint_sha256: string;
}
export interface HostKeyConfirmation {
candidate_id: string;
host: string;
fingerprint_sha256: string;
}
export interface RegisterDeviceInput {
alias: string;
ssh_config_host: string;
expected_host_key_sha256?: string;
labels?: Record<string, string>;
}
export interface RegisteredDevice {
device_id: string;
alias: string;
transport: {
type: string;
ssh_config_host: string | null;
expected_host_key_sha256: string | null;
};
labels: Record<string, string>;
}
export interface DiscoveredDevice {
host: string;
port: number;
}
export interface AuthOnboardResult {
ok: boolean;
detail?: string;
}
export interface FlashImageView {
board_model: string;
image_id: string;
source_url: string;
sha256: string;
compatible_boards: string[];
}
export interface TemplateView {
name: string;
title: string;
description: string;
requires: string[];
missing: string[];
runnable: boolean;
}
const DEFAULT_COMMAND = ["rdk-agent-host", "serve", "--stdio"];
export class DeviceService {
private client: RdkHostClient;
private humanClient: RdkHostClient;
constructor(command?: string[]) {
const resolved = command ?? resolveCommand();
this.client = new RdkHostClient({ command: resolved, timeoutMs: 30_000 });
this.humanClient = new RdkHostClient({
command: [...resolved, "--role", "human"],
timeoutMs: 30_000,
});
}
async listDevices(): Promise<DeviceSummary[]> {
@ -49,8 +119,128 @@ export class DeviceService {
return result;
}
/** TOFU step 1: fetch the board's host key and its SHA256 fingerprint. */
async showHostKey(host: string): Promise<HostKeyCandidateInfo> {
const result = await this.humanClient.call<{ candidate: HostKeyCandidateInfo }>(
"hostkey.show",
{ host },
);
return result.candidate;
}
/** TOFU step 2: a human trusts the shown fingerprint; writes known_hosts. */
async confirmHostKey(candidateId: string): Promise<HostKeyConfirmation> {
return this.humanClient.call<HostKeyConfirmation>("hostkey.confirm", {
candidate_id: candidateId,
});
}
async registerDevice(input: RegisterDeviceInput): Promise<RegisteredDevice> {
const result = await this.humanClient.call<{ registration: RegisteredDevice }>(
"device.register",
{ ...input },
);
return result.registration;
}
async unregisterDevice(deviceId: string): Promise<{ device_id: string; unregistered: boolean }> {
return this.humanClient.call("device.unregister", { device_id: deviceId });
}
/** Bounded local-subnet SSH discovery (USB RNDIS default + direct links first). */
async discoverDevices(): Promise<DiscoveredDevice[]> {
const result = await this.humanClient.call<{ candidates: DiscoveredDevice[] }>(
"device.discover",
);
return result.candidates;
}
/** Key-based liveness probe (BatchMode): can we already log in without a password? */
async authCheck(host: string): Promise<boolean> {
const result = await this.humanClient.call<{ ok: boolean }>("device.auth_check", { host });
return result.ok;
}
/** One-shot controlled password login to install the product key (docs/05 §5). */
async onboardKey(input: {
host: string;
user: string;
password: string;
}): Promise<AuthOnboardResult> {
return this.humanClient.call<AuthOnboardResult>("device.onboard_key", { ...input });
}
// -- human console + flashing wizard (never on the model plane) ----------
async listSerialPorts(): Promise<string[]> {
const result = await this.humanClient.call<{ ports: string[] }>("serial.ports");
return result.ports;
}
async tailSerial(port: string, maxLines = 200): Promise<string[]> {
const result = await this.humanClient.call<{ lines: string[] }>("serial.tail", {
port,
max_lines: maxLines,
});
return result.lines;
}
async flashImages(boardModel?: string): Promise<FlashImageView[]> {
const result = await this.humanClient.call<{ images: FlashImageView[] }>("flash.images", {
board_model: boardModel ?? null,
});
return result.images;
}
async suggestFlash(input: {
device_id: string;
board_model: string;
image_id: string;
}): Promise<Record<string, unknown>> {
return this.humanClient.call("flash.suggest", { ...input });
}
async confirmFlash(flashId: string): Promise<Record<string, unknown>> {
return this.humanClient.call("flash.confirm", { flash_id: flashId });
}
async runFlash(flashId: string): Promise<Record<string, unknown>> {
return this.humanClient.call("flash.run", { flash_id: flashId });
}
async flashStatus(flashId: string): Promise<Record<string, unknown>> {
return this.humanClient.call("flash.status", { flash_id: flashId });
}
async cancelFlash(flashId: string): Promise<Record<string, unknown>> {
return this.humanClient.call("flash.cancel", { flash_id: flashId });
}
// -- deterministic one-click templates (no LLM; CFR-003/014) -------------
async listTemplates(deviceId: string): Promise<TemplateView[]> {
const result = await this.humanClient.call<{ templates: TemplateView[] }>(
"template.list",
{ device_id: deviceId },
);
return result.templates;
}
async runTemplate(
name: string,
deviceId: string,
requestId: string,
): Promise<Record<string, unknown>> {
return this.humanClient.call("template.run", {
name,
device_id: deviceId,
request_id: requestId,
});
}
async close(): Promise<void> {
await this.client.close();
await this.humanClient.close();
}
}

View File

@ -10,6 +10,7 @@ const BY_PREFIX: Array<[string, number]> = [
["RDK-EXEC-", 5],
["RDK-DEV-", 3],
["RDK-PROTO-", 2],
["RDK-OWNER-", 6],
];
export function exitCodeFor(error: RdkProtocolError): number {

View File

@ -0,0 +1,66 @@
/**
* The S1-B "system health card" scripted task (docs/12 §8, S1-B §1).
*
* A deterministic, READ-ONLY ScriptedModel script: inventory one device, then
* inspect it. No device writes, no real S100P, no network. The observable
* evidence is the device snapshot the Host stores after inventory — any other
* surface can then observe the same facts via `task`/`device` queries.
*/
import { mkdirSync } from "node:fs";
import {
registerScriptedModel,
writeScriptedModelConfig,
type ScriptedModelHandle,
type ScriptedTurn,
} from "@rdk/rdk-agent-pi";
export interface HealthCardModel {
model: ScriptedModelHandle["model"];
}
/** The fixed read-only script for the first device in the task. */
export function buildHealthCardTurns(deviceIds: readonly string[]): ScriptedTurn[] {
const deviceId = deviceIds[0] ?? "fake-001";
return [
{
toolCalls: [
{ name: "rdk_device_inventory", arguments: { deviceId, profile: "quick" } },
],
},
{ toolCalls: [{ name: "rdk_device_inspect", arguments: { deviceId } }] },
{ text: `health card for ${deviceId}: read-only facts captured (no device writes)` },
];
}
/**
* Write the scripted provider config into a per-task agent dir and register the
* scripted model. No network, no credentials.
*/
export async function createHealthCardModel(
agentDir: string,
deviceIds: readonly string[],
): Promise<HealthCardModel> {
return createScriptedModel(agentDir, buildHealthCardTurns(deviceIds));
}
/** A resumed task re-attaches with a recovery-context script. When the Task
* service has no recovery context (e.g. steerTask re-attaching a disposed
* session), the default ack is used; it never re-runs anything. */
export function buildResumeTurns(context?: string): ScriptedTurn[] {
return [{ text: context ?? "resumed: re-attached to the existing task" }];
}
/**
* Generic scripted-model registration for an arbitrary turn script.
*/
export async function createScriptedModel(
agentDir: string,
turns: readonly ScriptedTurn[],
): Promise<HealthCardModel> {
mkdirSync(agentDir, { recursive: true });
writeScriptedModelConfig(agentDir);
const scripted = await registerScriptedModel([...turns]);
return { model: scripted.model };
}

View File

@ -0,0 +1,41 @@
/**
* Public package entry for @rdk/rdk-agent-surface (S1-B §4, §5).
*
* The CLI, TUI, GUI (Electron main) and MCP adapters all import the SAME
* TaskService / DeviceService from here. This barrel is the package contract:
* it must never be deleted or turned into a loose `export *` — that would
* silently expose internal implementation details (owner lock, workspace,
* envelope, exit codes). Keep it an explicit, reviewed surface.
*/
export { DeviceService } from "./deviceService.js";
export type {
AuthOnboardResult,
DeviceSummary,
DiscoveredDevice,
FlashImageView,
HostKeyCandidateInfo,
HostKeyConfirmation,
InspectResult,
RegisterDeviceInput,
RegisteredDevice,
TemplateView,
} from "./deviceService.js";
export { ProjectService } from "./projectService.js";
export type { WorkspaceEntry, WorkspaceFile } from "./projectService.js";
export { TaskService } from "./taskService.js";
export type { TaskServiceOptions } from "./taskService.js";
export { buildTaskService } from "./taskServiceFactory.js";
export { listSkills, readSkill } from "./tui.js";
// Real-model config helpers (re-exported from the Pi package so the desktop
// and other single-dep surfaces can read/write ~/.rdk/.env without depending
// on @rdk/rdk-agent-pi directly).
export {
defaultRealModelDotEnvPath,
resolveRealModelConfig,
writeRealModelDotEnv,
} from "@rdk/rdk-agent-pi";

View File

@ -1,9 +1,15 @@
/**
* MCP stdio server (S1-A device surface, docs/12 §6, CSEC-011/012).
* MCP stdio server (docs/12 §6, S1-B §7, CSEC-011/012).
*
* Two tools only: rdk_device_list, rdk_device_inspect. No listen port, no
* sampling, no task/approval/terminal/serial/flash/credential surface.
* Actor is external_agent; the caller can never self-approve.
* Exactly seven high-level tools, in a stable order:
*
* rdk_device_list, rdk_device_inspect,
* rdk_task_start, rdk_task_status, rdk_task_steer, rdk_task_cancel,
* rdk_artifact_read
*
* No listen port, no sampling, no approval decision, no terminal/serial/flash/
* credential tool. The caller is an external agent: it can never self-approve,
* complete a required action, or take over a task owner.
*/
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
@ -12,17 +18,22 @@ import { RdkProtocolError } from "@rdk/rdk-agent-pi";
import { z } from "zod";
import { DeviceService } from "./deviceService.js";
import { TaskService, type TaskMode } from "./taskService.js";
const SERVER_NAME = "rdk-agent";
const MCP_OWNER = "mcp";
export function createMcpServer(service: DeviceService): McpServer {
export function createMcpServer(
deviceService: DeviceService,
taskService: TaskService,
): McpServer {
const server = new McpServer({ name: SERVER_NAME, version: "0.1.0" });
server.registerTool(
"rdk_device_list",
{ description: "List registered devices (id, alias, transport, connection state, host-key confirmation)." },
async () => {
const devices = await service.listDevices();
const devices = await deviceService.listDevices();
return { content: [{ type: "text" as const, text: JSON.stringify(devices) }] };
},
);
@ -38,7 +49,85 @@ export function createMcpServer(service: DeviceService): McpServer {
},
},
async (args) => {
const result = await service.inspectDevice(args.device_id, args.refresh ?? "cached");
const result = await deviceService.inspectDevice(args.device_id, args.refresh ?? "cached");
return { content: [{ type: "text" as const, text: JSON.stringify(result) }] };
},
);
server.registerTool(
"rdk_task_start",
{
description:
"Start a system health-card task in a workspace under the bound workspace-root. mode is guide|auto_low_risk. Returns task_id, state, cursor.",
inputSchema: {
goal: z.string(),
workspace: z.string(),
device_ids: z.array(z.string()).optional(),
mode: z.enum(["guide", "auto_low_risk"]).optional(),
},
},
async (args) => {
const handle = await taskService.startTask(
args.goal,
args.workspace,
args.device_ids ?? [],
(args.mode ?? "guide") as TaskMode,
MCP_OWNER,
);
return { content: [{ type: "text" as const, text: JSON.stringify(handle) }] };
},
);
server.registerTool(
"rdk_task_status",
{
description:
"Read one task's state, outcome, evidence, events and required_action. No model reasoning or raw logs are returned.",
inputSchema: {
task_id: z.string(),
after_event_seq: z.number().int().min(0).optional(),
},
},
async (args) => {
const snapshot = await taskService.getTask(args.task_id, args.after_event_seq ?? 0);
return { content: [{ type: "text" as const, text: JSON.stringify(snapshot) }] };
},
);
server.registerTool(
"rdk_task_steer",
{
description:
"Append user intent to an existing task. Cannot change policy, verifiers, workspace root, device identity or approval state.",
inputSchema: { task_id: z.string(), message: z.string() },
},
async (args) => {
const handle = await taskService.steerTask(args.task_id, args.message, MCP_OWNER);
return { content: [{ type: "text" as const, text: JSON.stringify(handle) }] };
},
);
server.registerTool(
"rdk_task_cancel",
{
description: "Idempotently cancel a task's agent turn and active runs; returns the final/cleanup state.",
inputSchema: { task_id: z.string(), reason: z.string().optional() },
},
async (args) => {
const handle = await taskService.cancelTask(args.task_id, args.reason ?? "", MCP_OWNER);
return { content: [{ type: "text" as const, text: JSON.stringify(handle) }] };
},
);
server.registerTool(
"rdk_artifact_read",
{
description:
"Read a task artifact's sanitized preview/metadata. Large files return a reference only, never an arbitrary path.",
inputSchema: { task_id: z.string(), artifact_id: z.string() },
},
async (args) => {
const result = await taskService.readArtifact(args.task_id, args.artifact_id);
return { content: [{ type: "text" as const, text: JSON.stringify(result) }] };
},
);
@ -46,10 +135,31 @@ export function createMcpServer(service: DeviceService): McpServer {
return server;
}
export async function runMcpServer(service: DeviceService): Promise<void> {
const server = createMcpServer(service);
export async function runMcpServer(
deviceService: DeviceService,
taskService: TaskService,
): Promise<void> {
const server = createMcpServer(deviceService, taskService);
const transport = new StdioServerTransport();
await server.connect(transport);
// `connect()` resolves as soon as the stdio transport has registered its
// stdin listeners — it does NOT block (see sdk StdioServerTransport.start()).
// Without gating here, the caller's `.then(close)` would tear down the
// TaskService (and its spawned Host child) before any tool call runs. Block
// until the client disconnects or the process is signalled instead, so the
// TaskService stays live for the whole MCP session.
await new Promise<void>((resolve) => {
// stdin may already have ended by the time the server starts (e.g. a spawned
// client closed its pipe before connect()) — don't hang in that case.
if (process.stdin.readableEnded || process.stdin.destroyed) {
resolve();
return;
}
const done = () => resolve();
process.stdin.once("end", done);
process.stdin.once("close", done);
});
await server.close();
}
export { RdkProtocolError };

View File

@ -0,0 +1,96 @@
/**
* Controlled MCP *client* (connect OUT to explicitly-allowlisted servers).
*
* Trust model (docs/05 default-deny, CSEC-011/012): the ONLY servers this client
* will talk to are the ones a human wrote into the allowlist config
* (`RDK_MCP_CONFIG` path, default `~/.rdk/mcp.json`). External tool results are
* UNTRUSTED text: they are surfaced to a human (CLI/TUI) and are never promoted
* to device facts, capabilities, or policy inputs. This client is for the human
* authority plane; it is NOT exposed to the Pi agent or to external MCP callers.
*/
import { existsSync, readFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
export interface ExternalMcpServerConfig {
name: string;
command: string;
args?: string[];
env?: Record<string, string>;
}
export interface ExternalMcpConfig {
servers: ExternalMcpServerConfig[];
}
export function resolveMcpConfigPath(): string {
return process.env.RDK_MCP_CONFIG ?? join(homedir(), ".rdk", "mcp.json");
}
export function loadExternalMcpConfig(): ExternalMcpConfig {
const path = resolveMcpConfigPath();
if (!existsSync(path)) return { servers: [] };
try {
const parsed = JSON.parse(readFileSync(path, "utf-8")) as Partial<ExternalMcpConfig>;
return { servers: Array.isArray(parsed.servers) ? parsed.servers : [] };
} catch {
return { servers: [] };
}
}
export function getServer(name: string): ExternalMcpServerConfig | undefined {
return loadExternalMcpConfig().servers.find((s) => s.name === name);
}
export async function withClient<T>(
server: ExternalMcpServerConfig,
fn: (client: Client) => Promise<T>,
): Promise<T> {
const transport = new StdioClientTransport({
command: server.command,
args: server.args ?? [],
env: { ...process.env, ...(server.env ?? {}) } as Record<string, string>,
});
const client = new Client({ name: "rdk-agent-mcp-client", version: "0.1.0" });
await client.connect(transport);
try {
return await fn(client);
} finally {
await client.close();
}
}
export async function listExternalTools(serverName: string): Promise<
Array<{ name: string; description?: string }>
> {
const server = getServer(serverName);
if (!server) throw new Error(`external MCP server not in allowlist: ${serverName}`);
return withClient(server, async (client) => {
const tools = await client.listTools();
return tools.tools.map((t) => ({
name: t.name,
...(t.description !== undefined ? { description: t.description } : {}),
}));
});
}
export async function callExternalTool(
serverName: string,
tool: string,
args: Record<string, unknown> = {},
): Promise<string> {
const server = getServer(serverName);
if (!server) throw new Error(`external MCP server not in allowlist: ${serverName}`);
return withClient(server, async (client) => {
const result = await client.callTool({ name: tool, arguments: args });
const content = (result.content ?? []) as Array<{ type: string; text?: string }>;
return content
.filter((c) => c.type === "text" && typeof c.text === "string")
.map((c) => c.text as string)
.join("\n");
});
}

View File

@ -0,0 +1,144 @@
/**
* Per-task local owner lock (docs/12 §7, S1-B §6).
*
* A single-writer guard at `state/task-locks/<task-id>.json`. It is NOT a
* domain object, a lease service, or a distributed lock: it only protects one
* host's task state from two local surfaces writing at once. Real device side
* effects stay protected by request-id idempotency and the Device write lease.
*
* Atomicity comes from the OS `wx` create flag — two concurrent acquirers
* cannot both win. A stale lock (heartbeat too old, or owner pid gone) is
* eligible for explicit take-over only; the caller must reconcile active Runs
* first. `process_started_at` is recorded so a future layer can also guard
* against pid reuse, but pid liveness + heartbeat are the primary signals.
*/
import { randomUUID } from "node:crypto";
import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
export const LOCK_SCHEMA_VERSION = "1.0";
export const LOCK_HEARTBEAT_TTL_MS = 30_000;
export interface LockRecord {
schema_version: typeof LOCK_SCHEMA_VERSION;
task_id: string;
owner_instance_id: string;
pid: number;
process_started_at: string;
heartbeat_at: string;
}
export type PidLiveness = (pid: number) => boolean;
/** Default liveness: `kill(pid, 0)` throws ESRCH when dead, EPERM when alive. */
export function pidAlive(pid: number): boolean {
try {
process.kill(pid, 0);
return true;
} catch (err) {
return (err as NodeJS.ErrnoException).code === "EPERM";
}
}
export function newOwnerInstanceId(): string {
return `instance-${randomUUID()}`;
}
export type AcquireResult =
| { held: true }
| { held: false; existing: LockRecord; stale: boolean };
export class OwnerLock {
constructor(
private readonly lockDir: string,
private readonly liveness: PidLiveness = pidAlive,
) {}
private pathFor(taskId: string): string {
return join(this.lockDir, `${taskId}.json`);
}
/** Read-only observation: never mutates state. Returns null when absent. */
read(taskId: string): LockRecord | null {
try {
const raw = readFileSync(this.pathFor(taskId), "utf8");
const parsed = JSON.parse(raw) as LockRecord;
if (parsed.task_id !== taskId || parsed.schema_version !== LOCK_SCHEMA_VERSION) {
return null;
}
return parsed;
} catch {
return null;
}
}
isStale(record: LockRecord, nowMs: number): boolean {
const heartbeatAge = nowMs - Date.parse(record.heartbeat_at);
if (Number.isNaN(heartbeatAge) || heartbeatAge > LOCK_HEARTBEAT_TTL_MS) return true;
return !this.liveness(record.pid);
}
/**
* Atomically acquire the lock. Returns `held: false` when another live owner
* holds it (with `stale` flagging whether that owner is eligible for
* take-over). Never steals a fresh lock.
*/
acquire(taskId: string, ownerInstanceId: string, nowMs: number): AcquireResult {
mkdirSync(this.lockDir, { recursive: true });
const record: LockRecord = {
schema_version: LOCK_SCHEMA_VERSION,
task_id: taskId,
owner_instance_id: ownerInstanceId,
pid: process.pid,
process_started_at: new Date(nowMs).toISOString(),
heartbeat_at: new Date(nowMs).toISOString(),
};
try {
writeFileSync(this.pathFor(taskId), JSON.stringify(record, null, 2) + "\n", {
flag: "wx",
});
return { held: true };
} catch (err) {
if ((err as NodeJS.ErrnoException).code !== "EEXIST") throw err;
const existing = this.read(taskId);
if (existing === null) {
// A torn/foreign file; treat as not-held and let takeOver reclaim it.
return { held: false, existing: record, stale: true };
}
return { held: false, existing, stale: this.isStale(existing, nowMs) };
}
}
/**
* Explicit take-over (GUI/TUI/CLI user action). Succeeds only when the
* current lock is absent or stale; a fresh live owner is never displaced.
*/
takeOver(taskId: string, ownerInstanceId: string, nowMs: number): AcquireResult {
const existing = this.read(taskId);
if (existing === null) {
return this.acquire(taskId, ownerInstanceId, nowMs);
}
if (!this.isStale(existing, nowMs)) {
return { held: false, existing, stale: false };
}
// Reclaim the stale lock, then acquire atomically.
rmSync(this.pathFor(taskId), { force: true });
return this.acquire(taskId, ownerInstanceId, nowMs);
}
/** Refresh this owner's heartbeat. No-op when this owner no longer holds it. */
heartbeat(taskId: string, ownerInstanceId: string, nowMs: number): void {
const existing = this.read(taskId);
if (existing === null || existing.owner_instance_id !== ownerInstanceId) return;
existing.heartbeat_at = new Date(nowMs).toISOString();
writeFileSync(this.pathFor(taskId), JSON.stringify(existing, null, 2) + "\n");
}
/** Release only when this owner holds it; never remove another owner's lock. */
release(taskId: string, ownerInstanceId: string): void {
const existing = this.read(taskId);
if (existing === null || existing.owner_instance_id !== ownerInstanceId) return;
rmSync(this.pathFor(taskId), { force: true });
}
}

View File

@ -0,0 +1,65 @@
/**
* Project workspace browsing (human surface of the GUI project page).
*
* Wraps the host's versioned `workspace.*` methods with the product workspace
* as root. Read-only by design here: editing stays in the code editor/TUI
* surfaces (docs/12 §5); the GUI project page shows what a task wrote.
*/
import { RdkHostClient, RdkProtocolError } from "@rdk/rdk-agent-pi";
export interface WorkspaceEntry {
relpath: string;
kind: "file" | "dir";
size_bytes: number;
}
export interface WorkspaceFile {
path: string;
content: string;
}
const DEFAULT_COMMAND = ["rdk-agent-host", "serve", "--stdio"];
export class ProjectService {
private client: RdkHostClient;
constructor(command?: string[]) {
const resolved = command ?? resolveCommand();
this.client = new RdkHostClient({ command: resolved, timeoutMs: 30_000 });
}
async listEntries(path = ".", workspaceId = "."): Promise<WorkspaceEntry[]> {
const result = await this.client.call<{ entries: WorkspaceEntry[] }>(
"workspace.list",
{ workspace_id: workspaceId, path },
);
return result.entries;
}
async readFile(path: string, workspaceId = "."): Promise<WorkspaceFile> {
return this.client.call<WorkspaceFile>("workspace.read", {
workspace_id: workspaceId,
path,
});
}
async writeFile(path: string, content: string, workspaceId = "."): Promise<void> {
await this.client.call("workspace.write", {
workspace_id: workspaceId,
path,
content,
});
}
async close(): Promise<void> {
await this.client.close();
}
}
function resolveCommand(): string[] {
const raw = process.env.RDK_AGENT_COMMAND;
if (raw) return raw.split(/\s+/).filter(Boolean);
return [...DEFAULT_COMMAND];
}
export { RdkProtocolError };

View File

@ -0,0 +1,570 @@
/**
* The shared TaskService (docs/12 §1/§7, S1-B §5).
*
* ONE implementation used by CLI, TUI, GUI and MCP. It owns per-task
* `SessionHandle`s (one independent, recoverable session per active task),
* enforces the workspace boundary through the shared resolver, and guards
* against two local writers with the per-task owner lock. Domain truth (task
* state, runs, artifacts, device facts) always comes from the Host — never
* re-implemented here.
*
* Dependency injection is for tests only: `client` and `sessionFactory`/`model`
* may be faked; production uses `RdkHostClient` + `createRdkSession` + the
* scripted health-card model.
*/
import { mkdirSync } from "node:fs";
import { join } from "node:path";
import {
createRealModel,
createRdkSession,
RdkHostClient,
RdkProtocolError,
type RdkSessionOptions,
type ScriptedTurn,
} from "@rdk/rdk-agent-pi";
import {
buildHealthCardTurns,
buildResumeTurns,
createScriptedModel,
} from "./healthCard.js";
import { newOwnerInstanceId, OwnerLock } from "./ownerLock.js";
import { resolveProjectPath, resolveWorkspaceRoot } from "./workspace.js";
export type TaskMode = "guide" | "auto_low_risk";
export const TASK_MODES: readonly TaskMode[] = ["guide", "auto_low_risk"];
/** The minimal Host client surface TaskService needs (RdkHostClient satisfies it). */
export interface HostClientLike {
call<T = unknown>(method: string, params?: Record<string, unknown>): Promise<T>;
close(): Promise<void>;
}
export interface TaskSession {
prompt(message: string): Promise<unknown>;
dispose(): void;
}
export interface SessionHandleLike {
session: TaskSession;
close(): Promise<void>;
}
export interface SessionOptions {
cwd: string;
packageRoot: string;
agentDir: string;
model?: unknown;
agentCommand?: string[];
}
export type SessionFactory = (options: SessionOptions) => Promise<SessionHandleLike>;
export type ModelFactory = (agentDir: string, turns: ScriptedTurn[]) => Promise<{ model: unknown }>;
/** The real assembly: one shared Host client, one session per task. */
const defaultSessionFactory: SessionFactory = async (options) =>
createRdkSession({
cwd: options.cwd,
packageRoot: options.packageRoot,
agentDir: options.agentDir,
...(options.agentCommand ? { agentCommand: options.agentCommand } : {}),
...(options.model !== undefined
? { model: options.model as Parameters<typeof createRdkSession>[0]["model"] }
: {}),
});
const defaultModelFactory: ModelFactory = async (agentDir, turns) => {
// Real model when a key is configured (docs/08 §8); else the deterministic
// ScriptedModel (no network, no credentials).
const real = createRealModel(agentDir, turns);
if (real) return real;
return createScriptedModel(agentDir, turns);
};
export interface TaskServiceOptions {
client: HostClientLike;
/** Absolute workspace root; every task path resolves strictly under it. */
workspaceRoot: string;
/** Trusted pi-rdk-agent package root (for the session resource loader). */
packageRoot: string;
/** Parent dir for per-task agent dirs. */
agentDirRoot: string;
/** `state/task-locks` dir for the per-task owner lock. */
lockDir: string;
agentCommand?: string[];
ownerInstanceId?: string;
sessionFactory?: SessionFactory;
modelFactory?: ModelFactory;
now?: () => number;
}
export interface RequiredAction {
type: string;
title: string;
description: string;
allowed_surfaces: string[];
}
export interface TaskEvent {
seq: number;
kind: string;
owner: string;
detail: Record<string, unknown>;
at: string;
}
export interface TaskStatus {
task_id: string;
state: string;
outcome: string | null;
workspace_id: string;
device_ids: string[];
evidence_refs: string[];
required_action: RequiredAction | null;
cursor: number;
}
export interface TaskHandle {
task_id: string;
state: string;
cursor: number;
}
export interface TaskSnapshot {
status: TaskStatus;
events: TaskEvent[];
}
interface HostTask {
task_id: string;
goal: string;
state: string;
outcome: string | null;
workspace_id: string;
device_ids: string[];
run_ids: string[];
evidence_refs: string[];
}
/** Subset of the Host `Checkpoint` used to prime a resumed session. */
interface RecoveryCheckpoint {
checkpoint_id: string;
unsatisfied_verifier_ids: string[];
active_run_ids: string[];
completed_run_ids: string[];
waiting_on: string | null;
}
interface TaskRuntime {
taskId: string;
workspaceId: string;
absolute: string;
handle: SessionHandleLike | null;
owner: string;
events: TaskEvent[];
}
export class TaskService {
private readonly client: HostClientLike;
private readonly workspaceRoot: string;
private readonly packageRoot: string;
private readonly agentDirRoot: string;
private readonly lock: OwnerLock;
private readonly instanceId: string;
private readonly agentCommand: string[] | undefined;
private readonly sessionFactory: SessionFactory;
private readonly modelFactory: ModelFactory;
private readonly now: () => number;
private readonly runtimes = new Map<string, TaskRuntime>();
private humanClientInstance: RdkHostClient | null = null;
private closed = false;
constructor(options: TaskServiceOptions) {
this.client = options.client;
this.workspaceRoot = resolveWorkspaceRoot(options.workspaceRoot);
this.packageRoot = options.packageRoot;
this.agentDirRoot = options.agentDirRoot;
this.lock = new OwnerLock(options.lockDir);
this.instanceId = options.ownerInstanceId ?? newOwnerInstanceId();
this.agentCommand = options.agentCommand;
this.sessionFactory = options.sessionFactory ?? defaultSessionFactory;
this.modelFactory = options.modelFactory ?? defaultModelFactory;
this.now = options.now ?? Date.now;
}
// -- lifecycle -------------------------------------------------------------
async startTask(
goal: string,
workspace: string,
deviceIds: string[],
mode: TaskMode,
owner: string,
): Promise<TaskHandle> {
this.assertOpen();
if (!TASK_MODES.includes(mode)) {
throw new RdkProtocolError("RDK-INV-001", `mode must be one of ${TASK_MODES.join("|")}`);
}
// Project spaces are device-scoped: a device-bound task with the shared
// "." space is routed to that device's own space; multi-device tasks must
// not share one space (the host also enforces bindings at task.create).
let routedWorkspace = workspace;
if (workspace === ".") {
if (deviceIds.length === 1) {
routedWorkspace = deviceIds[0] ?? ".";
} else if (deviceIds.length > 1) {
throw new RdkProtocolError(
"RDK-INV-001",
"one project space belongs to exactly one device; start one task per device",
);
}
}
const project = resolveProjectPath(this.workspaceRoot, routedWorkspace);
mkdirSync(project.absolute, { recursive: true });
const created = await this.client.call<{ task: HostTask }>("task.create", {
goal,
workspace_id: project.projectPath,
device_ids: deviceIds,
actor_id: owner,
});
const taskId = created.task.task_id;
// New task id: the lock is always fresh. A live conflicting owner cannot
// exist, but stay defensive.
const acquired = this.lock.acquire(taskId, this.instanceId, this.now());
if (!acquired.held) {
throw new RdkProtocolError(
"RDK-OWNER-001",
`task ${taskId} lock already held`,
{ task_id: taskId },
);
}
const runtime: TaskRuntime = {
taskId,
workspaceId: project.projectPath,
absolute: project.absolute,
handle: null,
owner,
events: [],
};
this.runtimes.set(taskId, runtime);
this.record(runtime, "task.created", owner, { mode, workspace: project.projectPath });
await this.ensureSession(runtime, buildHealthCardTurns(deviceIds));
try {
// The user's goal drives the model — NOT a hardcoded health-card
// prompt. The S1-B scripted demo hard-coded "启动系统健康卡" here, which
// silently overrode every real-model task; restore goal-driven agency.
const target = deviceIds.length ? deviceIds.join(", ") : "(no device bound)";
await runtime.handle!.session.prompt(
`在设备 ${target} 上完成以下任务,按 rdk-develop skill 的工作流执行(inspect → write → plan → run → verify → report,失败就迭代修复):\n${goal}`,
);
this.record(runtime, "task.ran", owner, {});
} catch (err) {
this.record(runtime, "task.failed", owner, {
error: err instanceof Error ? err.message : String(err),
});
throw err;
}
const status = await this.status(taskId);
return { task_id: taskId, state: status.state, cursor: status.cursor };
}
async listTasks(): Promise<TaskStatus[]> {
this.assertOpen();
const result = await this.client.call<{ tasks: HostTask[] }>("task.list");
return (result.tasks ?? []).map((task) => this.toStatus(task));
}
async getTask(taskId: string, afterEventSeq = 0): Promise<TaskSnapshot> {
this.assertOpen();
const status = await this.status(taskId);
const runtime = this.runtimes.get(taskId);
const events = (runtime?.events ?? []).filter((e) => e.seq > afterEventSeq);
return { status, events };
}
async steerTask(taskId: string, message: string, owner: string): Promise<TaskHandle> {
this.assertOpen();
const runtime = await this.requireTask(taskId);
this.assertCanAct(taskId);
await this.ensureSession(runtime, buildResumeTurns());
await runtime.handle!.session.prompt(message);
this.record(runtime, "task.steered", owner, { message });
const status = await this.status(taskId);
return { task_id: taskId, state: status.state, cursor: status.cursor };
}
async cancelTask(taskId: string, reason: string, owner: string): Promise<TaskHandle> {
this.assertOpen();
const runtime = await this.requireTask(taskId);
this.assertCanAct(taskId);
const task = await this.getHostTask(taskId);
for (const runId of task.run_ids ?? []) {
await this.client.call("run.cancel", { run_id: runId, reason });
}
this.record(runtime, "task.cancelled", owner, { reason });
await this.disposeRuntime(runtime);
const status = await this.status(taskId);
return { task_id: taskId, state: status.state, cursor: status.cursor };
}
async resumeTask(taskId: string, owner: string, takeOver = false): Promise<TaskHandle> {
this.assertOpen();
const runtime = await this.requireTask(taskId);
if (takeOver) {
const result = this.lock.takeOver(taskId, this.instanceId, this.now());
if (!result.held) {
throw new RdkProtocolError(
"RDK-OWNER-001",
`task ${taskId} has a live owner; take-over refused`,
{ task_id: taskId },
);
}
this.record(runtime, "task.owner_changed", owner, { instance_id: this.instanceId });
} else {
// Observe: do not steal. Reject only a live foreign owner.
const existing = this.lock.read(taskId);
if (existing !== null && existing.owner_instance_id !== this.instanceId) {
if (!this.lock.isStale(existing, this.now())) {
throw new RdkProtocolError(
"RDK-OWNER-001",
`task ${taskId} is owned by another live surface`,
{ task_id: taskId, owner_instance_id: existing.owner_instance_id },
);
}
throw new RdkProtocolError(
"RDK-OWNER-002",
`task ${taskId} has a stale owner; resume with --take-over`,
{ task_id: taskId },
);
}
}
// Resume = the runtime re-attaching to a task: refresh non-terminal runs
// from device truth (AT-023 — never re-start), freeze a recovery
// checkpoint, and prime the session with recovery context so a real model
// picks up where the task left off (docs/08 §6).
await this.client.call("task.reconcile", { task_id: taskId });
const checkpoint = await this.client.call<RecoveryCheckpoint>(
"task.checkpoint",
{ task_id: taskId, waiting_on: "resumed" },
);
const task = await this.getHostTask(taskId);
await this.ensureSession(runtime, buildResumeTurns(this.resumeContext(taskId, task, checkpoint)));
const status = await this.status(taskId);
return { task_id: taskId, state: status.state, cursor: status.cursor };
}
private resumeContext(
taskId: string,
task: HostTask,
checkpoint: RecoveryCheckpoint,
): string {
const active = checkpoint.active_run_ids?.length ?? 0;
const completed = checkpoint.completed_run_ids?.length ?? 0;
const unsatisfied = checkpoint.unsatisfied_verifier_ids ?? [];
return [
`[resumed task ${taskId}]`,
`goal: ${task.goal ?? "(none)"}`,
`state: ${task.state}${task.outcome ? ` outcome=${task.outcome}` : ""}`,
`runs: ${task.run_ids?.length ?? 0} total (${active} active, ${completed} completed)`,
`unsatisfied verifiers: ${unsatisfied.length ? unsatisfied.join(", ") : "none"}`,
checkpoint.waiting_on ? `waiting_on: ${checkpoint.waiting_on}` : "",
]
.filter(Boolean)
.join("\n");
}
async readArtifact(taskId: string, artifactId: string): Promise<unknown> {
this.assertOpen();
await this.requireTask(taskId);
const task = await this.getHostTask(taskId);
// Artifacts belong to runs; read through the first run that owns it is not
// derivable without a lookup, so require an explicit run via the Host.
if (!(task.run_ids ?? []).length) {
throw new RdkProtocolError("RDK-INV-001", `task ${taskId} has no runs or artifacts`);
}
const runId = task.run_ids[0]!;
return this.client.call("artifact.read", { run_id: runId, artifact_id: artifactId });
}
// -- packs (S3: capability preservation) --------------------------------
async savePack(name: string, workspaceId: string, planId: string): Promise<unknown> {
this.assertOpen();
return this.client.call("pack.save", {
name, workspace_id: workspaceId, plan_id: planId,
});
}
async listPacks(): Promise<unknown> {
this.assertOpen();
return this.client.call("pack.list", {});
}
async runPack(name: string, deviceId: string, requestId: string): Promise<unknown> {
this.assertOpen();
return this.client.call("pack.run", {
name, device_id: deviceId, request_id: requestId,
});
}
// -- approvals (human plane; model surface can only request/list) --------
/** Pending + decided approvals (read side is agent-visible). */
async listApprovals(): Promise<Array<Record<string, unknown>>> {
const result = await this.client.call<{ approvals: Array<Record<string, unknown>> }>(
"approval.list",
);
return result.approvals;
}
/** Human-only approve/reject over the human authority plane. */
async decideApproval(approvalId: string, approve: boolean, reason = ""): Promise<void> {
await this.humanClient().call("approval.decide", {
approval_id: approvalId,
approve,
reason,
});
}
private humanClient(): RdkHostClient {
if (this.humanClientInstance === null) {
const cmd = this.agentCommand ?? ["rdk-agent-host", "serve", "--stdio"];
this.humanClientInstance = new RdkHostClient({
command: [...cmd, "--role", "human"],
timeoutMs: 30_000,
});
}
return this.humanClientInstance;
}
async close(): Promise<void> {
if (this.closed) return;
this.closed = true;
for (const runtime of this.runtimes.values()) {
await this.disposeRuntime(runtime);
}
this.runtimes.clear();
await this.client.close();
await this.humanClientInstance?.close();
}
// -- internals -------------------------------------------------------------
private assertOpen(): void {
if (this.closed) throw new RdkProtocolError("RDK-EXEC-004", "TaskService is closed");
}
private record(runtime: TaskRuntime, kind: string, owner: string, detail: Record<string, unknown>): void {
// Event sequences are 1-based (matching Host run-event semantics): the
// cursor is the count of events, and `after_event_seq` returns strictly
// later events.
runtime.events.push({
seq: runtime.events.length + 1,
kind,
owner,
detail,
at: new Date(this.now()).toISOString(),
});
}
private async getHostTask(taskId: string): Promise<HostTask> {
const result = await this.client.call<{ task: HostTask }>("task.show", { task_id: taskId });
return result.task;
}
private async requireTask(taskId: string): Promise<TaskRuntime> {
await this.getHostTask(taskId); // throws if unknown
let runtime = this.runtimes.get(taskId);
if (runtime === undefined) {
const task = await this.getHostTask(taskId);
runtime = {
taskId,
workspaceId: task.workspace_id,
absolute: join(this.workspaceRoot, task.workspace_id),
handle: null,
owner: "external",
events: [],
};
this.runtimes.set(taskId, runtime);
}
return runtime;
}
private async ensureSession(runtime: TaskRuntime, turns: ScriptedTurn[]): Promise<void> {
if (runtime.handle !== null) return;
const agentDir = join(this.agentDirRoot, runtime.taskId);
const { model } = await this.modelFactory(agentDir, turns);
const handle = await this.sessionFactory({
cwd: runtime.absolute,
packageRoot: this.packageRoot,
agentDir,
model,
...(this.agentCommand ? { agentCommand: this.agentCommand } : {}),
});
runtime.handle = handle;
}
private async disposeRuntime(runtime: TaskRuntime): Promise<void> {
const handle = runtime.handle;
runtime.handle = null;
if (handle !== null) await handle.close();
this.lock.release(runtime.taskId, this.instanceId);
}
private async status(taskId: string): Promise<TaskStatus> {
const task = await this.getHostTask(taskId);
const runtime = this.runtimes.get(taskId);
return {
...this.toStatus(task),
cursor: runtime?.events.length ?? 0,
};
}
private toStatus(task: HostTask): TaskStatus {
return {
task_id: task.task_id,
state: task.state,
outcome: task.outcome ?? null,
workspace_id: task.workspace_id,
device_ids: task.device_ids ?? [],
evidence_refs: task.evidence_refs ?? [],
required_action: null,
cursor: 0,
};
}
private assertCanAct(taskId: string): void {
const existing = this.lock.read(taskId);
if (existing === null) {
const acquired = this.lock.acquire(taskId, this.instanceId, this.now());
if (!acquired.held) {
throw new RdkProtocolError("RDK-OWNER-001", `task ${taskId} lock contention`, {
task_id: taskId,
});
}
return;
}
if (existing.owner_instance_id === this.instanceId) return;
if (!this.lock.isStale(existing, this.now())) {
throw new RdkProtocolError(
"RDK-OWNER-001",
`task ${taskId} is owned by another live surface`,
{ task_id: taskId, owner_instance_id: existing.owner_instance_id },
);
}
throw new RdkProtocolError(
"RDK-OWNER-002",
`task ${taskId} has a stale owner; resume with --take-over`,
{ task_id: taskId },
);
}
}

View File

@ -0,0 +1,77 @@
/**
* Production TaskService assembly (docs/12 §3.1, S1-B §6).
*
* Resolves the product-owned paths from the environment, never from user-global
* Pi state:
* - workspace-root: RDK_WORKSPACE_ROOT, else the caller's explicit value;
* - state dir: RDK_STATE_DIR (default `.rdk/state`) — also the Host's dir;
* - lock dir: `<state>/task-locks` (docs/12 §7);
* - agent dirs: `<state>/agent-dirs/<task-id>` (never `~/.pi/agent`);
* - package root: RDK_PACKAGE_ROOT, else resolved next to @rdk/rdk-agent-pi.
*/
import { existsSync, mkdirSync, realpathSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { homedir } from "node:os";
import { RdkHostClient } from "@rdk/rdk-agent-pi";
import { TaskService, type TaskServiceOptions } from "./taskService.js";
export function resolveAgentCommand(): string[] {
const raw = process.env.RDK_AGENT_COMMAND;
if (raw) return raw.split(/\s+/).filter(Boolean);
// Prefer the repo-local venv host so a bare `rdk-agent` works with no env.
try {
// resolvePackageRoot() = <repo>/packages/pi-rdk-agent → repo is two up.
const repoRoot = dirname(dirname(resolvePackageRoot()));
const venvHost = join(repoRoot, ".venv", "bin", "rdk-agent-host");
if (existsSync(venvHost)) return [venvHost, "serve", "--stdio"];
} catch {
// fall through to PATH
}
return ["rdk-agent-host", "serve", "--stdio"];
}
export function resolveStateDir(): string {
if (process.env.RDK_STATE_DIR) return process.env.RDK_STATE_DIR;
// Stable, user-global default so a globally-installed `rdk-agent` behaves the
// same from any CWD (never a CWD-relative `.rdk/state`).
return join(homedir(), ".rdk", "state");
}
/** Product-owned default workspace, created on demand (one-command entry). */
export function resolveDefaultWorkspaceRoot(): string {
const explicit = process.env.RDK_WORKSPACE_ROOT;
if (explicit) return explicit;
const root = join(resolveStateDir(), "workspaces");
mkdirSync(root, { recursive: true });
return root;
}
/** The trusted pi-rdk-agent package root (skills/prompts live there). */
export function resolvePackageRoot(): string {
const fromEnv = process.env.RDK_PACKAGE_ROOT;
if (fromEnv) return realpathSync(fromEnv);
const piEntry = import.meta.resolve("@rdk/rdk-agent-pi");
const piPkgRoot = resolve(dirname(fileURLToPath(piEntry)), "..");
return realpathSync(join(piPkgRoot, "..", "pi-rdk-agent"));
}
export function buildTaskService(
workspaceRoot: string,
overrides: Partial<TaskServiceOptions> = {},
): TaskService {
const stateDir = resolveStateDir();
const agentCommand = resolveAgentCommand();
return new TaskService({
client: new RdkHostClient({ command: agentCommand }),
workspaceRoot,
packageRoot: resolvePackageRoot(),
agentDirRoot: join(stateDir, "agent-dirs"),
lockDir: join(stateDir, "task-locks"),
agentCommand,
...overrides,
});
}

View File

@ -0,0 +1,144 @@
/**
* Minimal TUI (docs/12 §4, S1-B §7).
*
* A readline prompt over the SAME TaskService as CLI/GUI/MCP: a small dialog
* area, task status, steer (free text), cancel, resume and `/open-gui`. It
* reuses the task events and does not re-implement device business logic or a
* second task model.
*
* `dispatchTui` is pure (returns lines to print) so the interaction is
* unit-testable without a tty; `runTui` wraps it in a readline loop.
*/
import readline from "node:readline";
import { existsSync, readdirSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { resolvePackageRoot } from "./taskServiceFactory.js";
import { TaskService } from "./taskService.js";
const TUI_OWNER = "tui";
export type TuiCommand =
| "steer"
| "status"
| "cancel"
| "resume"
| "open-gui"
| "skills"
| "skill"
| "help"
| "quit";
export interface TuiInput {
command: TuiCommand;
arg?: string;
}
/** Trusted local skills shipped in the pi-rdk-agent package. */
export function listSkills(): string[] {
try {
const dir = join(resolvePackageRoot(), "skills");
if (!existsSync(dir)) return [];
return readdirSync(dir, { withFileTypes: true })
.filter((e) => e.isDirectory() && existsSync(join(dir, e.name, "SKILL.md")))
.map((e) => e.name);
} catch {
return [];
}
}
export function readSkill(name: string): string | null {
const path = join(resolvePackageRoot(), "skills", name, "SKILL.md");
if (!existsSync(path)) return null;
return readFileSync(path, "utf8");
}
export function parseTuiInput(line: string): TuiInput {
const trimmed = line.trim();
if (trimmed === "" || trimmed === "/quit" || trimmed === "/q") return { command: "quit" };
if (trimmed === "/help" || trimmed === "/?") return { command: "help" };
if (trimmed === "/status") return { command: "status" };
if (trimmed === "/cancel") return { command: "cancel" };
if (trimmed === "/resume") return { command: "resume" };
if (trimmed === "/open-gui") return { command: "open-gui" };
if (trimmed === "/skills") return { command: "skills" };
if (trimmed.startsWith("/resume ")) return { command: "resume", arg: trimmed.slice(8) };
if (trimmed.startsWith("/skill ")) return { command: "skill", arg: trimmed.slice(7) };
return { command: "steer", arg: trimmed };
}
export async function dispatchTui(
service: TaskService,
taskId: string,
input: TuiInput,
): Promise<string[]> {
switch (input.command) {
case "status": {
const snapshot = await service.getTask(taskId);
const s = snapshot.status;
return [
`${s.task_id}\t${s.state}\toutcome=${s.outcome ?? "—"}`,
`workspace=${s.workspace_id} devices=${s.device_ids.join(",") || "—"} evidence=${s.evidence_refs.length} events=${snapshot.events.length}`,
];
}
case "steer": {
const handle = await service.steerTask(taskId, input.arg ?? "", TUI_OWNER);
return [`steered: state=${handle.state} cursor=${handle.cursor}`];
}
case "cancel": {
const handle = await service.cancelTask(taskId, "", TUI_OWNER);
return [`cancelled: state=${handle.state}`];
}
case "resume": {
const handle = await service.resumeTask(taskId, TUI_OWNER, true);
return [`resumed: state=${handle.state} cursor=${handle.cursor}`];
}
case "open-gui":
return ["/open-gui: opening the desktop GUI (not yet wired in this build)"];
case "skills":
return [`skills: ${listSkills().join(", ") || "(none)"}`];
case "skill": {
const parts = (input.arg ?? "").trim().split(/\s+/);
const name = parts[0] ?? "";
const goal = parts.slice(1).join(" ");
const body = readSkill(name);
if (body === null) return [`/skill: unknown skill "${name}". Try /skills`];
const composed = `【主动调用 skill: ${name},按其步骤执行】\n${body}\n用户请求: ${goal || "(无附加请求)"}`;
const handle = await service.steerTask(taskId, composed, TUI_OWNER);
return [`skill "${name}" injected: state=${handle.state} cursor=${handle.cursor}`];
}
case "help":
return [
"/status /cancel /resume /open-gui /skills /skill <name> [请求] /quit — any other text steers",
];
case "quit":
return [];
}
}
export async function runTui(
service: TaskService,
taskId: string,
io: { input: NodeJS.ReadableStream; output: NodeJS.WritableStream },
): Promise<number> {
const rl = readline.createInterface({ input: io.input, output: io.output });
const prompt = () => {
rl.setPrompt("rdk> ");
rl.prompt();
};
prompt();
for await (const line of rl) {
const input = parseTuiInput(line);
if (input.command === "quit") break;
try {
const lines = await dispatchTui(service, taskId, input);
for (const out of lines) io.output.write(out + "\n");
} catch (err) {
io.output.write(`error: ${err instanceof Error ? err.message : String(err)}\n`);
}
prompt();
}
rl.close();
return 0;
}

View File

@ -0,0 +1,127 @@
/**
* Workspace path resolution (docs/12 §3.1, S1-B §6).
*
* One resolver for every surface: CLI args, GUI directory pickers and MCP
* params all land here. The root must be absolute and must exist; a task's
* project path is always RELATIVE to that root, and the resolved location must
* remain the root itself or a descendant — including after resolving symlinks,
* so a symlink inside the root cannot escape it.
*
* Missing arguments are a stable input error; we never silently fall back to
* the repository root or the user's home directory.
*/
import { realpathSync, statSync } from "node:fs";
import { basename, dirname, isAbsolute, normalize, relative, resolve } from "node:path";
export class WorkspaceError extends Error {
constructor(
public readonly code: string,
message: string,
) {
super(message);
this.name = "WorkspaceError";
}
}
/** True when `child` equals `parent` or is a strict descendant of it. */
function isWithin(parent: string, child: string): boolean {
const rel = relative(parent, child);
return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel));
}
/**
* Validate and canonicalize the workspace root. Returns the resolved real path.
*/
export function resolveWorkspaceRoot(root: string): string {
if (typeof root !== "string" || root.length === 0) {
throw new WorkspaceError("RDK-INV-001", "workspace-root is required");
}
if (!isAbsolute(root)) {
throw new WorkspaceError(
"RDK-INV-001",
`workspace-root must be an absolute path: ${root}`,
);
}
let real: string;
try {
real = realpathSync(root);
} catch {
throw new WorkspaceError("RDK-INV-001", `workspace-root does not exist: ${root}`);
}
if (!statSync(real).isDirectory()) {
throw new WorkspaceError("RDK-INV-001", `workspace-root is not a directory: ${root}`);
}
return real;
}
/**
* Resolve a task project path under the root. Returns the real root, the
* normalized relative project path (the workspace_id the Host stores), and the
* absolute candidate path.
*/
export interface ResolvedProject {
root: string;
projectPath: string;
absolute: string;
}
export function resolveProjectPath(root: string, projectPath: string): ResolvedProject {
const realRoot = resolveWorkspaceRoot(root);
if (typeof projectPath !== "string" || projectPath.length === 0) {
throw new WorkspaceError("RDK-INV-001", "a workspace project path is required");
}
if (isAbsolute(projectPath) || /^[a-zA-Z]:/.test(projectPath)) {
throw new WorkspaceError(
"RDK-INV-001",
`workspace path must be relative to the root: ${projectPath}`,
);
}
const candidate = resolve(realRoot, projectPath);
if (!isWithin(realRoot, candidate)) {
throw new WorkspaceError("RDK-INV-001", `workspace path escapes the root: ${projectPath}`);
}
const realCandidate = realpathOfNearestExisting(candidate);
if (!isWithin(realRoot, realCandidate)) {
throw new WorkspaceError(
"RDK-INV-001",
`workspace path escapes the root via symlink: ${projectPath}`,
);
}
return {
root: realRoot,
projectPath: normalizeProjectPath(projectPath),
absolute: candidate,
};
}
/** Strip a leading `./` and trailing separator so workspace_id is stable. */
function normalizeProjectPath(projectPath: string): string {
const normalized = normalize(projectPath);
if (normalized === "." || normalized === "") return ".";
return normalized.replace(/\/$/, "");
}
/**
* realpath of a path whose leaf may not exist yet: walk up to the nearest
* existing ancestor, resolve that, then re-append the missing suffix.
*/
function realpathOfNearestExisting(target: string): string {
const missing: string[] = [];
let current = target;
// eslint-disable-next-line no-constant-condition
while (true) {
try {
let result = realpathSync(current);
for (let i = missing.length - 1; i >= 0; i -= 1) {
result = resolve(result, missing[i]!);
}
return result;
} catch {
const parent = dirname(current);
if (parent === current) return target;
missing.push(basename(current));
current = parent;
}
}
}

View File

@ -36,7 +36,7 @@ test("doctor prints one envelope", async () => {
});
test("unknown command returns exit 2 with envelope, never silent", async () => {
const { code, lines } = await run(["run", "do-something"]);
const { code, lines } = await run(["frobnicate"]);
assert.equal(code, 2);
assert.equal(lines.length, 1);
const parsed = JSON.parse(lines[0]!);

View File

@ -0,0 +1,139 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { main } from "../src/cli.js";
import { makeFakeTaskService } from "./helpers.js";
async function run(argv: string[], taskService = makeFakeTaskService().service): Promise<{
code: number;
lines: string[];
}> {
const lines: string[] = [];
const originalWrite = process.stdout.write.bind(process.stdout);
process.stdout.write = ((chunk: string) => {
lines.push(String(chunk));
return true;
}) as typeof process.stdout.write;
try {
const code = await main(argv, { taskService });
return { code, lines };
} finally {
process.stdout.write = originalWrite;
}
}
test("run --json prints one envelope with a task id", async () => {
const { code, lines } = await run(["run", "check health", "--json"]);
assert.equal(code, 0);
assert.equal(lines.length, 1);
const parsed = JSON.parse(lines[0]!);
assert.equal(parsed.ok, true);
assert.match(parsed.data.task_id, /^task-/);
});
test("run without --json prints human progress, not JSON", async () => {
const { code, lines } = await run(["run", "check health"]);
assert.equal(code, 0);
assert.ok(lines.length >= 1);
assert.match(lines[0]!, /^task started: task-/);
});
test("run missing goal returns exit 2", async () => {
const { code } = await run(["run"]);
assert.equal(code, 2);
});
test("task list --json returns an envelope with tasks", async () => {
const fake = makeFakeTaskService();
await fake.service.startTask("a", "proj", ["fake-001"], "guide", "cli");
const { code, lines } = await run(["task", "list", "--json"], fake.service);
assert.equal(code, 0);
const parsed = JSON.parse(lines[0]!);
assert.equal(parsed.ok, true);
assert.equal(parsed.data.tasks.length, 1);
});
test("task status --json returns the task snapshot", async () => {
const fake = makeFakeTaskService();
const started = await fake.service.startTask("check health", "proj", ["fake-001"], "guide", "cli");
const { code, lines } = await run(["task", "status", started.task_id, "--json"], fake.service);
assert.equal(code, 0);
const parsed = JSON.parse(lines[0]!);
assert.equal(parsed.data.status.task_id, started.task_id);
});
test("task status --follow streams JSONL events", async () => {
const fake = makeFakeTaskService();
const started = await fake.service.startTask("check health", "proj", ["fake-001"], "guide", "cli");
const { code, lines } = await run(["task", "status", started.task_id, "--follow"], fake.service);
assert.equal(code, 0);
assert.ok(lines.length >= 1);
for (const line of lines) JSON.parse(line); // each line is valid JSON
});
test("task steer requires a message", async () => {
const fake = makeFakeTaskService();
const started = await fake.service.startTask("check health", "proj", ["fake-001"], "guide", "cli");
const { code } = await run(["task", "steer", started.task_id], fake.service);
assert.equal(code, 2);
});
test("task status on unknown task returns an error envelope", async () => {
const { code, lines } = await run(["task", "status", "task-nope", "--json"]);
assert.notEqual(code, 0);
const parsed = JSON.parse(lines[0]!);
assert.equal(parsed.ok, false);
});
test("run --mode with an invalid value returns exit 2", async () => {
const { code } = await run(["run", "check health", "--mode", "auto_high_risk"]);
assert.equal(code, 2);
});
test("run without a workspace-root is a clear input error, never a silent default", async () => {
const previous = process.env.RDK_WORKSPACE_ROOT;
delete process.env.RDK_WORKSPACE_ROOT;
const lines: string[] = [];
const originalWrite = process.stdout.write.bind(process.stdout);
process.stdout.write = ((chunk: string) => {
lines.push(String(chunk));
return true;
}) as typeof process.stdout.write;
try {
const code = await main(["run", "check health", "--json"], {});
assert.equal(code, 2);
const parsed = JSON.parse(lines[0]!);
assert.equal(parsed.ok, false);
assert.match(parsed.error.code, /RDK-INV-001/);
assert.match(parsed.error.message, /workspace-root is required/);
} finally {
process.stdout.write = originalWrite;
if (previous !== undefined) process.env.RDK_WORKSPACE_ROOT = previous;
}
});
test("task artifact --json returns the artifact envelope", async () => {
const fake = makeFakeTaskService();
const started = await fake.service.startTask("a", "proj", ["fake-001"], "guide", "cli");
fake.client.tasks.get(started.task_id)!.run_ids = ["run-1"];
const { code, lines } = await run(
["task", "artifact", started.task_id, "run-1/health.json", "--json"],
fake.service,
);
assert.equal(code, 0);
const parsed = JSON.parse(lines[0]!);
assert.equal(parsed.ok, true);
assert.equal(parsed.data.preview, "preview");
});
test("task artifact human mode prints the preview line", async () => {
const fake = makeFakeTaskService();
const started = await fake.service.startTask("a", "proj", ["fake-001"], "guide", "cli");
fake.client.tasks.get(started.task_id)!.run_ids = ["run-1"];
const { code, lines } = await run(
["task", "artifact", started.task_id, "run-1/health.json"],
fake.service,
);
assert.equal(code, 0);
assert.match(lines.join(""), /preview/);
});

View File

@ -1,10 +1,34 @@
import assert from "node:assert/strict";
import { chmodSync, mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { test } from "node:test";
import { DeviceService } from "../src/deviceService.js";
const ENABLED = process.env.RDK_RUN_HOST_INTEGRATION === "1";
// Fixed ed25519 wire-key base64 for the keyscan stub (fingerprint is derived
// by the host; no real board is needed).
const FAKE_KEY_B64 = "AAAAC3NzaC1lZDI1NTE5AAAAIB8T4TnNhGkTmDYqeZCe8W1ekvYbvThGXn3JcCB7bTzz";
function withTofuEnv<T>(run: () => Promise<T>): Promise<T> {
const stateDir = mkdtempSync(join(tmpdir(), "rdk-tofu-"));
const stub = join(stateDir, "keyscan-stub.sh");
writeFileSync(stub, `#!/bin/sh\necho "fake-board ssh-ed25519 ${FAKE_KEY_B64}"\n`);
chmodSync(stub, 0o755);
const savedKeyscan = process.env.RDK_KEYSCAN_BINARY;
const savedState = process.env.RDK_STATE_DIR;
process.env.RDK_KEYSCAN_BINARY = stub;
process.env.RDK_STATE_DIR = join(stateDir, "state");
return run().finally(() => {
if (savedKeyscan === undefined) delete process.env.RDK_KEYSCAN_BINARY;
else process.env.RDK_KEYSCAN_BINARY = savedKeyscan;
if (savedState === undefined) delete process.env.RDK_STATE_DIR;
else process.env.RDK_STATE_DIR = savedState;
});
}
test("device list reaches the real host (gated)", { skip: !ENABLED }, async () => {
const service = new DeviceService();
try {
@ -35,3 +59,55 @@ test("device inspect refresh of unknown device returns a stable error (gated)",
await service.close();
}
});
test("human connect flow: TOFU show/confirm/register round trip (gated)", {
skip: !ENABLED,
}, async () => {
await withTofuEnv(async () => {
const service = new DeviceService();
try {
// Step 1: sanitized candidate — fingerprint, never raw key material.
const candidate = await service.showHostKey("fake-board");
assert.equal(candidate.host, "fake-board");
assert.equal(candidate.key_type, "ssh-ed25519");
assert.ok(candidate.fingerprint_sha256.startsWith("SHA256:"));
assert.ok(!JSON.stringify(candidate).includes("public_key"));
// Step 2: human confirms the shown fingerprint.
const confirmation = await service.confirmHostKey(candidate.candidate_id);
assert.equal(confirmation.fingerprint_sha256, candidate.fingerprint_sha256);
// Step 3: register with the confirmed fingerprint.
const registered = await service.registerDevice({
alias: "bench",
ssh_config_host: "fake-board",
expected_host_key_sha256: confirmation.fingerprint_sha256,
});
assert.ok(registered.device_id.startsWith("dev-"));
// Step 4: the read-only list reports the confirmation truthfully.
const devices = await service.listDevices();
const row = devices.find((d) => d.device_id === registered.device_id);
assert.ok(row);
assert.equal(row.host_key_confirmed, true);
} finally {
await service.close();
}
});
});
test("confirm of unknown host key candidate rejects with RDK-INV-001 (gated)", {
skip: !ENABLED,
}, async () => {
await withTofuEnv(async () => {
const service = new DeviceService();
try {
await assert.rejects(
() => service.confirmHostKey("hk-missing"),
(err: unknown) => err instanceof Error && /RDK-INV-001/.test(err.message),
);
} finally {
await service.close();
}
});
});

View File

@ -0,0 +1,95 @@
/**
* S1-B cross-surface end-to-end (docs/12 §8, S1-B §9) — gated on
* RDK_RUN_HOST_INTEGRATION=1 because it spawns REAL `rdk-agent-host` +
* `rdk-agent-device` subprocesses and a REAL ScriptedModel session.
*
* Two TaskService instances share one state dir + workspace (exactly like two
* product surfaces on the same host): surface A "CLI" starts a scripted Fake
* health-card task; surface B "MCP/GUI" observes it, hits the live-owner wall
* on steer, and — after A cancels — resumes it with an explicit take-over. The
* observable device snapshot produced by A's health card is read back by B via
* a fresh DeviceService, proving the shared, durable Host state.
*
* Requires RDK_AGENT_COMMAND and RDK_DEVICE_COMMAND in the environment (the
* runner points them at the repo venv). Each service spawns its own Host; both
* inherit the shared RDK_STATE_DIR set below.
*/
import assert from "node:assert/strict";
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { test } from "node:test";
import { DeviceService } from "../src/deviceService.js";
import { buildTaskService } from "../src/taskServiceFactory.js";
const ENABLED = process.env.RDK_RUN_HOST_INTEGRATION === "1";
const AGENT_CMD = process.env.RDK_AGENT_COMMAND;
const DEVICE_CMD = process.env.RDK_DEVICE_COMMAND;
test(
"cross-surface: CLI starts, MCP observes, owner conflict + cancel + take-over resume",
{ skip: !ENABLED || !AGENT_CMD || !DEVICE_CMD },
async () => {
const agentCmd = AGENT_CMD!;
const deviceCmd = DEVICE_CMD!;
const stateDir = mkdtempSync(path.join(tmpdir(), "rdk-e2e-state-"));
const workspace = mkdtempSync(path.join(tmpdir(), "rdk-e2e-ws-"));
const prevState = process.env.RDK_STATE_DIR;
const prevDevice = process.env.RDK_DEVICE_COMMAND;
process.env.RDK_STATE_DIR = stateDir;
process.env.RDK_DEVICE_COMMAND = deviceCmd;
const a = buildTaskService(workspace); // "CLI" surface
const b = buildTaskService(workspace); // "MCP/GUI" surface (same state + lock dir)
try {
// Surface A starts the health card on the Fake device.
const handle = await a.startTask("e2e health card", ".", ["fake-001"], "guide", "cli");
assert.match(handle.task_id, /^task-/);
// Surface B observes the same task without owning it (read-only).
const tasks = await b.listTasks();
assert.ok(
tasks.some((t) => t.task_id === handle.task_id),
`task ${handle.task_id} observable from surface B`,
);
// Surface B cannot steer while A is the live owner.
await assert.rejects(
() => b.steerTask(handle.task_id, "hi", "mcp"),
(err: unknown) =>
err instanceof Error &&
"code" in err &&
(err as { code: string }).code === "RDK-OWNER-001",
);
// Surface A cancels (idempotent), releasing the owner lock.
const cancelled = await a.cancelTask(handle.task_id, "done", "cli");
assert.equal(cancelled.task_id, handle.task_id);
// Surface B resumes with explicit take-over → owner_changed.
const resumed = await b.resumeTask(handle.task_id, "mcp", true);
assert.equal(resumed.task_id, handle.task_id);
const snapshot = await b.getTask(handle.task_id);
assert.ok(snapshot.events.some((e) => e.kind === "task.owner_changed"));
// The health card's device snapshot is durable, shared Host state: a
// fresh DeviceService (third surface) reads the same evidence.
const device = new DeviceService(agentCmd.split(/\s+/).filter(Boolean));
try {
const inspected = await device.inspectDevice("fake-001", "cached");
assert.notEqual(inspected.snapshot, null, "health card produced a device snapshot");
} finally {
await device.close();
}
} finally {
await a.close();
await b.close();
if (prevState !== undefined) process.env.RDK_STATE_DIR = prevState;
else delete process.env.RDK_STATE_DIR;
if (prevDevice !== undefined) process.env.RDK_DEVICE_COMMAND = prevDevice;
else delete process.env.RDK_DEVICE_COMMAND;
}
},
);

View File

@ -0,0 +1,143 @@
/**
* Shared test doubles for the TaskService-backed surfaces (CLI/TUI/MCP tests).
* Not a *.test.ts file, so it is never run as a suite itself.
*/
import { mkdirSync, mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { RdkProtocolError, type ScriptedTurn } from "@rdk/rdk-agent-pi";
import type {
HostClientLike,
SessionHandleLike,
TaskServiceOptions,
} from "../src/taskService.js";
import { TaskService } from "../src/taskService.js";
export interface FakeTask {
task_id: string;
goal: string;
state: string;
outcome: string | null;
workspace_id: string;
device_ids: string[];
run_ids: string[];
evidence_refs: string[];
required_verifier_ids: string[];
}
export class FakeClient implements HostClientLike {
tasks = new Map<string, FakeTask>();
closed = false;
calls: Array<{ method: string; params: Record<string, unknown> }> = [];
cancelledRuns: string[] = [];
async call<T = unknown>(method: string, params: Record<string, unknown> = {}): Promise<T> {
this.calls.push({ method, params });
switch (method) {
case "task.create": {
const id = `task-${String(this.tasks.size + 1)}`;
const task: FakeTask = {
task_id: id,
goal: String(params.goal ?? ""),
state: "created",
outcome: null,
workspace_id: String(params.workspace_id ?? "."),
device_ids: (params.device_ids as string[]) ?? [],
run_ids: [],
evidence_refs: [],
required_verifier_ids: (params.required_verifier_ids as string[]) ?? [],
};
this.tasks.set(id, task);
return { task } as T;
}
case "task.reconcile": {
const task = this.tasks.get(String(params.task_id));
if (!task) throw new RdkProtocolError("RDK-INV-001", "unknown task");
return { task: { ...task } } as T;
}
case "task.checkpoint": {
const task = this.tasks.get(String(params.task_id));
if (!task) throw new RdkProtocolError("RDK-INV-001", "unknown task");
return {
checkpoint_id: "sha256:fake",
task_id: task.task_id,
unsatisfied_verifier_ids: [...task.required_verifier_ids],
active_run_ids: [],
completed_run_ids: [...task.run_ids],
waiting_on: String(params.waiting_on ?? "resumed"),
created_at: "2026-01-01T00:00:00Z",
} as T;
}
case "task.show": {
const task = this.tasks.get(String(params.task_id));
if (!task) throw new RdkProtocolError("RDK-INV-001", "unknown task");
return { task: { ...task } } as T;
}
case "task.list":
return { tasks: [...this.tasks.values()] } as T;
case "run.cancel":
this.cancelledRuns.push(String(params.run_id));
return {} as T;
case "artifact.read":
return { artifact: { artifact_id: params.artifact_id }, preview: "preview" } as T;
default:
throw new RdkProtocolError("RDK-PROTO-001", `unexpected ${method}`);
}
}
async close(): Promise<void> {
this.closed = true;
}
}
export class FakeSession implements SessionHandleLike {
prompts: string[] = [];
disposed = false;
closed = false;
session = {
prompt: async (message: string) => {
this.prompts.push(message);
},
dispose: () => {
this.disposed = true;
},
};
async close(): Promise<void> {
this.closed = true;
this.session.dispose();
}
}
export interface FakeTaskService {
client: FakeClient;
handles: FakeSession[];
service: TaskService;
root: string;
}
export function makeFakeTaskService(overrides: Partial<TaskServiceOptions> = {}): FakeTaskService {
const base = mkdtempSync(path.join(tmpdir(), "rdk-cli-"));
const root = path.join(base, "workspace");
mkdirSync(root, { recursive: true });
const client = new FakeClient();
const handles: FakeSession[] = [];
const service = new TaskService({
client,
workspaceRoot: root,
packageRoot: path.join(base, "pi-rdk-agent"),
agentDirRoot: path.join(base, "agent-dirs"),
lockDir: path.join(base, "task-locks"),
sessionFactory: async () => {
const handle = new FakeSession();
handles.push(handle);
return handle;
},
modelFactory: async (_agentDir: string, _turns: ScriptedTurn[]) => ({ model: { fake: true } }),
...overrides,
});
return { client, handles, service, root };
}

View File

@ -6,21 +6,32 @@ import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
import type { DeviceService } from "../src/deviceService.js";
import { createMcpServer } from "../src/mcp.js";
import { makeFakeTaskService } from "./helpers.js";
function stubService(): DeviceService {
const EXPECTED_TOOLS = [
"rdk_device_list",
"rdk_device_inspect",
"rdk_task_start",
"rdk_task_status",
"rdk_task_steer",
"rdk_task_cancel",
"rdk_artifact_read",
];
function stubDeviceService(): DeviceService {
return {
listDevices: async () => [],
inspectDevice: async () => ({
device_id: "d", snapshot: null, fresh: false, evidence_refs: [],
}),
close: async () => {},
} as unknown as DeviceService;
}
async function listTools(): Promise<string[]> {
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
const server = createMcpServer(stubService());
const server = createMcpServer(stubDeviceService(), makeFakeTaskService().service);
await server.connect(serverTransport);
const client = new Client({ name: "test", version: "1" });
await client.connect(clientTransport);
try {
@ -32,42 +43,82 @@ async function listTools(): Promise<string[]> {
}
}
test("tools/list returns exactly the two device tools in fixed order", async () => {
const names = await listTools();
assert.deepEqual(names, ["rdk_device_list", "rdk_device_inspect"]);
test("tools/list returns exactly the seven task/device tools in fixed order", async () => {
assert.deepEqual(await listTools(), EXPECTED_TOOLS);
});
test("no forbidden tools are registered (no task/approval/terminal/flash/credential)", async () => {
test("no forbidden or low-level tools are registered", async () => {
const names = await listTools();
for (const forbidden of [
"rdk_task_start", "rdk_task_status", "rdk_task_steer", "rdk_task_cancel",
"rdk_artifact_read", "approval_request", "shell", "terminal", "flash", "credential",
"approval_request", "rdk_approval_status", "rdk_task_resume",
"rdk_device_inventory", "rdk_run_plan", "rdk_run_start",
"complete_required_action", "shell", "terminal", "flash", "credential",
]) {
assert.ok(!names.includes(forbidden), `forbidden tool ${forbidden} present`);
}
});
test("rdk_device_inspect maps arguments and returns structured text", async () => {
test("rdk_task_start maps arguments and returns a task handle", async () => {
const fake = makeFakeTaskService();
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
let seen: unknown;
const service = {
listDevices: async () => [],
inspectDevice: async (id: string, refresh: string) => {
seen = { id, refresh };
return { device_id: id, snapshot: null, fresh: false, evidence_refs: [] };
},
} as unknown as DeviceService;
const server = createMcpServer(service);
const server = createMcpServer(stubDeviceService(), fake.service);
await server.connect(serverTransport);
const client = new Client({ name: "test", version: "1" });
await client.connect(clientTransport);
try {
const result = await client.callTool({
name: "rdk_device_inspect",
arguments: { device_id: "dev-1", refresh: "quick" },
name: "rdk_task_start",
arguments: { goal: "check health", workspace: "proj", device_ids: ["fake-001"], mode: "guide" },
});
assert.deepEqual(seen, { id: "dev-1", refresh: "quick" });
assert.equal((result.content as unknown[]).length, 1);
const text = (result.content as Array<{ text: string }>)[0]!.text;
const parsed = JSON.parse(text) as { task_id: string };
assert.match(parsed.task_id, /^task-/);
assert.equal(fake.client.tasks.size, 1);
} finally {
await client.close();
await server.close();
}
});
test("rdk_task_status maps task_id and returns the snapshot", async () => {
const fake = makeFakeTaskService();
const started = await fake.service.startTask("check health", "proj", ["fake-001"], "guide", "mcp");
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
const server = createMcpServer(stubDeviceService(), fake.service);
await server.connect(serverTransport);
const client = new Client({ name: "test", version: "1" });
await client.connect(clientTransport);
try {
const result = await client.callTool({
name: "rdk_task_status",
arguments: { task_id: started.task_id },
});
const text = (result.content as Array<{ text: string }>)[0]!.text;
const parsed = JSON.parse(text) as { status: { task_id: string } };
assert.equal(parsed.status.task_id, started.task_id);
} finally {
await client.close();
await server.close();
}
});
test("rdk_task_steer and rdk_task_cancel route through the shared TaskService", async () => {
const fake = makeFakeTaskService();
const started = await fake.service.startTask("check health", "proj", ["fake-001"], "guide", "mcp");
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
const server = createMcpServer(stubDeviceService(), fake.service);
await server.connect(serverTransport);
const client = new Client({ name: "test", version: "1" });
await client.connect(clientTransport);
try {
const steer = await client.callTool({
name: "rdk_task_steer", arguments: { task_id: started.task_id, message: "go" },
});
assert.ok((steer.content as unknown[]).length === 1);
const cancel = await client.callTool({
name: "rdk_task_cancel", arguments: { task_id: started.task_id },
});
assert.ok((cancel.content as unknown[]).length === 1);
} finally {
await client.close();
await server.close();

View File

@ -0,0 +1,15 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { callExternalTool, getServer, loadExternalMcpConfig } from "../src/mcpClient.js";
test("unknown server is not in allowlist and is rejected", async () => {
// RDK_MCP_CONFIG unset or empty in hermetic runs -> no servers allowlisted.
const cfg = loadExternalMcpConfig();
assert.ok(Array.isArray(cfg.servers));
assert.equal(getServer("not-allowlisted"), undefined);
await assert.rejects(
() => callExternalTool("not-allowlisted", "any_tool", {}),
/not in allowlist/,
);
});

View File

@ -0,0 +1,125 @@
/**
* MCP stdio executable lifecycle (S1-B.1, P2): a spawned `bin.js mcp --stdio`
* must stay live for the whole session (task tools reach an OPEN TaskService)
* and exit promptly + cleanly once the client closes stdin.
*
* This regresses the runMcpServer bug where `await connect()` resolved before
* any tool call, so `.then(close)` tore the TaskService down and every
* `rdk_task_*` tool returned "TaskService is closed".
*
* Gated on RDK_RUN_HOST_INTEGRATION=1 (spawns a real `rdk-agent-host` via
* RDK_AGENT_COMMAND); RDK_DEVICE_COMMAND points at the repo venv device.
*/
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { test } from "node:test";
import { fileURLToPath } from "node:url";
const ENABLED = process.env.RDK_RUN_HOST_INTEGRATION === "1";
const AGENT_CMD = process.env.RDK_AGENT_COMMAND;
const DEVICE_CMD = process.env.RDK_DEVICE_COMMAND;
interface McpMessage {
id?: number;
result?: unknown;
}
test(
"mcp executable: handshake, tool call reaches an open TaskService, stdin close exits cleanly",
{ skip: !ENABLED || !AGENT_CMD || !DEVICE_CMD, timeout: 60_000 },
async () => {
const deviceCmd = DEVICE_CMD!;
const workspace = mkdtempSync(path.join(tmpdir(), "rdk-mcp-life-ws-"));
const stateDir = mkdtempSync(path.join(tmpdir(), "rdk-mcp-life-state-"));
const prevState = process.env.RDK_STATE_DIR;
const prevDevice = process.env.RDK_DEVICE_COMMAND;
process.env.RDK_STATE_DIR = stateDir;
process.env.RDK_DEVICE_COMMAND = deviceCmd;
// The test build emits bin.ts into dist-test/src/bin.js (tsconfig.test.json
// uses rootDir "."). Spawn THAT so we exercise the real stdio entrypoint.
const binPath = fileURLToPath(new URL("../src/bin.js", import.meta.url));
const proc = spawn(
process.execPath,
[binPath, "mcp", "--stdio", "--workspace-root", workspace],
{ stdio: ["pipe", "pipe", "ignore"] },
);
try {
let buffer = "";
const pending = new Map<number, (message: McpMessage) => void>();
proc.stdout.on("data", (chunk: Buffer) => {
buffer += chunk.toString();
// Re-scan the newline offset every iteration — a stale offset here loops
// forever and hangs the test.
let nl = buffer.indexOf("\n");
while (nl >= 0) {
const line = buffer.slice(0, nl).trim();
buffer = buffer.slice(nl + 1);
if (line) {
const message = JSON.parse(line) as McpMessage;
if (message.id !== undefined) {
const resolve = pending.get(message.id);
if (resolve) {
pending.delete(message.id);
resolve(message);
}
}
}
nl = buffer.indexOf("\n");
}
});
let nextId = 1;
const call = (method: string, params: unknown): Promise<McpMessage> =>
new Promise((resolve) => {
const id = nextId++;
pending.set(id, resolve);
proc.stdin.write(JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n");
});
await call("initialize", {
protocolVersion: "2024-11-05",
capabilities: {},
clientInfo: { name: "lifecycle-smoke", version: "1.0" },
});
proc.stdin.write(JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }) + "\n");
const tools = await call("tools/list", {});
const names = (tools.result as { tools: Array<{ name: string }> }).tools.map((t) => t.name);
assert.equal(names.length, 7, "MCP exposes exactly seven tools");
// A missing task must read "unknown task" (Host task.show), NEVER
// "TaskService is closed": that would mean the lifecycle bug regressed.
const status = await call("tools/call", {
name: "rdk_task_status",
arguments: { task_id: "task-does-not-exist" },
});
const text = (status.result as { content: Array<{ text: string }> }).content[0]!.text;
assert.ok(
!text.includes("TaskService is closed"),
`TaskService must stay open across the MCP session (got: ${text})`,
);
assert.match(text, /unknown task/, "missing task surfaces as a Host error");
// Close stdin → runMcpServer resolves → services close → process exits 0.
proc.stdin.end();
const exitCode = await new Promise<number | null>((resolve) => {
proc.once("exit", resolve);
});
assert.equal(exitCode, 0, "MCP process exits cleanly after stdin closes");
} finally {
if (proc.exitCode === null) proc.kill("SIGKILL");
if (prevState !== undefined) process.env.RDK_STATE_DIR = prevState;
else delete process.env.RDK_STATE_DIR;
if (prevDevice !== undefined) process.env.RDK_DEVICE_COMMAND = prevDevice;
else delete process.env.RDK_DEVICE_COMMAND;
}
},
);

View File

@ -0,0 +1,164 @@
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { test } from "node:test";
import {
LOCK_SCHEMA_VERSION,
newOwnerInstanceId,
OwnerLock,
pidAlive,
} from "../src/ownerLock.js";
const NOW = Date.parse("2026-08-14T00:00:00Z");
function makeLockDir(): string {
return mkdtempSync(path.join(tmpdir(), "rdk-lock-"));
}
test("single writer: second live owner cannot acquire", () => {
const dir = makeLockDir();
const a = new OwnerLock(dir, () => true);
const b = new OwnerLock(dir, () => true);
const first = a.acquire("task-1", "a", NOW);
assert.equal(first.held, true);
const second = b.acquire("task-1", "b", NOW);
assert.equal(second.held, false);
if (second.held) return;
assert.equal(second.existing.owner_instance_id, "a");
assert.equal(second.stale, false);
});
test("release lets the next owner acquire", () => {
const dir = makeLockDir();
const a = new OwnerLock(dir, () => true);
const b = new OwnerLock(dir, () => true);
assert.equal(a.acquire("task-1", "a", NOW).held, true);
a.release("task-1", "a");
assert.equal(b.acquire("task-1", "b", NOW).held, true);
});
test("release never removes a lock held by another owner", () => {
const dir = makeLockDir();
const a = new OwnerLock(dir, () => true);
assert.equal(a.acquire("task-1", "a", NOW).held, true);
const b = new OwnerLock(dir, () => true);
b.release("task-1", "b");
assert.equal(a.read("task-1")?.owner_instance_id, "a");
});
test("stale when heartbeat is too old, regardless of pid liveness", () => {
const dir = makeLockDir();
const a = new OwnerLock(dir, () => true);
assert.equal(a.acquire("task-1", "a", NOW).held, true);
// Heartbeat stays at NOW while the clock advances past the TTL.
const stale = a.isStale(a.read("task-1")!, NOW + 60_000);
assert.equal(stale, true);
});
test("stale when the owner pid is dead even with a fresh heartbeat", () => {
const dir = makeLockDir();
const lock = new OwnerLock(dir, (pid) => pid !== 999999);
writeFileSync(
path.join(dir, "task-1.json"),
JSON.stringify({
schema_version: LOCK_SCHEMA_VERSION,
task_id: "task-1",
owner_instance_id: "ghost",
pid: 999999,
process_started_at: new Date(NOW).toISOString(),
heartbeat_at: new Date(NOW).toISOString(),
}),
);
assert.equal(lock.isStale(lock.read("task-1")!, NOW), true);
});
test("take-over succeeds on a stale owner and displaces it", () => {
const dir = makeLockDir();
const a = new OwnerLock(dir, () => true);
assert.equal(a.acquire("task-1", "a", NOW).held, true);
const b = new OwnerLock(dir, () => true);
const result = b.takeOver("task-1", "b", NOW + 60_000);
assert.equal(result.held, true);
assert.equal(b.read("task-1")?.owner_instance_id, "b");
});
test("take-over refuses a fresh live owner", () => {
const dir = makeLockDir();
const a = new OwnerLock(dir, () => true);
assert.equal(a.acquire("task-1", "a", NOW).held, true);
const b = new OwnerLock(dir, () => true);
const result = b.takeOver("task-1", "b", NOW);
assert.equal(result.held, false);
if (!result.held) assert.equal(result.stale, false);
assert.equal(a.read("task-1")?.owner_instance_id, "a");
});
test("read is a pure observation that never mutates the lock", () => {
const dir = makeLockDir();
const a = new OwnerLock(dir, () => true);
assert.equal(a.acquire("task-1", "a", NOW).held, true);
const before = a.read("task-1");
assert.deepEqual(a.read("task-1"), before);
});
test("heartbeat refreshes only the owning instance's timestamp", () => {
const dir = makeLockDir();
const a = new OwnerLock(dir, () => true);
assert.equal(a.acquire("task-1", "a", NOW).held, true);
a.heartbeat("task-1", "a", NOW + 5_000);
assert.equal(a.read("task-1")!.heartbeat_at, new Date(NOW + 5_000).toISOString());
});
test("two real processes compete for one lock; only the first holds it", async () => {
const dir = makeLockDir();
const moduleUrl = new URL("../src/ownerLock.js", import.meta.url).href;
const childCode = `
const { OwnerLock } = await import(${JSON.stringify(moduleUrl)});
const lock = new OwnerLock(process.env.RDK_LOCK_DIR, () => true);
const r = lock.acquire("task-1", "child", Date.now());
if (!r.held) { console.log("LOST"); process.exit(3); }
console.log("HELD");
setInterval(() => {}, 1000);
`;
const child = spawn(process.execPath, ["--input-type=module", "-e", childCode], {
env: { ...process.env, RDK_LOCK_DIR: dir },
stdio: ["ignore", "pipe", "inherit"],
});
let childHeld = false;
child.stdout.setEncoding("utf8");
await new Promise<void>((resolve, reject) => {
child.stdout.on("data", (chunk: string) => {
if (chunk.includes("HELD")) {
childHeld = true;
resolve();
}
});
child.on("exit", (code) => {
if (!childHeld) reject(new Error(`child exited early: ${String(code)}`));
});
});
assert.equal(childHeld, true);
const parent = new OwnerLock(dir, () => true);
const result = parent.acquire("task-1", "parent", NOW);
assert.equal(result.held, false);
if (!result.held) assert.equal(result.existing.pid, child.pid);
// The child dies; the lock becomes stale and take-over succeeds.
child.kill("SIGKILL");
await new Promise<void>((resolve) => child.on("exit", () => resolve()));
const parentStale = new OwnerLock(dir, (pid) => pid !== child.pid);
const takeover = parentStale.takeOver("task-1", "parent", Date.now());
assert.equal(takeover.held, true);
});
test("newOwnerInstanceId is unique per call", () => {
assert.notEqual(newOwnerInstanceId(), newOwnerInstanceId());
});
test("pidAlive reports true for the current process", () => {
assert.equal(pidAlive(process.pid), true);
});

View File

@ -0,0 +1,57 @@
/**
* Package-root import contract (S1-B §4): the public barrel exposes exactly the
* reviewed surface and never leaks internal implementation details.
*
* Guards against two regressions: (1) the barrel being deleted (which breaks
* desktop's `import ... from "@rdk/rdk-agent-surface"`), and (2) a loose
* `export *` re-exporting owner lock / workspace / envelope internals.
*/
import assert from "node:assert/strict";
import { test } from "node:test";
import * as entry from "../src/index.js";
import { DeviceService } from "../src/deviceService.js";
import { ProjectService } from "../src/projectService.js";
import { TaskService } from "../src/taskService.js";
import { buildTaskService } from "../src/taskServiceFactory.js";
test("public barrel re-exports the reviewed surface", () => {
const keys = Object.keys(entry).sort();
assert.deepEqual(
keys,
[
"DeviceService",
"ProjectService",
"TaskService",
"buildTaskService",
"defaultRealModelDotEnvPath",
"resolveRealModelConfig",
"writeRealModelDotEnv",
].sort(),
);
});
test("the re-exported symbols are the same implementations", () => {
assert.equal(entry.DeviceService, DeviceService);
assert.equal(entry.ProjectService, ProjectService);
assert.equal(entry.TaskService, TaskService);
assert.equal(entry.buildTaskService, buildTaskService);
});
test("the barrel does not leak internal implementation details", () => {
const keys = new Set(Object.keys(entry));
const forbidden = [
"OwnerLock",
"WorkspaceService",
"WorkspaceGuard",
"envelope",
"Envelope",
"resolveAgentCommand",
"resolveStateDir",
"resolvePackageRoot",
];
for (const name of forbidden) {
assert.equal(keys.has(name), false, `barrel leaked internal symbol ${name}`);
}
});

View File

@ -0,0 +1,362 @@
import assert from "node:assert/strict";
import { mkdirSync, mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { test } from "node:test";
import { RdkProtocolError, type ScriptedTurn } from "@rdk/rdk-agent-pi";
import type {
HostClientLike,
SessionFactory,
SessionHandleLike,
TaskServiceOptions,
} from "../src/taskService.js";
import { TaskService } from "../src/taskService.js";
interface FakeTask {
task_id: string;
goal: string;
state: string;
outcome: string | null;
workspace_id: string;
device_ids: string[];
run_ids: string[];
evidence_refs: string[];
required_verifier_ids: string[];
}
class FakeClient implements HostClientLike {
tasks = new Map<string, FakeTask>();
closed = false;
calls: Array<{ method: string; params: Record<string, unknown> }> = [];
cancelledRuns: string[] = [];
async call<T = unknown>(method: string, params: Record<string, unknown> = {}): Promise<T> {
this.calls.push({ method, params });
switch (method) {
case "task.create": {
const id = `task-${String(this.tasks.size + 1)}`;
const task: FakeTask = {
task_id: id,
goal: String(params.goal ?? ""),
state: "created",
outcome: null,
workspace_id: String(params.workspace_id ?? "."),
device_ids: (params.device_ids as string[]) ?? [],
run_ids: [],
evidence_refs: [],
required_verifier_ids: (params.required_verifier_ids as string[]) ?? [],
};
this.tasks.set(id, task);
return { task } as T;
}
case "task.reconcile": {
const task = this.tasks.get(String(params.task_id));
if (!task) throw new RdkProtocolError("RDK-INV-001", "unknown task");
return { task: { ...task } } as T;
}
case "task.checkpoint": {
const task = this.tasks.get(String(params.task_id));
if (!task) throw new RdkProtocolError("RDK-INV-001", "unknown task");
return {
checkpoint_id: "sha256:fake",
task_id: task.task_id,
unsatisfied_verifier_ids: [...task.required_verifier_ids],
active_run_ids: [],
completed_run_ids: [...task.run_ids],
waiting_on: String(params.waiting_on ?? "resumed"),
created_at: "2026-01-01T00:00:00Z",
} as T;
}
case "task.show": {
const task = this.tasks.get(String(params.task_id));
if (!task) throw new RdkProtocolError("RDK-INV-001", "unknown task");
return { task: { ...task } } as T;
}
case "task.list":
return { tasks: [...this.tasks.values()] } as T;
case "run.cancel":
this.cancelledRuns.push(String(params.run_id));
return {} as T;
case "artifact.read":
return { artifact: { artifact_id: params.artifact_id }, preview: "preview" } as T;
default:
throw new RdkProtocolError("RDK-PROTO-001", `unexpected ${method}`);
}
}
async close(): Promise<void> {
this.closed = true;
}
}
class FakeSession implements SessionHandleLike {
prompts: string[] = [];
disposed = false;
closed = false;
session = {
prompt: async (message: string) => {
this.prompts.push(message);
},
dispose: () => {
this.disposed = true;
},
};
async close(): Promise<void> {
this.closed = true;
this.session.dispose();
}
}
function makeOptions(overrides: Partial<TaskServiceOptions> = {}): {
client: FakeClient;
handles: FakeSession[];
service: TaskService;
root: string;
} {
const base = mkdtempSync(path.join(tmpdir(), "rdk-ts-"));
const root = path.join(base, "workspace");
mkdirSync(root, { recursive: true });
const client = new FakeClient();
const handles: FakeSession[] = [];
const sessionFactory: SessionFactory = async () => {
const handle = new FakeSession();
handles.push(handle);
return handle;
};
const service = new TaskService({
client,
workspaceRoot: root,
packageRoot: path.join(base, "pi-rdk-agent"),
agentDirRoot: path.join(base, "agent-dirs"),
lockDir: path.join(base, "task-locks"),
sessionFactory,
modelFactory: async (_agentDir: string, _turns: ScriptedTurn[]) => ({ model: { fake: true } }),
...overrides,
});
return { client, handles, service, root };
}
test("startTask creates a task, session, and runs the health-card prompt", async () => {
const { client, handles, service } = makeOptions();
const handle = await service.startTask("check health", "proj", ["fake-001"], "guide", "cli");
assert.match(handle.task_id, /^task-/);
assert.equal(handles.length, 1);
assert.ok(handles[0]!.prompts.length >= 1);
assert.equal(client.calls[0]!.method, "task.create");
await service.close();
});
test("each task gets its own independent SessionHandle", async () => {
const { handles, service } = makeOptions();
const a = await service.startTask("a", "proj", ["fake-001"], "guide", "cli");
const b = await service.startTask("b", "proj", ["fake-001"], "guide", "cli");
assert.notEqual(a.task_id, b.task_id);
assert.equal(handles.length, 2);
assert.notEqual(handles[0], handles[1]);
await service.close();
});
test("getTask returns durable status and this-process events", async () => {
const { service } = makeOptions();
const started = await service.startTask("check health", "proj", ["fake-001"], "guide", "cli");
const snapshot = await service.getTask(started.task_id);
assert.equal(snapshot.status.task_id, started.task_id);
assert.equal(snapshot.status.state, "created");
assert.equal(snapshot.status.required_action, null);
assert.ok(snapshot.events.length >= 1);
await service.close();
});
test("getTask filters events after a sequence number", async () => {
const { service } = makeOptions();
const started = await service.startTask("check health", "proj", ["fake-001"], "guide", "cli");
const all = await service.getTask(started.task_id);
const tail = await service.getTask(started.task_id, 1);
assert.equal(tail.events.length, all.events.length - 1);
await service.close();
});
test("steerTask appends a prompt to the task's session", async () => {
const { handles, service } = makeOptions();
const started = await service.startTask("check health", "proj", ["fake-001"], "guide", "cli");
const before = handles[0]!.prompts.length;
await service.steerTask(started.task_id, "keep going", "cli");
assert.equal(handles[0]!.prompts.length, before + 1);
await service.close();
});
test("cancelTask is idempotent and disposes the session", async () => {
const { client, handles, service } = makeOptions();
const started = await service.startTask("check health", "proj", ["fake-001"], "guide", "cli");
await service.cancelTask(started.task_id, "done", "cli");
assert.equal(handles[0]!.closed, true);
await service.cancelTask(started.task_id, "again", "cli"); // no throw
await service.close();
assert.equal(client.closed, true);
});
test("close disposes all sessions and closes the client", async () => {
const { client, handles, service } = makeOptions();
await service.startTask("a", "proj", ["fake-001"], "guide", "cli");
await service.startTask("b", "proj", ["fake-001"], "guide", "cli");
await service.close();
assert.equal(handles.length, 2);
assert.ok(handles.every((h) => h.closed));
assert.equal(client.closed, true);
});
test("readArtifact reads through the task's first run", async () => {
const { client, service } = makeOptions();
const started = await service.startTask("check health", "proj", ["fake-001"], "guide", "cli");
client.tasks.get(started.task_id)!.run_ids.push("run-1");
const result = await service.readArtifact(started.task_id, "art-1");
assert.equal((result as { preview: string }).preview, "preview");
assert.ok(client.calls.some((c) => c.method === "artifact.read"));
await service.close();
});
test("readArtifact without runs is a stable input error", async () => {
const { service } = makeOptions();
const started = await service.startTask("check health", "proj", ["fake-001"], "guide", "cli");
await assert.rejects(() => service.readArtifact(started.task_id, "art-1"), RdkProtocolError);
await service.close();
});
test("unknown task id is rejected for steer", async () => {
const { service } = makeOptions();
await assert.rejects(() => service.steerTask("task-nope", "hi", "cli"), RdkProtocolError);
await service.close();
});
test("invalid mode is rejected before any task is created", async () => {
const { client, service } = makeOptions();
await assert.rejects(
() => service.startTask("g", "proj", ["fake-001"], "auto_high_risk" as never, "cli"),
RdkProtocolError,
);
assert.equal(client.calls.length, 0);
await service.close();
});
function makeSharedService(opts: {
client: FakeClient;
root: string;
agentDirRoot: string;
lockDir: string;
now: () => number;
ownerInstanceId: string;
}): TaskService {
return new TaskService({
client: opts.client,
workspaceRoot: opts.root,
packageRoot: path.join(opts.root, "pi-rdk-agent"),
agentDirRoot: opts.agentDirRoot,
lockDir: opts.lockDir,
ownerInstanceId: opts.ownerInstanceId,
sessionFactory: async () => new FakeSession(),
modelFactory: async () => ({ model: { fake: true } }),
now: opts.now,
});
}
test("steerTask from a second live owner is refused", async () => {
const base = mkdtempSync(path.join(tmpdir(), "rdk-ts-shared-"));
const root = path.join(base, "workspace");
mkdirSync(root, { recursive: true });
const lockDir = path.join(base, "locks");
const agentDirRoot = path.join(base, "agents");
const client = new FakeClient();
const a = makeSharedService({
client, root, lockDir, agentDirRoot, now: () => 0, ownerInstanceId: "instance-a",
});
const b = makeSharedService({
client, root, lockDir, agentDirRoot, now: () => 0, ownerInstanceId: "instance-b",
});
const started = await a.startTask("check health", "proj", ["fake-001"], "guide", "a");
await assert.rejects(
() => b.steerTask(started.task_id, "hi", "b"),
(err: unknown) => err instanceof RdkProtocolError && err.code === "RDK-OWNER-001",
);
await a.close();
});
test("stale owner requires explicit take-over, then owner changes", async () => {
const base = mkdtempSync(path.join(tmpdir(), "rdk-ts-stale-"));
const root = path.join(base, "workspace");
mkdirSync(root, { recursive: true });
const lockDir = path.join(base, "locks");
const agentDirRoot = path.join(base, "agents");
const client = new FakeClient();
const a = makeSharedService({
client, root, lockDir, agentDirRoot, now: () => 0, ownerInstanceId: "instance-a",
});
const b = makeSharedService({
client, root, lockDir, agentDirRoot, now: () => 60_000, ownerInstanceId: "instance-b",
});
const started = await a.startTask("check health", "proj", ["fake-001"], "guide", "a");
await assert.rejects(
() => b.resumeTask(started.task_id, "b", false),
(err: unknown) => err instanceof RdkProtocolError && err.code === "RDK-OWNER-002",
);
const resumed = await b.resumeTask(started.task_id, "b", true);
assert.equal(resumed.task_id, started.task_id);
const snapshot = await b.getTask(started.task_id);
assert.ok(snapshot.events.some((e) => e.kind === "task.owner_changed"));
await a.close();
});
test("resume reconciles device truth, checkpoints, and injects recovery context", async () => {
const base = mkdtempSync(path.join(tmpdir(), "rdk-ts-resume-"));
const root = path.join(base, "workspace");
mkdirSync(root, { recursive: true });
const lockDir = path.join(base, "locks");
const agentDirRoot = path.join(base, "agents");
const client = new FakeClient();
const captured: ScriptedTurn[][] = [];
const mkService = (ownerInstanceId: string, now: number) =>
new TaskService({
client,
workspaceRoot: root,
packageRoot: path.join(root, "pi-rdk-agent"),
agentDirRoot,
lockDir,
ownerInstanceId,
sessionFactory: async () => new FakeSession(),
modelFactory: async (_agentDir: string, turns: ScriptedTurn[]) => {
captured.push(turns);
return { model: { fake: true } };
},
now: () => now,
});
const a = mkService("instance-a", 0);
const b = mkService("instance-b", 60_000);
const started = await a.startTask("check health", "proj", ["fake-001"], "guide", "a");
// The task has a required verifier not yet satisfied and one completed run.
const task = client.tasks.get(started.task_id)!;
task.required_verifier_ids = ["exit-ok"];
task.run_ids = ["run-1"];
const resumed = await b.resumeTask(started.task_id, "b", true);
assert.equal(resumed.task_id, started.task_id);
const methods = client.calls.map((c) => c.method);
assert.ok(methods.includes("task.reconcile"), "resume must reconcile device truth");
assert.ok(methods.includes("task.checkpoint"), "resume must freeze a recovery checkpoint");
// b created a fresh session primed with recovery context (the resume turn).
const resumeTurns = captured.at(-1) ?? [];
const text = (resumeTurns[0] as { text?: string } | undefined)?.text ?? "";
assert.match(text, /resumed task/, "context identifies the task");
assert.match(text, /check health/, "context carries the goal");
assert.match(text, /exit-ok/, "context lists unsatisfied verifiers");
await a.close();
await b.close();
});

View File

@ -0,0 +1,23 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { listSkills, parseTuiInput, readSkill } from "../src/tui.js";
test("parseTuiInput routes slash-skill and lists", () => {
assert.deepEqual(parseTuiInput("/skills"), { command: "skills" });
assert.deepEqual(parseTuiInput("/skill rdk-diagnose 查温度"), {
command: "skill",
arg: "rdk-diagnose 查温度",
});
assert.deepEqual(parseTuiInput("随便聊聊"), { command: "steer", arg: "随便聊聊" });
});
test("listSkills discovers trusted local skills and readSkill reads them", () => {
const skills = listSkills();
assert.ok(skills.includes("rdk-develop"));
assert.ok(skills.includes("rdk-diagnose"));
for (const name of skills) {
assert.ok((readSkill(name) ?? "").length > 0);
}
assert.equal(readSkill("not-a-skill"), null);
});

Some files were not shown because too many files have changed in this diff Show More