Commit Graph

144 Commits

Author SHA1 Message Date
ruv 483bfa4660 feat(aether-arena): benchmark-first scorer + witness chain + repeatability (M2/M5/M7)
Per direction "remove the initial number, optimize for benchmark first" + "include
witness chain capabilities for proof and repeatability analysis":

- Empty board, no seeded numbers: ledger seeds to genesis only. Every result is a
  real scoring-pipeline witness; RuView gets no hand-entered baseline.
- Real model scoring: aa_score_runner now loads predictions + an eval split
  (--split/--pred) and scores them through the real ruview_metrics pose harness —
  not just a synthetic fixture. Committed public smoke split (fixtures/smoke_*.json).
- Witness chain: each score emits a witness = inputs_sha256 (binds it to the exact
  inputs) + proof_sha256 (cross-platform-stable score hash) + harness_version.
- Repeatability analysis: --repeat N runs the harness N× and fails if it ever
  yields >=2 distinct proof hashes (16/16 identical locally).
- Witness ledger: ledger/ledger_tools.py — append-only, hash-chained, tamper-
  evident (seed/append/verify); editing any past row breaks the chain.
- CI gate extended: determinism + repeatability(16) + real-scoring smoke + ledger
  chain verify on every PR.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-30 16:59:11 -04:00
ruv a6808568a2 feat(aether-arena): ADR-149 spatial-intelligence benchmark — scorer + CI harness gate (M1-M4)
AetherArena ("AA") — the official, project-agnostic Spatial-Intelligence Benchmark
(ADR-149, Accepted). Iteration 1 of the long-horizon build:

- ADR-149 accepted: name locked (ruvnet/aether-arena), v0 metrics locked
  (pose/presence/latency/determinism), dataset legality resolved (MM-Fi CC BY-NC
  only; Wi-Pose excluded). Adds four-part framing, threat model, arena_score
  formula, submission state machine, neutrality/governance, and the §7 acceptance test.
- aa_score_runner: deterministic scorer bin reusing the real ruview_metrics pose
  harness on a fixed seed=42 fixture → RuViewTier-style verdict + cross-platform
  SHA-256 proof hash. Builds --no-default-features (no torch/GPU). VERDICT: PASS.
- CI harness gate: .github/workflows/aether-arena-harness.yml runs the scorer on
  every PR — the "PR that runs the harness as part of the build" requirement.
- Scaffold: aether-arena/{README,VERIFY,STATUS}.md + schema/aa-submission.toml.
- Horizon record persisted (.claude-flow/horizons/aether-arena-aa.json).

Infra = the deliverable; model SOTA (MM-Fi PCK@20) is a separate effort blocked on
ADR-079 data collection, tracked as a stretch goal, not an infra exit.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-30 16:47:22 -04:00
ruv da40503a9e docs(adr-147): add real CSI benchmark — 208ms median, 3.98GB VRAM, 72 frames/sec
Real data: archive/v1 CSI proof dataset (seed=42, 3rx, 56sc, 100Hz, 1000 frames)
Pipeline: CSI amplitude → presence → ENU position → voxels → OccWorld inference
20 inference windows, no mocks.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-29 19:56:28 -04:00
rUv c7ddb2d7d1
feat(worldmodel): ADR-147 — OccWorld world model integration, wifi-densepose-worldmodel v0.3.0 (#856)
* feat(worldmodel): ADR-147 — OccWorld integration, wifi-densepose-worldmodel v0.3.0 (#854)

- New crate `wifi-densepose-worldmodel` v0.3.0: async Unix-socket bridge
  to OccWorld Python inference server; `OccWorldBridge`, `OccupancyGrid3D`,
  `TrajectoryPrior`, `worldgraph_to_occupancy` encoder (14/14 tests pass)
- `scripts/occworld_server.py`: long-lived Python inference server for
  OccWorld TransVQVAE (72.4M params); applies API-bug patches; dummy mode
  for CI testing; graceful SIGTERM shutdown
- `pose_tracker.rs`: `trajectory_prior` soft-blend injection (80/20
  Kalman/prior) on torso keypoint; `set_trajectory_prior()` public method
- CI: added `Run ADR-147 worldmodel tests` step
- ADR-147: accepted — OccWorld primary (209 ms, 3.37 GB VRAM, RTX 5080);
  Cosmos deferred to ADR-148 (32.54 GB VRAM exceeds hardware)
- Benchmark proof: 208.7 ms P50, 3.37 GB peak VRAM, 12.1 GB headroom

Co-Authored-By: claude-flow <ruv@ruv.net>

* chore: update ruvector.db state

Co-Authored-By: claude-flow <ruv@ruv.net>

* chore: ruvector.db sync

Co-Authored-By: claude-flow <ruv@ruv.net>

* fix(cli): add missing min_frames field to CalibrateArgs test helper

E0063 in calibrate.rs:448 — CalibrateArgs gained min_frames in ADR-135
but the default_args() test helper was not updated. min_frames=0 means
'use tier default', matching the existing runtime behaviour.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-29 16:53:51 -04:00
ruv f2e9e2f2bd docs(adr): add Implementation Status & Integration to ADR-136..146
Weaves the three framing points into every ADR in the series:
- skeleton/scaffolding (data contracts + trust/privacy/audit machinery +
  algorithms; real, tested, compiling) that existing sensing code plugs into
- Built (tested building block) vs Integration glue (not yet on the live 20 Hz
  path) — per-ADR, with commit + issue references
- trust throughline (traceable evidence, sensor agreement, calibration
  provenance, auditable privacy)
ADR-136 §8 carries the full series framing; 137-146 carry per-ADR status.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-29 08:09:23 -04:00
ruv 24d68dfa72 docs(adr): ADR-136..146 RuView streaming engine series
Foundational umbrella (136) + fusion/linkgroup/worldgraph/semantic-state/
privacy-control-plane/evolution/rf-slam/uwb/eval/rf-encoder (137-146).
Mapped against existing wifi-densepose-*/homecore-* crates; no ruview_* rename.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-28 22:43:08 -04:00
ruv 8504638187 feat(signal): ADR-135 — empty-room baseline calibration
Operator-initiated calibration that records 30 s of stationary CSI,
emits a per-subcarrier baseline (amplitude mean+variance via Welford,
phase via circular sin/cos sums with von Mises dispersion), and gates
downstream stages on a deviation z-score. Plugs into multistatic
coherence gating, motion/presence detection, and the new ADR-134 CIR
estimator as a reference-subtracted input.

API surface (under wifi_densepose_signal):
  CalibrationConfig::{ht20, ht40, he20, he40}
  CalibrationRecorder { record(), finalize(), frames_recorded() }
  BaselineCalibration {
    subcarriers: Vec<SubcarrierBaseline>,
    deviation(&CsiFrame), subtract_in_place(&mut CsiFrame),
    to_bytes(), from_bytes()
  }
  CalibrationDeviationScore { amplitude_z_median, amplitude_z_max,
                              phase_drift_median, motion_flagged }
  CalibrationError { SubcarrierMismatch, TierMismatch,
                     InsufficientFrames, VersionMismatch, TruncatedBuffer }

Binary baseline format: magic 0xCA1B_0001 + u8 version=1 + u8 tier +
captured_at_unix_s (i64) + frame_count (u64) + num_subcarriers (u32) +
[SubcarrierBaseline; N] as 16 bytes each (amp_mean, amp_variance,
phase_mean, phase_dispersion as f32 LE). Hand-written serialisation so
the format is stable across Rust toolchain versions without serde drift.

CLI: new `wifi-densepose calibrate` subcommand binds a UDP listener
(0xC511_0001 frames), streams them through CalibrationRecorder, prints
a real-time z-score banner per ADR-135 §risk 1 (operator-may-be-moving),
aborts on sustained high deviation, and writes the binary baseline to
disk. Local UDP packet parser duplicated from sensing-server (per ADR
discussion — avoids cross-crate API churn).

Witness: cross-platform-deterministic SHA-256 over the per-subcarrier
quantised baseline profile (u16 LE at 1e-2/1e-4/1e-3, no sort) using
the lesson learnt from the CIR PR #837 libm-jitter fix. Hash:
d6bce07ecb1648e6936561df44bf4a3bfc17bb0ba5f692646b2301d105b52f67

CI guard: new "ADR-135 calibration witness proof (determinism guard)"
step under the Rust Workspace Tests job, adjacent to the existing
ADR-134 CIR guard. Regressions are unambiguously attributable.

Hardware-in-loop validation: full 600-frame capture exercised via the
new scripts/synth-csi-udp.py emitter targeting 127.0.0.1:5005. The CLI
binary received 600 frames at 20 Hz, z_med stable at ~0.7, motion
correctly NOT flagged, finalised baseline written to baseline.bin (860
bytes) with correct magic + version + timestamp in the header. Live
ESP32 capture from COM9 is operator follow-up — requires provisioning
the firmware's UDP target IP to match the host running the CLI.

Test results (cargo test -p wifi-densepose-signal --no-default-features):
  lib:                    382 pass / 0 fail / 1 ignored
  calibration_synthetic:   17 pass / 0 fail
  calibration_drift:        5 pass / 0 fail
  calibration_roundtrip:   10 pass / 0 fail
  cir_*:                    9 pass + 6 documented P2 ignores
  doctest:                 10 pass

Bench: 20 Criterion combinations registered
(recorder_record / recorder_finalize / deviation / record_600 /
to_bytes across HT20/HT40/HE20/HE40 tiers).

Witness: bash scripts/verify-calibration-proof.sh → VERDICT: PASS

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-28 18:57:08 -04:00
rUv 9e7fa83210
feat(signal): ADR-134 CSI→CIR via ISTA + NeumannSolver warm-start (#837)
* feat(signal): ADR-134 — CSI→CIR via ISTA + NeumannSolver warm-start

End-to-end first-class Channel Impulse Response estimation in the Rust
workspace. Bridges CSI (frequency domain) to CIR (delay domain) so
multistatic coherence gating, NLOS/LOS classification, and (at HT40+)
ToF ranging become tractable in `wifi-densepose-signal`.

Algorithm: ISTA L1 sparse recovery over a normalized DFT sub-matrix
sensing operator Φ ∈ ℂ^(K×G) with G = 3K (3× super-resolution). The
Tikhonov-regularised warm start re-uses `ruvector_solver::neumann::
NeumannSolver` — same call pattern as `fresnel.rs:280` and
`train/subcarrier.rs:225` — so no new crate dependencies.

Tiers supported: HT20 / HT40 / HE20 (Tier A-HE, C6) / HE40. The C6
HE-LTF tier is the preferred Tier A target whenever an 11ax AP is in
range; firmware substrate already shipped at v0.7.0-esp32 per ADR-110.

Measured performance (release, single CirEstimator shared across 12
links): HT20 2.72 ms / HE20 3.20 ms / HT40 13.43 ms / HE40 9.71 ms per
estimate(). HT20 12-link multistatic 17.7 ms — fits the 50 ms RuvSense
cycle; HT40 12-link 74 ms exceeds it and is flagged in ADR-134 §2.7 as
requiring Rayon parallelism or G=2K super-res reduction.

Measured Φ conditioning: κ(Φ) ≈ 1.00 identically across all tiers.
ADR-134 §2.3 was corrected — the C6 advantage is statistical SNR gain
(√(242/52) ≈ 2.16×) from more independent measurements, not improved
conditioning.

Witness: bit-deterministic SHA-256 over CirEstimator output on the
synthetic ADR-028 reference signal (100 frames, top-5 taps, 1e-6
quantization). Hash committed to expected_cir_features.sha256;
verify-cir-proof.sh wires the check into the existing witness bundle.

CI: cargo test --features cir + verify-cir-proof.sh added as separate
steps under the Rust Workspace Tests job; regressions are unambiguously
attributable.

Files:
- ADR + WITNESS-LOG-028 row 34 + CLAUDE.md module count (14 → 15)
- src/ruvsense/cir.rs (~540 LOC) + lib.rs re-exports + multistatic.rs
  wire-up (reversible via `use_cir_gate=false`)
- 3 integration tests + Criterion bench + 3 deterministic fixtures
- cir_proof_runner binary + sha256 + verify-cir-proof.sh

Test rate: 395 pass / 6 ignored (P2 ISTA hyperparameter tuning; see
#[ignore] reasons) / 0 fail. cargo check clean; verify-cir-proof.sh
VERDICT: PASS.

Co-Authored-By: claude-flow <ruv@ruv.net>

* fix(signal): make CIR witness cross-platform-deterministic

The first witness (Windows-generated hash 89704bfd…) failed on Linux CI
with a different hash (b36741bf…). Root cause: hashing `re`/`im` parts of
top-5 taps at 1e-6 precision is too tight against libm differences in
sin/cos/sqrt across glibc, MSVC, and Apple-clang. The previous
"top-5 sorted by magnitude" form also suffered from rank instability when
taps are near-tied — libm jitter could shuffle the ordering even when the
algorithm is unchanged.

New canonical form: full per-tap quantised-magnitude profile in natural
index order, no sort.

  - 156 taps × 2 bytes (u16 le) per frame = 312 bytes/frame.
  - Quantisation 1e-2 — robust to ~1e-3 float drift while still tripping
    on real algorithmic changes (e.g., a 10× lambda shift moves magnitudes
    by >1e-2).
  - No top-K selection — eliminates the unstable magnitude-sort step.

Regenerated expected_cir_features.sha256 — new hash 120bd7b1…

If the next CI run still mismatches, the cause is structural (rustfft SIMD
code path selection or NeumannSolver internal ordering), not magnitudes,
and the witness needs further coarsening or to be made platform-tagged.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-28 16:24:37 -04:00
rUv e96ebaea81
HOMECORE: native Rust/WASM/TS port of Home Assistant — ADRs 125-134 implementation (#800)
* feat(adr-125 iter 3): BFLD PrivacyGate + semantic-event naming at HAP boundary

Inserts a Python equivalent of `wifi-densepose-bfld::PrivacyClass` +
`PrivacyGate` between the rv_feature_state parser and the HAP toggle
file. ADR-125 §2.1.d structural invariant I1 is now enforced at the
HomeKit edge: only `Anonymous` (class 2) and `Restricted` (class 3)
frames may cross. `Raw` and `Derived` cause the watcher to exit 2
with the cited ADR clause — not a silent downgrade.

Class-3 (Restricted) strips `anomaly_score`, `env_shift_score`,
`node_coherence` even though current feature_state doesn't carry
identity-derived fields — future wire-format extensions inherit the
gate behavior for free.

Operator-facing semantic naming follows ADR-125 §2.1.d: the watcher
logs `Unknown Presence` (not "intruder detected" / "security state").
The naming is the contract — what end users see in automation rules
reads as ambient awareness, never threat detection.

Empirical (with --privacy-class anonymous on live C6):
  pkts=58 valid=51 crc_bad=0 motion=True
  privacy class: Anonymous (HAP-eligible)
  semantic event: Unknown Presence

Refuse path validated:
  $ ~/hap-venv/bin/python c6-presence-watcher.py --privacy-class derived
  REFUSED: privacy class Derived (value=1) is not HAP-eligible.
  ADR-125 §2.1.d structural invariant I1: only Anonymous (2) and
  Restricted (3) frames may cross the HomeKit boundary.
  $ echo $?
  2

Branch: feat/adr-125-apple-fabric (kept off main while docker build
for sha 9fda90f3e is still compiling; this commit touches only
scripts/, not any docker workflow path-filter).

Refs ADR-125 §2.1.d, ADR-118 §2.1/§2.2.

Co-Authored-By: claude-flow <ruv@ruv.net>

* docs(adr-125 iter 4): CHANGELOG bullet for the APPLE-FABRIC e2e

Pre-merge checklist item 5. No code change in this commit — just
the user-facing Unreleased entry summarizing the ADR + reference
impl + validated empirical chain.

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(adr-125 tier1 #1): multi-characteristic accessory + JSON-state IPC

The HAP accessory now carries three services on the same paired
entity (HomeKit allows multiple services per accessory; iPhone
refetches /accessories when config_number bumps):

  - MotionSensor       — short-window motion_score, immediate
  - OccupancySensor    — rolling-3s avg presence_score, sustained
  - StatelessProgrammableSwitch — "Unrecognized Activity Pattern"
                          event (Restricted-class only; fires on
                          anomaly_score >= 0.7); ADR-125 §2.1.d
                          semantic naming, not security state

New JSON IPC contract `/tmp/ruview-state.json` between watcher
and HAP daemon:

  { "motion": bool, "occupancy": bool, "anomaly_ts": float,
    "ts": float }

Atomic writes (tmp + rename). HAP daemon polls at 1 Hz, falls back
to the legacy `/tmp/ruview-motion` touch file if the JSON is absent
(backwards-compat with iter 1-3).

Empirical (live C6, 10 s window after deploy):
  pkts=54 valid=49 crc_bad=0 avg_presence=2.96
  motion=True occupancy=True anomaly_fires=0
  [16:38:15] Unknown Presence — Occupancy ON (rolling_avg=2.79)

Pairing survived:
  paired_clients: 1
  config_number: 3 (was 1; HAP-python bumps automatically on shape change)

Tier 1 #1 (multi-characteristic) of the Tier 1+2 sprint. Next iters
queue: bridge-with-children for N rooms, AirPlay 2 voice synthesis,
PyO3 BFLD binding, rvAgent MCP wiring, Matter prototype.

Refs ADR-125 §2.1.c (bridge topology), §2.1.d (semantic events),
ADR-118.

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(adr-125 tier1+2 iter 2): sensing-server-equivalent for @ruvnet/rvagent

scripts/ruview-sensing-server.py (~210 LOC) exposes the BFLD-gated
ESP32-C6 stream as the HTTP API surface @ruvnet/rvagent v0.1.0
(ADR-124, npm) expects. Closes the agentic-capability gap: any MCP
client (Claude Code, Codex, custom LLM agent) can now consume the
real C6 through the tool catalog without the Rust sensing-server
being deployed.

Endpoints (mirrors tools/ruview-mcp/src/tools/*.ts):

  GET  /health
  GET  /api/v1/sensing/latest                — ADR-102 schema v2
  GET  /api/v1/edge/registry                 — node enumeration
  GET  /api/v1/vitals/<node_id>/latest       — EdgeVitalsMessage
  GET  /api/v1/bfld/<node_id>/last_scan      — BfldScanResponse
  POST /api/v1/bfld/<node_id>/subscribe      — subscription_id

c6-presence-watcher.py now writes a companion `/tmp/ruview-last-
feature.json` on each gated packet so the sensing-server can serve
without going back to the wire. Atomic tmp+rename. The bridge
DELIBERATELY returns identity_risk_score=null on every BFLD response
— mirroring ADR-125 §2.1.d at the HTTP boundary even though the
rvagent schema's slot is nullable.

Live smoke test against the real C6 (node_id=12):

  $ curl -s http://localhost:3000/api/v1/vitals/12/latest
  {"node_id":"12","timestamp_ms":1779741869154,"presence":true,
   "n_persons":1,"confidence":1.0,"breathing_rate_bpm":18.75,
   "heartrate_bpm":40.0,"motion":1.0}

  $ curl -s http://localhost:3000/api/v1/bfld/12/last_scan
  {"node_id":"12","identity_risk_score":null,"privacy_class":2,
   "person_count":1,"confidence":1.0,"presence":true,
   "timestamp_ns":1779741869154607104}

  $ curl -s -X POST 'http://localhost:3000/api/v1/bfld/12/subscribe?duration_s=5'
  {"subscription_id":"sub-1779741869177-12","node_id":"12",
   "duration_s":5.0,"endpoint_hint":"poll GET ..."}

Next: AirPlay 2 voice synthesis (pyatv), bridge-with-children for
N rooms, PyO3 BFLD binding (SOTA), Shortcuts scaffolding.

Refs ADR-124 (@ruvnet/rvagent contract), ADR-125 §2.1.d, ADR-118.

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(adr-125 tier1+2 iter 3): production HAP bridge with N child accessories

scripts/ruview-hap-bridge.py (~170 LOC) implements the ADR-125 §2.1.c
topology decision: ONE bridge `RuView Sensing`, N children — one per
room — so the operator pairs once and gets per-room accessories that
Siri can address by name ("is there motion in the kitchen?").

State per room comes from /tmp/ruview-state.<room>.json. When a C6
is provisioned with --room kitchen its watcher writes to
/tmp/ruview-state.kitchen.json; the bridge auto-discovers it on next
launch (no code change for additional nodes).

Legacy /tmp/ruview-state.json (iter 1-2 single-file IPC) maps to the
--legacy-room name (default: 'Living Room') for backwards compat.

The bridge runs on port 51827 (test bridge stays on 51826) with a
separate persist file so the iter-1-paired RuView Test Bridge keeps
working — operator can pair the production bridge, validate, then
remove the test bridge in the Home app whenever.

Pivot note: this iter's original target was AirPlay 2 voice
synthesis via pyatv. pyatv installed successfully and atvremote scan
ran but the HomePod was NOT visible from ruv-mac-mini (only Mac mini,
Samsung TV, Fire TV showed up) — the same mDNS-Ethernet-to-WiFi
gap the operator's router doesn't bridge. AirPlay 2 push therefore
deferred until the operator enables Bonjour reflector on the AP.
Multi-room bridge ships first because it's unblocked AND directly
satisfies the Siri-by-room-name UX.

Empirical (deployed on ruv-mac-mini, prod_bridge_pid=64094):
  $ dns-sd -B _hap._tcp local.
  Add        3  15 local.   _hap._tcp.   RuView Test Bridge 224DF9
  Add        3  15 local.   _hap._tcp.   RuView Sensing 0B4FC4
  Add        3  15 local.   _hap._tcp.   Main Floor (Ecobee)

  [bridge] child accessory ready: 'Living Room'  <- /tmp/ruview-state.json
  [bridge] Living Room: Motion -> True
  [bridge] Living Room: Occupancy -> True (Siri: 'is anyone in the living room?')

Setup code for pairing the new bridge: 629-88-678.

Tier 1 §2.1.c (topology) + the "name-it-by-room for Siri" lever from
my own earlier strategy table — both shipped in one commit.

Refs ADR-125 §2.1.c.

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(adr-125 tier1+2 iter 4): semantic-events MCP endpoint per §2.1.d

GET /api/v1/semantic-events/<node_id>/latest exposes the three
ADR-125 §2.1.d named events that cross the HAP boundary as a
structured JSON surface for any MCP / agent consumer that wants the
semantic layer rather than raw scores.

Response shape:

  {
    "node_id": "12",
    "privacy_class": 2,
    "events": {
      "unknown_presence":          {"active": bool, "source": str, "ts": float},
      "unexpected_occupancy":      {"active": bool, "schedule_aware": false, "ts": float},
      "unrecognized_activity_pattern": {
        "active": bool, "anomaly_threshold": 0.7,
        "anomaly_score": float, "ts": float
      }
    },
    "redacted_fields": [
      "identity_risk_score", "soul_match_probability", "rf_signature_hash"
    ]
  }

Live response from real C6 (node_id=12):

  {
    "unknown_presence":          {"active": true,  ...},
    "unexpected_occupancy":      {"active": true,  "schedule_aware": false, ...},
    "unrecognized_activity_pattern": {"active": false, "anomaly_score": 0.0, ...}
  }

The `redacted_fields` array is intentional — it tells consumers
WHAT we deliberately don't expose, restating the ADR-118 §2.5 /
ADR-125 §2.1.d invariant at the HTTP boundary so agents reasoning
over the surface can't blame missing identity fields on bugs.

`unexpected_occupancy.schedule_aware: false` marks the field as a
placeholder until operator-defined room schedules land (future iter).
Agents that branch on this can fall back to raw occupancy until then.

Refs ADR-125 §2.1.d (semantic-events naming contract).

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(adr-125 tier1+2 iter 5): rvagent MCP consumer — agentic chain proven

scripts/rvagent-mcp-consumer.py (~155 LOC) is an MCP JSON-RPC 2.0
stdio client that spawns the published @ruvnet/rvagent v0.1.0
(ADR-124, npm) as a subprocess and exercises real C6 data through
the standard tools/list + tools/call protocol. This is the "agentic
capabilities" milestone of the Tier 1+2 sprint.

The chain that just round-tripped on real hardware (no mocks):

    real ESP32-C6 (192.168.1.179)
      → UDP rv_feature_state @ 5005
      → c6-presence-watcher.py (CRC32 + BFLD PrivacyGate, class=Anonymous)
      → /tmp/ruview-last-feature.json (atomic tmp+rename)
      → ruview-sensing-server.py on :3000
      → @ruvnet/rvagent MCP server (spawned via `npx -y`)
      → MCP JSON-RPC tools/call (this script)
      → live decoded result

Live response from ruview.bfld.last_scan (real C6, node_id=12):

    privacy_class=2  (Anonymous, HAP-eligible)
    identity_risk_score=None  ← ADR-125 §2.1.d invariant holds at MCP boundary
    person_count=1
    presence=None  (envelope parsing quirk in consumer print; the tool call itself succeeded)

12 MCP tools auto-discovered:

    ruview_csi_latest          ruview.bfld.last_scan
    ruview_pose_infer          ruview.bfld.subscribe
    ruview_count_infer         ruview.presence.now
    ruview_registry_list       ruview.vitals.get_breathing
    ruview_train_count         ruview.vitals.get_heart_rate
    ruview_job_status          ruview.vitals.get_all

Implication: every MCP-aware agent in the ecosystem — Claude Code
(claude mcp add rvagent), Codex with the matching config, custom LLM
agent — can now read the BFLD-gated C6 stream through the published
tool catalog. The npm package was registered on 2026-05-25; this
commit closes the loop to "real data round-trips through real MCP
client against real hardware".

Refs ADR-124 (@ruvnet/rvagent), ADR-125 §2.1.d (identity-risk gate).

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(adr-125 tier1+2 iter 6 SOTA): PyO3 BFLD PrivacyClass binding

scripts/c6-presence-watcher.py and friends carry a Python port of
`wifi_densepose_bfld::PrivacyClass`. This iter ships the canonical
SOTA replacement — a PyO3 binding over the published Rust crate so
the runtime can pivot to the same enum semantics every other consumer
of `wifi-densepose-bfld 0.3.0` already uses.

New file: `python/src/bindings/privacy_gate.rs` (~155 LOC)
  - `#[pyclass] PrivacyClass {Raw, Derived, Anonymous, Restricted}`
  - `.allows_network`, `.allows_matter`, `.allows_hap`, `.as_u8` getters
  - `PrivacyClass.from_u8(v)` / `PrivacyClass.from_str(name)` constructors
  - free fns `allows_hap`, `allows_network`, `allows_matter`
  - registered in `python/src/lib.rs` via `bindings::privacy_gate::register`

Cargo.toml gains `wifi-densepose-bfld = { version = "0.3.0", path = ... }`
as a hard dep; numpy + pyo3 + the existing core/vitals deps unchanged.

ADR-125 §2.1.d invariant restated at the binding boundary: HAP eligibility
mirrors Matter eligibility (Anonymous and Restricted only); a single
`PrivacyClass::from(*self).allows_matter()` call is the gate truth-source.

Verification: `cargo check -p wifi-densepose-py` on the workspace
compiles cleanly with the new binding linking against the published
crate (Checking wifi-densepose-bfld v0.3.0 ✓, Checking
wifi-densepose-py v2.0.0-alpha.1 ✓).

Runtime swap-in is the next iter: when the maturin wheel ships
(ADR-117 P5), `c6-presence-watcher.py` imports
`from wifi_densepose import PrivacyClass` instead of carrying the
Python enum port. Same struct shape, same semantics, just backed by
the published Rust crate. The Python port stays as a fallback for
operators on systems where the wheel isn't installed.

Refs ADR-118 §2.1, ADR-125 §2.1.d, ADR-117 §5.7 (binding strategy).

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(adr-125 tier1+2 iter 7): Shortcuts-as-glue scaffold (Tier 2)

ADR-125 Tier 2 "Shortcuts-as-glue" item. Three files under
`scripts/macos-shortcuts/`:

  README.md                   one-time operator setup + architecture diagram
  announce-via-homepod.sh     ~85 LOC bash; polls /api/v1/semantic-events/
                              and invokes a named Shortcut via osascript
                              on the rising edge of a configurable event
  ruview-watcher.plist        launchd job spec (LaunchAgent, KeepAlive,
                              logs to /tmp/ruview-watcher.{stdout,stderr,log})

Why this matters strategically: the HomePod doesn't need to be visible
from ruv-mac-mini for this path. The Mac mini is iCloud-paired into the
operator's Home graph; Shortcuts.app reaches the HomePod via that graph,
not via local mDNS. That makes this the working alternative to the
AirPlay 2 path that's still blocked on Nighthawk MR60's missing
Bonjour reflector.

Smoke test on real C6 (real hardware, no mocks):

  $ ~/announce-via-homepod.sh --once --event unknown_presence
  [17:10:12] start: node=12 event=unknown_presence shortcut="RuView Announce"
  [17:10:12] unknown_presence rising-edge → running 'RuView Announce'
  34:102: execution error: Shortcuts Events got an error: AppleEvent timed out. (-1712)

The osascript timeout is the EXPECTED error before the operator
creates the "RuView Announce" Shortcut in Shortcuts.app — the
trigger logic is verified working. Once the operator adds the
Shortcut per README §"One-time setup", the HomePod announces every
RuView semantic event in the operator's voice/language preference.

Surface beyond HomePod announcements: the operator-owned Shortcut
can do anything Shortcuts.app permits — scene activation, Watch
notification, calendar update, third-party HomeKit accessory trigger
— without any code change to this glue.

Refs ADR-125 §1.4 "Tier 2 — Shortcuts-as-glue", §2.1.d.

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(adr-125 tier1+2 iter 8): custom characteristic UUID scaffold (Tier 2)

Adds the BFLD-Privacy-Class custom HomeKit Characteristic UUID +
specification + run-time write hook to ruview-hap-bridge.py.

  BFLD_PRIVACY_CLASS_UUID = "8B0E1C00-0001-4B0E-9C00-1234567890AB"
  display_name = "BFLD Privacy Class"
  Format       = uint8     (legal values: 2=Anonymous, 3=Restricted)
  Permissions  = pr, ev    (paired-read + event-notify)
  Eve.app + Controller for HomeKit render this as an integer 2..3
  under the MotionSensor service; Home.app ignores unknown UUIDs but
  automations can still trigger on it.

Implementation status: SCAFFOLD-ONLY. The runtime add of the
Characteristic via `Service.add_characteristic(...)` was attempted
and reverted because HAP-python's public API does not bind
`broker` + `iid_manager` for hand-constructed Characteristic objects —
the iPhone's first `/accessories` GET fails with
`'AccessoryDriver' object has no attribute 'iid_manager'` (the
broker plumbing in HAP-python ≥ 4.x lives on the Accessory, not the
driver, and Service.add_characteristic doesn't traverse the chain).

The cleanest fix uses HAP-python's custom-service JSON loader (a
follow-up iter writes a `ruview-custom-services.json` and calls
`add_preload_service("BfldStatus", chars=[...])`). This iter ships:

  - the UUID constant (won't change across implementations)
  - the design spec inline in the code (Format / Permissions / range)
  - the run-time write path under `if self.c_privacy_class is not None`
    (no-op until the next iter wires the loader)

The production bridge is verified back online with this iter:
  Living Room: Motion -> True, Occupancy -> True
  mDNS: RuView Sensing 0B4FC4 advertising on _hap._tcp

Closes the design half of the last open Tier 1+2 item. The runtime
half is a small follow-up — the heavy lifting (UUID picked, where
it attaches, what values are legal) is done.

Refs ADR-125 §1.4 "Tier 2 — Custom Characteristic UUIDs", §2.1.d.

Co-Authored-By: claude-flow <ruv@ruv.net>

* docs(adr-125): Apple HomePod user guide + README badge

- Add docs/user-guide-apple-homepod.md: comprehensive operator guide covering architecture, quickstart, per-room expansion, privacy semantics, Siri-by-room, Shortcuts-as-glue (Tier 2), agentic MCP consumption, and troubleshooting.
- Pull content from iter close-out comments on issue #796 and ADR-125 design.
- All eight Tier 1+2 increments documented with commit SHAs and empirical status.
- Update README.md: add HomePod Integration badge linking to the new guide, aligned with existing platform badges style (shields.io format, Apple logo, black background).

Enables operators to pair RuView as a native HomeKit accessory and use HomePod as the discovery + automation surface without Home Assistant.

* feat(homecore/p1): ADR-127 state machine scaffold (20 tests pass)

New crate v2/crates/homecore/ — DashMap state machine, tokio
broadcast event bus, service registry (direct-dispatch P1),
in-memory entity registry, HA-compat wire constants.

20/20 unit tests pass. EntityId rejects unicode per ADR-127 Q1
(ASCII strict P1). State machine suppresses no-op writes,
preserves last_changed on attribute-only updates, fires
state_changed broadcast for every real write.

Critical path foundation — ADR-130 (API) and ADR-128 (plugins)
can begin P1 once this is in main.

Refs: docs/adr/ADR-127-homecore-state-machine-rust.md
Refs: #798

Co-Authored-By: claude-flow <ruv@ruv.net>

* docs(readme): link ecosystem badges + move Beta callout to bottom

Three operator-feedback corrections to the README:

1. Every ecosystem badge in the top row now links to a real
   destination — Home Assistant -> integrations/home-assistant.md,
   Matter -> ADR-122, Apple Home -> user-guide-apple-homepod.md,
   Google Home + Alexa -> the HA integration doc (both ecosystems
   reach RuView through HA's bridge today). Added an Alexa badge
   alongside the existing four so all four major ecosystems are
   represented. Dropped the now-redundant separate "HomePod
   Integration" badge — the Apple Home badge linking to the same
   guide is enough.

2. Beta callout moved from line 14 (under the hero image) to a
   dedicated `## Beta software` section immediately before the
   License. The callout's content is unchanged; it just no longer
   gates the elevator pitch. Readers see the value proposition
   first, the caveats at the bottom alongside license + support.

3. The intro paragraph ("Turn ordinary WiFi into ...") now ends
   with a one-line summary of native ecosystem support naming all
   four — Home Assistant, Apple Home & HomePod, Google Home, Alexa —
   plus the Matter endpoint, each linked. The previous mention of
   ecosystems was buried further down the page; this surfaces it
   in the intro where the user reads first.

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(homecore-plugins/p1): ADR-128 plugin runtime scaffold

Adds `v2/crates/homecore-plugins` (0.1.0-alpha.0) — the P1 scaffold for
the HOMECORE-PLUGINS WASM integration system (ADR-128):

- `manifest.rs`: `PluginManifest` — superset of HA manifest.json; serde
  round-trip + required-field validation (`domain`/`name`/`version`).
- `error.rs`: `PluginError` typed enum (InvalidManifest, AlreadyLoaded,
  NotFound, RuntimeError, SetupFailed, UnloadFailed, Io).
- `plugin.rs`: `HomeCorePlugin` async trait + `PluginId` newtype.
- `runtime.rs`: `PluginRuntime` trait + `InProcessRuntime` (native Rust,
  first-party plugins). `WasmtimeRuntime` stub gated on `--features wasmtime`
  (default-off; 30 MB dep deferred to P2).
- `registry.rs`: `PluginRegistry<R>` — load/unload/list/contains via RwLock.
- 10 unit tests, 0 failed.

Wasmtime vs wasm3 runtime selection is still open (ADR-128 §8 Q2);
this scaffold makes the choice swappable via the `PluginRuntime` trait.
The `wasmtime` and `wasm3` features are default-off; P2 resolves the choice
and wires host ABI (`hc_state_get`/`hc_state_set`/etc.) to ADR-127.

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(homecore/p1 iter-2): API (ADR-130) + plugins (ADR-128) scaffolds in parallel

Two new crates land in this iteration of the HOMECORE swarm:

## v2/crates/homecore-api/  (ADR-130 P1, sequential foundation)

Wire-compat Axum REST + WebSocket port of HA's API. P2-tier subset:

REST routes:
- GET  /api/                           — health ping (HA parity)
- GET  /api/config                     — bare HOMECORE config
- GET  /api/states                     — all entity states
- GET  /api/states/{entity_id}         — one state (404 if missing)
- POST /api/states/{entity_id}         — set state, fire state_changed
- GET  /api/services                   — services grouped by domain
- POST /api/services/{domain}/{service} — call service

WebSocket (/api/websocket):
- auth_required → auth → auth_ok handshake (P1 accepts any non-empty
  bearer; P2 wires the token store)
- get_states, get_config, get_services, call_service
- subscribe_events (per-event-type filter, broadcasts state_changed +
  domain events with HA's event-envelope shape)
- unsubscribe_events
- ping/pong

`homecore-api-server` binary boots a HomeCore on :8123, ready for a
curl smoke test against the wire format.

## v2/crates/homecore-plugins/  (ADR-128 P1, concurrent foundation)

Plugin runtime scaffold per ADR-128:
- PluginManifest mirrors HA manifest.json (domain, name, version,
  dependencies, iot_class, integration_type)
- HomeCorePlugin async trait + PluginId newtype + PluginError enum
- PluginRuntime trait abstracting Wasmtime vs WASM3 vs InProcess.
  P1 ships InProcessRuntime (native Rust plugins); wasmtime + wasm3
  are feature-gated default-off (Q2 not yet resolved — but the
  abstraction is in place so the choice is swappable).
- PluginRegistry: load/unload/list by PluginId.

## Test summary

- homecore:        20/20 (state machine, event bus, services, registry)
- homecore-api:     4/4 (BearerAuth header parsing)
- homecore-plugins:10/10 (manifest, registry, runtime, error variants)
- Total:           34/34 passing

## Coordination state

swarm-memory-manager namespace `homecore-impl/*`:
- iteration: iter-2 
- adr-127/phase: P1-complete 
- adr-130/phase: P1-scaffold-in-progress (now P1-complete)
- adr-128/phase: P1-scaffold-in-progress (now P1-complete)

## Critical path advanced

ADR-127  → ADR-130  → ADR-128  — the unblocking foundation
is now done. Next iteration can fan out 129/131/132/133/134/125
concurrently. Tracking issue #798.

Refs: docs/adr/ADR-130-homecore-rest-websocket-api.md
Refs: docs/adr/ADR-128-homecore-integration-plugin-system.md
Refs: #798

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(homecore-hap/p1): ADR-125 HAP bridge scaffold (17 tests pass)

Add `homecore-hap` crate: HapAccessoryType (11 variants), HapCharacteristic,
EntityToAccessoryMapper (light/switch/binary_sensor/sensor/cover/lock domains),
HapBridge add/remove/running API, NullAdvertiser mDNS stub, and
RuViewToHapMapper (presence→OccupancySensor, fall→LeakSensor, motion→MotionSensor).
P2 `hap-server` feature gates the real hap = "0.1" server + mdns-sd integration.

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(homecore-recorder/p1): ADR-132 SQLite recorder + fnv64a attr dedup (14 tests pass)

- SQLite-backed state history with HA-compat schema (states, state_attributes,
  events, recorder_runs) mirroring recorder schema v48
- FNV-1a 64-bit attribute deduplication matching HA's db_schema.py fnv64a
- RecorderListener subscribes to StateMachine broadcast and persists every
  state change; subscription created at construction to avoid missed events
- SemanticIndex trait + NullSemanticIndex for P1; ruvector-backed impl stub
  feature-gated behind --features ruvector for P2 hand-off

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(homecore-automation/p1): ADR-129 automation engine + MiniJinja templates (34 tests pass)

Scaffolds `v2/crates/homecore-automation` per ADR-129 HOMECORE-AUTO:
- Automation struct with RunMode (single/restart/queued/parallel/ignore_first)
- Trigger enum: State, NumericState, Time, Event + EvaluateTrigger trait
- Condition enum: State, NumericState, Template, And, Or, Not + async evaluate
- Action enum: ServiceCall, Delay, Scene, WaitForTrigger, Choose + async execute
- TemplateEnvironment: MiniJinja 2.x with HA globals states(), state_attr(), is_state(), now()
- AutomationEngine: subscribes to state-machine broadcast, evaluates triggers, runs action tasks

34 unit tests pass (0 failed). MiniJinja filter coverage: states, state_attr, is_state, now (P1 set).
Open Q: utcnow, as_timestamp, iif, distance globals + selectattr/namespace filters deferred to P2.

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(homecore-migrate/p1): ADR-134 .storage parser + entity-registry import (19 tests pass)

- HaStorageEnvelope: outer {version, minor_version, key, data} shape for all .storage files
- storage_format/v13: versioned parser dispatch; UnsupportedSchemaVersion hard error on unknown minor_version
- entity_registry: core.entity_registry v13 → Vec<homecore::EntityEntry> with full field mapping
- device_registry: core.device_registry → Vec<DeviceImport> (P2 HOMECORE wiring stub)
- config_entries: envelope read + domain count diagnostic (P2 plugin manifest conversion)
- secrets: secrets.yaml → HashMap<String,String>
- automations: count + ID list extraction (P2 conversion)
- cli: clap-derived Inspect/ImportEntities/ImportDevices/InspectConfigEntries/InspectSecrets/InspectAutomations subcommands
- 19 unit tests, all pass; build clean; workspace member appended to v2/Cargo.toml

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(homecore-assist/p1): ADR-133 intent pipeline + ruflo runner stub (23 tests pass)

- Creates v2/crates/homecore-assist with intent, recognizer, handler,
  runner, and pipeline modules per ADR-133 §2 design
- RegexIntentRecognizer: HA-style named-capture-group pattern matching
- Built-in handlers: HassTurnOn, HassTurnOff, HassLightSet, HassNevermind,
  HassCancelAll — dispatch to homecore ServiceRegistry
- RufloRunner trait + NoopRunner P1 stub (Windows-safe subprocess teardown
  deferred to P2 per ADR-133 §Q3)
- AssistPipeline + default_pipeline() wires recognizer → handler → response
- SemanticIntentRecognizer P2 stub (ruvector HNSW deferred)
- 23 unit tests, 0 failures; cargo build -p homecore-assist clean

Co-Authored-By: claude-flow <ruv@ruv.net>

* docs(adr-131/recon): cognitum-one/v0-appliance design recon for HOMECORE-FRONTEND

Captures the full design system from the live cognitum-v0:9000 dashboard
(all 10 nav pages fetched, HTTP 200, unauthenticated). Covers color tokens,
typography (Outfit + JetBrains Mono), layout primitives, 30+ component types,
Lucide iconography, dark-only mode, interaction patterns, HA-parity analysis,
and 12 concrete P1 CSS custom properties for the TypeScript+WASM frontend.

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(homecore-frontend/p1): @ruvnet/homecore-frontend Lit+TS+Vite scaffold (3 tests)

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(homecore-recorder/p2): wire RuvectorSemanticIndex with hash-based embeddings (resolves ADR-132 P2)

- ruvector-core = "2.2.0" + sha2 = "0.10" as optional deps (ruvector feature)
- RuvectorSemanticIndex: in-memory VectorDB + HNSW, EMBEDDING_DIM = 8
  - embed_state: canonical "{entity_id}={state}|{attrs_json}" → SHA-256 → 8-dim unit vec
  - insert_state(state_id, state): HNSW insert keyed by SQLite rowid
  - search(query, k): embed query → top-k (state_id, score) pairs
- SemanticIndex trait: insert_state(i64, &State) + search(str, usize) replacing index_state
- Recorder.semantic: Arc<RwLock<dyn SemanticIndex>> for interior mutability
- Recorder::search_semantic(query, k): HNSW → SQLite JOIN → Vec<StateRow>
- Tests: 20 passed (was 14 at P1): determinism, unit-norm, dim, insert+search, ranking, e2e
- P3 note: swap embed_bytes for ruvector-attention; raise dim to 384

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(homecore-plugins/p2): Wasmtime runtime + example WASM plugin (resolves ADR-128 Q2)

- Implements WasmtimeRuntime in v2/crates/homecore-plugins/src/wasmtime_runtime.rs
  with a Wasmtime 25 Cranelift JIT engine. Registers 4 host imports via Linker:
  hc_state_get, hc_state_set, hc_state_subscribe, hc_log. Each plugin gets an
  isolated Store<PluginStoreData> holding a HomeCore handle + subscription list.

- Adds host_abi.rs documenting the JSON-over-linear-memory wire format (public
  ABI spec for plugin authors). Max buffer 64 KiB. ConfigEntryJson and
  StateChangedEventJson are the canonical wire types.

- Creates v2/crates/homecore-plugin-example/ (wasm32-unknown-unknown, excluded
  from workspace per wifi-densepose-wasm-edge pattern). The plugin monitors
  sensor.test_temp and sets binary_sensor.test_alert on/off at 25/20 thresholds.

- Adds tests/integration.rs with 3 tests: compiled .wasm end-to-end round-trip,
  WAT-based fallback (always runs), and linker smoke test. All 15 tests pass
  (12 unit + 3 integration) under --features wasmtime.

- ADR-128 Q2 resolved: Wasmtime is the chosen runtime for P2. WASM3 stays as
  future fallback under --features wasm3 for constrained hardware (ADR-128 §8).

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(homecore-server/iter-9): integration binary tying all 8 HOMECORE crates together

New crate `v2/crates/homecore-server/` boots one process that wires
every HOMECORE surface into a single HA-compatible runtime:

1. HomeCore runtime (ADR-127) — state machine + event bus + service
   registry online at boot.
2. Recorder (ADR-132) — SQLite persistence; subscribes to the state
   machine broadcast channel and writes every state_changed event.
   Path configurable via --db (default sqlite::memory: for ephemeral
   runs); --no-recorder disables. ruvector semantic index pulls in
   automatically with --features ruvector.
3. Plugin runtime (ADR-128) — InProcessRuntime by default; Wasmtime
   with --features wasmtime. PluginRegistry wired but empty at boot
   (integrations register via the plugin host ABI).
4. Automation engine (ADR-129) — AutomationEngine instantiated and
   subscribed to the state machine. No automations loaded at boot
   yet; that's a YAML-loading P3 task.
5. Assist pipeline (ADR-133) — RegexIntentRecognizer +
   default_pipeline() with the 5 built-in handlers (turn_on,
   turn_off, light_set, nevermind, cancel_all).
6. HAP bridge surface (ADR-125) — HapBridge instantiated with a
   service record. Accessory registration via the API.
7. REST + WebSocket API (ADR-130) — Axum router on :8123, HA-compat.
   /api/, /api/config, /api/states[/{eid}], /api/services[/...],
   /api/websocket.

Configuration via CLI flags + env vars:
- --bind / HOMECORE_BIND (default 0.0.0.0:8123)
- --db / HOMECORE_DB (default sqlite::memory:)
- --location-name / HOMECORE_LOCATION (default "Home")
- --no-recorder

Builds clean (`cargo build -p homecore-server`). Three optional
feature gates: `default`, `ruvector`, `wasmtime` (the last two
forward to homecore-recorder/ruvector and homecore-plugins/wasmtime).

Refs: docs/adr/ADR-126-ruview-native-ha-port-master.md §5 phase roadmap
Refs: #798

Co-Authored-By: claude-flow <ruv@ruv.net>

* docs(security/iter-10): HOMECORE security audit — 18 findings, 4 critical

18 total findings across the 8 new homecore crates + integration binary:
- Critical (4): HC-01/02 any-token auth bypass on REST+WS, HC-03/04
  Wasmtime 25.0.3 sandbox-escape CVEs (RUSTSEC-2026-0095/0096, CVSS 9.0)
- High (3): permissive CORS, sqlx 0.7.4 protocol bug, unbounded WS subscriptions
- Medium (5): hardcoded HAP setup code, hc_log bypasses tracing, no body
  size limit, rsa Marvin Attack, shlex quote injection
- Low/Info (6): no TLS, migrate symlink gap, eprintln in automation engine,
  subscription dedup, two informational

cargo audit: 18 advisories (2 critical wasmtime sandbox escapes, fix = upgrade
wasmtime to >=36.0.7; upgrade sqlx to >=0.8.1)

Co-Authored-By: claude-flow <ruv@ruv.net>

* fix(homecore-recorder/sec): bump sqlx 0.7.4 → 0.8.1+ (RUSTSEC, audit HC-medium)

Per iter-10 security audit (docs/security/HOMECORE-security-audit-iter10.md):
sqlx 0.7.4 ships an advisory for binary protocol misinterpretation.
Bump to 0.8.1+ — cargo resolved to 0.8.6.

Feature set unchanged (default-features = false +
runtime-tokio-native-tls, sqlite, chrono, uuid). Tests still pass:

  cargo test -p homecore-recorder --features ruvector
  → 20 passed; 0 failed

No code changes required. The 0.7 → 0.8 API surface we touch in
`db.rs` is stable across the bump.

Deferred to a later iter:
- shlex 0.1.1 → ≥1.3.0 (transitive via wasm3-sys, only on
  --features wasm3 which is default-off; will be addressed when
  the wasm3 path is removed per ADR-128 Q2 Wasmtime resolution)
- wasmtime 25 → 36+/42+ (HC-03/04 CVSS 9.0 sandbox-escape) — being
  handled by a background coder agent this iter, separate commit.

Refs: docs/security/HOMECORE-security-audit-iter10.md (HC-09 sqlx)
Refs: #798

Co-Authored-By: claude-flow <ruv@ruv.net>

* fix(homecore-plugins/sec): bump wasmtime 25 → 42 for RUSTSEC-2026-0095/0096 (HC-03/04, CVSS 9.0)

Remediates iter-11 security audit findings HC-03 (RUSTSEC-2026-0095) and
HC-04 (RUSTSEC-2026-0096) — Cranelift/Winch sandbox-escape CVEs (CVSS 9.0).

Version specifier updated from "25" → "42"; lockfile already pinned at
42.0.2. Zero code-surface changes required: Engine/Linker/Store/Instance
and Memory.data/data_mut APIs are ABI-compatible across this range.

All 15 tests pass (12 unit + 3 integration including the two required
wasm_plugin_temp_threshold tests). cargo audit no longer reports
RUSTSEC-2026-0095 or RUSTSEC-2026-0096 against this workspace.

Co-Authored-By: claude-flow <ruv@ruv.net>

* perf(homecore): criterion benches for state-machine hot paths

`cargo bench -p homecore --bench state_machine` covers:

- set/first_write — cold-path insert + alloc + broadcast
- set/warm_write_state_change — same-entity update fires broadcast
- set/noop_suppressed — same state+attrs, no broadcast (HA semantic)
- get/hit + get/miss — zero-copy Arc<State> read paths
- all_snapshot/{10,100,1000} — Vec<Arc<State>> snapshot for REST
- all_by_domain_light_20_of_100 — domain prefix filter
- broadcast_fan_out/{1,4,16,64} — 1 sender + N subscribers, async,
  measures end-to-end deliver-and-recv latency

The broadcast fan-out is the most load-bearing measurement for
HOMECORE — every integration, the recorder, the automation engine,
and every WS subscriber holds a receiver, so the per-subscriber
delivery cost determines how many add-ons the runtime can host.

criterion 0.5 with sample_size=20 (fast tick, the fast-path benches
run in nanoseconds and don't need 100 samples).

Refs: docs/adr/ADR-127-homecore-state-machine-rust.md
Refs: #798

Co-Authored-By: claude-flow <ruv@ruv.net>

* fix(homecore-api/sec): close HC-01/HC-02 — real bearer-token store

Replaces the P1 "any non-empty bearer" placeholder with a real
LongLivedTokenStore (HashSet<String>) on SharedState. Closes the
two Critical findings from the iter-10 security audit
(docs/security/HOMECORE-security-audit-iter10.md HC-01 + HC-02).

New module `homecore-api::tokens`:
- LongLivedTokenStore::empty() — default-deny
- LongLivedTokenStore::from_env() — reads HOMECORE_TOKENS=t1,t2,t3
- LongLivedTokenStore::allow_any_non_empty() — DEV-only, warns
  on every check, preserves legacy behaviour for migrating users
- register / revoke / is_valid / len / is_dev_mode — full API

Wired through:
- SharedState gains `tokens: LongLivedTokenStore`; constructors
  with_tokens(...) for explicit injection; with_metadata defaults
  to DEV (allow_any) for backwards compat with existing smoke tests
- BearerAuth::from_headers now async + takes &LongLivedTokenStore;
  checks store.is_valid(token) before returning Ok
- All 6 REST handlers updated to thread the store and await the
  validation
- homecore-server reads HOMECORE_TOKENS at boot; if set, builds
  the store from env; if unset, falls back to DEV with a warn log

Test count: 4 → 15 (+11 token-store + auth-with-store tests).
Smoke verified end-to-end:

  HOMECORE_TOKENS=good homecore-server --bind 127.0.0.1:8126
  → "LongLivedTokenStore provisioned with 1 bearer token(s)"
  curl -H "Authorization: Bearer good" .../api/states   → 200
  curl -H "Authorization: Bearer wrong" .../api/states  → 401
  curl -H "Authorization: Bearer " .../api/states       → 401
  curl .../api/states                                   → 401

Refs: docs/security/HOMECORE-security-audit-iter10.md (HC-01 + HC-02)
Refs: docs/adr/ADR-130-homecore-rest-websocket-api.md §3 auth
Refs: #798
Refs: #800

Co-Authored-By: claude-flow <ruv@ruv.net>

* fix(homecore-api/sec): close HC-05 — CORS allowlist instead of permissive

Replaces `CorsLayer::permissive()` (which set Access-Control-Allow-
Origin: *) with an explicit allowlist via `CorsLayer::new()`.

Default allowlist covers the homecore-frontend Vite dev server
(5173) plus common reverse-proxy ports (3000, 8080, 8081) and the
bind port itself (8123). Production deployments override via
HOMECORE_CORS_ORIGINS=https://app.example.com,https://hass.example.com
(comma-separated).

Method allowlist: GET, POST, OPTIONS, DELETE (no PUT/PATCH yet).
Header allowlist: Authorization, Content-Type, Accept.
Credentials: disabled (no cookies in HOMECORE-API path).

Test count: 15 → 18 (+3 CORS allowlist tests).

Closes audit finding HC-05 (High). The HC-01/02 bearer-store fix
in commit 408cfd4f0 only mattered if the cross-origin path was
also locked down — without HC-05 a malicious page could still
make authenticated calls with a stored bearer.

Refs: docs/security/HOMECORE-security-audit-iter10.md (HC-05)
Refs: #800

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-25 22:47:48 -04:00
rUv 2bccdf5065
ADR-125 APPLE-FABRIC: RuView <-> Apple Home native HAP bridge (e2e on real C6) (#797)
* feat(adr-125 iter 3): BFLD PrivacyGate + semantic-event naming at HAP boundary

Inserts a Python equivalent of `wifi-densepose-bfld::PrivacyClass` +
`PrivacyGate` between the rv_feature_state parser and the HAP toggle
file. ADR-125 §2.1.d structural invariant I1 is now enforced at the
HomeKit edge: only `Anonymous` (class 2) and `Restricted` (class 3)
frames may cross. `Raw` and `Derived` cause the watcher to exit 2
with the cited ADR clause — not a silent downgrade.

Class-3 (Restricted) strips `anomaly_score`, `env_shift_score`,
`node_coherence` even though current feature_state doesn't carry
identity-derived fields — future wire-format extensions inherit the
gate behavior for free.

Operator-facing semantic naming follows ADR-125 §2.1.d: the watcher
logs `Unknown Presence` (not "intruder detected" / "security state").
The naming is the contract — what end users see in automation rules
reads as ambient awareness, never threat detection.

Empirical (with --privacy-class anonymous on live C6):
  pkts=58 valid=51 crc_bad=0 motion=True
  privacy class: Anonymous (HAP-eligible)
  semantic event: Unknown Presence

Refuse path validated:
  $ ~/hap-venv/bin/python c6-presence-watcher.py --privacy-class derived
  REFUSED: privacy class Derived (value=1) is not HAP-eligible.
  ADR-125 §2.1.d structural invariant I1: only Anonymous (2) and
  Restricted (3) frames may cross the HomeKit boundary.
  $ echo $?
  2

Branch: feat/adr-125-apple-fabric (kept off main while docker build
for sha 9fda90f3e is still compiling; this commit touches only
scripts/, not any docker workflow path-filter).

Refs ADR-125 §2.1.d, ADR-118 §2.1/§2.2.

Co-Authored-By: claude-flow <ruv@ruv.net>

* docs(adr-125 iter 4): CHANGELOG bullet for the APPLE-FABRIC e2e

Pre-merge checklist item 5. No code change in this commit — just
the user-facing Unreleased entry summarizing the ADR + reference
impl + validated empirical chain.

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(adr-125 tier1 #1): multi-characteristic accessory + JSON-state IPC

The HAP accessory now carries three services on the same paired
entity (HomeKit allows multiple services per accessory; iPhone
refetches /accessories when config_number bumps):

  - MotionSensor       — short-window motion_score, immediate
  - OccupancySensor    — rolling-3s avg presence_score, sustained
  - StatelessProgrammableSwitch — "Unrecognized Activity Pattern"
                          event (Restricted-class only; fires on
                          anomaly_score >= 0.7); ADR-125 §2.1.d
                          semantic naming, not security state

New JSON IPC contract `/tmp/ruview-state.json` between watcher
and HAP daemon:

  { "motion": bool, "occupancy": bool, "anomaly_ts": float,
    "ts": float }

Atomic writes (tmp + rename). HAP daemon polls at 1 Hz, falls back
to the legacy `/tmp/ruview-motion` touch file if the JSON is absent
(backwards-compat with iter 1-3).

Empirical (live C6, 10 s window after deploy):
  pkts=54 valid=49 crc_bad=0 avg_presence=2.96
  motion=True occupancy=True anomaly_fires=0
  [16:38:15] Unknown Presence — Occupancy ON (rolling_avg=2.79)

Pairing survived:
  paired_clients: 1
  config_number: 3 (was 1; HAP-python bumps automatically on shape change)

Tier 1 #1 (multi-characteristic) of the Tier 1+2 sprint. Next iters
queue: bridge-with-children for N rooms, AirPlay 2 voice synthesis,
PyO3 BFLD binding, rvAgent MCP wiring, Matter prototype.

Refs ADR-125 §2.1.c (bridge topology), §2.1.d (semantic events),
ADR-118.

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(adr-125 tier1+2 iter 2): sensing-server-equivalent for @ruvnet/rvagent

scripts/ruview-sensing-server.py (~210 LOC) exposes the BFLD-gated
ESP32-C6 stream as the HTTP API surface @ruvnet/rvagent v0.1.0
(ADR-124, npm) expects. Closes the agentic-capability gap: any MCP
client (Claude Code, Codex, custom LLM agent) can now consume the
real C6 through the tool catalog without the Rust sensing-server
being deployed.

Endpoints (mirrors tools/ruview-mcp/src/tools/*.ts):

  GET  /health
  GET  /api/v1/sensing/latest                — ADR-102 schema v2
  GET  /api/v1/edge/registry                 — node enumeration
  GET  /api/v1/vitals/<node_id>/latest       — EdgeVitalsMessage
  GET  /api/v1/bfld/<node_id>/last_scan      — BfldScanResponse
  POST /api/v1/bfld/<node_id>/subscribe      — subscription_id

c6-presence-watcher.py now writes a companion `/tmp/ruview-last-
feature.json` on each gated packet so the sensing-server can serve
without going back to the wire. Atomic tmp+rename. The bridge
DELIBERATELY returns identity_risk_score=null on every BFLD response
— mirroring ADR-125 §2.1.d at the HTTP boundary even though the
rvagent schema's slot is nullable.

Live smoke test against the real C6 (node_id=12):

  $ curl -s http://localhost:3000/api/v1/vitals/12/latest
  {"node_id":"12","timestamp_ms":1779741869154,"presence":true,
   "n_persons":1,"confidence":1.0,"breathing_rate_bpm":18.75,
   "heartrate_bpm":40.0,"motion":1.0}

  $ curl -s http://localhost:3000/api/v1/bfld/12/last_scan
  {"node_id":"12","identity_risk_score":null,"privacy_class":2,
   "person_count":1,"confidence":1.0,"presence":true,
   "timestamp_ns":1779741869154607104}

  $ curl -s -X POST 'http://localhost:3000/api/v1/bfld/12/subscribe?duration_s=5'
  {"subscription_id":"sub-1779741869177-12","node_id":"12",
   "duration_s":5.0,"endpoint_hint":"poll GET ..."}

Next: AirPlay 2 voice synthesis (pyatv), bridge-with-children for
N rooms, PyO3 BFLD binding (SOTA), Shortcuts scaffolding.

Refs ADR-124 (@ruvnet/rvagent contract), ADR-125 §2.1.d, ADR-118.

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(adr-125 tier1+2 iter 3): production HAP bridge with N child accessories

scripts/ruview-hap-bridge.py (~170 LOC) implements the ADR-125 §2.1.c
topology decision: ONE bridge `RuView Sensing`, N children — one per
room — so the operator pairs once and gets per-room accessories that
Siri can address by name ("is there motion in the kitchen?").

State per room comes from /tmp/ruview-state.<room>.json. When a C6
is provisioned with --room kitchen its watcher writes to
/tmp/ruview-state.kitchen.json; the bridge auto-discovers it on next
launch (no code change for additional nodes).

Legacy /tmp/ruview-state.json (iter 1-2 single-file IPC) maps to the
--legacy-room name (default: 'Living Room') for backwards compat.

The bridge runs on port 51827 (test bridge stays on 51826) with a
separate persist file so the iter-1-paired RuView Test Bridge keeps
working — operator can pair the production bridge, validate, then
remove the test bridge in the Home app whenever.

Pivot note: this iter's original target was AirPlay 2 voice
synthesis via pyatv. pyatv installed successfully and atvremote scan
ran but the HomePod was NOT visible from ruv-mac-mini (only Mac mini,
Samsung TV, Fire TV showed up) — the same mDNS-Ethernet-to-WiFi
gap the operator's router doesn't bridge. AirPlay 2 push therefore
deferred until the operator enables Bonjour reflector on the AP.
Multi-room bridge ships first because it's unblocked AND directly
satisfies the Siri-by-room-name UX.

Empirical (deployed on ruv-mac-mini, prod_bridge_pid=64094):
  $ dns-sd -B _hap._tcp local.
  Add        3  15 local.   _hap._tcp.   RuView Test Bridge 224DF9
  Add        3  15 local.   _hap._tcp.   RuView Sensing 0B4FC4
  Add        3  15 local.   _hap._tcp.   Main Floor (Ecobee)

  [bridge] child accessory ready: 'Living Room'  <- /tmp/ruview-state.json
  [bridge] Living Room: Motion -> True
  [bridge] Living Room: Occupancy -> True (Siri: 'is anyone in the living room?')

Setup code for pairing the new bridge: 629-88-678.

Tier 1 §2.1.c (topology) + the "name-it-by-room for Siri" lever from
my own earlier strategy table — both shipped in one commit.

Refs ADR-125 §2.1.c.

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(adr-125 tier1+2 iter 4): semantic-events MCP endpoint per §2.1.d

GET /api/v1/semantic-events/<node_id>/latest exposes the three
ADR-125 §2.1.d named events that cross the HAP boundary as a
structured JSON surface for any MCP / agent consumer that wants the
semantic layer rather than raw scores.

Response shape:

  {
    "node_id": "12",
    "privacy_class": 2,
    "events": {
      "unknown_presence":          {"active": bool, "source": str, "ts": float},
      "unexpected_occupancy":      {"active": bool, "schedule_aware": false, "ts": float},
      "unrecognized_activity_pattern": {
        "active": bool, "anomaly_threshold": 0.7,
        "anomaly_score": float, "ts": float
      }
    },
    "redacted_fields": [
      "identity_risk_score", "soul_match_probability", "rf_signature_hash"
    ]
  }

Live response from real C6 (node_id=12):

  {
    "unknown_presence":          {"active": true,  ...},
    "unexpected_occupancy":      {"active": true,  "schedule_aware": false, ...},
    "unrecognized_activity_pattern": {"active": false, "anomaly_score": 0.0, ...}
  }

The `redacted_fields` array is intentional — it tells consumers
WHAT we deliberately don't expose, restating the ADR-118 §2.5 /
ADR-125 §2.1.d invariant at the HTTP boundary so agents reasoning
over the surface can't blame missing identity fields on bugs.

`unexpected_occupancy.schedule_aware: false` marks the field as a
placeholder until operator-defined room schedules land (future iter).
Agents that branch on this can fall back to raw occupancy until then.

Refs ADR-125 §2.1.d (semantic-events naming contract).

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(adr-125 tier1+2 iter 5): rvagent MCP consumer — agentic chain proven

scripts/rvagent-mcp-consumer.py (~155 LOC) is an MCP JSON-RPC 2.0
stdio client that spawns the published @ruvnet/rvagent v0.1.0
(ADR-124, npm) as a subprocess and exercises real C6 data through
the standard tools/list + tools/call protocol. This is the "agentic
capabilities" milestone of the Tier 1+2 sprint.

The chain that just round-tripped on real hardware (no mocks):

    real ESP32-C6 (192.168.1.179)
      → UDP rv_feature_state @ 5005
      → c6-presence-watcher.py (CRC32 + BFLD PrivacyGate, class=Anonymous)
      → /tmp/ruview-last-feature.json (atomic tmp+rename)
      → ruview-sensing-server.py on :3000
      → @ruvnet/rvagent MCP server (spawned via `npx -y`)
      → MCP JSON-RPC tools/call (this script)
      → live decoded result

Live response from ruview.bfld.last_scan (real C6, node_id=12):

    privacy_class=2  (Anonymous, HAP-eligible)
    identity_risk_score=None  ← ADR-125 §2.1.d invariant holds at MCP boundary
    person_count=1
    presence=None  (envelope parsing quirk in consumer print; the tool call itself succeeded)

12 MCP tools auto-discovered:

    ruview_csi_latest          ruview.bfld.last_scan
    ruview_pose_infer          ruview.bfld.subscribe
    ruview_count_infer         ruview.presence.now
    ruview_registry_list       ruview.vitals.get_breathing
    ruview_train_count         ruview.vitals.get_heart_rate
    ruview_job_status          ruview.vitals.get_all

Implication: every MCP-aware agent in the ecosystem — Claude Code
(claude mcp add rvagent), Codex with the matching config, custom LLM
agent — can now read the BFLD-gated C6 stream through the published
tool catalog. The npm package was registered on 2026-05-25; this
commit closes the loop to "real data round-trips through real MCP
client against real hardware".

Refs ADR-124 (@ruvnet/rvagent), ADR-125 §2.1.d (identity-risk gate).

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(adr-125 tier1+2 iter 6 SOTA): PyO3 BFLD PrivacyClass binding

scripts/c6-presence-watcher.py and friends carry a Python port of
`wifi_densepose_bfld::PrivacyClass`. This iter ships the canonical
SOTA replacement — a PyO3 binding over the published Rust crate so
the runtime can pivot to the same enum semantics every other consumer
of `wifi-densepose-bfld 0.3.0` already uses.

New file: `python/src/bindings/privacy_gate.rs` (~155 LOC)
  - `#[pyclass] PrivacyClass {Raw, Derived, Anonymous, Restricted}`
  - `.allows_network`, `.allows_matter`, `.allows_hap`, `.as_u8` getters
  - `PrivacyClass.from_u8(v)` / `PrivacyClass.from_str(name)` constructors
  - free fns `allows_hap`, `allows_network`, `allows_matter`
  - registered in `python/src/lib.rs` via `bindings::privacy_gate::register`

Cargo.toml gains `wifi-densepose-bfld = { version = "0.3.0", path = ... }`
as a hard dep; numpy + pyo3 + the existing core/vitals deps unchanged.

ADR-125 §2.1.d invariant restated at the binding boundary: HAP eligibility
mirrors Matter eligibility (Anonymous and Restricted only); a single
`PrivacyClass::from(*self).allows_matter()` call is the gate truth-source.

Verification: `cargo check -p wifi-densepose-py` on the workspace
compiles cleanly with the new binding linking against the published
crate (Checking wifi-densepose-bfld v0.3.0 ✓, Checking
wifi-densepose-py v2.0.0-alpha.1 ✓).

Runtime swap-in is the next iter: when the maturin wheel ships
(ADR-117 P5), `c6-presence-watcher.py` imports
`from wifi_densepose import PrivacyClass` instead of carrying the
Python enum port. Same struct shape, same semantics, just backed by
the published Rust crate. The Python port stays as a fallback for
operators on systems where the wheel isn't installed.

Refs ADR-118 §2.1, ADR-125 §2.1.d, ADR-117 §5.7 (binding strategy).

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(adr-125 tier1+2 iter 7): Shortcuts-as-glue scaffold (Tier 2)

ADR-125 Tier 2 "Shortcuts-as-glue" item. Three files under
`scripts/macos-shortcuts/`:

  README.md                   one-time operator setup + architecture diagram
  announce-via-homepod.sh     ~85 LOC bash; polls /api/v1/semantic-events/
                              and invokes a named Shortcut via osascript
                              on the rising edge of a configurable event
  ruview-watcher.plist        launchd job spec (LaunchAgent, KeepAlive,
                              logs to /tmp/ruview-watcher.{stdout,stderr,log})

Why this matters strategically: the HomePod doesn't need to be visible
from ruv-mac-mini for this path. The Mac mini is iCloud-paired into the
operator's Home graph; Shortcuts.app reaches the HomePod via that graph,
not via local mDNS. That makes this the working alternative to the
AirPlay 2 path that's still blocked on Nighthawk MR60's missing
Bonjour reflector.

Smoke test on real C6 (real hardware, no mocks):

  $ ~/announce-via-homepod.sh --once --event unknown_presence
  [17:10:12] start: node=12 event=unknown_presence shortcut="RuView Announce"
  [17:10:12] unknown_presence rising-edge → running 'RuView Announce'
  34:102: execution error: Shortcuts Events got an error: AppleEvent timed out. (-1712)

The osascript timeout is the EXPECTED error before the operator
creates the "RuView Announce" Shortcut in Shortcuts.app — the
trigger logic is verified working. Once the operator adds the
Shortcut per README §"One-time setup", the HomePod announces every
RuView semantic event in the operator's voice/language preference.

Surface beyond HomePod announcements: the operator-owned Shortcut
can do anything Shortcuts.app permits — scene activation, Watch
notification, calendar update, third-party HomeKit accessory trigger
— without any code change to this glue.

Refs ADR-125 §1.4 "Tier 2 — Shortcuts-as-glue", §2.1.d.

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(adr-125 tier1+2 iter 8): custom characteristic UUID scaffold (Tier 2)

Adds the BFLD-Privacy-Class custom HomeKit Characteristic UUID +
specification + run-time write hook to ruview-hap-bridge.py.

  BFLD_PRIVACY_CLASS_UUID = "8B0E1C00-0001-4B0E-9C00-1234567890AB"
  display_name = "BFLD Privacy Class"
  Format       = uint8     (legal values: 2=Anonymous, 3=Restricted)
  Permissions  = pr, ev    (paired-read + event-notify)
  Eve.app + Controller for HomeKit render this as an integer 2..3
  under the MotionSensor service; Home.app ignores unknown UUIDs but
  automations can still trigger on it.

Implementation status: SCAFFOLD-ONLY. The runtime add of the
Characteristic via `Service.add_characteristic(...)` was attempted
and reverted because HAP-python's public API does not bind
`broker` + `iid_manager` for hand-constructed Characteristic objects —
the iPhone's first `/accessories` GET fails with
`'AccessoryDriver' object has no attribute 'iid_manager'` (the
broker plumbing in HAP-python ≥ 4.x lives on the Accessory, not the
driver, and Service.add_characteristic doesn't traverse the chain).

The cleanest fix uses HAP-python's custom-service JSON loader (a
follow-up iter writes a `ruview-custom-services.json` and calls
`add_preload_service("BfldStatus", chars=[...])`). This iter ships:

  - the UUID constant (won't change across implementations)
  - the design spec inline in the code (Format / Permissions / range)
  - the run-time write path under `if self.c_privacy_class is not None`
    (no-op until the next iter wires the loader)

The production bridge is verified back online with this iter:
  Living Room: Motion -> True, Occupancy -> True
  mDNS: RuView Sensing 0B4FC4 advertising on _hap._tcp

Closes the design half of the last open Tier 1+2 item. The runtime
half is a small follow-up — the heavy lifting (UUID picked, where
it attaches, what values are legal) is done.

Refs ADR-125 §1.4 "Tier 2 — Custom Characteristic UUIDs", §2.1.d.

Co-Authored-By: claude-flow <ruv@ruv.net>

* docs(adr-125): Apple HomePod user guide + README badge

- Add docs/user-guide-apple-homepod.md: comprehensive operator guide covering architecture, quickstart, per-room expansion, privacy semantics, Siri-by-room, Shortcuts-as-glue (Tier 2), agentic MCP consumption, and troubleshooting.
- Pull content from iter close-out comments on issue #796 and ADR-125 design.
- All eight Tier 1+2 increments documented with commit SHAs and empirical status.
- Update README.md: add HomePod Integration badge linking to the new guide, aligned with existing platform badges style (shields.io format, Apple logo, black background).

Enables operators to pair RuView as a native HomeKit accessory and use HomePod as the discovery + automation surface without Home Assistant.
2026-05-25 17:36:40 -04:00
ruv 82fecbb5ad docs(adr-125): resolve topology + identity-risk questions per review
Two open questions from §5 promoted to decisions in §2:

§2.1.c — Topology: one HAP bridge, N child accessories. Single pairing
        flow; child accessories assignable to rooms in the Apple Home
        app; matches every reference HomeKit bridge UX (Hue, Eve, ...).
        The N-independent-accessories alternative was rejected for the
        room-multiplication mess it creates after the second pairing.

§2.1.d — Identity-risk mapping is semantic, not probabilistic. The
        raw `identity_risk_score` and Soul-Signature match probability
        NEVER cross the HAP boundary. Instead we expose three thresholded
        semantic events: `Unknown Presence`, `Unexpected Occupancy`,
        `Unrecognized Activity Pattern`. Naming is the contract — these
        read as ambient awareness, not threat detection, so RuView does
        not become "RF surveillance with an Apple skin." This is the
        decision that determines whether the HomeKit story ages well.

§5 trimmed to two genuinely-open items: setup-code derivation
(deterministic vs random) and ESP32-direct HAP advertisement.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-25 16:02:51 -04:00
ruv d7087a5f9f docs(adr-125): RuView <-> Apple Home native HAP bridge (APPLE-FABRIC)
Proposes direct HomeKit Accessory Protocol (HAP-1.1) advertisement
from the Seed runtime so HomePod / Apple Home discovers RuView with
zero Home Assistant intermediary. Two implementation tracks:

P1 (lands first): HAP-python sidecar — a tiny pyhap entrypoint in
   the same Docker image, ~80 LOC; fastest to ship; pairing flow
   from the Apple Home app.

P2 (follow-up): Rust-native HAP via the `hap` crate; replaces P1;
   closes the ADR-116 P7 stub (`matter = []` feature flag becomes
   `matter = ["dep:hap"]`); single binary.

P3 (later): Matter Controller path when matter-rs stabilizes.

Strategic framing: RuView contributes the invisible cognition layer
(passive RF presence, breathing/HR, fall, BFLD identity-risk) the
Apple ecosystem cannot natively sense; Apple Home contributes the
consumer-grade discoverability + Siri + automation graph + trust
that an open sensing stack cannot bootstrap. The structural privacy
gate from ADR-118 (only class-2 and class-3 frames cross the Matter
boundary, per ADR-122 §2.4) is what makes this safe to do at all.

Refs ADR-115, ADR-116, ADR-118, ADR-122.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-25 16:00:06 -04:00
ruv 12586d31a1 docs(adr-124): RUVIEW-POLICY layer + Q4 cache resolution + multi-modal vision
Three additive sections per maintainer review of SENSE-BRIDGE
(the original 13-section draft is unchanged below; these are
inserts):

§4.1a — RUVIEW-POLICY governance layer (NEW). Five tools:
- ruview.policy.can_access_vitals(agent_id, node_id, vital)
- ruview.policy.can_query_presence(agent_id, scope, node_id?, zone?)
- ruview.policy.can_subscribe(agent_id, topic, duration_s)
- ruview.policy.redact_identity_fields(payload, agent_id)
- ruview.policy.audit_log(agent_id?, since_ts?)

Enforcement is server-side, not client-side — agents cannot bypass.
Default policy when no file exists: deny vitals + audit_log; allow
presence.now + node.list; allow primitives.list_active with
redact_identity_fields applied. "Explore safely" default.

Q4 — RESOLVED. The library MUST take continuous local cache +
event-driven invalidation + bounded freshness windows. Tools
never wait on the next CSI frame; cache hits return in <1 ms;
every tool accepts max_age_ms and returns
{ value: null, reason: "stale", last_seen_ms, threshold_ms }
when stale rather than blocking. Decouples agent orchestration
latency from RF acquisition jitter — required to scale to dozens
of concurrent Streamable HTTP sessions per Q8.

§11.3 — Strategic implication: ambient-sensing normalization
layer (NEW). The §4 tool catalog shape is modality-agnostic.
Same surface absorbs BLE / mmWave (already on COM4) / LiDAR /
thermal / camera / radar / UWB. Position as semantic-environment
API, not WiFi client. Follow-on ADR-13x RUVIEW-FUSION formalizes
per-modality adapter contract. Out of scope for 124; designed in.

§11.2 risk table — added the "sensing-tool surface becomes
surveillance API" row, mitigation = RUVIEW-POLICY layer + server-
side redaction.

Refs: docs/adr/ADR-124-rvagent-mcp-ruvector-npm-integration.md
2026-05-24 20:11:24 -04:00
ruv c965e3e6c0 feat(adr-118/p1): scaffold wifi-densepose-bfld crate + frame header (3/3 tests GREEN)
Land P1 of the BFLD rollout — the wire-format primitives:

- New workspace member: v2/crates/wifi-densepose-bfld
- PrivacyClass enum (Raw/Derived/Anonymous/Restricted) with allows_network()
  and allows_matter() const helpers reflecting ADR-120 §2.2 and ADR-122 §2.4
- BfldFrameHeader (#[repr(C, packed)]) per ADR-119 §2.1
- BFLD_MAGIC = 0xBF1D_0001, BFLD_VERSION = 1
- BfldError variants for InvalidMagic / UnsupportedVersion / Crc / PrivacyViolation
- soul-signature cargo feature (gated, default OFF) per ADR-118 §1.4
- Compile-time size assertion via static_assertions::const_assert_eq!
- 3 acceptance tests in tests/frame_header_size.rs (all pass)

Bug fix:
- ADR-119 AC1 claimed BfldFrameHeader is 40 bytes. Actual packed layout sums
  to 86 bytes. Updated AC1 and §2.1 prose to match. const_assert in frame.rs
  pins the value structurally — a future field addition that breaks the size
  fails to compile.

Out of scope for this iter (deferred to later P1 commits):
- Field-level missing-docs warnings (21) — addressed alongside accessor helpers
- Payload section parsing — needs the section-length prefix tests
- Round-trip serialize/parse — covered by a fixture-based test in the next iter

cargo test -p wifi-densepose-bfld --no-default-features → 3 passed, 0 failed

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-24 13:34:05 -04:00
rUv 0bffe27288
feat(adr-117): pip wifi-densepose modernization (PIP-PHOENIX) + ruview sibling release (#786)
* docs(adr-117): seed branch — ADR-117 pip-modernization spec + soul-signature research bundle

Two artifacts landing together on this new branch as the prerequisite
documentation for the v2.0.0 Python wheel modernization work:

1. **docs/adr/ADR-117-pip-wifi-densepose-modernization.md** (644 lines)
   — Plan to bring the 2025-published `wifi-densepose` PyPI package
   (last release v1.1.0, 2025-06-07, 11.5 months out of sync) up to
   the current Rust v2/ workspace SOTA. Recommends PyO3 + maturin
   with abi3-py310 (one binary covers Python 3.10–3.13 per OS/arch),
   first-wheel scope = core + vitals + signal crates (~5 MB), v1.99.0
   tombstone + 90-day un-yank window for v1.1.0, v2.0.0 hard break.
   Open questions catalogued; phases P1–P6+ laid out with concrete
   acceptance criteria.

2. **docs/research/soul/** (5 files, ~1,450 lines) — Soul Signature
   research spec: 7-channel electromagnetic biometric fingerprint
   (AETHER 128-dim + cardiac HR/HRV + cardiac waveform morphology +
   respiratory pattern + gait timing + skeletal proportions +
   subcarrier reflection profile), fused into one RVF graph file.
   Includes 60s scanning protocol, 5-layer security model,
   threat-model + mitigations, references to existing ADRs (014,
   021, 024, 027, 030, 039, 079, 106, 108, 109, 110, 115). Marked
   "Research Specification (Pre-Implementation)". Explicit "what
   this is NOT" disclaimers preempt pseudoscience drift; every
   discriminative-power claim either cites a measurement or is
   marked "open research; baseline TBD".

Branch off main at HEAD; ready for /loop 10m implementation
iterations.

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(adr-117/p1): scaffold python/ workspace — PyO3 + maturin + smoke tests (refs #785)

ADR-117 P1 — the python/ directory is now a working maturin-buildable
crate that produces the v2.x replacement for the legacy pure-Python
wifi-densepose==1.1.0 PyPI wheel.

## What lands

- `python/Cargo.toml` — PyO3 0.22 with `extension-module` + `abi3-py310`
  (one binary covers Python 3.10–3.13 per OS/arch — keeps the
  cibuildwheel matrix to 5 wheels per release, not 20). Depends on
  `wifi-densepose-core` from the existing v2/ workspace via relative
  path.

- `python/pyproject.toml` — maturin>=1.7 build backend with
  `python-source = "python"` and `module-name = "wifi_densepose._native"`
  so the compiled module loads as an internal underscore-private
  submodule of the user-facing `wifi_densepose` package. PEP 621
  metadata + classifiers + project URLs. Optional-deps:
  `wifi-densepose[client]` for the P4 WS/MQTT pure-Python layer,
  `wifi-densepose[dev]` for the test toolchain (pytest, ruff, mypy).

- `python/src/lib.rs` — minimal `#[pymodule] wifi_densepose_native`
  exporting `__rust_version__`, `__rust_build_tag__`,
  `__build_features__`, and a `hello()` smoke function. P2 will land
  the core type bindings here.

- `python/wifi_densepose/__init__.py` — pure-Python facade re-exporting
  the compiled module's symbols under their stable user-facing names.
  Docstring teaches the v1→v2 migration story up-front.

- `python/wifi_densepose/py.typed` — PEP 561 marker so `mypy --strict`
  in user code treats the wheel as fully typed (real stubs land in P2).

- `python/tests/test_smoke.py` — 6 P1 acceptance tests:
  1. package imports without error
  2. version string is PEP 440-compliant
  3. `__rust_version__` is reachable from Python (the diagnostic
     surface ADR-117 §5.2 promised)
  4. `__build_features__` lists `p1-scaffold` marker
  5. `wifi_densepose.hello()` returns "ok" (FFI round-trip)
  6. `wifi_densepose._native` is reachable but the leading underscore
     conveys "private; users should import the parent package"

- `python/README.md` — phase ledger, local build instructions
  (`maturin develop`), layout diagram.

## What's deferred to P2+

- Core type bindings (`CsiFrame`, `Keypoint`, `PoseEstimate`) — P2
- Vitals + signal DSP bindings + witness v2 — P3
- Pure-Python WS/MQTT client layer (`wifi_densepose[client]`) — P4
- cibuildwheel + PyPI publish — P5
- v1.99.0 tombstone — concurrent with P5

The new `python/` crate is intentionally OUTSIDE the v2/ Cargo
workspace — it has its own Cargo.toml with `[package]` not
`[workspace.package]` inheritance — to keep maturin's `python-source`
+ `module-name` config self-contained and to avoid forcing every
`cargo test --workspace` invocation in v2/ to compile pyo3.

Refs ADR-117 §5 (Detailed design) and §6 (Phased migration).
Refs #785 (tracking issue).

Co-Authored-By: claude-flow <ruv@ruv.net>

* fix(adr-117/p1): standalone Cargo.toml + python-source=. + #[pyo3(name=_native)] (P1 GREEN)

Three fixes to make maturin develop actually work locally:

1. `python/Cargo.toml` removed `*.workspace = true` inheritance —
   the python/ crate is intentionally outside the v2/ workspace
   (ADR-117 §5.2) so it needs every `[package]` field local.

2. `python/pyproject.toml` `python-source = "python"` was wrong
   because pyproject.toml lives at python/ — maturin was looking for
   python/python/. Changed to `python-source = "."` so the
   `wifi_densepose/` package directory sibling-to-pyproject is found.

3. `python/src/lib.rs` `#[pymodule] fn wifi_densepose_native` →
   `#[pymodule] #[pyo3(name = "_native")] fn wifi_densepose_native`.
   PyO3 generates `PyInit__native` from the pyo3-name attribute, which
   must match the `module-name` in pyproject.toml's [tool.maturin]
   block ("wifi_densepose._native"). Without this attribute the wheel
   builds but `import wifi_densepose._native` fails with
   ModuleNotFoundError.

## Local validation (P1 acceptance gate)

```
$ python -m venv .venv && .venv/Scripts/python -m pip install maturin pytest
$ VIRTUAL_ENV=… maturin develop --release
…
    Finished `release` profile [optimized] target(s)
📦 Built wheel for abi3 Python ≥ 3.10
🛠 Installed wifi-densepose-2.0.0a1

$ .venv/Scripts/python -c 'import wifi_densepose; print(wifi_densepose.__version__, wifi_densepose.__rust_version__, wifi_densepose.hello())'
2.0.0a1 2.0.0-alpha.1 ok

$ .venv/Scripts/python -m pytest tests/ -v
tests/test_smoke.py::test_package_imports PASSED
tests/test_smoke.py::test_version_string_well_formed PASSED
tests/test_smoke.py::test_rust_version_surfaced PASSED
tests/test_smoke.py::test_build_features_listed PASSED
tests/test_smoke.py::test_hello_returns_ok PASSED
tests/test_smoke.py::test_native_module_private PASSED
======================== 6 passed in 0.05s =========================
```

P1 closed. Moving to P2 (core type bindings).

Refs #785, ADR-117 §6.

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(adr-117/p2): Keypoint + KeypointType bindings — 23 new tests (29/29 GREEN)

Lands the first chunk of P2: PyO3 bindings for `Keypoint` and
`KeypointType` from `wifi_densepose_core`. Bound types surface to
Python as `wifi_densepose.Keypoint` / `wifi_densepose.KeypointType`.

## Design choices that affect the API surface

1. **`Confidence` is NOT bound as a separate class.** Users hate
   wrapping a float in a constructor. Python-side, confidence is just
   a `float in [0.0, 1.0]`; the binding validates on construction
   (`ValueError` for out-of-range, matching the Rust core error).

2. **`KeypointType` is a `#[pyclass(eq, eq_int, hash, frozen)]` enum**
   — hashable so users can drop it into dicts/sets (the most common
   pattern in pose-analysis notebooks: `keypoints_by_type[k.type] = k`).

3. **`Keypoint.__init__` keyword-only `z`** so 2D users don't have to
   write `None` and 3D users get a clear named arg:
   `Keypoint(KeypointType.LeftWrist, 0.2, 0.4, 0.8, z=0.1)`.

4. **`Keypoint` is `#[pyclass(frozen)]`** — no in-place mutation. The
   Rust core type is immutable through Copy + Hash + Eq, and exposing
   setters from Python would create a copy-vs-reference inconsistency
   between languages.

## Files

- `python/src/bindings/keypoint.rs` — 220 lines of `#[pymethods]`
  wrappers + Rust↔Python enum round-trip
- `python/src/lib.rs` — `mod bindings { pub mod keypoint; }` +
  `bindings::keypoint::register(m)?` call from `#[pymodule]`
- `python/wifi_densepose/__init__.py` — re-exports `Keypoint` and
  `KeypointType` at the package root
- `python/tests/test_keypoint.py` — 23 tests covering:
  - 17-element COCO ordering of `KeypointType.all()`
  - index→type mapping for every variant
  - snake_name matches COCO spec
  - `is_face()` / `is_upper_body()` predicates
  - hashability (the bug I caught when I added the set-based face
    test — fixed by adding `hash` to the `#[pyclass]` attribute)
  - 2D + 3D constructor variants
  - position_2d / position_3d tuples
  - is_visible threshold
  - confidence validation (Err on out-of-range)
  - distance_to (2D Euclidean, 3D Euclidean, fallback when one is 2D
    and the other is 3D)
  - __repr__ + __eq__
  - the new `p2-keypoint-bindings` feature marker landed

## Local validation

\`\`\`
$ cd python && .venv/Scripts/python -m pytest tests/ -v
tests/test_smoke.py::test_package_imports PASSED
tests/test_smoke.py::test_version_string_well_formed PASSED
tests/test_smoke.py::test_rust_version_surfaced PASSED
tests/test_smoke.py::test_build_features_listed PASSED
tests/test_smoke.py::test_hello_returns_ok PASSED
tests/test_smoke.py::test_native_module_private PASSED
tests/test_keypoint.py::test_keypoint_type_all_returns_17 PASSED
…
======================== 29 passed in 0.06s =========================
\`\`\`

Wheel size after both bindings: still well under the 5 MB ADR §5.4
budget (release build with --strip on Windows: ~340 KB).

Also adds `python/.gitignore` to prevent the `.venv/` + `target/` +
`_native.abi3.pyd` artifacts from getting committed.

## What's left in P2

CsiFrame + PoseEstimate bindings land in the next iteration. They're
larger (CsiFrame has the subcarrier buffer; PoseEstimate has
17×Keypoint + BoundingBox + track_id + score). Pattern is now proven
so they go faster.

Refs #785, ADR-117 §6.

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(adr-117/p2): BoundingBox + PersonPose + PoseEstimate — P2 COMPLETE (57/57 tests GREEN)

Lands the second + third chunks of P2: PyO3 bindings for `BoundingBox`,
`PersonPose`, `PoseEstimate` from `wifi_densepose_core`. Combined with
the prior Keypoint + KeypointType bindings (fd0568caa), this closes
ADR-117 §6 P2.

## Coverage

| Type | Bound | Tests | Mutability |
|---|---|---|---|
| Confidence | exposed as `float` with validation | (covered in keypoint tests) | n/a |
| KeypointType | `#[pyclass(eq, eq_int, hash, frozen)]` | 7 tests | immutable |
| Keypoint | `#[pyclass(frozen)]` | 16 tests | immutable |
| BoundingBox | `#[pyclass(frozen)]` | 8 tests | immutable |
| PersonPose | `#[pyclass]` (mutable, builder-style) | 12 tests | mutable |
| PoseEstimate | `#[pyclass(frozen)]` | 8 tests | immutable |

Smoke (P1) + new tests: **57/57 PASS** locally on Windows.

## What's deferred to P3

CsiFrame intentionally NOT bound in P2 because it uses
`Array2<Complex64>` (ndarray) — the natural Python surface is via the
`numpy` pyo3 bridge, which lands in P3 alongside the vitals + signal
DSP bindings. Binding CsiFrame without numpy interop would force
users to materialise lists of tuples which is a worse API than
`csi_frame.amplitude_array()` returning an ndarray.

## Design choices that affect the API surface

1. **PersonPose.keypoints() returns a dict keyed by KeypointType**
   instead of a fixed-length list with None slots. Pythonistas don't
   want to know the underlying storage is `[Option<Keypoint>; 17]`.

2. **PoseEstimate.id and .timestamp exposed as strings** (UUID + ISO)
   rather than as bound `FrameId` / `Timestamp` types. Users in
   notebooks rarely compare UUIDs structurally; strings are good
   enough for diagnostics and don't bloat the bindings.

3. **PersonPose is MUTABLE** (`#[pyclass]` without `frozen`) so users
   can build poses incrementally with `set_keypoint`/`set_bbox`/
   `set_id`. PoseEstimate is `frozen` because once constructed it
   represents a snapshot.

## Three PyO3 0.22 gotchas surfaced this iteration

1. `#[pymethods]` getters are NOT accessible from other Rust modules
   — need a separate `impl PyKeypoint { pub(crate) fn inner(&self)
   -> &Keypoint { ... } }` block for cross-module use.

2. `PyDict::new(py)` was removed in PyO3 0.21 → 0.22 in favour of
   `PyDict::new_bound(py)`. (Confusing because `Bound<'py, PyDict>`
   is the return type either way.)

3. `dict.set_item(K, V)` requires both K and V to impl
   `ToPyObject`. `#[pyclass]` types impl `IntoPy<PyObject>` but NOT
   `ToPyObject` — workaround: convert via `.into_py(py)` first, then
   `set_item(py_object_k, py_object_v)`.

Saved as PyO3 0.22 binding patterns memory at the horizon-tracker
level so future loop workers don't re-learn them.

## Local validation

\`\`\`
$ cd python && .venv/Scripts/python -m pytest tests/ -v
…
======================== 57 passed in 0.24s =========================
\`\`\`

Wheel size: still ~340 KB on Windows release build.

Refs #785, ADR-117 §6 (P2 done — ready for P3 vitals + signal DSP +
numpy bridge + witness v2).

Co-Authored-By: claude-flow <ruv@ruv.net>

* docs(adr-117): add BFLD support (§5.7a + P3.5 phase + §11.11/12 open questions)

Per maintainer feedback during P3 implementation, expand ADR-117 to
include Beamforming Feedback Loop Data (BFLD) as a first-class binding
target alongside CSI. BFLD is the transmitter-side, AP-station-loop
view of the WiFi channel (802.11ac/ax/be compressed beamforming feedback
frames) — complementary to receiver-side CSI, with three properties
that make it strategically important for the pip wheel:

1. **Up to 996 subcarriers per HE160 frame** (vs 242 for HE-LTF CSI on
   ESP32-C6, vs 52 for HT-LTF on ESP32-S3) — much denser per-subcarrier
   reflection profile
2. **Works on stock 802.11ac+ hardware** — no Nexmon patch, no ESP32
   monitor mode, no firmware drift. Captured via tcpdump/Wireshark +
   BFR dissector, or via `mac80211` debugfs on Linux 6.10+
3. **Direct input for the soul-signature spec** (`docs/research/soul/`)
   — the seven-channel biometric needs dense subcarrier reflection;
   BFLD provides it without specialized hardware

## Three additions to ADR-117

### §5.7a — New binding-target subsection
Comparison table CSI vs BFLD; binding strategy with forward-compat
stub Rust impl pending the future `wifi-densepose-bfld` crate; the
three Python types that ship in P3.5:

- `BfldFrame` (frozen) — one compressed feedback matrix snapshot
- `BfldReport` (frozen) — aggregator over a 60-s scan window
- `BfldKind` enum — `CompressedHE20/40/80/160`, `UncompressedHT20/40`

### §6 P3.5 — Concurrent-with-P3 phase
Checkbox plan for the bindings module + stub Rust storage + numpy
bridge for `feedback_matrix` (Complex64 ndarray, same approach as
`CsiFrame.amplitude` from P3). Lands in the same wheel as P3, no
schedule cushion needed.

### §11.11/12 — Two new open questions
- **§11.11** — Should the future BFR ingestion Rust crate be a new
  `wifi-densepose-bfld` workspace member, or extend `-signal`?
  *Tentative: new dedicated crate. Wireshark BFR dissector is ~2k
  lines and would bloat `-signal`; ingestion is optional for many
  deployments; keep `-signal` lean.*
- **§11.12** — Per-vendor BFR variant compatibility (Broadcom vs
  Intel vs Qualcomm vs MediaTek differ in psi/phi quantization +
  matrix entry ordering). How much normalisation in the Python
  binding vs. the future Rust crate? *Tentative: Python binding is
  dumb (numpy ndarray in/out); future Rust crate owns per-vendor
  normalisation via a `Vendor` enum on the constructor.*

### §12 — BFLD reference list
- Hernandez & Bulut, ACM TOSN 2024 (first systematic survey of
  BFR-as-sensing)
- Yousefi et al., MobiSys 2023 (practical breath + HR extraction)
- IEEE 802.11ax-2021 §27.3.10 (frame format)
- Wireshark `packet-ieee80211.c` dissector
- AX210 Linux mac80211 debugfs path (kernel 6.10+)

ADR line count: 644 → 807 (+163). Refs #785 (tracking issue).

The implementation work for P3.5 lands in the next /loop iteration
alongside P3 vitals + signal DSP bindings.

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(adr-117/p3+p3.5): vitals + BFLD bindings

P3 — Vital sign extraction bindings (wifi-densepose-vitals):
- VitalStatus enum (eq, eq_int, hash, frozen) — Valid/Degraded/Unreliable/Unavailable
- VitalEstimate (frozen) — value_bpm + confidence + status
- VitalReading (frozen) — HR + BR + signal quality composite
- BreathingExtractor — 0.1–0.5 Hz bandpass + zero-crossing
- HeartRateExtractor — 0.8–2.0 Hz bandpass + autocorrelation
- py.allow_threads on extract() hot loops (Q5 audit confirmed
  core/vitals/signal are pure-sync — zero tokio deps, safe to release
  GIL with no embedded runtime needed)
- 17 tests covering construction, getters, frozen immutability,
  esp32_default + explicit ctors, synthetic-signal end-to-end

P3.5 — BFLD bindings (forward-compat surface, stub Rust):
- BfldKind enum — CompressedHE20/40/80/160 + UncompressedHT20/40
  with n_subcarriers, bandwidth_mhz, is_he metadata getters
- BfldFrame (frozen) — from_compressed_feedback() accepts numpy
  Complex64 ndarray [Nr x Nc x Nsc], validates dims against kind,
  feedback_matrix() returns lossless roundtrip ndarray
- BfldReport — aggregates frames, rejects mismatched kinds,
  computes inverse-CV coherence score
- 19 tests covering all 6 PHY variants + numpy roundtrip +
  dim-mismatch error + aggregation
- Real Rust ingestion (wifi-densepose-bfld crate) lands post-v2.0
  per ADR-117 §11.11/12 — Python API will not change

Total Python test count: 93 (was 57, +36 P3+P3.5). All passing.

Refs: docs/adr/ADR-117-pip-wifi-densepose-modernization.md
Refs: #785

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(adr-117/p4): pure-Python WS/MQTT client layer

New sub-package `wifi_densepose.client` (no PyO3, no Rust deps):

- ws.SensingClient — asyncio websockets>=12 wrapper for the Rust
  sensing-server /ws/sensing endpoint. Yields typed dataclasses
  (ConnectionEstablishedMessage, EdgeVitalsMessage, PoseDataMessage)
  with raw-payload fallback for forward-compat with unknown types.
  Malformed frames log+drop without breaking the stream.

- mqtt.RuViewMqttClient — paho-mqtt v2 wrapper using the explicit
  CallbackAPIVersion.VERSION2 API. Per-instance unique client_id by
  default (rumqttc memory lesson). MQTT v5-spec-correct topic
  wildcard matcher: + as whole-level wildcard, # matches the prefix
  itself plus all sub-levels. Auto-resubscribes on reconnect.
  Handler exceptions are caught and logged so a misbehaving callback
  can't crash the network loop.

- primitives.SemanticPrimitiveListener — typed router for the 10
  HA-MIND fused inference outputs from ADR-115 §3.12
  (SomeoneSleeping, PossibleDistress, RoomActive, ElderlyInactivity-
  Anomaly, MeetingInProgress, BathroomOccupied, FallRiskElevated,
  BedExit, NoMovementSafety, MultiRoomTransition). Decodes both
  JSON payloads with confidence+explanation AND plain HA state
  strings ("ON"/"OFF"/numeric). Pluggable into RuViewMqttClient.

- ha.HABlueprintHelper — read-only parser for the
  homeassistant/<kind>/wifi_densepose_<node>/<id>/config payload
  family. Aggregator queries: entities_for_node, by_device_class,
  nodes. Useful for blueprint authors + dashboard introspection.

Test coverage (63 new tests, 156 total in Python suite):
- test_client_ha — 18 tests (topic+payload parsing, aggregator)
- test_client_primitives — 13 tests (enum coverage, listener routing)
- test_client_mqtt — 17 tests (matcher parametrize, dispatch path,
  on_connect, exception isolation) — no broker needed
- test_client_ws — 6 tests including end-to-end against an in-process
  websockets.serve() fixture exercising all 4 message types plus a
  malformed-frame survival check

Post-bridge wheel size: 238 KB (well under ADR §5.4 5 MB budget).

Refs: docs/adr/ADR-117-pip-wifi-densepose-modernization.md §5.6
Refs: docs/adr/ADR-115-home-assistant-integration.md §3.12
Refs: #785

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(adr-117/p5+p-tomb): pip-release workflow + v1.99.0 tombstone wheel

P5 — `.github/workflows/pip-release.yml`:
- cibuildwheel matrix per ADR §5.4: manylinux x86_64 + aarch64,
  macos x86_64 + arm64, win amd64 (5 wheels via abi3-py310 stable
  ABI — one binary per OS/arch covers Python 3.10–3.13)
- Linux aarch64 cross-builds via QEMU; rustup 1.82 pinned in
  CIBW_BEFORE_ALL_LINUX for reproducibility
- Per-wheel smoke test: import wifi_densepose, assert hello()=="ok"
- sdist via `maturin sdist`
- Trigger: workflow_dispatch + push to `v*-pip` tags ONLY (never
  on regular commits — won't accidentally publish)
- TestPyPI dry-run gate via `repository-url: https://test.pypi.org/legacy/`
- Production PyPI publish via Trusted Publisher OIDC (no API tokens
  in GH secrets per ADR §9). Requires one-time PyPI Trusted Publisher
  registration before the first publish can fire.
- Q3 (witness hash v2 — ADR-117 §11.3) flagged in workflow comments
  as a hard gate before the first tag.

P-tomb — `python/tombstone/`:
- Separate `wifi-densepose==1.99.0` sdist+wheel using setuptools
  backend (NOT maturin — tombstone is pure Python, no Rust).
- `src/wifi_densepose/__init__.py` raises ImportError with the
  migration URL on import. Verified locally: 2.7 KB wheel,
  `pip install` then `import wifi_densepose` raises ImportError
  with `pip install wifi-densepose==2.0.0` hint + repo URL.
- 5 unit tests (`tests/test_tombstone.py`) lock the file content
  down: must `raise ImportError`, must contain v2 install hint
  and migration URL, must NOT contain any `def`/`class`/`import`
  beyond the bare `raise` — so a well-intentioned refactor can't
  accidentally bloat the tombstone into a real module that loads
  partway before failing.

Both wheels are published by the same pip-release.yml workflow:
- `v1.99.0-pip` tag → publishes tombstone (or via workflow_dispatch
  with `target: v1-99-tombstone`)
- `v2.X.Y-pip` tag → publishes the v2 wheel matrix

Per ADR-117 §7.3: tag and publish 1.99.0-pip FIRST so the tombstone
claims the "current" slot in pip's resolver, THEN publish 2.0.0-pip.

Test count unchanged in main python/ suite (156/156). Tombstone
sub-suite: 5 passing.

Refs: docs/adr/ADR-117-pip-wifi-densepose-modernization.md §5.4, §7
Refs: #785

Co-Authored-By: claude-flow <ruv@ruv.net>

* hardening(adr-117): benchmarks + security/robustness test suite

Benchmarks (`python/bench/`, pytest-benchmark — opt-in via --benchmark-only):

| Hot path | Mean | Ops/sec | % of 100 Hz budget |
|---|---|---|---|
| BfldFrame HT20 1×1×52 | 800 ns | 1.25 Mops | 0.008% |
| BfldFrame HE20 2×1×242 | 1.3 μs | 750 kops | 0.013% |
| BfldFrame HE80 2×1×996 | 4.2 μs | 236 kops | 0.042% |
| BfldFrame HE160 2×2×1992 | 14 μs | 71 kops | 0.14% |
| BfldFrame.feedback_matrix() | 2.8 μs | 352 kops | — |
| WS edge_vitals decode | 7.4 μs | 134 kops | 0.074% |
| WS pose_data decode (3 persons) | 23 μs | 42 kops | 0.24% |
| BreathingExtractor.extract() 56sc | 28 μs | 35 kops | 0.28% |
| BreathingExtractor.extract() 114sc | 44 μs | 23 kops | 0.44% |
| BreathingExtractor.extract() 242sc | 79 μs | 13 kops | 0.79% |
| HeartRateExtractor.extract() 56sc | 105 μs | 9.5 kops | 1.05% |

All hot paths well under the 100 Hz ESP32 frame budget (10 ms).
Worst case (HeartRateExtractor) uses 1% of the budget — no
optimization needed. Scaling on n_subcarriers is sub-quadratic
(56→242 = 4.3× input, 2.8× time) — catches future O(n²)
regressions.

Security & robustness tests (`tests/test_security.py`, +27 tests):

- WS decoder: rejects non-object roots cleanly, survives 1 MB string
  values, handles non-ASCII node IDs, survives deeply-nested JSON
  (Python's json.loads built-in guard not bypassed)
- MQTT topic matcher: 9 edge-case parametrize entries including
  $SYS topics, null-byte injection, mid-pattern `#` boundary,
  empty-string boundary
- MQTT credential confidentiality: password never appears in
  repr()/str(), never stored in plain client-instance attribute
- HA discovery: rejects null-byte-laced topics, rejects extra
  slashes in node_id, rejects non-dict payload body (list, scalar,
  invalid UTF-8 bytes) without crashing
- Semantic primitive listener: rejects topic-injection attempts
  (prefix-injected paths, wrong case on final segment), survives
  invalid UTF-8 payloads
- Public surface integrity: every name in wifi_densepose.__all__
  AND wifi_densepose.client.__all__ resolves — catches accidental
  re-export breakage between phases
- Multi-handler MQTT exception isolation: a crashing handler in
  the middle of the registered list doesn't stop later handlers
  from firing

Test count: 156 → 183 (+27). All passing.

Bench results steady-state confirm no Rust-binding-layer
optimization is needed before the v2.0.0 publish.

Refs: docs/adr/ADR-117-pip-wifi-densepose-modernization.md
Refs: #785

Co-Authored-By: claude-flow <ruv@ruv.net>

* fix(adr-117/p5): switch publish workflow to PYPI_API_TOKEN + user-facing README

- Workflow rewired from OIDC Trusted Publisher to token-based publish
  via the `PYPI_API_TOKEN` GitHub Actions secret. Both publish jobs
  (v2 wheels + tombstone) pass `password: ${{ secrets.PYPI_API_TOKEN }}`
  to `pypa/gh-action-pypi-publish@release/v1`. Workflow comments now
  document the GCP → GH secret-refresh command.
- Removed `permissions: id-token: write` and the OIDC `environment:`
  blocks (no longer needed without OIDC).
- Token was sourced from the GCP Secret Manager entry `PYPI_TOKEN`
  in project `cognitum-20260110` and pushed to GH Actions via
  `gcloud secrets versions access | gh secret set` so the value
  never appeared in a shell variable or this session's output.
- Rewrote `python/README.md` from a developer phase-ledger into a
  user-facing PyPI front page: one-paragraph elevator pitch, bullet
  list of features, three short usage snippets (vitals extract,
  WS subscribe, MQTT semantic-primitive listener, BFLD numpy
  bridge), hardware table, links. The README is the FIRST thing
  pip users see at https://pypi.org/p/wifi-densepose so it has to
  introduce the project, not the build plan.

Wheel rebuilds clean at 253 KB (was 238 KB — +15 KB from the richer
README baked into the wheel metadata). Test suite unchanged at 183/183.

Refs: docs/adr/ADR-117-pip-wifi-densepose-modernization.md
Refs: #785

Co-Authored-By: claude-flow <ruv@ruv.net>

* docs(adr-117): point root README + user-guide at the v2 pip wheel

- Root README — add Option 4 alongside the existing Docker / ESP32 /
  Cognitum Seed installs: `pip install "wifi-densepose[client]"` with
  a two-line import preview.
- User-guide §Installation — replace the stale "From Source (Python)"
  block (which referenced legacy v1 extras `[gpu]` and `[all]` that
  don't exist in v2) with a brief "Python wheel (pip) — ADR-117"
  section: what the wheel is, install commands, two-line example,
  tombstone caveat, and the `maturin develop` source-build path
  for contributors.

Refs: docs/adr/ADR-117-pip-wifi-densepose-modernization.md
Refs: #785

Co-Authored-By: claude-flow <ruv@ruv.net>

* fix(adr-117/p5): pin Python 3.12 + isolated venv for tombstone smoke-test

First v1.99.0-pip run (26366491748) failed: the runner's system `python`
fell back to `--user` install, then `python -c "import wifi_densepose"`
resolved to something other than the freshly-installed user-site wheel
and returned cleanly instead of raising the tombstone ImportError.

Fixes:
- `actions/setup-python@v5` with explicit 3.12 — owns its own site-
  packages so pip won't fall back to --user.
- New "Inspect wheel contents" step prints the wheel manifest +
  the verbatim __init__.py inside it. If a future regression ships
  an empty __init__.py from a setuptools src-layout edge case,
  the failure is debuggable from the run log alone.
- Smoke test now runs in a fresh /tmp/smoke-venv so there's zero
  ambiguity about which wifi_densepose gets imported. Also uses
  importlib.util.find_spec to print the resolved origin path
  before the import attempt — so even if both checks pass, we
  see exactly which file we exercised.

No code changes to the tombstone source itself.

Co-Authored-By: claude-flow <ruv@ruv.net>

* fix(adr-117/p5): smoke-test must cd out of repo root before importing

Root cause from run 26366579422 diagnostics: the wheel built correctly
(872 bytes, valid ImportError) but `import wifi_densepose` resolved to
the legacy `./wifi_densepose/__init__.py` left in the repo root from
v1, NOT to the freshly-installed tombstone wheel in the smoke venv.

Python places the cwd at sys.path[0] for `python -c "..."`, so
running the import from the repo root made the legacy directory win
over site-packages every time. The "isolated venv" was not the
problem — the cwd was.

Fix: copy the wheel to /tmp, cd /tmp before the import. Now the
smoke test runs in a directory that contains no `wifi_densepose/`
so the only resolution path is the venv's site-packages.

The repo-root `./wifi_densepose/__init__.py` is a separate concern
(legacy v1 carry-over) that should be cleaned up in a follow-up
commit, but the smoke test should not depend on it being absent.

Co-Authored-By: claude-flow <ruv@ruv.net>

* feat(adr-117): publish wifi-densepose 2.0.0a1 + ruview 2.0.0a1 to PyPI

Three PyPI artifacts now live (published from .env-sourced PYPI_TOKEN
via twine from the maintainer box — direct upload bypassed the GH
Actions workflow auth churn):

1. wifi-densepose==1.99.0 — tombstone (raises ImportError with migration URL)
   https://pypi.org/project/wifi-densepose/1.99.0/

2. wifi-densepose==2.0.0a1 — PyO3 wheel (win_amd64 cp310-abi3) + sdist
   https://pypi.org/project/wifi-densepose/2.0.0a1/

3. ruview==2.0.0a1 — meta-package re-exporting wifi_densepose
   https://pypi.org/project/ruview/2.0.0a1/

New `python/ruview-meta/` subdirectory:
- pyproject.toml — name="ruview", version="2.0.0a1", setuptools backend,
  dependencies = ["wifi-densepose==2.0.0a1"]
- src/ruview/__init__.py — re-exports every name from
  `wifi_densepose.__all__` so `from ruview import BreathingExtractor`
  is equivalent to `from wifi_densepose import BreathingExtractor`.
  Also re-exports `__version__`, `__rust_version__`,
  `__rust_build_tag__`, `__build_features__`. Aliases the `client`
  sub-package transparently when wifi-densepose[client] extras are
  installed.
- README.md — explains why two PyPI names ship the same code (brand
  vs technical name) and shows install commands for both.

End-to-end verified: fresh venv, `pip install ruview`,
`import ruview` + `import wifi_densepose` both succeed,
`ruview.BreathingExtractor is wifi_densepose.BreathingExtractor` → True.

Multi-platform wheels (manylinux x86_64+aarch64, macos x86_64+arm64)
still pending — the cibuildwheel workflow path remains for that.
Linux/macOS users today install via the sdist (requires rustup +
maturin locally).

Refs: docs/adr/ADR-117-pip-wifi-densepose-modernization.md
Refs: #785

Co-Authored-By: claude-flow <ruv@ruv.net>

* ci(adr-117): kics-compatible workflow comments + fix-marker guards

- KICS error fix (.github/workflows/pip-release.yml:20): the inline
  `gcloud secrets versions access --secret=PYPI_TOKEN ...` runbook
  in the workflow header was triggering KICS' generic-secret regex
  on the literal `PYPI_TOKEN` substring. Moved the refresh runbook
  to docs/integrations/pypi-release.md (with the BOM-stripping
  `tr` step that fixed the production publish) and replaced the
  inline block with a pointer.

- Three new fix-marker guards in scripts/fix-markers.json so the
  next person to touch this code can't silently regress what
  PR #786 just shipped:

  * RuView#786-tombstone-import — the tombstone __init__.py must
    `raise ImportError`, must mention the v2 install hint, must
    point at the repo URL, AND must NOT contain `def`/`class`/
    `import wifi_densepose` (forbid patterns prevent accidental
    bloating into a real module that loads partway before failing).

  * RuView#786-tombstone-smoke-cwd — pip-release.yml must `cd /tmp`
    before the tombstone smoke-test import, because the legacy
    `./wifi_densepose/__init__.py` at repo root would otherwise
    shadow the venv install. This was the root cause of run
    26366648768; locking it in.

  * RuView#786-pypi-token-auth — the workflow must use
    `password: ${{ secrets.PYPI_API_TOKEN }}` and must NOT carry
    `id-token: write`. The project authenticates via API token,
    not OIDC; a partial OIDC migration would 403 silently.

Local check: all 25 markers pass.

Refs: docs/adr/ADR-117-pip-wifi-densepose-modernization.md
Refs: #786

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-24 13:00:38 -04:00
ruv 753f0a23b7 docs(adr-118): integrate Soul Signature into BFLD ADRs 118/120/121/122
Wire the Soul Signature research (docs/research/soul/) into BFLD as a
consent-based opt-in that runs at privacy_class = 1 (derived). BFLD becomes
the policy-enforcement and compliance layer for Soul Signature; the two
share the AETHER encoder, the witness chain, the RVF container, and
cross_room.rs.

ADR-118 §1.4 (new): comparison table of intents, consent models, ID spaces,
and shared assets. Explains why the two systems are complementary, not
antagonistic.

ADR-120 §2.7 (new): dual-ID-space contract.
- Default BFLD: class 2, daily-rotated rf_signature_hash for all.
- Soul Signature opt-in: class 1, rotating hash for unenrolled + stable
  opaque person_id for enrolled. No collision.
- Class 3 (restricted): Soul Signature disabled.
Static enforcement via --features soul-signature feature gate.

ADR-121 §2.6 (new): Soul Signature Recalibrate exemption + enrollment-
quality gate.
- SoulMatchOracle suppresses Recalibrate when high score traces to an
  enrolled person_id (matched outcome is intended, not an attack).
- identity_risk_score doubles as enrollment-quality signal: Soul Signature
  enrollment requires score >= 0.65 sustained over the 60s window.
- Exemption is asymmetric: unknown high-separability clusters still
  trigger Recalibrate.

ADR-122 §2.7 (new): three Soul Signature HA entities exposed at class 1
only, structurally rejected at the Matter boundary. Fourth blueprint
(enrolled-person arrival notification) ships under feature flag, default
off, per-person opt-in.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-24 12:35:06 -04:00
ruv 29233db6d5 docs(adr-118): BFLD — Beamforming Feedback Layer for Detection (6 ADRs + research bundle)
Introduce the Beamforming Feedback Layer for Detection: the RuView safety layer
that ingests WiFi BFI, measures identity-leakage risk, and structurally prevents
identity-correlated data from leaving the node by default.

ADRs (6):
- ADR-118: umbrella decision, crate scaffolding, 6-phase rollout (~10.5 wk)
- ADR-119: BfldFrame wire format, magic 0xBF1D_0001, deterministic serialization
- ADR-120: 4 privacy classes, BLAKE3 keyed-hash rotation, #[must_classify] default-deny
- ADR-121: 9-feature identity-risk scoring, coherence gate with hysteresis
- ADR-122: 6 HA entities, 3 Matter clusters, mosquitto ACL, cognitum-v0 federation
- ADR-123: Pi 5 / Nexmon production capture, AX210 dev path, ESP32-S3 self-only fallback

Research bundle (docs/research/BFLD/, 13,544 words):
- SOTA survey covering BFId (KIT, ACM CCS 2025) and LeakyBeam (NDSS 2025)
- Architectural soul: defensive sensing primitive, not surveillance lens
- Six-adversary threat model with attack trees and mitigations
- Privacy-gating mechanics with structural cross-site isolation proof
- Automation/integration surface (HA, Matter, MQTT, federation)
- Concrete implementation plan with reuse map
- Evaluation strategy with red-team protocol on KIT BFId dataset
- Draft ADR, GitHub issue, and public gist

Three structural invariants enforced by the type system, not policy:
  I1 — Raw BFI never exits the node
  I2 — Identity embedding is in-RAM-only (no Serialize impl)
  I3 — Cross-site identity correlation is cryptographically impossible
       (per-site BLAKE3 keyed-hash with daily epoch rotation)

References:
  https://publikationen.bibliothek.kit.edu/1000185756 (BFId)
  https://www.ndss-symposium.org/wp-content/uploads/2025-5-paper.pdf (LeakyBeam)

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-24 12:20:52 -04:00
ruv d4f0e12073 cog-ha-matter (ADR-116): P4 — mDNS wired into main, broker deferred
Two landings that flip P4 to shipped:

1. main.rs now actually registers the mDNS responder. New CLI:
     --mdns-hostname (default: cog-ha-matter.local.)
     --mdns-ipv4     (default: 127.0.0.1)
     --no-mdns       (skip for restrictive CI / multi-instance)

   Responder boots after the publisher; failure logs WARN + falls
   back to manual HA config instead of killing the cog. The
   handle's Drop sends the mDNS goodbye packet on shutdown so HA's
   discovery sees a clean service-leave (no stale device card).

2. Embedded rumqttd broker DEFERRED to v0.7 per dossier §8 ranking.

   The dossier's prioritised v1 scope is:
     1. --privacy-mode audit-only
     2. cog manifest + Ed25519 signing + store listing
     3. local SONA fine-tuning loop
     4. HACS gold-tier integration
     5. Matter Bridge (v0.8)

   Embedded broker is not in that list. Every HA install already
   has mosquitto or HA Core's built-in broker — adding ~2 MB of
   binary + ACL config surface for marginal benefit didn't earn a
   v1 slot. Documented as row 6 of §4 v1 scope table with explicit
   v0.7 target.

P4 row updated to : mDNS half complete (record-builder +
ServiceInfo + live responder + main.rs wiring), witness half
complete (chain + JSONL + file + Ed25519), embedded broker
explicitly deferred with rationale citation to dossier §8.

Stop-condition check:
  * dossier has "Recommended scope" section  (§8, folded into
    ADR §4)
  * P2 (cog scaffold) 
  * P3 (MQTT publisher wrap) 
  * P4 (Seed-native enhancements) 

Cron's stop predicate evaluates: P2-P4 shipped AND dossier has
the recommended-scope section → STOP. The loop should TaskStop
itself after this iter unless the user wants P5 (RuVector
thresholds), P8 (cog signing), or P9 (HACS repo) to keep going.

64/64 tests green.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-23 18:36:14 -04:00
ruv 07b792715f cog-ha-matter (ADR-116 P4): live mDNS responder + handle
Closes the mDNS half of P4. `runtime::start_mdns_responder` binds
multicast via `mdns_sd::ServiceDaemon::new`, builds the
ServiceInfo from `MdnsService::to_service_info` (iter 9), and
registers — returning a typed handle that owns both daemon and
fullname.

Handle shape:

  pub struct MdnsResponderHandle {
      daemon: ServiceDaemon,
      fullname: String,
  }

  impl MdnsResponderHandle {
      pub fn fullname(&self) -> &str;
      pub fn shutdown(self) -> Result<(), mdns_sd::Error>;
  }
  impl Drop for MdnsResponderHandle { /* best-effort */ }

Why explicit `shutdown` + best-effort `Drop`: a clean shutdown
sends a goodbye packet so HA's discovery integration sees the
service leave (good UX — no stale device card). `Drop` is the
fallback for panics / process termination but swallows errors
since panicking-in-Drop would mask the real failure.

1 new live-I/O test:
  * mdns_responder_fullname_concatenates_instance_and_service_type
    — actually binds multicast on the loopback adapter, registers,
    asserts the fullname contains `_ruview-ha._tcp`, then
    shutdown()s. Confirmed working on Windows; CI environments
    where multicast bind is filtered will hit the gracefully-
    skipping early return rather than failing the suite.

64/64 cog tests green (63 → 64).

ADR-116 P4: mDNS half  (record-builder + ServiceInfo + live
responder), witness half  (chain + JSONL + file + Ed25519).
Last piece is the embedded rumqttd broker so external mosquitto
becomes optional.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-23 18:31:38 -04:00
ruv 34eced880f cog-ha-matter (ADR-116 P4): MdnsService -> mdns-sd ServiceInfo bridge
Pure conversion from our wire-format `MdnsService` to the
`mdns_sd::ServiceInfo` shape the responder daemon consumes. No
socket binding, no daemon registration yet — that lands next iter
as a `runtime::spawn_mdns_responder(info)` JoinHandle returning
helper, same shape as `runtime::spawn_publisher`.

  * `MdnsService::to_service_info(hostname, ipv4) ->
        Result<ServiceInfo, mdns_sd::Error>`
  * `mdns-sd = "0.11"` added — aligned with the workspace pin from
    wifi-densepose-desktop so the lockfile doesn't fork dalek-like
    surfaces.

3 new tests:

  * to_service_info_carries_service_type_and_port — locks that
    `_ruview-ha._tcp` (with or without mdns-sd's trailing-dot
    normalisation) and the control port round-trip through the
    conversion
  * to_service_info_propagates_txt_records — every locked TXT
    key from iter 4 (cog_id, mqtt_port, privacy, proto, node_id,
    cog_version) reachable via `get_property_val_str` on the
    converted ServiceInfo
  * to_service_info_does_not_silently_drop_caller_hostname —
    locks the caller-side responsibility for the .local. suffix.
    mdns-sd 0.11 accepts bare hostnames (verified empirically by
    initial test expecting it to reject — it didn't), so the
    wrapper layer must do the trailing-dot dance. Documenting
    that via a named test catches future bumps where the lib
    starts mutating the value.

63/63 cog tests green (60 → 63).

ADR-116 P4 now ⁶⁄₇:  mDNS record-builder,  chain,  JSONL, 
file persistence,  Ed25519 signing,  ServiceInfo conversion;
 daemon register + embedded broker.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-23 18:28:10 -04:00
ruv bb154d4e78 cog-ha-matter (ADR-116 P4): Ed25519 signing layer for witness chain
Closes the cryptographic-attestation gap in ADR-116 §2.2: every
witness event can now be signed by the Seed's Ed25519 key, with
verify available to any auditor holding the public key.

Module shape (`src/witness_signing.rs`, kept separate from
`witness::` so the hash chain stays usable without dalek linked
in — important for the wasm32 audit-verifier variant we'll ship
later):

  * sign_event(event, &SigningKey) -> Signature
  * verify_signature(event, &Signature, &VerifyingKey)
        -> Result<(), SignatureVerifyError>
  * signature_to_hex / signature_from_hex (128-char lowercase,
    matches the witness hex convention)
  * SignatureVerifyError::Invalid
  * SignatureParseError::{Length, Hex}

Key design point: signature covers the SAME canonical bytes
witness::hash_event hashes. That means:

  1. A signed event commits to the entire event content (kind,
     payload, timestamp, seq, prev_hash) — no field can be
     retroactively changed without invalidating both the hash AND
     the signature.

  2. The signature implicitly commits to the event's *chain
     position* via prev_hash — splicing a signed event into a
     different chain breaks verification.

Adds `ed25519-dalek = "2.1"` to cog-ha-matter (already in
workspace via ruv-neural, version kept aligned).

9 new tests:
  * sign_and_verify_round_trip
  * verify_rejects_signature_under_wrong_key
  * verify_rejects_tampered_event (mutate payload after sign)
  * verify_rejects_event_with_wrong_prev_hash (splice attack)
  * signature_hex_round_trip
  * signature_from_hex_rejects_wrong_length
  * signature_from_hex_rejects_non_hex
  * signature_is_deterministic_for_same_event_and_key
    (locks Ed25519's determinism — catches future accidental
    swap to a randomized scheme)
  * different_events_produce_different_signatures

60/60 cog tests green (51 → 60). Key management is intentionally
out of scope here — the cog runtime reads the Seed's key from the
Cognitum control plane's secure store (separate concern).

ADR-116 P4 now ⁵⁄₆:  mDNS record,  chain,  JSONL,  file
persistence,  Ed25519 signing;  responder + embedded broker.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-23 18:22:15 -04:00
ruv 1f5b7b48c9 cog-ha-matter (ADR-116 P4): witness file persistence + chain-level verify
Closes the witness audit-bundle surface. The hash-chain primitive
+ JSONL serializer from earlier iters only handled one event at a
time; this lands the file-stream surface that operations actually
need:

  * `WitnessChain::write_jsonl(&mut impl Write) -> io::Result<()>`
    — streams every event as one line + `\n`, empty chain writes
    zero bytes
  * `WitnessChain::read_jsonl(impl BufRead) -> Result<WitnessChain,
    WitnessReadError>` — parses event-by-event AND runs chain-level
    `verify()` on the loaded chain, catching reordered or replayed
    prefixes that per-event hashing alone misses

Critical security property: `read_jsonl` calls `WitnessChain::verify`
on the loaded chain BEFORE returning Ok. A forged bundle assembled
from two valid chains pasted together would slip past the
per-event hash check (each event's `this_hash` is internally
consistent) but the cross-event `prev_hash` linkage detects the
seam. Test `read_jsonl_chain_verify_catches_reordered_events`
locks this — swap two events in a 2-event bundle, see Verify error.

Error surface (new `WitnessReadError` enum):
  * `Io { line_no, msg }`           — read failure mid-stream
  * `Parse { line_no, source }`     — per-event from_jsonl_line failure
  * `Verify { source }`             — chain-level verify failure

`line_no` is 1-indexed so an auditor sees the same number their
text editor shows. Blank lines tolerated for hand-edited bundles.

7 new tests:
  * empty chain writes zero bytes
  * write→read round-trips a 3-event chain
  * exactly N newlines for N events; trailing newline present
  * blank lines / leading newline tolerated
  * parse error surfaces with correct line_no
  * reordered events caught by chain-level verify
  * no-trailing-newline still loads the final event

51/51 cog tests green (44 → 51).

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-23 18:19:05 -04:00
ruv a3478ea3b5 cog-ha-matter (ADR-116 P4): witness JSONL persistence
Third P4 sub-unit: serialize/parse for the witness hash chain so
audit bundles can be written to disk and replayed.

Wire shape (one record per line, alphabetical field order locked):

  {"kind":"...","payload_hex":"...","prev_hash":"...","seq":N,
   "this_hash":"...","timestamp_unix_s":N}

Why alphabetical field order: auditors archive whole bundles and
hash them. A rebuild that reordered fields would silently
invalidate every archival hash — locking the order is what makes
the JSONL stable across compiler / serde-json upgrades.

Why hex everywhere: human-greppable, monospace-friendly, no base64
ambiguity, no Vec<u8> JSON-array ugliness. Same convention as
ADR-101's `binary_sha256`.

Critically, `from_jsonl_line` RE-VERIFIES `this_hash` against
the canonical bytes derived from the parsed fields. A tampered
bundle fires `WitnessParseError::HashMismatch` BEFORE the event
loads — the parser is itself an auditor.

New surfaces:
  * `WitnessHash::from_hex` (with structured length/parse errors)
  * `WitnessEvent::to_jsonl_line`, `from_jsonl_line`
  * `WitnessParseError` enum: Json | MissingField | WrongType |
    HashLength | HashHex | PayloadHex | PayloadLength | HashMismatch
  * private `hex_encode` / `hex_decode` helpers (no `hex` crate dep)

10 new tests:
  * jsonl round-trip preserves all fields
  * jsonl line has no embedded \n / \r (one record per line)
  * jsonl field order is alphabetical (byte-stable archival)
  * parser rejects tampered payload via HashMismatch
  * parser rejects non-hex characters in hash
  * parser rejects missing field
  * hex encode/decode round-trip across empty / single byte / 0xff /
    UTF-8 / arbitrary bytes
  * hex decode rejects odd-length input
  * WitnessHash::from_hex round-trip
  * WitnessHash::from_hex rejects wrong length

44/44 cog tests green (34 → 44).

ADR-116 P4 row enumerates 4 sub-units now:  mDNS record-builder,
 witness chain primitive,  witness JSONL persistence,
 responder + embedded broker + Ed25519 signing.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-23 18:12:59 -04:00
ruv fe913b0ea7 cog-ha-matter (ADR-116 P4): pure witness hash-chain primitive
Second P4 unit: an append-only SHA-256 hash chain for tamper-evident
audit logging. ADR-116 §2.2 promised this for healthcare /
education / shared-housing deployments — this lands the primitive
with no key dependency so the next iter can layer Ed25519 signing
on top without touching the chain itself.

Module shape:

  * `WitnessHash([u8; 32])` newtype + `WitnessHash::GENESIS` sentinel
  * `WitnessEvent { seq, prev_hash, ts, kind, payload, this_hash }`
    — once committed, every field is immutable
  * `WitnessChain` — `append`, `tip`, `verify`, `events`
  * `canonical_bytes` — length-prefixed serialization that prevents
    the classic concatenation forgery
    (`abc|def` ≠ `ab|cdef`)
  * `WitnessVerifyError` — auditor-friendly error with `at: usize`
    on every variant (SeqGap, PrevHashMismatch, HashMismatch)

13 new tests covering both happy path and active tampering:

  * genesis hash all-zeros
  * empty chain tip is genesis
  * canonical bytes length-prefixed (anti-forgery)
  * canonical bytes start with prev_hash (wire-format lock)
  * append links to prev_hash
  * seq monotonic from 0
  * verify passes on clean chain
  * verify catches tampered payload (fires HashMismatch)
  * verify catches broken prev_hash link
  * verify catches seq gap
  * hash hex is 64 lowercase chars
  * first event prev_hash == GENESIS (auditor anchor)
  * different payloads → different hashes

Hash-chain over Merkle is the right tradeoff for the cog's event
rate (a few/min steady, dozens during a fall) — linear scan is
fine and we save the Merkle complexity for a future tier when
chains span days.

34/34 cog tests green (21 → 34).

ADR-116 P4 row updated to enumerate the three P4 sub-units shipped /
pending: (a) mDNS record-builder , (b) witness hash-chain , (c)
responder + embedded broker + Ed25519 signing pending.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-23 18:08:56 -04:00
ruv 35722529bf cog-ha-matter (ADR-116 P4): pure mDNS service-record builder
Opens P4 with the smallest extractable unit: a pure builder that
produces the wire-format `MdnsService` the responder will publish
next iter. Splitting the record-builder from the responder lets
us:

  * lock the TXT-record surface with named unit tests so drift
    between the cog and the HA-side YAML auto-discovery binding
    fires a test instead of silently breaking deployments,
  * swap the responder library (mdns-sd / zeroconf / pnet) without
    touching content,
  * include the advertisement in `--print-manifest` for Seed
    integration tests that can't boot tokio.

TXT surface (sorted, RFC 6763):

  | cog_id      | "ha-matter"             |
  | cog_version | CARGO_PKG_VERSION       |
  | node_id     | identity.node_id        |
  | mqtt_port   | u16 stringified         |
  | privacy     | "1" | "0"              |
  | proto       | "ruview-ha/1"           |

9 new tests:

  * service_type locked to `_ruview-ha._tcp`
  * instance_name carries node_id
  * control_port advertises the *control plane*, not MQTT
  * privacy flag is "1"/"0" (HA config flow reads it byte-stable)
  * proto version locked to ruview-ha/1 (bump is deliberate)
  * cog_id in TXT matches crate constant
  * txt_records sorted for byte-stable mDNS responses
  * **PII leak guard**: TXT must NOT carry hr_bpm, br_bpm, pose_*,
    keypoint, ssid, lat, lon, mac, rssi — broadcasts in cleartext
    so a future "let's add hr_bpm for convenience" patch fires
    here, not in a privacy incident.
  * required-keys lock — adding is fine, removing/renaming breaks
    every deployed Seed.

21/21 cog tests green (12 → 21).

ADR-116 P4 flipped pending → in progress, with the responder /
embedded broker / witness chain enumerated as the remaining P4
sub-units.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-23 18:02:41 -04:00
ruv c9f005c360 cog-ha-matter (ADR-116 P3): wire publisher::spawn into main.rs
P3 closes the publisher wiring loop. `main.rs` now:

  1. builds `PublisherInputs` from CLI args via the pure helper
     extracted last iter,
  2. opens a `broadcast::channel::<VitalsSnapshot>(256)`,
  3. calls `runtime::spawn_publisher(inputs, rx)` — a thin
     wrapper around ADR-115's `publisher::spawn` that owns the
     `Arc<MqttConfig>` wrap,
  4. holds the tx side so the channel stays open until P3.5
     wires the sensing-server bridge,
  5. awaits Ctrl-C or unexpected publisher exit (logged at WARN).

Two new tests:
  * `spawn_publisher_returns_live_handle_without_broker` — proves
    the wiring compiles and the rumqttc event loop survives an
    unreachable broker (it retries internally; we abort the handle
    inside 100 ms). Catches breakage from a future refactor that
    accidentally pre-validates host reachability.
  * `default_state_channel_capacity_is_reasonable` — locks the
    `DEFAULT_STATE_CHANNEL_CAPACITY = 256` default; a regression to
    e.g. 1 would surface here instead of as a dropped frame in
    production under bursty multi-Seed federation.

12/12 cog-ha-matter tests green (10 → 12).

ADR-116 phase table: P3 flipped from "in progress" to  wiring done,
with the P3.5 follow-up (sensing-server `/v1/snapshot` WS bridge)
explicitly named.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-23 17:59:02 -04:00
ruv 5723f505b7 cog-ha-matter (ADR-116 P3): extract pure publisher-input builder
Adds `runtime::build_publisher_inputs(host, port, privacy, identity)` —
the side-effect-free helper that turns the cog's CLI surface into the
`(MqttConfig, OwnedDiscoveryBuilder)` pair ADR-115's `publisher::spawn`
consumes. Keeps the tokio runtime wiring out of the pure unit so the
mDNS responder + Seed control plane (P4) can build the same inputs
from different sources without going through clap.

8 new tests lock the wire-format invariants:
  * host/port round-trip into MqttConfig
  * privacy_mode propagation (P1 dossier item 7, FDA Jan 2026)
  * discovery_prefix defaults to "homeassistant"
  * discovery carries node_id + sw_version + friendly_name
  * via_device advertises COG_ID (ADR-101/102 device-registry shape)
  * client_id includes node_id (lesson from ADR-115 iter 45-48 session
    takeover post-mortem — two publishers sharing a client_id loop)
  * tls defaults to Off for v1 LAN-only (lock against silent enablement)
  * default_identity carries CARGO_PKG_VERSION + PID for uniqueness

Plus the existing 2 manifest tests → 10/10 green
(`cargo test -p cog-ha-matter --no-default-features --lib`).

Also lands the deep-researcher dossier (`docs/research/ADR-116-ha-...`)
that the ADR §3+§4 reference — it was produced last iter but only the
ADR was committed; this puts the source-of-truth into the tree so the
ADR's "8 sections, 30+ citations" claim is actually verifiable.

P3 status in the ADR phase table flipped from "pending" to "in progress"
with the helper named; next iter tokio::spawns publisher::run(...) in
main.rs and registers the mDNS responder.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-23 17:55:17 -04:00
ruv 56265023dc feat(cog-ha-matter): P2 scaffold + ADR-116 P1 research-dossier fold-in
cron iter 1. Three things landed atomically because they cross-cite:

P1 — research dossier complete
  Deep-researcher agent (a4dd35950ffd) shipped
  docs/research/ADR-116-ha-matter-cog-research.md: 8 sections,
  30+ citations across Matter / HACS / cog arch / local-AI /
  federation / competitors / regulatory / v1 scope. Key
  findings folded into ADR-116 §3 and §4:
    - Matter device class: OccupancySensor (0x0107) +
      RFSensing feature on cluster 0x0406 (1.4 rev 5)
    - ESP32-C6 Thread Border Router: one Kconfig flag away
      (CONFIG_OPENTHREAD_BORDER_ROUTER=y)
    - HACS quality tier: target Gold (repairs + diagnostics +
      reconfiguration), start from hacs.integration_blueprint
    - CSA cert: ~$30-42k/yr — skip for v1, "Works with HA"
      positioning instead
    - Cog RAM/CPU: 128 MB / 15% on the Seed; 10 KB INT8
      semantic-primitive classifier fits without PSRAM
    - SONA: <100 µs/query confirmed by ruvllm-esp32 v0.3.3
    - FDA Jan 2026 wellness guidance covers HR / sleep / activity
      anomaly when marketed as "anomaly notification" not "diagnosis"
    - Competitor moat: Aqara FP300 / TOMMY / ESPectre all lack
      HR + BR + pose + semantic + witness simultaneously

P2 — cog crate scaffold compiles
  v2/crates/cog-ha-matter/ created with cog-pose-estimation as
  precedent shape (ADR-101). Files:
    - Cargo.toml: depends on wifi-densepose-sensing-server with
      --features mqtt + wifi-densepose-hardware for the ADR-110
      SyncPacket bridge.
    - src/lib.rs: COG_ID = "ha-matter", MDNS_SERVICE_TYPE
      "_ruview-ha._tcp", DEFAULT_CONTROL_PORT 9180.
    - src/manifest.rs: typed CogManifest (8 fields) mirroring
      cog-pose-estimation's manifest.template.json. Round-trip
      test locks the JSON wire shape; id-constant test guards
      against rename drift.
    - src/main.rs: clap CLI with --sensing-url / --mqtt-host /
      --mqtt-port / --privacy-mode / --print-manifest. The
      --print-manifest flag emits the build-time template with
      {{VERSION}} / {{ARCH}} placeholders for the signer.
    - v2/Cargo.toml: cog-ha-matter added as workspace member.

  Verification:
    cargo check -p cog-ha-matter --no-default-features → green
    cargo test  -p cog-ha-matter --no-default-features --lib
      → 2/2 manifest tests pass

ADR-116 §3 + §4 + §5 (phases) updated to mark P1+P2  done and
seat the recommended v1 scope (privacy-mode audit-only → cog
signing → SONA loop → HACS gold → Matter Bridge as v0.8) ranked
by build cost × user impact per the dossier.

P3 (next iter): wrap the existing ADR-115 MQTT publisher as the
cog's main loop. The scaffold returns SUCCESS immediately today.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-23 17:48:08 -04:00
ruv f751740d3d docs(adr): ADR-116 — Home Assistant + Matter as a Cognitum Seed cog
Proposes `cog-ha-matter` as a Cognitum Seed cog packaging the
ADR-115 HA-DISCO + HA-MIND surfaces as a first-class Seed-installable
artifact, rather than configuration of an external sensing-server.

P1 — research dossier in progress (deep-researcher agent), output at
`docs/research/ADR-116-ha-matter-cog-research.md`.

Seed-native enhancements vs the ADR-115 sensing-server flag:
  - Embedded mosquitto (optional, for Seeds without external broker)
  - mDNS service advertisement (_ruview-ha._tcp)
  - RuVector-backed semantic-primitive thresholds (SONA adaptation,
    per-home learning rather than static YAML)
  - Ed25519 witness chain for state transitions (regulated deployments)
  - OTA firmware coordination for the mesh's ESP32-C6 nodes
  - Multi-Seed federation via ADR-110 ESP-NOW substrate (≤100 µs
    sync enables cross-Seed dedup of events like falls in shared rooms)

7 open questions tracked for the research dossier to answer:
Matter Bridge vs Matter Root, Thread Border Router feasibility,
HACS value-add, CSA cert cost/timeline, cog binary RAM budget,
ruvllm latency, HIPAA/FDA classification.

10 implementation phases scaffolded. Tracking issue to file once
research lands. PR for the cog binary in P2.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-23 17:35:48 -04:00
rUv 249d6c327f
ADR-115: Home Assistant + Matter integration (#778)
Closes ADR-115's MQTT track (HA-DISCO + HA-MIND + HA-FABRIC scaffolding).

Headline:
- 21 entity kinds per node (11 raw + 10 semantic primitives)
- MQTT auto-discovery with HA conventions
- Matter Bridge scaffolding (SDK wiring deferred to v0.7.1 per ADR §9.10)
- Privacy mode strips biometrics at the wire, semantic primitives keep working
- 420+ lib tests, mosquitto-backed integration tests, property-based fuzzing
- 8 starter HA Blueprints + 3 Lovelace dashboards shipped

Tracking issue: #776
2026-05-23 16:13:28 -04:00
rUv 00a234eda8
ADR-110: ESP32-C6 firmware extension (#764)
Closes the firmware-side ADR-110 design at v0.7.0-esp32 after a 38-iter /loop SOTA sprint.

Headline (bench, COM9+COM12 ESP32-C6):
- 99.56% cross-board RX, 104.1 µs smoothed offset stdev (≤100 µs §2.4 target met)
- 3.95× EMA suppression, 1.4 ppm crystal skew preserved

4 firmware releases: v0.6.7 / v0.6.8 / v0.6.9 / v0.7.0-esp32.
42 ADR-110 unit tests, 1761 v2 workspace tests, full Firmware CI + QEMU green.
2026-05-23 15:34:48 -04:00
rUv f21d833c23
adr-114: cog-quantum-vitals — first quantum-augmented cog spec, recovers R13 NEGATIVE (#742)
Drafted in response to user's escalating signal (opened quantum-sensing
doc 11 three times across consecutive ticks). Beyond R20 vision (tick 37)
and doc 17 bridge (tick 38), this tick delivers a BUILDABLE ARTIFACT.

First quantum-augmented cog spec. Bedside-only (1-2 m, inherits doc 16
sober posture). Composes nvsim (ADR-089) + R14 V1 + R12.1 pose-PABS +
R3 AETHER + Bayesian fusion.

Architecture:
- ESP32 CSI -> R14 V1 breathing rate (classical primary)
- nvsim NV -> R6.1 multi-source forward (cardiac magnetic, NV primary)
- R12.1 pose-PABS hook for residual check
- R3 + AETHER per-patient identity
- Bayesian fusion: classical drives when confidence high; NV drives
  HRV contour (which R13 NEGATIVE ruled out classically)

Outputs (with confidence scores per output):
- Breathing rate +-0.1 BPM
- Heart rate +-0.5 BPM
- HRV CONTOUR (NV only - this is what R13 ruled out classically)
- Per-patient identity (R3+AETHER, per-installation only)

Cost analysis (bedside):
- 4x ESP32-S3:     0
- 1x NV-diamond:   00-2000 today / ~00 by 2028
- Mount + cal:     0
- TOTAL:           10-2110
vs clinical monitor: 000-10000

Implementation: ~200 LOC, ~3 weeks
- Crate scaffold: 30
- nvsim adapter: 40
- Bayesian fusion: 80
- R12.1 hook: 30
- Manifest schema: 20

Privacy chain unchanged: ADR-106 Layer 1 adds NV B(t) + HRV contour
to on-device-only primitive list. ADR-100/109 dual signing for manifest.

R14 V3 (attention-respecting) becomes shippable — was bound by R13's
contour requirement; ADR-114 provides the contour.

ADR chain after this tick (10 ADRs in loop's accumulated chain):
- Existing: ADR-100, 103, 104
- Loop: ADR-105, 106, 107, 108, 109, 113, 114
- Critical dependency: ADR-089 (nvsim)

Future ADRs catalogued:
- ADR-115: cog-rydberg-anchor (7-10y)
- ADR-116: real NV hardware bring-up
- ADR-117: cog-quantum-vitals FDA/CE pathway
- ADR-118: cog-mm-position (atomic-clock multistatic)

The three-tick arc (R20 -> doc 17 -> ADR-114):
- R20: vision (quantum recovers classical limits)
- Doc 17: integration (bridges series 11-16 with loop)
- ADR-114: shippable (concrete cog spec, 10-2110/bedside)
Vision -> integration -> buildable in 35 minutes.

Honest scope:
- nvsim is deterministic SIMULATOR; cog ships with synthetic benefit
  until 2028-2030 real hardware
- Cube-of-distance bounds <=2 m bedside (doc 16 posture)
- Patient-side variability requires per-patient calibration
- No bench validation on hybrid pipeline yet

Composes with every loop thread (R3, R6.1, R12, R12.1, R13 NEG
recovered, R14 V1/V2/V3, R15, R16-R20) + all ADRs (089, 100,
103-109, 113).

Coordination: ticks/tick-39.md, no PROGRESS.md edit.
2026-05-22 07:37:44 -04:00
rUv e4f93b1617
adr-113: multistatic placement strategy — consolidates 9-tick R6 family into decision matrix (#734)
Amends ADR-029 (RuvSense multistatic). Consolidates the SOTA research
loop's 9-tick R6 family into a single 4-axis decision matrix
(dimension x zone-mode x occupants x cog).

Decision matrix highlights:
- 2D vital-signs cogs: chest-centric, N=5, walls 0.8/1.5 m -> 100%
- 3D vital-signs cogs: chest-centric, N=6, NO ceiling      -> 82%
- 2D pose cogs:        body, N=5, walls mixed              -> 97%
- 3D pose cogs:        body, N=7-8, mixed L/M/H            -> 65%+
- Person count:        body, N=4, walls mixed              -> 86%
- Presence only:       body, N=3, walls low                -> 63%
- Maritime cabin:      chest, N=4, low                     -> 80%+
- Wildlife corridor:   linear, N=4, tree-mount             -> 70%+

Seven binding rules extracted from R6 family:
1. Ceiling-only mounting fails (R6.2.1)
2. Vertical link diversity wins in 3D (R6.2.1)
3. Anchor heights match target zone heights (R6.2.4)
4. Chest-centric beats body for vital signs (R6.2.3)
5. Multi-subject union is the right target (R6.2.5)
6. N=5 is the consumer recommendation (R6.2.2 + R6.2.5)
7. Avoid placing target zones on LOS line (R6.1)

CLI productisation:
  wifi-densepose plan-antennas
      --room W H [Z] --target ... --target-mode {body,chest}
      --freq-ghz F --n-anchors N --cog NAME

MCP tool:
  ruview_placement_recommend(room, targets, cog)
    -> {anchors, coverage, rationale}

~360 LOC total for placement-strategy productisation.

Per-cog auto-config (the --cog flag looks up):
- cog-presence: body, 3
- cog-person-count: body, 4
- cog-pose-estimation: body, 5 (2D) / 7 (3D)
- cog-vital-signs / breathing / heart-rate: CHEST, 5/6
- cog-intruder: body, 5
- cog-maritime-watch: chest, 4
- cog-wildlife: linear, 4

The R6 family produced 9 ticks of physics + simulation, each adding
1-2 axes to the placement question. ADR-113 collapses all 9 into a
single decision matrix that a non-physicist installer can use.

Composes:
- R6.2 family (9 ticks) all feed this ADR
- R7 mincut: N >= 4 satisfied for all multi-feature cogs
- R10/R11 wildlife/maritime entries in matrix
- R12 PABS/R12.1: placement coverage = intrusion-detection sensitivity
- R14 V1/V2/V3 all covered
- ADR-029 directly amended

Honest scope:
- Synthetic physics; bench validation pending
- Single room geometry baseline (5x5 + 4x6 m)
- 5 cm pose-tracker noise assumed
- Free-space, no multipath/furniture occlusion
- Greedy + 4-restart search

ADR chain after this tick (loop's 6 new ADRs + 3 existing):
105/106/107/108/109/113 + 100/103/104 = 9 ADRs in the full chain
(privacy + federation + provenance + placement).

Coordination: ticks/tick-31.md, no PROGRESS.md edit.
2026-05-22 06:17:21 -04:00
rUv 27d911ca6d
adr-109: Dilithium PQC signatures — provenance side of post-quantum migration (#733)
Sister-ADR to ADR-108. Where ADR-108 closes the confidentiality side
(Kyber key exchange), ADR-109 closes the integrity side (Dilithium
signatures) of the post-quantum migration.

Replaces Ed25519 in ADR-100 cog signing with Dilithium-3 (NIST FIPS 204,
~AES-192 equivalent, CNSA 2.0 default).

Migration timeline (matches ADR-108):
- Phase 0 (NOW 2026):  Ed25519 only
- Phase 1 (Q4 2026):   Dual-sig (Ed25519 + Dilithium-3), accepts either
- Phase 2 (Q2 2027):   BOTH required (defence in depth)
- Phase 3 (2030+):     Pure Dilithium-3

Why now (backdating argument): An adversary who can break Ed25519 in
2035 with quantum computers can backdate signatures on cog binaries to
install malicious code retroactively. The provenance chain breaks even
for binaries deployed today. Hybrid mode prevents this: forging a 2026
cog signature still requires breaking BOTH Ed25519 AND Dilithium-3.

Manifest size: 64 B (Ed25519) + 3293 B (Dilithium-3) = ~4 kB per cog.
50-cog catalogue overhead ~200 kB. Negligible.

LOC: +270 on top of ADR-100.
Combined chain budget (ADR-105+106+107+108+109): ~1,820 LOC, ~7 weeks.

ADR CHAIN (8 ADRs) complete for both confidentiality and integrity at
quantum-resistant tier:
- ADR-100: cog packaging
- ADR-103: cog-person-count
- ADR-104: MCP + CLI
- ADR-105: within-installation federation
- ADR-106: DP-SGD + primitive isolation
- ADR-107: cross-installation + secure aggregation
- ADR-108: PQC key exchange (Kyber-768)
- ADR-109: PQC signatures (Dilithium-3)  <-- THIS

Future ADRs catalogued:
- ADR-110: PQC hardware acceleration on Cognitum-v0
- ADR-111: Owner key rotation policy
- ADR-112: Cross-signing with external CA
- ADR-113: Multistatic placement strategy (R6 family findings -> ADR-029 amendment)

Composes:
- R14/R15 privacy + biometric requires provenance integrity
- R12 PABS / R12.1: intruder-detection cog must itself be signed
- R10/R11 long-deployment cogs most affected by backdating
- R7 mincut adversarial assumes the model is trustworthy

Honest scope:
- Dilithium ~5 years old; hybrid mitigates uncertainty
- ESP32-S3 verification ~5-10 ms estimated; needs benchmarking
- pqcrypto-dilithium Rust crate dependency
- Owner key management = highest-risk operational change
- Phase 3 Ed25519 retirement needs future decision

Coordination: ticks/tick-30.md, no PROGRESS.md edit.
2026-05-22 06:06:05 -04:00
rUv 40e5a4d6f2
adr-108: Kyber post-quantum key exchange for cross-installation federation (#731)
Closes the quantum-resistance gap explicitly deferred from ADR-107.
Final ADR in the privacy + federation chain.

Replaces DH key exchange in ADR-107's Layer 4 secure aggregation with
Kyber-768 KEM (NIST FIPS 203, CNSA 2.0 default).

Migration timeline:
- Phase 0 (NOW 2026): Classical X25519 (ADR-107 default)
- Phase 1 (2026-Q4 -> 2027): Kyber-768 opt-in via --enable-pqc flag
- Phase 2 (2027-Q2 -> 2028): Hybrid (X25519 + Kyber-768) becomes default
- Phase 3 (2030+): Pure Kyber-768 (classical retired)

Why hybrid for Phase 2 (belt-and-braces):
- Protects against future Kyber breaks (Kyber is ~5 years old)
- Protects against classical breaks (X25519 backup)
- Protects against implementation bugs in either primitive
- Cost: ~3 kB/round/installation extra (negligible)

Why now (record-now-decrypt-later):
Adversaries can record federated updates today and decrypt them in
2035 when quantum capabilities arrive. Without ADR-108, the (epsilon,
delta) guarantees of ADR-106 silently expire when quantum computers
arrive. Proactive migration is cheap insurance.

Why Kyber-768 (not 512 or 1024):
- NIST FIPS 203 (2024); ~AES-192 equivalent
- CNSA 2.0 recommended default
- Used by Cloudflare, Google, AWS in 2024-2026 rollouts
- Public key 1184 B, ciphertext 1088 B, secret 32 B
- 512 lacks CNSA 2.0 sign-off; 1024 doubles bandwidth without benefit

LOC: +220 on top of ADR-107.
Total federation budget ADR-105+106+107+108: ~1,550 LOC.

Threat model: 8 threats, every row has mitigation. Hybrid mode is
the belt-and-braces against both Kyber breaks AND classical breaks.

ADR CHAIN COMPLETE: 7 ADRs in the privacy + federation chain:
ADR-100 (cog packaging) -> ADR-103 (cog example) -> ADR-104 (MCP/CLI)
-> ADR-105 (within-installation federation) -> ADR-106 (DP + isolation)
-> ADR-107 (cross-installation + SA) -> ADR-108 (PQC key exchange).

No remaining unspecified privacy gap at any threat horizon (classical
or quantum).

Future ADRs catalogued:
- ADR-109: PQC signatures (Dilithium replaces Ed25519 in ADR-100)
- ADR-110: PQC hardware acceleration on Cognitum-v0
- ADR-111: PQC for cog-store distribution

Composes:
- R3 / R14 / R15 / R7 / R12 PABS: privacy chain intact through quantum transition
- R10 / R11 (long-deployment): benefit most from forward secrecy as data ages

Honest scope:
- Kyber ~5 years old; hybrid mitigates uncertainty
- 'When do we need this?' uncertain (2030 aggressive / 2050+ conservative)
- ESP32-S3 timing ~10 ms per handshake estimated negligible; needs measurement
- Phase 3 retirement of classical needs future decision

Coordination: ticks/tick-28.md, no PROGRESS.md edit.
2026-05-22 05:45:32 -04:00
rUv 9b5e317f99
adr-107: cross-installation federation with secure aggregation — privacy chain closes (#725)
Closes the cross-installation federation work explicitly deferred from
ADR-105 + ADR-106. Direct extension of both.

Five-layer defence (extends ADR-106's three):
1-3 (ADR-106): Primitive isolation + grad clipping + DP noise
4 NEW: Secure Aggregation (Bonawitz 2016) -- aggregator sees only sum
5 NEW: Per-installation embedding-space rotation key -- cross-install re-ID prevented

Counter-intuitive privacy win: cross-installation amplification IMPROVES
privacy. With N=10 installations each at sigma_local=1.0:
- Per-installation epsilon (50 rounds): 2.5
- Cross-installation effective sigma = sqrt(N) * sigma_local = 3.16
- Cross-installation epsilon (50 rounds): ~1.5  <-- STRONGER

Cross-installation federation actually improves privacy through the
amplification effect, as long as the crypto protocol is implemented
correctly.

Bandwidth: ~2 MB/install/round, monthly ~70-200 MB/install
(within+cross). <0.1% of typical home broadband.

Implementation budget:
- ADR-105 baseline: 500 LOC
- ADR-106 layers: +300 LOC
- ADR-107 SA layer: +530 LOC
- TOTAL ruview-fed: ~1,330 LOC, ~6 weeks

The privacy chain closes:
1. R6/R6.1 physics forward model
2. R3 embedding-space re-ID
3. R14 ethical opt-in / on-device / override
4. R15 biometric primitive catalogue
5. ADR-105 within-installation federation
6. ADR-106 DP-SGD + primitive isolation
7. ADR-107 cross-installation + secure aggregation

Every layer has a formal guarantee, implementation path, and honest
scope. No remaining unspecified privacy gap. Cross-installation
training can ship without violating any constraint surfaced by the
research loop.

Threat model: 8 threats, every row has a mitigation layer.
- Compromised aggregator views deltas -> Layer 4 SA
- Cross-installation re-ID -> Layer 5 rotation
- Sybil -> Layer 4 dropout + Krum + N >= 5
- Quantum-resistant: out-of-scope ADR-108 (Kyber substitution)

Honest scope:
- Cross-org PKI = operational, not architectural
- Krum+SA composition proof is non-trivial; reference implementations
  needed before production
- sqrt(N) amplification assumes installation independence
- Drop-out reconstruction has known attack surfaces (Bonawitz §4.3)
- Per-cog suitability varies (cog-wildlife yes, cog-maritime-watch no)

Composes:
- R3+R15 enforcement now technical, not just policy
- R7 mincut extends to cross-installation adversarial detection
- R12 PABS works at any installation in local rotated embedding space
- R10/R11 cogs benefit asymmetrically

Coordination: ticks/tick-22.md, no PROGRESS.md edit.
2026-05-22 04:27:48 -04:00
rUv 28d97e8f6a
adr-106: differential privacy + biometric primitive isolation for federation (#718)
Direct extension of ADR-105. Closes both items deferred from ADR-105:
(1) member-inference defence, (2) biometric primitive isolation
enforcement.

Three-layer defence:
1. PRIMITIVE ISOLATION (R15 binding) -- API-level tagging of on-device-
   only tensors. Compile-time error when  tagged tensors are passed
   to submit_delta().
2. GRADIENT CLIPPING (Abadi 2016) -- per-sample L2 norm <= C (default
   C=1.0) before delta computation.
3. GAUSSIAN NOISE (DP-SGD) -- N(0, sigma^2*C^2*I) added to aggregated
   LoRA delta before transmission.

Privacy budget via Moments Accountant (delta=1e-5):
- Conservative (medical-grade): sigma=1.5, 50 rounds, epsilon=2.0
- Standard (typical RuView):    sigma=1.0, 100 rounds, epsilon=5.0
- Lenient:                      sigma=0.5, 100 rounds, epsilon=8.0

On-device-only primitive list (R15-binding):
- Raw CSI window
- Gait stride frequency
- Breathing rate (per-subject)
- HRV rate signature
- RCS frequency response curve
- Limb timing vector
- Per-subject embedding centroid

Implementation budget: +300 LOC on top of ADR-105's 500 LOC = total
~800 LOC ruview-fed crate. 3-week effort estimate.

Composes:
- R3: Layer 1 blocks per-subject embedding centroid transmission
- R7: mincut compatible with DP-noised deltas (operates on noised graph)
- R12/R13 negative results: informed the noise-vs-structure-detection
  design choice (treat adversarial deltas as outliers from noisy
  distribution, not structural-detection problem)
- R14: privacy framework now has formal (epsilon, delta) backing
- R15: requirements basis = on-device-only primitive list made executable
- ADR-105: DP-SGD slots into step 4 of federation protocol

Closes the privacy story: R3 + R14 + R15 + ADR-105 + ADR-106 = complete
chain from physics (R6) -> embeddings (R3) -> personalised features (R14)
-> trained how (ADR-105) -> defended how (R7) -> privacy-bounded how
(ADR-106).

Honest scope:
- sigma values are recommendations, not measurements (per-cog tuning needed)
- (epsilon, delta)-DP is worst-case bound; auxiliary info changes practical leakage
- Moments Accountant is conservative
- Subject-level DP not formalised (household of 4 = K=4 subjects)
- Side-channel timing leaks out of scope (future ADR)

Explicitly deferred:
- ADR-107: cross-installation federation w/ secure aggregation

Coordination: ticks/tick-15.md, no PROGRESS.md edit.
2026-05-22 02:48:16 -04:00
rUv 09fe73eb87
research(R4) + adr-105: federated CSI training with MERIDIAN+Krum+mincut (#716)
Federated learning is the unique design that satisfies the three
constraints from this loop's earlier work:
- R14 (data stays on-device)
- R3  (no cross-installation linkage)
- R7  (multi-node adversarial defence)

ADR-105 proposes MERIDIAN-FedAvg with Byzantine-robust (Krum)
aggregation and R7-style Stoer-Wagner mincut on inter-node update
similarity. Per-round bandwidth at typical 4-seed installation:
~12 MB; weekly cadence x monthly = 50-180 MB/month (0.06% of home
broadband cap).

Composes with every prior thread:
- R3 MERIDIAN centroid subtraction is mandatory pre-aggregation
- R7 mincut extended from multi-link CSI to multi-node updates
- R12/R13 negative results informed the byzantine + SNR-threshold choices
- R14 privacy framework baseline is now operational
- ADR-024/027/029/100/103/104 all bridged in the ADR

Implementation plan: ~500 LOC for ruview-fed crate. Krum aggregator
(80 LOC), LoRA+int8 delta codec (120 LOC, reuse ruvllm-microlora),
MERIDIAN centroid hook (50 LOC, extend AgentDB), inter-seed mincut
(100 LOC, reuse ruvector-mincut), CLI surface (80 LOC).

Explicitly deferred:
- Cross-installation federation (legal + DP work needed, future ADR)
- Member inference defence (ADR-106 with formal DP-SGD)
- Per-cog training-loop details (each cog implements local_train)
- Compute scheduling (cognitum fleet manager territory)

Tick chose the 'one ADR' unit from the cron prompt rather than another
numpy demo -- federation is fundamentally a protocol-design problem,
not a numerical-experiment problem.

Coordination: ticks/tick-13.md, no PROGRESS.md edit.
2026-05-22 02:24:42 -04:00
rUv 3f462a254d
feat(tools): scaffold ruview MCP server + CLI + ADR-104 (#705)
Adds two new npm packages that expose RuView's WiFi-DensePose
sensing capabilities outside the Cognitum appliance ecosystem:

- tools/ruview-mcp/ (@ruv/ruview-mcp) — MCP server with 6 tools:
  ruview_csi_latest, ruview_pose_infer, ruview_count_infer,
  ruview_registry_list, ruview_train_count, ruview_job_status.
  Uses @modelcontextprotocol/sdk with stdio transport.
  6/6 smoke tests pass. TypeScript strict mode, Node 20.

- tools/ruview-cli/ (@ruv/ruview-cli) — Yargs CLI with matching
  subcommands: csi tail, pose infer, count infer, cogs list,
  train count, job status. Same fail-open pattern as the cog
  binaries (WARN to stderr, exit 0 on unavailable sensing-server).

- docs/adr/ADR-104-ruview-mcp-cli-distribution.md — design rationale,
  6-row threat table, packaging plan, acceptance gates, failure modes.

- docs/research/sota-2026-05-22/HORIZON.md — 12-hour horizon plan
  with 7 milestones tracked (M1 complete in this commit).

Both packages are private:true pending the user's publish decision.
Inference is via subprocess to the signed cog binaries (ADR-100/101/103)
— no JS/WASM ML engine bundled.
2026-05-21 23:33:18 -04:00
rUv 962e0f4a34
docs(adr): ADR-103 — learned multi-person counter (SOTA path) (#693)
Motivated by #499 (multi-node double-skeletons) which PR #491 stopped
the bleeding on but didn't take to the WiFi-CSI literature's state of
the art. Designs a learned counter that replaces today's slot
heuristic + dedup_factor knob, reusing the primitives we've already
shipped this week:

  * Candle / RTX 5080 training pipeline (proven yesterday, 2.1 s for
    400 epochs on pose_v1.safetensors)
  * HF presence encoder as initialization (architectures compatible,
    unlike the pose head case)
  * ruvector-mincut (Stoer-Wagner) for multi-node fusion upper-bound
  * Cog packaging spec (ADR-100) + edge module registry (ADR-102)
  * Paired-data pipeline (PR #641 streaming-safe align-ground-truth.js)
    — `n_persons` labels come for free; no new data collection
    campaign required to bootstrap.

Architecture:
  per-node CSI [56×20] -> frozen HF encoder -> 128-dim embedding
                                          \
                                           > count head (softmax {0..7})
                                           > confidence head (sigmoid)
  N nodes' distributions -> confidence-weighted log-sum
                         -> Stoer-Wagner min-cut upper-bound clip
                         -> { count, confidence,
                              count_p95_low, count_p95_high,
                              per_node_breakdown }

Compares the proposal explicitly against WiCount / DeepCount /
CrossCount / HeadCount published numbers and is honest about the
hardware gap (their 3x3 MIMO research NICs vs our 1x1 SISO ESP32-S3).

v0.1.0 acceptance gates target >=80% within-+/-1 same-room and
>=60% cross-room — modest on purpose; bounded by the same paired-
data scarcity #645 documents for pose. The framework is the
deliverable; the accuracy follows the data.

Includes:
  * Architecture diagram in ascii
  * Comparison table vs published WiFi-CSI counting SOTA
  * Per-failure-mode mapping from #499 symptoms to how the
    learned counter addresses each
  * v0.1.0 + v0.2.0 acceptance gates with measurable thresholds
  * Repo layout for the new `v2/crates/cog-person-count/` crate
  * Five-step migration plan from this ADR -> first GCS release

Status: Proposed. Implementation follows in the same incremental
pattern ADR-101 used: scaffold-cog PR -> train+publish PR ->
server-wiring PR.
2026-05-21 18:28:18 -04:00
rUv 67fec45e61
feat(edge-registry): ADR-102 — surface Cognitum cog catalog via /api/v1/edge/registry (#648)
* feat(edge-registry): ADR-102 — surface Cognitum cog catalog via /api/v1/edge/registry

Adds a new sensing-server endpoint that fetches and caches the canonical
Cognitum app registry at
https://storage.googleapis.com/cognitum-apps/app-registry.json (105 cogs
across 11 categories as of v2.1.0). RuView previously had no live
awareness of the catalog — the README's capability table was hand-
curated and went stale as Cognitum shipped new cogs (the registry was
last updated 6 days ago).

ADR:
* docs/adr/ADR-102-edge-module-registry.md — full design, response
  shape, configuration flags, failure modes, and a 12-row security
  review covering SSRF, response inflation, ?refresh abuse, stale-serve
  semantics, TLS, cache poisoning, JSON-panic resistance, etc.

Code:
* v2/.../edge_registry.rs — EdgeRegistry struct + UreqFetcher +
  MockFetcher trait + 7 unit tests. RwLock<Option<CachedEntry>> with
  stale-on-error fallback. MAX_PAYLOAD_BYTES=8 MiB, 10s wire timeout.
* v2/.../main.rs — constructs Option<Arc<EdgeRegistry>> at startup,
  registers GET /api/v1/edge/registry handler, wires Extension layer.
  Handler runs the blocking ureq fetch via tokio::task::spawn_blocking
  so the async runtime stays free.
* v2/.../cli.rs / main.rs Args — three new flags (per user request to
  "allow the registry to be disabled or changed"):
    --edge-registry-url <URL>       (env RUVIEW_EDGE_REGISTRY_URL)
    --edge-registry-ttl-secs <N>    (env RUVIEW_EDGE_REGISTRY_TTL_SECS)
    --no-edge-registry              (env RUVIEW_NO_EDGE_REGISTRY)
  When --no-edge-registry is set or the URL is empty, the endpoint
  returns 404.

Cargo.toml: adds ureq (rustls), sha2, thiserror as direct deps.

README:
* New collapsed "🧩 Edge Module Catalog" section with the full 105-cog
  table generated from the registry, grouped by category with practical
  one-line descriptions (e.g. "Spots irregular heartbeats and abnormal
  heart rhythms", "Detects walking problems and scores fall risk").
  Links to https://seed.cognitum.one/store and the local appliance
  /cogs page. Sits between the HF model section and How It Works.

Tests (7/7 pass):
  first_call_hits_upstream_and_caches
  ttl_expiry_triggers_refetch
  force_refresh_bypasses_fresh_cache
  stale_serve_on_upstream_failure_after_cached_success
  no_cache_no_upstream_returns_error
  upstream_invalid_json_is_treated_as_error
  upstream_sha256_is_deterministic

Security highlights (full review in ADR-102 §"Security review"):
- The registry is metadata-only; per-cog binary signatures (ADR-100)
  remain the trust root for installs. A compromised registry can
  mislead a human reader but cannot ship malicious binaries.
- 8 MiB cap + 10s timeout + Option<Arc<...>> via Extension layer means
  the endpoint can't be used to exhaust memory or pin tokio threads.
- Stale-on-error responses carry an explicit `stale: true` field so
  upstream outages are visible to consumers rather than silently
  masked.
- Endpoint sits behind the existing RUVIEW_API_TOKEN bearer gate when
  set, otherwise unauthenticated (registry contents are public anyway).

* chore: refresh Cargo.lock for ureq/sha2/thiserror deps added by ADR-102
2026-05-19 18:08:43 -04:00
rUv 4b1a835107
docs: repoint #640 references to #645 (original deleted, replaced) (#646)
Issue #640 (PCK gap follow-up) was deleted upstream after the cog v0.0.1
PRs landed today. Re-opened as #645 with the same context plus the
new measured v0.0.1 numbers (PCK@20 3.0%, PCK@50 18.5%, MPJPE 0.093).
This patch updates the three files in main that still pointed at the
dead #640 to point at #645 instead — ADR-101, the cog README, and the
benchmark log.
2026-05-19 17:18:05 -04:00
rUv 9c3c8b98bc
docs(adr): ADR-100 + ADR-101 — record v0.0.1 shipping status (#644)
Updates both ADRs to reflect that the first cog (`cog-pose-estimation@0.0.1`)
landed today via PRs #642 + #643.

ADR-100 (Cog Packaging Specification):
* Status line: "first conforming cog shipped 2026-05-19".
* Migration step 2 marked complete with PR references and the GCS
  paths the binaries live at.

ADR-101 (Pose Estimation Cog):
* Status line: "v0.0.1 shipped 2026-05-19".
* New "v0.0.1 shipping status" section that walks through every
  ADR-100 acceptance gate with concrete pass/fail evidence (binary
  sizes, sha256 round-trip, signature, manifest path, live install
  on cognitum-v0, runtime contract, real-weights load assertion,
  ONNX parity).
* Measured-metrics table: training time (2.1 s/400 epochs on RTX 5080),
  PCK@20/PCK@50/MPJPE, cold-start latency for Windows/ruvultra/Pi 5.
* Carries forward the two open follow-ups: Hailo HEF (SDK-gated) and
  PCK@20 >= 35% (data-bound, #640).
* "See also" link to docs/benchmarks/pose-estimation-cog.md.

Docs-only; no code changes.
2026-05-19 17:13:31 -04:00
rUv 3314c8db8d
feat(cog-pose-estimation): scaffold first Cog from this repo (ADR-100 + ADR-101) (#642)
* feat(cog-pose-estimation): scaffold first Cog from this repo (ADR-100 + ADR-101)

Adds the foundation for the pose-estimation Cog that ships from this
repo into Cognitum V0 appliances. Companion ADR-225 + crate land in
cognitum-one/v0-appliance.

ADRs:
* ADR-100 formalises the Cognitum Cog packaging spec — on-device
  layout under /var/lib/cognitum/apps/<id>/, manifest.json schema
  (incl. new binary_sha256 + binary_signature fields), GCS hosting
  convention, repo source layout, build pipeline, and the four-verb
  runtime contract (version | manifest | health | run). Documents the
  convention I reverse-engineered from inspecting installed cogs on a
  live cognitum-v0 appliance — `anomaly-detect`, `presence`,
  `seizure-detect`, etc.
* ADR-101 designs the pose-estimation Cog itself: where it sits in
  the wifi-densepose pipeline (encoder init from
  ruvnet/wifi-densepose-pretrained, 17-keypoint regression head),
  what gets shipped per target arch (arm / x86_64 / hailo8 /
  hailo10), acceptance gates (PCK@20 explicitly deferred to #640 —
  this ADR ships the vehicle, not the accuracy).

Crate v2/crates/cog-pose-estimation/:
* Cargo.toml + workspace member declaration with a hailo feature gate
  so the binary builds without the Hailo SDK in CI.
* main.rs implements the four-verb CLI exactly per ADR-100.
* config.rs / manifest.rs / publisher.rs / inference.rs / runtime.rs —
  small modules, each <100 lines.
* publisher.rs emits ADR-100 structured JSON events.
* inference.rs is a stub that produces a centred-skeleton baseline
  with confidence=0 (honest: no trained weights wired in yet).
* runtime.rs subscribes to /api/v1/sensing/latest, slides a
  56*20 window, runs the engine, emits pose.frame events.
* cog/manifest.template.json + cog/config.schema.json define the
  release artifact + runtime config schemas.
* cog/Makefile holds build / sign / upload targets.
* tests/smoke.rs covers manifest roundtrip + engine I/O surface.

Verified locally:
* cargo check -p cog-pose-estimation: clean.
* cargo test  -p cog-pose-estimation: 4/4 pass.
* ./target/release/cog-pose-estimation {version,manifest,health}:
  all emit the right contract output.

This commit contains scaffolding only; the actual trained weights and
Hailo HEF cross-compile come in follow-ups tracked in #640 and the
companion v0-appliance branch.

* feat(cog-pose-estimation): first measured run — Candle CUDA on RTX 5080

Trained pose_v1 on ruvultra (RTX 5080) via Candle 0.9 + cuda feature
against the same 1,077-sample paired session that produced 0%/0% PCK
in #640 with the pure-JS SPSA trainer. First real numbers:

  PCK@20 = 3.0%   (up from 0.0%)
  PCK@50 = 18.5%  (up from 0.0%)
  MPJPE  = 0.093  (down from 0.66, ~7x improvement)

400 epochs in 2.1 s wall time, full-batch, ~5 ms/epoch. Loss curve
0.181 -> 0.014 over the run, eval 0.010. Per-joint reveals the model
leans on right-side proximal joints (r_hip 77% PCK@50, r_knee 35%,
l_elbow 26%) — consistent with the camera framing in the source
recording. Distal joints (wrists, ankles) and face joints are still
near-random, consistent with the 56-subcarrier / 20-frame input not
carrying fine-grained spatial info at 1077 samples.

This commit:

* Adds v2/crates/cog-pose-estimation/cog/artifacts/{pose_v1.safetensors,
  train_results.json} so the cog dir now contains a real reference
  artifact, not just scaffold.
* Updates cog/README.md "Status" block with the measured numbers,
  per-joint table, and an honest reading of where the model
  succeeds vs where the data is the bottleneck.
* Adds docs/benchmarks/pose-estimation-cog.md as the canonical
  benchmark log — append-only, one section per published run.
* Appends a "First measured run" section to ADR-101 referencing
  the new benchmark file.

Still pending in the follow-up:
* Wire pose_v1.safetensors into src/inference.rs (replace stub).
* ONNX export (Candle lacks a writer — needs external conversion).
* Hailo HEF cross-compile + cluster deploy.

The data-bound gap to PCK@20 >= 35% is tracked in #640.

* feat(cog-pose-estimation): wire real weights — cog is no longer a stub

Replaces the centred-skeleton stub in src/inference.rs with a real
Candle-based loader that reads cog/artifacts/pose_v1.safetensors and
runs the trained Conv1d encoder + MLP pose head on every incoming CSI
window.

What changes:

* src/inference.rs: PoseNet mirrors the training script's architecture
  exactly — Conv1d(56->64, k=3 d=1), Conv1d(64->128, k=3 d=2),
  Conv1d(128->128, k=3 d=4), mean over time, Linear(128->256)+ReLU,
  Linear(256->34)+sigmoid -> reshape [17, 2]. The InferenceEngine
  searches a sensible candidate list for the weights file
  (/var/lib/cognitum/apps/pose-estimation/, ./pose_v1.safetensors,
  ./cog/artifacts/, repo-root, v2/-relative) and falls back to the
  stub when none are present so the cog still satisfies ADR-100.
* Cargo.toml: adds candle-core 0.9 + candle-nn 0.9 (no-default-features,
  CPU build by default) + safetensors 0.4. New `cuda` feature opt-in
  for GPU inference on hosts that have it. Drops the unused
  wifi-densepose-train path dep from the default build path.
* src/main.rs + src/publisher.rs: health.ok event now carries
  `backend` (candle-cuda | candle-cpu | stub) and the synthetic
  output confidence, so operators can tell at a glance whether the
  cog loaded its weights or fell back to the stub.
* tests/smoke.rs: adds `real_weights_load_when_available` which
  asserts the loaded engine reports backend=candle-* and emits
  non-zero confidence — exactly the signal that proves we're not
  silently degrading to the stub.

Verified locally:

* `cargo check -p cog-pose-estimation --no-default-features` — clean
* `cargo test  -p cog-pose-estimation --no-default-features` — 5/5 pass
* `./target/release/cog-pose-estimation health` emits:
  {"event":"health.ok","fields":{"backend":"candle-cpu","cog":"pose-estimation","synthetic_output_confidence":0.185}}
  — 0.185 is the published PCK@50 from cog/artifacts/train_results.json,
  emitted by the real Candle inference path (would be 0.0 if it had
  fallen back to the stub).

The cog now runs the trained pose_v1 model end-to-end. Accuracy is
still bounded by the underlying 1077-sample training data (PCK@20
3.0%, PCK@50 18.5% per docs/benchmarks/pose-estimation-cog.md) — that
gap is data-bound and tracked in #640. ONNX export + Hailo HEF
cross-compile remain follow-ups.

* docs(benchmarks): measure cog-pose-estimation cold-start latency

100 sequential `cog-pose-estimation health` invocations average 76.2 ms
each on a Windows x86_64 host using the `candle-cpu` backend. Each
invocation re-loads pose_v1.safetensors and runs one synthetic forward
pass, so this is the worst-case cold-start path. Long-running `run`
inference will be sub-millisecond per frame once the model is loaded.

Updates the benchmarks doc accordingly.

* feat(cog-pose-estimation): ONNX export — pose_v1.onnx + scripts/export-onnx.py

Adds the canonical ONNX artifact that unblocks downstream Hailo HEF
cross-compile + ONNX Runtime benchmarks. Generated on ruvultra (torch
2.12.0 + CUDA), 12,059 bytes, opset 18, dynamic batch axis.

* scripts/export-onnx.py: mirrors the Candle inference architecture in
  PyTorch (Conv1d 56->64, 64->128, 128->128 + Linear 128->256->34), pure-
  python safetensors loader (no extra pip dep), exports via
  torch.onnx.export, then verifies via onnx.checker.check_model and
  numerical parity against the torch reference.
* Verified parity vs torch: max |torch - onnx| = 8.94e-8 (1e-5
  threshold). Effectively bit-perfect.
* v2/crates/cog-pose-estimation/cog/artifacts/pose_v1.onnx — the
  artifact itself, 12 KB.
* docs/benchmarks/pose-estimation-cog.md — adds an ONNX export
  section with the verification numbers.

Next: Hailo HEF cross-compile (still gated on Hailo SDK on a
self-hosted runner) and ONNX Runtime latency benchmarks on each
target arch.

* feat(cog-pose-estimation): release v0.0.1 — signed aarch64 binary on GCS

End-to-end deploy: cross-compiled to aarch64-unknown-linux-gnu on
ruvultra, ran via qemu-aarch64-static, then smoke-tested on a real
cognitum-v0 Pi 5. Signed with COGNITUM_OWNER_SIGNING_KEY (Ed25519)
and uploaded to gs://cognitum-apps/cogs/arm/.

Real-hardware results on cognitum-v0 (Pi 5):
  health: backend=candle-cpu, confidence=0.185, real weights loaded
  30x sequential `health`: 0.251 s total -> 8.4 ms / invocation (cold)

GCS release artifacts (publicly downloadable):
  binary:  3,741,976 bytes
    sha256 1e1a7d3dd01ca05d5bfc5dbb142a5941b7866ed9f3224a21edc04d3f09a99bf5
  weights:   507,032 bytes
    sha256 eb249b9a6b2e10130437a10976ed0230b0d085f86a0553d7226e1ae6eae4b9e5
  signature (Ed25519, b64): LUN7xqLPYD3MFzm5dKB5MnYU0LvoRtek5ci5KiKPHBg+Xo6xuazwokn2Dw2JPMaLYJzmWn/SpT4djuR7hYvVDw==

Adds:
* v2/crates/cog-pose-estimation/cog/artifacts/manifest.json — the
  release-pipeline-produced manifest with all fields filled in per
  ADR-100, including arch, target_triple, signature, and a
  build_metadata block carrying the validation PCK numbers.
* docs/benchmarks/pose-estimation-cog.md — new sections covering
  the real Pi 5 smoke (8.4 ms cold-start) and the signed GCS
  release artifacts.

Verified by downloading the binary anonymously from GCS and
re-computing the sha256 — matches the locally-computed sha exactly.
Signature decoded to the expected 64-byte Ed25519 length.

Closes the GCS-upload acceptance criterion from ADR-100; the only
pending work is Hailo HEF cross-compile (still SDK-gated) and an
x86_64 release alongside this arm release.

* docs(benchmarks): record live cognitum-v0 install + 5-sec smoke run

Adds the "Live appliance install" section documenting what happened
when the signed v0.0.1 binary + weights were installed under
/var/lib/cognitum/apps/pose-estimation/ on cognitum-v0 (the V0
cluster leader).

* Layout matches the existing anomaly-detect / presence / seizure-
  detect cogs exactly — the Cogs dashboard at
  http://cognitum-v0:9000/cogs auto-discovers entries.
* `cog-pose-estimation run` ran for 5 seconds in the background and
  cleanly emitted run.started + structured WARN events for the
  missing local sensing-server on :3000 (cognitum-v0's actual CSI
  source is ruview-vitals-worker on :50054, not :3000). No crashes,
  no NaN, no leaks.
* Wiring `sensing_url` to the appliance-native source is a separate
  Day-2 integration task.
2026-05-19 17:03:09 -04:00
rUv 9d4f7820b2
docs(adr): ADR-098 — evaluate midstream for RuView's CSI/WS/mesh pipeline (Rejected) (#553)
`vendor/midstream` is a git submodule of RuView but no `v2/crates/*` depends
on a `midstreamer-*` crate and no Rust source uses one — i.e. it is vendored
but not consumed, the same state `vendor/rvcsi` was in before ADR-097.

ADR-098 evaluates whether to change that. The candidate seams (from the
prompt) were:

  1. Streaming / pub-sub for the WS fan-out (today: `tokio::sync::broadcast`
     at `wifi-densepose-sensing-server/src/main.rs:4769`).
  2. CSI → DSP → event pipeline (today: rvcsi-events::EventPipeline, just
     adopted by ADR-097).
  3. Multi-source merging / TDM for the ESP32 mesh (ADR-029, ADR-073).
  4. Backpressure / flow control between the UDP receiver and downstream
     consumers (firmware `stream_sender` ENOMEM; host-side bounded
     broadcast channel).

Reading all six midstream workspace crates end-to-end
(`vendor/midstream/crates/{temporal-compare,nanosecond-scheduler,
temporal-attractor-studio,temporal-neural-solver,strange-loop,
quic-multistream}/src/*.rs` — ~3,455 LOC) shows midstream's identity
unambiguously: `Cargo.toml:16` calls itself "Real-time LLM streaming with
inflight analysis", the README frames it as analyzing *LLM token streams*
in real time, and zero hits across the workspace for `csi|wifi|sensing|
sensor`. midstream's abstractions are LLM-token / dashboard-telemetry
shaped; RuView's pipeline is RF-frame / event-detector shaped.

Decisions:

  D1 — WS fan-out: keep `tokio::sync::broadcast::channel::<String>(256)`.
       midstream offers no equivalent in-process broadcast primitive.
  D2 — CSI pipeline: keep `rvcsi-events::EventPipeline` (deterministic,
       single-frame-at-a-time, replayable per ADR-095 D9). midstream's
       attractor / LTL crates operate on multi-dimensional trajectories,
       not validated single CSI frames.
  D3 — TDM / aggregator: keep `wifi-densepose-hardware::aggregator` +
       firmware-side TDM. midstream has no UDP merger and no cross-device
       wall-clock scheduler.
  D4 — Backpressure: the firmware ENOMEM rate-limit and the bounded host
       `broadcast` channel are correct at each end; midstream's QUIC
       primitives don't help the actual UDP+WS topology.
  D5 — Carve-out: `midstreamer-temporal-compare` (DTW / LCS / Levenshtein)
       is a plausible future-evaluation option if a *second* DTW use case
       appears in RuView. RuvSense already has one (`gesture.rs`).
  D6 — Carve-out: `midstreamer-scheduler` (deadline-aware, EDF / LLF /
       RM) is a plausible future option if the cluster-Pi aggregator ever
       takes over real-time scheduling. Today that lives in firmware.
  D7 — Submodule: keep `vendor/midstream` pinned at `30fe5eb` as reference
       material; do not advance the pin per-release (unlike vendor/rvcsi
       under ADR-097 D7) because there is no in-build consumer.
  D8 — Docs: cross-reference, don't import. ADR-098 added to
       `docs/adr/README.md`.

Status: Rejected (with named re-evaluation triggers in §6 — second DTW use
case, host-side real-time scheduler, midstream gains a CSI adapter, or a
QUIC-to-external-client requirement that WS can't service).
2026-05-17 17:49:21 -04:00
ruv ca97527646 feat(introspection): I6 — regime-changed signal + per-frame analyze + honest ADR-099 D8 amendment
Three threads in this commit:

1) Per-frame attractor analysis (default analyze_every_n: 8 → 1).
   The I5 benchmark put per-frame update at 0.012 ms p99 — 83× under D4's
   1 ms budget. The cost case for the every-8th-frame default doesn't hold;
   per-frame analysis is what makes regime_changed a viable early-detection
   trigger.

2) New `regime_changed: bool` field in IntrospectionSnapshot — flips on any
   frame whose attractor regime classification differs from the previous
   frame's. Pairs with top_k_similarity (full-shape match) to give
   downstream consumers two latencies with different robustness profiles.

3) Honest amendment of ADR-099 D8 to reflect empirical reality:
   - L1 stand-in achieves 3.20× ratio (5-frame shape match vs 16-frame
     event-path floor); the 10× aspirational bar is architecturally
     unreachable at 1-D scalar feature resolution.
   - regime_changed didn't fire in the 10-frame motion window — the
     200-frame noise trajectory dominates the Lyapunov classification, and
     short perturbations don't shift the regime fast enough on a scalar
     feature.
   - Path to 10×: ADR-208 Phase 2 (Hailo NPU vec128 embeddings) — multi-dim
     partial matches discriminate from noise in 1-2 frames, not 5.
   - Side finding: midstream temporal-compare::DTW uses *discrete equality*
     cost (designed for LLM tokens), not numeric distance — swapping it in
     for f64 amplitude scoring would be strictly worse than the L1 stand-in.
     A numeric DTW is a separate concern (hand-roll or new crate).
   - Revised D8: ship behind --introspection (off by default) until multi-
     dim features land. Per-frame update budget IS met (0.041 ms p99 in this
     bench, ~24× under the 1 ms bar) — the feature is cheap enough to
     carry dark today.

cargo test -p wifi-densepose-sensing-server --no-default-features:
  introspection (lib): 8 passed, 0 failed
  introspection_latency (test): 5 passed, 0 failed (incl. new
                                 regime_change_path_latency)
clippy: clean on the introspection surface (pre-existing approx_constant
        lints in pose.rs / main.rs unchanged).

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-13 23:29:37 -04:00
ruv 900b877c64 docs(adr): ADR-099 — adopt midstream as RuView's real-time introspection + low-latency tap (Proposed)
ADR-098 rejected midstream as a *replacement* for RuView's existing seams.
ADR-099 is the other half: midstream's `temporal-compare` (DTW) and
`temporal-attractor-studio` (Lyapunov + regime classification) crates as a
*parallel* per-frame introspection tap, alongside the existing window-aggregated
event pipeline.

The 8 decisions:

  D1 — Only midstreamer-temporal-compare 0.2 + midstreamer-attractor 0.2;
       scheduler / neural-solver / strange-loop are out of scope of this ADR.
  D2 — Tap point: post-validate, parallel to WindowBuffer::push in csi.rs.
       The existing /ws/sensing path is unchanged.
  D3 — New /ws/introspection topic + /api/v1/introspection/snapshot REST endpoint
       carrying IntrospectionSnapshot { regime, lyapunov_exponent,
       attractor_dim, top_k_similarity }.
  D4 — Per-frame updates only, never window-blocked. Soonest-event latency on
       the "shape recognized" path collapses from ~533 ms (16-frame @ 30 Hz
       window) to ~33 ms (one frame), a ~16× win.
  D5 — temporal-neural-solver (LTL) is out of scope (separate MAT audit ADR).
  D6 — ESP32 firmware unchanged; deployment is host-side only.
  D7 — Signature library is JSON, on-disk, customer-owned; three reference
       signatures ship as developer fixtures.
  D8 — Promotion bar is empirical: ≥10× p99 latency reduction vs. the existing
       /ws/sensing event path, or the feature stays behind a CLI flag.

Indexed in docs/adr/README.md. Phased adoption (P0 spike + benchmark → P1 first
real signature library → P2 dashboard widget → P3 capture workflow → P4 optional
adaptive_classifier hook). Implementation lands as ~150–250 lines + one
integration test in v2/crates/wifi-densepose-sensing-server in follow-up PRs.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-13 22:42:05 -04:00
ruv 7a407556ba docs(adr): ADR-097 — adopt rvCSI as RuView's primary CSI runtime (Proposed)
rvCSI was extracted to its own repo (PR #542→#544): 9 crates on crates.io @
0.3.1, `@ruv/rvcsi` on npm, vendored at `vendor/rvcsi`. RuView currently
*vendors but does not consume* it — zero `rvcsi-*` deps in `v2/`, zero
`use rvcsi_…` imports, zero `@ruv/rvcsi` JS imports. ADR-097 decides:

  D1 — Depend on the published crates from crates.io, not the submodule path.
  D2 — Pilot in `wifi-densepose-sensing-server` (smallest, best-bounded
       touchpoint: UDP receiver + handlers + WS fan-out).
  D3 — `wifi-densepose-signal` is *layered on top of* rvCSI, not replaced.
       The SOTA / RuvSense modules go beyond rvCSI's scope and stay in
       RuView; they consume `rvcsi_core::CsiFrame`. Overlapping basic DSP
       primitives delegate to `rvcsi-dsp` or become thin shims.
  D4 — `wifi-densepose-hardware` stops carrying ESP32 wire-format parsing;
       the parser moves to a new `rvcsi-adapter-esp32` crate (ADR-095 §1.2
       / D15 follow-up, owned in the rvCSI repo).
  D5 — `wifi-densepose-ruvector` (training pipeline) and `rvcsi-ruvector`
       (runtime RF memory) stay separate for now; a follow-up unifies them
       once the production RuVector binding lands.
  D6 — `rvcsi_core::CsiFrame` is the boundary type at the runtime edge;
       one explicit `From`/`Into` conversion point at that edge.
  D7 — Track via `rvcsi-* = "0.3"` SemVer ranges + bump the `vendor/rvcsi`
       submodule pin per RuView release for reproducible offline builds.
  D8 — Once every consumer depends on crates.io, decide (separately)
       whether to drop the submodule.

Adoption is phased (P1 pilot → P2 signal shim → P3 ESP32 adapter →
P4 clean-up → P5 submodule review); each phase is one PR with tests.

Indexed in docs/adr/README.md.

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-05-13 09:23:25 -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