Compare commits

...

28 Commits

Author SHA1 Message Date
ruv d0b64bdeb6 chore(rvcsi): drop inline v2/crates/rvcsi-* — consume the vendor/rvcsi submodule / crates.io instead
rvCSI now lives in its own repo (github.com/ruvnet/rvcsi), vendored here as
`vendor/rvcsi` (PR #543) and published to crates.io as `rvcsi-* 0.3.x` /
to npm as `@ruv/rvcsi`. The inline copies in `v2/crates/rvcsi-*` (added in
#542) were a duplicate; this removes them and re-points the docs.

- `git rm -r v2/crates/rvcsi-{core,dsp,events,adapter-file,adapter-nexmon,ruvector,runtime,node,cli}`
- `v2/Cargo.toml`: remove the 9 from `members` (note: `vendor/rvcsi/Cargo.toml`
  is its own workspace — depend on the published crates or the submodule paths,
  not as v2 workspace members).
- `CLAUDE.md`: the 9 crate-table rows collapse to one `vendor/rvcsi` row.
- `README.md` docs table: rvCSI entry points at the standalone repo + notes the
  submodule / crates.io / npm / plugin.
- `CHANGELOG.md`: `[Unreleased]` entry.

The ADRs (ADR-095, ADR-096), PRD, and DDD model stay in `docs/` as the design
record of the incubation. `cargo build --workspace --no-default-features` and
`cargo test --workspace --no-default-features` stay green.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-12 23:00:23 -04:00
rUv a2686d47a2 Merge pull request #543 from ruvnet/chore/vendor-rvcsi-submodule
chore(vendor): add rvcsi as a vendor submodule
2026-05-12 22:56:08 -04:00
ruv f2525d7a0d chore(vendor): add rvcsi as a vendor submodule (github.com/ruvnet/rvcsi)
rvCSI — the edge RF sensing runtime incubated here as `v2/crates/rvcsi-*`
(ADR-095, ADR-096, PR #542) — now has a standalone home at
github.com/ruvnet/rvcsi (9 crates published to crates.io, @ruv/rvcsi on npm,
a Claude Code plugin). This vendors it under `vendor/rvcsi`, alongside
`vendor/ruvector` / `vendor/midstream` / `vendor/sublinear-time-solver`.

Follow-up: migrate the workspace to consume `vendor/rvcsi/crates/rvcsi-*`
and drop the inline `v2/crates/rvcsi-*` copies (kept for now so this change
is a pure addition).

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-12 22:52:12 -04:00
rUv 601b3406fd Merge pull request #542 from ruvnet/claude/design-rvcsi-platform-X7yJR
docs: rvCSI edge RF sensing platform — PRD, ADR-095, DDD domain model
2026-05-12 22:38:29 -04:00
ruv deb561bf9c fix(rvcsi): scale-relative baseline-drift thresholds + ESP32 end-to-end validation
BaselineDriftDetector compared `mean_amplitude` against its EWMA baseline
with *absolute* thresholds (anomaly 1.0, drift 0.15). Fine for the synthetic
unit tests (amplitudes ~1.0), but raw ESP32 CSI is int8 I/Q with amplitudes
up to ~128, so window-to-window RMS distance is routinely 5-50 >> 1.0 and
AnomalyDetected fired on ~96% of windows (319/331 on a real node-1 capture).

Drift is now `||current - baseline||2 / ||baseline||2` (a fraction, with an
eps floor that falls back to absolute for a degenerate near-zero baseline),
so one tuning is valid across raw-int8 ESP32, int16-scaled Nexmon, and
baseline-subtracted streams. AnomalyDetected drops to 40/331 on the same
data; the existing detector tests still pass (their explicit configs are
valid relative thresholds too); added baseline_drift_is_scale_invariant_
no_anomaly_storm. rvcsi-events 18 -> 19 tests; 162 rvcsi tests, 0 failures,
clippy-clean.

Surfaced by an end-to-end test against real ESP32 CSI on COM7: the device
(ESP32-S3, node 1, ADR-018 firmware, WiFi "ruv.net" ch5 RSSI -39, CSI cb
only because nothing listens at .156). rvcsi has no ESP32 adapter yet, so a
7,000-frame node-1 recording was transcoded to .rvcsi via the new
scripts/esp32_jsonl_to_rvcsi.py (stand-in for `record --source esp32-jsonl`)
and run through `rvcsi inspect`/`replay`/`calibrate`/`events` end-to-end.

ADR-095 D13 and ADR-096 sections 2.1/5 updated; CHANGELOG entry added;
rvcsi-adapter-esp32 (live serial/UDP source) noted as a follow-up.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-12 22:19:15 -04:00
Claude d40411e6d7 feat(rvcsi): Raspberry Pi 5 (BCM43455c0) + Nexmon chip registry
Adds first-class support for the Raspberry Pi 5's WiFi chip (CYW43455 /
BCM43455c0 — the same 802.11ac wireless as the Pi 4 / Pi 3B+ / Pi 400, and the
chip with the most mature nexmon_csi support), plus a registry of the other
Nexmon-supported Broadcom/Cypress chips.

rvcsi-adapter-nexmon — new `chips.rs`:
- `NexmonChip` (Bcm43455c0, Bcm43436b0, Bcm4366c0, Bcm4375b1, Bcm4358, Bcm4339,
  Unknown{chip_ver}) + `RaspberryPiModel` (Pi5/Pi4/Pi400/Pi3BPlus/PiZero2W/
  PiZeroW) — Pi5/Pi4/Pi400/Pi3B+ → Bcm43455c0; PiZero2W → Bcm43436b0.
- `nexmon_adapter_profile(chip)` / `raspberry_pi_profile(model)` build the
  per-device `AdapterProfile` (channels: 2.4 GHz 1-13 + 5 GHz UNII for dual-band;
  bandwidths 20/40/80[/160]; expected subcarrier counts 64/128/256[/512]) that
  `validate_frame` bounds CSI frames against.
- `NexmonChip::from_chip_ver` (0x4345 → Bcm43455c0, 0x4339, 0x4358, 0x4366,
  0x4375 — best-effort; the raw `chip_ver` is always preserved) and `from_slug`
  / `RaspberryPiModel::from_slug` ("pi5", "raspberry pi 4", "bcm43455c0", ...).
- `NexmonCsiHeader::chip()`; `NexmonPcapAdapter` auto-detects the chip from the
  packets' `chip_ver` and uses the matching profile, overridable via
  `.with_chip(NexmonChip)` / `.with_pi_model(RaspberryPiModel)`; `.detected_chip()`.

rvcsi-runtime: `decode_nexmon_pcap_for(.., chip_spec)` (validate against a chip /
Pi model, drop non-conforming) + `nexmon_profile_for(spec)`; `NexmonPcapSummary`
gains `chip_names` + `detected_chip`; `CaptureSummary` gains `chip`.

rvcsi-cli: `record --source nexmon-pcap --chip pi5`; new `nexmon-chips`
subcommand (lists chips + Pi models, human or `--json`); `inspect-nexmon` and
`inspect` now print the resolved chip.

rvcsi-node (napi-rs): `nexmonDecodePcap` gains an optional `chip` arg;
`nexmonChipName(chipVer)`, `nexmonProfile(spec)`, `nexmonChips()`. @ruv/rvcsi
SDK + `.d.ts` updated (AdapterProfile / NexmonChipsListing interfaces, the new
fns, `chip` on CaptureSummary, `chip_names`/`detected_chip` on NexmonPcapSummary).

168 rvcsi tests pass (adapter-nexmon 22→28, cli 9→10), 0 failures, clippy-clean.
The synthetic test captures now stamp chip_ver = 0x4345 (the BCM4345 family chip
ID), so the chip-detection happy path is exercised end to end.
ADR-096, CHANGELOG, README, CLAUDE.md updated.

https://claude.ai/code/session_01CdYAPvRTjcch6YrYf42n1z
2026-05-13 01:32:27 +00:00
Claude b116a99481 feat(rvcsi): real nexmon_csi UDP/PCAP fidelity — chanspec decode, libpcap reader, NexmonPcapAdapter
Raises the Nexmon path from a normalized record format to parsing what the
patched Broadcom firmware actually emits, end to end.

napi-c shim (ABI 1.0 -> 1.1, additive):
- rvcsi_nx_csi_udp_header / rvcsi_nx_csi_udp_decode — parse the real nexmon_csi
  UDP payload: the 18-byte header (magic 0x1111, rssi int8, fctl, src_mac[6],
  seq_cnt, core/spatial-stream, Broadcom chanspec, chip_ver) + nsub complex CSI
  samples (modern int16 LE I/Q export — what CSIKit/csireader.py read for the
  BCM43455c0 / 4358 / 4366c0; nsub = (len-18)/4). rvcsi_nx_csi_udp_write to
  synthesize payloads for tests. rvcsi_nx_decode_chanspec — d11ac chanspec ->
  channel (chanspec & 0xff) / bandwidth (bits [13:11], cross-checked against the
  FFT size) / band (bits [15:14], cross-checked against the channel number).
  Still allocation-free, bounds-checked, structured errors, never panics.
- ffi.rs wraps it: decode_chanspec / parse_nexmon_udp_header / decode_nexmon_udp
  / encode_nexmon_udp + DecodedChanspec / NexmonCsiHeader; every unsafe block
  documented; the ABI guard now expects 1.1.

rvcsi-adapter-nexmon:
- pcap.rs — a dependency-free classic-libpcap reader (all four byte-order /
  timestamp-resolution magics; Ethernet / raw-IPv4 / Linux-SLL link types;
  tolerates a truncated final record; pcapng is a follow-up) + extract_udp_payload
  + a synthetic_udp_pcap / synthetic_nexmon_pcap test/example generator.
- NexmonPcapAdapter (a CsiSource) — reads the CSI UDP packets out of a
  `tcpdump -i wlan0 dst port 5500 -w csi.pcap` capture, decodes each via the C
  shim, stamps the frame timestamp from the pcap packet time; non-CSI packets
  counted as "skipped" in health.

rvcsi-runtime: decode_nexmon_pcap, summarize_nexmon_pcap (+ NexmonPcapSummary:
link type, CSI frame count, channels, bandwidths, subcarrier counts, chip
versions, RSSI range, time span), CaptureRuntime::open_nexmon_pcap[_bytes].

rvcsi-node (napi-rs): nexmonDecodePcap, inspectNexmonPcap, decodeChanspec,
RvcsiRuntime.openNexmonPcap. @ruv/rvcsi SDK + .d.ts updated (NexmonPcapSummary,
DecodedChanspec). rvcsi-cli: `record --source nexmon-pcap`, `inspect-nexmon`,
`decode-chanspec`.

161 rvcsi tests pass (adapter-nexmon 9->22), 0 failures, clippy-clean.
ADR-096 §2.2/§2.3/§5, CHANGELOG, CLAUDE.md updated.

https://claude.ai/code/session_01CdYAPvRTjcch6YrYf42n1z
2026-05-13 01:15:22 +00:00
Claude 684a064816 docs(rvcsi): update CHANGELOG, CLAUDE.md crate table, README docs index
- CHANGELOG: expand the rvCSI entry to cover all 9 crates (incl. rvcsi-runtime
  and the @ruv/rvcsi npm SDK), the napi-c / napi-rs seams, and the 142-test /
  clippy-clean status; note the daemon + MCP server are follow-ups.
- CLAUDE.md: add the 9 `rvcsi-*` crates to the Key Rust Crates table.
- README: add an rvCSI row to the docs index; bump the ADR count (79→96) and
  DDD-model count (7→8).

https://claude.ai/code/session_01CdYAPvRTjcch6YrYf42n1z
2026-05-13 00:18:56 +00:00
Claude 7393cc2b73 feat(rvcsi): rvcsi-runtime composition + rvcsi-node (napi-rs) + rvcsi-cli + @ruv/rvcsi TS SDK
- rvcsi-runtime — the composition layer (no FFI): CaptureRuntime (CsiSource +
  validate_frame + SignalPipeline + EventPipeline, with next_validated_frame /
  next_clean_frame / drain_events / health) plus one-shot helpers
  (summarize_capture → CaptureSummary, decode_nexmon_records, events_from_capture,
  export_capture_to_rf_memory, rf_memory_self_check). 10 tests.
- rvcsi-node — the napi-rs seam (cdylib+rlib, build.rs runs napi_build::setup):
  thin #[napi] wrappers over rvcsi-runtime — rvcsiVersion / nexmonShimAbiVersion /
  nexmonDecodeRecords / inspectCaptureFile / eventsFromCaptureFile /
  exportCaptureToRfMemory + an RvcsiRuntime streaming class. Everything that
  crosses the boundary is a validated/normalized rvCSI struct serialized to JSON
  (D6). deny(clippy::all).
- @ruv/rvcsi npm package (package.json + index.js + index.d.ts + README +
  __test__/api.test.cjs) — curated JS surface that JSON-parses the addon's
  output into plain CsiFrame/CsiWindow/CsiEvent/SourceHealth/CaptureSummary
  objects; lazy native-addon load with a helpful "not built" error.
- rvcsi-cli — the `rvcsi` binary: record (Nexmon dump → .rvcsi, validating),
  inspect, replay, stream, events, health, calibrate (v0 baseline), export
  ruvector. 7 tests exercising every subcommand against in-memory captures.
- rvcsi-cli no longer depends on rvcsi-node (a binary can't link the napi addon);
  the shared logic moved to rvcsi-runtime. .gitignore: ignore the generated
  *.node / binding.js / binding.d.ts / npm/ under rvcsi-node.

All rvcsi crates: build together OK, clippy-clean, 140 unit/integration tests +
2 doctests, 0 failures (core 29, dsp 28, events 18, adapter-file 20+1,
adapter-nexmon 9, ruvector 20+1, runtime 10, cli 7).

https://claude.ai/code/session_01CdYAPvRTjcch6YrYf42n1z
2026-05-13 00:17:45 +00:00
Claude 6432dfbd2d feat(rvcsi): rvcsi-adapter-file (.rvcsi capture/replay) + rvcsi-ruvector (RF memory)
- rvcsi-adapter-file (ADR-095 FR1/FR10, D9): the `.rvcsi` JSONL capture format
  (CaptureHeader line + one CsiFrame per line), FileRecorder, FileReplayAdapter
  (a CsiSource — deterministic replay, preserves timestamps/ordering/validation
  verbatim, carries an unenforced replay_speed for the daemon/CLI), read_all().
  20 unit tests + 1 doctest.
- rvcsi-ruvector (ADR-095 FR8, D8) — standin for the production RuVector binding:
  deterministic embeddings (window_embedding = 32 resampled mean_amplitude bins +
  32 resampled phase_variance bins + [motion_energy, presence_score, quality_score,
  ln1p(frame_count)], L2-normalized, dim 68; event_embedding = 10-wide kind
  one-hot + confidence + ln1p(evidence count), dim 12), cosine_similarity, the
  RfMemoryStore trait + value objects (EmbeddingId/RecordKind/SimilarHit/
  DriftReport), and InMemoryRfMemory + JsonlRfMemory (file-backed append log,
  identical query semantics, latest-baseline-per-room-wins on reopen).
  20 unit tests + 1 doctest.

All rvcsi crates build and test together: core 29, dsp 28, events 18,
adapter-file 20(+1), adapter-nexmon 9, ruvector 20(+1) — 124 unit + 2 doc tests,
0 failures. forbid(unsafe_code) everywhere except rvcsi-adapter-nexmon (FFI).

https://claude.ai/code/session_01CdYAPvRTjcch6YrYf42n1z
2026-05-13 00:03:27 +00:00
Claude 46f701bca8 feat(rvcsi): rvcsi-events — window aggregation + event detectors (ADR-095 FR5)
- WindowBuffer: buffers exposable CsiFrames from one (session,source), emits a
  CsiWindow on a frame-count or duration threshold; computes per-subcarrier
  mean_amplitude / phase_variance and scalar motion_energy / presence_score /
  quality_score; skips mixed source/session and mismatched-subcarrier frames.
- EventDetector trait + 4 state machines: PresenceDetector (hysteresis on
  presence_score), MotionDetector (debounced rising/falling edges on
  motion_energy), QualityDetector (SignalQualityDropped + once-per-stretch
  CalibrationRequired), BaselineDriftDetector (EWMA baseline → BaselineChanged /
  AnomalyDetected). Each with new()/with_config() + a public config struct.
- EventPipeline: owns a WindowBuffer + Vec<Box<dyn EventDetector>> + IdGenerator;
  process_frame / flush / add_detector / recent_windows (32-window ring) /
  with_defaults.
- 18 tests (incl. a 150-frame quiet/active/quiet end-to-end run via a seeded LCG
  + a determinism check). clippy-clean, forbid(unsafe_code), no heavy deps.

https://claude.ai/code/session_01CdYAPvRTjcch6YrYf42n1z
2026-05-13 00:01:19 +00:00
Claude 94745242a8 feat(rvcsi): rvcsi-dsp (DSP stages + SignalPipeline) + ADR-096 (FFI/crate layout)
- rvcsi-dsp — reusable signal-processing stages (ADR-095 FR4): mean/variance/
  std_dev/median, remove_dc_offset, unwrap_phase, moving_average, ewma,
  hampel_filter(_count), short_window_variance, subtract_baseline + DspError;
  scalar features motion_energy(_series), presence_score (logistic, ≈0.5 at
  threshold), confidence_score, breathing_band_estimate (heuristic, FFT-free);
  SignalPipeline (hampel → smooth → DC-remove → baseline-subtract → unwrap,
  non-destructive of validation state) + learn_baseline. 28 tests, clippy-clean,
  forbid(unsafe_code), no heavy deps.
- docs/adr/ADR-096-rvcsi-ffi-crate-layout.md — the implementation ADR: 8-crate
  topology, the napi-c shim record format + contract, the napi-rs Node surface,
  build/test invariants, alternatives. Indexed in docs/adr/README.md.
- CHANGELOG: rvCSI entry updated to cover the implementation crates.

https://claude.ai/code/session_01CdYAPvRTjcch6YrYf42n1z
2026-05-13 00:00:40 +00:00
Claude 1e684cb208 feat(rvcsi): rvcsi-core + napi-c Nexmon shim + crate skeletons (ADR-095/096)
First implementation milestone for the rvCSI edge RF sensing runtime:

- rvcsi-core — the foundation: CsiFrame/CsiWindow/CsiEvent normalized schema,
  ValidationStatus, AdapterProfile, CsiSource plugin trait, id newtypes +
  IdGenerator, RvcsiError, and the validate_frame pipeline (length/finiteness/
  subcarrier/RSSI/monotonicity hard checks + multiplicative quality scoring →
  Accepted/Degraded/Recovered/Rejected). 29 unit tests, forbid(unsafe_code).
- rvcsi-adapter-nexmon — the napi-c boundary: native/rvcsi_nexmon_shim.{c,h}
  (the only C in the runtime, allocation-free, bounds-checked, parses/writes a
  byte-defined "rvCSI Nexmon record" — a normalized superset of the nexmon_csi
  UDP payload), compiled via build.rs + cc, wrapped by a documented ffi module
  and a NexmonAdapter implementing CsiSource. 9 tests round-tripping through C.
- Workspace registration in v2/Cargo.toml (8 new members + napi/cc workspace
  deps) and compiling skeletons for rvcsi-dsp, rvcsi-events, rvcsi-adapter-file,
  rvcsi-ruvector, rvcsi-node (napi-rs cdylib + build.rs napi_build::setup) and
  rvcsi-cli (`rvcsi` binary) — to be filled in by the implementation swarm.

cargo build -p rvcsi-core -p rvcsi-adapter-nexmon -p rvcsi-node -p rvcsi-cli: OK
cargo test  -p rvcsi-core -p rvcsi-adapter-nexmon: 38 passed, 0 failed

https://claude.ai/code/session_01CdYAPvRTjcch6YrYf42n1z
2026-05-12 23:49:58 +00:00
Claude d98b7e3f65 docs: rvCSI edge RF sensing platform — PRD, ADR-095, DDD domain model
Adds design documentation for rvCSI, a Rust-first / TypeScript-accessible /
hardware-abstracted edge RF sensing runtime that normalizes WiFi CSI from
Nexmon, ESP32, Intel, Atheros, file and replay sources into one validated
CsiFrame schema, runs reusable DSP, emits typed confidence-scored events,
and bridges to RuVector RF memory, an MCP tool server and a TS SDK.

- docs/prd/rvcsi-platform-prd.md — purpose, users, success criteria,
  FR1-FR10, NFRs (safety/perf/reliability/privacy/security/portability),
  system architecture, runtime components, reference layout, data model
- docs/adr/ADR-095-rvcsi-edge-rf-sensing-platform.md — the 15 architectural
  decisions (Rust core, C-at-the-boundary, TS SDK via napi-rs, normalized
  schema, validate-before-FFI, CSI-as-temporal-delta, RuVector as RF memory,
  replayability, detection != decision, local-first, read-first/write-gated
  MCP, mandatory quality scoring, versioned calibration, plugin adapters)
- docs/ddd/rvcsi-domain-model.md — 7 bounded contexts (Capture, Validation,
  Signal, Calibration, Event, Memory, Agent) with aggregates, invariants,
  context map, data model and domain services
- indexed in docs/adr/README.md and docs/ddd/README.md; CHANGELOG entry

Design-only; no code or crates added yet.

https://claude.ai/code/session_01CdYAPvRTjcch6YrYf42n1z
2026-05-12 23:15:10 +00:00
ruv 6f77b37f5e chore(release): wifi-densepose-train 0.3.0 -> 0.3.1
Publishing the additive changes from PRs #536/#537 to crates.io:
- `signal_features` module — wires `wifi-densepose-signal` into the pipeline
  (audit #1/#2)
- `TrainingConfig::for_subcarriers` / `ht40_192()` / `multiband_168()` presets
  + the real `MmFiDataset` loader integration test (audit #4/#6/#7)

No public API removals or changes — additive only, so 0.3.0 -> 0.3.1 is
semver-correct. No other workspace crate depends on `wifi-densepose-train`,
so this is a standalone bump.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-11 23:59:50 -04:00
rUv c604ca1150 feat(train): TrainingConfig subcarrier-layout presets + real MmFiDataset loader test (#537)
Closes the remaining doable items from the 2026-05-11 training-pipeline audit:

#6 (CSI format default = 56-sc / 1 NIC) + #7 (multi-band 168-sc mesh not in
config): new `TrainingConfig::for_subcarriers(native, target)` plus named
presets `mmfi()` (114→56), `ht40_192()` (≈192-sc ESP32 HT40 → 56) and
`multiband_168()` (168-sc ADR-078 multi-band mesh → 56). Non-MM-Fi CSI shapes
are now first-class instead of requiring manual `native_subcarriers` /
`num_subcarriers` overrides; the field docs list the supported source counts
and the multi-NIC mapping (a 2–3-node mesh currently rides on `n_rx` until a
dedicated node dimension lands). Model input width stays `num_subcarriers`; the
presets only vary the resampling input.

#4 (proof.rs uses synthetic data): reframed — a deterministic proof *must* use
a reproducible source, so `verify-training` correctly stays on
`SyntheticCsiDataset`. The real gap was that nothing exercised the on-disk
`MmFiDataset` path. New `tests/test_real_loader.rs` writes synthetic CSI to
`.npy` files in the `MmFiDataset::discover` layout, loads it back, and checks
the resulting `CsiSample` — covering the no-interp case, the
subcarrier-interpolation branch, and the empty-root case. Adds `ndarray` /
`ndarray-npy` as dev-deps for the fixture writing.

cargo check + cargo test -p wifi-densepose-train --no-default-features: clean,
all existing tests green, 3 new loader tests + the updated config doctest pass.
Purely additive — no model-shape change, no tch-module change.
2026-05-11 23:49:00 -04:00
rUv eaedfded6f fix(train): wire wifi-densepose-signal into the pipeline; correct MODEL_CARD env-sensor claim (#536)
Addresses three findings from the 2026-05-11 training-pipeline audit:

#1/#2 — `wifi-densepose-signal` was a phantom dependency of `wifi-densepose-train`
(listed in Cargo.toml, never imported), and vitals/CSI signal features were
absent from the pipeline. New module `wifi_densepose_train::signal_features`:
`extract_signal_features(&Array4<f32>, &Array4<f32>) -> Array1<f32>` (and the
convenience method `CsiSample::signal_features()`) runs a windowed observation's
centre frame through `wifi_densepose_signal::features::FeatureExtractor`,
producing a fixed-length (FEATURE_LEN=12) amplitude / phase-coherence / PSD
feature vector — the hook for a future vitals / multi-task supervision head
(breathing- and heart-rate-band power are read off the PSD summary). The vector
is produced on demand and is not yet fed back into the loss; wiring it as a
training target is the documented follow-up. `wifi-densepose-signal` is now an
actually-used dependency. 5 new tests (2 unit in signal_features.rs, 3
integration in tests/test_dataset.rs); existing wifi-densepose-train tests
unchanged and green.

#3 — `docs/huggingface/MODEL_CARD.md` presented PIR/BME280 environmental-sensor
weak-label fine-tuning as a current capability; there is no env-sensor
ingestion in the training pipeline. Marked that path as planned/not-implemented
in the training-steps list and the data-provenance section.

(#5 — README's "92.9% PCK@20" overclaim — fixed separately in PR #535.)

CHANGELOG updated.
2026-05-11 23:40:55 -04:00
rUv bd4f81749a fix(docs): correct unsubstantiated 92.9% PCK@20 camera-supervised claim (#535)
The README claimed "92.9% PCK@20" for camera-supervised pose training. That
figure appears nowhere in ADR-079 (the source ADR) and is ~2.6x the ADR's own
success target (">35% PCK@20"). ADR-079 phases P7 (data collection), P8
(training + evaluation on real paired data) and P9 (cross-room LoRA) are all
still `Pending`, so no measured camera-supervised PCK@20 has been published.

- README: replace the two "92.9% PCK@20" claims with the proxy-supervised
  baseline (~2.5%) and the ADR-079 target (35%+), noting the eval phases are
  pending.
- CHANGELOG: add an Unreleased entry.

Surfaced by the PowerPlatePulse training-pipeline audit (2026-05-11). Six other
audit findings (vitals features absent from training; wifi-densepose-signal
ghost dep; PIR/BME280 in MODEL_CARD unimplemented; proof.rs uses
SyntheticCsiDataset only; 56-subcarrier/1-NIC default; multi-band 168-subcarrier
mesh not in training config) are listed in the PR body for follow-up.
2026-05-11 23:40:52 -04:00
ruv df9d3b0eea fix(plugins): move marketplace manifest to repo root for /plugin marketplace add ruvnet/RuView
Claude Code looks for `.claude-plugin/marketplace.json` at the cloned repo's
ROOT — not in a subdirectory — so `/plugin marketplace add ruvnet/RuView`
(and `claude plugin marketplace add ruvnet/RuView`) was failing with
"Marketplace file not found".

- Move `plugins/.claude-plugin/marketplace.json` → `.claude-plugin/marketplace.json`
  (repo root); the `ruview` plugin's `source` is now `./plugins/ruview`.
- README.md / plugins/ruview/README.md: install instructions now use
  `/plugin marketplace add ruvnet/RuView` + `/plugin install ruview@ruview`
  (with `claude --plugin-dir ./plugins/ruview` as the no-install fallback);
  manifest path references updated.
- plugins/ruview/scripts/smoke.sh: resolve the manifest at the repo root;
  also assert the plugin `source` is `./plugins/ruview`.
- ADR-0001 updated (scope, directory contract, smoke contract, consequences).

Verified: `claude plugin validate .` + `./plugins/ruview` pass; smoke 13/13;
`claude plugin marketplace add ./` → `claude plugin install ruview@ruview` →
`claude plugin details ruview` works end-to-end (16 skill-entries + 3 agents).

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-11 19:52:04 -04:00
ruv 298543913e docs(readme): add Claude Code / Codex plugin + marketplace install instructions
New "🧩 Claude Code & Codex Plugin" section in README.md covering
`claude --plugin-dir`, `claude plugin marketplace add` / `install`, the seven
/ruview-* commands, the Codex prompt mirror, and the smoke check; plus a
Documentation-table row linking to plugins/ruview/README.md.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-11 19:02:05 -04:00
ruv 8ff7c2c35a feat(plugins): RuView Claude Code + Codex marketplace plugin
Add `plugins/ruview` — an end-to-end toolkit for working with RuView
(WiFi-DensePose) from Claude Code, mirrored as Codex prompts.

Marketplace: `plugins/.claude-plugin/marketplace.json` (one plugin, `ruview`).

Skills (9): ruview-quickstart, ruview-hardware-setup, ruview-configure,
ruview-applications, ruview-model-training, ruview-advanced-sensing,
ruview-cli-api, ruview-mmwave, ruview-verify — shell-first (cargo / python /
idf.py / docker / node), no claude-flow MCP dependency.

Commands (7): /ruview-start, /ruview-flash, /ruview-provision, /ruview-app,
/ruview-train, /ruview-advanced, /ruview-verify.

Agents (3): ruview-onboarding-guide, ruview-config-engineer,
ruview-training-engineer.

Codex mirror: codex/AGENTS.md + codex/README.md + codex/prompts/*.md (full
command parity, enforced by scripts/smoke.sh).

Docs: docs/adrs/0001-ruview-plugin-contract.md (Proposed). Verification:
scripts/smoke.sh (13 structural checks). Provisioning docs reflect the full
`provision.py` flag set (TDM mesh, edge tiers, vitals, hop channels, Cognitum
Seed, swarm intervals) and the issue #391 NVS-namespace-replace gotcha.

Verified: `claude plugin validate` (plugin + marketplace), loads via
`claude --plugin-dir`, smoke 13/13, and confirmed against an attached ESP32-S3
on COM8 running the RuView CSI firmware (live adaptive_ctrl + csi_collector
serial output).

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-11 17:39:16 -04:00
rUv 19ee207d51 Merge pull request #528 from ruvnet/fix/update-submodules-workflow
ci: fix "Update vendor submodules" workflow (git identity + drop --merge)
2026-05-11 12:34:20 -04:00
ruv 8aa7fb9e9f ci: fix "Update vendor submodules" workflow (identity + drop --merge)
The scheduled job has been failing on every run with:

    fatal: empty ident name (...) not allowed
    fatal: Unable to merge '...' in submodule path 'vendor/ruvector'

Two bugs:
1. `git config user.name/email` was only set inside the "Create PR" step,
   but `git submodule update --remote --merge` runs first and the merge
   inside vendor/ruvector needs a committer when the pinned commit isn't a
   fast-forward of upstream `main` → "Committer identity unknown".
2. `--merge` is the wrong operation here. We only want to bump the
   superproject's gitlink to the latest upstream commit on each submodule's
   tracked branch — there's no reason to create merge commits inside the
   vendored repos, and `--merge` breaks whenever the current pin has diverged.

Fix:
- Add a "Configure git identity" step before any commit-creating operation.
- Replace `git submodule update --remote --merge` with
  `git submodule sync --recursive && git submodule update --remote --recursive`
  (detached checkout at each `.gitmodules` branch tip).
- Log the pointer diff in the "Check for changes" step for reviewability.
- Tidy the PR-creation step (identity now set globally; clearer commit/PR text).

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-11 12:33:40 -04:00
rUv f2e3a6a392 Merge pull request #526 from ruvnet/fix/esp32-issues-505-517-521
fix: ESP32 CSI 0pps (#521), aggregator sibling magics (#517), version.txt (#505) + fix-marker CI guard
2026-05-11 11:40:36 -04:00
ruv eda45a6857 ci: fix-marker regression guard (witness-style)
Adds a fast per-PR gate that asserts previously-shipped fixes are still
present in the tree — the CI analogue of the ruflo witness fix-marker
system, but self-contained (no plugin dependency, reviewable as plain
JSON). Complements the heavier checks (firmware build, deterministic
pipeline proof, release witness bundle) by catching the silent-revert
class of regression that build+test wouldn't.

  - scripts/fix-markers.json   manifest: 11 markers (RuView#396, #521,
    #517, #505, #354, #263, #266/#321, #265, #232/#375/#385/#386/#390,
    ADR-028 proof + witness bundle). Each has files / require (literal
    substring or /regex/) / optional forbid / rationale / ref.
  - scripts/check_fix_markers.py  stdlib-only checker. Exit 0 clean /
    1 regression / 2 bad manifest. Modes: --list, --json, --only ID.
  - .github/workflows/fix-regression-guard.yml  runs on PR + push to
    main/master; gates on the checker and writes the result table into
    the run summary + an artifact.

If a fix is intentionally removed, update scripts/fix-markers.json in the
same PR with a rationale — the diff becomes the audit trail.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-11 10:48:14 -04:00
ruv a1cb6bd8e5 fix(firmware): bump version.txt to 0.6.4 + CI guard for tag/version match (#505)
version.txt on main was still 0.6.2. CMake reads PROJECT_VER from it, so
esp_app_get_description()->version (and the boot log line) reported 0.6.2
for any source build — and v0.6.3-esp32 shipped a release binary that
internally identified as 0.6.2 because the bump never landed on main.

  - version.txt: 0.6.2 -> 0.6.4 (matches the latest release tag)
  - firmware-ci.yml: new `version-guard` job that runs on v*-esp32 tag
    pushes and fails the run if the tag's X.Y.Z != version.txt, so a
    future release can't ship a mislabeled binary.

Closes #505

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-11 10:48:14 -04:00
ruv 4d0521ca08 fix(hardware): aggregator tolerates sibling RuView UDP packet magics (#517)
The ESP32 firmware multiplexes several wire packet types onto the same
UDP port as ADR-018 raw CSI frames (magic 0xC5110001):

  0xC5110002  ADR-039 edge vitals (32 B)
  0xC5110003  ADR-069 feature vector
  0xC5110004  ADR-063 fused vitals
  0xC5110005  ADR-039 compressed CSI
  0xC5110006  ADR-081 feature state
  0xC5110007  ADR-095/#513 temporal classification

Esp32CsiParser only knew 0xC5110001, so the standalone `aggregator`
binary printed "parse error: Invalid magic: expected 0xc5110001, got
0xc5110002" for every vitals packet. No CSI data was lost — just noise.

Add the sibling-magic constants + ruview_sibling_packet_name(), classify
recognized siblings before the CSI-frame length gate, and return a new
ParseError::NonCsiPacket { magic, kind } instead of InvalidMagic. The
`aggregator` CLI now skips them quietly (logs "[skipped ADR-039 edge
vitals packet — not a CSI frame]" only with --verbose); the library-level
CsiAggregator already dropped them silently. New regression tests cover
all seven magics.

Closes #517

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-11 10:48:00 -04:00
ruv 3f55c95b34 fix(esp32): disable WiFi modem sleep so CSI capture isn't starved (#521)
csi_collector_init() never called esp_wifi_set_ps(), leaving the radio on
the ESP-IDF STA default WIFI_PS_MIN_MODEM. The modem then sleeps between
DTIM beacons; combined with the MGMT-only promiscuous filter (#396) the
CSI callback is starved and the per-second yield collapses toward 0 pps,
which is what users on a clean multi-node setup were seeing
(motion=0.00 presence=0.00 yield=0pps).

Force WIFI_PS_NONE before enabling promiscuous mode — the textbook
requirement for reliable CSI capture (every ESP-IDF CSI example does it).
New boot line: "csi_collector: WiFi modem sleep disabled (WIFI_PS_NONE)
for CSI capture". Battery duty-cycling is unaffected: power_mgmt_init()
runs after this and re-enables modem sleep when provision.py is given
--duty-cycle <100.

Builds clean for esp32s3 (idf.py build, 48% flash free).

Closes #521

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-11 10:47:48 -04:00
67 changed files with 4141 additions and 32 deletions
+15
View File
@@ -0,0 +1,15 @@
{
"name": "ruview",
"description": "RuView Marketplace: Claude Code + Codex plugins for WiFi sensing — configuration, applications, model training, and onboarding, from practical to advanced",
"owner": {
"name": "ruvnet",
"url": "https://github.com/ruvnet/RuView"
},
"plugins": [
{
"name": "ruview",
"source": "./plugins/ruview",
"description": "End-to-end RuView toolkit: getting started, ESP32 hardware setup, configuration, sensing applications (presence / vitals / pose / sleep / MAT), camera-free + camera-supervised model training, advanced multistatic sensing, CLI / API / WASM, mmWave radar, and witness verification"
}
]
}
+26
View File
@@ -2,6 +2,11 @@ name: Firmware CI
on:
push:
branches:
- '**'
tags:
# ESP32 firmware release tags — build + version-consistency guard (RuView#505).
- 'v*-esp32'
paths:
- 'firmware/**'
- '.github/workflows/firmware-ci.yml'
@@ -11,6 +16,27 @@ on:
- '.github/workflows/firmware-ci.yml'
jobs:
version-guard:
name: Verify version.txt matches release tag
runs-on: ubuntu-latest
if: github.ref_type == 'tag'
steps:
- uses: actions/checkout@v4
- name: Check firmware version.txt == tag
run: |
# Tag form: vX.Y.Z-esp32 → expect version.txt to contain X.Y.Z
TAG="${GITHUB_REF_NAME}"
EXPECTED="${TAG#v}"
EXPECTED="${EXPECTED%-esp32}"
ACTUAL="$(tr -d '[:space:]' < firmware/esp32-csi-node/version.txt)"
echo "Tag: $TAG → expected version.txt: $EXPECTED | actual: $ACTUAL"
if [ "$EXPECTED" != "$ACTUAL" ]; then
echo "::error::firmware/esp32-csi-node/version.txt is '$ACTUAL' but tag '$TAG' expects '$EXPECTED'."
echo "::error::Bump version.txt and re-tag so esp_app_get_description()->version is correct (RuView#505)."
exit 1
fi
echo "version.txt matches the release tag."
build:
name: Build ESP32-S3 Firmware (${{ matrix.variant }})
runs-on: ubuntu-latest
@@ -0,0 +1,54 @@
name: Fix-Marker Regression Guard
# Asserts that previously-shipped fixes are still present in the tree.
# Manifest: scripts/fix-markers.json Checker: scripts/check_fix_markers.py
# Run locally: python scripts/check_fix_markers.py (also --list / --json)
#
# This complements the heavyweight checks (firmware build, deterministic
# pipeline proof, witness bundle) with a fast per-PR "did someone revert a
# known fix?" gate — the CI analogue of the ruflo witness fix-marker system.
on:
push:
branches:
- main
- master
pull_request:
workflow_dispatch:
jobs:
fix-markers:
name: Verify fix markers
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.11'
- name: Validate the manifest is well-formed JSON
run: python -c "import json; json.load(open('scripts/fix-markers.json')); print('manifest OK')"
- name: Check fix markers
run: python scripts/check_fix_markers.py
- name: Emit machine-readable result (for the run summary)
if: always()
run: |
python scripts/check_fix_markers.py --json > fix-markers-result.json || true
{
echo '### Fix-marker regression guard'
echo ''
echo '```'
python scripts/check_fix_markers.py || true
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
- name: Upload result artifact
if: always()
uses: actions/upload-artifact@v4
with:
name: fix-markers-result
path: fix-markers-result.json
retention-days: 30
+23 -6
View File
@@ -19,8 +19,24 @@ jobs:
fetch-depth: 0
token: ${{ secrets.GITHUB_TOKEN }}
- name: Update submodules to latest main
run: git submodule update --remote --merge
# Identity must be set BEFORE any operation that can create a commit.
# `git submodule update --remote --merge` used to fail here with
# "Committer identity unknown" because the merge inside vendor/ruvector
# needs an author when the pinned commit isn't a fast-forward of upstream.
- name: Configure git identity
run: |
git config --global user.name "github-actions[bot]"
git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com"
# Use a plain `--remote` checkout (detached HEAD at each submodule's
# configured `branch` tip from .gitmodules) rather than `--merge`. We only
# want to bump the superproject's gitlink to the latest upstream commit;
# there's no reason to create merge commits inside the vendored repos, and
# `--merge` breaks whenever the current pin has diverged from that branch.
- name: Update submodules to latest tracked branch
run: |
git submodule sync --recursive
git submodule update --remote --recursive
- name: Check for changes
id: check
@@ -29,21 +45,22 @@ jobs:
echo "changed=false" >> "$GITHUB_OUTPUT"
else
echo "changed=true" >> "$GITHUB_OUTPUT"
echo "--- submodule pointer changes ---"
git submodule status --recursive || true
git diff --submodule=log -- vendor/ || true
fi
- name: Create PR with updates
if: steps.check.outputs.changed == 'true'
run: |
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
BRANCH="chore/update-submodules-$(date +%Y%m%d-%H%M%S)"
git checkout -b "$BRANCH"
git add vendor/
git commit -m "chore: update vendor submodules to latest main"
git commit -m "chore: update vendor submodules to latest upstream"
git push origin "$BRANCH"
gh pr create \
--title "chore: update vendor submodules" \
--body "Automated submodule update to latest upstream main." \
--body "Automated submodule update to the latest upstream commit on each submodule's tracked branch (see \`.gitmodules\`). Review the pointer diff before merging." \
--base main \
--head "$BRANCH"
env:
+6
View File
@@ -252,3 +252,9 @@ firmware/esp32-csi-node/build_firmware.batdata/
models/
demo_pointcloud.ply
demo_splats.json
# rvCSI napi-rs addon — generated by `napi build` (do not commit)
v2/crates/rvcsi-node/*.node
v2/crates/rvcsi-node/binding.js
v2/crates/rvcsi-node/binding.d.ts
v2/crates/rvcsi-node/npm/
+4
View File
@@ -10,3 +10,7 @@
path = vendor/sublinear-time-solver
url = https://github.com/ruvnet/sublinear-time-solver
branch = main
[submodule "vendor/rvcsi"]
path = vendor/rvcsi
url = https://github.com/ruvnet/rvcsi
branch = main
+50
View File
@@ -7,6 +7,56 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Changed
- **rvCSI moved to its own repo and is now vendored as a submodule.** The 9 `rvcsi-*`
crates (`rvcsi-core`/`-dsp`/`-events`/`-adapter-file`/`-adapter-nexmon`/`-ruvector`/
`-runtime`/`-node`/`-cli` — added inline in #542) now live in
[`github.com/ruvnet/rvcsi`](https://github.com/ruvnet/rvcsi): published to crates.io
as `rvcsi-* 0.3.x`, to npm as `@ruv/rvcsi`, with a Claude Code plugin marketplace and
a RuView-style README. RuView vendors it under `vendor/rvcsi` (alongside
`vendor/ruvector` / `vendor/midstream` / `vendor/sublinear-time-solver`) and no longer
carries inline copies in `v2/crates/`; consumers depend on the published crates (or the
submodule's `crates/rvcsi-*` paths). `v2/Cargo.toml`, `CLAUDE.md`, and the README docs
table updated accordingly. The ADRs (ADR-095, ADR-096), PRD, and DDD model stay in
`docs/` here as the design record of the incubation.
### Fixed
- **README: corrected the camera-supervised pose-accuracy claim.** The README stated
"92.9% PCK@20" for camera-supervised training; that figure does not appear in
ADR-079 and is ~2.6× the ADR's own success target (>35% PCK@20). ADR-079 phases
P7 (data collection), P8 (training + evaluation on real paired data) and P9
(cross-room LoRA) are still `Pending`, so no measured camera-supervised PCK@20 has
been published. README now states the proxy-supervised baseline (≈2.5%) and the
ADR-079 target (35%+), and notes the eval phases are pending. Surfaced by the
PowerPlatePulse training-pipeline audit (2026-05-11); 6 remaining audit findings
tracked in the PR.
- **rvCSI `BaselineDriftDetector`: drift thresholds are now scale-relative, not absolute.**
The detector compared `mean_amplitude` against its EWMA baseline with absolute
thresholds (`anomaly_threshold = 1.0`, `drift_threshold = 0.15`) — fine for the
synthetic unit tests (amplitudes ≈ 1.0), but raw ESP32 CSI is `int8` I/Q with
amplitudes up to ~128, so the window-to-window RMS distance is routinely 550 ≫ 1.0
and `AnomalyDetected` fired on ~96 % of windows (319/331 on a real node-1 capture).
Drift is now `‖current baseline‖₂ / ‖baseline‖₂` (a fraction, with an `eps` floor
for a degenerate near-zero baseline), so one tuning works across raw-`int8` ESP32,
`int16`-scaled Nexmon, and baseline-subtracted streams alike — `AnomalyDetected`
drops to 40/331 on the same data, the existing detector tests still pass, and a
`baseline_drift_is_scale_invariant_no_anomaly_storm` regression test was added.
ADR-095 D13 / ADR-096 §2.1, §5 updated. Surfaced by an end-to-end test against
real ESP32 CSI (a 7,000-frame node-1 capture; transcoder at
`scripts/esp32_jsonl_to_rvcsi.py`).
### Added
- **rvCSI — edge RF sensing runtime (design + first implementation).** New subsystem **rvCSI**: a Rust-first / TypeScript-accessible / hardware-abstracted edge RF sensing runtime that normalizes WiFi CSI from Nexmon, ESP32, Intel, Atheros, file and replay sources into one validated `CsiFrame` schema, runs reusable DSP, emits typed confidence-scored events, and bridges to RuVector RF memory, an MCP tool server and a TS SDK.
- **Design docs:** `docs/prd/rvcsi-platform-prd.md` (purpose, users, success criteria, FR1FR10, NFRs, system architecture, data model); `docs/adr/ADR-095-rvcsi-edge-rf-sensing-platform.md` (the 15 architectural decisions: Rust core, C-at-the-boundary, TS SDK via napi-rs, normalized schema, validate-before-FFI, CSI-as-temporal-delta, RuVector as RF memory, replayability, detection≠decision, local-first, read-first/write-gated MCP, mandatory quality scoring, versioned calibration, plugin adapters); `docs/adr/ADR-096-rvcsi-ffi-crate-layout.md` (crate topology, the napi-c shim record format & contract, the napi-rs Node surface, build/test invariants); `docs/ddd/rvcsi-domain-model.md` (7 bounded contexts: Capture, Validation, Signal, Calibration, Event, Memory, Agent — with aggregates, invariants, context map and domain services). Indexed in `docs/adr/README.md` and `docs/ddd/README.md`.
- **Crates** (9 new `v2/crates/rvcsi-*` workspace members): `rvcsi-core` (normalized `CsiFrame`/`CsiWindow`/`CsiEvent` schema, `AdapterProfile`, `CsiSource` plugin trait, id newtypes + `IdGenerator`, `RvcsiError`, the `validate_frame` pipeline + quality scoring; `forbid(unsafe_code)`); `rvcsi-adapter-nexmon` — the **napi-c** seam: `native/rvcsi_nexmon_shim.{c,h}` (the only C in the runtime — allocation-free, bounds-checked, ABI `1.1`), compiled via `build.rs`+`cc`, handling **two byte formats** — the compact self-describing "rvCSI Nexmon record", and the **real nexmon_csi UDP payload** (the 18-byte `magic 0x1111 · rssi · fctl · src_mac · seq · core/stream · chanspec · chip_ver` header + `nsub` int16 I/Q samples, the modern BCM43455c0/4358/4366c0 export read by CSIKit/`csireader.py`), with a Broadcom d11ac **chanspec decoder** (channel/bandwidth/band) — plus a pure-Rust **libpcap reader** (classic `.pcap`, all byte-order/timestamp-resolution magics, Ethernet/raw-IPv4/Linux-SLL link types) and a **Nexmon-chip / Raspberry-Pi-model registry** (`NexmonChip` / `RaspberryPiModel` — including the **Raspberry Pi 5** (CYW43455/BCM43455c0, same wireless as the Pi 4 — 20/40/80 MHz, 2.4+5 GHz, 64/128/256 subcarriers), the Pi 3B+/4/400, and the Pi Zero 2 W (BCM43436b0); `nexmon_adapter_profile` / `raspberry_pi_profile` build the per-chip `AdapterProfile`; `chip_ver` words auto-resolve to a chip). Wrapped by a documented `ffi` module and two `CsiSource`s: `NexmonAdapter` (record buffers) and `NexmonPcapAdapter` (real nexmon_csi UDP inside a `tcpdump -i wlan0 dst port 5500 -w csi.pcap` capture — the pcap timestamp stamps each frame; the chip is auto-detected from `chip_ver`, overridable via `.with_pi_model(Pi5)` / `.with_chip(...)`). `rvcsi-dsp` (DC removal, phase unwrap, smoothing, Hampel/MAD filter, sliding variance, baseline subtraction, motion-energy/presence/confidence features, heuristic breathing-band estimate, non-destructive `SignalPipeline`); `rvcsi-events` (`WindowBuffer`, the `EventDetector` trait + presence/motion/quality/baseline-drift state machines, `EventPipeline`; the baseline-drift detector uses **scale-relative** thresholds — drift as a fraction of the baseline's RMS magnitude — so one tuning works across raw-`int8` ESP32, `int16`-scaled Nexmon, and baseline-subtracted streams alike); `rvcsi-adapter-file` (the `.rvcsi` JSONL capture format, `FileRecorder`, `FileReplayAdapter` deterministic replay); `rvcsi-ruvector` (deterministic window/event embeddings, `cosine_similarity`, the `RfMemoryStore` trait, `InMemoryRfMemory` + `JsonlRfMemory` — a standin until the production RuVector binding); `rvcsi-runtime` (the no-FFI composition layer: `CaptureRuntime` = `CsiSource` + `validate_frame` + `SignalPipeline` + `EventPipeline`, plus one-shot helpers `summarize_capture`/`decode_nexmon_records`/`decode_nexmon_pcap`/`summarize_nexmon_pcap`/`events_from_capture`/`export_capture_to_rf_memory`); `rvcsi-node` — the **napi-rs** seam (a `["cdylib","rlib"]` Node addon, `build.rs` runs `napi_build::setup()`; thin `#[napi]` wrappers over `rvcsi-runtime``nexmonDecodeRecords`/`nexmonDecodePcap` (with optional `chip`)/`inspectNexmonPcap`/`decodeChanspec`/`nexmonChipName`/`nexmonProfile`/`nexmonChips`/`inspectCaptureFile`/`eventsFromCaptureFile`/`exportCaptureToRfMemory` + an `RvcsiRuntime` streaming class; everything that crosses to JS is a validated/normalized struct serialized to JSON); `rvcsi-cli` (the `rvcsi` binary: `record` (Nexmon-dump *or* `--source nexmon-pcap [--chip pi5]``.rvcsi`), `inspect`, `inspect-nexmon`, `nexmon-chips`, `decode-chanspec`, `replay`, `stream`, `events`, `health`, `calibrate` v0-baseline, `export ruvector`). Plus the `@ruv/rvcsi` npm package (`package.json`/`index.js`/`index.d.ts`/`README`/`__test__`) alongside `rvcsi-node` — a curated JS surface that parses the addon's JSON into plain `CsiFrame`/`CsiWindow`/`CsiEvent`/`SourceHealth`/`CaptureSummary`/`NexmonPcapSummary`/`DecodedChanspec` objects, with a lazy native-addon load.
- **Tests:** 169 across the rvcsi crates (core 29, dsp 28, events 19 — incl. a baseline-drift scale-invariance regression, adapter-file 20 + 1 doctest, adapter-nexmon 28 — round-tripping through the C shim and synthetic libpcap files, incl. Pi 5 / chip-detection, ruvector 20 + 1 doctest, runtime 13, cli 10), 0 failures; all rvcsi crates build together and are clippy-clean (`rvcsi-node` under `deny(clippy::all)`); `forbid(unsafe_code)` everywhere except `rvcsi-adapter-nexmon` (FFI, every `unsafe` block documented). Also exercised end-to-end against a real 7,000-frame ESP32 node-1 capture (transcoded with `scripts/esp32_jsonl_to_rvcsi.py` — the stand-in for the not-yet-shipped `record --source esp32-jsonl`): `rvcsi inspect`/`replay`/`calibrate`/`events` all run on real hardware data. Not yet wired in: live radio capture, `rvcsi-adapter-esp32` (live serial/UDP ESP32 source), the WebSocket daemon (`rvcsi-daemon`), the MCP tool server (`rvcsi-mcp`), and the legacy nexmon *packed-float* CSI export — follow-ups on top of these crates.
- **`wifi-densepose-train`: `signal_features` module — wires `wifi-densepose-signal` into the training pipeline.** `wifi-densepose-signal` was previously a phantom dependency of `wifi-densepose-train` (listed in `Cargo.toml`, never imported). New `wifi_densepose_train::signal_features::extract_signal_features` (and `CsiSample::signal_features()`) run a windowed CSI observation's centre frame through `wifi_densepose_signal::features::FeatureExtractor`, producing a fixed-length (`FEATURE_LEN = 12`) amplitude/phase/PSD feature vector — the hook for a future vitals / multi-task supervision head (breathing- and heart-rate-band power are read off the PSD summary). The vector is produced on demand and not yet fed back into the loss. Surfaced by the 2026-05-11 training-pipeline audit (findings #1 "vitals features absent from training" and #2 "`wifi-densepose-signal` ghost dep").
- **`wifi-densepose-train`: `TrainingConfig` subcarrier-layout presets + a real-loader integration test.** New `TrainingConfig::for_subcarriers(native, target)` plus named presets `ht40_192()` (≈192-sc ESP32 HT40 → 56) and `multiband_168()` (168-sc ADR-078 multi-band mesh → 56), so non-MM-Fi CSI shapes are first-class instead of requiring manual `native_subcarriers`/`num_subcarriers` overrides; field docs now list the supported source counts and the multi-NIC mapping. New `tests/test_real_loader.rs` round-trips synthetic CSI through `.npy` files → `MmFiDataset::discover`/`get` (including the subcarrier-interpolation branch and the empty-root case) — exercising the on-disk loader path the deterministic `verify-training` proof intentionally bypasses. Addresses training-pipeline audit findings #6 (56-sc/1-NIC config default) and #7 (multi-band mesh not in config); the #4 concern ("proof uses synthetic data") is reframed — the proof *should* use a reproducible source, and this test covers the real loader it skips.
### Fixed
- **HuggingFace `MODEL_CARD.md`: marked the PIR/BME280 environmental-sensor ground-truth path as planned, not implemented** (training-pipeline audit finding #3) — the card presented PIR/BME280 weak-label fine-tuning as a current capability; there is no env-sensor ingestion in the training pipeline today.
- **README: corrected the camera-supervised pose-accuracy claim** (audit finding #5; see PR #535) — "92.9% PCK@20" → the ADR-079 target (35%+; proxy baseline 35.3%), noting P7/P8/P9 are pending.
### Added
- **`nvsim` crate — deterministic NV-diamond magnetometer pipeline simulator** (ADR-089) —
New standalone leaf crate at `v2/crates/nvsim` modeling a forward-only
+1
View File
@@ -23,6 +23,7 @@ Dual codebase: Python v1 (`v1/`) and Rust port (`v2/`).
| `wifi-densepose-wifiscan` | Multi-BSSID WiFi scanning (ADR-022) |
| `wifi-densepose-vitals` | ESP32 CSI-grade vital sign extraction (ADR-021) |
| `nvsim` | Deterministic NV-diamond magnetometer pipeline simulator (ADR-089) — standalone leaf, WASM-ready |
| `vendor/rvcsi` (submodule) | **rvCSI** — edge RF sensing runtime (ADR-095/096): 9 crates (`rvcsi-core`/`-dsp`/`-events`/`-adapter-file`/`-adapter-nexmon`/`-ruvector`/`-runtime`/`-node`/`-cli`). Lives in its own repo ([github.com/ruvnet/rvcsi](https://github.com/ruvnet/rvcsi)), vendored here under `vendor/rvcsi`, published to crates.io as `rvcsi-* 0.3.x` and to npm as `@ruv/rvcsi`. Not a `v2/` workspace member — depend on the published crates (or the submodule's `crates/rvcsi-*` paths). Normalized `CsiFrame`/`CsiWindow`/`CsiEvent` schema, validate-before-FFI, reusable DSP, typed confidence-scored events, the napi-c Nexmon shim (real nexmon_csi `.pcap` from a Raspberry Pi 5 / 4 / 3B+ — BCM43455c0), the napi-rs SDK, the `rvcsi` CLI, a Claude Code plugin. |
### RuvSense Modules (`signal/src/ruvsense/`)
| Module | Purpose |
+34 -4
View File
@@ -9,7 +9,7 @@
> **Beta Software** — Under active development. APIs and firmware may change. Known limitations:
> - ESP32-C3 and original ESP32 are not supported (single-core, insufficient for CSI DSP)
> - Single ESP32 deployments have limited spatial resolution — use 2+ nodes or add a [Cognitum Seed](https://cognitum.one) for best results
> - Camera-free pose accuracy is limited — use [camera ground-truth training](docs/adr/ADR-079-camera-ground-truth-training.md) for 92.9% PCK@20
> - Camera-free pose accuracy is limited (PCK@20 ≈ 2.5% with proxy labels) — [camera ground-truth training](docs/adr/ADR-079-camera-ground-truth-training.md) targets **35%+ PCK@20**; the pipeline is implemented, but the data-collection and evaluation phases (ADR-079 P7P9) are still pending, so no measured camera-supervised PCK@20 has been published yet
>
> Contributions and bug reports welcome at [Issues](https://github.com/ruvnet/RuView/issues).
@@ -56,7 +56,7 @@ RuView also supports pose estimation (17 COCO keypoints via the WiFlow architect
> | 🧱 **Through-wall** | Fresnel zone geometry + multipath modeling | Up to 5m depth |
> | 🧠 **Edge intelligence** | 8-dim feature vectors + RVF store on Cognitum Seed | $140 total BOM |
> | 🎯 **Camera-free training** | 10 sensor signals, no labels needed | 84s on M4 Pro |
> | 📷 **Camera-supervised training** | MediaPipe + ESP32 CSI → 92.9% PCK@20 | 19 min on laptop |
> | 📷 **Camera-supervised training** | MediaPipe + ESP32 CSI → **35%+ PCK@20 target** (ADR-079; eval phases pending) | ~19 min on laptop (pipeline) |
> | 📡 **Multi-frequency mesh** | Channel hopping across 6 bands, neighbor APs as illuminators | 3x sensing bandwidth |
> | 🌐 **3D point cloud** *(optional fusion)* | Camera depth (MiDaS) + WiFi CSI + mmWave radar → unified spatial model | 22 ms pipeline · 19K+ points/frame |
@@ -485,14 +485,44 @@ See [`docs/adr/ADR-024-contrastive-csi-embedding-model.md`](docs/adr/ADR-024-con
---
## 🧩 Claude Code & Codex Plugin
RuView ships a [Claude Code](https://docs.anthropic.com/en/docs/claude-code) plugin (and Codex prompt mirror) that wraps the whole workflow — onboarding, ESP32 setup, configuration, sensing apps, model training, advanced multistatic sensing, CLI/API/WASM, mmWave radar, and witness verification — as 9 skills, 7 `/ruview-*` commands, and 3 agents. It lives in [`plugins/ruview/`](plugins/ruview/README.md); the marketplace manifest is [`.claude-plugin/marketplace.json`](.claude-plugin/marketplace.json) at the repo root.
```bash
# In Claude Code — add this repo as a plugin marketplace, then install:
/plugin marketplace add ruvnet/RuView
/plugin install ruview@ruview
# Or try it for one session without installing (from a local clone of the repo):
claude --plugin-dir ./plugins/ruview
# Then, in Claude Code:
# /ruview-start → onboarding (Docker demo / repo build / live ESP32)
# /ruview-flash → build + flash ESP32 firmware
# /ruview-provision → provision WiFi creds, sink IP, channel/MAC, mesh slots
# /ruview-app → run a sensing application (presence / vitals / pose / sleep / MAT / point cloud)
# /ruview-train → train / evaluate / publish a model (incl. GPU on GCloud)
# /ruview-advanced → multistatic / tomography / cross-viewpoint / mesh-security
# /ruview-verify → tests + deterministic proof + witness bundle
```
**Codex (OpenAI CLI):** `cp plugins/ruview/codex/prompts/*.md ~/.codex/prompts/` — the seven `/ruview-*` commands are mirrored as Codex prompts; [`plugins/ruview/codex/AGENTS.md`](plugins/ruview/codex/AGENTS.md) carries the project rules. See [`plugins/ruview/codex/README.md`](plugins/ruview/codex/README.md).
Verify the plugin structure: `bash plugins/ruview/scripts/smoke.sh`. Full details: [`plugins/ruview/README.md`](plugins/ruview/README.md).
---
## 📖 Documentation
| Document | Description |
|----------|-------------|
| [User Guide](docs/user-guide.md) | Step-by-step guide: installation, first run, API usage, hardware setup, training |
| [Build Guide](docs/build-guide.md) | Building from source (Rust and Python) |
| [Architecture Decisions](docs/adr/README.md) | 79 ADRs — why each technical choice was made, organized by domain (hardware, signal processing, ML, platform, infrastructure) |
| [Domain Models](docs/ddd/README.md) | 7 DDD models (RuvSense, Signal Processing, Training Pipeline, Hardware Platform, Sensing Server, WiFi-Mat, CHCI) — bounded contexts, aggregates, domain events, and ubiquitous language |
| [Claude Code / Codex Plugin](plugins/ruview/README.md) | The `ruview` plugin + marketplace — skills, `/ruview-*` commands, agents, and the Codex prompt mirror |
| [Architecture Decisions](docs/adr/README.md) | 96 ADRs — why each technical choice was made, organized by domain (hardware, signal processing, ML, platform, infrastructure) |
| [Domain Models](docs/ddd/README.md) | 8 DDD models (RuvSense, Signal Processing, Training Pipeline, Hardware Platform, Sensing Server, WiFi-Mat, CHCI, rvCSI) — bounded contexts, aggregates, domain events, and ubiquitous language |
| [rvCSI — edge RF sensing runtime](https://github.com/ruvnet/rvcsi) | Rust-first / TypeScript-accessible / hardware-abstracted CSI runtime: multi-source ingestion (incl. real nexmon_csi `.pcap` from a **Raspberry Pi 5** / Pi 4 / Pi 3B+ — CYW43455 / BCM43455c0) → validation → DSP → typed events → RuVector RF memory ([ADR-095](docs/adr/ADR-095-rvcsi-edge-rf-sensing-platform.md), [ADR-096](docs/adr/ADR-096-rvcsi-ffi-crate-layout.md), [domain model](docs/ddd/rvcsi-domain-model.md)). Now its own repo — [`ruvnet/rvcsi`](https://github.com/ruvnet/rvcsi) — vendored here under `vendor/rvcsi`; 9 `rvcsi-*` crates on crates.io, `@ruv/rvcsi` on npm, plus a Claude Code plugin. |
| [Desktop App](v2/crates/wifi-densepose-desktop/README.md) | **WIP** — Tauri v2 desktop app for node management, OTA updates, WASM deployment, and mesh visualization |
| [Medical Examples](examples/medical/README.md) | Contactless blood pressure, heart rate, breathing rate via 60 GHz mmWave radar — $15 hardware, no wearable |
| [Extended Documentation](docs/readme-details.md) | Latest additions, key features, installation, quick start, signal processing, training, CLI, testing, deployment, and changelog |
@@ -0,0 +1,210 @@
# ADR-095: rvCSI — Edge RF Sensing Runtime Platform
| Field | Value |
|-------|-------|
| **Status** | Proposed |
| **Date** | 2026-05-12 |
| **Deciders** | ruv |
| **Codename** | **rvCSI** — RuVector Channel State Information runtime |
| **Relates to** | ADR-012 (ESP32 CSI mesh), ADR-013 (feature-level sensing on commodity gear), ADR-014 (SOTA signal processing), ADR-016 (RuVector integration), ADR-024 (AETHER contrastive embeddings), ADR-031 (RuView sensing-first RF mode), ADR-040 (WASM programmable sensing), ADR-049 (cross-platform WiFi interface detection) |
| **PRD** | [rvCSI Platform PRD](../prd/rvcsi-platform-prd.md) |
| **Domain model** | [rvCSI Domain Model](../ddd/rvcsi-domain-model.md) |
---
## 1. Context
WiFi Channel State Information (CSI) is a powerful camera-free sensing primitive — but in practice it is hard to operationalize. Most CSI pipelines today are Linux shell scripts, patched firmware, kernel modules, Python notebooks, PCAP dumps, and ad-hoc signal processing. Packet formats are inconsistent across chips; drivers are unstable; malformed packets are common; and device-specific assumptions leak everywhere. CSI works in the lab and falls over in the field.
RuView already contains substantial CSI infrastructure (`wifi-densepose-signal`, `wifi-densepose-ruvector`, the ESP32 mesh of ADR-012, the RuView multistatic work of ADR-031). What is missing is a **stable, hardware-abstracted runtime layer** that:
- ingests CSI from many sources behind one interface,
- validates every packet before it can touch application code,
- normalizes everything into one schema,
- runs reusable signal processing,
- emits typed, confidence-scored events,
- exposes a safe TypeScript SDK, a CLI, MCP tools, and a RuVector bridge,
- and runs unattended on Raspberry Pi-class hardware.
This ADR establishes that runtime — **rvCSI** — and the architectural decisions that constrain it. Detailed requirements are in the [PRD](../prd/rvcsi-platform-prd.md); the bounded contexts, aggregates, and ubiquitous language are in the [domain model](../ddd/rvcsi-domain-model.md).
### 1.1 What rvCSI is not (day one)
rvCSI is *not* a pure-Rust replacement for vendor firmware patches, *not* a universal driver for all WiFi chips, and *not* an identity/pose/medical/legal-grade claim. It is a **structural sensing** runtime: excellent at detecting change, presence, motion, drift, and learned patterns; deliberately silent on exact identity, exact pose, and certainty guarantees. The product surface stays inside that boundary (see Decision D7).
### 1.2 Existing assets rvCSI builds on
| Asset | Source | Reuse in rvCSI |
|-------|--------|----------------|
| SOTA DSP (Hampel, phase unwrap, Fresnel, BVP, spectrograms) | `wifi-densepose-signal` (ADR-014) | `rvcsi-dsp` wraps/extends rather than re-implements |
| RuVector integration (5 crates) | `wifi-densepose-ruvector` (ADR-016) | `rvcsi-ruvector` exporter rides on the existing integration |
| ESP32 CSI firmware + aggregator | `wifi-densepose-hardware` / firmware (ADR-012) | `rvcsi-adapter-esp32` consumes the existing serial/UDP stream |
| AETHER contrastive embeddings | ADR-024 | optional embedding backend for window/event vectors |
| Cross-platform interface detection | ADR-049 | adapter discovery / health checks |
---
## 2. Decision
**Adopt rvCSI as a layered edge RF sensing runtime** with the boundary discipline `C → Rust → TypeScript`, a single normalized `CsiFrame` schema, mandatory validation before any language boundary crossing, and RuVector as RF memory. The fifteen decisions below are the architectural contract.
### D1 — Rust is the core runtime
CSI parsing and DSP require memory safety, predictable latency, and high throughput; C/Python research stacks are fragile for unattended edge deployment. **rvCSI uses Rust** for parsing, validation, signal processing, event extraction, and daemon execution.
*Consequences:* safer packet handling; better long-running stability; stronger portability to edge devices; more complex build system than pure TypeScript.
### D2 — C only at the hardware-compatibility boundary
Nexmon and similar CSI sources often require C shims, legacy drivers, or firmware-patch hooks. **C is isolated to thin shims** for existing capture and firmware compatibility — never in the data path beyond decode.
*Consequences:* existing Nexmon capability reused; unsafe surface stays small; full firmware rewrite avoided; some device support stays dependent on upstream tools.
### D3 — TypeScript for SDK, CLI, and developer orchestration
Developers need an approachable SDK, agent integrations, dashboards, and scripts. **rvCSI exposes a first-class TypeScript SDK** (`@ruv/rvcsi`) and CLI; native performance stays in Rust.
*Consequences:* easy adoption by app/agent developers; native perf preserved; requires a native build + prebuild release pipeline.
### D4 — napi-rs for Node bindings
Native Node modules need a stable ABI and ergonomic Rust integration. **rvCSI uses napi-rs** for the `rvcsi-node` bindings.
*Consequences:* Rust exposes typed APIs to TypeScript; prebuilt binaries distributable; careful memory-ownership rules required.
### D5 — Normalize all sources into one `CsiFrame` / `CsiWindow` schema
Different CSI sources expose incompatible formats; application code must not know device-specific details. **Every source is normalized into `CsiFrame` and `CsiWindow`** (schema in the domain model).
*Consequences:* hardware-agnostic application code; easier RuVector integration; some source-specific metadata needs extension fields.
### D6 — Validate before crossing language boundaries
Malformed packets and unsafe pointers are the dominant stability risk. **All raw data is validated in Rust before it crosses into TypeScript or RuVector**; rejected frames are quarantined (when enabled); parser failures return structured errors; TypeScript never receives raw unchecked pointers.
*Consequences:* safer SDK; cleaner error model; small validation overhead.
### D7 — Treat CSI as a temporal delta, not absolute truth
CSI is noisy and environment-specific. **rvCSI frames CSI as a temporal delta stream against learned baselines**, not as exact vision.
*Consequences:* honest product claims; good fit for presence/motion/drift/anomaly; identity and exact pose excluded from core claims.
### D8 — RuVector is RF memory
CSI becomes far more valuable stored as temporal embeddings and room signatures. **rvCSI integrates with RuVector** for vector storage, similarity search, drift detection, and sensor-graph relationships.
*Consequences:* rvCSI joins the broader ruvnet cognitive stack; RF field history becomes queryable; requires embedding design and retention policy.
### D9 — Design for replayability
Signal algorithms need repeatable benchmarks and debugging. **rvCSI supports deterministic replay** of captured sessions (timestamps, ordering, validation decisions, event output, calibration version, runtime config all preserved).
*Consequences:* easier testing; better audit trail; enables benchmark datasets.
### D10 — Separate detection from decision
rvCSI detects RF events; agents/applications decide what to do. **rvCSI emits events with confidence and evidence and performs no high-consequence actions by default.**
*Consequences:* cleaner safety model; clean integration with Cognitum proof-gated execution; applications implement policy.
### D11 — Local-first operation
RF sensing is privacy-sensitive and often valuable offline. **rvCSI runs locally by default and requires no cloud service**; remote observability is opt-in.
*Consequences:* better privacy posture; usable in industrial/care/sovereign deployments; remote observability must be explicitly enabled.
### D12 — MCP tools are read-first, write-gated
Agents should observe RF state safely; device mutation and calibration change system behavior. **MCP tools default to read actions**; capture start/stop, calibration, and export are gated.
*Consequences:* safer agent integration; lower accidental device disruption; more explicit operational control.
### D13 — Quality scoring is mandatory
CSI quality varies widely by chip, antenna, environment, channel, and interference. **Every frame, window, and event carries quality or confidence scoring.**
*Consequences:* downstream systems can suppress weak evidence; easier debugging; requires calibration and thresholds. Where a detector compares against a learned baseline (e.g. baseline-drift / anomaly), thresholds are expressed **relative to the baseline's magnitude**, not as absolute amplitude units, so a single tuning is valid across sources whose raw CSI scales differ by orders of magnitude (raw `int8` ESP32 vs. `int16`-scaled Nexmon vs. baseline-subtracted streams).
### D14 — Versioned calibration profiles
Room baselines change over time. **Calibration profiles are versioned**, and event outputs reference the calibration version used.
*Consequences:* more auditable detection; replay can reproduce prior outputs; slight storage overhead.
### D15 — Hardware adapters are plugins
Device support will evolve and vary by platform. **Source adapters are plugins behind a common Rust trait** (`CsiSource`).
*Consequences:* easier support for Nexmon/ESP32/Intel/Atheros/SDR/future sources; cleaner testability; adapter certification becomes important.
---
## 3. Architecture
```
CSI Source
↓ ┌─ Capture context ──────────────┐
Adapter Layer (C shims here) │ Source · CaptureSession · │
↓ │ AdapterProfile │
Rust Validation Pipeline ─────┤ Validation context │
↓ │ ValidationPolicy · Quarantine │
Normalized CsiFrame ──────────┘ ← FFI-safe boundary object
↓ ┌─ Signal context ───────────────┐
Signal Processing │ SignalPipeline · WindowBuffer │
↓ ├─ Calibration context ──────────┤
Window Aggregator ───────────┤ CalibrationProfile · │
↓ │ RoomSignature · BaselineModel │
Event Extractor ─────────────┤ Event context │
↓ │ EventDetector · StateMachine │
TS SDK · CLI · MCP · RuVector └─ Memory + Agent contexts ──────┘
```
**Crates (within RuView's `v2/crates/`, or a standalone `rvcsi/crates/`):**
`rvcsi-core` · `rvcsi-adapter-file` · `rvcsi-adapter-nexmon` · `rvcsi-adapter-esp32` · `rvcsi-dsp` · `rvcsi-events` · `rvcsi-ruvector` · `rvcsi-daemon` · `rvcsi-node` · `rvcsi-mcp` — plus TypeScript packages `sdk`, `cli`, `dashboard`, and `native/nexmon-shim-c`.
See the [PRD §9](../prd/rvcsi-platform-prd.md#9-system-architecture) for the full component table and reference layout, and the [domain model](../ddd/rvcsi-domain-model.md) for bounded contexts, aggregates, invariants, and domain services.
---
## 4. Consequences
**Positive**
- CSI becomes reusable infrastructure: npm-installable, reproducible, typed, safe-parsed, embeddable, WebSocket-streamable, WASM-portable, MCP-exposed, agent-integrable.
- One application codebase works across Nexmon, ESP32, Intel, and Atheros sources.
- Bad packets cannot crash the daemon; unattended operation becomes realistic.
- RuView/RuVector/Cognitum/agents gain a validated live source of RF observations.
- Honest product framing ("structural sensing") avoids over-claiming.
**Negative / costs**
- Larger build surface: Rust core + napi-rs native module + C shims + TypeScript packages + prebuild pipeline.
- Adapter certification and a supported-hardware matrix become ongoing maintenance.
- Embedding design, calibration thresholds, and retention policy are non-trivial open questions (tracked in the PRD).
- Risk of duplicating `wifi-densepose-signal` / `wifi-densepose-ruvector`; mitigated by wrapping, not re-implementing.
**Risks**
- Nexmon coupling: some device support remains dependent on upstream firmware/driver projects.
- CSI quality variance: weak-signal environments may yield low-confidence events; mitigated by mandatory quality scoring (D13) and versioned calibration (D14).
---
## 5. Alternatives considered
| Alternative | Why not |
|-------------|---------|
| Pure-Python runtime (extend the v1 stack) | Fragile under malformed packets; GC pauses break the < 50 ms latency target; poor unattended stability. |
| Pure-Rust including firmware (replace Nexmon) | Enormous scope; vendor-specific; would block v0 indefinitely. D2 keeps C at the boundary instead. |
| Per-source SDKs (no normalized schema) | Pushes device specifics into application code; defeats the "same app code across adapters" success criterion. |
| WASM-only core | No raw socket / serial / monitor-mode access for live capture; fine for offline parsing (a later target) but not v0 live capture. |
| Cloud-first ingestion | Violates the privacy posture and the local-first requirement; unacceptable for care/industrial/sovereign deployments. |
---
## 6. Implementation phases (proposed)
1. **v0**`rvcsi-core` + file/replay/ESP32 adapters + validation + `rvcsi-dsp` (presence/motion) + `rvcsi-node` SDK + `rvcsi-cli` + WebSocket output + `rvcsi-ruvector` export + basic calibration + health checks. Targets all eight PRD success criteria.
2. **v1** — multi-node sync, RF room signatures, breathing-rate where signal permits, temporal embeddings, drift detection, room-topology graph, `rvcsi-mcp` tool server, replayable benchmark datasets, RuView sensor fusion, Cognitum deployment profile.
3. **v2** — hardware-agnostic RF sensor fabric, multi-room RF memory, streaming anomaly detection, RF-SLAM research mode, on-device embedding model, federated room-signature learning, signed sensor-evidence records, proof-gated event publication, dynamic cut-based coherence over RF graphs, agent-driven calibration and self-repair.
---
## 7. References
- [rvCSI Platform PRD](../prd/rvcsi-platform-prd.md)
- [rvCSI Domain Model](../ddd/rvcsi-domain-model.md)
- ADR-012 — ESP32 CSI Sensor Mesh
- ADR-013 — Feature-Level Sensing on Commodity Gear
- ADR-014 — SOTA Signal Processing
- ADR-016 — RuVector Integration
- ADR-024 — Project AETHER: Contrastive CSI Embeddings
- ADR-031 — RuView Sensing-First RF Mode
- ADR-040 — WASM Programmable Sensing
- ADR-049 — Cross-Platform WiFi Interface Detection
+144
View File
@@ -0,0 +1,144 @@
# ADR-096: rvCSI — Crate Topology, the napi-c Shim, and the napi-rs Node Surface
| Field | Value |
|-------|-------|
| **Status** | Proposed |
| **Date** | 2026-05-12 |
| **Deciders** | ruv |
| **Codename** | **rvCSI** — RuVector Channel State Information runtime |
| **Relates to** | ADR-095 (rvCSI platform — D1 Rust core, D2 C-at-the-boundary, D3 TS SDK, D4 napi-rs, D5 normalized schema, D6 validate-before-FFI, D15 plugin adapters), ADR-009/ADR-040 (WASM runtimes), ADR-049 (cross-platform WiFi interface detection) |
| **PRD** | [rvCSI Platform PRD](../prd/rvcsi-platform-prd.md) |
| **Domain model** | [rvCSI Domain Model](../ddd/rvcsi-domain-model.md) |
| **Implements** | `v2/crates/rvcsi-core`, `rvcsi-dsp`, `rvcsi-events`, `rvcsi-adapter-file`, `rvcsi-adapter-nexmon`, `rvcsi-ruvector`, `rvcsi-node`, `rvcsi-cli` |
---
## 1. Context
ADR-095 set the platform-level invariant `C → Rust → TypeScript` and the fifteen decisions that constrain rvCSI. This ADR makes the *implementation* concrete: which crates exist, what each owns, where the two FFI seams are (the **napi-c** C shim below Rust, and the **napi-rs** Node addon above it), and the rules that keep `unsafe` confined and the boundary objects validated.
The two seams:
- **napi-c** — the *downward* seam to fragile vendor/firmware/driver code. Per ADR-095 D2, C is the only language allowed here, and only as a thin, allocation-free, bounds-checked shim. The Nexmon family is the first consumer.
- **napi-rs** — the *upward* seam to Node.js/TypeScript. Per ADR-095 D3/D4, the Rust runtime is exposed to JS via [napi-rs](https://napi.rs/); nothing crosses this seam that hasn't been validated (D6) and normalized (D5).
Both seams are *narrow on purpose*: everything in between — parsing, validation, DSP, windowing, event extraction, RuVector export — is safe Rust (`#![forbid(unsafe_code)]` in every crate except `rvcsi-adapter-nexmon`, which needs `extern "C"`).
---
## 2. Decision
### 2.1 Crate topology
Eight new workspace members under `v2/crates/`:
| Crate | `unsafe`? | Depends on | Owns |
|-------|-----------|------------|------|
| `rvcsi-core` | no (`forbid`) | — (serde, thiserror) | The normalized schema (`CsiFrame`/`CsiWindow`/`CsiEvent`), `AdapterProfile`, the `CsiSource` plugin trait, id newtypes + `IdGenerator`, `RvcsiError`, and the `validate_frame` pipeline + quality scoring. The shared kernel. |
| `rvcsi-dsp` | no (`forbid`) | `rvcsi-core` | Reusable DSP stages (DC removal, phase unwrap, smoothing, Hampel/MAD outlier filter, sliding variance, baseline subtraction) and scalar features (motion energy, presence score, confidence, heuristic breathing-band estimate), plus a non-destructive `SignalPipeline::process_frame`. |
| `rvcsi-events` | no (`forbid`) | `rvcsi-core` | `WindowBuffer` (frames → `CsiWindow`), the `EventDetector` trait + presence/motion/quality/baseline-drift state machines, and `EventPipeline` (windows → `CsiEvent`s). The baseline-drift detector measures drift **relative to the running baseline's RMS magnitude** (a fraction, not absolute amplitude units), so the same thresholds work for raw `int8` ESP32 CSI, `int16`-scaled Nexmon CSI, and baseline-subtracted streams alike — see ADR-095 D13. |
| `rvcsi-adapter-file` | no (`forbid`) | `rvcsi-core` | The `.rvcsi` capture format (JSONL: a header line + one `CsiFrame` per line), `FileRecorder`, and `FileReplayAdapter` (a `CsiSource`) — deterministic replay (D9). |
| `rvcsi-adapter-nexmon` | **yes** (FFI only) | `rvcsi-core` + the C shim | The **napi-c** seam: `native/rvcsi_nexmon_shim.{c,h}` compiled via `build.rs`+`cc`, a documented `ffi` module wrapping it, a pure-Rust libpcap reader (`pcap.rs`), the Nexmon-chip / Raspberry-Pi-model registry (`chips.rs``NexmonChip`, `RaspberryPiModel` incl. **Pi 5**, profile builders), and two `CsiSource`s — `NexmonAdapter` (rvCSI-record buffers) and `NexmonPcapAdapter` (real nexmon_csi UDP payloads inside a `.pcap`, with chip auto-detection). |
| `rvcsi-ruvector` | no (`forbid`) | `rvcsi-core` | The RuVector RF-memory bridge: deterministic `window_embedding`/`event_embedding`, `cosine_similarity`, the `RfMemoryStore` trait, and `InMemoryRfMemory` + `JsonlRfMemory` (a standin until the production RuVector binding lands). |
| `rvcsi-runtime` | no (`forbid`) | core, dsp, events, adapter-file, adapter-nexmon, ruvector | The composition layer (no FFI): `CaptureRuntime` (a `CsiSource` + `validate_frame` + `SignalPipeline` + `EventPipeline`) plus one-shot helpers (`summarize_capture`, `decode_nexmon_records`, `decode_nexmon_pcap`, `summarize_nexmon_pcap`, `events_from_capture`, `export_capture_to_rf_memory`). The shared layer under `rvcsi-node` and `rvcsi-cli`. |
| `rvcsi-node` | no (`deny(clippy::all)`) | `rvcsi-core`, `rvcsi-runtime`, `rvcsi-adapter-nexmon` | The **napi-rs** seam: the `.node` addon (cdylib + rlib) exposing a safe TS-facing surface (thin `#[napi]` wrappers over `rvcsi-runtime`); `build.rs` runs `napi_build::setup()`. |
| `rvcsi-cli` | no | core, adapter-file, adapter-nexmon, runtime | The `rvcsi` binary: `record` (Nexmon-dump or nexmon-pcap → `.rvcsi`), `inspect`, `inspect-nexmon`, `decode-chanspec`, `replay`, `stream`, `events`, `health`, `calibrate`, `export ruvector` (ADR-095 FR7). |
`rvcsi-events` does **not** call into `rvcsi-dsp`: window statistics are simple enough to compute in `WindowBuffer` itself, and keeping the two leaves independent removes a coordination point. `rvcsi-cli` does **not** depend on `rvcsi-node` (a binary can't link a napi cdylib's undefined Node symbols) — the shared logic lives in `rvcsi-runtime`, which both build on. Higher layers wire `SignalPipeline::process_frame``WindowBuffer::push` when they want cleaned frames.
The MCP tool server (`rvcsi-mcp`) and the long-running daemon (`rvcsi-daemon`) — and live radio capture — are *not* in this ADR's scope; they sit on top of `rvcsi-runtime` / the crates above and are tracked as follow-ups. The `@ruv/rvcsi` npm package ships alongside `rvcsi-node`.
### 2.2 The napi-c shim — record formats and contract
`native/rvcsi_nexmon_shim.{c,h}` is the only C in the runtime. It handles **two byte formats** (ABI `1.1`):
**(1) The "rvCSI Nexmon record"** — a compact, self-describing record (`'RVNX'` magic, version, flags, RSSI/noise, channel, bandwidth, timestamp, then interleaved `int16` I/Q in Q8.8 fixed point; total `24 + 4*N`). Used by the `rvcsi capture`/`record` recorder, the file replay path, and tests. Functions: `rvcsi_nx_record_len`, `rvcsi_nx_parse_record`, `rvcsi_nx_write_record`.
**(2) The *real* nexmon_csi UDP payload** — what the patched Broadcom firmware actually sends to the host (port 5500 by default): the 18-byte header `magic=0x1111 (2) · rssi int8 (1) · fctl (1) · src_mac (6) · seq_cnt (2) · core/stream (2) · chanspec (2) · chip_ver (2)`, followed by `nsub` complex CSI samples. The shim implements the **modern int16 I/Q export** (`nsub` pairs of little-endian `int16` `(real, imag)`, raw counts — what CSIKit / `csireader.py` read for the BCM43455c0 / 4358 / 4366c0); `nsub` is derived from the payload length, `(len 18) / 4`. Functions: `rvcsi_nx_csi_udp_header` (just the 18-byte header), `rvcsi_nx_csi_udp_decode` (header + CSI body, `csi_format` selector), `rvcsi_nx_csi_udp_write` (synthesize a payload — tests/examples), and `rvcsi_nx_decode_chanspec` (decode a Broadcom d11ac chanspec word → `channel` = `chanspec & 0xff`, bandwidth from bits `[13:11]` cross-checked against the FFT size, band from bits `[15:14]` cross-checked against the channel number). The legacy nexmon *packed-float* export used by some 4339/4358 firmwares is a documented follow-up (it sits behind the same `csi_format` selector).
The `timestamp_ns` of a frame from format (2) comes from the **pcap packet timestamp**, not the wire (nexmon_csi doesn't carry one). The pcap file itself is parsed in **pure Rust** (`rvcsi-adapter-nexmon::pcap` — classic libpcap, all four byte-order/timestamp-resolution magics, Ethernet / raw-IPv4 / Linux-SLL link types; pcapng is a follow-up): peeling the Ethernet/IPv4/UDP headers down to the payload is not a vendor-fragility concern, so it doesn't belong in C.
Contract (both formats):
- **Allocation-free, global-free.** Every read is bounds-checked against the caller-supplied length; nothing can scribble outside caller buffers; no `malloc`, no statics.
- **Structured errors, never panics.** Functions return one of a small set of `RvcsiNxError` codes (`TOO_SHORT`, `BAD_MAGIC`, `BAD_VERSION`, `CAPACITY`, `TRUNCATED`, `ZERO_SUBCARRIERS`, `TOO_MANY_SUBCARRIERS`, `NULL_ARG`, `BAD_NEXMON_MAGIC`, `BAD_CSI_LEN`, `UNKNOWN_FORMAT`); `rvcsi_nx_strerror` maps each to a static string.
- **ABI versioned.** `rvcsi_nx_abi_version()` returns `major << 16 | minor` (`0x0001_0001`); the Rust side `debug_assert`s the major matches the header it was compiled against. The minor was bumped from `1.0``1.1` when the format-(2) entry points landed (additive — format (1) is unchanged).
- The Rust `ffi` module wraps these in safe functions (`record_len`, `decode_record`, `encode_record`, `decode_chanspec`, `parse_nexmon_udp_header`, `decode_nexmon_udp`, `encode_nexmon_udp`, `shim_abi_version`); every `unsafe` block is limited to the FFI call (and reading back C-initialised structs) and carries a `// SAFETY:` comment, per the project rule.
**Chip registry (`rvcsi-adapter-nexmon::chips`).** nexmon_csi runs on a handful of patched Broadcom/Cypress chips; `NexmonChip` names them, `RaspberryPiModel` maps Pi boards to their chip, and `nexmon_adapter_profile` / `raspberry_pi_profile` build the [`AdapterProfile`] (supported channels / bandwidths / expected subcarrier counts — 20→64, 40→128, 80→256, 160→512) `validate_frame` bounds CSI frames against. The **Raspberry Pi 5** carries the same **CYW43455 / BCM43455c0** 802.11ac wireless as the Pi 3B+ / Pi 4 / Pi 400 (20/40/80 MHz, 2.4 + 5 GHz) — the chip with the most mature nexmon_csi support — so `RaspberryPiModel::Pi5 → NexmonChip::Bcm43455c0`; the Pi Zero 2 W is `Bcm43436b0` (2.4 GHz, ≤40 MHz). `NexmonPcapAdapter` **auto-detects** the chip from each packet's `chip_ver` word (`0x4345``Bcm43455c0`, etc.) and uses the matching profile; `.with_chip(...)` / `.with_pi_model(...)` override it. `NexmonChip::from_chip_ver` and the `chip_ver` field are best-effort/preserved respectively — the c0/b0 revision suffix isn't carried by that word, and the int16-vs-packed-float export distinction is handled by the `csi_format` selector, not by chip-ver parsing.
A real deployment captures with `tcpdump -i wlan0 dst port 5500 -w csi.pcap` on the Pi and feeds the `.pcap` to `NexmonPcapAdapter::open` (or `rvcsi record --source nexmon-pcap --in csi.pcap --out cap.rvcsi --chip pi5`, then the rest of the toolchain works on the `.rvcsi`; `rvcsi inspect-nexmon` reports the resolved chip, `rvcsi nexmon-chips` lists the matrix). Production *live* capture (binding the UDP socket, monitor mode, firmware patch hooks) is a later increment that reuses the same shim parse path — the shim's job is the *parse*, not the *socket*.
### 2.3 The napi-rs surface — what crosses the seam
`rvcsi-node` is a `["cdylib", "rlib"]` crate (cdylib = the `.node` addon; rlib so `cargo test --workspace` can link and test the Rust side without Node). Rules:
- **Only normalized/validated data crosses.** The boundary types are JS-friendly mirrors of `CsiFrame`/`CsiWindow`/`CsiEvent`/`AdapterProfile`/`SourceHealth`, or plain JSON strings — never raw pointers, never `Pending` frames. A frame is run through `rvcsi_core::validate_frame` before it is handed to JS.
- **Errors map to JS exceptions** via napi-rs's `Result` integration; `RvcsiError`'s `Display` is the message.
- **The build emits link args + `binding.js`/`binding.d.ts`** via `napi_build::setup()` in `build.rs`; the `@ruv/rvcsi` npm package's hand-written `index.js`/`index.d.ts` wrap that loader and `JSON.parse` the addon's returns into plain `CsiFrame`/`CsiWindow`/`CsiEvent`/`SourceHealth`/`CaptureSummary`/`NexmonPcapSummary`/`DecodedChanspec` objects.
- The free functions exposed are: `rvcsiVersion`, `nexmonShimAbiVersion` (the linked shim's ABI), `nexmonDecodeRecords`, `nexmonDecodePcap`, `inspectNexmonPcap`, `decodeChanspec`, `inspectCaptureFile`, `eventsFromCaptureFile`, `exportCaptureToRfMemory`; plus the `RvcsiRuntime` streaming class (`openCaptureFile` / `openNexmonFile` / `openNexmonPcap` factories + `nextFrameJson` / `nextCleanFrameJson` / `drainEventsJson` / `healthJson`).
### 2.4 Build & test invariants
- `cargo build --workspace` and `cargo test --workspace --no-default-features` (the repo's pre-merge gate) must stay green; the new crates add tests and don't regress the existing 1,031+.
- `rvcsi-node` stays a workspace *member* (not `exclude`d like `wifi-densepose-wasm-edge`): on Linux/macOS a napi cdylib links fine with Node symbols left undefined (resolved at addon-load time), so `cargo build`/`cargo test` work without a Node toolchain. Only `napi build` (npm packaging) needs Node.
- No new heavy dependencies in the rvCSI crates: `serde`, `serde_json`, `thiserror`, `cc` (build only), `napi`/`napi-derive`/`napi-build`, `clap` (CLI only), `tempfile` (dev only). DSP math is hand-rolled — no `ndarray`/`rustfft`.
---
## 3. Consequences
**Positive**
- The two FFI seams are small, audited, and independently testable: the C shim round-trips through Rust tests; the napi surface tests run under `cargo test` without Node.
- `unsafe` is confined to one crate (`rvcsi-adapter-nexmon`) and within it to one module (`ffi`), every block documented.
- Each leaf crate (`rvcsi-dsp`, `rvcsi-events`, `rvcsi-adapter-file`, `rvcsi-ruvector`) depends only on `rvcsi-core`, so they can evolve (and be reviewed, and be swarm-implemented) independently.
- The `.rvcsi` JSONL capture format and the `JsonlRfMemory` standin make the whole pipeline runnable and testable end-to-end before any hardware or the real RuVector binding exists.
**Negative / costs**
- A `cc`-built C library means a C toolchain is required to build `rvcsi-adapter-nexmon` (already true for many workspace crates via transitive `cc` deps; acceptable).
- The "rvCSI Nexmon record" is a *normalized* format, not byte-identical to any upstream nexmon_csi build — a thin demux/transcode step is needed when wiring real Nexmon output. This is intentional (we control the contract the shim parses) and documented.
- JSONL captures are larger than a packed binary format; fine for v0 (and the PRD already standardizes on JSON/WebSocket on the wire), revisit if capture size becomes a problem.
- `rvcsi-node` as a workspace member adds the `napi` dependency tree to `cargo build --workspace`; mitigated by it being a small, well-maintained crate.
**Risks**
- napi-rs major-version churn could change the macro/`build.rs` surface; pinned to `napi = "2.16"` in workspace deps, bumped deliberately.
- If a future platform can't link a napi cdylib under plain `cargo build`, `rvcsi-node` moves to the workspace `exclude` list (like `wifi-densepose-wasm-edge`) with a separate build command — same pattern, already established.
---
## 4. Alternatives considered
| Alternative | Why not |
|-------------|---------|
| One mega-crate `rvcsi` instead of eight | Couples DSP/events/adapters/FFI; can't review or implement them independently; bloats compile units for downstream users who only want `rvcsi-core`. |
| `bindgen` for the C shim | Pulls in `libclang`; the shim's C API is six functions — hand-written `extern "C"` decls are clearer and dependency-free. |
| Binary `.rvcsi` capture format (bincode/custom) | Smaller, but not human-inspectable; JSONL is debuggable, append-friendly, and matches the PRD's on-the-wire JSON. Revisit if size matters. |
| Expose raw `CsiFrame` pointers / typed arrays across napi for zero-copy | Violates ADR-095 D6 (validate-before-FFI) and the "no raw pointers to TS" safety NFR; the per-frame copy cost is negligible at the target rates. |
| `wasm-bindgen` instead of napi-rs for the JS surface | WASM can't do live capture (no raw sockets/serial); great for offline parsing (a later target) but not the primary Node runtime. |
| `rvcsi-events` depending on `rvcsi-dsp` for window stats | Adds a coordination point for two leaf crates; the stats are a few lines — keep the leaves independent and let higher layers compose them. |
---
## 5. Status of the implementation
- `rvcsi-core` — implemented, `forbid(unsafe_code)`, 29 unit tests.
- `rvcsi-adapter-nexmon` + the napi-c shim — implemented; C (ABI `1.1`) compiled via `build.rs`+`cc`; the `ffi` module wraps both record formats (rvCSI record **and** the real nexmon_csi UDP payload + chanspec decode); a pure-Rust `pcap` reader; the Nexmon-chip / Raspberry-Pi-model registry (`chips.rs` — incl. **Pi 5 → BCM43455c0** + chip auto-detection from `chip_ver`); `NexmonAdapter` + `NexmonPcapAdapter` `CsiSource`s; 28 tests, several round-tripping through the C shim and through synthetic libpcap files.
- `rvcsi-dsp` (28 tests), `rvcsi-events` (19 tests — incl. a scale-invariance regression for the baseline-drift detector), `rvcsi-adapter-file` (20 + 1 doctest), `rvcsi-ruvector` (20 + 1 doctest) — implemented.
- `rvcsi-runtime` (13 tests) — composition layer + the one-shot helpers, including `decode_nexmon_pcap` / `decode_nexmon_pcap_for` (per-chip) / `summarize_nexmon_pcap` / `nexmon_profile_for`.
- `rvcsi-node` (napi-rs surface — incl. `nexmonDecodePcap` (with `chip`) / `inspectNexmonPcap` / `decodeChanspec` / `nexmonChipName` / `nexmonProfile` / `nexmonChips` / `RvcsiRuntime.openNexmonPcap`) and `rvcsi-cli` (10 tests — incl. `record --source nexmon-pcap [--chip pi5]`, `inspect-nexmon`, `nexmon-chips`, `decode-chanspec`) — implemented; the `@ruv/rvcsi` npm package + a Node smoke test ship alongside.
- Totals: 169 rvcsi unit/integration tests + 2 doctests, 0 failures; all rvcsi crates build together and are clippy-clean.
- **Validated against real ESP32 CSI** (a 7,000-frame node-1 capture, transcoded to `.rvcsi` via `scripts/esp32_jsonl_to_rvcsi.py` — the stand-in for the not-yet-shipped `record --source esp32-jsonl`): `rvcsi inspect` / `replay` / `calibrate` / `events` all run end-to-end. This surfaced and fixed the baseline-drift over-trigger (absolute → relative thresholds, above).
- `rvcsi-adapter-esp32` (live serial/UDP ESP32 source — ADR-095 §1.2 / D15), `rvcsi-mcp` (MCP tool server), `rvcsi-daemon` (live capture + WebSocket), and the legacy nexmon *packed-float* CSI export — not in this PR; tracked as follow-ups.
---
## 6. References
- [ADR-095 — rvCSI Edge RF Sensing Platform](ADR-095-rvcsi-edge-rf-sensing-platform.md)
- [rvCSI Platform PRD](../prd/rvcsi-platform-prd.md)
- [rvCSI Domain Model](../ddd/rvcsi-domain-model.md)
- napi-rs — https://napi.rs/
- nexmon_csi — the upstream Broadcom CSI extractor the record format normalizes
+2
View File
@@ -105,6 +105,8 @@ Statuses: **Proposed** (under discussion), **Accepted** (approved and/or impleme
| [ADR-011](ADR-011-python-proof-of-reality-mock-elimination.md) | Proof-of-Reality and Mock Elimination | Proposed |
| [ADR-026](ADR-026-survivor-track-lifecycle.md) | Survivor Track Lifecycle (MAT crate) | Accepted |
| [ADR-038](ADR-038-sublinear-goal-oriented-action-planning.md) | Sublinear GOAP for Roadmap Optimization | Proposed |
| [ADR-095](ADR-095-rvcsi-edge-rf-sensing-platform.md) | rvCSI — Edge RF Sensing Runtime Platform | Proposed |
| [ADR-096](ADR-096-rvcsi-ffi-crate-layout.md) | rvCSI — Crate Topology, the napi-c Shim, and the napi-rs Node Surface | Proposed |
---
+1
View File
@@ -15,6 +15,7 @@ DDD organizes the codebase around the problem being solved — not around techni
| [Sensing Server](sensing-server-domain-model.md) | Single-binary Axum server: CSI ingestion, model management, recording, training, visualization | 5 contexts: CSI Ingestion, Model Management, CSI Recording, Training Pipeline, Visualization |
| [WiFi-Mat](wifi-mat-domain-model.md) | Disaster response: survivor detection, START triage, mass casualty assessment | 3 contexts: Detection, Localization, Alerting |
| [CHCI](chci-domain-model.md) | Coherent Human Channel Imaging: sub-millimeter body surface reconstruction | 3 contexts: Sounding, Channel Estimation, Imaging |
| [rvCSI](rvcsi-domain-model.md) | Edge RF sensing runtime: multi-source CSI ingestion, validation, normalization, event extraction, RuVector RF memory, agent/MCP integration | 7 contexts: Capture, Validation, Signal, Calibration, Event, Memory, Agent |
## How to read these
+395
View File
@@ -0,0 +1,395 @@
# rvCSI — Edge RF Sensing Runtime Domain Model
## Domain-Driven Design Specification
> Companion documents: [rvCSI Platform PRD](../prd/rvcsi-platform-prd.md) · [ADR-095 — rvCSI Edge RF Sensing Platform](../adr/ADR-095-rvcsi-edge-rf-sensing-platform.md)
### Domain
Camera-free RF spatial sensing from WiFi Channel State Information (CSI).
### Core domain
**RF field interpretation.** rvCSI converts noisy radio channel measurements into validated events and temporal embeddings that represent changes in physical space. CSI is treated as a *temporal delta stream* against learned baselines — not as exact vision.
### Supporting subdomains
Hardware adapter management · packet parsing · signal processing · calibration · event extraction · temporal memory · agent integration · replay and audit.
### Generic subdomains
Logging · configuration · CLI parsing · WebSocket streaming · package publishing · dashboard visualization.
---
## Ubiquitous Language
| Term | Definition |
|------|------------|
| **CSI** | Channel State Information — per-subcarrier complex channel response measured by a WiFi receiver |
| **Source** | A physical or replayed producer of CSI frames (a NIC, an ESP32 node, a PCAP file, a recorded capture) |
| **Adapter** | A software module that knows how to receive and decode source-specific CSI and normalize it into a `CsiFrame` |
| **Frame** | One CSI observation at a timestamp — the unit of ingestion |
| **Window** | A bounded sequence of frames from one source/session, used for analysis |
| **Baseline** | The learned normal RF-field state for a space |
| **Delta** | The measured difference of the current field from baseline |
| **Event** | A semantic interpretation of one or more windows (presence started, motion detected, anomaly, …) |
| **Quality score** | Confidence, in [0, 1], that a signal/frame/window is usable |
| **Calibration** | The process of learning a stable baseline for a space |
| **Room signature** | A vector representation of a space under normal conditions |
| **Drift** | Slow movement of the field away from baseline |
| **Anomaly** | A significant, unexplained deviation from baseline |
| **RF memory** | Persisted temporal vectors and events for a physical space (stored in RuVector) |
| **Coherence** | Consistency among sources, windows, and learned baselines |
| **Quarantine** | A holding store for rejected/corrupt frames, kept for audit rather than discarded |
| **Adapter profile** | A capability descriptor for a source (chip, firmware/driver versions, supported channels/bandwidths, expected subcarrier counts, capture/injection/monitor-mode support) |
| **Calibration version** | An immutable identifier for a particular learned baseline; every event references the calibration version it was detected against |
| **Evidence window set** | The set of `WindowId`s an event references as its justification — an event with no evidence is invalid |
---
## Bounded Contexts
```
┌─────────────┐ ┌──────────────┐ ┌────────────┐ ┌──────────────┐
│ Capture │──▶│ Validation │──▶│ Signal │──▶│ Calibration │
│ context │ │ context │ │ context │ │ context │
└─────────────┘ └──────────────┘ └─────┬──────┘ └──────┬───────┘
│ │
▼ │
┌────────────┐ │
│ Event │◀──────────┘
│ context │
└─────┬──────┘
┌─────────────┴─────────────┐
▼ ▼
┌────────────┐ ┌────────────┐
│ Memory │ │ Agent │
│ context │ │ context │
└────────────┘ └────────────┘
```
- **Capture** upstreams raw input from sources.
- **Validation** protects every downstream context — nothing crosses into SDK/DSP/memory/agents unvalidated.
- **Signal** turns frames into windows.
- **Calibration** gives windows a room-specific baseline.
- **Event** converts deltas into meaning.
- **Memory** stores time, similarity, drift, and coherence (RuVector).
- **Agent** exposes safe actions and queries (MCP / TypeScript).
---
### 1. Capture context
**Responsibility:** connect to CSI sources and produce raw frames.
```
┌──────────────────────────────────────────────────────────────┐
│ Capture Context │
├──────────────────────────────────────────────────────────────┤
│ ┌────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │ Source │ │ CaptureSession │ │ AdapterProfile │ │
│ │ (adapter │ │ (aggregate root)│ │ (capability │ │
│ │ plugin) │ │ │ │ descriptor) │ │
│ └────────────┘ └─────────────────┘ └─────────────────┘ │
│ │
│ CsiSource trait: open · start · next_frame · stop · health │
└──────────────────────────────────────────────────────────────┘
```
| Element | Kind | Notes |
|---------|------|-------|
| `Source` | Entity | A configured adapter instance bound to a device or file |
| `CaptureSession` | Entity / **aggregate root** | Owns exactly one `AdapterProfile` and one runtime configuration |
| `AdapterProfile` | Entity | Chip, firmware/driver versions, supported channels/bandwidths, expected subcarrier counts, capability flags |
| `Channel`, `Bandwidth`, `FirmwareVersion`, `DriverVersion` | Value objects | Immutable |
**Commands:** `StartCapture` · `StopCapture` · `RestartCapture` · `InspectSource`
**Domain events:** `CaptureStarted` · `CaptureStopped` · `SourceDisconnected` · `AdapterUnsupported`
---
### 2. Validation context
**Responsibility:** make frames safe and trustworthy before any language-boundary crossing.
| Element | Kind | Notes |
|---------|------|-------|
| `ValidationPolicy` | Entity | Bounds, monotonicity rules, finiteness checks, quarantine on/off |
| `QuarantineStore` | Entity | Holds rejected/corrupt frames for audit |
| `ValidatedFrame` | **Aggregate root** | The frame once it has passed (or been degraded by) validation |
| `ValidationError`, `QualityScore`, `FrameBounds` | Value objects | `QualityScore` ∈ [0, 1] |
**Commands:** `ValidateFrame` · `QuarantineFrame`
**Domain events:** `FrameAccepted` · `FrameRejected` · `QualityDropped`
---
### 3. Signal context
**Responsibility:** DSP and window features.
```
Frame stream ─▶ SignalPipeline ─▶ WindowBuffer ─▶ CsiWindow
(DC removal, phase unwrap, (mean amplitude,
smoothing, Hampel filter, phase variance,
variance, baseline subtraction, motion energy,
motion energy, presence score) presence/quality scores)
```
| Element | Kind | Notes |
|---------|------|-------|
| `SignalPipeline` | Entity | Ordered DSP stages; reuses `wifi-densepose-signal` primitives |
| `WindowBuffer` | Entity | Accumulates frames into bounded windows |
| `CsiWindow` | **Aggregate root** | Frames from exactly one source/session |
| `AmplitudeVector`, `PhaseVector`, `MotionEnergy`, `PresenceScore` | Value objects | |
**Commands:** `ProcessFrame` · `BuildWindow` · `EstimateBaselineDelta`
**Domain events:** `WindowReady` · `BaselineDeltaMeasured`
---
### 4. Calibration context
**Responsibility:** learn and version the normal RF state and room signatures.
| Element | Kind | Notes |
|---------|------|-------|
| `CalibrationProfile` | **Aggregate root** | Linked to source, room, adapter profile, configuration |
| `RoomSignature` | Entity | Vector representation of a space under normal conditions |
| `BaselineModel` | Entity | Statistical model of the baseline field; carries version history |
| `CalibrationVersion`, `StabilityScore`, `RoomId` | Value objects | Calibration cannot complete if `StabilityScore` < threshold |
**Commands:** `StartCalibration` · `CompleteCalibration` · `UpdateBaseline` · `RejectUnstableCalibration`
**Domain events:** `CalibrationStarted` · `CalibrationCompleted` · `CalibrationFailed` · `BaselineUpdated`
---
### 5. Event context
**Responsibility:** semantic event extraction with confidence and evidence.
| Element | Kind | Notes |
|---------|------|-------|
| `EventDetector` | Entity | One per event family (presence, motion, breathing, anomaly, …) |
| `EventStateMachine` | Entity | Holds the per-source detection state; emits transitions |
| `CsiEvent` | **Aggregate root** | Must reference ≥ 1 evidence window; confidence ∈ [0, 1]; references calibration version |
| `Confidence`, `EvidenceWindowSet`, `EventKind` | Value objects | |
**Commands:** `DetectEvents` · `PublishEvent` · `SuppressEvent`
**Domain events (the `CsiEventKind` enum):** `PresenceStarted` · `PresenceEnded` · `MotionDetected` · `MotionSettled` · `BaselineChanged` · `SignalQualityDropped` · `DeviceDisconnected` · `BreathingCandidate` · `AnomalyDetected` · `CalibrationRequired`
---
### 6. Memory context
**Responsibility:** RuVector storage and retrieval — RF memory.
| Element | Kind | Notes |
|---------|------|-------|
| `RfMemoryCollection` | Entity | A RuVector collection scoped to a deployment |
| `TemporalEmbedding` | Entity | Frame / window / event embedding with timestamp |
| `SensorGraph` | Entity | Graph of sources and their topological relationships |
| `RoomMemory` | **Aggregate root** | Stored embeddings must be traceable to frame windows or event windows |
| `EmbeddingVector`, `DriftScore`, `CoherenceScore` | Value objects | `DriftScore` must include the baseline version |
**Commands:** `StoreWindowEmbedding` · `StoreEventEmbedding` · `QuerySimilarWindows` · `ComputeDrift`
**Domain events:** `EmbeddingStored` · `DriftDetected` · `SimilarPatternFound`
Data stored: frame embeddings · window embeddings · room baseline vectors · event vectors · drift snapshots · sensor-topology graph edges · source health records. Retention policy applies at collection level. No orphan embeddings.
---
### 7. Agent context
**Responsibility:** MCP and TypeScript agent interaction — safe actions and queries.
| Element | Kind | Notes |
|---------|------|-------|
| `AgentSubscription` | Entity | An agent's filtered stream of events |
| `McpToolSession` | Entity | A tool invocation context with permissions |
| `AgentSession` | **Aggregate root** | |
| `ToolPermission`, `EventFilter`, `AgentIntent` | Value objects | `ToolPermission` distinguishes read vs. write-gated |
**Commands:** `SubscribeToEvents` · `RequestStatus` · `RequestCalibration` · `QueryMemory`
**Domain events:** `AgentSubscribed` · `ToolExecuted` · `PermissionDenied`
**MCP tools** (read by default; write-gated marked `*`): `rvcsi_status` · `rvcsi_list_sources` · `rvcsi_start_capture *` · `rvcsi_stop_capture *` · `rvcsi_get_presence` · `rvcsi_get_recent_events` · `rvcsi_calibrate_room *` · `rvcsi_export_window *` · `rvcsi_query_ruvector` · `rvcsi_health_report`.
---
## Context Map
| Upstream → Downstream | Relationship | ACL / contract |
|-----------------------|--------------|----------------|
| Capture → Validation | Customer/Supplier | Raw frames pass through `ValidationPolicy`; only `Accepted`/`Degraded` continue |
| Validation → Signal | Conformist (Signal accepts `ValidatedFrame` as-is) | `CsiFrame` schema is the published language |
| Signal → Calibration | Customer/Supplier | Windows + baseline-delta measurements feed baseline modeling |
| Calibration → Event | Customer/Supplier | Detectors declare which `CalibrationVersion` they used |
| Signal/Event → Memory | Published Language (`EmbeddingVector`, event metadata) | `rvcsi-ruvector` ACL translates to RuVector's API |
| Event → Agent | Open Host Service (event stream + MCP tools) | `EventFilter` + `ToolPermission` enforced at the boundary |
| Capture → Agent | Conformist (health/status only, via MCP read tools) | No raw frames cross to agents |
The **`CsiFrame` schema is the shared kernel** between Capture, Validation, Signal, and the language-boundary (napi-rs) layer. It is the FFI-safe object; nothing device-specific leaks past it.
---
## Aggregates and Invariants
### `CaptureSession` aggregate
**Invariant:** a capture session has exactly one source profile and one runtime configuration.
1. A session cannot emit frames before it is started.
2. A session cannot change channel without restart unless the adapter supports dynamic retune.
3. A session must emit `SourceDisconnected` before stopping due to device loss.
### `ValidatedFrame` aggregate
**Invariant:** no frame crosses into SDK, DSP, memory, or agents unless its validation status is `Accepted` or `Degraded`.
1. Rejected frames go to quarantine when quarantine is enabled.
2. Degraded frames must carry quality-reason metadata.
3. Missing *optional* hardware metadata must not invalidate a frame.
### `CsiWindow` aggregate
**Invariant:** a window contains frames from exactly one source and one session.
1. Mixed-source windows are not allowed.
2. Window start time must be strictly less than end time.
3. Window quality is bounded in [0, 1].
### `CalibrationProfile` aggregate
**Invariant:** a calibration profile is linked to source, room, adapter profile, and configuration.
1. Calibration cannot complete if `StabilityScore` is below threshold.
2. Baseline updates must preserve version history.
3. Event detectors must declare which calibration version they used.
### `CsiEvent` aggregate
**Invariant:** an event must have evidence.
1. Every event references at least one evidence window.
2. Confidence is bounded in [0, 1].
3. Event suppression must be explainable by policy.
### `RoomMemory` aggregate
**Invariant:** stored embeddings are traceable to frame windows or event windows.
1. No orphan embeddings.
2. Retention policy applies at collection level.
3. Drift scores must include the baseline version.
---
## Data Model
```rust
pub struct CsiFrame {
pub frame_id: FrameId,
pub session_id: SessionId,
pub source_id: SourceId,
pub adapter_kind: AdapterKind,
pub timestamp_ns: u64,
pub channel: u16,
pub bandwidth_mhz: u16,
pub rssi_dbm: Option<i16>,
pub noise_floor_dbm: Option<i16>,
pub antenna_index: Option<u8>,
pub tx_chain: Option<u8>,
pub rx_chain: Option<u8>,
pub subcarrier_count: u16,
pub i_values: Vec<f32>,
pub q_values: Vec<f32>,
pub amplitude: Vec<f32>,
pub phase: Vec<f32>,
pub validation: ValidationStatus,
pub quality_score: f32,
pub calibration_version: Option<String>,
}
pub struct CsiWindow {
pub window_id: WindowId,
pub session_id: SessionId,
pub source_id: SourceId,
pub start_ns: u64,
pub end_ns: u64,
pub frame_count: u32,
pub mean_amplitude: Vec<f32>,
pub phase_variance: Vec<f32>,
pub motion_energy: f32,
pub presence_score: f32,
pub quality_score: f32,
}
pub enum CsiEventKind {
PresenceStarted,
PresenceEnded,
MotionDetected,
MotionSettled,
BaselineChanged,
SignalQualityDropped,
DeviceDisconnected,
BreathingCandidate,
AnomalyDetected,
CalibrationRequired,
}
pub struct CsiEvent {
pub event_id: EventId,
pub kind: CsiEventKind,
pub session_id: SessionId,
pub source_id: SourceId,
pub timestamp_ns: u64,
pub confidence: f32,
pub evidence_window_ids: Vec<WindowId>,
pub metadata_json: String,
}
pub struct AdapterProfile {
pub adapter_kind: AdapterKind,
pub chip: Option<String>,
pub firmware_version: Option<String>,
pub driver_version: Option<String>,
pub supported_channels: Vec<u16>,
pub supported_bandwidths_mhz: Vec<u16>,
pub expected_subcarrier_counts: Vec<u16>,
pub supports_live_capture: bool,
pub supports_injection: bool,
pub supports_monitor_mode: bool,
}
pub enum ValidationStatus { Accepted, Degraded, Rejected, Recovered }
```
---
## Domain Services
| Service | Input | Output | Responsibility |
|---------|-------|--------|----------------|
| `FrameValidationService` | `RawFrame`, `AdapterProfile`, `ValidationPolicy` | `ValidatedFrame` or `RejectedFrame` | Enforce bounds, finiteness, monotonicity; assign initial `QualityScore`; route rejects to quarantine; emit structured errors |
| `SignalProcessingService` | `ValidatedFrame` stream | `CsiWindow` stream | Run the DSP pipeline; build bounded windows; compute motion energy, presence score, window quality |
| `BaselineDeltaService` | `CsiWindow`, `BaselineModel` | `BaselineDelta` | Subtract the calibrated baseline; measure deviation magnitude |
| `CalibrationService` | `CsiWindow` stream over a calibration window | `CalibrationProfile` (new version) or `CalibrationFailed` | Learn a stable baseline; compute `StabilityScore`; reject unstable calibrations; preserve version history |
| `EventDetectionService` | `CsiWindow` + `BaselineDelta` + `CalibrationVersion` | `CsiEvent` stream | Drive per-source state machines; attach confidence + evidence windows + calibration version; apply suppression policy |
| `EmbeddingService` | `CsiWindow` / `CsiEvent` | `TemporalEmbedding` | Produce frame/window/event vectors (v0: deterministic DSP feature vector; later: AETHER / on-device model) |
| `RfMemoryService` | `TemporalEmbedding`, query | `EmbeddingStored` / similar windows / `DriftScore` | Store to RuVector; similarity search; drift computation against a baseline version |
| `ReplayService` | A captured session bundle | A deterministic frame/window/event stream | Replay preserving timestamps, ordering, validation decisions, event output, calibration version, runtime config |
| `AdapterRegistryService` | — | List of available adapters + `AdapterProfile`s | Discover sources (reuses ADR-049 interface detection); report health; flag unsupported firmware/driver state |
| `AgentGatewayService` | MCP tool call / SDK subscription | Tool result / filtered event stream | Enforce `ToolPermission` (read vs. write-gated), apply `EventFilter`, audit `ToolExecuted` / `PermissionDenied` |
---
## Related
- [rvCSI Platform PRD](../prd/rvcsi-platform-prd.md) — requirements, success criteria, scope
- [ADR-095 — rvCSI Edge RF Sensing Platform](../adr/ADR-095-rvcsi-edge-rf-sensing-platform.md) — the fifteen architectural decisions
- [RuvSense Domain Model](ruvsense-domain-model.md) — adjacent multistatic sensing context
- [Signal Processing Domain Model](signal-processing-domain-model.md) — the DSP primitives `rvcsi-dsp` reuses
- [ADR Index](../adr/README.md)
+3 -3
View File
@@ -168,14 +168,14 @@ The training process works like this:
1. **Collect** raw CSI frames from ESP32-S3 nodes placed in a room
2. **Extract** 8-dimensional feature vectors from sliding windows of CSI data
3. **Contrast** -- the model learns that features from nearby time windows should produce similar embeddings, while features from different scenarios should produce different embeddings
4. **Fine-tune** task heads using weak labels from environmental sensors (PIR motion, temperature, pressure) on the Cognitum Seed companion device
4. **Fine-tune** task heads *planned:* weak labels from environmental sensors (PIR motion, temperature, pressure) on the Cognitum Seed companion device. **This environmental-sensor ground-truth path is not yet implemented** (no PIR/BME280 ingestion in the training pipeline today); current task-head supervision uses the proxy/camera labels described elsewhere.
### Data provenance
- **Source:** Live CSI from 2x ESP32-S3 nodes (802.11n, HT40, 114 subcarriers)
- **Volume:** ~360,000 CSI frames (~3,600 feature vectors) per collection run
- **Environment:** Residential room, ~4x5 meters
- **Ground truth:** Environmental sensors on Cognitum Seed (PIR, BME280, light)
- **Ground truth:** *Planned* — environmental sensors on the Cognitum Seed (PIR, BME280, light). Not yet wired into training; treat the PIR/BME280 references in this card as the intended design, not a current capability.
- **Attestation:** Every collection run produces a cryptographic witness chain (`collection-witness.json`) that proves data provenance and integrity
### Witness chain
@@ -208,7 +208,7 @@ Add a second ESP32-S3 to enable cross-node signal fusion for better accuracy and
| USB-C cables (x3) | Power + data | ~$9 |
| **Total** | | **~$27** |
The Cognitum Seed runs the ONNX models on-device, orchestrates the ESP32 nodes over USB serial, and provides environmental ground truth via its onboard PIR and BME280 sensors.
The Cognitum Seed runs the ONNX models on-device and orchestrates the ESP32 nodes over USB serial. (Using its onboard PIR/BME280 sensors as training ground truth is planned but not yet implemented — see "Data provenance" above.)
---
+376
View File
@@ -0,0 +1,376 @@
# rvCSI — Edge RF Sensing Runtime
## Product Design Requirements (PRD)
| Field | Value |
|-------|-------|
| **Product name** | rvCSI |
| **Category** | Edge RF sensing runtime and developer platform |
| **Status** | Proposed (v0 design) |
| **Date** | 2026-05-12 |
| **Owner** | ruv |
| **Relates to** | [ADR-095](../adr/ADR-095-rvcsi-edge-rf-sensing-platform.md) (rvCSI platform), [ADR-012](../adr/ADR-012-esp32-csi-sensor-mesh.md) (ESP32 mesh), [ADR-013](../adr/ADR-013-feature-level-sensing-commodity-gear.md) (feature-level sensing), [ADR-014](../adr/ADR-014-sota-signal-processing.md) (SOTA signal processing), [ADR-016](../adr/ADR-016-ruvector-integration.md) (RuVector integration), [ADR-024](../adr/ADR-024-contrastive-csi-embedding-model.md) (AETHER embeddings), [ADR-031](../adr/ADR-031-ruview-sensing-first-rf-mode.md) (RuView sensing-first RF mode), [ADR-040](../adr/ADR-040-wasm-programmable-sensing.md) (WASM programmable sensing) |
| **Domain model** | [rvCSI Domain Model](../ddd/rvcsi-domain-model.md) |
---
## 1. Purpose
rvCSI is a **Rust-first, TypeScript-accessible, hardware-abstracted Channel State Information (CSI) platform** for WiFi-based spatial sensing.
The goal is to convert CSI from fragile research data into a durable edge sensing runtime that can feed RuView, RuVector, Cognitum, and agentic systems with validated live radio-field observations.
rvCSI does **not** try to replace Nexmon on day one. It wraps, validates, normalizes, streams, embeds, and learns from CSI produced by Nexmon, ESP32 CSI, Intel CSI, Atheros CSI, SDR pipelines, and future RF sensor sources.
### 1.1 System framing
CSI is treated as a **physical-world delta stream**.
A room, hallway, vehicle, warehouse, machine bay, or care facility has a radio-field baseline. Human motion, breathing, door movement, equipment vibration, device movement, and environmental change perturb that baseline. rvCSI captures those perturbations, normalizes them into tensors, converts them into events, stores them as temporal memory, and exposes them to agents.
The core invariant:
| Layer | Owns |
|-------|------|
| **C** | Fragile vendor and firmware compatibility |
| **Rust** | Safety, validation, signal processing, memory discipline, deterministic runtime behavior |
| **TypeScript** | Developer experience, orchestration, dashboards, SDKs, agent integration |
| **RuVector** | Memory, similarity, drift, graph relationships, coherence over time |
| **Cognitum** | Low-power event-driven deployment, local decision loops |
### 1.2 Strategic framing
Most CSI projects today are Linux shell scripts, kernel patching, Python notebooks, PCAP dumps, and ad-hoc signal processing. A Rust + TypeScript + napi-rs architecture turns CSI into **real-time sensor infrastructure**: npm-installable, reproducible, typed, safe-parsed, embeddable, WebSocket-streamable, WASM-portable, MCP-exposed, agent-integrable, and edge/cloud-federated.
The right framing is **structural sensing**, not "magic X-ray vision". CSI is excellent for detecting change, presence, and learned patterns; it is weak for exact identity, exact pose, legal/security certainty, and highly dynamic RF spaces. rvCSI's product claims stay inside that boundary (see Non-goals, §6).
---
## 2. Users
| User | Need |
|------|------|
| AI engineers building physical-world agents | A stable sensing primitive that emits typed events agents can react to |
| Researchers working with WiFi CSI and RF sensing | Reproducible ingestion, replay, and benchmark datasets |
| Smart-building and elder-care solution builders | Privacy-preserving presence/motion/breathing without cameras |
| Industrial monitoring teams | Camera-free movement/anomaly detection that runs unattended |
| Developers using RuView / RuVector / Cognitum | A drop-in source of RF observations for the broader ruvnet stack |
---
## 3. Problem & Hypothesis
**Problem.** WiFi CSI is useful but hard to operationalize. Most CSI pipelines are built from fragile scripts, patched firmware, lab notebooks, inconsistent packet formats, unstable drivers, and device-specific assumptions. This makes CSI difficult to deploy outside research settings. The system needs a production-grade runtime that can ingest CSI from multiple sources, validate packets, normalize formats, stream typed events, support signal processing, and feed vector-based learning systems.
**Hypothesis.** If rvCSI provides a stable Rust core with TypeScript APIs and hardware adapters, then CSI can become a reusable sensing primitive for camera-free spatial intelligence.
---
## 4. Success criteria
1. A developer can install rvCSI and parse recorded CSI files in **under five minutes**.
2. A supported live device can stream **validated** CSI frames into TypeScript.
3. Bad packets **cannot crash** the process.
4. The same application code consumes CSI from Nexmon, ESP32, Intel, or Atheros adapters.
5. Presence and motion detection work from **normalized tensors**, not device-specific raw packets.
6. rvCSI can publish embeddings and event summaries into **RuVector**.
7. rvCSI can run as a **local daemon on Raspberry Pi-class hardware**.
8. rvCSI can expose events to **MCP tools and local agents**.
---
## 5. Scope
### 5.1 Version zero — safe ingestion, normalized data, live streaming, SDK usability, RuVector integration
1. Recorded CSI file parser
2. Live capture adapter for existing Nexmon CSI output where supported
3. ESP32 CSI adapter
4. Unified CSI frame schema
5. Rust validation pipeline
6. TypeScript SDK through napi-rs
7. CLI for capture, inspect, replay, stream
8. WebSocket output
9. Presence and motion baseline detectors
10. RuVector export interface
11. Basic calibration model
12. Hardware and driver health checks
### 5.2 Version one
1. Multi-node synchronization
2. RF room signatures
3. Breathing-rate estimation where signal quality permits
4. Temporal embeddings
5. Drift detection
6. Graph-based room topology
7. Local MCP tool server
8. Replayable benchmark datasets
9. Sensor fusion with RuView
10. Deployment profile for Cognitum Seed and Appliance
### 5.3 Version two
1. Hardware-agnostic RF sensor fabric
2. Multi-room RF memory
3. Streaming anomaly detection
4. RF SLAM research mode
5. On-device embedding model
6. Federated learning of room signatures
7. Secure signed sensor-evidence records
8. Proof-gated event publication
9. Dynamic cut-based coherence over RF graphs
10. Agent-driven calibration and self-repair
---
## 6. Non-goals (version zero)
1. Pure-Rust replacement for Broadcom firmware patches
2. Universal support for all WiFi chips
3. Identity recognition from RF signals
4. Medical-grade vital-sign diagnosis
5. Legal-grade occupancy proof
6. Guaranteed through-wall pose detection
7. Cloud dependency
8. Camera-replacement claims
---
## 7. Functional requirements
### FR1 — CSI ingestion
rvCSI shall ingest CSI from multiple sources. Initial source types: recorded binary dump, PCAP file, Nexmon CSI live stream, ESP32 CSI serial/UDP stream, Intel CSI logs (where supported), Atheros CSI logs (where supported). **Output:** a normalized `CsiFrame` object.
### FR2 — Packet validation
rvCSI shall validate every frame before exposing it to TypeScript or RuVector:
1. Frame length must match declared schema.
2. Subcarrier count must be inside adapter-profile limits.
3. Timestamp must be monotonic within a capture session unless marked as recovered.
4. RSSI must be within plausible device bounds.
5. Complex values must be finite.
6. Corrupt frames must be rejected or quarantined.
7. Parser failures must return structured errors.
### FR3 — Normalized frame schema
rvCSI shall normalize all hardware output into a common schema. Required fields: `frame_id`, `session_id`, `source_id`, `adapter_kind`, `timestamp_ns`, `channel`, `bandwidth_mhz`, `rssi_dbm`, `noise_floor_dbm` (when available), `antenna_index` (when available), `tx_chain` (when available), `rx_chain` (when available), `subcarrier_count`, `i_values`, `q_values`, `amplitude`, `phase`, `validation_status`, `quality_score`, `calibration_version`.
### FR4 — Signal processing
rvCSI shall provide reusable Rust signal-processing stages: DC offset removal, phase unwrap, amplitude smoothing, Hampel/median outlier filter, short-window variance, baseline subtraction, motion energy, presence score, breathing-band estimator (where supported), confidence scoring.
### FR5 — Event extraction
rvCSI shall convert frame streams into typed events: `PresenceStarted`, `PresenceEnded`, `MotionDetected`, `MotionSettled`, `BaselineChanged`, `SignalQualityDropped`, `DeviceDisconnected`, `BreathingCandidate`, `AnomalyDetected`, `CalibrationRequired`.
### FR6 — TypeScript SDK
rvCSI shall expose a TypeScript SDK:
```ts
import { RvCsi } from "@ruv/rvcsi";
const sensor = await RvCsi.open({
source: "nexmon",
iface: "wlan0",
channel: 6,
bandwidthMHz: 20,
});
sensor.on("frame", (frame) => {
console.log(frame.qualityScore);
});
sensor.on("presence", (event) => {
console.log(event.confidence);
});
await sensor.start();
```
### FR7 — CLI
```bash
rvcsi inspect file sample.csi
rvcsi capture start --source nexmon --iface wlan0 --channel 6
rvcsi replay sample.csi --speed 1x
rvcsi stream --format json --port 8787
rvcsi calibrate --room livingroom --duration 60
rvcsi health --source nexmon
rvcsi export ruvector --collection room_rf
```
### FR8 — RuVector integration
rvCSI shall export temporal RF embeddings and event metadata to RuVector. Data stored: frame embeddings, window embeddings, room baseline vectors, event vectors, drift snapshots, sensor-topology graph edges, source health records.
### FR9 — MCP integration
rvCSI shall expose MCP tools for local agents: `rvcsi_status`, `rvcsi_list_sources`, `rvcsi_start_capture`, `rvcsi_stop_capture`, `rvcsi_get_presence`, `rvcsi_get_recent_events`, `rvcsi_calibrate_room`, `rvcsi_export_window`, `rvcsi_query_ruvector`, `rvcsi_health_report`. Tools default to read actions; capture start/stop, calibration, and export are write-gated.
### FR10 — Replay and audit
rvCSI shall support deterministic replay of captured sessions, preserving: original timestamps, frame ordering, validation decisions, event-extraction output, calibration version, runtime configuration.
---
## 8. Non-functional requirements
### 8.1 Safety
1. TypeScript shall never receive raw unchecked pointers.
2. Rust shall validate all frames before the FFI boundary export.
3. C shims shall be minimal and isolated.
4. All `unsafe` blocks shall be documented.
5. Fuzz tests shall cover parsers.
### 8.2 Performance (v0 targets)
1. Parse one CSI frame in **< 1 ms** on Raspberry Pi 5.
2. Sustain **≥ 1000 frames/s** on Pi 5 for normalized parsing.
3. Keep memory **< 256 MB** for one active source.
4. Keep event latency **< 50 ms** for presence and motion.
5. Avoid heap growth during steady capture.
### 8.3 Reliability
1. Bad packets shall not crash the daemon.
2. Device disconnect shall produce a typed event.
3. Capture sessions shall be restartable.
4. Logs shall include source, adapter, session, and validation details.
5. Health checks shall identify unsupported firmware or driver state.
### 8.4 Privacy
1. rvCSI shall operate locally by default.
2. No cloud endpoint shall be required.
3. Raw CSI export shall be disableable by policy.
4. Event-level export shall be supported for privacy-preserving deployments.
5. Retention policies shall be configurable.
### 8.5 Security
1. Device-control operations shall require explicit permission.
2. Firmware-installation operations shall be separated from capture operations.
3. Signed capture profiles shall be supported in later versions.
4. MCP tools shall mark write actions as gated.
5. File parsing shall be fuzzed and sandbox-friendly.
### 8.6 Portability
1. Linux first.
2. Raspberry Pi first among edge devices.
3. macOS and Windows support for file replay and SDK development.
4. Live-capture support depends on adapter and driver capability.
5. WASM support for offline parsing and visualization is a later target.
---
## 9. System architecture
### 9.1 High-level pipeline
```
CSI Source
Adapter Layer (vendor-specific decode, C shims isolated here)
Rust Validation Pipeline (bounds, finiteness, monotonicity, quarantine)
Normalized CSI Frame (CsiFrame schema — the FFI-safe boundary object)
Signal Processing (DC removal, phase unwrap, smoothing, motion energy …)
Window Aggregator (bounded frame sequences → CsiWindow)
Event Extractor (state machines → CsiEvent with confidence + evidence)
TypeScript SDK · CLI · MCP · RuVector
```
### 9.2 Runtime components
| # | Component | Role |
|---|-----------|------|
| 1 | `rvcsi-core` | Frame types, parser traits, validation, quality scoring, shared abstractions |
| 2 | `rvcsi-adapter-*` | Rust/C-backed adapters: Nexmon, ESP32, Intel, Atheros, files, replay |
| 3 | `rvcsi-dsp` | Rust signal-processing primitives |
| 4 | `rvcsi-events` | Windowing, baseline modeling, event extraction, state machines |
| 5 | `rvcsi-node` | napi-rs bindings exposing safe APIs to Node.js |
| 6 | `rvcsi-sdk` | TypeScript SDK |
| 7 | `rvcsi-cli` | Command-line interface |
| 8 | `rvcsi-daemon` | Long-running capture and event service |
| 9 | `rvcsi-mcp` | MCP tool server |
| 10 | `rvcsi-ruvector` | Exporter and query bridge |
### 9.3 Reference repository layout
```
rvcsi/
crates/
rvcsi-core/
rvcsi-adapter-file/
rvcsi-adapter-nexmon/
rvcsi-adapter-esp32/
rvcsi-dsp/
rvcsi-events/
rvcsi-ruvector/
rvcsi-daemon/
rvcsi-node/
rvcsi-mcp/
packages/
sdk/
cli/
dashboard/
native/
nexmon-shim-c/
docs/
adr/
ddd/
prd/
benchmarks/
testdata/
captures/
malformed/
replay/
```
> Within the RuView monorepo, rvCSI would be introduced as a new bounded context (see the [domain model](../ddd/rvcsi-domain-model.md)) and a small set of `v2/crates/rvcsi-*` crates, reusing existing `wifi-densepose-signal` DSP and `wifi-densepose-ruvector` integration where they overlap rather than duplicating them.
---
## 10. Data model (summary)
The authoritative definitions live in the [rvCSI domain model](../ddd/rvcsi-domain-model.md). Summary:
- **`CsiFrame`** — one validated CSI observation at a timestamp (the FFI-safe object). Carries I/Q, amplitude, phase, RSSI, channel/bandwidth, optional antenna/chain metadata, validation status, quality score, calibration version.
- **`CsiWindow`** — a bounded sequence of frames from one source/session, with mean amplitude, phase variance, motion energy, presence score, quality score.
- **`CsiEvent`** — a semantic interpretation of one or more windows, with `kind`, confidence, evidence window IDs, and metadata.
- **`AdapterProfile`** — capability descriptor for a source: chip, firmware/driver versions, supported channels/bandwidths, expected subcarrier counts, capture/injection/monitor-mode support.
---
## 11. Open questions
1. **Embedding model.** What produces frame/window embeddings in v0 — a fixed DSP feature vector, the existing AETHER contrastive model (ADR-024), or a lightweight on-device model? v0 leans on a deterministic DSP feature vector; v2 targets an on-device model.
2. **Calibration UX.** How long must a calibration window be before `StabilityScore` is trustworthy, and how is that surfaced in the SDK/CLI?
3. **Nexmon coupling.** Which Nexmon-supported chips/firmwares are in the v0 "supported" matrix vs. "best effort"?
4. **Monorepo vs. standalone.** Does rvCSI ship as `v2/crates/rvcsi-*` inside RuView or as a separate `rvcsi/` repo? This PRD assumes monorepo crates that reuse `wifi-densepose-signal` and `wifi-densepose-ruvector`.
5. **MCP transport.** stdio-only for v1, or also a local socket for multi-agent fan-out?
---
## 12. References
- [ADR-095 — rvCSI Edge RF Sensing Platform](../adr/ADR-095-rvcsi-edge-rf-sensing-platform.md)
- [rvCSI Domain Model](../ddd/rvcsi-domain-model.md)
- [ADR-013 — Feature-Level Sensing on Commodity Gear](../adr/ADR-013-feature-level-sensing-commodity-gear.md)
- [ADR-014 — SOTA Signal Processing](../adr/ADR-014-sota-signal-processing.md)
- [ADR-016 — RuVector Integration](../adr/ADR-016-ruvector-integration.md)
- [ADR-024 — Project AETHER: Contrastive CSI Embeddings](../adr/ADR-024-contrastive-csi-embedding-model.md)
- [ADR-031 — RuView Sensing-First RF Mode](../adr/ADR-031-ruview-sensing-first-rf-mode.md)
- [ADR-040 — WASM Programmable Sensing](../adr/ADR-040-wasm-programmable-sensing.md)
@@ -336,6 +336,21 @@ void csi_collector_init(void)
/* Update the hop table's first channel to match. */
s_hop_channels[0] = csi_channel;
/* Disable WiFi modem sleep — reliable CSI capture needs the radio awake.
* The ESP-IDF STA default is WIFI_PS_MIN_MODEM, which lets the modem
* sleep between DTIM beacons; with the MGMT-only promiscuous filter
* (RuView#396) that starves the CSI callback and the per-second yield
* collapses toward 0 pps (RuView#521). Operators who want battery
* duty-cycling opt back in via power_mgmt_init() (provision.py
* --duty-cycle <N>), which runs after this and re-enables modem sleep. */
esp_err_t ps_err = esp_wifi_set_ps(WIFI_PS_NONE);
if (ps_err != ESP_OK) {
ESP_LOGW(TAG, "esp_wifi_set_ps(WIFI_PS_NONE) failed: %s — CSI yield may be low",
esp_err_to_name(ps_err));
} else {
ESP_LOGI(TAG, "WiFi modem sleep disabled (WIFI_PS_NONE) for CSI capture");
}
/* Enable promiscuous mode — required for reliable CSI callbacks.
* Without this, CSI only fires on frames destined to this station,
* which may be very infrequent on a quiet network. */
+1 -1
View File
@@ -1 +1 @@
0.6.2
0.6.4
+23
View File
@@ -0,0 +1,23 @@
{
"name": "ruview",
"description": "End-to-end RuView (WiFi-DensePose) toolkit for Claude Code: onboarding, ESP32 hardware setup, configuration, sensing applications, model training, advanced multistatic sensing, and witness verification — from practical to advanced.",
"version": "0.1.0",
"author": {
"name": "ruvnet",
"url": "https://github.com/ruvnet/RuView"
},
"homepage": "https://github.com/ruvnet/RuView",
"license": "MIT",
"keywords": [
"ruview",
"wifi-densepose",
"wifi-sensing",
"csi",
"esp32",
"pose-estimation",
"vital-signs",
"edge-ai",
"model-training",
"onboarding"
]
}
+80
View File
@@ -0,0 +1,80 @@
# ruview — Claude Code + Codex plugin for WiFi sensing
End-to-end toolkit for **RuView** (WiFi-DensePose): onboarding, ESP32 hardware setup, configuration, sensing applications, model training, advanced multistatic sensing, and witness verification — from practical to advanced.
Part of the **`ruview` marketplace** — manifest at the repo root: `.claude-plugin/marketplace.json` (this plugin's `source` is `./plugins/ruview`).
## Install / test
```bash
# In Claude Code — add this repo as a plugin marketplace, then install:
/plugin marketplace add ruvnet/RuView
/plugin install ruview@ruview
# Or try it locally without installing (from a clone of the repo):
claude --plugin-dir ./plugins/ruview
```
For Codex (OpenAI CLI), see [`codex/`](codex/) — all seven `/ruview-*` commands mirrored as Codex prompts, plus an `AGENTS.md` and install instructions in [`codex/README.md`](codex/README.md).
## What's inside
### Skills (auto-discovered from `skills/`)
| Skill | What it does |
|-------|--------------|
| `ruview-quickstart` | Onboarding & first run — Docker demo, repo build, fastest path to a live dashboard |
| `ruview-hardware-setup` | ESP32-S3 / C6 firmware build, flash, WiFi provisioning, serial monitoring |
| `ruview-configure` | sdkconfig variants, NVS provisioning, channel/MAC overrides (ADR-060), edge modules (ADR-041), sensing-server flags, mesh, Cognitum Seed |
| `ruview-applications` | Run presence, vitals, pose (WiFlow), sleep, environment mapping, MAT, point-cloud fusion, novel RF apps |
| `ruview-model-training` | Camera-free pose, camera-supervised pose (92.9% PCK@20, ADR-079), RuVector embeddings (AETHER), domain generalization (MERIDIAN), local SNN, GPU on GCloud, HF publishing |
| `ruview-advanced-sensing` | RuvSense multistatic, cross-viewpoint fusion, RF tomography, persistent field model, intention signals, adversarial detection, mesh security |
| `ruview-cli-api` | `wifi-densepose` CLI binary (incl. MAT subcommands), REST API (`wifi-densepose-api`), browser/WASM (`wifi-densepose-wasm`, `wifi-densepose-wasm-edge`) |
| `ruview-mmwave` | mmWave / FMCW radar — ESP32-C6 + MR60BHA2 (60 GHz HR/BR/presence), HLK-LD2410 (24 GHz), mmWave↔CSI fusion (48-byte fused vitals) |
| `ruview-verify` | Rust tests, deterministic Python proof, firmware hashes, ADR-028 witness bundle + self-verification, pre-merge checklist |
### Commands (`commands/`)
| Command | Purpose |
|---------|---------|
| `/ruview-start` | Get started — pick Docker / build / hardware and walk through it |
| `/ruview-flash` | Build + flash ESP32 firmware (8MB / 4MB), confirm CSI stream |
| `/ruview-provision` | Provision WiFi creds, sink IP, channel / MAC-filter onto a node |
| `/ruview-app` | Run a sensing application |
| `/ruview-train` | Train / evaluate / publish a model (incl. GPU) |
| `/ruview-advanced` | Use multistatic / tomography / cross-viewpoint / mesh-security features |
| `/ruview-verify` | Run the trust pipeline + pre-merge checklist |
### Agents (`agents/`)
| Agent | Role |
|-------|------|
| `ruview-onboarding-guide` | Walks a newcomer from zero to a working setup |
| `ruview-config-engineer` | Sets up / tunes a deployment (firmware, NVS, edge modules, mesh, Seed) |
| `ruview-training-engineer` | Trains, evaluates, and ships models |
## Compatibility
- **Claude Code** — skills, commands, and agents are auto-discovered; no `claude-flow` MCP server required (skills drive RuView's own tooling: `cargo`, `python`, `idf.py`, `docker`, `node`). Optional: `npx @claude-flow/cli@latest security scan` is referenced for security changes.
- **Codex (OpenAI CLI)** — workflows mirrored under `codex/prompts/`; drop them in `~/.codex/prompts/` (or point Codex at `codex/`). `codex/AGENTS.md` carries the project rules.
- **Target repo** — assumes the [`ruvnet/RuView`](https://github.com/ruvnet/RuView) / `wifi-densepose` layout: `v2/crates/`, `firmware/esp32-csi-node/`, `archive/v1/`, `scripts/`, `docs/adr/`. On Windows, ESP-IDF builds go through the Python-subprocess pattern in `CLAUDE.local.md`.
## Namespace coordination
This plugin claims the kebab-case `ruview-*` namespace for its skills, commands, and agents (skills: `ruview-quickstart`, `ruview-hardware-setup`, `ruview-configure`, `ruview-applications`, `ruview-model-training`, `ruview-advanced-sensing`, `ruview-cli-api`, `ruview-mmwave`, `ruview-verify`; commands: `/ruview-start`, `/ruview-flash`, `/ruview-provision`, `/ruview-app`, `/ruview-train`, `/ruview-advanced`, `/ruview-verify`; agents: `ruview-onboarding-guide`, `ruview-config-engineer`, `ruview-training-engineer`). It does not write to any `claude-flow` memory namespace. If combined with the `ruflo` marketplace, defer to `ruflo-agentdb` ADR-0001 §"Namespace convention" — there is no overlap (`ruview-*` vs. `ruflo-*`).
## Verification
```bash
bash plugins/ruview/scripts/smoke.sh
```
Structural contract: plugin.json has `version` + `keywords` and does **not** enumerate skills/commands/agents; every skill/command/agent file exists with valid frontmatter; README has a Compatibility section and a Namespace coordination block; ADR-0001 exists with status `Proposed`; no wildcard tools in skills; Codex mirror present **and parity** — every `commands/<name>.md` has a matching `codex/prompts/<name>.md`.
## Architecture Decisions
- [`docs/adrs/0001-ruview-plugin-contract.md`](docs/adrs/0001-ruview-plugin-contract.md) — plugin contract (Proposed): structure, namespace, compatibility surface, smoke scope, Codex mirror policy.
## Hardware note
`COM8` is the default ESP32 serial port in this plugin's docs — confirmed against an attached **ESP32-S3** (USB VID:PID `303A:1001`, Espressif) running the RuView CSI firmware (live `adaptive_ctrl` ticks + `csi_collector: CSI cb #… len=128 …` on the serial monitor). The repo's `CLAUDE.local.md` historically referenced `COM7`; some README snippets reference `COM9`. Always confirm the actual port (`python -c "import serial.tools.list_ports as l; print([p.device for p in l.comports()])"`, or Device Manager) before flashing. On Windows, `provision.py --help` needs `PYTHONUTF8=1` to print (non-ASCII in the help text); the build/flash path goes through the Python-subprocess pattern in `CLAUDE.local.md` (ESP-IDF v5.4 ≠ Git Bash).
@@ -0,0 +1,29 @@
---
name: ruview-config-engineer
description: Configures RuView deployments — ESP32 firmware variants (8MB/4MB/Heltec), sdkconfig, NVS provisioning, WiFi channel / MAC-filter overrides (ADR-060), edge intelligence modules (ADR-041), sensing-server flags, multi-node mesh, and Cognitum Seed integration. Use to set up or tune a RuView system without changing source code.
model: sonnet
---
# RuView Config Engineer
You own everything tunable in a RuView deployment — from a single provision flag to a full mesh + Cognitum Seed.
## What you do
- **Firmware build config:** pick the sdkconfig variant (`sdkconfig.defaults.template` for 8MB no-mock, `sdkconfig.defaults.4mb`, `sdkconfig.defaults.heltec_n16r2`), copy it to `sdkconfig.defaults`, rebuild via the Windows Python-subprocess command (`CLAUDE.local.md`). **Never test in mock mode.**
- **Device runtime config (`provision.py`):** writes the `csi_cfg` NVS namespace over serial. Always check `python firmware/esp32-csi-node/provision.py --help` first (on Windows: `PYTHONUTF8=1 PYTHONIOENCODING=utf-8 python …` — non-ASCII help text). Flags: WiFi/sink (`--ssid` `--password` `--target-ip` `--target-port` 5005 `--node-id`), TDM mesh (`--tdm-slot` `--tdm-total`), edge (`--edge-tier 0|1|2`), thresholds (`--pres-thresh` `--fall-thresh` 15000≈15 rad/s²), vitals (`--vital-win` `--vital-int` `--subk-count`), channel/hop (`--channel` `--filter-mac` `--hop-channels` `--hop-dwell`), Cognitum Seed (`--seed-url` `--seed-token` `--zone`), swarm (`--swarm-hb` `--swarm-ingest`), mode (`--dry-run` `--force-partial`). ⚠️ **Issue #391:** a flash replaces the *entire* `csi_cfg` namespace — keys not on the CLI are erased; pass the full set, warn before re-provisioning a working node. Fleet: `scripts/generate_nvs_matrix.py`.
- **Sensing server flags:** `cargo run -p wifi-densepose-sensing-server -- --help`; modes: live sink, `--pretrain`, `--train --save-rvf`, `--model X --embed`, `--model X --build-index env`.
- **Edge modules (ADR-041):** which modules ship in a build + their NVS thresholds; host-side mirrors in `scripts/*.js` (apnea, gait, material, passive-radar, mincut, fingerprint).
- **Multi-node mesh:** TDM + channel hopping (`wifi-densepose-hardware/src/esp32/`); all nodes → same sink IP.
- **Cognitum Seed:** bridge ESP32 → Seed for RVF memory / kNN / Ed25519 witness chain; `scripts/rf-scan.js`, `scripts/snn-csi-processor.js`; `docs/tutorials/cognitum-seed-pretraining.md`.
## Workflow
1. Run the `ruview-configure` skill for the canonical procedures; use `ruview-hardware-setup` for the actual flash/monitor loop.
2. Make the smallest config change that achieves the goal; verify on real hardware (COM8) with real WiFi CSI.
3. After any firmware/config change that affects behaviour, run `cd v2 && cargo test --workspace --no-default-features` and `python archive/v1/data/proof/verify.py`, then regenerate the witness bundle if needed (`/ruview-verify`).
## Ground rules
- Read before edit. No new files unless required. No secrets / `.env` in commits.
- Reference ADR-022, 028, 041, 060, 061, 081; `CLAUDE.md` / `CLAUDE.local.md`; `example.env`.
@@ -0,0 +1,28 @@
---
name: ruview-onboarding-guide
description: Walks a newcomer through RuView (WiFi-DensePose) from zero to a working sensing setup — picks the right path (Docker demo / repo build / live ESP32), explains the physics and the hardware caveats, and points to the next steps. Use when someone is new to the project or asks "how do I get started".
model: sonnet
---
# RuView Onboarding Guide
You help people get started with **RuView** — WiFi-based human sensing from Channel State Information (CSI). Be concrete and friendly; assume the person has not used the project before.
## Your job
1. **Figure out what they have.** No hardware? → Docker demo. Want to build? → Rust workspace + Python proof. Have an ESP32-S3/C6? → flash + provision + sensing server.
2. **Run the `ruview-quickstart` skill** for the canonical steps. For hardware, hand to `ruview-hardware-setup`.
3. **Set expectations honestly:**
- ESP32-C3 and the original ESP32 are **not supported** (single-core).
- One node = limited spatial resolution; 2+ nodes (or a Cognitum Seed) for good results.
- Camera-free pose is modest; camera-supervised training reaches 92.9% PCK@20 (ADR-079).
- Everything runs on the edge — no cloud, no cameras, no internet required.
4. **Explain the idea in one breath:** WiFi already fills the room with radio waves; people moving/breathing perturb them measurably; ESP32 captures CSI; RuView turns it into who's there / what they're doing / are they okay.
5. **Hand off** to the right next skill/command: `ruview-configure`, `ruview-applications` (`/ruview-app`), `ruview-model-training` (`/ruview-train`), `ruview-advanced-sensing` (`/ruview-advanced`), `ruview-verify` (`/ruview-verify`).
## Ground rules
- Read a file before editing it. Don't create files unless asked.
- Don't commit secrets or `.env`.
- Use the project's own tooling: `cargo`, `python`, `idf.py` (via the Python-subprocess on Windows — see `CLAUDE.local.md`), `docker`, `node` scripts.
- Reference, don't paraphrase: `README.md`, `docs/user-guide.md`, `docs/build-guide.md`, `docs/TROUBLESHOOTING.md`, `docs/tutorials/`, `examples/`.
@@ -0,0 +1,40 @@
---
name: ruview-training-engineer
description: Trains, evaluates, and ships RuView models — camera-free WiFlow pose, camera-supervised pose (MediaPipe + ESP32 CSI → 92.9% PCK@20, ADR-079), RuVector contrastive embeddings (AETHER, ADR-024), domain generalization (MERIDIAN, ADR-027), local SNN environment adaptation, GPU training on GCloud, and Hugging Face publishing. Use for any model-building task.
model: sonnet
---
# RuView Training Engineer
You build and ship RuView models. Know the tracks, the data layout, and the validation gate.
## Tracks
- **A — camera-free WiFlow pose:** `cargo run -p wifi-densepose-sensing-server -- --pretrain --dataset data/csi/ --pretrain-epochs 50``-- --train --dataset data/mmfi/ --epochs 100 --save-rvf model.rvf`. ~84 s on M4 Pro; modest accuracy. Bench: `node scripts/benchmark-wiflow.js`; eval: `node scripts/eval-wiflow.js`.
- **B — camera-supervised pose (ADR-079):** `python scripts/collect-ground-truth.py` (MediaPipe), `python scripts/collect-training-data.py` (CSI), `node scripts/align-ground-truth.js`, train on `data/paired/`, eval `eval-wiflow.js` → reports PCK@20. ~19 min on a laptop; 92.9% PCK@20. Needs `data/pose_landmarker_lite.task`.
- **C — RuVector embeddings (AETHER ADR-024):** `wifi-densepose-train` + `wifi-densepose-ruvector` (RuVector v2.0.4); `-- --model model.rvf --embed`, `-- --build-index env`. Spectrogram embeddings: ADR-076.
- **D — domain generalization (MERIDIAN ADR-027):** domain-gen options in the training pipeline; `ruview_metrics`.
- **E — local SNN adaptation:** `node scripts/snn-csi-processor.js --port 5006`; adapts <30 s; ADR-084/085 (RaBitQ), ADR-086 (novelty gate); `docs/tutorials/cognitum-seed-pretraining.md`.
## GPU & publishing
- GCloud (project `cognitum-20260110`, L4/A100/H100): `bash scripts/gcloud-train.sh [--dry-run] [--gpu l4|a100|h100] [--hours N] [--config FILE] [--sweep] [--keep-vm]`. VM auto-deletes. Local Mac: `bash scripts/mac-mini-train.sh`. Bench: `python scripts/benchmark-model.py`.
- Publish: `python scripts/publish-huggingface.py` (or the `.sh`); `docs/huggingface/`.
## Data
`data/recordings/` raw CSI · `data/csi/` pretrain · `data/mmfi/` MM-Fi · `data/paired/` camera↔CSI · `data/ground-truth/` MediaPipe landmarks · `data/pose_landmarker_lite.task` · `models/`. Record more: `python scripts/record-csi-udp.py`.
## Validation gate (always, after a training change)
1. `cd v2 && cargo test --workspace --no-default-features` — 1,400+ pass, 0 fail.
2. `cd .. && python archive/v1/data/proof/verify.py` — VERDICT: PASS.
3. Regenerate the witness bundle if tests/proof changed (`bash scripts/generate-witness-bundle.sh`; self-verify 7/7).
## Workflow
Run the `ruview-model-training` skill for canonical commands. Make the change, train, evaluate with the right metric (PCK@20 for pose), run the validation gate, then hand off to `/ruview-verify`. Read before edit; no new files unless required; no secrets in commits.
## Reference
ADRs 015, 016, 017, 024, 027, 076, 079, 084, 085, 095, 096; crates `wifi-densepose-train`, `-nn`, `-ruvector`, `-sensing-server`; `CLAUDE.md` build/test section.
+55
View File
@@ -0,0 +1,55 @@
# AGENTS.md — RuView (WiFi-DensePose)
Project rules for Codex (and any agent) working in the `ruvnet/RuView` / `wifi-densepose` repo. Mirrors the Claude Code `ruview` plugin.
## What this repo is
WiFi-based human sensing from Channel State Information (CSI). Dual codebase: Rust port in `v2/` (15 crates), Python v1 in `archive/v1/`. ESP32-S3 / ESP32-C6 firmware in `firmware/esp32-csi-node/`. 96 ADRs in `docs/adr/`.
## Hard rules
- Do exactly what's asked — nothing more, nothing less.
- Never create files (especially `*.md`/README) unless required for the task. Prefer editing an existing file.
- Never save working files/tests/notes to the repo root — use `v2/crates/`, `tests/`, `docs/`, `scripts/`, `examples/`.
- Read a file before editing it.
- Never commit secrets, credentials, or `.env`.
- Validate user input at system boundaries; sanitize file paths.
- ESP32-C3 and the original ESP32 are **not supported** (single-core). Use ESP32-S3 (8MB/4MB) or ESP32-C6.
## Build & test
```bash
# Rust workspace (1,400+ tests, ~2 min)
cd v2 && cargo test --workspace --no-default-features
# Single crate, no GPU
cargo check -p wifi-densepose-train --no-default-features
# Deterministic Python pipeline proof (SHA-256 Trust Kill Switch)
python archive/v1/data/proof/verify.py # must print VERDICT: PASS
# Python v1 tests
cd archive/v1 && python -m pytest tests/ -x -q
```
## ESP32 firmware (Windows)
ESP-IDF v5.4 does **not** work under Git Bash/MSYS2 and `cmd.exe /C` hangs when called from bash. Build/flash via the **Espressif Python venv as a subprocess with `MSYSTEM*` env vars stripped** — the exact command is in `CLAUDE.local.md`. Default ESP32 serial port: **COM8** (confirm with `mode` / Device Manager — older docs say COM7 or COM9). Provision WiFi: `python firmware/esp32-csi-node/provision.py --port COM8 --ssid ... --password ... --target-ip ... [--channel N] [--filter-mac MAC]`. Serial monitor via pyserial, not `idf.py monitor`. Always test with real WiFi CSI, never mock mode.
## Witness verification (ADR-028)
After significant changes: run the Rust tests + Python proof, then `bash scripts/generate-witness-bundle.sh`, then `cd dist/witness-bundle-ADR028-*/ && bash VERIFY.sh` (7/7 PASS). Pre-merge checklist lives in `CLAUDE.md`.
## Prompt files in `codex/prompts/`
| Prompt | Purpose |
|--------|---------|
| `ruview-start` | Onboarding — Docker demo / repo build / live ESP32 |
| `ruview-flash` | Build + flash ESP32 firmware (8MB / 4MB) |
| `ruview-provision` | Provision WiFi creds + sink IP + channel/MAC overrides |
| `ruview-app` | Run a sensing application (presence / vitals / pose / sleep / MAT / point cloud) |
| `ruview-train` | Train / evaluate / publish a model (incl. GPU on GCloud) |
| `ruview-verify` | Run the trust pipeline + pre-merge checklist |
Install: copy `codex/prompts/*.md` into `~/.codex/prompts/`, or run Codex with this directory on its prompt path.
## Reference
`README.md`, `docs/user-guide.md`, `docs/wifi-mat-user-guide.md`, `docs/build-guide.md`, `docs/TROUBLESHOOTING.md`, `docs/adr/`, `docs/tutorials/`, `examples/`, `CLAUDE.md`, `CLAUDE.local.md`.
+47
View File
@@ -0,0 +1,47 @@
# RuView prompts for Codex (OpenAI CLI)
This directory mirrors the Claude Code `ruview` plugin's operator commands as Codex prompts, plus an `AGENTS.md` carrying the RuView project rules.
## Contents
| File | Purpose |
|------|---------|
| `AGENTS.md` | Project rules — repo layout, hard rules, build/test, ESP32 firmware on Windows, witness verification |
| `prompts/ruview-start.md` | Onboarding — Docker demo / repo build / live ESP32 |
| `prompts/ruview-flash.md` | Build + flash ESP32 firmware (8MB / 4MB) |
| `prompts/ruview-provision.md` | Provision WiFi creds + sink IP + channel/MAC overrides |
| `prompts/ruview-app.md` | Run a sensing application (presence / vitals / pose / sleep / MAT / point cloud) |
| `prompts/ruview-train.md` | Train / evaluate / publish a model (incl. GPU on GCloud) |
| `prompts/ruview-advanced.md` | Multistatic / tomography / cross-viewpoint / field-model / mesh-security |
| `prompts/ruview-verify.md` | Run the trust pipeline + pre-merge checklist |
Prompt parity with the Claude Code plugin is enforced by `plugins/ruview/scripts/smoke.sh` (every `commands/<name>.md` must have a matching `codex/prompts/<name>.md`).
## Install
**Per-user prompts** — copy the prompt files into Codex's prompt directory:
```bash
mkdir -p ~/.codex/prompts
cp plugins/ruview/codex/prompts/*.md ~/.codex/prompts/
# now in the codex TUI: /ruview-start /ruview-flash /ruview-app /ruview-train /ruview-verify /ruview-advanced
```
**Project rules** — point Codex at the `AGENTS.md`. Codex auto-discovers an `AGENTS.md` at the repo root and in the working directory; either symlink it or copy it:
```bash
ln -s plugins/ruview/codex/AGENTS.md AGENTS.md # repo root (if you don't already have one)
# — or, if a root AGENTS.md exists, append the relevant sections from plugins/ruview/codex/AGENTS.md
```
**Config (optional)** — to keep prompts in-repo instead of `~/.codex/prompts`, add to `~/.codex/config.toml`:
```toml
# Codex reads prompts from ~/.codex/prompts by default; symlinking keeps them versioned with the repo:
# ln -s "$PWD/plugins/ruview/codex/prompts" ~/.codex/prompts/ruview (then prompts appear as /ruview/ruview-start, etc.)
```
## Notes
- The Codex mirror is the **operator-facing subset** — the seven `/ruview-*` commands. The Claude Code plugin additionally ships skills (`ruview-quickstart`, `ruview-hardware-setup`, `ruview-configure`, `ruview-applications`, `ruview-model-training`, `ruview-advanced-sensing`, `ruview-cli-api`, `ruview-mmwave`, `ruview-verify`) and agents (`ruview-onboarding-guide`, `ruview-config-engineer`, `ruview-training-engineer`) that have no Codex equivalent — their content is folded into `AGENTS.md` and the prompt files.
- On Windows, ESP-IDF firmware builds go through the Python-subprocess pattern documented in `CLAUDE.local.md` (Git Bash / MSYS2 is not supported by ESP-IDF v5.4). Default ESP32 serial port: **COM8**.
@@ -0,0 +1,15 @@
# /ruview-advanced — advanced RuView capabilities
Drive RuView's research-grade / multi-node features. Topic: `$ARGUMENTS` (one of `multistatic`, `cross-viewpoint`, `tomography`, `field-model`, `intention`, `adversarial`, `security`; if empty, ask).
- **multistatic** (ADR-029) — treat every WiFi link in range (incl. neighbours' APs) as a bistatic radar pair, then fuse. `v2/crates/wifi-densepose-signal/src/ruvsense/multistatic.rs` (attention-weighted fusion, geometric diversity), `phase_align.rs` (iterative LO phase-offset, circular mean), `multiband.rs`, `coherence.rs` / `coherence_gate.rs` (Z-score scoring; Accept / PredictOnly / Reject / Recalibrate).
- **cross-viewpoint** (ADR-016 viewpoint module) — combine 2+ nodes geometrically. `v2/crates/wifi-densepose-ruvector/src/viewpoint/`: `attention.rs` (CrossViewpointAttention, GeometricBias, softmax with `G_bias`), `geometry.rs` (GeometricDiversityIndex, CramérRao bounds, Fisher Information), `coherence.rs` (phase-phasor coherence, hysteresis gate), `fusion.rs` (MultistaticArray aggregate root). Explore geometry first: `node scripts/mesh-graph-transformer.js`, `node scripts/deep-scan.js`.
- **tomography** — `ruvsense/tomography.rs` reconstructs a voxel occupancy grid via an ISTA L1 solver (sparse — most voxels empty); pair with cross-viewpoint geometry for through-wall volumetric imaging. RuVector solver crates back the 114→56 subcarrier sparse interpolation.
- **field-model** (ADR-030) — `ruvsense/field_model.rs` builds an SVD eigenstructure of the room, persists it (RVF, ideally on a Cognitum Seed); new frames are projected against it and the residual is the perturbation. Survives restarts; answers "what's different from the empty-room baseline?"
- **intention** — `ruvsense/intention.rs`, pre-movement lead signals 200500 ms ahead.
- **adversarial** — `ruvsense/adversarial.rs`, rejects physically impossible signals + cross-checks multi-link consistency.
- **security** (ADR-032, multistatic mesh hardening) — using neighbour APs and pooling links across a mesh expands the attack surface. Mitigations: `adversarial.rs` + `coherence_gate.rs` quarantine (Reject / Recalibrate) + Ed25519 witness chain (ADR-028). Run a security review (`docs/security-audit-wasm-edge-vendor.md`); see `/ruview-verify`.
Also relevant: ADR-031 (sensing-first RF mode), ADR-081 (adaptive CSI mesh firmware kernel), ADR-083 (per-cluster π compute hop), ADR-095/096 (on-ESP32 temporal modeling, sparse GQA).
Validate: `cd v2 && cargo test -p wifi-densepose-signal --no-default-features && cargo test -p wifi-densepose-ruvector --no-default-features`, then `cd .. && python archive/v1/data/proof/verify.py`.
@@ -0,0 +1,13 @@
# /ruview-app — run a RuView sensing application
Run a RuView application. Which one: `$ARGUMENTS` (one of `presence`, `vitals`, `pose`, `sleep`, `environment`, `mat`, `pointcloud`, or a novel-RF app name; if empty, show the catalogue and ask).
- **presence / vitals / pose / environment** → `cd v2 && cargo run -p wifi-densepose-sensing-server` against a live ESP32 sink, or the Docker demo (`docker run -p 3000:3000 ruvnet/wifi-densepose:latest`) for simulated CSI. For environment also `-- --model model.rvf --build-index env`. Vitals: breathing 630 BPM (bandpass 0.10.5 Hz), heart rate 40120 BPM (bandpass 0.82.0 Hz), `wifi-densepose-vitals` crate (ADR-021). Pose: 17 COCO keypoints via WiFlow (ADR-059 live pipeline) — train for accuracy (`/ruview-train`).
- **sleep** → `examples/sleep/` + `node scripts/apnea-detector.js` (sleep-stage classification, apnea screening).
- **mat** (Mass Casualty Assessment — disaster survivor detection) → `wifi-densepose-mat` crate, `docs/wifi-mat-user-guide.md`.
- **pointcloud** → `python scripts/mmwave_fusion_bridge.py` (camera depth via MiDaS + WiFi CSI + mmWave radar → unified spatial model, ~22 ms, 19K+ pts/frame; ADR-094).
- **novel RF** → `scripts/passive-radar.js`, `material-classifier.js`, `device-fingerprint.js`, `mincut-person-counter.js`, `gait-analyzer.js` (ADR-077/078).
No hardware? Fall back to the Docker demo or `python examples/ruview_live.py`. Visualisers: `node scripts/csi-spectrogram.js`, `node scripts/csi-graph-visualizer.js`.
Help me pick: through-wall → presence/activity (≤5 m depth); stationary subject → vitals/sleep; need skeletons → pose (train it); search & rescue → MAT; best spatial accuracy → 2+ ESP32 nodes + cross-viewpoint fusion (`v2/crates/wifi-densepose-ruvector/src/viewpoint/`), optionally + Cognitum Seed. Examples: `examples/{environment,medical,sleep,stress,happiness-vector}/`.
@@ -0,0 +1,17 @@
# /ruview-flash — build + flash ESP32 firmware
Build and flash RuView ESP32 firmware. Variant + port: `$ARGUMENTS` (default `8mb`, port `COM8`).
1. **Variant.** `8mb` → ensure it builds from `firmware/esp32-csi-node/sdkconfig.defaults.template` (no mock — real WiFi CSI). `4mb``cp firmware/esp32-csi-node/sdkconfig.defaults.4mb firmware/esp32-csi-node/sdkconfig.defaults` first (display disabled, dual OTA via `partitions_4mb.csv`). `heltec``sdkconfig.defaults.heltec_n16r2`.
2. **Build (Windows).** ESP-IDF v5.4 does NOT work under Git Bash; `cmd.exe /C` hangs. Use the Espressif Python venv as a subprocess with `MSYSTEM*` env vars stripped — the exact command is in `CLAUDE.local.md` (`[python, idf_py, 'build']`, cwd = `firmware/esp32-csi-node`). Outputs in `firmware/esp32-csi-node/build/{bootloader/bootloader.bin, partition_table/partition-table.bin, esp32-csi-node.bin, ota_data_initial.bin}`.
3. **Flash.** Same subprocess with `[python, idf_py, '-p', 'COM8', 'flash']`, or:
```
python -m esptool --chip esp32s3 --port COM8 --baud 460800 write_flash \
0x0 firmware/esp32-csi-node/build/bootloader/bootloader.bin \
0x8000 firmware/esp32-csi-node/build/partition_table/partition-table.bin \
0xf000 firmware/esp32-csi-node/build/ota_data_initial.bin \
0x20000 firmware/esp32-csi-node/build/esp32-csi-node.bin
```
4. **Confirm.** Serial monitor via pyserial on `COM8` @ 115200 (NOT `idf.py monitor` — it hangs in a subprocess). Then `cd v2 && cargo run -p wifi-densepose-sensing-server` — frames should arrive. If not: re-run `/ruview-provision`, match the AP channel, drop any `--filter-mac`.
Never test in mock mode — the Kconfig fall-threshold bug only showed up with real CSI.
@@ -0,0 +1,25 @@
# /ruview-provision — provision an ESP32 sensing node
Write NVS config to a RuView ESP32 node. Args: `$ARGUMENTS` (expect `--port`, `--ssid`, `--password`, `--target-ip`, optional `--channel`, `--filter-mac`). Default port `COM8`.
First get the authoritative flag list: `python firmware/esp32-csi-node/provision.py --help` (on Windows prefix `PYTHONUTF8=1 PYTHONIOENCODING=utf-8` — the help text has non-ASCII and crashes under cp1252). Then run:
```
python firmware/esp32-csi-node/provision.py --port COM8 \
--ssid "<SSID>" --password "<PW>" --target-ip <SINK_IP> --target-port 5005 --node-id <0-255> \
[--channel <N>] [--filter-mac <AA:BB:CC:DD:EE:FF>] [--hop-channels 1,6,11 --hop-dwell 200] \
[--tdm-slot <i> --tdm-total <n>] [--edge-tier 0|1|2] [--pres-thresh 50] [--fall-thresh 15000] \
[--vital-win 300] [--vital-int 1000] [--subk-count 32] \
[--seed-url http://10.1.10.236 --seed-token <bearer> --zone lobby] [--swarm-hb 30] [--swarm-ingest 5] [--dry-run]
```
Trade-offs:
- `--channel <N>` pins the node to one WiFi channel (set it to the AP's channel). Omit it and pass `--hop-channels 1,6,11` for the firmware's multi-band hopping schedule (more sensing bandwidth, uses neighbour APs as illuminators; `--hop-dwell` ms per channel).
- `--filter-mac <MAC>` restricts CSI capture to one transmitter (cleaner signal); omit for all transmitters (more data, more noise).
- `--edge-tier` 0/1/2 = off / stats / vitals (ADR-041). `--tdm-slot`/`--tdm-total` slot a multi-node mesh. `--fall-thresh 15000` ≈ 15.0 rad/s² (raise to cut false falls).
⚠️ **Issue #391:** flashing rewrites the *entire* `csi_cfg` NVS namespace — every key not on the CLI is erased. Pass the full set you want; warn before re-provisioning a working node. `--dry-run` builds the NVS binary without flashing; `--force-partial` allows config without WiFi creds (knowingly).
Fleet provisioning: `python scripts/generate_nvs_matrix.py` (subprocess-first — the `esp_idf_nvs_partition_gen` API changed across versions).
Verify: serial monitor (pyserial on `COM8`, 115200) should show `adaptive_ctrl` ticks + `csi_collector: CSI cb #… len=128 rssi=… ch=…` lines; the sink `cd v2 && cargo run -p wifi-densepose-sensing-server` should report incoming UDP frames if `--target-ip` points at this host. If no frames: wrong channel, MAC filter too tight, target-ip not this host, or WiFi creds wrong — re-run with corrected args.
@@ -0,0 +1,11 @@
# /ruview-start — onboard onto RuView
Help me get started with RuView (WiFi-DensePose). Path: `$ARGUMENTS` (one of `docker`, `build`, `hardware`; if empty, ask which hardware I have).
- **docker** (no hardware): `docker pull ruvnet/wifi-densepose:latest && docker run -p 3000:3000 ruvnet/wifi-densepose:latest`, then open http://localhost:3000 (simulated CSI, full UI).
- **build** (from source): `cd v2 && cargo test --workspace --no-default-features`, then `cd .. && python archive/v1/data/proof/verify.py` (expect `VERDICT: PASS`). Single-crate sanity: `cargo check -p wifi-densepose-train --no-default-features`.
- **hardware** (ESP32-S3/C6): use `/ruview-flash` then `/ruview-provision`, then `cd v2 && cargo run -p wifi-densepose-sensing-server` to consume the UDP CSI stream. Also: `node scripts/rf-scan.js --port 5006`, `node scripts/snn-csi-processor.js --port 5006`.
Warn me about: ESP32-C3 / original ESP32 are unsupported (single-core); one node = limited spatial resolution (use 2+ or add a Cognitum Seed); camera-free pose is modest — camera-supervised training reaches 92.9% PCK@20 (ADR-079); no cloud/cameras/internet needed.
Then point me at next steps: `/ruview-app`, `/ruview-train`, `/ruview-verify`, and the configuration workflow (sdkconfig variants, NVS provisioning, edge modules, mesh, Cognitum Seed). Reference `README.md`, `docs/user-guide.md`, `docs/build-guide.md`, `docs/TROUBLESHOOTING.md`, `examples/`.
@@ -0,0 +1,14 @@
# /ruview-train — train a RuView model
Train / evaluate / publish a RuView model. Track: `$ARGUMENTS` (one of `camera-free`, `camera-supervised`, `embeddings`, `domain-gen`, `snn`, `gpu`; if empty, ask).
- **camera-free** (WiFlow pose, no labels): `cd v2 && cargo run -p wifi-densepose-sensing-server -- --pretrain --dataset data/csi/ --pretrain-epochs 50`, then `-- --train --dataset data/mmfi/ --epochs 100 --save-rvf model.rvf`. ~84 s on M4 Pro, modest accuracy. Bench `node scripts/benchmark-wiflow.js`, eval `node scripts/eval-wiflow.js`.
- **camera-supervised** (ADR-079, 92.9% PCK@20, ~19 min): `python scripts/collect-ground-truth.py` (MediaPipe landmarks; needs `data/pose_landmarker_lite.task`), `python scripts/collect-training-data.py` (CSI capture), `node scripts/align-ground-truth.js` (timestamp align), then `cd v2 && cargo run -p wifi-densepose-sensing-server -- --train --dataset data/paired/ --epochs <N> --save-rvf model.rvf`, eval `node scripts/eval-wiflow.js` (reports PCK@20).
- **embeddings** (AETHER ADR-024 / spectrogram ADR-076): `wifi-densepose-train` + `wifi-densepose-ruvector`; `-- --model model.rvf --embed`, `-- --model model.rvf --build-index env`. 171K emb/s on M4 Pro.
- **domain-gen** (MERIDIAN ADR-027): domain-generalization options in the training pipeline + `ruview_metrics`.
- **snn** (local env adaptation, <30 s): `node scripts/snn-csi-processor.js --port 5006`; `docs/tutorials/cognitum-seed-pretraining.md`; ADR-084/085 (RaBitQ), ADR-086 (novelty gate).
- **gpu**: `gcloud auth login && gcloud config set project cognitum-20260110`, then `bash scripts/gcloud-train.sh --dry-run` (smoke), `bash scripts/gcloud-train.sh --gpu l4 --hours 2` (proto, ~$0.80/hr), `bash scripts/gcloud-train.sh --gpu a100 --config scripts/training-config-sweep.json` (~$3.60/hr), `bash scripts/gcloud-train.sh --sweep` (full sweep). VM auto-deletes unless `--keep-vm`. Local Mac: `bash scripts/mac-mini-train.sh`. Bench: `python scripts/benchmark-model.py`.
Data: `data/recordings/` raw CSI · `data/csi/` pretrain · `data/mmfi/` MM-Fi · `data/paired/` camera↔CSI · `data/ground-truth/` MediaPipe · `models/` artifacts. Record more: `python scripts/record-csi-udp.py`.
After training: `cd v2 && cargo test --workspace --no-default-features`, `cd .. && python archive/v1/data/proof/verify.py` (VERDICT: PASS). Publish: `python scripts/publish-huggingface.py` (or `.sh`; `docs/huggingface/`). Then run `/ruview-verify`.
@@ -0,0 +1,12 @@
# /ruview-verify — run the RuView trust pipeline
Verify a RuView build. Scope: `$ARGUMENTS` (one of `tests`, `proof`, `bundle`, `all`; default `all`).
1. **tests**`cd v2 && cargo test --workspace --no-default-features` → must be 1,400+ passed, 0 failed (~2 min). Single-crate: `cargo test -p wifi-densepose-signal --no-default-features`, etc.
2. **proof**`cd .. && python archive/v1/data/proof/verify.py` → must print `VERDICT: PASS`. If a hash mismatch from a legitimate numpy/scipy bump: `python archive/v1/data/proof/verify.py --generate-hash`, then re-run. Optional: `cd archive/v1 && python -m pytest tests/ -x -q`.
3. **bundle**`bash scripts/generate-witness-bundle.sh` produces `dist/witness-bundle-ADR028-<sha>.tar.gz` (WITNESS-LOG-028.md, ADR-028 audit, proof, rust test log, firmware hash manifest, crate versions, VERIFY.sh). Then `cd dist/witness-bundle-ADR028-*/ && bash VERIFY.sh` → must be 7/7 PASS.
4. **all** — do 1→3 in order.
If this follows a code change, walk the pre-merge checklist from `CLAUDE.md`: Rust tests pass; Python proof passes; README updated if scope changed; CLAUDE.md updated if scope changed; CHANGELOG `[Unreleased]` entry; `docs/user-guide.md` updated if new data sources/CLI flags/setup; ADR count bumped in README if a new ADR added; witness bundle regenerated if tests/proof hash changed; Docker image rebuilt only if Dockerfile/deps/runtime changed; crate publishing only if a published crate's public API changed (publish in dependency order — see CLAUDE.md); `.gitignore` updated for new artifacts; security review for new hardware/network-boundary modules.
For security-related changes also run `npx @claude-flow/cli@latest security scan`. QEMU firmware CI (ADR-061): local helpers `scripts/qemu-esp32s3-test.sh`, `qemu-mesh-test.sh`, `qemu-chaos-test.sh`, `install-qemu.sh`.
@@ -0,0 +1,19 @@
---
description: Use advanced RuView capabilities — multistatic sensing, cross-viewpoint fusion, RF tomography, persistent field model, intention signals, adversarial detection, mesh security.
argument-hint: "[multistatic|cross-viewpoint|tomography|field-model|intention|adversarial|security]"
---
# /ruview-advanced
Drive RuView's research-grade / multi-node features.
1. Invoke the **`ruview-advanced-sensing`** skill.
2. Route on `$ARGUMENTS`:
- **multistatic** (ADR-029) — `wifi-densepose-signal/src/ruvsense/multistatic.rs`, `phase_align.rs`, `coherence_gate.rs`; neighbours' APs as illuminators.
- **cross-viewpoint** (ADR-016 viewpoint) — `wifi-densepose-ruvector/src/viewpoint/`; needs 2+ nodes; `node scripts/mesh-graph-transformer.js`.
- **tomography** — `ruvsense/tomography.rs` (ISTA L1 voxel solver) + cross-viewpoint geometry; through-wall volumetric.
- **field-model** (ADR-030) — `ruvsense/field_model.rs`, SVD room eigenstructure persisted to RVF (Cognitum Seed); residual = perturbation.
- **intention** — `ruvsense/intention.rs`, 200500 ms pre-movement lead signals.
- **adversarial** — `ruvsense/adversarial.rs`, physically-impossible-signal + multi-link consistency checks.
- **security** (ADR-032) — mesh hardening: adversarial gate + coherence quarantine + Ed25519 witness chain; run a security review (`docs/security-audit-wasm-edge-vendor.md`), see `/ruview-verify`.
3. Validate: `cd v2 && cargo test -p wifi-densepose-signal --no-default-features && cargo test -p wifi-densepose-ruvector --no-default-features`, then `python archive/v1/data/proof/verify.py`.
+18
View File
@@ -0,0 +1,18 @@
---
description: Run a RuView sensing application — presence, vitals, pose, sleep, environment mapping, MAT, point cloud, or a novel RF app.
argument-hint: "[presence|vitals|pose|sleep|environment|mat|pointcloud|<name>]"
---
# /ruview-app
Launch a RuView application.
1. Invoke the **`ruview-applications`** skill.
2. Map `$ARGUMENTS` to an application; if empty, show the catalogue and ask. Quick mappings:
- `presence` / `vitals` / `pose` / `environment``cd v2 && cargo run -p wifi-densepose-sensing-server` (live ESP32 sink) or the Docker demo for simulated CSI; for environment also `--build-index env`.
- `sleep``examples/sleep/` + `node scripts/apnea-detector.js`.
- `mat` (Mass Casualty Assessment) → `wifi-densepose-mat` crate, `docs/wifi-mat-user-guide.md`.
- `pointcloud``python scripts/mmwave_fusion_bridge.py` (camera depth + CSI + mmWave).
- novel RF → `scripts/passive-radar.js`, `material-classifier.js`, `device-fingerprint.js`, `mincut-person-counter.js`.
3. If no hardware: fall back to `docker run -p 3000:3000 ruvnet/wifi-densepose:latest` or `python examples/ruview_live.py`.
4. Help pick the right modality (through-wall → presence/activity; stationary subject → vitals/sleep; need skeletons → pose, train it for accuracy; search & rescue → MAT; best accuracy → 2+ nodes + cross-viewpoint fusion via `/ruview-advanced`).
+15
View File
@@ -0,0 +1,15 @@
---
description: Build and flash RuView ESP32 firmware (8MB or 4MB), then confirm the CSI stream.
argument-hint: "[8mb|4mb] [COM port]"
---
# /ruview-flash
Build + flash RuView firmware to an ESP32-S3 sensing node.
1. Invoke the **`ruview-hardware-setup`** skill.
2. Determine variant from `$ARGUMENTS` (default `8mb`). For `4mb`: `cp firmware/esp32-csi-node/sdkconfig.defaults.4mb firmware/esp32-csi-node/sdkconfig.defaults` first. For `8mb`: ensure it's built from `sdkconfig.defaults.template` (no mock).
3. Build using the **Python-subprocess** command from `CLAUDE.local.md` (ESP-IDF v5.4 does NOT work under Git Bash — strip `MSYSTEM*` env vars). Never use `cmd.exe /C` from bash.
4. Flash: same subprocess, `[python, idf_py, '-p', '<COM port>', 'flash']` (default port **COM8**), or `python -m esptool ... write_flash ...` with the four binaries.
5. Confirm: serial monitor via pyserial (not `idf.py monitor`), then `cd v2 && cargo run -p wifi-densepose-sensing-server` to see frames arrive.
6. If no frames: re-run `/ruview-provision`, check channel matches the AP, drop any `--filter-mac`.
@@ -0,0 +1,24 @@
---
description: Provision WiFi credentials, sink IP, and optional channel / MAC-filter overrides onto a RuView ESP32 node.
argument-hint: "--port COM8 --ssid ... --password ... --target-ip ... [--channel N] [--filter-mac AA:BB:..]"
---
# /ruview-provision
Write NVS config to an ESP32 sensing node.
1. Invoke the **`ruview-configure`** skill (§"Runtime device config" — has the full `provision.py` flag table).
2. Run `python firmware/esp32-csi-node/provision.py --help` for the authoritative options (on Windows: `PYTHONUTF8=1 PYTHONIOENCODING=utf-8 python …` — the help text has non-ASCII). Collect any missing params (port — default **COM8**, SSID, password, target sink IP, `--target-port` default 5005, `--node-id`).
3. Run:
```bash
python firmware/esp32-csi-node/provision.py --port <PORT> \
--ssid "<SSID>" --password "<PW>" --target-ip <IP> --target-port 5005 --node-id <0-255> \
[--channel <N>] [--filter-mac <MAC>] [--hop-channels 1,6,11 --hop-dwell 200] \
[--tdm-slot <i> --tdm-total <n>] [--edge-tier {0|1|2}] [--pres-thresh 50] [--fall-thresh 15000] \
[--vital-win 300] [--vital-int 1000] [--subk-count 32] \
[--seed-url http://… --seed-token … --zone lobby] [--swarm-hb 30] [--swarm-ingest 5] [--dry-run]
```
4. Explain trade-offs: `--channel` pins the node (AP's channel) vs. `--hop-channels` for ADR-061 multi-freq hopping; `--filter-mac` restricts to one transmitter vs. omit for all (more data, more noise); `--edge-tier` 0/1/2 = off/stats/vitals; `--tdm-slot`/`--tdm-total` slot a multi-node mesh.
5. ⚠️ **Issue #391**: flashing rewrites the *entire* `csi_cfg` NVS namespace — every key not on the CLI is erased. Pass the full set you want; warn the user before re-provisioning a working node. `--force-partial` bypasses the WiFi-creds requirement (knowingly). `--dry-run` builds the NVS binary without flashing.
6. Fleet provisioning: `scripts/generate_nvs_matrix.py` (subprocess-first).
7. Verify: serial monitor (pyserial on the port, 115200) should show `adaptive_ctrl` ticks + `csi_collector: CSI cb #… len=128 …` lines; the sink (`cd v2 && cargo run -p wifi-densepose-sensing-server`) should report incoming UDP frames if `--target-ip` points at this host.
+16
View File
@@ -0,0 +1,16 @@
---
description: Get started with RuView — pick the fastest path (Docker demo, repo build, or live ESP32) and walk through it.
argument-hint: "[docker|build|hardware]"
---
# /ruview-start
Onboard the user onto RuView (WiFi-DensePose).
1. Invoke the **`ruview-quickstart`** skill.
2. If `$ARGUMENTS` names a tier (`docker`, `build`, `hardware`), go straight to it; otherwise ask which hardware they have:
- **No hardware** → Tier 0: `docker run -p 3000:3000 ruvnet/wifi-densepose:latest`, open `http://localhost:3000`.
- **Want to build from source** → Tier 1: `cd v2 && cargo test --workspace --no-default-features`, then `python archive/v1/data/proof/verify.py`.
- **Have an ESP32-S3 / C6** → Tier 2: hand off to `/ruview-flash` then `/ruview-provision`, then `cargo run -p wifi-densepose-sensing-server`.
3. Warn about the gotchas: ESP32-C3 / original ESP32 unsupported; single node = limited spatial resolution; camera-free pose is modest (use camera-supervised for 92.9% PCK@20).
4. Point to next steps: `/ruview-app`, `/ruview-train`, `/ruview-advanced`, `/ruview-verify`, and the `ruview-configure` skill.
+18
View File
@@ -0,0 +1,18 @@
---
description: Train a RuView model — camera-free WiFlow pose, camera-supervised pose (92.9% PCK@20), RuVector embeddings, domain generalization, local SNN, with optional GPU on GCloud.
argument-hint: "[camera-free|camera-supervised|embeddings|domain-gen|snn|gpu] [--epochs N]"
---
# /ruview-train
Train, fine-tune, evaluate, or publish a RuView model.
1. Invoke the **`ruview-model-training`** skill.
2. Pick the track from `$ARGUMENTS`; if empty, ask which:
- **camera-free** (Track A) — `cargo run -p wifi-densepose-sensing-server -- --pretrain --dataset data/csi/ --pretrain-epochs 50` then `-- --train --dataset data/mmfi/ --epochs 100 --save-rvf model.rvf`. ~84 s on M4 Pro, modest accuracy.
- **camera-supervised** (Track B, ADR-079) — `python scripts/collect-ground-truth.py`, `python scripts/collect-training-data.py`, `node scripts/align-ground-truth.js`, then train on `data/paired/`, eval with `node scripts/eval-wiflow.js`. ~19 min, 92.9% PCK@20. Needs `data/pose_landmarker_lite.task`.
- **embeddings** (Track C, AETHER ADR-024) — `wifi-densepose-train` + `wifi-densepose-ruvector`; `-- --model model.rvf --embed`, `-- --build-index env`.
- **domain-gen** (Track D, MERIDIAN ADR-027) / **snn** (Track E) — `node scripts/snn-csi-processor.js --port 5006`; cognitum-seed-pretraining tutorial.
- **gpu** — `gcloud config set project cognitum-20260110`; `bash scripts/gcloud-train.sh --gpu l4 --hours 2` (or `--gpu a100 --sweep`, `--dry-run` to smoke-test). VM auto-deletes unless `--keep-vm`.
3. After training: `cd v2 && cargo test --workspace --no-default-features`, `python archive/v1/data/proof/verify.py`. To publish: `python scripts/publish-huggingface.py`.
4. Hand off to `/ruview-verify` for the witness bundle.
+17
View File
@@ -0,0 +1,17 @@
---
description: Verify a RuView build — Rust tests, deterministic Python proof, firmware hashes, ADR-028 witness bundle + self-verification, and the pre-merge checklist.
argument-hint: "[tests|proof|bundle|all]"
---
# /ruview-verify
Run RuView's trust pipeline.
1. Invoke the **`ruview-verify`** skill.
2. Based on `$ARGUMENTS` (default `all`):
- **tests** — `cd v2 && cargo test --workspace --no-default-features` (1,400+ pass, 0 fail).
- **proof** — `python archive/v1/data/proof/verify.py` (must print `VERDICT: PASS`; if hash drift from a legit numpy/scipy bump, `--generate-hash` then re-run). Optionally `cd archive/v1 && python -m pytest tests/ -x -q`.
- **bundle** — `bash scripts/generate-witness-bundle.sh`, then `cd dist/witness-bundle-ADR028-*/ && bash VERIFY.sh` (must be 7/7 PASS).
- **all** — do all of the above in order.
3. If this follows a code change, walk the **pre-merge checklist** from `CLAUDE.md` (README/CLAUDE.md/CHANGELOG/user-guide updates, ADR count, witness bundle regen, Docker rebuild only if needed, crate publishing in dependency order, `.gitignore`, security review for hardware/network modules).
4. For security-related changes also run `npx @claude-flow/cli@latest security scan`.
@@ -0,0 +1,43 @@
# ADR-0001 — ruview plugin contract
- **Status:** Proposed
- **Date:** 2026-05-11
- **Scope:** `plugins/ruview` (and the repo-root `.claude-plugin/marketplace.json` that lists it)
## Context
RuView (WiFi-DensePose) is a large dual-codebase project (Rust `v2/`, Python `archive/v1/`, ESP32 firmware, 96 ADRs). Newcomers and operators repeatedly re-derive the same workflows: spin up the Docker demo, flash and provision an ESP32, run a sensing application, train a pose model, run the witness verification. We want those workflows packaged as a single discoverable Claude Code plugin (and mirrored for Codex), spanning practical → advanced.
## Decision
1. **One mega-plugin, marketplace-listed from the repo root.** A single plugin `ruview` under `plugins/ruview/`, listed by `.claude-plugin/marketplace.json` **at the repo root** (marketplace name `ruview`, plugin `source: "./plugins/ruview"`). The manifest sits at the repo root so `claude plugin marketplace add ruvnet/RuView` (and `/plugin marketplace add ruvnet/RuView` in Claude Code) resolve it — Claude Code looks for `.claude-plugin/marketplace.json` at the cloned repo's root, not in subdirectories. No sub-plugins; the breadth is organized by skill instead.
2. **Directory contract.**
```
.claude-plugin/marketplace.json # REPO ROOT — marketplace name `ruview`, plugin source ./plugins/ruview
plugins/ruview/.claude-plugin/plugin.json # name, description, version, author, homepage, license, keywords — NO skills/commands/agents arrays
plugins/ruview/skills/<name>/SKILL.md # frontmatter: name, description, allowed-tools
plugins/ruview/commands/<name>.md # frontmatter: description (+ argument-hint)
plugins/ruview/agents/<name>.md # frontmatter: name, description, model
plugins/ruview/docs/adrs/0001-ruview-plugin-contract.md
plugins/ruview/scripts/smoke.sh # structural contract
plugins/ruview/codex/AGENTS.md + codex/README.md + codex/prompts/*.md # Codex mirror
plugins/ruview/README.md # Compatibility + Namespace coordination + Verification + ADR sections
```
Skills/commands/agents are **auto-discovered** from the directory tree — they are deliberately *not* enumerated in `plugin.json`.
3. **Shell-first skills.** Skills drive RuView's own tooling — `cargo`, `python`, `idf.py` (via the Windows Python-subprocess pattern in `CLAUDE.local.md`), `docker`, `node` scripts. `allowed-tools` is limited to core tools (`Bash Read Write Edit Glob Grep`); **no `mcp__claude-flow__*` dependency** and **no wildcard tools**. The only external CLI referenced is `npx @claude-flow/cli@latest security scan`, and only as an optional step for security changes.
4. **Namespace.** The plugin claims the `ruview-*` namespace for skills (`ruview-quickstart`, `ruview-hardware-setup`, `ruview-configure`, `ruview-applications`, `ruview-model-training`, `ruview-advanced-sensing`, `ruview-cli-api`, `ruview-mmwave`, `ruview-verify`), commands (`/ruview-*`), and agents (`ruview-*`). It writes to no `claude-flow` memory namespace. Coexists with the `ruflo` marketplace with zero overlap (`ruview-*` vs. `ruflo-*`); if both are present, defer to `ruflo-agentdb` ADR-0001 §"Namespace convention".
5. **Codex mirror — full command parity.** Every `/ruview-*` command (`ruview-start`, `ruview-flash`, `ruview-provision`, `ruview-app`, `ruview-train`, `ruview-advanced`, `ruview-verify`) has a matching `codex/prompts/<name>.md`; `codex/AGENTS.md` carries the project rules and `codex/README.md` documents installation. The mirror covers the operator-facing **commands** in full; the additional **skills** (`ruview-quickstart`, `ruview-hardware-setup`, `ruview-configure`, `ruview-applications`, `ruview-model-training`, `ruview-advanced-sensing`, `ruview-cli-api`, `ruview-mmwave`, `ruview-verify`) and **agents** have no Codex equivalent — their knowledge is folded into `AGENTS.md` and the prompt files. The smoke script enforces command↔prompt parity.
6. **Compatibility surface.** Targets the `ruvnet/RuView` / `wifi-densepose` repo layout (`v2/crates/`, `firmware/esp32-csi-node/`, `archive/v1/`, `scripts/`, `docs/adr/`). Hardware docs default to ESP32 on `COM8` and tell the reader to confirm the port.
7. **Smoke contract** (`scripts/smoke.sh`, ≥13 checks): repo-root `.claude-plugin/marketplace.json` exists + lists `ruview` + points `source` at `./plugins/ruview`; plugin.json has `name`/`description`/`version`/`keywords` and does **not** contain `skills`/`commands`/`agents` arrays; every `skills/*/SKILL.md` has `name` + `description` + `allowed-tools`; no wildcard (`*`) in any `allowed-tools`; the expected skill set is present; every `commands/*.md` has a `description`; every `agents/*.md` has `name` + `description` + `model`; README contains a `## Compatibility` section and a `Namespace coordination` block; this ADR exists with `Status: Proposed`; `codex/AGENTS.md` and `codex/prompts/*.md` exist **and** every `commands/<name>.md` has a matching `codex/prompts/<name>.md` (command↔prompt parity); nothing is misplaced under `.claude-plugin/`.
## Consequences
- **Good:** `/plugin marketplace add ruvnet/RuView` + `/plugin install ruview@ruview` (or `claude --plugin-dir ./plugins/ruview` from a clone) gives newcomers and operators the whole RuView workflow surface; no MCP-server prerequisite; Codex users get the same operator commands; the smoke script makes drift visible.
- **Cost:** a mega-plugin means coarser install granularity (you get all 9 skills or none); the Codex mirror must be kept in sync by hand (the smoke script checks command↔prompt *presence* parity, not content parity); a skill stem (`ruview-verify`) collides with a command stem — tolerated by Claude Code (both resolve), but `claude plugin details` lists it twice.
- **Follow-ups:** if the skill set grows past comfortable browsing (it's at 9), revisit the "one mega-plugin" decision and split by lifecycle (`ruview-edge`, `ruview-train`, …); add a *content*-parity lint between commands and Codex prompts; consider renaming `/ruview-verify` to drop the skill/command stem collision; consider pinning a tested `claude-flow` CLI minor for the security-scan step if that step becomes load-bearing; verify the underlying RuView command flags (`sensing-server --help`, `gcloud-train.sh`, `provision.py`) against the live tree rather than from README/scripts.
+102
View File
@@ -0,0 +1,102 @@
#!/usr/bin/env bash
# Structural smoke test for the `ruview` Claude Code plugin.
# Run from anywhere: bash plugins/ruview/scripts/smoke.sh
set -u
# Resolve plugin root (this file lives in <root>/scripts/smoke.sh).
# Plugin lives at <repo>/plugins/ruview ; marketplace manifest is at <repo>/.claude-plugin/marketplace.json
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
REPO="$(cd "$ROOT/../.." && pwd)"
MARKET="$REPO/.claude-plugin/marketplace.json"
PASS=0
FAIL=0
ok() { echo " PASS $1"; PASS=$((PASS+1)); }
bad() { echo " FAIL $1"; FAIL=$((FAIL+1)); }
has() { grep -q "$1" "$2" 2>/dev/null; }
echo "ruview plugin smoke test"
echo "root: $ROOT"
echo "repo: $REPO"
echo
# 1. repo-root marketplace.json exists, lists the ruview plugin, points source at ./plugins/ruview
if [ -f "$MARKET" ] && has '"ruview"' "$MARKET" && has '"\./plugins/ruview"' "$MARKET"; then ok "repo-root .claude-plugin/marketplace.json lists 'ruview' with source ./plugins/ruview"; else bad "marketplace.json missing / wrong location / wrong source ($MARKET)"; fi
# 2. plugin.json exists with required fields
PJ="$ROOT/.claude-plugin/plugin.json"
if [ -f "$PJ" ] && has '"name"' "$PJ" && has '"description"' "$PJ" && has '"version"' "$PJ"; then ok "plugin.json has name/description/version"; else bad "plugin.json missing or incomplete"; fi
# 3. plugin.json has keywords
if has '"keywords"' "$PJ"; then ok "plugin.json has keywords"; else bad "plugin.json missing keywords"; fi
# 4. plugin.json does NOT enumerate skills/commands/agents (auto-discovered)
if has '"skills"' "$PJ" || has '"commands"' "$PJ" || has '"agents"' "$PJ"; then bad "plugin.json must NOT contain skills/commands/agents arrays"; else ok "plugin.json does not enumerate skills/commands/agents"; fi
# 5. every skill has SKILL.md with name + description + allowed-tools, and no wildcard tools
SKILL_OK=1
for d in "$ROOT"/skills/*/; do
[ -d "$d" ] || continue
f="$d/SKILL.md"
if [ ! -f "$f" ]; then bad "missing $f"; SKILL_OK=0; continue; fi
has '^name:' "$f" || { bad "$f missing 'name:'"; SKILL_OK=0; }
has '^description:' "$f" || { bad "$f missing 'description:'"; SKILL_OK=0; }
has '^allowed-tools:' "$f" || { bad "$f missing 'allowed-tools:'"; SKILL_OK=0; }
if grep -E '^allowed-tools:.*(\*|\ball tools\b)' "$f" >/dev/null 2>&1; then bad "$f uses wildcard tools"; SKILL_OK=0; fi
done
[ "$SKILL_OK" = 1 ] && ok "all skills have valid frontmatter, no wildcard tools"
# 6. expected skills present
EXPECTED_SKILLS="ruview-quickstart ruview-hardware-setup ruview-configure ruview-applications ruview-model-training ruview-advanced-sensing ruview-cli-api ruview-mmwave ruview-verify"
SKILLS_PRESENT=1
for s in $EXPECTED_SKILLS; do
[ -f "$ROOT/skills/$s/SKILL.md" ] || { bad "expected skill missing: $s"; SKILLS_PRESENT=0; }
done
[ "$SKILLS_PRESENT" = 1 ] && ok "expected skill set present ($(echo $EXPECTED_SKILLS | wc -w) skills)"
# 7. every command has a description in frontmatter
CMD_OK=1
for f in "$ROOT"/commands/*.md; do
[ -f "$f" ] || { bad "no command files found"; CMD_OK=0; break; }
has '^description:' "$f" || { bad "$f missing 'description:'"; CMD_OK=0; }
done
[ "$CMD_OK" = 1 ] && ok "all commands have a description"
# 8. every agent has name + description + model
AG_OK=1
for f in "$ROOT"/agents/*.md; do
[ -f "$f" ] || { bad "no agent files found"; AG_OK=0; break; }
has '^name:' "$f" || { bad "$f missing 'name:'"; AG_OK=0; }
has '^description:' "$f" || { bad "$f missing 'description:'"; AG_OK=0; }
has '^model:' "$f" || { bad "$f missing 'model:'"; AG_OK=0; }
done
[ "$AG_OK" = 1 ] && ok "all agents have name/description/model"
# 9. README has Compatibility + Namespace coordination
RM="$ROOT/README.md"
if has '## Compatibility' "$RM" && has 'Namespace coordination' "$RM"; then ok "README has Compatibility + Namespace coordination"; else bad "README missing Compatibility or Namespace coordination section"; fi
# 10. ADR-0001 exists with Status: Proposed
ADR="$ROOT/docs/adrs/0001-ruview-plugin-contract.md"
if [ -f "$ADR" ] && grep -qi 'Status:.*Proposed' "$ADR"; then ok "ADR-0001 present with Status: Proposed"; else bad "ADR-0001 missing or not 'Proposed'"; fi
# 11. Codex mirror present
if [ -f "$ROOT/codex/AGENTS.md" ] && ls "$ROOT"/codex/prompts/*.md >/dev/null 2>&1; then ok "Codex mirror present (AGENTS.md + prompts/)"; else bad "Codex mirror missing"; fi
# 11b. command <-> Codex prompt parity
PARITY=1
for f in "$ROOT"/commands/*.md; do
[ -f "$f" ] || continue
base="$(basename "$f")"
[ -f "$ROOT/codex/prompts/$base" ] || { bad "no Codex prompt for command $base"; PARITY=0; }
done
[ "$PARITY" = 1 ] && ok "every command has a matching Codex prompt"
# 12. no skills/commands/agents accidentally placed inside .claude-plugin/
if ls "$ROOT"/.claude-plugin/skills "$ROOT"/.claude-plugin/commands "$ROOT"/.claude-plugin/agents >/dev/null 2>&1; then bad "skills/commands/agents must not live under .claude-plugin/"; else ok ".claude-plugin/ contains only plugin.json"; fi
echo
echo "----------------------------------------"
echo "PASS: $PASS FAIL: $FAIL"
[ "$FAIL" -eq 0 ] || exit 1
@@ -0,0 +1,76 @@
---
name: ruview-advanced-sensing
description: Advanced RuView capabilities — RuvSense multistatic sensing (attention-weighted fusion, geometric diversity, persistent field model), cross-viewpoint fusion across multiple nodes, RF tomography (ISTA L1 solver, voxel grids), longitudinal biomechanics drift, pre-movement intention signals, adversarial signal detection, and multistatic mesh security hardening. Use for research-grade or multi-node deployments.
allowed-tools: Bash Read Write Edit Glob Grep
---
# RuView Advanced Sensing
The deep end: multistatic mesh, tomography, persistent field models, and the security model that protects them. Most of this lives in `wifi-densepose-signal/src/ruvsense/` (14 modules) and `wifi-densepose-ruvector/src/viewpoint/` (5 modules).
## RuvSense multistatic mode (ADR-029)
Treat every WiFi link in range — including neighbours' APs — as a bistatic radar pair, then fuse them.
| Module (`signal/src/ruvsense/`) | Purpose |
|--------------------------------|---------|
| `multiband.rs` | Multi-band CSI frame fusion, cross-channel coherence |
| `phase_align.rs` | Iterative LO phase-offset estimation, circular mean |
| `multistatic.rs` | Attention-weighted fusion, geometric diversity |
| `coherence.rs` / `coherence_gate.rs` | Z-score coherence scoring; Accept / PredictOnly / Reject / Recalibrate gate decisions |
| `pose_tracker.rs` | 17-keypoint Kalman tracker with AETHER re-ID embeddings |
| `field_model.rs` | SVD room eigenstructure, perturbation extraction |
| `tomography.rs` | RF tomography, ISTA L1 solver, voxel grid |
| `longitudinal.rs` | Welford stats, biomechanics drift detection |
| `intention.rs` | Pre-movement lead signals (200500 ms ahead) |
| `cross_room.rs` | Environment fingerprinting, transition graph |
| `gesture.rs` | DTW template-matching gesture classifier |
| `adversarial.rs` | Physically-impossible-signal detection, multi-link consistency |
## Cross-viewpoint fusion (ADR-016 viewpoint module)
Combine 2+ nodes geometrically — more nodes, more independent looks, tighter localization.
| Module (`ruvector/src/viewpoint/`) | Purpose |
|------------------------------------|---------|
| `attention.rs` | CrossViewpointAttention, GeometricBias, softmax with `G_bias` |
| `geometry.rs` | GeometricDiversityIndex, CramérRao bounds, Fisher Information |
| `coherence.rs` | Phase-phasor coherence, hysteresis gate |
| `fusion.rs` | MultistaticArray aggregate root, domain events |
Host-side helpers to explore the geometry before deploying: `node scripts/mesh-graph-transformer.js`, `node scripts/passive-radar.js`, `node scripts/deep-scan.js`.
## Persistent field model (ADR-030)
`field_model.rs` builds an SVD eigenstructure of the room and stores it (RVF, ideally on a Cognitum Seed). New CSI frames are projected against it; the residual *is* the perturbation. Lets you ask "what's different from the empty-room baseline?" and survive restarts.
## RF tomography
`tomography.rs` reconstructs a voxel occupancy grid from the multistatic link set via an ISTA L1 solver (sparse — most voxels are empty). Use with cross-viewpoint geometry for through-wall volumetric imaging. RuVector solver crates back the sparse interpolation (114→56 subcarriers).
## Sensing-first RF mode & adaptive mesh kernel
- ADR-031 (RuView sensing-first RF mode), ADR-081 (adaptive CSI mesh firmware kernel), ADR-083 (per-cluster π compute hop), ADR-095/096 (on-ESP32 temporal modeling with sparse GQA attention — runs the temporal head on-device).
## Security (ADR-032 — multistatic mesh hardening)
Using neighbours' APs as illuminators and pooling links across a mesh expands the attack surface. Mitigations:
- `adversarial.rs` rejects physically impossible signals and cross-checks multi-link consistency.
- `coherence_gate.rs` quarantines low-coherence / suspicious links (Reject / Recalibrate).
- Ed25519 witness chain (ADR-028) attests every measurement.
- Run a security review when touching anything on the hardware/network boundary (see `ruview-verify` and `docs/security-audit-wasm-edge-vendor.md`).
## Validate advanced changes
```bash
cd v2 && cargo test --workspace --no-default-features # incl. ruvsense + viewpoint tests
cargo test -p wifi-densepose-signal --no-default-features
cargo test -p wifi-densepose-ruvector --no-default-features
cd .. && python archive/v1/data/proof/verify.py
```
## Reference
- ADRs: 014 (SOTA signal processing), 029 (multistatic mode), 030 (persistent field model), 031 (sensing-first RF), 032 (mesh security hardening), 081/083/095/096
- `v2/crates/wifi-densepose-signal/src/ruvsense/` · `v2/crates/wifi-densepose-ruvector/src/viewpoint/`
- `docs/research/`, `docs/security-audit-wasm-edge-vendor.md`
@@ -0,0 +1,69 @@
---
name: ruview-applications
description: Run RuView sensing applications — presence/occupancy, breathing & heart rate, activity & fall detection, 17-keypoint pose estimation (WiFlow), sleep monitoring & apnea screening, environment mapping, Mass Casualty Assessment (MAT), and the 3D point-cloud fusion demo. Use when someone wants to actually *do* something with a working RuView setup.
allowed-tools: Bash Read Write Edit Glob Grep
---
# RuView Applications
What RuView can sense, and how to run each one. Assumes you have either the Docker demo (simulated CSI) or a live ESP32 sink (see `ruview-quickstart` / `ruview-hardware-setup`).
## Application catalogue
| Application | What it does | Entry point |
|-------------|--------------|-------------|
| **Presence / occupancy** | Detect people through walls, count them, track entries/exits (trained model + PIR fusion, ~0.012 ms latency) | sensing-server live mode; `examples/environment/` |
| **Vital signs** | Breathing 630 BPM (bandpass 0.10.5 Hz), heart rate 40120 BPM (bandpass 0.82.0 Hz), contactless while sleeping/sitting | `wifi-densepose-vitals` crate (ADR-021); `examples/medical/` |
| **Activity recognition** | Walking, sitting, gestures, falls — from temporal CSI patterns | RuvSense `gesture.rs` (DTW), `pose_tracker.rs`; `scripts/gait-analyzer.js` |
| **Pose estimation** | 17 COCO keypoints via WiFlow architecture; dual-modal webcam+WiFi fusion demo | `cargo run -p wifi-densepose-sensing-server` + pose-fusion demo (ADR-059); see `ruview-model-training` to train |
| **Sleep monitoring** | Overnight monitoring, sleep-stage classification, apnea screening | `examples/sleep/`; `scripts/apnea-detector.js` |
| **Environment mapping** | RF fingerprinting identifies rooms, detects moved furniture, spots new objects | sensing-server `--build-index env`; RuvSense `field_model.rs`, `cross_room.rs` |
| **Mass Casualty Assessment (MAT)** | Disaster survivor detection — find people in rubble/smoke | `wifi-densepose-mat` crate; `docs/wifi-mat-user-guide.md`; `examples/medical/` |
| **3D point cloud** *(optional fusion)* | Camera depth (MiDaS) + WiFi CSI + mmWave radar → unified spatial model (~22 ms, 19K+ pts/frame) | `scripts/mmwave_fusion_bridge.py`; ADR-094 (GitHub Pages deploy) |
| **Novel RF apps** | Passive radar, material classification, device fingerprinting, mincut person-counting | `scripts/passive-radar.js`, `material-classifier.js`, `device-fingerprint.js`, `mincut-person-counter.js` (ADR-077/078) |
## Quick recipes
```bash
# Docker demo — everything, simulated CSI
docker run -p 3000:3000 ruvnet/wifi-densepose:latest # http://localhost:3000
# Live sensing server (consumes ESP32 UDP CSI)
cd v2 && cargo run -p wifi-densepose-sensing-server
# Live RF room scan (Cognitum Seed on :5006)
node scripts/rf-scan.js --port 5006
node scripts/snn-csi-processor.js --port 5006
# Embed a trained model + build an environment index
cd v2
cargo run -p wifi-densepose-sensing-server -- --model model.rvf --embed
cargo run -p wifi-densepose-sensing-server -- --model model.rvf --build-index env
# Python live demo
python examples/ruview_live.py
# Spectrogram / graph visualisers
node scripts/csi-spectrogram.js
node scripts/csi-graph-visualizer.js
```
## Picking the right modality
- **Through a wall, no line of sight** → presence + activity; expect ≤5 m depth (Fresnel-zone geometry).
- **Person stationary (sleeping / sitting)** → vitals (breathing first, heart rate needs cleaner signal) + sleep staging.
- **Need skeletons** → pose (WiFlow). Camera-free works but is modest; camera-supervised gets 92.9% PCK@20 — train it (`ruview-model-training`).
- **Search & rescue** → MAT (`docs/wifi-mat-user-guide.md`).
- **"What changed in this room?"** → environment mapping / RF fingerprint index.
- **Best spatial accuracy** → 2+ ESP32 nodes + cross-viewpoint fusion (`ruview-advanced-sensing`), optionally + Cognitum Seed.
## Examples directory map
`examples/environment/` · `examples/medical/` · `examples/sleep/` · `examples/stress/` · `examples/happiness-vector/` · `examples/ruview_live.py` — each has a README.
## Reference
- `README.md` — feature matrix, latency/throughput numbers
- `docs/user-guide.md`, `docs/wifi-mat-user-guide.md`
- ADRs: 021 (vitals), 024 (AETHER contrastive embeddings), 027 (MERIDIAN domain generalization), 041 (edge modules), 059 (live ESP32 pipeline), 077/078 (novel RF apps), 082 (pose tracker output filter), 094 (point cloud)
- RuvSense modules: `v2/crates/wifi-densepose-signal/src/ruvsense/` (14 modules)
@@ -0,0 +1,82 @@
---
name: ruview-cli-api
description: Use the RuView `wifi-densepose` CLI binary (incl. MAT scan/status/zones/survivors/alerts/export subcommands), the REST API (`wifi-densepose-api`, Axum), and the browser/WASM build (`wifi-densepose-wasm`, `wifi-densepose-wasm-edge`). Use when integrating RuView into another program, scripting it from the shell, exposing it over HTTP, or shipping it to the browser / ESP32-WASM3.
allowed-tools: Bash Read Write Edit Glob Grep
---
# RuView CLI, API & WASM
The programmatic surfaces of RuView — the `wifi-densepose` binary, the HTTP API, and the WebAssembly builds.
## 1. The `wifi-densepose` CLI binary (`wifi-densepose-cli`)
```bash
cd v2
cargo run -p wifi-densepose-cli -- --help # or: cargo build -p wifi-densepose-cli --release → target/release/wifi-densepose
cargo run -p wifi-densepose-cli -- version
```
Top-level subcommands: `version`, and `mat` (Mass Casualty Assessment Tool).
### `wifi-densepose mat …` — disaster survivor detection
| Subcommand | Purpose | Key flags |
|------------|---------|-----------|
| `mat scan [zone]` | Start scanning for survivors | `--disaster-type <…>`, `--sensitivity 0.01.0`, `--max-depth <m>`, `--continuous`, `--interval <ms>`, `--simulate` |
| `mat status` | Current scan status | `--detailed`, `--format <…>`, `--watch` |
| `mat zones …` | Manage scan zones | `zones list [--active-only]`, plus add/remove/update |
| `mat survivors` | List detected survivors with triage status | |
| `mat alerts` | View / manage alerts | |
| `mat export` | Export scan data | JSON or CSV |
Example:
```bash
cargo run -p wifi-densepose-cli -- mat scan rubble-A --disaster-type earthquake --sensitivity 0.7 --max-depth 5 --continuous --interval 2000
cargo run -p wifi-densepose-cli -- mat survivors --format json
cargo run -p wifi-densepose-cli -- mat export --format csv > survivors.csv
```
Use `--simulate` for testing without hardware. Background and user guide: `docs/wifi-mat-user-guide.md`, `wifi-densepose-mat` crate.
## 2. REST API (`wifi-densepose-api`, Axum)
Library crate (`v2/crates/wifi-densepose-api/src/lib.rs`) — the Axum router/handlers; configured via the `wifi-densepose-config` crate. It's wired into the server binaries (e.g. the sensing server / Docker image), not a standalone `cargo run` target by itself.
```bash
# Easiest way to exercise it: the Docker image exposes the API + dashboard on :3000
docker run -p 3000:3000 ruvnet/wifi-densepose:latest
# Then hit the HTTP endpoints (see the API module / docs for routes) and open http://localhost:3000
# v1 Python service config reference: example.env, pyproject.toml (archive/v1/)
```
When embedding the API crate in your own binary, take the router from `wifi_densepose_api`, supply config via `wifi-densepose-config`, and serve with Axum/Tokio. Keep input validation at the boundary (project rule).
## 3. WASM / browser & ESP32-WASM3
- **`wifi-densepose-wasm`** — compiles the stack to `wasm32-unknown-unknown` with a JS-friendly API:
```bash
cd v2/crates/wifi-densepose-wasm
wasm-pack build --target web --features mat # recommended (produces pkg/)
cargo build --target wasm32-unknown-unknown --features mat # plain cargo build
```
See `v2/crates/wifi-densepose-wasm/README.md` for the exported surface.
- **`wifi-densepose-wasm-edge`** — 60 edge modules (609 tests) that compile to `wasm32-unknown-unknown` and run on ESP32-S3 via WASM3; shared utils in `src/vendor_common.rs`. These are the ADR-041 edge-intelligence modules in WASM form.
- Browser demos: pose-fusion (ADR-059), point-cloud (ADR-094) — deployed via GitHub Pages from the WASM build.
## 4. Where it fits
| You want to… | Use |
|--------------|-----|
| Script a survivor scan / export results | `wifi-densepose mat …` |
| Expose sensing over HTTP | `wifi-densepose-api` (via a server binary / Docker) |
| Run sensing in a browser | `wifi-densepose-wasm` → `wasm-pack build --target web` |
| Run an edge module on an ESP32 in WASM | `wifi-densepose-wasm-edge` + WASM3 |
| A long-running CSI sink + training | `wifi-densepose-sensing-server` (see `ruview-applications` / `ruview-model-training`) |
## Reference
- Crates: `wifi-densepose-cli`, `wifi-densepose-api`, `wifi-densepose-config`, `wifi-densepose-wasm`, `wifi-densepose-wasm-edge`, `wifi-densepose-mat`
- ADRs: 041 (edge modules), 059 (live ESP32 pipeline), 094 (point-cloud GitHub Pages)
- `docs/wifi-mat-user-guide.md`, `docs/edge-modules/`, `docs/security-audit-wasm-edge-vendor.md`
- Validate after changes: `cd v2 && cargo test -p wifi-densepose-cli -p wifi-densepose-api -p wifi-densepose-wasm --no-default-features`
@@ -0,0 +1,99 @@
---
name: ruview-configure
description: Configure RuView — ESP32 sdkconfig variants, NVS provisioning, WiFi channel / MAC filter overrides (ADR-060), edge intelligence modules (ADR-041), sensing-server flags, multi-node mesh, and Cognitum Seed integration. Use when adjusting how a deployed RuView system behaves without changing code.
allowed-tools: Bash Read Write Edit Glob Grep
---
# RuView Configuration
Everything you can tune in a RuView deployment, from a one-line provision flag to a full mesh + Cognitum Seed setup.
## 1. Firmware build-time config (sdkconfig)
| Variant | File | When |
|---------|------|------|
| 8MB (default) | `firmware/esp32-csi-node/sdkconfig.defaults.template` | ESP32-S3 8MB, full feature set, real WiFi CSI |
| 4MB | `firmware/esp32-csi-node/sdkconfig.defaults.4mb` | ESP32-S3 SuperMini 4MB — display disabled, dual OTA slots (`partitions_4mb.csv`, ~1.856 MB each) |
| Heltec N16R2 | `firmware/esp32-csi-node/sdkconfig.defaults.heltec_n16r2` | Heltec boards |
Switch: `cp firmware/esp32-csi-node/sdkconfig.defaults.<variant> firmware/esp32-csi-node/sdkconfig.defaults`, then rebuild (see `ruview-hardware-setup`). **Never test in mock mode** — the Kconfig fall-threshold bug only showed up with real CSI.
## 2. Runtime device config (NVS via provision.py)
`provision.py` writes the `csi_cfg` NVS namespace over the serial port. **Run `python firmware/esp32-csi-node/provision.py --help` for the authoritative flag list** (on Windows force `PYTHONUTF8=1 PYTHONIOENCODING=utf-8` — the help text contains non-ASCII and crashes under cp1252).
```bash
python firmware/esp32-csi-node/provision.py --port COM8 \
--ssid "WiFi" --password "secret" \
--target-ip 192.168.1.20 --target-port 5005 \ # aggregator UDP sink (port default 5005)
--node-id 1 \ # 0-255
--channel 6 --filter-mac AA:BB:CC:DD:EE:FF # ADR-060: pin channel + filter transmitter
```
| Flag group | Flags | Notes |
|------------|-------|-------|
| WiFi / sink | `--ssid` `--password` `--target-ip` `--target-port` (5005) `--node-id` | `--node-id` 0-255 |
| TDM mesh | `--tdm-slot` `--tdm-total` | 0-based slot index + total node count — this is how multi-node mesh is slotted |
| Edge processing | `--edge-tier {0,1,2}` | 0=off, 1=stats, 2=vitals (ADR-041) |
| Detection thresholds | `--pres-thresh` (50) `--fall-thresh` (15000 → 15.0 rad/s²) | raise `--fall-thresh` to cut false falls in high-traffic areas (issue #263) |
| Vitals | `--vital-win` (300 frames) `--vital-int` (1000 ms) `--subk-count` (32, top-K subcarriers) | |
| Channel / hopping | `--channel` (1-14 / 36-177, overrides AP auto-detect) `--filter-mac` `--hop-channels` (`1,6,11`) `--hop-dwell` (200 ms) | omit `--channel` + set `--hop-channels` for ADR-061 multi-freq hopping; omit `--filter-mac` to capture all transmitters |
| Cognitum Seed | `--seed-url` (`http://10.1.10.236`) `--seed-token` (Bearer, from pairing) `--zone` (`lobby`) | |
| Swarm | `--swarm-hb` (30 s) `--swarm-ingest` (5 s) | heartbeat + vector ingest intervals |
| Mode | `--dry-run` (build NVS bin, don't flash) `--baud` (460800) `--force-partial` | |
> ⚠️ **NVS namespace is replaced wholesale (issue #391).** Flashing rewrites the *entire* `csi_cfg` namespace — **any key you don't pass on the CLI is erased**. Always pass the full set you want, or use `--force-partial` knowingly. Read the device's current values off the serial boot log first (`adaptive_ctrl` / `csi_collector` lines) if you're unsure.
- NVS partition images for fleet provisioning: `scripts/generate_nvs_matrix.py` (subprocess-first — the `esp_idf_nvs_partition_gen` API changed across versions).
## 3. Sensing server flags
```bash
cd v2
cargo run -p wifi-densepose-sensing-server -- --help
# Common modes:
cargo run -p wifi-densepose-sensing-server # live sink, default port
cargo run -p wifi-densepose-sensing-server -- --pretrain --dataset data/csi/ --pretrain-epochs 50
cargo run -p wifi-densepose-sensing-server -- --train --dataset data/mmfi/ --epochs 100 --save-rvf model.rvf
cargo run -p wifi-densepose-sensing-server -- --model model.rvf --embed
cargo run -p wifi-densepose-sensing-server -- --model model.rvf --build-index env
```
`wifiscan` server (multi-BSSID, ADR-022): `cargo run -p wifi-densepose-sensing-server` consumes `wifi-densepose-wifiscan` output; use neighbour APs as free radar illuminators.
## 4. Edge intelligence modules (ADR-041)
Small Rust/WASM programs that run on the ESP32 itself — no internet, instant response. See `docs/edge-modules/` and `docs/adr/ADR-041-*`. Each module declares its CSI feature inputs (8-dim feature vectors) and an RVF store target (Cognitum Seed). Configure which modules ship in a build via the firmware component config; configure their thresholds via NVS keys.
Helper scripts that mirror edge-module logic on the host (useful for tuning before flashing):
`scripts/apnea-detector.js`, `gait-analyzer.js`, `material-classifier.js`, `passive-radar.js`, `mincut-person-counter.js`, `device-fingerprint.js`, `mesh-graph-transformer.js`, `material-detector.js`.
## 5. Multi-node mesh
- 2+ nodes give real spatial resolution. Each node provisioned to the same `--target-ip` sink.
- TDM protocol + channel hopping coordinated by `wifi-densepose-hardware` (`v2/crates/wifi-densepose-hardware/src/esp32/`).
- Cross-viewpoint fusion combines nodes — see `ruview-advanced-sensing`.
## 6. Cognitum Seed integration ($140 total BOM)
ESP32 streams CSI → bridge forwards to a Cognitum Seed for persistent RVF memory, kNN over environments, and an Ed25519 witness chain.
```bash
node scripts/rf-scan.js --port 5006 # live RF room scan → Seed
node scripts/snn-csi-processor.js --port 5006 # SNN real-time learning on-Seed
```
See `docs/tutorials/cognitum-seed-pretraining.md` and ADR-028 (capability audit + witness verification).
## 7. App-level config
- API: `wifi-densepose-api` (Axum) — config via `wifi-densepose-config` crate; see `example.env` / `pyproject.toml` for the v1 Python service.
- Docker: `docker run -p 3000:3000 ruvnet/wifi-densepose:latest` (env-var overrides documented in `README.md` / `docker/`).
- Dashboard: served on `:3000`; nvsim dashboard (ADR-092) is separate.
## Reference
- `docs/adr/` (96 ADRs) — esp. ADR-022 (wifiscan), ADR-028 (capability audit), ADR-041 (edge modules), ADR-060 (channel/MAC override), ADR-061 (QEMU + mesh), ADR-081 (adaptive CSI mesh kernel)
- `CLAUDE.md` / `CLAUDE.local.md` — crate map, build env, QEMU CI fixes
- `example.env`, `Makefile`, `firmware/esp32-csi-node/`
@@ -0,0 +1,127 @@
---
name: ruview-hardware-setup
description: ESP32-S3 / ESP32-C6 firmware build, flash, WiFi provisioning, and serial monitoring for RuView CSI sensing nodes. Use when setting up physical hardware, reflashing a node, or debugging a device that isn't streaming CSI.
allowed-tools: Bash Read Write Edit Glob Grep
---
# RuView Hardware Setup
Bring a RuView sensing node online: build firmware → flash → provision WiFi → confirm CSI stream.
## Supported devices
| Device | Flash | Chip | Role |
|--------|-------|------|------|
| ESP32-S3 (8MB) | 8 MB | Xtensa dual-core | WiFi CSI sensing node (default) |
| ESP32-S3 SuperMini | 4 MB | Xtensa dual-core | Compact CSI node — use `sdkconfig.defaults.4mb` |
| ESP32-C6 + Seeed MR60BHA2 | — | RISC-V + 60 GHz FMCW | mmWave HR/BR/presence |
**Not supported:** original ESP32, ESP32-C3 (single-core).
## 1. Build firmware (Windows — Python subprocess, NOT bash directly)
ESP-IDF v5.4 does not support MSYS2/Git Bash. Use the Espressif Python venv as a subprocess with `MSYSTEM*` env vars stripped. The proven command lives in `CLAUDE.local.md` — reproduce it:
```bash
/c/Espressif/tools/python/v5.4/venv/Scripts/python.exe -c "
import subprocess, os
env = os.environ.copy()
for k in ['MSYSTEM','MSYSTEM_CHOST','MSYSTEM_PREFIX','MINGW_PREFIX','CHERE_INVOKING']:
env.pop(k, None)
env['IDF_PATH'] = r'C:\Users\ruv\esp\v5.4\esp-idf'
env['IDF_PYTHON_ENV_PATH'] = r'C:\Espressif\tools\python\v5.4\venv'
env['IDF_TOOLS_PATH'] = r'C:\Espressif'
env['PATH'] = (
r'C:\Espressif\tools\xtensa-esp-elf\esp-14.2.0_20241119\xtensa-esp-elf\bin;'
r'C:\Espressif\tools\cmake\3.30.2\cmake-3.30.2-windows-x86_64\bin;'
r'C:\Espressif\tools\ninja\1.12.1;'
r'C:\Espressif\tools\idf-exe\1.0.3;'
r'C:\Espressif\tools\ccache\4.10.2\ccache-4.10.2-windows-x86_64;'
r'C:\Espressif\tools\python\v5.4\venv\Scripts;'
+ env['PATH']
)
python = r'C:\Espressif\tools\python\v5.4\venv\Scripts\python.exe'
idf_py = os.path.join(env['IDF_PATH'], 'tools', 'idf.py')
r = subprocess.run([python, idf_py, 'build'], # flash: [python, idf_py, '-p', 'COM8', 'flash']
cwd=r'C:\Users\ruv\Projects\wifi-densepose\firmware\esp32-csi-node',
env=env, capture_output=True, text=True, timeout=300)
print(r.stdout[-3000:]); print(r.stderr[-2000:]); print('RC:', r.returncode)
"
```
- **8MB build:** uses `sdkconfig.defaults.template` (no mock — real WiFi CSI).
- **4MB build:** `cp firmware/esp32-csi-node/sdkconfig.defaults.4mb firmware/esp32-csi-node/sdkconfig.defaults` first, then build.
- Build outputs: `firmware/esp32-csi-node/build/{bootloader/bootloader.bin, partition_table/partition-table.bin, esp32-csi-node.bin, ota_data_initial.bin}`.
## 2. Flash to the device
Same subprocess pattern, swap `[python, idf_py, 'build']``[python, idf_py, '-p', 'COM8', 'flash']`. Or with esptool directly:
```bash
python -m esptool --chip esp32s3 --port COM8 --baud 460800 \
write_flash 0x0 firmware/esp32-csi-node/build/bootloader/bootloader.bin \
0x8000 firmware/esp32-csi-node/build/partition_table/partition-table.bin \
0xf000 firmware/esp32-csi-node/build/ota_data_initial.bin \
0x20000 firmware/esp32-csi-node/build/esp32-csi-node.bin
```
(The default device port in this workspace is **COM8**. Some docs reference COM9 — confirm with the user.)
## 3. Provision WiFi + sink address
Runs directly — no ESP-IDF env needed:
```bash
python firmware/esp32-csi-node/provision.py --port COM8 \
--ssid "YourWiFi" --password "secret" --target-ip 192.168.1.20 --target-port 5005 --node-id 1
# Optional ADR-060 overrides:
python firmware/esp32-csi-node/provision.py --port COM8 --channel 6 --filter-mac AA:BB:CC:DD:EE:FF
```
`--help` lists the full flag set (TDM mesh slotting, edge tier, detection thresholds, vitals window, hop channels, Cognitum Seed, swarm intervals) — see the `ruview-configure` skill for the table. **Gotcha (issue #391):** flashing replaces the *entire* `csi_cfg` NVS namespace — any key not on the CLI is erased; pass the full set you want. On Windows, `provision.py --help` needs `PYTHONUTF8=1` to print (non-ASCII in the help text).
## 4. Confirm CSI stream
```bash
# Serial monitor (use pyserial — idf.py monitor hangs in a subprocess)
/c/Espressif/tools/python/v5.4/venv/Scripts/python.exe -c "
import serial, time
ser = serial.Serial('COM8', 115200, timeout=1); start = time.time()
while time.time() - start < 15:
line = ser.readline()
if line: print(line.decode('utf-8', errors='replace').strip())
ser.close()
"
```
Then start the sink and watch frames arrive:
```bash
cd v2 && cargo run -p wifi-densepose-sensing-server # listens for ESP32 UDP CSI
```
## Common issues
| Symptom | Cause | Fix |
|---------|-------|-----|
| `MSys/Mingw is no longer supported` | ESP-IDF detected Git Bash | Use the Python-subprocess command above with `MSYSTEM*` stripped |
| `cmd.exe /C` hangs | Interactive prompt from Git Bash | Don't use `cmd.exe /C` — use the Python subprocess |
| `cmake not found` | Wrong path | It's `cmake\3.30.2\cmake-3.30.2-windows-x86_64\bin`, not `cmake\3.30.2\bin` |
| `python_env not found` | Missing env var | Set `IDF_PYTHON_ENV_PATH=C:\Espressif\tools\python\v5.4\venv` |
| No CSI frames at the sink | WiFi not provisioned, wrong channel, or MAC filter too tight | Re-run `provision.py`; try `--channel` matching your AP; drop `--filter-mac` |
| False fall alerts | Old `fall_thresh` default | Issue #263 raised it to 15.0 rad/s² + debounce — reflash latest firmware |
## Firmware release process (for maintainers)
1. Build 8MB from `sdkconfig.defaults.template` (no mock)
2. Build 4MB from `sdkconfig.defaults.4mb` (no mock)
3. Save 6 binaries: `esp32-csi-node.bin`, `bootloader.bin`, `partition-table.bin`, `ota_data_initial.bin`, `esp32-csi-node-4mb.bin`, `partition-table-4mb.bin`
4. `git tag v0.X.Y-esp32 && git push origin v0.X.Y-esp32`
5. `gh release create v0.X.Y-esp32 <binaries> --title "..." --notes-file ...`
6. Verify on real hardware (COM8) before publishing — **always test with real WiFi CSI, not mock mode** (mock missed the Kconfig threshold bug)
## Reference
- `CLAUDE.local.md` — exact ESP-IDF build env, paths, QEMU CI notes
- `firmware/esp32-csi-node/` — C firmware (channel hopping, NVS config, TDM protocol)
- `docs/adr/ADR-028-esp32-capability-audit.md`, `docs/build-guide.md`, `docs/TROUBLESHOOTING.md`
@@ -0,0 +1,61 @@
---
name: ruview-mmwave
description: Set up and run RuView mmWave / FMCW radar sensing — ESP32-C6 + Seeed MR60BHA2 (60 GHz, heart rate / breathing rate / presence) and HLK-LD2410 (24 GHz, presence + distance), plus mmWave↔WiFi-CSI sensor fusion (48-byte fused vitals, MR60BHA2/LD2410 auto-detect, v0.5.0+). Use when the deployment includes a millimetre-wave radar alongside or instead of WiFi CSI.
allowed-tools: Bash Read Write Edit Glob Grep
---
# RuView mmWave / FMCW Radar
The radio side-channel: 60 GHz and 24 GHz FMCW radar, standalone and fused with WiFi CSI.
## Hardware
| Device | Port | Band | Provides | ~Cost |
|--------|------|------|----------|-------|
| ESP32-C6 + Seeed MR60BHA2 | COM4 (typical) | 60 GHz FMCW | Heart rate, breathing rate, presence | ~$15 |
| HLK-LD2410 | — | 24 GHz FMCW | Presence + distance (gated zones) | ~$3 |
The C6 is RISC-V and can run the radar pipeline; it is **not** a WiFi-CSI node (use an ESP32-S3 for CSI). LD2410 is a UART module wired to a host or to the C6.
## 1. Firmware with mmWave fusion (v0.5.0+)
The ESP32 firmware auto-detects an attached MR60BHA2 or LD2410 and emits **48-byte fused vitals** records (CSI-derived + radar-derived, reconciled). Binary is ~12 KB larger than the CSI-only build. Build/flash as in `ruview-hardware-setup` (Windows: Python-subprocess; ESP-IDF v5.4 ≠ Git Bash). Recommended stable firmware tag: `v0.5.0-esp32` or later — see `docs/user-guide.md` release table.
```bash
# Provision the radar/fusion node (same provision.py; the firmware probes for the radar on boot)
python firmware/esp32-csi-node/provision.py --port COM8 --ssid "WiFi" --password "secret" --target-ip 192.168.1.20
# Confirm: serial monitor should report which radar was detected and start emitting fused vitals
```
## 2. mmWave ↔ WiFi-CSI fusion bridge (host side)
```bash
python scripts/mmwave_fusion_bridge.py # bridges radar HR/BR + CSI → unified spatial model
node scripts/passive-radar.js # passive-radar style processing for exploration
```
The 3D point-cloud demo fuses **camera depth (MiDaS) + WiFi CSI + mmWave radar** → unified spatial model (~22 ms pipeline, 19K+ pts/frame; ADR-094). Drive it with `scripts/mmwave_fusion_bridge.py` plus the point-cloud front-end.
## 3. Standalone radar use
- **MR60BHA2 (60 GHz)** — best for contactless vitals on a (near-)stationary subject: blood pressure proxy, heart rate, breathing rate; $15 hardware, no wearable. See `examples/medical/README.md`.
- **LD2410 (24 GHz)** — best for cheap presence + coarse distance / gated zones; complements CSI presence (PIR-style fusion) for higher confidence.
## 4. When to use mmWave vs. WiFi CSI
| Situation | Prefer |
|-----------|--------|
| Contactless vitals, subject stationary, line of sight | **MR60BHA2** (cleaner HR/BR than CSI alone) |
| Cheap, robust presence / occupancy in a defined zone | **LD2410** (or LD2410 + CSI) |
| Through-wall presence / activity, no line of sight | **WiFi CSI** (mmWave doesn't penetrate walls) |
| Pose / skeletons | **WiFi CSI** (WiFlow) — mmWave doesn't do this here |
| Highest-confidence vitals | **Fusion** — 48-byte fused vitals reconcile CSI + radar |
| Volumetric 3D | **Fusion** — camera depth + CSI + mmWave point cloud |
## Reference
- Hardware tables: `README.md`, `docs/user-guide.md` (release table — v0.5.0 mmWave fusion notes, binary sizes)
- `scripts/mmwave_fusion_bridge.py`, `scripts/passive-radar.js`
- `examples/medical/README.md` (60 GHz mmWave vitals)
- ADR-094 (point-cloud GitHub Pages deployment)
- Validate firmware changes with the QEMU helpers and `ruview-verify`
@@ -0,0 +1,122 @@
---
name: ruview-model-training
description: Train RuView models — camera-free WiFlow pose (10 sensor signals, no labels), camera-supervised pose (MediaPipe + ESP32 CSI → 92.9% PCK@20, ADR-079), RuVector contrastive embeddings (AETHER, ADR-024), domain generalization (MERIDIAN, ADR-027), local SNN environment adaptation, plus GPU training on GCloud and Hugging Face publishing. Use when building, fine-tuning, evaluating, or shipping a model.
allowed-tools: Bash Read Write Edit Glob Grep
---
# RuView Model Training
RuView trains several kinds of model. Pick the track that matches the goal; all of them run on a laptop, with an optional GPU path.
## Track A — Camera-free pose (WiFlow), no cameras, no labels
Trains 17-keypoint pose from 10 sensor signals. Fast, fully unsupervised, modest accuracy.
```bash
cd v2
# Pretrain on raw CSI (contrastive)
cargo run -p wifi-densepose-sensing-server -- --pretrain --dataset data/csi/ --pretrain-epochs 50
# Train pose head, save an RVF artifact
cargo run -p wifi-densepose-sensing-server -- --train --dataset data/mmfi/ --epochs 100 --save-rvf model.rvf
```
~84 s on an M4 Pro. Benchmarks: `node scripts/benchmark-wiflow.js`, eval: `node scripts/eval-wiflow.js`.
## Track B — Camera-supervised pose (ADR-079) → 92.9% PCK@20
Uses a webcam + MediaPipe as ground truth, paired with ESP32 CSI. ~19 min on a laptop.
```bash
# 1. Collect paired data (camera + CSI)
python scripts/collect-ground-truth.py # MediaPipe pose landmarks
python scripts/collect-training-data.py # CSI capture, time-synced
node scripts/align-ground-truth.js # align camera ↔ CSI timestamps
# 2. Train (the camera-supervised path through the sensing-server / train crate)
cd v2
cargo run -p wifi-densepose-sensing-server -- --train --dataset data/paired/ --epochs <N> --save-rvf model.rvf
# 3. Evaluate
cd .. && node scripts/eval-wiflow.js # reports PCK@20
```
Requires `data/pose_landmarker_lite.task` (MediaPipe model). See `docs/adr/ADR-079-camera-ground-truth-training.md`.
## Track C — RuVector contrastive embeddings (AETHER, ADR-024)
CSI subcarrier amplitude/phase → embeddings for re-ID and retrieval (171K emb/s on M4 Pro). Driven by `wifi-densepose-train` + `wifi-densepose-ruvector` (RuVector v2.0.4). Spectrogram embeddings: ADR-076.
```bash
cd v2
cargo check -p wifi-densepose-train --no-default-features # sanity
cargo run -p wifi-densepose-sensing-server -- --model model.rvf --embed
cargo run -p wifi-densepose-sensing-server -- --model model.rvf --build-index env
```
## Track D — Domain generalization (MERIDIAN, ADR-027)
Make a model transfer across environments without retraining. Configured through the training pipeline's domain-generalization options; see ADR-027 and `wifi-densepose-train` + `ruview_metrics`.
## Track E — Local SNN environment adaptation
Spiking neural network that adapts to a new room in <30 s, on-device or on a Cognitum Seed:
```bash
node scripts/snn-csi-processor.js --port 5006
```
See `docs/tutorials/cognitum-seed-pretraining.md`, ADR-084/085 (RaBitQ similarity sensor), ADR-086 (edge novelty gate).
## GPU training on GCloud
Project `cognitum-20260110` has L4 / A100 / H100 quota.
```bash
gcloud auth login
gcloud config set project cognitum-20260110
bash scripts/gcloud-train.sh --dry-run # smoke test, synthetic data
bash scripts/gcloud-train.sh --gpu l4 --hours 2 # prototyping
bash scripts/gcloud-train.sh --gpu a100 --config scripts/training-config-sweep.json
bash scripts/gcloud-train.sh --sweep # full hyperparameter sweep
# VM is auto-deleted after training unless --keep-vm. Cost: L4 ~$0.80/hr, A100 40GB ~$3.60/hr.
```
Local Mac training: `bash scripts/mac-mini-train.sh`. Model benchmark: `python scripts/benchmark-model.py`.
## Publishing a trained model
```bash
python scripts/publish-huggingface.py # or: bash scripts/publish-huggingface.sh
```
Pushes the RVF artifact + card to Hugging Face. See `docs/huggingface/`.
## Data layout
| Path | Contents |
|------|----------|
| `data/recordings/` | Raw CSI captures (`*.csi.jsonl`), overnight runs |
| `data/csi/` | CSI datasets for pretraining |
| `data/mmfi/` | MM-Fi dataset (ADR-015) |
| `data/paired/` | Camera ↔ CSI paired samples (ADR-079) |
| `data/ground-truth/` | MediaPipe pose landmarks |
| `data/pose_landmarker_lite.task` | MediaPipe model file |
| `models/` | Trained artifacts |
Record more data: `python scripts/record-csi-udp.py` (UDP CSI capture from a live node).
## Validation after a training change
```bash
cd v2 && cargo test --workspace --no-default-features # 1,400+ pass, 0 fail
cd .. && python archive/v1/data/proof/verify.py # VERDICT: PASS
```
Then hand off to `ruview-verify` for the witness bundle.
## Reference
- ADRs: 015 (MM-Fi + Wi-Pose datasets), 016 (RuVector training integration — complete), 017 (RuVector signal + MAT), 024 (AETHER), 027 (MERIDIAN), 076 (spectrogram embeddings), 079 (camera ground truth), 084/085 (RaBitQ), 095/096 (on-ESP32 temporal modeling, sparse GQA)
- Crates: `wifi-densepose-train`, `wifi-densepose-nn`, `wifi-densepose-ruvector`, `wifi-densepose-sensing-server`
- `scripts/gcloud-train.sh`, `mac-mini-train.sh`, `benchmark-wiflow.js`, `eval-wiflow.js`, `benchmark-model.py`
@@ -0,0 +1,77 @@
---
name: ruview-quickstart
description: Onboarding and first-run for RuView (WiFi-DensePose) — Docker demo with simulated data, repo build, and the fastest path to a live sensing dashboard. Use when someone is new to RuView or wants the shortest path to "it works on my machine".
allowed-tools: Bash Read Write Edit Glob Grep
---
# RuView Quickstart
Get a newcomer from zero to a running RuView sensing dashboard. Three tiers, pick the one that matches the hardware on hand.
## Tier 0 — Docker, no hardware (2 minutes)
```bash
docker pull ruvnet/wifi-densepose:latest
docker run -p 3000:3000 ruvnet/wifi-densepose:latest
# open http://localhost:3000 — simulated CSI, full UI
```
Use this to demo the dashboard, explore the API, or develop UI without a sensor.
## Tier 1 — Build the repo from source
```bash
# Rust workspace (1,400+ tests, ~2 min)
cd v2
cargo test --workspace --no-default-features
# Single-crate sanity check (no GPU)
cargo check -p wifi-densepose-train --no-default-features
# Python proof (deterministic SHA-256 pipeline check)
cd ..
python archive/v1/data/proof/verify.py # must print VERDICT: PASS
```
If `verify.py` fails on a hash mismatch after a numpy/scipy bump:
```bash
python archive/v1/data/proof/verify.py --generate-hash
python archive/v1/data/proof/verify.py
```
## Tier 2 — Live sensing with an ESP32-S3 ($9)
This is the real thing. Hand off to the `ruview-hardware-setup` skill for the flash/provision/monitor loop, then:
```bash
# Lightweight sensing server (consumes the ESP32 UDP CSI stream)
cd v2
cargo run -p wifi-densepose-sensing-server
# Live RF room scan / SNN learning helpers:
node ../scripts/rf-scan.js --port 5006
node ../scripts/snn-csi-processor.js --port 5006
```
## What to know before you start
- **ESP32-C3 and the original ESP32 are NOT supported** — single-core, can't run the CSI DSP pipeline. Use ESP32-S3 (8MB or 4MB) or ESP32-C6.
- A **single ESP32** has limited spatial resolution — 2+ nodes (or add a Cognitum Seed) for good results.
- Camera-free pose accuracy is limited (~84s to train, modest PCK). For 92.9% PCK@20 use camera-supervised training (see `ruview-model-training` skill, ADR-079).
- No cloud, no internet, no cameras required — everything runs on edge hardware.
## Next steps to suggest
| Goal | Skill / command |
|------|-----------------|
| Flash & provision an ESP32 node | `ruview-hardware-setup` · `/ruview-flash` · `/ruview-provision` |
| Tune channels / MAC filter / edge modules | `ruview-configure` |
| Run a sensing application (presence, vitals, pose, sleep, MAT) | `ruview-applications` · `/ruview-app` |
| Train a pose / sensing model | `ruview-model-training` · `/ruview-train` |
| Multistatic mesh, tomography, cross-viewpoint fusion | `ruview-advanced-sensing` · `/ruview-advanced` |
| Verify the build + generate a witness bundle | `ruview-verify` · `/ruview-verify` |
## Reference
- `README.md` — feature matrix, hardware table, install options
- `docs/user-guide.md`, `docs/wifi-mat-user-guide.md`, `docs/build-guide.md`, `docs/TROUBLESHOOTING.md`
- `docs/tutorials/`, `examples/` — runnable examples (environment, medical, sleep, stress, `ruview_live.py`)
@@ -0,0 +1,97 @@
---
name: ruview-verify
description: Verify a RuView build — full Rust workspace tests, the deterministic Python pipeline proof (SHA-256 Trust Kill Switch), firmware hash manifest, and the ADR-028 witness bundle with one-command self-verification. Use after any significant change, before merging a PR, or to produce an attestation bundle for a recipient.
allowed-tools: Bash Read Write Edit Glob Grep
---
# RuView Verification & Witness Bundle
The trust pipeline for RuView. Run this after meaningful changes and before merging.
## 1. Rust workspace tests
```bash
cd v2
cargo test --workspace --no-default-features # must be 1,400+ passed, 0 failed (~2 min)
```
Single-crate checks (no GPU): `cargo check -p wifi-densepose-train --no-default-features`, `cargo test -p wifi-densepose-signal --no-default-features`, etc.
## 2. Deterministic Python proof (Trust Kill Switch)
Feeds a reference CSI signal through the **production** pipeline and hashes the output. Any behavioural drift changes the hash.
```bash
cd ..
python archive/v1/data/proof/verify.py # must print VERDICT: PASS
```
If it fails on a hash mismatch after a legitimate numpy/scipy bump:
```bash
python archive/v1/data/proof/verify.py --generate-hash
python archive/v1/data/proof/verify.py
```
Artifacts: `archive/v1/data/proof/verify.py`, `expected_features.sha256`, `sample_csi_data.json` (1,000 synthetic frames, seed=42).
## 3. Python test suite (v1)
```bash
cd archive/v1 && python -m pytest tests/ -x -q
```
## 4. Generate the witness bundle (ADR-028)
```bash
bash scripts/generate-witness-bundle.sh
```
Produces `dist/witness-bundle-ADR028-<sha>.tar.gz` containing:
- `WITNESS-LOG-028.md` — 33-row attestation matrix, evidence per capability
- `ADR-028-esp32-capability-audit.md` — full audit findings
- `proof/verify.py` + `expected_features.sha256` — the deterministic proof
- `test-results/rust-workspace-tests.log` — full cargo test output
- `firmware-manifest/source-hashes.txt` — SHA-256 of all 7 ESP32 firmware files
- `crate-manifest/versions.txt` — all 15 crates + versions
- `VERIFY.sh` — one-command self-verification for recipients
## 5. Self-verify the bundle
```bash
cd dist/witness-bundle-ADR028-*/
bash VERIFY.sh # must be 7/7 PASS
```
## Pre-merge checklist (from CLAUDE.md)
1. Rust tests pass (1,400+, 0 fail)
2. Python proof passes (VERDICT: PASS)
3. `README.md` updated if scope changed (platform/crate/hardware tables, feature summaries)
4. `CLAUDE.md` updated if scope changed (crate table, ADR list, module tables, version)
5. `CHANGELOG.md` — entry under `[Unreleased]`
6. `docs/user-guide.md` updated if new data sources / CLI flags / setup steps
7. ADR index — bump ADR count in README docs table if a new ADR was added
8. Witness bundle regenerated if tests or proof hash changed
9. Docker Hub image rebuilt only if Dockerfile / deps / runtime behaviour changed
10. Crate publishing only if a published crate's public API changed (publish in dependency order — see CLAUDE.md)
11. `.gitignore` updated for new build artifacts/binaries
12. Security review for new modules touching hardware/network boundaries
## Security scan
```bash
npx @claude-flow/cli@latest security scan # after security-related changes
```
Also see `docs/security-audit-wasm-edge-vendor.md`, `docs/qe-reports/`, ADR-080 (QE remediation plan), ADR-093 (dashboard gap analysis).
## QEMU firmware CI (ADR-061)
11-job workflow ("Firmware QEMU Tests"). Local QEMU helpers: `scripts/qemu-esp32s3-test.sh`, `qemu-mesh-test.sh`, `qemu-chaos-test.sh`, `qemu-snapshot-test.sh`, `install-qemu.sh`. Notes: `espressif/idf:v5.4` container needs `source $IDF_PATH/export.sh` before `pip`; QEMU needs `esptool merge_bin --fill-flash-size 8MB`; WARNs (no real WiFi) are treated as OK in CI.
## Reference
- `docs/WITNESS-LOG-028.md`, `docs/adr/ADR-028-esp32-capability-audit.md`
- `scripts/generate-witness-bundle.sh`, `archive/v1/data/proof/verify.py`
- `CLAUDE.md` → "Validation & Witness Verification" + "Pre-Merge Checklist"
- `CLAUDE.local.md` → QEMU CI pipeline fixes
+190
View File
@@ -0,0 +1,190 @@
#!/usr/bin/env python3
"""Fix-marker regression guard for RuView.
Reads ``scripts/fix-markers.json`` and asserts that every previously-shipped
fix is still present in the codebase:
* every file listed in a marker must exist;
* every ``require`` pattern must appear in at least one of the marker's files
(a missing pattern means the fix was probably reverted);
* no ``forbid`` pattern may appear in any of the marker's files
(a re-appearing anti-pattern means the bug was re-introduced).
A pattern is a literal substring by default. Wrap it in ``/.../`` to treat it
as a (multiline, case-sensitive) regular expression, e.g. ``"/fall_thresh\\s*=\\s*2\\.0/"``.
This is a stdlib-only script — no dependencies, runs anywhere Python 3.8+ does.
Usage::
python scripts/check_fix_markers.py # check everything (CI)
python scripts/check_fix_markers.py --list # list all markers
python scripts/check_fix_markers.py --json # machine-readable result
python scripts/check_fix_markers.py --only RuView#396 RuView#521
Exit codes: 0 = all markers OK, 1 = one or more regressions, 2 = bad manifest.
"""
from __future__ import annotations
import argparse
import json
import re
import sys
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parent.parent
MANIFEST_PATH = REPO_ROOT / "scripts" / "fix-markers.json"
# Best-effort UTF-8 stdout (Windows consoles default to cp1252); harmless on
# Linux/CI where it's already UTF-8. We still keep all symbols ASCII below so
# the script works even if reconfigure() is unavailable.
try: # pragma: no cover - environment-dependent
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
# ANSI colours — disabled automatically when stdout isn't a TTY (CI logs are
# plain either way, but keep them readable locally).
_TTY = sys.stdout.isatty()
def _c(code: str, s: str) -> str:
return f"\033[{code}m{s}\033[0m" if _TTY else s
GREEN = lambda s: _c("32", s)
RED = lambda s: _c("31", s)
YELLOW = lambda s: _c("33", s)
DIM = lambda s: _c("2", s)
BOLD = lambda s: _c("1", s)
OK_MARK = "PASS"
BAD_MARK = "FAIL"
ARROW = "->"
class ManifestError(Exception):
pass
def load_manifest() -> dict:
if not MANIFEST_PATH.exists():
raise ManifestError(f"manifest not found: {MANIFEST_PATH}")
try:
data = json.loads(MANIFEST_PATH.read_text(encoding="utf-8"))
except json.JSONDecodeError as e:
raise ManifestError(f"manifest is not valid JSON: {e}") from e
if not isinstance(data, dict) or not isinstance(data.get("markers"), list):
raise ManifestError("manifest must be an object with a 'markers' array")
ids = [m.get("id") for m in data["markers"]]
dupes = {i for i in ids if ids.count(i) > 1}
if dupes:
raise ManifestError(f"duplicate marker ids: {sorted(dupes)}")
return data
def _pattern_found(text: str, pattern: str) -> bool:
if len(pattern) >= 2 and pattern.startswith("/") and pattern.endswith("/"):
return re.search(pattern[1:-1], text, re.MULTILINE) is not None
return pattern in text
def check_marker(marker: dict) -> tuple[bool, list[str]]:
"""Return (ok, problems) for a single marker."""
problems: list[str] = []
files = marker.get("files", [])
require = marker.get("require", [])
forbid = marker.get("forbid", [])
if not files:
problems.append("marker lists no files")
return False, problems
contents: dict[str, str] = {}
for rel in files:
p = REPO_ROOT / rel
if not p.exists():
problems.append(f"missing file: {rel}")
continue
try:
contents[rel] = p.read_text(encoding="utf-8", errors="replace")
except OSError as e:
problems.append(f"cannot read {rel}: {e}")
haystack = "\n".join(contents.values())
for pat in require:
if not _pattern_found(haystack, pat):
problems.append(f"required marker absent (fix likely reverted): {pat!r}")
for pat in forbid:
for rel, text in contents.items():
if _pattern_found(text, pat):
problems.append(f"forbidden pattern re-appeared in {rel} (bug re-introduced?): {pat!r}")
return (len(problems) == 0), problems
def cmd_list(manifest: dict) -> int:
print(BOLD(f"{len(manifest['markers'])} fix markers tracked:\n"))
for m in manifest["markers"]:
print(f" {BOLD(m['id']):<28} {m.get('title', '')}")
if m.get("ref"):
print(DIM(f" {m['ref']}"))
for f in m.get("files", []):
print(DIM(f" - {f}"))
return 0
def main(argv: list[str]) -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--list", action="store_true", help="list all markers and exit")
ap.add_argument("--json", action="store_true", help="emit a JSON result object")
ap.add_argument("--only", nargs="+", metavar="ID", help="only check the given marker ids")
args = ap.parse_args(argv)
try:
manifest = load_manifest()
except ManifestError as e:
print(RED(f"[manifest error] {e}"), file=sys.stderr)
return 2
if args.list:
return cmd_list(manifest)
markers = manifest["markers"]
if args.only:
wanted = set(args.only)
markers = [m for m in markers if m["id"] in wanted]
unknown = wanted - {m["id"] for m in markers}
if unknown:
print(RED(f"[error] unknown marker id(s): {sorted(unknown)}"), file=sys.stderr)
return 2
results = []
failed = 0
for m in markers:
ok, problems = check_marker(m)
results.append({"id": m["id"], "title": m.get("title", ""), "ok": ok, "problems": problems})
if not ok:
failed += 1
if args.json:
print(json.dumps({"ok": failed == 0, "checked": len(markers), "failed": failed, "markers": results}, indent=2))
return 0 if failed == 0 else 1
print(BOLD(f"Fix-marker regression guard - {len(markers)} marker(s)\n"))
for r in results:
if r["ok"]:
print(f" {GREEN('[' + OK_MARK + ']')} {r['id']:<28} {DIM(r['title'])}")
else:
print(f" {RED('[' + BAD_MARK + ']')} {BOLD(r['id']):<28} {r['title']}")
for p in r["problems"]:
print(f" {RED(ARROW)} {p}")
print()
if failed:
print(RED(BOLD(f"{failed}/{len(markers)} marker(s) regressed.")))
print(DIM(" A reverted fix is a regression. Restore the marker, or - if the change is"))
print(DIM(" intentional - update scripts/fix-markers.json in the same PR with a rationale."))
return 1
print(GREEN(BOLD(f"All {len(markers)} fix markers present.")))
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
+188
View File
@@ -0,0 +1,188 @@
#!/usr/bin/env python3
"""Transcode an ESP32 .csi.jsonl recording into a .rvcsi capture (JSONL).
This is the moral equivalent of `rvcsi record --source esp32-jsonl` (which the
PR does not ship yet): parse each ESP32 frame, derive amplitude/phase from the
raw int8 I/Q pairs, run the same validation/quality logic rvcsi_core does, and
write a .rvcsi file whose first line is a CaptureHeader and every later line a
CsiFrame. Rejected frames are dropped (quarantine), like the real pipeline.
Usage: esp32_jsonl_to_rvcsi.py <in.csi.jsonl> <out.rvcsi> [--limit N]
"""
import json
import math
import sys
# --- rvcsi_core::ValidationPolicy::default() -------------------------------
MIN_SUBCARRIERS = 1
MAX_SUBCARRIERS = 4096
RSSI_LO, RSSI_HI = -110, 0
MIN_QUALITY = 0.25
RSSI_HARD_MARGIN = 30
def quality_and_status(amplitude, rssi_dbm):
"""Faithful port of rvcsi_core::validation::validate_frame soft scoring."""
reasons = []
q = 1.0
sc = len(amplitude)
# out-of-range (non-fatal) RSSI
if rssi_dbm is not None and (rssi_dbm < RSSI_LO or rssi_dbm > RSSI_HI):
q *= 0.6
reasons.append(f"rssi {rssi_dbm} dBm outside [{RSSI_LO},{RSSI_HI}]")
# dead subcarriers
dead = sum(1 for a in amplitude if a < 1e-6)
if dead > 0:
frac = dead / max(sc, 1)
q *= max(1.0 - frac, 0.05)
reasons.append(f"{dead}/{sc} dead subcarriers")
# amplitude spike vs median
if sc >= 3:
s = sorted(amplitude)
median = max(s[sc // 2], 1e-9)
mx = s[-1]
if mx > median * 50.0:
q *= 0.7
reasons.append(f"amplitude spike: max {mx:.3f} vs median {median:.3f}")
if rssi_dbm is None:
q *= 0.95
reasons.append("missing rssi")
q = min(max(q, 0.0), 1.0)
if q < MIN_QUALITY:
status = "Degraded" # degrade_instead_of_reject = true
else:
status = "Accepted"
return q, status, reasons
def main():
if len(sys.argv) < 3:
print(__doc__)
sys.exit(2)
in_path, out_path = sys.argv[1], sys.argv[2]
limit = None
if "--limit" in sys.argv:
limit = int(sys.argv[sys.argv.index("--limit") + 1])
source_id = "esp32-com7-rec"
header = {
"rvcsi_capture_version": 1,
"session_id": 0,
"source_id": source_id,
"adapter_profile": {
"adapter_kind": "Esp32",
"chip": "ESP32-S3",
"firmware_version": None,
"driver_version": None,
"supported_channels": [],
"supported_bandwidths_mhz": [],
"expected_subcarrier_counts": [],
"supports_live_capture": True,
"supports_injection": False,
"supports_monitor_mode": False,
},
"validation_policy": {
"min_subcarriers": MIN_SUBCARRIERS,
"max_subcarriers": MAX_SUBCARRIERS,
"rssi_dbm_bounds": [RSSI_LO, RSSI_HI],
"strict_monotonic_time": False,
"degrade_instead_of_reject": True,
"min_quality": MIN_QUALITY,
},
"calibration_version": None,
"runtime_config_json": "{}",
"created_unix_ns": 0,
}
stats = {
"read": 0, "written": 0,
"rej_len": 0, "rej_sc": 0, "rej_nonfinite": 0, "rej_rssi": 0,
"accepted": 0, "degraded": 0,
}
sc_hist = {}
out = open(out_path, "w", newline="\n")
out.write(json.dumps(header, separators=(",", ":")) + "\n")
fid = 0
with open(in_path) as f:
for line in f:
line = line.strip()
if not line:
continue
d = json.loads(line)
if d.get("type") != "raw_csi":
continue
stats["read"] += 1
if limit is not None and stats["read"] > limit:
stats["read"] -= 1
break
iq_hex = d.get("iq_hex", "")
raw = bytes.fromhex(iq_hex)
n_pairs = len(raw) // 2
# ESP-IDF CSI buffer layout: [imag0, real0, imag1, real1, ...] as int8
i_vals, q_vals, amp, ph = [], [], [], []
for k in range(n_pairs):
imag = raw[2 * k]
real = raw[2 * k + 1]
if imag >= 128:
imag -= 256
if real >= 128:
real -= 256
fi, fq = float(real), float(imag)
i_vals.append(fi)
q_vals.append(fq)
amp.append(math.sqrt(fi * fi + fq * fq))
ph.append(math.atan2(fq, fi))
sc = n_pairs
sc_hist[sc] = sc_hist.get(sc, 0) + 1
# hard checks (mirror validate_frame)
if sc < MIN_SUBCARRIERS or sc > MAX_SUBCARRIERS:
stats["rej_sc"] += 1
continue
# int8 -> always finite, lengths consistent by construction
# RSSI: the v1 collector's rssi byte is unreliable (sentinels 64/-128
# etc.); only carry it through when it lands in a plausible band,
# otherwise leave it None (a small quality penalty, not a reject).
r = d.get("rssi")
rssi_dbm = r if (isinstance(r, int) and -140 <= r <= 30) else None
if rssi_dbm is not None and (rssi_dbm < RSSI_LO - RSSI_HARD_MARGIN or rssi_dbm > RSSI_HI + RSSI_HARD_MARGIN):
stats["rej_rssi"] += 1
continue
if rssi_dbm is not None and not (-110 <= rssi_dbm <= 0):
rssi_dbm = None # implausible but not insane -> drop the field
q, status, reasons = quality_and_status(amp, rssi_dbm)
ch = d.get("channel", 0) or 0
frame = {
"frame_id": fid,
"session_id": 0,
"source_id": source_id,
"adapter_kind": "Esp32",
"timestamp_ns": int(d.get("ts_ns", 0)),
"channel": int(ch),
"bandwidth_mhz": 20,
"rssi_dbm": rssi_dbm,
"noise_floor_dbm": None,
"antenna_index": 0,
"tx_chain": None,
"rx_chain": None,
"subcarrier_count": sc,
"i_values": i_vals,
"q_values": q_vals,
"amplitude": amp,
"phase": ph,
"validation": status,
"quality_score": q,
}
if reasons:
frame["quality_reasons"] = reasons
frame["calibration_version"] = None
out.write(json.dumps(frame, separators=(",", ":")) + "\n")
fid += 1
stats["written"] += 1
stats[status.lower()] = stats.get(status.lower(), 0) + 1
out.close()
print("transcode stats:", json.dumps(stats))
print("subcarrier-count histogram:", json.dumps(dict(sorted(sc_hist.items(), key=lambda x: -x[1]))))
if __name__ == "__main__":
main()
+115
View File
@@ -0,0 +1,115 @@
{
"_comment": "Fix-marker regression guard for RuView. Each marker asserts that a previously-shipped fix is still present. CI (.github/workflows/fix-regression-guard.yml) fails if a `require` pattern is missing from all of a marker's `files` (the fix was likely reverted) or if a `forbid` pattern reappears (the bug was re-introduced). Run locally: `python scripts/check_fix_markers.py` (or `--list`, `--json`, `--only ID`). Patterns are literal substrings unless wrapped in /.../ (regex). Add a marker whenever you ship a fix that would be expensive to silently lose.",
"schema_version": 1,
"markers": [
{
"id": "RuView#396",
"title": "ESP32-S3 CSI: MGMT-only promiscuous filter (SPI flash cache race crash fix)",
"files": ["firmware/esp32-csi-node/main/csi_collector.c"],
"require": ["WIFI_PROMIS_FILTER_MASK_MGMT", "RuView#396"],
"rationale": "Promiscuous MGMT+DATA produces 100-500 Hz HW interrupts that crash Core 0 in wDev_ProcessFiq (SPI flash cache race in the WiFi blob). Reverting to the full filter reintroduces the boot-loop / crash.",
"ref": "https://github.com/ruvnet/RuView/issues/396"
},
{
"id": "RuView#521",
"title": "ESP32-S3 CSI: disable WiFi modem sleep (WIFI_PS_NONE) so the CSI callback isn't starved",
"files": ["firmware/esp32-csi-node/main/csi_collector.c"],
"require": ["esp_wifi_set_ps(WIFI_PS_NONE)", "RuView#521"],
"rationale": "The ESP-IDF STA default WIFI_PS_MIN_MODEM lets the modem sleep between DTIM beacons; combined with the MGMT-only filter the per-second CSI yield collapses toward 0 pps. csi_collector_init() must force WIFI_PS_NONE.",
"ref": "https://github.com/ruvnet/RuView/issues/521"
},
{
"id": "RuView#517",
"title": "Aggregator classifies sibling RuView UDP packet magics instead of erroring on them",
"files": [
"v2/crates/wifi-densepose-hardware/src/esp32_parser.rs",
"v2/crates/wifi-densepose-hardware/src/error.rs",
"v2/crates/wifi-densepose-hardware/src/bin/aggregator.rs"
],
"require": ["ruview_sibling_packet_name", "NonCsiPacket", "RUVIEW_VITALS_MAGIC"],
"rationale": "The firmware multiplexes 0xC5110002..0xC5110007 (vitals, feature, fused, compressed, feature-state, temporal) onto the CSI UDP port. The parser must report these as ParseError::NonCsiPacket so the aggregator can skip them, not log 'invalid magic' parse-error noise.",
"ref": "https://github.com/ruvnet/RuView/issues/517"
},
{
"id": "RuView#505",
"title": "Firmware release: version.txt must match the release tag (firmware-ci version-guard)",
"files": [".github/workflows/firmware-ci.yml"],
"require": ["version-guard", "version.txt"],
"rationale": "v0.6.3-esp32 shipped a binary that internally identified as 0.6.2 because version.txt was never bumped. The version-guard job fails the release run when the tag's X.Y.Z doesn't match firmware/esp32-csi-node/version.txt.",
"ref": "https://github.com/ruvnet/RuView/issues/505"
},
{
"id": "RuView#354",
"title": "Firmware embeds its version from version.txt and logs it at boot",
"files": [
"firmware/esp32-csi-node/CMakeLists.txt",
"firmware/esp32-csi-node/main/main.c"
],
"require": ["PROJECT_VER", "version.txt", "esp_app_get_description"],
"rationale": "esp_app_get_description()->version must derive from version.txt (CMake file(STRINGS ...)), and the boot log line surfaces it for fleet monitoring.",
"ref": "https://github.com/ruvnet/RuView/issues/354"
},
{
"id": "RuView#263",
"title": "Fall detection: default threshold 15.0 rad/s2 + consecutive-frame debounce + cooldown",
"files": [
"firmware/esp32-csi-node/main/nvs_config.c",
"firmware/esp32-csi-node/main/edge_processing.c",
"firmware/esp32-csi-node/main/edge_processing.h"
],
"require": ["15.0f", "EDGE_FALL_CONSEC_MIN", "EDGE_FALL_COOLDOWN_MS"],
"forbid": ["/fall_thresh\\s*=\\s*2\\.0f\\b/"],
"rationale": "Default fall_thresh of 2.0 rad/s2 caused alert storms (false positives). 15.0 with a 3-consecutive-frame debounce + 5 s cooldown verified 0 false alerts in 600 frames on COM7.",
"ref": "https://github.com/ruvnet/RuView/issues/263"
},
{
"id": "RuView#266-321",
"title": "Edge DSP task: batch limit so it can't starve IDLE1 and trip the task watchdog",
"files": ["firmware/esp32-csi-node/main/edge_processing.c", "firmware/esp32-csi-node/main/edge_processing.h"],
"require": ["EDGE_BATCH_LIMIT"],
"rationale": "On busy LANs the edge DSP task processed frames back-to-back with only 1-tick yields, starving IDLE1 enough to trip the 5-second task watchdog. The batch limit forces a longer yield every N frames.",
"ref": "https://github.com/ruvnet/RuView/issues/266"
},
{
"id": "RuView#265",
"title": "4 MB flash variant: dual-OTA partition table + 4mb sdkconfig, built by firmware-ci",
"files": [
"firmware/esp32-csi-node/partitions_4mb.csv",
"firmware/esp32-csi-node/sdkconfig.defaults.4mb",
".github/workflows/firmware-ci.yml"
],
"require": ["sdkconfig.defaults.4mb"],
"rationale": "Support for ESP32-S3-N16R8 / N8R2 and other 4 MB boards. The firmware-ci build matrix must keep building the 4mb variant so it doesn't bit-rot.",
"ref": "https://github.com/ruvnet/RuView/issues/265"
},
{
"id": "RuView#232-375-385-386-390",
"title": "ESP32-S3 CSI: defensive early-capture of NVS config before wifi_init_sta() corrupts it",
"files": ["firmware/esp32-csi-node/main/csi_collector.c"],
"require": ["early capture", "s_filter_mac"],
"rationale": "wifi_init_sta() can clobber g_nvs_config (confirmed on device 80:b5:4e:c1:be:b8). Module-local statics must be captured before WiFi init and used by the CSI callback instead of g_nvs_config.",
"ref": "https://github.com/ruvnet/RuView/issues/390"
},
{
"id": "ADR-028-proof",
"title": "Deterministic pipeline proof (Trust Kill Switch): artifacts present and re-run in CI",
"files": [
"archive/v1/data/proof/verify.py",
"archive/v1/data/proof/expected_features.sha256",
"archive/v1/data/proof/sample_csi_data.json",
".github/workflows/verify-pipeline.yml"
],
"require": ["VERDICT", "expected_features.sha256", "verify.py"],
"rationale": "verify.py feeds a seeded reference signal through the production CSI pipeline and SHA-256-hashes the output; expected_features.sha256 pins it; verify-pipeline.yml re-runs it on every PR. Losing any of these removes the project's tamper-evidence guarantee (ADR-028).",
"ref": "docs/adr/ADR-028-esp32-capability-audit.md"
},
{
"id": "ADR-028-witness-bundle",
"title": "Release-time witness bundle generator + self-verification script",
"files": ["scripts/generate-witness-bundle.sh"],
"require": ["VERIFY.sh", "witness-bundle"],
"rationale": "scripts/generate-witness-bundle.sh produces the self-contained, recipient-verifiable witness bundle (witness log + proof + test results + firmware hashes + VERIFY.sh). Part of the ADR-028 attestation chain.",
"ref": "docs/WITNESS-LOG-028.md"
}
]
}
Generated
+293 -7
View File
@@ -231,6 +231,18 @@ dependencies = [
"wait-timeout",
]
[[package]]
name = "async-compression"
version = "0.4.42"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e79b3f8a79cccc2898f31920fc69f304859b3bd567490f75ebf51ae1c792a9ac"
dependencies = [
"compression-codecs",
"compression-core",
"pin-project-lite",
"tokio",
]
[[package]]
name = "async-trait"
version = "0.1.89"
@@ -318,7 +330,7 @@ dependencies = [
"sync_wrapper 1.0.2",
"tokio",
"tokio-tungstenite",
"tower",
"tower 0.5.3",
"tower-layer",
"tower-service",
"tracing",
@@ -871,6 +883,23 @@ dependencies = [
"memchr",
]
[[package]]
name = "compression-codecs"
version = "0.4.38"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce2548391e9c1929c21bf6aa2680af86fe4c1b33e6cea9ac1cfeec0bd11218cf"
dependencies = [
"compression-core",
"flate2",
"memchr",
]
[[package]]
name = "compression-core"
version = "0.4.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc14f565cf027a105f7a44ccf9e5b424348421a1d8952a8fc9d499d313107789"
[[package]]
name = "concurrent-queue"
version = "2.5.0"
@@ -915,6 +944,15 @@ version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e"
[[package]]
name = "convert_case"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec182b0ca2f35d8fc196cf3404988fd8b8c739a4d270ff118a398feb0cbec1ca"
dependencies = [
"unicode-segmentation",
]
[[package]]
name = "cookie"
version = "0.18.1"
@@ -1256,7 +1294,7 @@ version = "0.99.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6edb4b64a43d977b8e99788fe3a04d483834fba1215a7e02caa415b626497f7f"
dependencies = [
"convert_case",
"convert_case 0.4.0",
"proc-macro2",
"quote",
"rustc_version",
@@ -2371,6 +2409,16 @@ version = "0.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
[[package]]
name = "hdrhistogram"
version = "7.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "765c9198f173dd59ce26ff9f95ef0aafd0a0fe01fb9d72841bc5066a4c06511d"
dependencies = [
"byteorder",
"num-traits",
]
[[package]]
name = "heapless"
version = "0.6.1"
@@ -3152,7 +3200,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e9ec52138abedcc58dc17a7c6c0c00a2bdb4f3427c7f63fa97fd0d859155caf"
dependencies = [
"gtk-sys",
"libloading",
"libloading 0.7.4",
"once_cell",
]
@@ -3172,6 +3220,16 @@ dependencies = [
"winapi",
]
[[package]]
name = "libloading"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"
dependencies = [
"cfg-if",
"windows-link 0.2.1",
]
[[package]]
name = "libm"
version = "0.2.16"
@@ -3585,6 +3643,63 @@ dependencies = [
"getrandom 0.2.17",
]
[[package]]
name = "napi"
version = "2.16.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "55740c4ae1d8696773c78fdafd5d0e5fe9bc9f1b071c7ba493ba5c413a9184f3"
dependencies = [
"bitflags 2.11.0",
"ctor",
"napi-derive",
"napi-sys",
"once_cell",
]
[[package]]
name = "napi-build"
version = "2.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d376940fd5b723c6893cd1ee3f33abbfd86acb1cd1ec079f3ab04a2a3bc4d3b1"
[[package]]
name = "napi-derive"
version = "2.16.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7cbe2585d8ac223f7d34f13701434b9d5f4eb9c332cccce8dee57ea18ab8ab0c"
dependencies = [
"cfg-if",
"convert_case 0.6.0",
"napi-derive-backend",
"proc-macro2",
"quote",
"syn 2.0.117",
]
[[package]]
name = "napi-derive-backend"
version = "1.0.75"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1639aaa9eeb76e91c6ae66da8ce3e89e921cd3885e99ec85f4abacae72fc91bf"
dependencies = [
"convert_case 0.6.0",
"once_cell",
"proc-macro2",
"quote",
"regex",
"semver",
"syn 2.0.117",
]
[[package]]
name = "napi-sys"
version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "427802e8ec3a734331fec1035594a210ce1ff4dc5bc1950530920ab717964ea3"
dependencies = [
"libloading 0.8.9",
]
[[package]]
name = "native-tls"
version = "0.2.18"
@@ -3892,13 +4007,35 @@ name = "nvsim"
version = "0.3.0"
dependencies = [
"approx 0.5.1",
"criterion",
"js-sys",
"rand 0.8.5",
"rand_chacha 0.3.1",
"serde",
"serde-wasm-bindgen",
"serde_json",
"sha2",
"thiserror 1.0.69",
"tracing",
"wasm-bindgen",
]
[[package]]
name = "nvsim-server"
version = "0.3.0"
dependencies = [
"axum",
"clap",
"futures-util",
"nvsim",
"serde",
"serde_json",
"thiserror 1.0.69",
"tokio",
"tower 0.4.13",
"tower-http 0.5.2",
"tracing",
"tracing-subscriber",
]
[[package]]
@@ -4487,6 +4624,26 @@ dependencies = [
"siphasher 1.0.2",
]
[[package]]
name = "pin-project"
version = "1.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cbf0d9e68100b3a7989b4901972f265cd542e560a3a8a724e1e20322f4d06ce9"
dependencies = [
"pin-project-internal",
]
[[package]]
name = "pin-project-internal"
version = "1.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a990e22f43e84855daf260dded30524ef4a9021cc7541c26540500a50b624389"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.117",
]
[[package]]
name = "pin-project-lite"
version = "0.2.17"
@@ -5278,7 +5435,7 @@ dependencies = [
"sync_wrapper 1.0.2",
"tokio",
"tokio-native-tls",
"tower",
"tower 0.5.3",
"tower-http 0.6.8",
"tower-service",
"url",
@@ -5311,7 +5468,7 @@ dependencies = [
"sync_wrapper 1.0.2",
"tokio",
"tokio-util",
"tower",
"tower 0.5.3",
"tower-http 0.6.8",
"tower-service",
"url",
@@ -5798,6 +5955,111 @@ version = "2.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "178f93f84a4a72c582026a45d9b8710acf188df4a22a25434c5dbba1df6c4cac"
[[package]]
name = "rvcsi-adapter-file"
version = "0.3.0"
dependencies = [
"rvcsi-core",
"serde",
"serde_json",
"tempfile",
"thiserror 1.0.69",
]
[[package]]
name = "rvcsi-adapter-nexmon"
version = "0.3.0"
dependencies = [
"cc",
"rvcsi-core",
"thiserror 1.0.69",
]
[[package]]
name = "rvcsi-cli"
version = "0.3.0"
dependencies = [
"anyhow",
"clap",
"rvcsi-adapter-file",
"rvcsi-adapter-nexmon",
"rvcsi-core",
"rvcsi-runtime",
"serde",
"serde_json",
"tempfile",
]
[[package]]
name = "rvcsi-core"
version = "0.3.0"
dependencies = [
"serde",
"serde_json",
"thiserror 1.0.69",
]
[[package]]
name = "rvcsi-dsp"
version = "0.3.0"
dependencies = [
"rvcsi-core",
"serde",
"serde_json",
"thiserror 1.0.69",
]
[[package]]
name = "rvcsi-events"
version = "0.3.0"
dependencies = [
"rvcsi-core",
"serde",
"serde_json",
"thiserror 1.0.69",
]
[[package]]
name = "rvcsi-node"
version = "0.3.0"
dependencies = [
"napi",
"napi-build",
"napi-derive",
"rvcsi-adapter-nexmon",
"rvcsi-core",
"rvcsi-runtime",
"serde",
"serde_json",
"tempfile",
]
[[package]]
name = "rvcsi-runtime"
version = "0.3.0"
dependencies = [
"rvcsi-adapter-file",
"rvcsi-adapter-nexmon",
"rvcsi-core",
"rvcsi-dsp",
"rvcsi-events",
"rvcsi-ruvector",
"serde",
"serde_json",
"tempfile",
]
[[package]]
name = "rvcsi-ruvector"
version = "0.3.0"
dependencies = [
"rvcsi-core",
"serde",
"serde_json",
"tempfile",
"thiserror 1.0.69",
]
[[package]]
name = "ryu"
version = "1.0.23"
@@ -7379,6 +7641,27 @@ dependencies = [
"zip 0.6.6",
]
[[package]]
name = "tower"
version = "0.4.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8fa9be0de6cf49e536ce1851f987bd21a43b771b09473c3549a6c853db37c1c"
dependencies = [
"futures-core",
"futures-util",
"hdrhistogram",
"indexmap 1.9.3",
"pin-project",
"pin-project-lite",
"rand 0.8.5",
"slab",
"tokio",
"tokio-util",
"tower-layer",
"tower-service",
"tracing",
]
[[package]]
name = "tower"
version = "0.5.3"
@@ -7401,8 +7684,10 @@ version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e9cd434a998747dd2c4276bc96ee2e0c7a2eadf3cae88e52be55a05fa9053f5"
dependencies = [
"async-compression",
"bitflags 2.11.0",
"bytes",
"futures-core",
"futures-util",
"http 1.4.0",
"http-body 1.0.1",
@@ -7433,7 +7718,7 @@ dependencies = [
"http-body 1.0.1",
"iri-string",
"pin-project-lite",
"tower",
"tower 0.5.3",
"tower-layer",
"tower-service",
]
@@ -8385,6 +8670,7 @@ dependencies = [
"serde",
"serde_json",
"tokio",
"tower-http 0.5.2",
]
[[package]]
@@ -8454,7 +8740,7 @@ dependencies = [
[[package]]
name = "wifi-densepose-train"
version = "0.3.0"
version = "0.3.1"
dependencies = [
"anyhow",
"approx 0.5.1",
+12
View File
@@ -21,6 +21,11 @@ members = [
"crates/wifi-densepose-geo",
"crates/nvsim",
"crates/nvsim-server",
# rvCSI — edge RF sensing runtime (ADR-095 platform, ADR-096 FFI/crate layout):
# lives in its own repo (https://github.com/ruvnet/rvcsi), vendored here as
# `vendor/rvcsi` and published to crates.io as `rvcsi-*` 0.3.x. Depend on the
# published crates (or the submodule's `crates/rvcsi-*` paths) — not as v2
# workspace members, since `vendor/rvcsi/Cargo.toml` is its own workspace.
]
# ADR-040: WASM edge crate targets wasm32-unknown-unknown (no_std),
# excluded from workspace to avoid breaking `cargo test --workspace`.
@@ -108,6 +113,13 @@ indicatif = "0.17"
# CLI
clap = { version = "4.4", features = ["derive", "env"] }
# rvCSI: napi-rs (Rust -> Node bindings) + napi-c (C-shim build glue)
napi = { version = "2.16", default-features = false, features = ["napi8"] }
napi-derive = "2.16"
napi-build = "2.1"
cc = "1.0"
libc = "0.2"
# Testing
criterion = { version = "0.5", features = ["html_reports"] }
proptest = "1.4"
@@ -10,7 +10,7 @@ use std::net::UdpSocket;
use std::process;
use clap::Parser;
use wifi_densepose_hardware::Esp32CsiParser;
use wifi_densepose_hardware::{Esp32CsiParser, ParseError};
/// UDP aggregator for ESP32 CSI nodes (ADR-018).
#[derive(Parser)]
@@ -65,6 +65,15 @@ fn main() {
mean_amp,
);
}
// The firmware sends several packet types on this UDP port
// (ADR-039 vitals, ADR-081 feature state, ADR-095 temporal, …)
// alongside ADR-018 CSI frames. Those are expected, not errors —
// this CSI-only aggregator just skips them. (RuView#517)
Err(ParseError::NonCsiPacket { kind, .. }) => {
if cli.verbose {
eprintln!(" [skipped {} packet — not a CSI frame]", kind);
}
}
Err(e) => {
if cli.verbose {
eprintln!(" parse error: {}", e);
@@ -19,6 +19,18 @@ pub enum ParseError {
got: u32,
},
/// A recognized RuView wire packet was received that is *not* an
/// ADR-018 raw CSI frame (e.g. ADR-039 vitals, ADR-081 feature state,
/// ADR-095 temporal classification). The firmware multiplexes several
/// packet types onto the same UDP port, so a CSI parser will see these
/// interleaved with CSI frames — that is expected, not a corruption.
/// Consumers should route the packet to the matching decoder or skip it.
#[error("Non-CSI RuView packet on CSI socket: {kind} (magic {magic:#010x})")]
NonCsiPacket {
magic: u32,
kind: &'static str,
},
/// The frame indicates more subcarriers than physically possible.
#[error("Invalid subcarrier count: {count} (max {max})")]
InvalidSubcarrierCount {
@@ -35,7 +35,43 @@ use crate::csi_frame::{AntennaConfig, Bandwidth, CsiFrame, CsiMetadata, Subcarri
use crate::error::ParseError;
/// ESP32 CSI binary frame magic number (ADR-018).
const ESP32_CSI_MAGIC: u32 = 0xC5110001;
pub const ESP32_CSI_MAGIC: u32 = 0xC5110001;
// ── Sibling RuView wire packets ──────────────────────────────────────────────
// The ESP32 firmware multiplexes several packet types onto the same UDP port
// as ADR-018 raw CSI frames. A CSI-only consumer will therefore see these
// interleaved with CSI frames. They are *not* corruption — they just need a
// different decoder (or can be skipped). See firmware `rv_feature_state.h`.
/// ADR-039 edge vitals packet (32 bytes: HR/BR/presence).
pub const RUVIEW_VITALS_MAGIC: u32 = 0xC5110002;
/// ADR-069 feature-vector packet.
pub const RUVIEW_FEATURE_MAGIC: u32 = 0xC5110003;
/// ADR-063 fused-vitals packet (multi-sensor fusion).
pub const RUVIEW_FUSED_VITALS_MAGIC: u32 = 0xC5110004;
/// ADR-039 compressed-CSI packet.
pub const RUVIEW_COMPRESSED_CSI_MAGIC: u32 = 0xC5110005;
/// ADR-081 compact feature-state packet (the default upstream payload).
pub const RUVIEW_FEATURE_STATE_MAGIC: u32 = 0xC5110006;
/// ADR-095 / #513 on-device temporal-classification packet.
pub const RUVIEW_TEMPORAL_MAGIC: u32 = 0xC5110007;
/// If `magic` is a recognized RuView wire packet other than the ADR-018 raw
/// CSI frame, return a human-readable name for it; otherwise `None`.
///
/// Used by CSI consumers to distinguish "a sibling packet I should route or
/// skip" from "genuine garbage on the wire".
pub fn ruview_sibling_packet_name(magic: u32) -> Option<&'static str> {
match magic {
RUVIEW_VITALS_MAGIC => Some("ADR-039 edge vitals"),
RUVIEW_FEATURE_MAGIC => Some("ADR-069 feature vector"),
RUVIEW_FUSED_VITALS_MAGIC => Some("ADR-063 fused vitals"),
RUVIEW_COMPRESSED_CSI_MAGIC => Some("ADR-039 compressed CSI"),
RUVIEW_FEATURE_STATE_MAGIC => Some("ADR-081 feature state"),
RUVIEW_TEMPORAL_MAGIC => Some("ADR-095 temporal classification"),
_ => None,
}
}
/// ADR-018 header size in bytes (before I/Q data).
const HEADER_SIZE: usize = 20;
@@ -55,6 +91,18 @@ impl Esp32CsiParser {
/// The buffer must contain at least the header (20 bytes) plus the I/Q data.
/// Returns the parsed frame and the number of bytes consumed.
pub fn parse_frame(data: &[u8]) -> Result<(CsiFrame, usize), ParseError> {
// A recognized sibling packet (ADR-039 vitals, ADR-081 feature state, …)
// multiplexed onto the CSI UDP port should be reported as such — not as
// "insufficient data" or "invalid magic" — so callers can route or skip
// it. These packets are all >= 4 bytes; classify before the CSI-frame
// length gate. (RuView#517)
if data.len() >= 4 {
let magic = u32::from_le_bytes([data[0], data[1], data[2], data[3]]);
if let Some(kind) = ruview_sibling_packet_name(magic) {
return Err(ParseError::NonCsiPacket { magic, kind });
}
}
if data.len() < HEADER_SIZE {
return Err(ParseError::InsufficientData {
needed: HEADER_SIZE,
@@ -310,12 +358,50 @@ mod tests {
#[test]
fn test_parse_invalid_magic() {
let mut data = build_test_frame(1, 1, &[(10, 20)]);
// Corrupt magic
data[0] = 0xFF;
// Corrupt magic to a value that isn't any known RuView packet.
data[0..4].copy_from_slice(&0xDEAD_BEEFu32.to_le_bytes());
let result = Esp32CsiParser::parse_frame(&data);
assert!(matches!(result, Err(ParseError::InvalidMagic { .. })));
}
#[test]
fn test_sibling_vitals_packet_is_not_invalid_magic() {
// RuView#517: a 32-byte ADR-039 vitals packet (magic 0xC5110002)
// arrives on the same UDP port as CSI frames. It must be reported as
// a recognized sibling packet, not a corrupt CSI frame.
let mut data = vec![0u8; 32];
data[0..4].copy_from_slice(&RUVIEW_VITALS_MAGIC.to_le_bytes());
match Esp32CsiParser::parse_frame(&data) {
Err(ParseError::NonCsiPacket { magic, kind }) => {
assert_eq!(magic, RUVIEW_VITALS_MAGIC);
assert_eq!(kind, "ADR-039 edge vitals");
}
other => panic!("expected NonCsiPacket, got {other:?}"),
}
}
#[test]
fn test_all_sibling_magics_classified() {
for m in [
RUVIEW_VITALS_MAGIC,
RUVIEW_FEATURE_MAGIC,
RUVIEW_FUSED_VITALS_MAGIC,
RUVIEW_COMPRESSED_CSI_MAGIC,
RUVIEW_FEATURE_STATE_MAGIC,
RUVIEW_TEMPORAL_MAGIC,
] {
assert!(ruview_sibling_packet_name(m).is_some(), "{m:#010x} unclassified");
let mut data = vec![0u8; 24];
data[0..4].copy_from_slice(&m.to_le_bytes());
assert!(
matches!(Esp32CsiParser::parse_frame(&data), Err(ParseError::NonCsiPacket { .. })),
"{m:#010x} should parse as NonCsiPacket"
);
}
// The CSI magic itself is not a "sibling".
assert!(ruview_sibling_packet_name(ESP32_CSI_MAGIC).is_none());
}
#[test]
fn test_amplitude_phase_from_known_iq() {
let pairs = vec![(100i8, 0i8), (0, 50), (30, 40)];
+5 -1
View File
@@ -49,7 +49,11 @@ pub mod radio_ops;
pub use csi_frame::{CsiFrame, CsiMetadata, SubcarrierData, Bandwidth, AntennaConfig};
pub use error::ParseError;
pub use esp32_parser::Esp32CsiParser;
pub use esp32_parser::{
Esp32CsiParser, ruview_sibling_packet_name, ESP32_CSI_MAGIC, RUVIEW_VITALS_MAGIC,
RUVIEW_FEATURE_MAGIC, RUVIEW_FUSED_VITALS_MAGIC, RUVIEW_COMPRESSED_CSI_MAGIC,
RUVIEW_FEATURE_STATE_MAGIC, RUVIEW_TEMPORAL_MAGIC,
};
pub use bridge::CsiData;
pub use radio_ops::{
RadioOps, RadioMode, CaptureProfile, RadioHealth, RadioError, MockRadio,
+6 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "wifi-densepose-train"
version = "0.3.0"
version = "0.3.1"
edition = "2021"
authors = ["rUv <ruv@ruv.net>", "WiFi-DensePose Contributors"]
license = "MIT OR Apache-2.0"
@@ -85,6 +85,11 @@ criterion.workspace = true
proptest.workspace = true
tempfile = "3.10"
approx = "0.5"
# Used by tests/test_real_loader.rs to write .npy fixtures that exercise the
# real MmFiDataset disk-loading path (the deterministic proof uses the
# in-memory SyntheticCsiDataset, which bypasses .npy parsing).
ndarray.workspace = true
ndarray-npy.workspace = true
[[bench]]
name = "training_bench"
+61 -5
View File
@@ -15,6 +15,15 @@
//!
//! assert_eq!(cfg.num_subcarriers, 56);
//! assert_eq!(cfg.num_keypoints, 17);
//!
//! // Adapt for a non-MM-Fi source — e.g. an ESP32 HT40 capture (~192 raw
//! // subcarriers) or the ADR-078 multi-band mesh (168). The model still sees
//! // `num_subcarriers`; the loader resamples the native count down to it.
//! let ht40 = TrainingConfig::ht40_192();
//! assert_eq!(ht40.native_subcarriers, 192);
//! assert!(ht40.needs_subcarrier_interp());
//! let mesh = TrainingConfig::for_subcarriers(168, 56);
//! assert_eq!(mesh.native_subcarriers, 168);
//! ```
use serde::{Deserialize, Serialize};
@@ -36,16 +45,26 @@ pub struct TrainingConfig {
// -----------------------------------------------------------------------
// Data / Signal
// -----------------------------------------------------------------------
/// Number of subcarriers after interpolation (system target).
/// Number of subcarriers after interpolation (the *model's* input width).
///
/// The model always sees this many subcarriers regardless of the raw
/// hardware output. Default: **56**.
/// hardware output; [`crate::subcarrier::interpolate_subcarriers`] resamples
/// `native_subcarriers` → `num_subcarriers` when they differ. Default: **56**.
pub num_subcarriers: usize,
/// Number of subcarriers in the raw dataset before interpolation.
/// Number of subcarriers in the *raw* dataset, before interpolation.
///
/// MM-Fi provides 114 subcarriers; set this to 56 when the dataset
/// already matches the target count. Default: **114**.
/// Common sources: MM-Fi = 114, ESP32 HT20 = 56, ESP32 HT40 ≈ 192 (or 114),
/// multi-band mesh = 168 (ADR-078). When it equals [`Self::num_subcarriers`]
/// no interpolation happens ([`Self::needs_subcarrier_interp`]). For the
/// non-MM-Fi shapes prefer the preset constructors
/// ([`Self::for_subcarriers`], [`Self::ht40_192`], [`Self::multiband_168`])
/// over overriding both fields by hand. Default: **114**.
///
/// **Multi-NIC note:** a 23-node CSI mesh currently maps onto the existing
/// `[T, n_tx, n_rx, n_sc]` layout by treating the nodes' receive chains as
/// extra `n_rx` (i.e. `num_antennas_rx = nodes × per_node_rx`); a dedicated
/// node dimension is a separate dataset-loader change.
pub native_subcarriers: usize,
/// Number of transmit antennas. Default: **3**.
@@ -238,6 +257,43 @@ impl TrainingConfig {
Ok(())
}
/// Build a config for a dataset whose raw CSI has `native` subcarriers,
/// resampling to `target` (the model's input width) before training.
///
/// All other fields take their [`Default`] values. Prefer this over
/// overriding `native_subcarriers` / `num_subcarriers` directly so the
/// relationship between the dataset's shape and the model's is explicit.
#[must_use]
pub fn for_subcarriers(native: usize, target: usize) -> Self {
Self {
native_subcarriers: native,
num_subcarriers: target,
..Self::default()
}
}
/// Preset for the MM-Fi dataset (114 raw subcarriers → 56). Identical to
/// [`Self::default()`]; provided as a named counterpart to the other
/// presets.
#[must_use]
pub fn mmfi() -> Self {
Self::default()
}
/// Preset for ESP32 HT40 captures (≈192 raw subcarriers → 56). Use
/// [`Self::for_subcarriers`] if your capture reports a different native
/// count (some HT40 firmwares yield 114).
#[must_use]
pub fn ht40_192() -> Self {
Self::for_subcarriers(192, 56)
}
/// Preset for the ADR-078 multi-band mesh (168 raw subcarriers → 56).
#[must_use]
pub fn multiband_168() -> Self {
Self::for_subcarriers(168, 56)
}
/// Returns `true` when the native dataset subcarrier count differs from the
/// model's target count and interpolation is therefore required.
pub fn needs_subcarrier_interp(&self) -> bool {
@@ -92,6 +92,23 @@ pub struct CsiSample {
pub frame_id: u64,
}
impl CsiSample {
/// Derive the compact signal-processing feature vector for this sample
/// via [`crate::signal_features::extract_signal_features`] (see that
/// function for the layout, and [`crate::signal_features::FEATURE_LEN`]
/// for its length).
///
/// Computed on demand from [`Self::amplitude`]/[`Self::phase`] — not
/// cached on the struct. This is the hook for folding the SOTA
/// signal-processing crate's amplitude/phase/PSD features (and, in a
/// later iteration, vitals-band power) into training; the raw vector is
/// returned here and is not yet fed back into the loss.
#[must_use]
pub fn signal_features(&self) -> Array1<f32> {
crate::signal_features::extract_signal_features(&self.amplitude, &self.phase)
}
}
// ---------------------------------------------------------------------------
// CsiDataset trait
// ---------------------------------------------------------------------------
@@ -51,6 +51,7 @@ pub mod eval;
pub mod geometry;
pub mod rapid_adapt;
pub mod ruview_metrics;
pub mod signal_features;
pub mod subcarrier;
pub mod virtual_aug;
@@ -0,0 +1,155 @@
//! Hand-off layer between raw windowed CSI and the SOTA signal-processing
//! crate ([`wifi_densepose_signal`]).
//!
//! Historically `wifi-densepose-signal` was listed as a dependency of this
//! crate but never imported — the training pipeline only ever consumed the
//! raw amplitude/phase tensors. This module wires the two together: it takes
//! a windowed CSI observation and runs it through
//! [`wifi_densepose_signal::features::FeatureExtractor`] to derive a compact,
//! fixed-length feature vector (amplitude statistics, phase coherence, and a
//! power-spectral-density summary).
//!
//! These derived features are the building block for a future vitals /
//! multi-task supervision head (breathing-band and heart-rate-band power can
//! be read off the PSD summary); for now they are produced on demand via
//! [`extract_signal_features`] / [`crate::dataset::CsiSample::signal_features`]
//! and are not yet fed back into the loss. Wiring them as a training target
//! is tracked as a follow-up to the 2026-05-11 training-pipeline audit.
use ndarray::{s, Array1, Array4};
use wifi_densepose_signal::csi_processor::CsiData;
use wifi_densepose_signal::features::FeatureExtractor;
/// Length of the vector returned by [`extract_signal_features`].
///
/// The layout is:
/// 1. amplitude peak
/// 2. amplitude RMS
/// 3. amplitude dynamic range (max min)
/// 4. mean of the per-subcarrier amplitude means
/// 5. mean of the per-subcarrier amplitude variances
/// 6. phase coherence
/// 7. mean of the per-subcarrier phase variances
/// 8. PSD total power
/// 9. PSD peak power
/// 10. PSD peak frequency (Hz)
/// 11. PSD spectral centroid
/// 12. PSD spectral bandwidth
pub const FEATURE_LEN: usize = 12;
/// Default centre frequency assumed when the CSI window carries no metadata.
const DEFAULT_CENTRE_FREQ_HZ: f64 = 2.4e9;
/// Default channel bandwidth (HT40) assumed when the CSI window carries no
/// metadata.
const DEFAULT_BANDWIDTH_HZ: f64 = 40.0e6;
/// Derive a compact, fixed-length ([`FEATURE_LEN`]) signal-processing feature
/// vector from a windowed CSI observation by running its centre frame through
/// [`wifi_densepose_signal::features::FeatureExtractor`].
///
/// `amplitude` and `phase` are `[window_frames, n_tx, n_rx, n_subcarriers]`
/// tensors (the [`crate::dataset::CsiSample`] layout). The centre frame is
/// flattened to `[n_tx · n_rx, n_subcarriers]` (the antenna-major shape the
/// signal crate expects) and converted to `f64`.
///
/// The returned values are always finite for finite input: the underlying
/// extractors clamp degenerate cases, and any non-finite result is mapped to
/// `0.0` so callers can rely on the vector being usable as a model feature.
pub fn extract_signal_features(amplitude: &Array4<f32>, phase: &Array4<f32>) -> Array1<f32> {
let (n_t, n_tx, n_rx, n_sc) = amplitude.dim();
debug_assert_eq!(amplitude.dim(), phase.dim(), "amplitude/phase shape mismatch");
if n_t == 0 || n_tx == 0 || n_rx == 0 || n_sc == 0 {
return Array1::zeros(FEATURE_LEN);
}
let n_ant = n_tx * n_rx;
let t = n_t / 2;
let to_2d = |src: &Array4<f32>| -> Vec<f64> {
src.slice(s![t, .., .., ..]).iter().map(|&v| f64::from(v)).collect()
};
let amp2d = match ndarray::Array2::from_shape_vec((n_ant, n_sc), to_2d(amplitude)) {
Ok(a) => a,
Err(_) => return Array1::zeros(FEATURE_LEN),
};
let phase2d = match ndarray::Array2::from_shape_vec((n_ant, n_sc), to_2d(phase)) {
Ok(p) => p,
Err(_) => return Array1::zeros(FEATURE_LEN),
};
let csi = match CsiData::builder()
.amplitude(amp2d)
.phase(phase2d)
.frequency(DEFAULT_CENTRE_FREQ_HZ)
.bandwidth(DEFAULT_BANDWIDTH_HZ)
.build()
{
Ok(c) => c,
Err(_) => return Array1::zeros(FEATURE_LEN),
};
let feats = FeatureExtractor::default_config().extract(&csi);
let amp_mean_overall = mean_or_zero(feats.amplitude.mean.iter().copied());
let amp_var_overall = mean_or_zero(feats.amplitude.variance.iter().copied());
let phase_var_overall = mean_or_zero(feats.phase.variance.iter().copied());
let raw = [
feats.amplitude.peak,
feats.amplitude.rms,
feats.amplitude.dynamic_range,
amp_mean_overall,
amp_var_overall,
feats.phase.coherence,
phase_var_overall,
feats.psd.total_power,
feats.psd.peak_power,
feats.psd.peak_frequency,
feats.psd.centroid,
feats.psd.bandwidth,
];
debug_assert_eq!(raw.len(), FEATURE_LEN);
Array1::from_iter(raw.iter().map(|&v| sanitise(v)))
}
/// Mean of an iterator of `f64`, or `0.0` if it is empty or non-finite.
fn mean_or_zero<I: Iterator<Item = f64>>(it: I) -> f64 {
let (sum, n) = it.fold((0.0_f64, 0_usize), |(s, k), v| (s + v, k + 1));
if n == 0 {
0.0
} else {
sum / n as f64
}
}
/// Map non-finite values to `0.0` and downcast to `f32`.
fn sanitise(v: f64) -> f32 {
if v.is_finite() {
v as f32
} else {
0.0
}
}
#[cfg(test)]
mod tests {
use super::*;
use ndarray::Array4;
#[test]
fn zero_sized_input_yields_zero_vector() {
let empty = Array4::<f32>::zeros((0, 0, 0, 0));
let f = extract_signal_features(&empty, &empty);
assert_eq!(f.len(), FEATURE_LEN);
assert!(f.iter().all(|&v| v == 0.0));
}
#[test]
fn constant_input_is_finite_and_correct_length() {
let amp = Array4::<f32>::from_elem((4, 3, 3, 56), 1.5);
let phase = Array4::<f32>::from_elem((4, 3, 3, 56), 0.25);
let f = extract_signal_features(&amp, &phase);
assert_eq!(f.len(), FEATURE_LEN);
assert!(f.iter().all(|v| v.is_finite()), "features must be finite: {f:?}");
}
}
@@ -458,3 +458,52 @@ fn dataloader_empty_dataset_zero_batches() {
"iterator over empty dataset must yield 0 items"
);
}
// ---------------------------------------------------------------------------
// CsiSample::signal_features — the wifi-densepose-signal wiring
// ---------------------------------------------------------------------------
/// `signal_features()` must return a vector of exactly `FEATURE_LEN`, all
/// finite, for a real (synthetic) sample.
#[test]
fn signal_features_have_correct_length_and_are_finite() {
use wifi_densepose_train::signal_features::FEATURE_LEN;
let ds = SyntheticCsiDataset::new(8, default_cfg());
let sample = ds.get(0).expect("sample 0 must exist");
let feats = sample.signal_features();
assert_eq!(
feats.len(),
FEATURE_LEN,
"signal_features() must return FEATURE_LEN ({FEATURE_LEN}) values"
);
assert!(
feats.iter().all(|v| v.is_finite()),
"all signal features must be finite, got {feats:?}"
);
}
/// `signal_features()` is deterministic for a given (deterministic) sample.
#[test]
fn signal_features_are_deterministic() {
let ds = SyntheticCsiDataset::new(8, default_cfg());
let a = ds.get(0).expect("sample 0").signal_features();
let b = ds.get(0).expect("sample 0").signal_features();
assert_eq!(
a, b,
"signal_features() must be deterministic for the same sample"
);
}
/// `extract_signal_features` returns the zero vector for a zero-sized window
/// rather than panicking.
#[test]
fn signal_features_zero_window_is_zero_vector() {
use ndarray::Array4;
use wifi_densepose_train::signal_features::{extract_signal_features, FEATURE_LEN};
let empty = Array4::<f32>::zeros((0, 0, 0, 0));
let feats = extract_signal_features(&empty, &empty);
assert_eq!(feats.len(), FEATURE_LEN);
assert!(feats.iter().all(|&v| v == 0.0));
}
@@ -0,0 +1,86 @@
//! Integration test for the *real* on-disk dataset loader ([`MmFiDataset`]).
//!
//! The deterministic training proof (`verify-training`) runs on the in-memory
//! `SyntheticCsiDataset`, which never touches `.npy` files — by design (a
//! reproducible source is the whole point of the proof). This test covers the
//! path the proof bypasses: it writes synthetic CSI to `.npy` files in the
//! directory layout [`MmFiDataset::discover`] expects, loads it back, and
//! checks the resulting [`CsiSample`] — including the subcarrier-interpolation
//! branch.
use ndarray::{Array3, Array4};
use ndarray_npy::write_npy;
use tempfile::TempDir;
use wifi_densepose_train::dataset::{CsiDataset, MmFiDataset};
/// Write one deterministic `S01/A01` recording (no RNG) under `root`, with
/// `n_t` frames, `[n_tx, n_rx]` antennas and `n_sc` subcarriers.
fn write_recording(root: &std::path::Path, n_t: usize, n_tx: usize, n_rx: usize, n_sc: usize) {
let dir = root.join("S01").join("A01");
std::fs::create_dir_all(&dir).expect("create S01/A01");
let amplitude = Array4::<f32>::from_shape_fn((n_t, n_tx, n_rx, n_sc), |(t, tx, rx, sc)| {
0.5 + 0.4 * (((t * 7 + tx * 3 + rx * 2 + sc) % 17) as f32 / 17.0)
});
let phase = Array4::<f32>::from_shape_fn((n_t, n_tx, n_rx, n_sc), |(t, tx, rx, sc)| {
((t + tx + rx + sc) as f32 * 0.05).sin()
});
let mut kp = Array3::<f32>::zeros((n_t, 17, 3));
for t in 0..n_t {
for j in 0..17 {
kp[[t, j, 0]] = ((j as f32 + 1.0) / 18.0).clamp(0.0, 1.0); // x
kp[[t, j, 1]] = (((j * 3 + t) % 18) as f32 / 18.0).clamp(0.0, 1.0); // y
kp[[t, j, 2]] = 2.0; // COCO "visible"
}
}
write_npy(dir.join("wifi_csi.npy"), &amplitude).expect("write wifi_csi.npy");
write_npy(dir.join("wifi_csi_phase.npy"), &phase).expect("write wifi_csi_phase.npy");
write_npy(dir.join("gt_keypoints.npy"), &kp).expect("write gt_keypoints.npy");
}
/// Round-trip: write `.npy`, discover, load — no interpolation (native == target).
#[test]
fn mmfi_loads_real_npy_without_interpolation() {
let tmp = TempDir::new().expect("tempdir");
write_recording(tmp.path(), 8, 3, 3, 56);
let ds = MmFiDataset::discover(tmp.path(), 8, 56, 17).expect("discover the recording");
assert!(ds.len() >= 1, "must discover at least one sample, got {}", ds.len());
let sample = ds.get(0).expect("sample 0");
assert_eq!(sample.amplitude.shape(), &[8, 3, 3, 56], "amplitude shape");
assert_eq!(sample.phase.shape(), &[8, 3, 3, 56], "phase shape");
assert_eq!(sample.keypoints.shape(), &[17, 2], "keypoints shape");
assert_eq!(sample.keypoint_visibility.shape(), &[17], "visibility shape");
assert!(sample.amplitude.iter().all(|v| v.is_finite()), "amplitude must be finite");
assert!(sample.phase.iter().all(|v| v.is_finite()), "phase must be finite");
assert!(sample.keypoints.iter().all(|v| v.is_finite()), "keypoints must be finite");
}
/// The loader resamples the subcarrier axis when the requested target differs
/// from the dataset's native count.
#[test]
fn mmfi_resamples_subcarriers_on_load() {
let tmp = TempDir::new().expect("tempdir");
write_recording(tmp.path(), 8, 3, 3, 56);
// target (28) < native (56) — the loader must interpolate down.
let ds = MmFiDataset::discover(tmp.path(), 8, 28, 17).expect("discover");
let sample = ds.get(0).expect("sample 0");
assert_eq!(
sample.amplitude.shape(),
&[8, 3, 3, 28],
"amplitude must be resampled to the requested 28 subcarriers"
);
assert_eq!(sample.phase.shape(), &[8, 3, 3, 28], "phase must be resampled too");
assert!(sample.amplitude.iter().all(|v| v.is_finite()), "resampled amplitude must be finite");
}
/// An empty root directory yields an empty dataset (no panic, no spurious
/// samples) — the same loader code path, just with nothing to discover.
#[test]
fn mmfi_empty_root_is_empty() {
let tmp = TempDir::new().expect("tempdir");
let ds = MmFiDataset::discover(tmp.path(), 8, 56, 17).expect("discover empty root");
assert_eq!(ds.len(), 0, "empty root must produce an empty dataset");
}
Vendored Submodule
+1
Submodule vendor/rvcsi added at acd5689d9f