Rust v2 Homecore platform
Overview
The v2 Homecore platform is a Rust workspace slice rooted in v2/Cargo.toml, with Rust 1.89 pinned in v2/rust-toolchain.toml for workspace dependencies that require newer stable language/runtime support. The relevant workspace members are the Homecore runtime crates (v2/crates/homecore, homecore-api, homecore-automation, homecore-recorder, homecore-plugins, homecore-hap, homecore-assist, homecore-migrate, homecore-server), deployable Cognitum cog crates (v2/crates/cog-pose-estimation, cog-person-count, cog-ha-matter), and the NV simulator (v2/crates/nvsim, nvsim-server). v2/Cargo.toml also documents that homecore-plugin-example is excluded from the main workspace because it is a wasm32-unknown-unknown plugin build, not a normal host test target.
v2/…/lib.rs is the core runtime surface. HomeCore in v2/…/homecore.rs is a cheap-to-clone coordinator over five shared subsystems: the event bus, state machine, service registry, entity registry, and device registry. The state machine in v2/…/state.rs stores Arc<State> snapshots in a DashMap; set atomically updates one entity, suppresses no-op writes, and emits both its private state-change broadcast and a typed SystemEvent::StateChanged on the shared bus. restore is the silent startup path and requires a restoration-marked Context. The bus in v2/…/bus.rs exposes bounded Tokio broadcast channels for typed system events and untyped domain events; lagging receivers must resync from current state. Services in v2/…/service.rs are registered by ServiceName, called outside the registry lock, and convert handler panics into ServiceError::HandlerPanicked so one integration cannot unwind the caller task.
The integration binary is v2/…/main.rs. Startup validates API auth first: HOMECORE_TOKENS is required unless --insecure-dev-auth is explicitly set, then it creates HomeCore, opens the optional SQLite recorder, restores registries and latest states via v2/…/restore.rs, registers built-in services, optionally seeds demo entities, starts the recorder listener, starts plugins, loads YAML automations, builds the Assist pipeline, starts optional HAP, merges the API router with the UI/backend gateway, and serves Axum with graceful shutdown. Static dashboard assets live under v2/crates/homecore-server/ui; ui/…/app.js builds the HOMECORE shell, hash-routes panels, and fans one WebSocket connection into a browser-side event bus.
v2/…/app.rs builds the Home Assistant-compatible REST and WebSocket surface under /api/* and /api/websocket. v2/…/rest.rs gates handlers with BearerAuth, maps state reads/writes and service calls into HomeCore, and uses the recorder attached to SharedState for history and logbook endpoints. v2/…/ws.rs implements the HA-style auth_required / auth / auth_ok handshake against the same LongLivedTokenStore as REST, dispatches commands like get_states, call_service, fire_event, render_template, and keeps event subscriptions alive across recoverable broadcast lag. Token provisioning and dev-mode behavior are in v2/…/tokens.rs; SharedState in v2/…/state.rs is also where an optional recorder is attached for query endpoints.
v2/…/gateway.rs is the backend-for-frontend for the dashboard. It adds /api/intent/handle, /api/homecore/rooms, /api/homecore/cogs, /api/homecore/appliance, and a /api/cal/* reverse proxy to a calibration service. It reuses the API token store for every route, attaches the server-side calibration bearer only inside the proxy, rejects traversal-shaped proxy paths, returns typed 503 upstream_unavailable for appliance/Seed upstreams not present in this repo, adapts calibration RoomState JSON into the dashboard room shape, reads cog manifests from the configured apps directory, and reports cheap /proc-based appliance metrics plus TCP probes.
Automations live in v2/crates/homecore-automation. AutomationEngine in src/engine.rs subscribes to HomeCore state changes and also starts a 1 Hz local wall-clock timer for time triggers. Registered automations are evaluated as trigger match → all conditions pass → RunState dispatch, so run modes such as single, restart, queued, parallel, and max concurrency are enforced outside the action code. src/trigger.rs implements state, numeric-state, time, and event trigger shapes, though the engine's event loop currently feeds state-change contexts; domain-event triggers are represented in the enum but need an event-bus loop to fire at runtime. src/action.rs executes service calls through HomeCore.services(), bounded delays, scene activation via homeassistant.turn_on, wait_for_trigger as a timeout stub, and first-matching choose branches with live state/template evaluation.
Recording is handled by v2/crates/homecore-recorder. src/listener.rs subscribes to the state machine at construction time and writes every StateChangedEvent with a new state into Recorder::record_state; lag only drops the missed window and logs a warning. src/db.rs opens SQLite, applies schema DDL, deduplicates state attributes by FNV hash, stores rows with context IDs and timestamps, exposes bounded history/text/semantic query paths, and best-effort indexes into a SemanticIndex when the ruvector feature is enabled. Server startup passes this recorder into SharedState for history/logbook and into restore_startup for latest-state restoration.
Plugins are split between the generic library in v2/crates/homecore-plugins and server ownership in v2/…/plugins.rs. The library parses HA-compatible manifests with Homecore fields in src/manifest.rs, performs bounded filesystem discovery in src/discovery.rs, exposes in-process and feature-gated Wasmtime runtimes in src/runtime.rs / src/wasmtime_runtime.rs, verifies Wasm hashes/signatures and publisher policy, and enforces state-write permissions. The server never loads arbitrary native dynamic libraries: NATIVE_PLUGINS is an explicit compiled-in registration list, currently empty. External plugin directories require the wasmtime feature; without it, configuring directories or trust options aborts startup. With Wasmtime enabled, discovery reads <root>/…/manifest.json and a same-directory .wasm, verifies trust, calls setup, and then the server dispatches matching state changes to Wasm plugins on a blocking task. v2/…/lib.rs is the wasm-side ABI example: it subscribes to sensor.test_temp and writes binary_sensor.test_alert through host imports.
Assist is v2/crates/homecore-assist. src/pipeline.rs is the public path: recognizer → handler lookup → handler response. homecore-server wires a RegexIntentRecognizer in main.rs with patterns for HassTurnOn, HassTurnOff, HassLightSet, HassNevermind, and HassCancelAll, registers the matching handlers, and exposes it through the gateway /api/intent/handle. The crate also contains semantic recognizer, speech, voice, satellite, and runner modules, but the server path currently uses local regex recognition plus built-in HA-style handlers.
HAP/HomeKit support is optional. v2/…/lib.rs provides accessory mapping, persisted pairing identity, pairing protocol pieces, encrypted/session types, mDNS, a HapBridge, and feature-gated network server support. v2/…/hap.rs leaves HAP disabled unless --hap-bind is supplied; with the hap-server feature it requires a device ID, advertise address, and pairing store/setup code, creates or opens the pairing store, starts mDNS/TCP service, builds a HapBridge, synchronizes current states into accessories, and keeps the bridge fresh from state-change events. v2/…/bridge.rs maps entity states to HAP accessories, maintains the registered accessory set, and emits characteristic events to bounded subscribers.
Home Assistant migration tooling is in v2/crates/homecore-migrate. The library reads HA .storage envelopes, supports v13 registry formats, converts entity/device registries into homecore registry rows, preserves config entries with warnings, redacts secrets.yaml parse errors, and counts automations. The CLI in src/main.rs has inspect/import subcommands for entities, devices, config entries, secrets, and automations, writing JSON summaries for import operations. homecore-server/…/restore.rs reuses the migrate storage reader at runtime to restore .homecore/storage/core.entity_registry and core.device_registry before restoring latest recorder states.
The cog crates are deployable companions rather than core server modules. v2/…/runtime.rs polls a sensing-server JSON endpoint, builds a sliding CSI window, runs an inference engine, and emits pose.frame JSONL events through src/publisher.rs when confidence passes configuration. v2/…/runtime.rs uses the same polling/window shape for a count head and emits person.count events; src/publisher.rs clamps output to trained count classes and marks out-of-distribution counts as low-confidence warnings. v2/…/lib.rs is the Seed-installable Home Assistant/Matter wrapper around the sensing-server MQTT publisher: src/runtime.rs builds MQTT discovery/publisher inputs, derives unique client IDs from the Seed/node identity, can spawn the publisher over a VitalsSnapshot broadcast receiver, and can advertise _ruview-ha._tcp over mDNS. There is no homecore-matter crate in the covered tree; Matter-facing behavior in this slice is represented by cog-ha-matter.
The NV simulator is a standalone deterministic simulator under v2/crates/nvsim. src/scene.rs defines serializable ground-truth magnetic primitives and sensor positions. src/pipeline.rs wires scene field synthesis, propagation/sensor/digitiser stages, produces one MagFrame per sensor per sample, and derives a SHA-256 witness over frame bytes; the same (scene, config, seed) is intended to be byte-identical. src/proof.rs pins a canonical reference scene, sample count, seed, and published witness to catch physics, PRNG, frame-format, or pipeline drift. v2/…/main.rs wraps this with an Axum REST control plane for scene/config/seed/run/pause/reset/step/witness/proof endpoints and a /ws/stream binary frame stream; it initializes from the reference proof scene.
Developer navigation and packaging helpers live in the harnesses. harness/…/README.md describes the npx homecore metaharness, which provides source-cited guidance, bounded read-only MCP tools, focused verification profiles, local host delegation, and reviewed “brain” search without starting servers or modifying repositories by default. harness/…/kernel.js prefers the packaged WebAssembly metaharness kernel and reports fallback honestly. harness/…/README.md describes the umbrella npx ruview CLI/MCP package, which exposes RuView sensing tools plus the Homecore metaharness through one install. Examples under examples/ are demos, blueprints, Lovelace snippets, and research scripts; they are useful for operator-facing shapes but are not the Homecore server runtime. tests/test_invariant_Cargo.py is a Python invariant test around safe Cargo.lock/OpenSSL-version parsing behavior.
Coupling
- If state-change semantics change in v2/…/state.rs, verify v2/…/listener.rs, v2/…/engine.rs, v2/…/ws.rs, v2/…/plugins.rs, and v2/…/hap.rs; all consume the bounded state broadcast and make different resync/drop decisions on lag.
- If
ContextorStatewire shape changes in v2/…/event.rs or v2/…/entity.rs, also update REST/WS views in v2/…/rest.rs and src/ws.rs, recorder persistence/restore in v2/…/db.rs, and migration/registry restoration in v2/…/restore.rs. - If API authentication changes in v2/…/tokens.rs or src/auth.rs, update both REST and WebSocket paths plus v2/…/gateway.rs; the gateway intentionally shares the API token store so dashboard aggregation routes do not become a weaker parallel surface.
- If routes are added outside
homecore_api::router, apply the same CORS/auth/tracing policy in v2/…/main.rs; gateway routes are merged after the API router and therefore rely on the outerbuild_cors_layer()andTraceLayerapplied there. - If the calibration API path or
RoomStateJSON changes, update v2/…/gateway.rs and the UI panels underv2/crates/homecore-server/ui/js/panels/; the browser only sees the adapted/api/homecore/roomsshape and cannot call the calibration upstream directly. - If plugin manifest fields, host imports, or permission claims change in v2/…/manifest.rs, also update discovery/verification/Wasmtime loading in v2/…/discovery.rs, src/verify.rs, src/wasmtime_runtime.rs, server loading in v2/…/plugins.rs, and the guest ABI example in v2/…/lib.rs.
- If automation YAML shape changes in v2/…/trigger.rs, src/condition.rs, or src/action.rs, verify v2/…/main.rs boot loading via
serde_yaml::from_strand v2/…/automations.rs; migration currently counts automations rather than fully converting them. - If recorder schema or latest-state restore changes in v2/…/db.rs / src/schema.rs, verify v2/…/rest.rs history/logbook limits and v2/…/restore.rs startup ordering; server restore expects registries before restored state snapshots.
- If HAP is enabled or its mapping expands, check both v2/…/mapping.rs/src/bridge.rs and v2/…/hap.rs; network startup is feature-gated and mDNS advertisement is tied to a successfully bound server.
- If Cog runtime event schemas change (
pose.frame,person.count, or MQTT discovery), update the corresponding publisher/runtime pairs in v2/…/publisher.rs, v2/…/publisher.rs, and v2/…/runtime.rs; downstream appliance/UI consumers see stdout JSONL or MQTT discovery shapes, not Rust types. - If
MagFrame, physics constants, PRNG use, or pipeline ordering changes inv2/crates/nvsim, update the published witness in v2/…/proof.rs only after auditing the drift, and verify v2/…/main.rs still reports the same expected witness constant. - If package or MCP policy changes in
harness/homecore, update harness/…/manifest.json and verify the README-stated constraints remain true: MCP tools are read-only, Cargo verification is CLI-only, host writes require both--allow-writeand--confirm, and the WASM kernel fallback is reported honestly.
Risks
- Event consumers can silently miss state windows under sustained load because v2/…/bus.rs and v2/…/state.rs use bounded broadcast channels. v2/…/listener.rs logs and continues after lag, which means history may have gaps; v2/…/plugins.rs also logs and drops skipped plugin events. Tests in these files explicitly exercise lag behavior, so changes to channel capacity or lag handling should be reviewed as data-loss behavior, not just performance tuning.
- v2/…/main.rs has an explicit insecure dev auth escape hatch (
--insecure-dev-auth) that causes v2/…/tokens.rs to accept any non-empty bearer. If this flag is used outside isolated development, every REST, WebSocket, and gateway route guarded by the shared token store is effectively open to anyone with any bearer string. - v2/…/trigger.rs represents event triggers, but v2/…/engine.rs subscribes only to state changes plus the wall-clock timer. A YAML automation using
platform: eventcan deserialize yet not fire from domain events until an event-bus loop is added. - Plugin startup is fail-closed but operationally brittle: v2/…/plugins.rs aborts server startup when configured Wasm plugin discovery, trust verification, compilation, or setup fails. That is safer than running unknown code, but a bad package in a configured plugin directory can prevent the whole Homecore server from starting.
- HAP identity and pairing data are durable secrets in v2/…/hap.rs and v2/…/pairing.rs. Recent history includes fixes around HAP secret redaction and SRP verifier padding (
fix(homecore): review findings from PR #1451 — HAP secret redaction...,fix(homecore-hap): pad the SRP verifier to 384 bytes), so pairing-store logging/serialization and verifier handling are fragile areas. - v2/…/main.rs has permissive CORS by default (
--allowed-origin *) and no auth; keep it as a local/simulation control plane or put an authenticated reverse proxy in front before exposing it. Its WebSocket stream sends binary frames generated from the configured scene/seed and is not protected like Homecore's API.