Skip to content

PHOS Current State

This file is an implementation handoff for coding agents. It records what is present in the checked-out repository and distinguishes implementation from hardware verification.

Current implementation summary

PHOS keeps the robot namespace, Raspberry Pi 3 target, and existing Core, application-service, lifecycle, and MCP boundaries. See Architecture and Development for the canonical technical references.

The provider-independent physical lifecycle supports the native serial controller, optional MQTT, and optional ESPHome Native API observations. MQTT and ESPHome measurements remain separate from native sensor snapshots and native retained history. Authorized current external observations are exposed through the existing MCP physical-context projection.

ESPHome Native API uses explicitly configured encrypted devices, bounded inventory, numeric/binary mapping, separate authorization/revocation, and write-only credential handling. The Web Admin supports manual onboarding, device actions, per-device mapping batch save, and optional descriptive zone metadata. Zone comes from persisted device configuration and is included in authorized ESPHome observation output; it does not change identities or trigger a provider restart. Full operation, security, and projection details are in the ESPHome Native API guide.

The maintainer reports that the performed 1.10.0 essential real-device acceptance procedure completed successfully, including the implemented Native API workflow. This is maintainer-reported hardware evidence, not independent verification by the coding agent. It does not establish that every entity type, zone-propagation scenario, recovery path, or credential-rotation scenario was hardware-tested. Focused automated coverage exists; final automated regression evidence is recorded in the 1.10.0 release record. See the roadmap for current limitations.

The ESPHome UI intentionally exposes manual configured-device administration; internal candidate-registry and discovery services do not imply visible discovery or proposal controls in this UI.

Identity and hardware baseline

Hardware baseline

  • Project: PHOS.
  • Python namespace: robot.
  • Target: Raspberry Pi 3.
  • Display target: 5-inch 800x600.
  • Microphone available; exact interface remains TBD.
  • Display/eyes and Pi Camera/tracking are documented as operational in docs/hardware.md; exact camera model remains unspecified.

Official companion ESP32 firmware

The companion firmware repository is live at phosairobot/phos-esp32. It implements the phos-hw v1 serial JSONL connection for ENS160 + AHT21 telemetry and WS2812B semantic LED control. Makers should follow that repository's build/flashing instructions, then use the PHOS controller setup to enable the Pi-side serial connection and check advertised capabilities.

Current source version

robot.__version__ reports 1.10.0. The current release candidate is not tagged, so this documentation does not by itself establish a published release. See the 1.10.0 release record for its acceptance summary.

Transient Overlay System v1

The source implements source-scoped, bounded semantic transient overlays with renderer and protected-admin-layer integration. Automated core and UI coverage passes; physical Raspberry display validation is deferred.

Semantic Physical Context v1

Temporal History v0.1

PHOS retains a RAM-only, six-hour rolling history of accepted environmental and air-quality measurements (at most one per metric per minute) and confirmed semantic physical transitions. History is discarded on restart, contains no camera frames, audio, transcripts, or identity, and is exposed only through the read_physical_history permission via phos_query_measurements and phos_list_physical_transitions. It is bounded to 360 samples per metric and 500 transitions; it neither pushes a notification for every sample nor interpolates missing observations.

The repository implements a read-only, provider-independent semantic perception context through PhosApplicationService; it is automated-tested and available to the MCP semantic adapter.

Minimal Agent Permission Model

The repository implements an in-code, immutable semantic permission boundary for future trusted external-agent adapters. AgentApplicationService delegates only approved semantic reads and actions to PhosApplicationService; it adds no MCP transport, user/account model, persistence, or raw hardware/render surface. standard and read-only observer profiles are automated-tested. This is not a network or OS security boundary; Stage 3.1 adds the separate transitional identity/authentication boundary below.

MCP Semantic Adapter — Stage 2

The repository implements a trusted-local Streamable HTTP MCP adapter over AgentApplicationService, with standard semantic read/action tools and read-only semantic snapshot resources (phos://status, phos://physical-context, phos://environment, and the on-demand image/jpeg camera resource phos://vision/snapshot). It runs embedded in the one PHOS runtime owner started by normal PHOS startup; it exposes the configured Streamable HTTP listener over that existing runtime. The camera snapshot is synchronous, read-only and non-streaming; it travels through the application/agent permission boundary without opening another camera. The standard profile has the dedicated read_camera_snapshot permission; the observer profile does not. The stdio phos-mcp-bridge dynamically forwards Resources without snapshot-specific bridge code. Automated coverage verifies preview independence, and Raspberry Pi validation confirmed that phos://vision/snapshot remains available with Camera Preview disabled and returns a non-empty image/jpeg blob. This establishes resource availability and JPEG output, not image-content quality. Async semantic change cues use SDK subscriptions/listen; clients receive URI-only notifications and re-read current Resources. Camera snapshots are excluded from notifications. MCP Stage 3.3 is complete: configured bearer secret_ref values resolve only through SecretsService; valid credentials resolve a request-scoped AgentIdentity and existing permission profile. Missing, malformed, or invalid bearers fail before application execution with no default-agent fallback.

Stage 3.2 loads the canonical agents registry at startup. A configured default agent resolves to AgentIdentity, its existing permission profile, and then the agent application facade. Changes are restart-only. Stage 3.3 adds only non-secret credential references, not tokens, Web Admin management, bridge credentials, or credential-management UI.

MCP Stage 3.4 supplies AgentCredentialService for creation, rotation, revocation, and non-secret status of configured bearer references. It uses the existing encrypted SecretsService; bearer values are generated with the OS CSPRNG, disclosed only at create/rotate time, and are never readable through the lifecycle service. Rotation preserves secret_ref and invalidates the old bearer; revocation removes the stored value while retaining the configured identity/profile. Stage 3.4 itself did not add Web Admin management, bridge transport support, expiry policy, or an external identity provider.

MCP Stage 3.5 adds the authenticated Web Admin Settings → Agents page for existing configured agents. It displays only identity/profile and non-secret credential status, calls AgentCredentialService rather than SecretsService, requires confirmation for rotate/revoke, and renders a newly issued bearer only in its immediate create/rotate response. Agent-definition editing remains the canonical restart-required configuration workflow.

MCP Stage 3.6 is complete in the separately owned phos-mcp-bridge: its stdio transport reads PHOS_MCP_TOKEN and creates an authenticated Streamable HTTP connection to PHOS. The security boundary is deliberate: the bridge transports the credential, while PHOS resolves AgentIdentity and PermissionProfile and enforces authorization, including camera and Resource permissions, through BearerAgentAuthenticator and AgentApplicationService. The bridge has no identity or permission logic, rejects visible bearer CLI arguments, and does not fall back to an unauthenticated/default identity. Credential rotation or revocation in PHOS invalidates the old bearer; update PHOS_MCP_TOKEN and restart/relaunch the bridge if required to create a new authenticated upstream connection. Hot credential reload is not claimed. Bridge automated validation passed (10 tests); live PHOS/bridge interoperability validation is not yet recorded and remains Stage 3.7 work.

MCP Stage 3.1 establishes an application-level identity boundary. Each inbound MCP request passes through one authentication middleware hook that resolves an immutable provider-neutral AgentIdentity; its permission-profile reference is then used to create the permission-checked AgentApplicationService facade. The transitional LocalAgentAuthenticator resolves every trusted-local client as local-agent with the existing standard profile and verifies no credentials. It preserves prior behavior but is explicitly not production-grade authentication. Credential-backed configuration, per-client authentication, and lifecycle operations are now implemented; expiry policy and external identity providers remain future work.

Sensor availability/freshness transitions are complete: numeric samples remain read-only, while status transitions publish semantic Resource cues. Raspberry Pi validation confirmed direct-HTTP phos://status sleep/wake notifications, phos://physical-context semantic updates, phos://environment availability updates, environment loss/recovery, and motion/IMU availability transitions. The separately owned phos-mcp-bridge was externally validated with a stdio subscription receiving two consecutive phos://status ResourceUpdated notifications. No physical air-quality validation is claimed. A fake-clock test of the monitor sleep loop with a real sensor-service age calculation remains a non-blocking test improvement; _check_sensor_freshness() is automated-tested.

PHOS 1.9.0 — Physical Context & Object Awareness

PHOS 1.9.0 adds bounded six-hour, RAM-only physical measurement and semantic transition history, queried through phos_query_measurements and phos_list_physical_transitions. The documented Physical Context Intelligence v0.1 pattern lets external Agents combine those bounded observations with phos_get_physical_context; PHOS supplies facts and summaries, while Agents remain responsible for interpretation and decisions.

It also adds optional, on-demand NanoDet object awareness through phos_get_visible_objects. It reuses the existing VisionPipeline frame owner, is disabled by default, and returns only labels, confidences, and frame freshness—not images, boxes, identities, tracking, or retained object history. The release also corrects the BGR/RGB preview boundary while preserving BGR for OpenCV vision consumers.

PHOS 1.8.0 — MCP & Runtime Administration Stabilization

PHOS 1.8.0 includes Streamable HTTP MCP semantic tools and Resources, the on-demand permission-controlled phos://vision/snapshot JPEG Resource, and the Web Admin Runtime settings split with immediate Camera Preview/log-level application. Automated coverage verifies the application and permission boundaries; Raspberry Pi camera-snapshot testing confirmed operation with Camera Preview disabled. MCP Stages 2 and 3.3–3.6 are complete; live external multi-agent interoperability validation remains Stage 3.7 work.

PHOS 1.7.0 — External Hardware Controller & Semantic LED Control

The repository implements the generic phos-hw v1 serial controller boundary, capability discovery, reconnect lifecycle, and controller-backed environmental, air-quality, and IMU semantic providers. It also includes Hardware Controller Web Admin read/configuration paths, capability-aware semantic LED command transport, and POST /api/v1/signal arbitration. These are Raspberry-side implementation records. See the 1.7.0 release record and architecture reference.

PHOS 1.4.0 — Voice & Interaction Foundation

PHOS 1.4.0 implements startup/readiness (splash, ready sound and hidden cursor), touch/gesture input, USB microphone capture, canonical 16 kHz PCM16 processing, VAD and bounded pre-roll. Default local Vosk and optional Cartesia Ink batch STT implement the provider-neutral transcription boundary. Local Piper, Cartesia and ElevenLabs TTS adapters feed AudioOutputProvider and the SPEAKING state through /api/v1/speak. YAML is the canonical editable configuration; YAML is the only supported runtime configuration file format.

At the 1.4.0 snapshot, transcript-to-intent/command interpretation, wake words, continuous listening, conversational LLM, Home Assistant and MCP events/subscriptions remained deferred. Subsequent source implements bounded deterministic English/Italian commands and MCP event/resource subscriptions; wake words, continuous listening, conversational LLM and Home Assistant remain deferred. See the voice command, MCP, and roadmap references for current status.

PHOS 1.3.0 release candidate

This is a historical 1.3.0 release-candidate record. The current source version was 1.4.0. Version 1.3.0 added stable Presence and Attention state, transient presence LED reactions, observed facial-expression telemetry, and a bounded expression-reaction policy to the existing Remote API and Web Admin. Automated regression has passed. See release-1.3.0.md for current gates; older release sections below are retained as implementation history, not current release status.

The recommended Raspberry Pi OS installation path is now ./scripts/install-phos.sh. It validates the supported platform, installs the canonical .[all] runtime dependency aggregate, prepares the configured local ONNX model, and performs software-only smoke checks. Follow the hardware setup instructions in the installation guide.

PHOS 1.4.0 Slice 1 adds a local startup splash owned by the existing eye display. Runtime readiness records required display/core and optional Vision, sensors, and LED outcomes as ready, degraded, or failed; normal eyes appear only for ready/degraded startup. Optional local ready sound and face-display-only cursor hiding are configured through the canonical startup section. Physical Pi asset diagnostics now report the resolved splash/sound paths, readability, splash loader result, and aplay outcome. Default PHOS assets are packaged under robot.assets; explicit config overrides remain configuration-relative.

Startup-experience Pi integration tests

On power-on, confirm the splash appears before normal eyes; it must remain while components initialize. Confirm one ready sound when configured, normal eyes only after ready/degraded state, and a persistent startup error for a critical failure. Verify an unavailable optional sensor permits degraded startup. Move a mouse over the face display to confirm its cursor is hidden, then open Web Admin and confirm the browser cursor remains normal. Touch/gesture behavior is documented separately from this startup test sequence.

Present in the repository

Core and behavior

  • Event bus and explicit RobotState state machine.
  • BehaviorEngine under src/robot/core/behavior_engine.py.
  • Skin-owned Physical Personality v0.2 is an IDLE-only policy: analytical, playful, and calm select bounded blink/gaze timing internally (the missing-field fallback is analytical). Analytical uses 4.8–7.2 s blinks, 4.0–7.0 s gaze rests, 1.4–2.3 s holds and a 1.5% double-blink chance; playful uses 2.4–4.2 s, 1.5–3.2 s, 0.65–1.25 s and 18%; calm uses 5.5–8.0 s, 4.8–8.0 s, 1.8–3.0 s and 4%. A double blink has a bounded 90–220 ms open pause (preset-specific). Gaze targets hold, return to neutral, then rest. Attention, vision tracking, IMU motion, explicit reactions, non-IDLE states, and skin changes cancel pending personality sequences. In global appearance mode, the persisted appearance.global_skin_id selects the complete Skin identity (appearance, palette, and personality); no selected Skin retains legacy global appearance with the analytical fallback. Focused automated coverage is present. User-confirmed Raspberry Pi observations cover visible preset differences, persistence, manual application, and IMU integration; broader Vision/attention integration and performance testing remain planned work.
  • Environmental behavior is implemented through EnvironmentalInterpreter: confirmed, hysteretic temperature and ENS160 eCO2/TVOC context becomes EnvironmentalState, then a BehaviorEngine eye/LED accent. ENS160 is controller-backed; eCO2 is estimated equivalent CO2, not direct NDIR CO2. Missing, stale or unavailable data produces no alarm. CCS811 references below are historical; current source uses the controller ENS160 path.
  • Environmental overlays are additive display decoration: the interpreter also exposes independently confirmed temperature (warm/cold) and air-quality (warning/bad) intents, allowing sweat/snow and haze to coexist while the existing single priority EnvironmentalState continues to drive eyes and LEDs.
  • Behavior produces FaceState and handles blink/idle gaze.
  • Robot states include IDLE, LISTENING, THINKING, SPEAKING, SLEEPING and ERROR.
  • Presence/Attention vertical slice is implemented and covered by hardware-free lifecycle tests: provider-neutral selected-face observations use confirmed Presence edges and Attention IDLE → ACQUIRING → TRACKING → LOST → IDLE. It supplies semantic gaze and optional configured LED enter/leave transients through BehaviorEngine and FaceState, without identity recognition.

UI / eyes

  • UI-neutral FaceState and expression/blink enums.
  • The manually selectable expression set is neutral, happy, curious, surprised, sad, angry, focused, tired, confused, scared and skeptical. sleepy and worried remain renderer vocabulary for existing state/reaction behavior, rather than manual commands. Robot state and expression remain independent: for example, focused can be selected while PHOS is thinking without changing that state. Manual selection persists until explicitly replaced. The shared canonical expression profile and geometry path drives both live Tk eyes and Appearance Preview; automatic BehaviorEngine selection of the manually selectable expressions is deferred.
  • Every expression supports the configured/custom iris color. HAPPY's blue eye-body accent and SURPRISED's yellow eye-body accent remain specific semantic exceptions; expression geometry is the primary visual language, not a general emotion-to-color mapping. FURIOUS and expression intensity are not implemented.
  • Eye renderer/display runtime with smooth frame updates.
  • Standalone eye demo under src/robot/ui/demo.py.
  • Current README documents an 800x600/fullscreen runtime path and keyboard-driven eye demo.

Vision

  • Provider-neutral camera, face-detector and expression-provider contracts.
  • Picamera2 camera adapter and OpenCV face detection/expression implementation are present.
  • VisionPipeline rate-limits detection and expression inference independently and publishes stable-expression / face-lost events.
  • Temporal expression smoothing is present. BehaviorEngine maps only stable observations to subtle FaceState reactions, refreshes sustained reactions, and decays them to baseline. UNKNOWN is explicit; negative classes never select a PHOS expression. Surprise is temporary with rearming/cooldown. Neutral perception defaults to disabled pending calibration; RobotState takes priority. Semantic thresholds and diagnostics are in docs/vision.md.
  • FaceState includes a provider-neutral VisualAccent; the eye renderer smoothly applies its semantic neutral/warm/curious/alert/sleepy/error colors to eye and pupil appearance without depending on Vision labels.
  • OpenCV Zoo MobileFaceNet is the selected expression replacement candidate; FER+ remains the rollback/comparison baseline. The existing provider supports both, with presets and inference timing. An in-memory paired camera benchmark is available as python -m robot.vision.benchmark. Pi CPU inference is measured; two camera comparisons had poor face detection coverage and showed no recognition improvement. A rotation probe did not resolve detection; see docs/vision-model-evaluation.md for model details, evidence, channel-order inconsistency and test steps.
  • Face-position tracking is implemented: Vision initially acquires the largest valid face, then prefers geometric continuity and publishes normalized selected-face position events, and BehaviorEngine smoothly maps them into bounded FaceState pupil targets. Hardware operation is recorded in docs/hardware.md; fresh release regression remains required.
  • Expression crops are bounded squares with configurable margin and smoothed scale; two matching detections are required before inference. Debug logs expose all detections, selections and rejections. See docs/vision.md for geometric gates, reacquisition rules and physical crop verification.

AI

  • Provider-neutral LLMProvider contract and RobotAgent skeleton exist.
  • OpenAI, Anthropic and local/LAN provider adapter modules exist.
  • Provider maturity should be judged from code/tests rather than filename presence alone.

Runtime

  • An application runtime/coordinator already exists and can supervise Core/UI and optional Vision.
  • This code predates the newer vertical-milestone discipline. Preserve it, but do not use its existence as a reason to expand unfinished subsystems automatically.

Voice / TTS

  • Voice input follows Microphone → capture/VAD → VoiceCaptureSession → STTProvider → transcript for bounded utterances. Local/Vosk is the default provider and Cartesia Ink is opt-in batch STT; explicit cloud selection never silently falls back. Optional provider failures do not prevent general PHOS startup.
  • robot.interaction supplies provider-neutral TranscriptResult, InteractionInput, resolved/unresolved canonical intent data, conservative language-tag normalization, and an async IntentResolver contract. These are foundation-only contracts. The configured deterministic resolver has a small exact English/Italian vocabulary. When enabled, the main runtime observes completed voice transcripts and publishes resolved, unresolved, or failed interaction events/status. A separate pure CommandRouter validates and maps resolved intents to semantic commands. Voice execution is opt-in through interaction.execution_enabled, which defaults to false; when enabled, a voice-scoped allowlist authorizes sleep, wake, expression, temperature, pressure, and air-quality commands through CommandExecutor and PhosApplicationService; the accepted phrases are listed in Voice Commands. Queries return bounded InteractionOutcome data (temperature_c, pressure_hpa, or atomic eco2_ppm/tvoc_ppb) or an explicit unavailable outcome. The local, deterministic InteractionResponseRenderer renders query outcomes in English or Italian. Optional interaction.response_tts_enabled (false by default) speaks those query responses through the existing application-owned TTS/audio path; actions and unresolved input remain silent, and a speech failure preserves the rendered response.
  • Speech output follows text → TTSProvider → AudioOutputProvider → SPEAKING. TTSProvider supports Local/Piper, Cartesia and ElevenLabs integration; Audio Output selects ALSA (aplay, default, normalized HDMI playback) or PipeWire (pw-play, direct WAV to PipeWire's default sink) independently, and /api/v1/speak reaches this same runtime path.
  • Voice & Speech applies supported STT/TTS/audio changes live. Candidate activation precedes persistence; failure retains the previous provider/configuration. In-progress sessions/speech retain their original references; subsequent work uses the replacement.
  • Project physical-validation records cover local Vosk STT, Cartesia STT, local Piper TTS, Cartesia TTS, Voice & Speech Web Admin, and live STT/TTS switching without a service restart. ElevenLabs is implemented, but end-to-end physical availability remains subject to external account and voice-plan constraints.

Current development priority

Complete PHOS 1.3.0 release integration testing on the target Pi: Presence/Attention, expression observation/reaction, optional LED feedback, and existing sensor/overlay paths must be verified together. Automated regression is passed. See the 1.3.0 release record for the remaining manual gates. Other scope remains deferred. The expression-reaction implementation needs target-hardware verification with a selected lightweight ONNX model. Confirm the model's labels, dimensions and preprocessing, then verify semantic happy/surprised confirmation and UNKNOWN abstention on the Pi Camera/display while checking CPU use and clean shutdown. Neither current model has demonstrated reliable recognition; neutral activation requires calibration, not just a high softmax score.

Presence / Attention Pi integration tests

On the Pi, start with no person (no_one / idle), enter and remain in frame (one confirmed person_entered, idle → acquiring → tracking, configured entered sweep and gaze), then move in each direction while checking environmental/expression visuals remain independent. A brief departure must not emit person_left; a confirmed departure must emit it once, run the configured reverse sweep and hold Attention in lost for attention.lost_hold_ms before idle. Re-entry must repeat one complete cycle. Finally verify Dashboard/Status update target details and show unavailable—not fake 100%—confidence when the detector has no confidence value.

Selectable expression providers

Local ONNX remains the default; optional AWS Rekognition is implemented behind ExpressionProvider, with local tracking/cropping, bounded background requests, cache expiry, change gating, stability gating and failure backoff. Settings now come from the complete canonical config/phos.yaml and can be overridden by deprecated CLI settings. Cloud cached samples retain capture timestamps and do not advance semantic confirmation. See Vision and installation for policy, privacy, exact commands and external credentials. Mocked tests cover cloud behavior without credentials/network/cost. Physical Pi/AWS validation, expression accuracy and cloud threshold calibration remain outstanding. No automatic provider fallback is implemented.

Canonical configuration

ConfigRepository and robot.config own RuntimeConfig, strict full-file schema validation, configuration-relative paths and reusable atomic save. YAML is the sole editable configuration format; legacy JSON configuration requires explicit one-time migration. Runtime composition passes typed values for display, behavior, Vision, voice/audio providers, sensors and logging. The default display starts with eyes; camera and optional sensor features are disabled. No secrets are part of the model. run_pi.sh seeds phos.yaml only when the destination has no phos.yaml, phos.yml or legacy phos.json; see the migration warning for the .yaml service-path edge. The web interface reuses the model for structured settings and an advanced YAML editor that saves back to the active YAML source; see below. Startup flags remain deprecated overrides pending a separately announced removal after consumers migrate.

SecretsService is the separate encrypted, runtime-only local secret boundary. It keeps logical provider credentials out of configuration and source control; the Web Admin Credentials page is write-only and reports slot status without ever rendering stored values. Cartesia and ElevenLabs resolve their credentials only through this boundary; no secret is returned in configuration, status, logs, or Web responses.

Local Piper loads its installed Python voice lazily and reuses it within the provider instance. Cartesia and ElevenLabs TTS adapters are implemented through the same provider-neutral synthesis/output boundary. Provider availability and physical validation are separate from configuration support.

Web administration

Implemented: optional Flask/Waitress process, required canonical web section, responsive domain pages with shared navigation, per-page merges through full configuration validation/atomic saves, provider selection, bootstrap password rotation, hashed local credentials, expiring revocable sessions, CSRF and global password attempt throttling. Startup owns worker cleanup and exposes parent-owned active configuration metadata on a separate read-only Status page. General provides navigation; Network, Display & Appearance, Vision, Expression Recognition, Logging and Web Administration / Security expose only implemented fields. Password management stays separate. Settings → Configuration presents the complete validated configuration as YAML, uses revision protection against stale saves, and requires an explicit restart after any advanced-editor save; it never applies or converts settings live. Voice & Speech is the exception for supported STT, TTS and audio-output settings: its three sections submit validated candidate configuration through the application/lifecycle boundary to the main runtime. A candidate is activated before persistence; a failure keeps the prior runtime provider and configuration. The page shows configured and active provider/device state separately, with availability or active state shown as Unknown when the runtime snapshot is not available; enabled state is shown where applicable. An operation already in progress retains its provider/output reference; new work uses the replacement. Logging level, iris appearance and camera-preview settings are live-reloadable after full canonical validation. Confirmed PHOS restart uses the supplied user systemd service; manual launches reject browser restart. No OS reboot, AWS credential probe, automatic backup or Internet deployment. The General, System / Status and Sensors pages additionally use the authenticated Remote API for an initial semantic runtime snapshot and live SSE updates. The Waitress-compatible event stream reconnects with bounded backoff and retains last-known values; the Sensors dashboard presents optional sensor states independently and capabilities populate runtime controls. Server-rendered status remains available when JavaScript is unavailable. See user manual for installation and recovery. Tests are hardware-free; Pi resource usage and LAN browser verification remain required.

Remote API application boundary

robot.services.PhosApplicationService is the remote-control boundary. It returns provider-neutral JSON models and accepts semantic operations only; it never exposes GPIO, I2C registers, pixels, camera frames, or renderer objects. The Flask adapter exposes /api/v1/status, /state, /environment, /motion, /health, /capabilities, /overlay, /config, /expression, /visual-source and /events. Events use {type, timestamp, payload} and suppress consecutive duplicate payloads.

When composed into the optional local web process, the API uses canonical web.host and web.port; the committed default is disabled/loopback. Do not publish it to the Internet. For LAN/remote use, retain administrator authentication and terminate TLS/additional authentication at a trusted reverse proxy. Example after authenticating locally: curl http://127.0.0.1:8080/api/v1/status. WSGI uses a low-rate SSE-compatible event stream; a future WebSocket adapter must reuse this same service boundary. See Remote API for the endpoint contract, authentication, and LAN deployment guidance.

PHOS 1.0.0 finalization

The established 1.0.0 scope is frozen; the separately approved BME280/BMP280 addition is recorded below. See release record and deferred roadmap. Version is authoritative in src/robot/__init__.py, with package metadata, startup logs and Status using it. Camera failure/partial-start and cancellation cleanup are hardened. Source sync ships metadata, docs and the pinned web dependency snapshot while preserving deployed settings/credentials. At this historical 1.0.0 snapshot, packaged installs included the then-canonical JSON configuration.

Validated reload and managed restart

robot.lifecycle.LifecycleService owns the active snapshot, load timestamp and fixed status/reload/restart policy. The web worker uses a local process channel; it cannot submit commands or paths. Reload validates the entire saved file and applies logging level, iris appearance and camera preview through their application-service boundaries, preserving AWS SDK log suppression. Other changed fields are listed as restart-required, except MQTT broker reconciliation and supported Voice & Speech provider/output changes which use the live activation and persistence path described above. Authenticated restart requires CSRF and one-use explicit confirmation, then graceful runtime shutdown and exit 75. deploy/phos.service performs process replacement under the desktop user with no sudo/polkit or shell endpoint. Source sync includes the unit but never enables it. System actions remain separate from ordinary config forms. OS reboot and the still-deferred roadmap capabilities remain outside this path.

Eye appearance refinement

Display & Appearance validates display.iris_color and display.eye_shape in the canonical configuration. Skins may select classic_oval, round, expressive, angular, or compact; omitted legacy values use classic_oval. EyeRenderer receives the resolved shape at startup and through the render-loop appearance queue, while Tk keeps the legacy oval path and uses layered contours for custom shapes. Custom iris/pupil graphics use conservative containment rather than pixel clipping. FaceState continues to supply semantic reaction intent; expression labels/providers do not control rendering.

Local camera picture-in-picture

An optional diagnostic preview is disabled by default. When active it uses the existing Vision camera owner, retains only a latest-frame reference in memory, and passes a UI-neutral image/diagnostic value through PhosRuntime to the display compositor. Web Admin → Vision settings apply through validated configuration reload. Frames are neither persisted nor exposed through Web Admin. Enabling the preview starts the dormant pipeline if no other Vision feature is running; disabling it releases the camera when no other Vision feature needs it.

Live eye appearance reload verification

display.iris_color and display.eye_shape are live-reloadable eye-style settings. Semantic accents remain BehaviorEngine-produced FaceState and need no configuration reload. The lifecycle service validates the whole canonical document, then gives the typed RuntimeConfig to PhosRuntime. Its display-loop boundary safely queues the iris theme and eye shape onto the asyncio render thread; EyeRenderer interpolates the color on subsequent frames. Reload does not rebuild Core, Vision, camera, BehaviorEngine, providers or the renderer object. Mixed changes apply logging, iris appearance and preview while retaining other changed fields in restart_required. Invalid configuration applies nothing.

Final release hardening

At this historical 1.0.0 source snapshot, release status was not ready to tag until the remaining release record verification gates were verified. A 1.0.0 tag now exists; this note and its checklist record the then-open gates, not current release status. Earlier test counts are superseded by this audit; git history retains those historical records.

Implemented fixes: preview defaults off; reload waits for camera lifecycle acceptance and preserves configuration-relative paths; failed/cancelled startup releases resources; shutdown drains reload tasks and Vision supervisor waiters; intentional preview-only camera stop does not trigger a subsystem failure; stopped pipelines clear snapshots; rapid toggling cannot build up encoder jobs; preview converts BGR to RGB for Tk without altering Vision/model preprocessing. Runtime and web-worker failures propagate a nonzero exit so systemd can recover. Invalid configuration applies nothing. A later hardware apply failure leaves previously successful appearance changes recorded and reports the failure.

Verification (macOS, Python 3.11.6):

  • Focused runtime/main/lifecycle/configuration/AWS-mock/worker-cleanup checks: 129 passed.
  • Full suite rechecked on 2026-09-23: 285 passed, 1 skipped, 2 failed in 219.08 seconds (.venv/bin/python -m pytest -q --tb=short -rs). Both failures are sandbox PermissionError binding localhost in test_real_web_worker_serves_and_releases_port and test_real_worker_reload_reaches_parent_application; permission for an unsandboxed rerun was declined. The skip is tests/vision/test_expression.py:105 because cv2 is unavailable. No test was weakened/skipped to hide these failures. Installing OpenCV and wheel and rerunning the localhost tests outside the sandbox were requested again during this verification and declined. These integration checks remain blocked; no additional implementation change was needed.
  • Final acknowledgement-path runtime/main/lifecycle/UI checks: 58 passed after retaining completion acknowledgement across an IPC timeout.
  • No real AWS calls or Pi/display/systemd operations were performed. Mobile/tablet review covered responsive CSS/templates and form tests, not a physical browser.
  • pip check, canonical version/config validation, CLI help, shell syntax and diff whitespace checks pass. Source archive built with 1.0.0 metadata and required canonical config, unit, web assets and dependency snapshot verified.
  • Wheel/editable installation unavailable locally (bdist_wheel missing). The local venv has an old installed 0.1.0 package; source launch and tests select src explicitly. This is not the authoritative release version.
  • Targeted tracked-file scans found no AWS key/private-key patterns or tracked generated artifacts. Functional deprecated CLI overrides, eye demo and paired Vision benchmark are retained; no roadmap scaffolding was removed.

The fresh-install guide now provides one complete path through dependencies, configuration, model/SDK selection, credentials and the recommended user service. Release documentation owns integration test steps and performance limitations; no new Pi performance or recognition-quality claim is made.

BME280 / BMP280 follow-on integration

The explicitly requested BME280/BMP280 addition is implemented separately from the frozen 1.0.0 baseline (ADR-022); the source version remains unchanged. It is disabled by default. robot.sensors provides immutable environmental values, a synchronous provider contract and one bounded worker with current-state snapshots. robot.hardware.bme280 owns lazy RPi.bme280/smbus2 access to bus 1, address 0x76/0x77, chip-ID validation, calibration, sampling and cleanup. robot.hardware.bmp280 adds Pimoroni BMP280 with the same ownership boundary; hardware.environmental centralizes type selection. Nullable humidity and explicit capabilities distinguish unsupported humidity from unavailable samples.

Runtime starts/stops the service; sensor absence, invalid samples and I/O errors stay local to sensor availability with retry/backoff. Native slow calls cannot block eyes/Vision or accumulate jobs. Monotonic freshness and UTC update time prevent old readings being shown as current. The lifecycle status snapshot sends read-only state to authenticated Web Admin → Sensors over the existing channel. All five new canonical settings require restart; no CLI fields or behavior coupling were added. Existing deployment JSON needs the explicit sensors.environmental migration and type field; Web Admin offers both types and shows the active sensor.

See installation for exact Pi commands and hardware for expected signal wiring and breakout specifications. The CCS811, MPU-6050 and LED-ring extensions are recorded below.

Verification on 2026-09-23 (macOS, Python 3.11.6):

  • Final complete suite: 325 passed, 1 skipped in 151.16 seconds (.venv/bin/python -m pytest -q --tb=short -rs, outside the sandbox with permission for localhost binding). Both real web-worker tests passed.
  • The sole skip is the existing Vision preprocessing test at tests/vision/test_expression.py:105, because local cv2 is unavailable.
  • Sensor coverage uses fake providers/vendor modules: disabled/no access, both addresses and chip ID, units, invalid values, polling/freshness, backoff/recovery, render continuity, bounded shutdown during read/start, clean restart, config migration/validation, lifecycle IPC and web display/save.
  • pip check, Python compilation, startup --help, shell syntax and git diff --check passed. Optional BME280 libraries were not installed locally; real I2C and Raspberry Pi resource measurements were not performed.

These BME280-only results are historical; the extension verification is recorded below.

Selectable environmental sensor extension (2026-09-24)

Changed implementation files: config/phos.json, pyproject.toml, src/robot/config.py, src/robot/runtime.py, src/robot/sensors.py, src/robot/hardware/bme280.py, src/robot/hardware/bmp280.py, src/robot/hardware/environmental.py, src/robot/web/configuration.py, src/robot/web/domains.py, src/robot/web/templates/configuration.html, tests/test_sensors.py, and tests/test_web.py. Documentation updated: README, hardware, installation, development/configuration, web administration, architecture, decisions, current state and roadmap. The pre-existing uncommitted BME280 work is extended, not discarded; existing lifecycle/main/web-app integration is retained without further changes.

The shared provider/service now supports both chips. Runtime snapshots carry active type, explicit available measurements, values, freshness and health. BMP280 humidity is null and displayed as Not supported. Wrong chip IDs and capability mismatches are unavailable, with bounded retries and clear logs. All five sensors.environmental settings require restart; no hot swapping. The required config migration is documented in development. RPi.bme280 remains unchanged; BMP280 uses the optional bmp280 1.x / i2cdevice library and the same adapter-owned smbus2 bus. Pi setup and runnable physical checks remain in installation.

Verification (macOS, Python 3.11): sensor suite 50 passed; final complete suite 340 passed, 1 skipped in 223.37 seconds (.venv/bin/python -m pytest -q --tb=short -rs, with permission for localhost binding). The single skip is the existing Vision preprocessing check because cv2 is unavailable. Both real web-worker checks passed. The sandbox-only run had two localhost-binding PermissionErrors; these disappeared in the authorized run. Canonical JSON validation, Python compilation, pip check and git diff --check passed. Driver distributions were inspected without installing sensor dependencies locally. No unresolved architectural conflicts were found.

Historical CCS811 air-quality implementation (2026-09-24; removed later)

This feature record describes a prior implementation, not the current checkout. The direct Raspberry Pi CCS811 provider and sensors.ccs811 configuration were removed in the ENS160 implementation change (354062d, “ENS160 implementation”). Current air-quality behavior uses controller-supplied ENS160/AHT21 telemetry; current source, configuration and tests do not expose a CCS811 path. The historical implementation and verification details below are retained as project history and must not be read as current support evidence.

This dated implementation record predates the JSON-to-YAML migration described in the current configuration guide; references below to canonical JSON describe the configuration format at the time of this change.

The explicitly requested CCS811 capability extends the sensor services (ADR-023). hardware.ccs811.CCS811Provider uses smbus2, validates chip/application status, initializes mode 1, handles readiness and returns typed eCO2 ppm / TVOC ppb. AirQualitySensorService shares the existing bounded worker with the environmental service; neither failure nor conditioning blocks rendering/Vision. eCO2 is estimated equivalent CO2, not direct NDIR CO2.

Canonical sensors.ccs811 has enabled, I2C address, polling and stale timeout; all require restart and the committed default is disabled. Existing deployment JSON must merge this required block. The Sensors page includes configuration, measurements, timestamp/age, health and compensation input over the same lifecycle channel. Fresh temperature/humidity may pass through the environmental service; BMP280 or unavailable sources restore device defaults. Conditioning withholds values for 20 minutes after initialization; first-use/physical stability remains unverified. No baseline storage, firmware loader or GPIO wake controller is added.

Implementation files changed for this task: src/robot/hardware/ccs811.py, src/robot/sensors.py, src/robot/runtime.py, src/robot/config.py, config/phos.json, pyproject.toml, src/robot/web/configuration.py, src/robot/web/domains.py, src/robot/web/templates/configuration.html, tests/test_air_quality.py, tests/test_web.py. README and hardware, installation, development, web administration, architecture, decisions, roadmap and this handoff were updated. Prior uncommitted environmental work is preserved.

Physical TODO: identify the precise Keyestudio/SEN breakout, verify supply and Pi-side logic/wake wiring, sustained bus transfers, conditioning/stability, compensation, failure recovery and concurrent eyes/Vision/Web Admin operation. Use the concrete commands/checks in installation. WS2812B remains out of scope; the MPU-6050 follow-on is recorded below.

Verification for CCS811: 88 sensor tests passed (environmental regression plus air quality); 3 targeted Web Admin tests passed. Final full suite: 379 passed, 1 skipped in 220.95 seconds with .venv/bin/python -m pytest -q --tb=short -rs and localhost socket permission. The sole skip is the existing Vision preprocessing test because local cv2 is unavailable. Canonical JSON validation, Python compilation, pip check and git diff --check passed. No physical I2C test was run. No architectural conflict was found. Identify the SEN/Keyestudio board's electrical specifications before wiring it.

CCS811 initialization diagnosis follow-up

User reports HW_ID=0x81 after sensor power recovery, then all registers=0xff once PHOS starts, persisting after PHOS stops with BMP280 disconnected. This localizes the trigger to startup interaction but does not establish the exact physical cause. The unconditional SW_RESET was removed from normal startup; APP_START is now conditional on boot mode, and mode 1 is verified after writing. Initialization errors include address, phase and actual values; all-ones STATUS is rejected before interpreting flags. No config or architecture changes.

Changed src/robot/hardware/ccs811.py, tests/test_air_quality.py, installation troubleshooting and this handoff. Mock tests cover boot/application startup, reconnect without reset, and invalid reads at each initialization checkpoint. The physical fix remains pending a test using the updated file on the Pi after power recovery. No deployment or commit was performed.

Verification of this follow-up: 94 sensor tests passed; full suite 385 passed, 1 skipped in 222.07 seconds (.venv/bin/python -m pytest -q --tb=short -rs, with localhost socket permission). The skip remains missing local cv2. Compilation and git diff --check passed. These are software checks, not confirmation that removing SW_RESET resolves the reported physical failure.

MPU-6050 IMU follow-on (2026-09-25)

The requested GY-521 / MPU-6050 extension is implemented as a separate typed sensor path: MPU6050Provider owns smbus2/register access and IMUSensorService owns polling, freshness, retry and status. IMUReading exposes acceleration XYZ in m/s² and angular velocity XYZ in °/s. Canonical sensors.imu is disabled by default and supports 0x68/0x69; all changes require restart. Web Admin edits that block and reads a service snapshot only. The adapter uses ±2 g / ±250 °/s factory scale factors, without automatic offset calibration, sensor fusion, orientation or behavior integration. Physical wiring and concurrent Pi testing remain pending.

The follow-on motion interpreter derives stable STILL, MOVING, tilt, SHAKE and IMPACT observations from IMU service samples only. Its configurable thresholds are live-reloadable; hardware configuration remains restart-only. Their raw status is visible in Web Admin.

The approved follow-on now routes stable IMU motion state changes through Core to BehaviorEngine. It produces visible FaceState-only tilt, movement, shake and impact reactions; no IMU-to-renderer, GPIO or LED connection exists. Behavior parameters reload live, while Core states retain priority.

Tilt interpretation now uses normalized filtered gravity ahead of MOVING, with exit hysteresis, explicit signed mounting axes and temporal confirmation. Canonical polling is 20 Hz; deployment migration and Pi verification are in the MPU-6050 installation guide.

IMU visual intent is deliberately amplified for the 800×600 display: persistent movement and tilts stay active while observed, while shake and impact use alert overlays with hold then decay. Impact has the strongest allowed FaceState eye opening and reaction strength. All visual tuning remains live-reloadable.

Horizontal IMU tilt now has explicit mirrored eye asymmetry: TILT_LEFT opens the left eye and TILT_RIGHT opens the right. Forward/back and transient IMU alerts keep equal eye sizes. The renderer receives only signed FaceState intent and smoothly interpolates left/right openings independently.

The earlier FaceState LED consumer remains implemented and disabled by led_ring.enabled by default. It is a legacy path, not the hardware wiring for the current robot. The WS2812B ring connects to the ESP32; enable hardware_controller and require session LED capability for semantic output. See controller setup.

Dynamic MQTT broker administration

Connectivity → MQTT now applies global enable/disable and broker, credential, TLS, connection and discovery changes through the existing application/lifecycle boundary, without a PHOS restart. Unchanged provider connections remain intact. Desired configuration is persisted before reconciliation; connection errors and partial application remain visible separately. Discovery trust does not transfer across broker security boundaries, and retired ingress is fenced. Details and remaining real-broker verification are documented in MQTT.

MQTT external observations through MCP

The current development branch includes a bounded, thread-safe, protocol-independent latest-observation read model for accepted non-native PhysicalObservation events. phos_get_physical_context retains its native sections and adds external_observations; physical assessment reports the same sources as distinct current observations, not history or independent evidence. Authorization and availability are checked again at read time. Revoked, removed, suspended, or retired sources are excluded, and a reapproval cannot reveal the old authorization lifecycle’s value.

Automated aiomqtt/amqtt coverage exercises Discovery approval, live ingress, freshness, offline state, revocation, and reapproval fencing. Separately, the maintainer reported a production check with a real ESPHome temperature sensor, real broker, approved active source, accepted canonical observation, stored external observation, and a fresh authorized MCP result. This is distinct from the automated broker suite and does not establish every MQTT lifecycle scenario. The earlier report of an empty external-observations array has no conclusively recorded root cause; it is not presented as resolved by this status note.

MQTT final acceptance status (04J)

The MQTT provider architecture, canonical ingress, multiple broker lifecycle, Discovery review/approval/revocation/reapproval, dynamic activation, Topic Explorer, shared-topic subscription preservation, candidate removal, and MCP external-observation path are implemented. Focused automated coverage uses an isolated amqtt broker plus aiomqtt; it is distinct from a Mosquitto or physical-device result. The maintainer has separately reported real Mosquitto and ESPHome acceptance for scalar and JSON readings, multiple authorized entities sharing a topic, lifecycle recovery after ESP32/PHOS/broker restarts, candidate removal, MCP Inspector, and ChatGPT retrieval.

Guided Manual Mapping (04L.3) is not a separately implemented workflow. The current MQTT Web Admin supports explicit broker manual mappings and completion/edit of a Discovery candidate, but Topic Explorer does not create a mapping. ESPHome Native API is implemented as a separate provider; source fusion, spatial inference, distributed history, and provider-specific MCP tools remain outside this completed MQTT milestone.

Regression closure follow-up (04J.2)

The complete-suite failures reported during MQTT closure were narrowed to three regressions: MQTT rejection logging read a nonexistent ingress-result attribute after a canonical rejection and could terminate the receive loop; the native ENS160 bridge forwarded canonical normalized integral readings as floats to the legacy integer-only aggregate; and a native-context test omitted the intentional external_observations response member. The implementation now uses the ingress result code, restores exact integers only at the ENS160 compatibility boundary, and verifies the complete native-plus-empty-external MCP shape. The maintainer completed the final full regression run successfully: 1765 passed, 0 failed, 1 skipped, and 31 warnings in 748.51 seconds.

Final MQTT baseline and next-step readiness

MQTT milestones 04J, 04J.1, and 04J.2 are complete. The MQTT subsystem is accepted for its implemented read-only scope, based on its focused broker/lifecycle coverage, the historical complete automated regression result above, and maintainer-reported Mosquitto/ESPHome hardware acceptance. Guided Manual Mapping (04L.3) remains an open, non-blocking MQTT backlog item. ESPHome Native API milestones were implemented subsequently; current status and remaining work are in the roadmap.

The accepted baseline was recorded at Git revision 0f8fc0fa246a4bbf1ba411cb5356c61fc10c2bef (0f8fc0f resolve MQTT and native sensor regressions and finalize MQTT acceptance), using Python 3.11.6, pytest 9.1.1, aiomqtt 2.5.1, amqtt 0.12.2, MCP 2.3.0, Pydantic 2.14.0, and PyYAML 6.0.3. The 31 non-failing warnings, including dependency deprecation warnings, are future technical-maintenance work; they do not change runtime behavior or release versions.