Back to Ruview

rvCSI — Edge RF Sensing Runtime Domain Model

docs/ddd/rvcsi-domain-model.md

1.99.0-pip19.7 KB
Original Source

rvCSI — Edge RF Sensing Runtime Domain Model

Domain-Driven Design Specification

Companion documents: rvCSI Platform PRD · ADR-095 — rvCSI Edge RF Sensing Platform

Domain

Camera-free RF spatial sensing from WiFi Channel State Information (CSI).

Core domain

RF field interpretation. rvCSI converts noisy radio channel measurements into validated events and temporal embeddings that represent changes in physical space. CSI is treated as a temporal delta stream against learned baselines — not as exact vision.

Supporting subdomains

Hardware adapter management · packet parsing · signal processing · calibration · event extraction · temporal memory · agent integration · replay and audit.

Generic subdomains

Logging · configuration · CLI parsing · WebSocket streaming · package publishing · dashboard visualization.


Ubiquitous Language

TermDefinition
CSIChannel State Information — per-subcarrier complex channel response measured by a WiFi receiver
SourceA physical or replayed producer of CSI frames (a NIC, an ESP32 node, a PCAP file, a recorded capture)
AdapterA software module that knows how to receive and decode source-specific CSI and normalize it into a CsiFrame
FrameOne CSI observation at a timestamp — the unit of ingestion
WindowA bounded sequence of frames from one source/session, used for analysis
BaselineThe learned normal RF-field state for a space
DeltaThe measured difference of the current field from baseline
EventA semantic interpretation of one or more windows (presence started, motion detected, anomaly, …)
Quality scoreConfidence, in [0, 1], that a signal/frame/window is usable
CalibrationThe process of learning a stable baseline for a space
Room signatureA vector representation of a space under normal conditions
DriftSlow movement of the field away from baseline
AnomalyA significant, unexplained deviation from baseline
RF memoryPersisted temporal vectors and events for a physical space (stored in RuVector)
CoherenceConsistency among sources, windows, and learned baselines
QuarantineA holding store for rejected/corrupt frames, kept for audit rather than discarded
Adapter profileA capability descriptor for a source (chip, firmware/driver versions, supported channels/bandwidths, expected subcarrier counts, capture/injection/monitor-mode support)
Calibration versionAn immutable identifier for a particular learned baseline; every event references the calibration version it was detected against
Evidence window setThe set of WindowIds an event references as its justification — an event with no evidence is invalid

Bounded Contexts

┌─────────────┐   ┌──────────────┐   ┌────────────┐   ┌──────────────┐
│  Capture    │──▶│  Validation  │──▶│   Signal   │──▶│ Calibration  │
│  context    │   │   context    │   │  context   │   │   context    │
└─────────────┘   └──────────────┘   └─────┬──────┘   └──────┬───────┘
                                            │                 │
                                            ▼                 │
                                     ┌────────────┐           │
                                     │   Event    │◀──────────┘
                                     │  context   │
                                     └─────┬──────┘
                                            │
                              ┌─────────────┴─────────────┐
                              ▼                           ▼
                       ┌────────────┐              ┌────────────┐
                       │   Memory   │              │   Agent    │
                       │  context   │              │  context   │
                       └────────────┘              └────────────┘
  • Capture upstreams raw input from sources.
  • Validation protects every downstream context — nothing crosses into SDK/DSP/memory/agents unvalidated.
  • Signal turns frames into windows.
  • Calibration gives windows a room-specific baseline.
  • Event converts deltas into meaning.
  • Memory stores time, similarity, drift, and coherence (RuVector).
  • Agent exposes safe actions and queries (MCP / TypeScript).

1. Capture context

Responsibility: connect to CSI sources and produce raw frames.

┌──────────────────────────────────────────────────────────────┐
│                      Capture Context                          │
├──────────────────────────────────────────────────────────────┤
│  ┌────────────┐   ┌─────────────────┐   ┌─────────────────┐   │
│  │  Source    │   │ CaptureSession  │   │ AdapterProfile  │   │
│  │ (adapter   │   │ (aggregate root)│   │ (capability     │   │
│  │  plugin)   │   │                 │   │  descriptor)    │   │
│  └────────────┘   └─────────────────┘   └─────────────────┘   │
│                                                                │
│  CsiSource trait: open · start · next_frame · stop · health    │
└──────────────────────────────────────────────────────────────┘
ElementKindNotes
SourceEntityA configured adapter instance bound to a device or file
CaptureSessionEntity / aggregate rootOwns exactly one AdapterProfile and one runtime configuration
AdapterProfileEntityChip, firmware/driver versions, supported channels/bandwidths, expected subcarrier counts, capability flags
Channel, Bandwidth, FirmwareVersion, DriverVersionValue objectsImmutable

Commands: StartCapture · StopCapture · RestartCapture · InspectSource Domain events: CaptureStarted · CaptureStopped · SourceDisconnected · AdapterUnsupported


2. Validation context

Responsibility: make frames safe and trustworthy before any language-boundary crossing.

ElementKindNotes
ValidationPolicyEntityBounds, monotonicity rules, finiteness checks, quarantine on/off
QuarantineStoreEntityHolds rejected/corrupt frames for audit
ValidatedFrameAggregate rootThe frame once it has passed (or been degraded by) validation
ValidationError, QualityScore, FrameBoundsValue objectsQualityScore ∈ [0, 1]

Commands: ValidateFrame · QuarantineFrame Domain events: FrameAccepted · FrameRejected · QualityDropped


3. Signal context

Responsibility: DSP and window features.

Frame stream ─▶ SignalPipeline ─▶ WindowBuffer ─▶ CsiWindow
              (DC removal, phase unwrap,        (mean amplitude,
               smoothing, Hampel filter,         phase variance,
               variance, baseline subtraction,   motion energy,
               motion energy, presence score)    presence/quality scores)
ElementKindNotes
SignalPipelineEntityOrdered DSP stages; reuses wifi-densepose-signal primitives
WindowBufferEntityAccumulates frames into bounded windows
CsiWindowAggregate rootFrames from exactly one source/session
AmplitudeVector, PhaseVector, MotionEnergy, PresenceScoreValue objects

Commands: ProcessFrame · BuildWindow · EstimateBaselineDelta Domain events: WindowReady · BaselineDeltaMeasured


4. Calibration context

Responsibility: learn and version the normal RF state and room signatures.

ElementKindNotes
CalibrationProfileAggregate rootLinked to source, room, adapter profile, configuration
RoomSignatureEntityVector representation of a space under normal conditions
BaselineModelEntityStatistical model of the baseline field; carries version history
CalibrationVersion, StabilityScore, RoomIdValue objectsCalibration cannot complete if StabilityScore < threshold

Commands: StartCalibration · CompleteCalibration · UpdateBaseline · RejectUnstableCalibration Domain events: CalibrationStarted · CalibrationCompleted · CalibrationFailed · BaselineUpdated


5. Event context

Responsibility: semantic event extraction with confidence and evidence.

ElementKindNotes
EventDetectorEntityOne per event family (presence, motion, breathing, anomaly, …)
EventStateMachineEntityHolds the per-source detection state; emits transitions
CsiEventAggregate rootMust reference ≥ 1 evidence window; confidence ∈ [0, 1]; references calibration version
Confidence, EvidenceWindowSet, EventKindValue objects

Commands: DetectEvents · PublishEvent · SuppressEvent Domain events (the CsiEventKind enum): PresenceStarted · PresenceEnded · MotionDetected · MotionSettled · BaselineChanged · SignalQualityDropped · DeviceDisconnected · BreathingCandidate · AnomalyDetected · CalibrationRequired


6. Memory context

Responsibility: RuVector storage and retrieval — RF memory.

ElementKindNotes
RfMemoryCollectionEntityA RuVector collection scoped to a deployment
TemporalEmbeddingEntityFrame / window / event embedding with timestamp
SensorGraphEntityGraph of sources and their topological relationships
RoomMemoryAggregate rootStored embeddings must be traceable to frame windows or event windows
EmbeddingVector, DriftScore, CoherenceScoreValue objectsDriftScore must include the baseline version

Commands: StoreWindowEmbedding · StoreEventEmbedding · QuerySimilarWindows · ComputeDrift Domain events: EmbeddingStored · DriftDetected · SimilarPatternFound

Data stored: frame embeddings · window embeddings · room baseline vectors · event vectors · drift snapshots · sensor-topology graph edges · source health records. Retention policy applies at collection level. No orphan embeddings.


7. Agent context

Responsibility: MCP and TypeScript agent interaction — safe actions and queries.

ElementKindNotes
AgentSubscriptionEntityAn agent's filtered stream of events
McpToolSessionEntityA tool invocation context with permissions
AgentSessionAggregate root
ToolPermission, EventFilter, AgentIntentValue objectsToolPermission distinguishes read vs. write-gated

Commands: SubscribeToEvents · RequestStatus · RequestCalibration · QueryMemory Domain events: AgentSubscribed · ToolExecuted · PermissionDenied

MCP tools (read by default; write-gated marked *): rvcsi_status · rvcsi_list_sources · rvcsi_start_capture * · rvcsi_stop_capture * · rvcsi_get_presence · rvcsi_get_recent_events · rvcsi_calibrate_room * · rvcsi_export_window * · rvcsi_query_ruvector · rvcsi_health_report.


Context Map

Upstream → DownstreamRelationshipACL / contract
Capture → ValidationCustomer/SupplierRaw frames pass through ValidationPolicy; only Accepted/Degraded continue
Validation → SignalConformist (Signal accepts ValidatedFrame as-is)CsiFrame schema is the published language
Signal → CalibrationCustomer/SupplierWindows + baseline-delta measurements feed baseline modeling
Calibration → EventCustomer/SupplierDetectors declare which CalibrationVersion they used
Signal/Event → MemoryPublished Language (EmbeddingVector, event metadata)rvcsi-ruvector ACL translates to RuVector's API
Event → AgentOpen Host Service (event stream + MCP tools)EventFilter + ToolPermission enforced at the boundary
Capture → AgentConformist (health/status only, via MCP read tools)No raw frames cross to agents

The CsiFrame schema is the shared kernel between Capture, Validation, Signal, and the language-boundary (napi-rs) layer. It is the FFI-safe object; nothing device-specific leaks past it.


Aggregates and Invariants

CaptureSession aggregate

Invariant: a capture session has exactly one source profile and one runtime configuration.

  1. A session cannot emit frames before it is started.
  2. A session cannot change channel without restart unless the adapter supports dynamic retune.
  3. A session must emit SourceDisconnected before stopping due to device loss.

ValidatedFrame aggregate

Invariant: no frame crosses into SDK, DSP, memory, or agents unless its validation status is Accepted or Degraded.

  1. Rejected frames go to quarantine when quarantine is enabled.
  2. Degraded frames must carry quality-reason metadata.
  3. Missing optional hardware metadata must not invalidate a frame.

CsiWindow aggregate

Invariant: a window contains frames from exactly one source and one session.

  1. Mixed-source windows are not allowed.
  2. Window start time must be strictly less than end time.
  3. Window quality is bounded in [0, 1].

CalibrationProfile aggregate

Invariant: a calibration profile is linked to source, room, adapter profile, and configuration.

  1. Calibration cannot complete if StabilityScore is below threshold.
  2. Baseline updates must preserve version history.
  3. Event detectors must declare which calibration version they used.

CsiEvent aggregate

Invariant: an event must have evidence.

  1. Every event references at least one evidence window.
  2. Confidence is bounded in [0, 1].
  3. Event suppression must be explainable by policy.

RoomMemory aggregate

Invariant: stored embeddings are traceable to frame windows or event windows.

  1. No orphan embeddings.
  2. Retention policy applies at collection level.
  3. Drift scores must include the baseline version.

Data Model

rust
pub struct CsiFrame {
    pub frame_id: FrameId,
    pub session_id: SessionId,
    pub source_id: SourceId,
    pub adapter_kind: AdapterKind,
    pub timestamp_ns: u64,
    pub channel: u16,
    pub bandwidth_mhz: u16,
    pub rssi_dbm: Option<i16>,
    pub noise_floor_dbm: Option<i16>,
    pub antenna_index: Option<u8>,
    pub tx_chain: Option<u8>,
    pub rx_chain: Option<u8>,
    pub subcarrier_count: u16,
    pub i_values: Vec<f32>,
    pub q_values: Vec<f32>,
    pub amplitude: Vec<f32>,
    pub phase: Vec<f32>,
    pub validation: ValidationStatus,
    pub quality_score: f32,
    pub calibration_version: Option<String>,
}

pub struct CsiWindow {
    pub window_id: WindowId,
    pub session_id: SessionId,
    pub source_id: SourceId,
    pub start_ns: u64,
    pub end_ns: u64,
    pub frame_count: u32,
    pub mean_amplitude: Vec<f32>,
    pub phase_variance: Vec<f32>,
    pub motion_energy: f32,
    pub presence_score: f32,
    pub quality_score: f32,
}

pub enum CsiEventKind {
    PresenceStarted,
    PresenceEnded,
    MotionDetected,
    MotionSettled,
    BaselineChanged,
    SignalQualityDropped,
    DeviceDisconnected,
    BreathingCandidate,
    AnomalyDetected,
    CalibrationRequired,
}

pub struct CsiEvent {
    pub event_id: EventId,
    pub kind: CsiEventKind,
    pub session_id: SessionId,
    pub source_id: SourceId,
    pub timestamp_ns: u64,
    pub confidence: f32,
    pub evidence_window_ids: Vec<WindowId>,
    pub metadata_json: String,
}

pub struct AdapterProfile {
    pub adapter_kind: AdapterKind,
    pub chip: Option<String>,
    pub firmware_version: Option<String>,
    pub driver_version: Option<String>,
    pub supported_channels: Vec<u16>,
    pub supported_bandwidths_mhz: Vec<u16>,
    pub expected_subcarrier_counts: Vec<u16>,
    pub supports_live_capture: bool,
    pub supports_injection: bool,
    pub supports_monitor_mode: bool,
}

pub enum ValidationStatus { Accepted, Degraded, Rejected, Recovered }

Domain Services

ServiceInputOutputResponsibility
FrameValidationServiceRawFrame, AdapterProfile, ValidationPolicyValidatedFrame or RejectedFrameEnforce bounds, finiteness, monotonicity; assign initial QualityScore; route rejects to quarantine; emit structured errors
SignalProcessingServiceValidatedFrame streamCsiWindow streamRun the DSP pipeline; build bounded windows; compute motion energy, presence score, window quality
BaselineDeltaServiceCsiWindow, BaselineModelBaselineDeltaSubtract the calibrated baseline; measure deviation magnitude
CalibrationServiceCsiWindow stream over a calibration windowCalibrationProfile (new version) or CalibrationFailedLearn a stable baseline; compute StabilityScore; reject unstable calibrations; preserve version history
EventDetectionServiceCsiWindow + BaselineDelta + CalibrationVersionCsiEvent streamDrive per-source state machines; attach confidence + evidence windows + calibration version; apply suppression policy
EmbeddingServiceCsiWindow / CsiEventTemporalEmbeddingProduce frame/window/event vectors (v0: deterministic DSP feature vector; later: AETHER / on-device model)
RfMemoryServiceTemporalEmbedding, queryEmbeddingStored / similar windows / DriftScoreStore to RuVector; similarity search; drift computation against a baseline version
ReplayServiceA captured session bundleA deterministic frame/window/event streamReplay preserving timestamps, ordering, validation decisions, event output, calibration version, runtime config
AdapterRegistryServiceList of available adapters + AdapterProfilesDiscover sources (reuses ADR-049 interface detection); report health; flag unsupported firmware/driver state
AgentGatewayServiceMCP tool call / SDK subscriptionTool result / filtered event streamEnforce ToolPermission (read vs. write-gated), apply EventFilter, audit ToolExecuted / PermissionDenied