Skip to content

Latest commit

 

History

History
903 lines (703 loc) · 39 KB

MOCK_DEVICE_TESTING.md

File metadata and controls

903 lines (703 loc) · 39 KB

Mock device and hardware record/replay architecture

Status: implemented architecture for fixture contracts, replay, recording, CLI capture/verification, semantic mock profiles, and injected agent hardware. The root corpus contains reviewed captures with automatic device, Agent, IPC, and desktop regression suites. Fixture schema v1 remains unreleased and is not yet a stable public format. See current guarantees and commands.

Why this needs more than one mock

OpenLogi already has two useful but separate hardware-free paths:

  • openlogi-agent-mock implements the agent IPC service from a hard-coded, mutable inventory. It is good for manual GUI development, but it bypasses device enumeration and HID++ parsing.
  • openlogi-device::replay supplies cassette-backed channels and mutable topology below production device code. Focused unit tests still use concise scripted responders where a persisted cassette would obscure the contract.

The missing piece is not one more fake device. It is a small test platform that can retain facts learned from real devices, replay them below production device logic, and add deterministic behavior that cannot be learned from one capture.

Hardware complexity makes the distinction important:

  • One OS node may be a Bolt or Unifying receiver serving several device slots, while a Bluetooth or wired device is addressed directly.
  • Node presence, successful open, channel connectivity, receiver pairing, and paired-device online state are independent. Collapsing them into one online flag cannot reproduce recovery bugs.
  • HID++ 1.0 register traffic and HID++ 2.0 feature traffic have different correlation rules. HID++ 2.0 feature indexes are assigned by each device at runtime and its software ID can differ between channel opens.
  • A channel has a dedicated reader and can carry concurrent requests, responses, late responses, and unsolicited lifecycle/input notifications.
  • Some output uses request/response HID++ reports, some lighting uses 64-byte 0x12 reports, and standalone Litra devices are tried over HID++ 0x1990 before falling back to raw writes with no response.
  • Enumeration is event-first and stateful. It reuses channels, caches immutable probe data, refreshes volatile battery state, replays last-good inventory through transient failures, and eventually retires and reopens unhealthy channels.
  • Gesture capture and pairing are asynchronous state machines with cleanup obligations. A successful byte transcript does not describe what should happen after cancellation, sleep, disconnect, or a missing response.
  • The native backend includes behavior a portable replay cannot prove: macOS TCC identity and exclusive opens, Windows composite short/long collections, Linux receiver-child filtering, and host HID callback failures.

The framework therefore has three source artifacts with different contracts:

                         semantic reads
┌──────────────┐       ───────────────────▶  Device Profile
│ Real device  │                                  │
│ and receiver │                                  ├──▶ IPC mock / desktop tests
└──────┬───────┘                                  └──▶ human-reviewed expectations
       │
       │ observed HID reports
       └──────────────────────────────────▶  HID Cassette
                                                   │
                                                   └──▶ device-layer replay

Hand-authored deterministic transitions ─────▶  Scenario
                                                   │
                                                   └──▶ lifecycle/fault/state tests

Goals

  1. Turn a real but otherwise unavailable Logitech device into a reviewable, sanitized regression fixture.
  2. Exercise production HID++ parsing, feature probing, routing, reads, and writes without hardware in CI.
  3. Feed realistic device inventories and initial settings to the existing IPC mock without making the GUI know it is using a fixture.
  4. Reproduce lifecycle and failure paths deterministically, without real-time sleeps or flaky global ordering assumptions.
  5. Make an incomplete or stale fixture fail loudly: unmatched requests, unconsumed required exchanges, unsupported schema versions, and sensitive identifiers are errors.
  6. Keep platform-specific hardware verification explicit. A replay pass is not evidence that macOS TCC, Linux hidraw access, Windows composite opening, or a physical write works.

Non-goals

  • Emulating arbitrary Logitech firmware.
  • Recording all traffic from a normal desktop session and treating it as a deterministic test.
  • Replacing focused hand-written protocol and state-machine unit tests.
  • Running real hardware in mandatory CI.
  • Adding mock-control methods to the append-only production agent IPC service.
  • Making fixture data part of the agent/GUI wire format or product config.
  • Proving that a value generated by the current parser is correct merely by recording it as a golden value.

Testing layers

The layers intentionally overlap. A failure should name the lowest broken contract rather than surface only as a GUI mismatch.

Layer Production code exercised Data source Primary purpose
Protocol codec openlogi-hidpp message/feature decoders Hand-written bytes Byte layout and unknown-value handling
Device operation openlogi-device over a replay raw channel HID cassette Feature lookup, reads, writes, fallback
Discovery/recovery Enumerator over a replay HidBackend Profile + cassette + scenario Topology, cache, ledger, channel lifecycle
Agent semantics MockAgent initially; real agent-core later Device profile + scenario Snapshot and command contract
Desktop projection Desktop state merge/render seams Agent snapshot derived from profile Panels, routes, online/offline presentation
Hardware-in-loop Native backend and physical device Opt-in local run Host permissions, opens, transport, actual effects

The first implementation should stop at the device and IPC-mock layers. Full real-agent replay requires coherent hardware dependency injection and is a later phase, not a prerequisite for useful fixtures.

Architectural invariants

  1. Production device logic never branches on “mock”. It sees a HidBackend, RawHidChannel, or RawWriter with the existing contracts.
  2. Physical topology and device state stay separate. OS node presence, open result, channel connection, receiver slot pairing, and link liveness are distinct values.
  3. Identity stays separate from transport. A specimen can have Bolt, Bluetooth, and USB links. Captures must not merge two physical devices just because their model IDs match, and must not turn an OS node ID into a stable identity.
  4. Capabilities come from observed feature data, not device kind. Fixtures preserve the same rule as production inventory.
  5. Raw evidence and semantic expectations are separate. Raw reports can be replayed after parser changes; expected inventory/settings are independently reviewable assertions.
  6. Recorded order is local, not global. Concurrent receiver slots may interleave differently. Matching is per logical channel and normalized request; unsolicited events are explicit.
  7. Fixture time is logical. Tests advance state or release a barrier. They do not wait for the production 30-second recovery scan, 90-second pairing deadline, or mock battery timers.
  8. Recording is read-only by default. A write case needs explicit consent, a known restoration plan, and a failed restoration prevents fixture output.
  9. No sensitive raw data reaches disk by default. Sanitization happens in memory before an atomic write.
  10. Strict replay is the default. Unknown outgoing requests fail immediately, and every required exchange must be consumed by the end of a case.

Ownership

Fixture contracts and device replay have different dependency boundaries. The schema is a published, host-free crate consumed by capture, verification, and semantic mocks; replay stays beside the HidBackend contract it implements.

openlogi-fixture

Owns the persisted contract and its pure verification:

  • Versioned semantic profile, cassette, and manifest schemas.
  • Synthetic identity generation and protocol-aware identity extraction.
  • Exact relationship, privacy, occurrence-count, and framing validation.
  • The packaged canonical synthetic profile used by the no-argument mock.

It performs no file I/O, host access, or async work and depends only on openlogi-core plus serialization/error support. This keeps the published CLI dependency closure valid and lets schema checks run without pulling in HID++ transport.

openlogi-device

The replay module owns runtime behavior over fixture cassettes:

  • ReplayRawHidChannel, ReplayRawWriter, and ReplayBackend.
  • A mutable virtual topology and explicit event injection handles.
  • Response barriers, request matching, and completion diagnostics.

Reusable transport plumbing lives here rather than in the test-only channel::scripted module. Concise responder helpers remain for hand-written unit tests; a fixture should not make small tests harder to read.

This remains portable: it knows HID++ and HidBackend, not async-hid, paths, files, clocks, or a host OS.

openlogi-hid

Own native recording because this is where async-hid channels are turned into HidppChannels and raw writers:

  • A recording backend variant wraps native channels before they are shared.
  • An optional channel observer records actual post-normalization reports and request outcomes.
  • Raw 0x12/Litra writers are observed separately because they bypass the request/response channel.
  • Native NodeInfo, supported report widths, open failures, and channel IDs are reported to the recorder without becoming persisted physical identity.

The process-wide native HID manager remains shared. A recorder may own a separate backend facade and handle cache, but it must not create a second host HID manager per operation.

openlogi-cli

Own user interaction and file I/O:

  • openlogi fixture contribute
  • openlogi fixture record profile
  • openlogi fixture record case
  • openlogi fixture verify <fixture-directory>
  • Strict target selection, safety warnings, sanitization report, case self-replay, atomic publication, and strict corpus loading.

snapshot already means camera capture, so fixture commands must not reuse that name.

openlogi-agent-mock

Load a semantic profile and construct its own current AgentStatus, generation, camera, foreground-app, and pairing state. A captured AgentSnapshot is not the fixture format: it contains host status and protocol-version concerns that do not describe a device.

The built-in scripted inventory remains the no-argument default. Manual demo mode can retain moving battery/app/camera behavior. Test mode freezes those inputs and changes them only through a scenario or the console's advance command.

While it runs, the mock reads one console command per stdin line (help lists them). The console changes only semantic state that the IPC contract already exposes:

  • a paired device's battery reading;
  • a device's online flag;
  • a fault that makes every read and write to an online device fail;
  • a lock-key or backlight indicator change;
  • frozen test time;
  • every open client connection, closed as an agent restart closes them.

Battery readings and indicators go through the same agent-core state machines that the orchestrator uses. Tests build Command values and call MockAgent::apply directly; the command words are for people only. The console does not replace the scenario controls below: it models no channel, report, or barrier.

openlogi-agent-core (later)

When full-agent replay has a concrete test that needs it, introduce one coherent hardware runtime value rather than adding backend parameters one call at a time. It must supply the same backend to:

  • the persistent enumerator and hotplug watcher;
  • the channel pool and registry;
  • pairing;
  • standalone enumeration and Litra writes;
  • the device I/O gate and probe-cache store.

Production constructs a native runtime; tests construct a replay runtime with an in-memory cache store. This is dependency injection, not a new event bus: hotplug and HID lifecycle input continue through their existing streams. No IPC change is needed.

Virtual hardware model

The replay backend models four orthogonal levels.

Topology

VirtualHardware
  nodes[]
    NodeInfo (sanitized)
    presence: absent | present
    open: hidpp | not_hidpp | denied | disconnected
    report_support: short_and_long | long_only
    raw_writer: optional
    logical_channel_id

Topology snapshots are returned by enumerate/enumerate_hidpp. A scenario updates the snapshot and emits a HotplugEvent; the event never secretly changes topology by itself. Tests can therefore reproduce a missed event or a changed snapshot independently.

Channel

A replay channel owns:

  • pending cassette exchanges keyed by normalized requests;
  • an incoming report queue;
  • an explicit connected flag;
  • unsolicited event injection;
  • all observed writes;
  • a completion report naming unmatched and unconsumed exchanges.

Several routes behind one receiver share one logical channel. Direct devices use separate channels. Reopening a node creates a new channel lifetime so tests can distinguish a repaired connection from continued use of a stale one.

Device state

The semantic mock starts with a small typed state, not a generic property bag:

  • DPI current value and capabilities;
  • SmartShift status;
  • scroll mode;
  • backlight state;
  • accepted lighting/light operations;
  • battery snapshot;
  • online/offline status.

Only add a state field when production exposes a read-after-write contract for it. HID cassettes can assert exact writes without pretending to model the resulting firmware state. This prevents the framework from growing into an incomplete firmware implementation.

Scenario control

Scenarios perform explicit transitions such as:

  • connect or remove a node;
  • fail the next open;
  • disconnect an open channel;
  • put one receiver slot to sleep or wake it;
  • enqueue an unsolicited HID++ notification;
  • answer a request with a feature error or malformed report;
  • release a blocked request after the test reaches a barrier;
  • begin, advance, cancel, or fail pairing.

Start with hand-authored Rust scenarios. A serialized scenario language should be added only after several tests repeat the same transition vocabulary. Static device facts and captures belong in data; race orchestration is clearer in code.

Fixture corpus

Store one directory per sanitized physical specimen, with one or more transport links:

fixtures/devices/
  mx-master-3s-001/
    manifest.json
    profile.json
    cases/
      bolt-probe.json
      dpi-read.json
      smartshift-read.json

The built-in profile-only synthetic fixture is packaging data rather than captured corpus. It lives under crates/openlogi-fixture/fixtures/devices/openlogi-canonical-synthetic-001/ so crates.io packages remain self-contained. It must not be copied into the root corpus or presented as physical-hardware evidence.

The numeric suffix is a synthetic specimen identity, not a device serial. Two captures are linked as the same specimen only when the recorder/operator knows they came from the same physical unit. Matching model IDs is insufficient.

manifest.json

Contains the exact privacy and relationship contract, not capture provenance or semantic expectations:

  • fixture schema version;
  • synthetic specimen ID and related profile ID;
  • named case, logical channel, and receiver/device relationship;
  • fixture-local receiver and device principals with typed profile routes;
  • canonical synthetic identity representations;
  • exact nonzero occurrence counts at typed profile/cassette locations.

Do not store contributor identity, local paths, OS node IDs, capture timestamps that create churn, hashed hardware identifiers, original values, or a sanitized boolean. Verification re-extracts identity evidence from the profile and every cassette rather than trusting capture metadata.

profile.json

Contains semantic initial state and expected domain values:

  • receiver/direct/raw-HID shape;
  • paired device records and capabilities;
  • standalone device capabilities;
  • supported setting reads and their initial results;
  • stable synthetic identities preserving relationships within the fixture.

Use the existing domain types where their JSON shape is appropriate, wrapped in an independently versioned profile schema. Do not serialize bincode IPC goldens or make profile schema changes bump PROTOCOL_VERSION.

cases/*.json

Each file represents one named operation or coherent probe, not an ambient session:

{
  "schema_version": 1,
  "name": "dpi-read",
  "channel": "bolt-receiver-1",
  "report_support": "short_and_long",
  "exchanges": [
    {
      "request_match": "hidpp20",
      "request": "1101001100000000000000000000000000000000",
      "response": "1101001104000000000000000000000000000000",
      "required": true
    }
  ]
}

The example illustrates shape only; captured values must come from the actual operation. Hex is lowercase and includes the report ID. The cassette contains raw evidence only; independently reviewed semantic expectations belong in the profile or an operation-contract test and are not silently regenerated from replay output.

Split cases because a full inventory probe can contain hundreds of exchanges and changes more often than a focused DPI read. A regression should identify the operation that no longer matches.

Run openlogi fixture verify <fixture-directory> before review. The loader accepts only a real, non-symlink directory whose name equals the manifest ID, requires exactly manifest.json, profile.json, and the complete declared cases/*.json set, and rejects unknown files, unsafe case names, symlinks, and unknown JSON fields. It reports schema, relationship, privacy, and replay validation separately. This command performs no hardware access and does not establish semantic or physical correctness.

The CLI corpus tests discover and strictly verify every directory under both fixtures/devices/ and the packaged synthetic corpus. The root corpus may be absent until the first contribution; once present, every entry must be a valid fixture directory. Run cargo test -p openlogi-cli fixture::verify locally.

Recording model

Two capture modes

Semantic profile capture should prefer the running agent's existing IPC snapshot and read methods. The agent is the normal owner of device permission and already holds stable channels. This mode records no raw reports and needs no new IPC method.

Raw case capture is a controlled direct diagnostic operation. It uses the same ownership model as the existing openlogi diag commands: discover devices, select one target, open it, run one named read operation, and exit. Discovery uses production enumeration, which may write receiver notification flags (register 0x00) and request arrival reports (register 0x02) on connected receivers before target selection. Those flags are not restored. The CLI warns before discovery; use semantic profile capture to avoid this direct access. These setup writes are outside the cassette and are not accepted as read-only exchanges by the sanitizer. Capture does not change device settings or pairings and is not an ambient sniffer.

Before enumerating hardware, raw fixture capture acquires the same profile's agent.lock used by agent startup, then checks that the IPC endpoint is unreachable. The selected target holds the lock for the entire capture, including all eight cases in the contribution wizard. This excludes agent relaunches and other fixture captures until completion; errors, cancellation, and process exit release the lock. It does not exclude Options+ or other direct diagnostic tools.

Contribution wizard

openlogi fixture contribute combines the safe capture modes without changing their ownership boundaries:

openlogi fixture contribute \
  --id mx-master-3s-001 \
  --name "MX Master 3S" \
  --device "MX Master 3S" \
  --output fixtures/devices/mx-master-3s-001

Run it once while the Agent is available. The CLI captures and validates one semantic profile, then stores only that sanitized profile and a hidden resumption file containing synthetic fixture metadata and a sanitized route. It never stores the selector, original receiver identity, node path, hashes, timestamps, or contributor identity.

For HID++ devices, stop the Agent and rerun the same command. The CLI confirms the same transport kind and receiver slot (or direct VID/PID), records all eight supported read-only operation cases, self-replays every candidate, and generates manifest.json from the finalized profile and cassettes. Manifest generation re-extracts exact identity occurrences; it does not trust sanitizer audit counts. A profile-derived synthetic identity plan keeps cassette receiver and device identities related to the profile even when the selected receiver slot is not the first retained device.

The wizard captures all cassettes in memory before publishing any case. A capture or verification failure leaves the resumable state in place and writes no partial case set. The state file is removed only after cases and manifest have been written; strict on-disk verification then rejects any unexpected entry or relationship. No upload, branch, commit, or pull request is created.

--profile-only ends after the Agent phase. Raw-HID standalone devices use this mode automatically because fixture schema v1 has no safe replay contract for raw writes. The lower-level fixture record profile and fixture record case commands remain available for focused diagnostics, but contributors should not hand-author the manifest or identity occurrence ledger.

On macOS these are different TCC identities. A packaged or development agent's Input Monitoring grant does not authorize the CLI, and a GUI grant authorizes neither. The raw recorder must never prompt indirectly or claim the agent's grant applies to it. It should:

  1. detect and refuse conflicting agent/Options+ ownership where possible;
  2. identify itself as direct CLI hardware access;
  3. report an open failure using the existing permission/exclusive-open classification;
  4. leave semantic profile capture available through the agent when direct capture is not authorized.

Do not add raw-recording methods to production IPC. They would permanently expand an append-only wire with a developer-only, sensitive-data interface.

Reliable request association

Raw write then read order is insufficient: receiver slots probe concurrently and unsolicited reports can appear between a request and its response. The recording path needs an optional no-op-by-default observer at the HidppChannel boundary, where pending request IDs and response matching are already known.

The observer records:

  • outgoing request ID and actual post-normalization report;
  • matched incoming report and request ID;
  • unmatched incoming report;
  • timeout, write failure, or cancellation outcome;
  • fire-and-forget and raw writes without a response ID.

Incoming bytes should be observed before parse rejection as well, so an explicit malformed-report case can retain its evidence. The native backend adds node/channel metadata; it does not reimplement correlation.

Capture plans

Version capture plans by name. The initial read-only plan should contain:

  1. target identity and transport metadata;
  2. production inventory/probe for the selected node;
  3. feature and firmware tables;
  4. capability-gated reads for battery, DPI, SmartShift, wheel, controls, and backlight;
  5. semantic expectations produced as a review candidate;
  6. local self-replay before output is accepted.

Unsupported features and typed device errors are valid recorded outcomes. Host open errors and interrupted captures are capture failures, not device fixtures.

Target selection must reject ambiguity. The current diagnostic convenience of choosing the first case-insensitive name match is not safe when a corpus must claim which physical route it represents.

Writes

The default plan records only reads. Its pre-selection receiver discovery has the notification/arrival setup side effects described above; it is not a zero-write hardware session. Setting-write cases are not implemented. A future named write case requires --allow-writes and must define:

  • the initial read;
  • a bounded alternate value supported by that device;
  • verification when the protocol exposes it;
  • restoration of the exact initial value;
  • an error path that attempts restoration and refuses to write a fixture if restoration is not confirmed.

This still cannot protect against process or host failure between write and restore, so the CLI must state the risk before it starts. Pairing/unpairing is excluded from automated recording in the first versions because it is destructive, interactive, and carries addresses/passkeys.

Output transaction

The recorder performs the following transaction entirely before the final path appears:

  1. capture into memory;
  2. classify and sanitize identifiers;
  3. validate schema and invariants;
  4. replay through production device APIs;
  5. compare replay output with the candidate semantic result;
  6. run the privacy validator;
  7. write a temporary file and atomically rename it.

Self-replay proves completeness and determinism, not semantic correctness. A reviewer still confirms model, transport, capabilities, and expected values.

Sanitization

Values requiring replacement include at least:

  • receiver unique ID/serial;
  • device serial number and unit ID;
  • raw-HID serial identity and host node identity;
  • Bluetooth device address;
  • pairing passkey;
  • any local path or foreground-application data accidentally included by a broader capture.

Replacement is relation-preserving and protocol-aware. For example, every occurrence of one receiver ID maps to the same synthetic receiver ID in the profile and raw response. Use generated synthetic values, not hashes of the original: a hash remains a persistent fingerprint and can be reversible for a small identifier space.

Raw payload replacement must preserve report length and field validity. The sanitizer tracks feature-index mappings learned during the capture so it can recognize known identity functions even though their runtime indexes differ by device. Receiver registers use their own protocol-specific rules.

Unknown raw data is not automatically safe. If the sanitizer cannot classify a report that may carry identity or pairing data, it may retain it only in an explicit local/private capture; it must refuse to mark the fixture committable. Passkeys are never persisted, even in a sanitized pairing transcript.

The repository test walks every fixture and reruns the privacy validator. This guards later manual edits as well as the recorder.

Replay matching

HID++ 2.0 normalization

Match the actual report ID, length, device index, feature index, function, and payload. Normalize only the request software-ID low nibble. On response:

  • a normal response receives the current request software ID in its header;
  • a feature-error response receives it in the echoed original function/software byte;
  • all other bytes remain exact.

Arbitrary user-authored masks are rejected. They make fixtures pass after meaningful payload changes and hide recorder bugs.

HID++ 1.0

Do not apply the HID++ 2.0 software-ID rule. Register address and payload are matched using HID++ 1.0 correlation semantics. The HID++ 2.0 ping used to detect a 1.0 device is represented explicitly as that cross-version exchange.

Repetition and concurrency

Store a FIFO queue per normalized request key. This supports repeated reads whose response changes while allowing independent receiver-slot requests to interleave. Do not assert one global write order unless the production contract itself requires serialization, such as ordered lighting frames.

Unsolicited input

Notifications are scenario events, even if they were observed during capture. A cassette may retain an unassociated report as evidence, but replay injects it only at an explicit step/barrier. Otherwise a scheduler difference would turn recorded timing into a flaky test.

Capture drops an unmatched HID++ report that no recorded request could have taken as its answer: a receiver or device notification, or a reply to another host driver on the same node (on Linux, hid-logitech-dj and hid-logitech-hidpp drive a receiver through the hidraw node capture reads, and hid-logitech-hidpp tags its requests with software ID 1). It rejects the recording when some recorded request could have taken the report, because that request's recorded answer may then belong to another sender.

Completion

A replay case reports:

  • unmatched outgoing requests with normalized and actual hex;
  • required exchanges not consumed;
  • optional exchanges consumed or unused;
  • unexpected raw writes;
  • channel open/reopen counts;
  • final connection/topology state.

Optional exchanges are reserved for documented best-effort production reads. They are not a general escape hatch for fixture drift.

Determinism and failure testing

Use immediate, controlled outcomes for most failures:

  • HID++ feature error;
  • malformed response;
  • backend open error;
  • transport write error;
  • explicit channel disconnect;
  • dropped node or sleeping slot;
  • late response released after a barrier.

A “no response” test otherwise waits for the production five-second channel deadline. Keep timeout mechanics in focused openlogi-hidpp tests that call the configurable timeout with a small budget. Higher-layer fixture tests should use an equivalent immediate failure unless the deadline itself is their subject.

Inventory schedule tests use a logical/manual clock or existing scheduling seams. They should advance the 200/400 ms settle windows, two-second repair window, and 30-second recovery interval without sleeping. The IPC mock has two clock modes:

  • Demo: current wall/monotonic behavior for visually changing battery, foreground application, and camera state.
  • Test: frozen time advanced only by the scenario.

Race tests should synchronize on explicit barriers such as “request written” or “channel retirement started,” never millisecond sleeps.

Test suites generated from the corpus

The current implementation discovers all fourteen contributed specimens and replays all 98 declared reads. openlogi-fixture owns strict filesystem loading behind its optional fs feature; the default schema and privacy APIs remain host-free. ReplayTopology::for_device owns capture and corpus topology. ReplayBackend::from_profile supports the single-device HID++ contributions currently recorded and rejects unsupported target shapes.

CLI operation expectations, Agent lifecycle gates, mock RPC/socket behavior, and desktop projection are mandatory workspace tests. The following sections also describe extensions that require additional captures: firmware, complete enumeration sessions, physical writes, and hardware-in-loop validation are not covered by the current read corpus. See the corpus contract for the exact boundary of each executed suite.

Corpus integrity

One test discovers every fixture directory and verifies:

  • known schema version and no unknown fields;
  • unique synthetic identities and valid route relationships;
  • no sensitive identifiers;
  • capabilities and declared operation results are consistent;
  • every case names a profile link and logical channel that exist;
  • every hex report has a valid declared length.

Device operation contracts

For each relevant case, construct a replay channel/backend and invoke the same public openlogi-device operation production uses. Assert the independently reviewed semantic result, exact required writes, and complete cassette consumption.

Initial case families:

  • direct and receiver-backed probe;
  • feature/firmware/control dump;
  • battery read across unified, legacy, and voltage features;
  • DPI and SmartShift read;
  • wheel and backlight read;
  • long-only direct-device request widening;
  • raw lighting/Litra encoding expectations.

Enumeration and recovery scenarios

Combine a profile/cassette with hand-authored topology transitions to test:

  • several slots sharing one receiver channel;
  • offline slots surfacing without feature probes;
  • transient open/probe failure replaying last-good inventory;
  • channel retirement and later reopen;
  • a disappeared OS node being forgotten independently of a sleepy slot;
  • hotplug and HID lifecycle event coalescing;
  • probe-cache warm start and volatile battery refresh.

These tests should assert inventory plus channel/open/cache effects. Inventory alone can be correct while a stale channel leak remains.

Stateful command scenarios

The semantic mock verifies:

  • setting read/write round trips;
  • nearest supported DPI selection;
  • unsupported-feature errors;
  • writes to unknown or offline routes;
  • console battery, link, fault, indicator, time, and disconnect transitions;
  • generation changes only when observable state changes;
  • pairing cancel/restart isolation;
  • frozen-time event progression.

The byte-layer suite separately verifies what reports production writes. The semantic mock does not claim its state transition proves physical firmware behavior.

Desktop and IPC

Derive an agent observation from a profile and feed it through the desktop's normal state merge boundary. Test device identity, route-specific capabilities, panel availability, online/offline updates, and setting failures there.

Keep process/socket tests small: one current-version handshake and snapshot, one state-changing command/readback, and one observation generation update are enough to prove the mock server wiring. The IPC wire itself remains protected by its existing bincode goldens.

Hardware-in-loop

Provide an opt-in command that runs the same named capture/read plan against hardware and compares its semantic result to a fixture. It reports rather than gates normal CI. The report distinguishes:

  • not run on hardware;
  • node not enumerated;
  • open/permission/exclusive-access failure;
  • protocol mismatch;
  • semantic mismatch;
  • write not runtime-verified.

This is the only layer that can support claims about platform HID access and physical effects.

Incremental delivery

Each phase is independently useful and should land with its own tests.

Phase 1: replay foundation

  • Define schema v1 and corpus validator.
  • Generalize the existing scripted raw channel into strict cassette replay.
  • Add replay raw writer and mutable replay backend topology.
  • Check in one synthetic direct-device and one receiver-backed fixture built from existing responders.
  • Run production DPI/probe reads against them.

Success criterion: Linux CI exercises direct and receiver device code with no hardware, and an altered request fails with a useful unmatched-report message.

Phase 2: semantic profiles and IPC mock

  • Extract the hard-coded mock inventory into the profile/state model.
  • Keep it as the built-in default.
  • Add openlogi-agent-mock --fixture and frozen test time.
  • Add profile validation and setting round-trip tests.
  • Add the desktop state-injection seam needed to consume a profile-derived observation.

Success criterion: one profile drives both mock-agent behavior and desktop state tests without duplicating the inventory in Rust.

Phase 3: read-only recorder

  • Add observed-channel recording and raw-writer capture.
  • Add strict, unambiguous target selection.
  • Implement fixture record profile, fixture record case, and fixture verify.
  • Implement known identity sanitizers and refuse unclassified committable raw output.
  • Record and review the first real direct and receiver-backed devices.

Success criterion: a fresh clone can replay a fixture captured on another host, obtain the reviewed semantic output, and pass privacy validation.

Phase 4: lifecycle and fault scenarios

  • Add explicit event/barrier controls.
  • Cover channel failure/repair, sleeping slots, malformed reports, late responses, gesture restoration, and pairing cancellation.
  • Serialize a scenario format only if repeated authored scenarios demonstrate a stable vocabulary.

Success criterion: tests reproduce recovery sequences without real sleeps and assert channel/cache effects as well as final inventory.

Phase 5: full agent-core replay

  • Introduce the coherent hardware runtime dependency.
  • Route inventory, pool, pairing, standalone devices, lights, gate, and cache through it.
  • Add a small agent-core integration suite over ReplayBackend.

Success criterion: the real orchestration publishes and mutates a replayed device without any native backend call. This phase must not replace the faster IPC mock or device-level suites.

Phase 6: explicit write capture and hardware comparison

  • Add individually reviewed, restorable write plans.
  • Add opt-in hardware comparison reports.
  • Keep pairing/unpairing and any non-restorable operation manual unless a safe device-specific protocol is established.

Success criterion: every supported write case states whether it was byte-tested, semantic-readback-tested, and runtime-tested on physical hardware.

First vertical slice

The smallest implementation that validates the architecture is:

  1. schema and validator for one profile plus named cassettes;
  2. strict replay of a direct mouse channel and a Bolt receiver channel;
  3. production get_dpi_info and inventory probe assertions;
  4. the current mock mouse represented as a profile and loaded by openlogi-agent-mock;
  5. no recording, writes, pairing, serialized scenario language, or full-agent dependency injection yet.

This proves that one semantic profile can serve UI development while raw cassettes independently protect device parsing. Only then is native recording worth adding.

Rejected shortcuts

  • One linear transcript per device: breaks under concurrent receiver slots, retries, optional reads, and unsolicited reports.
  • IPC-only recording: useful for screenshots, but cannot catch parser, feature-index, routing, or write regressions.
  • Raw-only firmware emulator: a capture cannot infer state transitions, cancellation cleanup, or unobserved failures.
  • Persisting AgentSnapshot: couples fixtures to host status and the append-only wire instead of device facts.
  • Adding fixture control to Agent: permanently expands production IPC for developer-only behavior.
  • Global timing replay: reproduces the recorder's scheduler, not the device contract, and becomes flaky across hosts.
  • Arbitrary byte masks: lets meaningful request changes match stale fixtures.
  • Automatically blessing semantic output: records current bugs as expected behavior without independent review.
  • Refactoring the whole agent before the first fixture: delays the useful device-layer and IPC-mock tests and creates an unproven abstraction.