AI Agent

CTO Mode — technical reference for the AI agent layer of the Greenacres Platform.

1. Agent Overview Updated: v4.0.32

CTO Mode is the AI agent layer of the Greenacres Platform. It acts as a technical operator: diagnosing faults, deploying platform changes, maintaining documentation, and delivering structured intelligence briefings. The agent runs on demand via Claude Code CLI on Mac — it is not a background daemon. All production actions require explicit authorisation from the platform operator before execution.
PropertyValue
Agent nameCTO Mode — AI agent layer, Greenacres Platform
RoleTechnical operator. Diagnoses, deploys, maintains, briefs. Does not self-initiate beyond opening CTO check.
OperatorCEO / platform owner. Signs off all production changes. Uses Claude Code CLI on Mac.
InvocationType cto mode in Claude Code terminal. Triggers immediate system health briefing — no setup required.
Server accessHP (192.168.0.10) + OP (192.168.0.20) via SSH key ~/.ssh/id_ed25519. Both LAN-whitelisted in fail2ban.
Authorisation modelPropose → Authorise → Execute → Verify. Never deploys to production without explicit sign-off.
Relationship to platformThe agent reads all platform data, writes all hub pages, and maintains all platform documentation. It is both consumer and maintainer of the platform.

2. Model & Runtime Updated: v4.0.32

PropertyValueNotes
Model routing (SOV-1/SOV-2)Sonnet / Haiku / TemplateAsk HAI: Sonnet. HAI morning/evening briefings: Haiku. Auto-downgrade at 95% week usage (SOV-2: economy mode). Template fallback when Anthropic API credits exhausted (30-min probe cache — auto-recovers when credits restored). Tiered alerts at 50/80/95%. Updated: v4.0.32.
Deep reasoning modelClaude Opus 4.6 — claude-opus-4-6Switched to only for complex architectural decisions. Not used by default.
InterfaceClaude Code CLIInteractive terminal on Mac. Not a web UI or API call. Full tool access (Bash, Read, Write, Edit, Grep, Glob, SCP).
Session typeInteractive — operator-initiatedNot a daemon or scheduled process. Runs only when the operator opens a session.
Context management/compact before long sessionsCompresses prior context before CTO mode on sessions with significant prior conversation. Prevents context overflow.
Memory loadingAuto on session startReads MEMORY.md index + all relevant project memory files. Prior decisions, backlog, SSH config, preferences all loaded before first message.
HAI briefing modelTemplate engine (zero API cost)HAI briefings use a Python template engine as Claude API balance is currently depleted. Key stored at /etc/hai.conf. LLM-authored briefings resume when topped up.
Token postureConservativeBatches SSH into single round-trips. Targeted Grep/Glob over broad exploration. Does not re-read files already in context.

3. Access & Authentication Updated: v4.0.32

ChannelEndpointAuth MethodUsed For
SSH — HParash@192.168.0.10:22Ed25519 key: ~/.ssh/id_ed25519File read/write, service management, script execution, sudo operations
SSH — OParash@192.168.0.20:22Ed25519 key: ~/.ssh/id_ed25519DNS config reads, OP service management, unbound status
HA REST APIhttps://192.168.0.10/ha-api/Bearer token injected by nginx from /etc/ha-token.conf. Agent calls the proxy — never the token directly.Lock/unlock, thermostat control, entity state reads, service calls
Starling Hub APIhttp://192.168.0.25/api/Bearer key from /etc/starling.conf (read via SSH)Thermostat states (2 units), camera online/offline, Protect smoke/CO data
InfluxDBdocker exec influxdb influx queryDocker exec via SSH — no separate credentialHistorical metric queries beyond 7-day history.json window. Bucket: greenacres
Pi-hole HPVia status.json (60s cache) or http://192.168.0.10/admin/api.phpstatus.json: SSH. Direct API: no auth required on LAN.DNS query counts, block rate, top domains
Hub pages (write)/srv/www/newsite/ via SCP + sudoSSH key + sudo. Scripts written to /tmp/, SCP’d, then run with sudo python3Deploying HTML page changes, new pages, version updates
nginx config/etc/nginx/sites-enabled/intranet-https.confSSH + sudo. Always runs nginx -t before reload.Routing changes, new location blocks, proxy config

4. Session Workflow Updated: v4.0.32

StepActionDetail
1Load memoryReads MEMORY.md index and all relevant memory files from ~/.claude/projects/-Users-arash/memory/. Loads project state, backlog, preferences, SSH config, prior session outcomes.
2Pull live statusSingle SSH call to HP. Reads status.json. Parses server vitals, Docker state (6 containers), network (6 devices), lock state, HAI health scores, active insights. Data age checked; >120s flags stale.
3Deliver briefingStructured CTO report: HP+OP vitals, Docker, network, security (lock+cameras+battery), HAI intelligence, open backlog. Delivered immediately — no questions first.
4Receive instructionAwaits direction. Agent does not self-initiate work beyond the opening briefing.
5ResearchSSH reads of affected files, logs, status.json. States findings before proposing any change.
6PlanDescribes the exact change: which files, what lines, what effect. No code written yet.
7AuthorisePauses and waits for explicit sign-off. Does not proceed on implicit approval.
8ExecuteScripts SCP’d to /tmp/ and run with sudo python3. Production files written only after sign-off.
9VerifyRe-reads file, checks service status, or re-polls status.json. Does not mark a task complete until verified.
10Update memory + docsUpdates MEMORY.md, project_greenacres_plan.md, and hub pages (/docs/, /ai/, /dev/) to reflect completed work and new backlog items.

5. Capability Matrix Updated: v4.0.32

DomainCapabilityNotes
Infrastructure SSH to HP (.10) and OP (.20)Key: ~/.ssh/id_ed25519. Both LAN-whitelisted in fail2ban.
Read/write any server fileVia SCP + sudo. All production writes require authorisation.
systemd service managementstart / stop / restart / status on all greenacres-* services + Docker.
Self-healing SREProposes fixes (docker restart, log cleanup, service restart) to proposed_fixes.jsonl on triggers. Operator approves in /admin/ Proposed Fixes card. Strict whitelist execution. SELF-1/2 v3.39–v3.40.
Docker controlps, start, stop, restart, exec, logs on all 6 containers.
nginx edit + reloadEdits intranet-https.conf. Runs nginx -t before every reload.
Run maintenance scriptsAny script in /usr/local/sbin/ — backup, maintain-all, intelligence, history, etc.
Platform Data status.jsonFull live state. All 11 top-level keys. ~18 KB. Schema documented in Platform Docs §7.
history.json14 time-series, 30-day rolling, ~137+ pts/series (grows with uptime), ~60 KB.
hai_briefing.jsonLatest HAI briefing including health scores, headline, narrative, and context summary.
InfluxDB queryDirect Flux query via docker exec influxdb influx query. Bucket: greenacres.
HA state snapshotAll HA entities via REST API or saved ha-state-dump.json snapshot.
Hub & Portal Bug diagnosis + fixFull source access to all 11 hub pages + monitoring portal (1905 lines).
Maintain /help/ Ask HAI pageUpdates system prompt context, suggestion chips, and offline messaging as platform evolves.
Release automationRuns greenacres-release at end of each deploy session — updates version badges, release cards, and /dev/ in one command.
Build new pagesSingle-file HTML, no build step. Deploy to /srv/www/newsite/.
Bulk nav updatesPython script approach updates nav across all pages atomically.
Version bumpString replace across all hub pages + releases hero/history/meta in one pass.
Maintain /docs/ /ai/ /dev/These pages are written and updated by the agent on every release.
Release preview modeShows exactly what will change before any release executes: version, notes, backlog items shipping, pages to update. Requires y/N confirmation. Flag --yes for non-interactive. Introduced v3.5.0.
Automated QA gate18-check post-release verification: all 13 pages HTTP 200, status.json freshness (<120s), admin-api health, sidebar version consistency. Hard exit on failure. Introduced v3.5.0.
Backlog-driven releasesgreenacres-release reads backlog.json, marks items shipped with correct codename/date, regenerates /dev/ via greenacres-dev-render. Introduced v3.5.0.
Remote access via TailscalePlatform accessible from anywhere via https://hp.tailabbaf3.ts.net over Tailscale VPN. Valid 90-day TLS cert via tailscale cert, auto-renewing Monday 03:00. No port forwarding, no public exposure. Introduced v3.10.0.
Agent Brief page/docs/onboarding/ — cold-start reference for AI agent sessions. Covers system overview, operator values, key file locations, release process, known landmines, and session checklist. Introduced v3.11.0.
Generic entity renderer/controls/ dynamically renders any HA entity type returned in status.json. media_player entities appear with on/off toggle buttons; unknown domains show name, state, and entity_id. Framework supports light, switch, fan, input_boolean, automation. Introduced v3.13.0.
PWA offline modeV-M3: Hub installs as a standalone PWA (manifest.json with app shortcuts, icons, theme). Service worker pre-caches all 13 pages on install; cache-first strategy for shell assets; network-first for live data with offline fallback. HA API calls always go to network. Introduced v3.15.0.
Smart Home Read device stateVia status.json (60s) or live HA API via /ha-api/ nginx proxy.
Call HA service endpointsPOST /ha-api/services/{domain}/{service} — lock/unlock, thermostat set, scene activate.
Read Starling dataThermostats (2), cameras, Protect via Starling Hub at 192.168.0.25.
HA config diagnosisHA config files readable via SSH. ha-filebrowser container available for browser-based access.
iOS push notificationsAlerts via HA notify API (mobile_app_arash). push_alerts_smart v2: push once on new alert, silent on persistent, re-push when alert resolves and returns. 10-min resolved window. push_sent.json tracks per-alert state.
Live camera snapshots in portalCAP-4: Security tab shows real-time JPEG stills for all 5 online cameras (Driveway, Doorbell, Patio, Garage 1, Garage 2) via /ha-api/camera_proxy/{entity_id}. Auto-refreshes on every status.json update (~60s). Offline cameras greyed out. Bearer token injected server-side — browser sees no credentials. Introduced v4.0.12.
All-device battery gridCAP-8 / CAP-7: Security tab shows all 28 battery sensors in a colour-coded grid (green/amber/red), sorted worst-first. Badge shows critical/low/ok counts. Reads all battery sensors from ha.sensors in status.json — includes cameras, locks, motion sensors, door contacts, smoke detectors. Introduced v4.0.14.
Laundry status + energy costENG-1: Climate tab shows washer and dryer running state with minutes remaining. Energy cost computed at 28p/kWh (Ofgem unit rate) — yesterday usage, month-to-date, and cycle count from HA Miele integration. Introduced v4.0.14.
Intelligence Consumable trackingDedicated detector for printer ink (warn <20%, alert <10%) and Claude API credits (warn ≥75%, alert ≥90%). Surfaces as insights in status.json — visible on /status/ Active Insights panel and morning push.
Active Insights on /status/Alert + warn insights rendered in real-time on Status page. Severity-colour-coded with full detail text. Hidden when all clear.
Pi-hole top queried domains/analytics/ shows live top-10 queried domains from Pi-hole v6 API (updated every 60s via greenacres_influx_write). Visual bar chart with counts. Introduced v3.12.0.
WAN bandwidth chartV-C2: /analytics/ shows 30-day download and upload Mbps for enp1s0 (WAN interface). Live rate from delta state file; history via InfluxDB derivative() on wan_rx_bytes/wan_tx_bytes. Chart hidden until sufficient data accumulates. Introduced v3.16.0.
Contextual HAI briefingsMorning (07:00) + evening (19:00) + escalation briefings generated by claude-haiku-4-5-20251001 from live status.json + InfluxDB data. Template fallback if API unavailable. Introduced v3.6.0.
Natural language reasoning from live dataHAI prompt passes server vitals, health scores, active insights, 12h InfluxDB summary, presence data. Claude produces headline + narrative + priorities + recommendation. Introduced v3.6.0.
Weather-aware intelligenceTWIN-1: Open-Meteo free API (no key) fetches 12h hourly forecast every 30 minutes. Storm (WMO 95–99), rain, and wind >50km/h trigger storm-aware insights. Camera batteries auto-flagged when adverse weather forecast — “Power Optimised” context. Weather block added to status.json. Coordinates in /etc/hai.conf. Introduced v3.42.0.
Cmd+K global searchNAV-1: Search overlay on all 17 portal pages. Indexes pages, features, actions, and changelog items. Keyboard shortcut ⌘K / Ctrl+K. Arrow key navigation, Enter to go. Loads changelog.json for version/item search. Introduced v3.63.0.
Files API knowledge base for Ask HAIAPI-5: Four knowledge base documents (platform architecture, device reference, automation policy, troubleshooting runbooks) uploaded to Anthropic Files API and injected into every Ask HAI conversation. greenacres-ask-cto loads file_ids from /var/lib/greenacres/files_api.json and prepends document blocks to first user message. Ask HAI can now cite specific platform docs in answers. Files API beta header combined with existing prompt caching. Introduced v3.64.0.
Batch API on weekly AI scriptsAPI-3: greenacres-backlog-suggest and greenacres-automation-suggest submit via Message Batches API (/v1/messages/batches). 50% token discount on all weekly analysis. Combined with prompt caching: ~75% total cost reduction. Results available async within 1h. Introduced v3.62.0.
Vision AI — camera anomaly detectionAPI-4: greenacres-camera-vision fetches snapshots from doorbell, driveway, and garage1 cameras every 5 minutes via HA camera_proxy. Sends to Claude Haiku vision with prompt caching. Detects: person, package, vehicle. Alert insights injected into intelligence engine when activity detected. Doorbell push notification enriched with AI activity description. Vision + Cache tiles in /admin/ System Health grid. Introduced v3.61.0.
Prompt caching on all AI callsAPI-1: All 4 Claude scripts (HAI briefings, Ask HAI, backlog-suggest, automation-suggest) use cache_control: ephemeral on system prompt. 70-80% token cost reduction on repeated context. Cache read/write tokens tracked per briefing. Introduced v3.60.0.
HA Met.no weather on dashboardHA-13: weather.forecast_greenacres added via HA config flow (Met.no, free, no key). Weather chip on Home view shows live temperature + conditions. Weather Forecast card in Environment view shows 7-day daily forecast. 24h history-graph cards for room temps, humidity, and CO ppm. Introduced v3.55.0.
Platform suggests its own improvementsgreenacres-backlog-suggest analyses 14-day event patterns, calls Claude Haiku weekly, generates 3–5 evidence-backed backlog suggestions. Visible on /dev/ as Review queue. Introduced v3.7.0.
Platform Audit Full system health auditSystematic check: HTTP 200 all 11 pages, status.json age, all 6 Docker healthy, InfluxDB last-write per measurement, all systemd timers firing, Ask HAI endpoint POST test, HAI briefing freshness, events.jsonl writing, push log state. Run at session start and after major changes.
Data accuracy verificationCross-checks status.json fields against live HA API: cameras online count, lock state, thermostat temps, presence, sensor values. Flags stale data (>120s), missing fields, or type mismatches.
Security hardeningSEC3: Basic Auth on /admin/ + /admin-api/ (nginx htpasswd). SEC4: XSS escapeHtml() in /events/ JS render. SEC5: ha-filebrowser bound to 127.0.0.1:25405 (not 0.0.0.0). SEC6: Mosquitto allow_anonymous false + password_file enforced. Introduced v3.8.0.
Live health transparencyUAT1: amber banner on all 13 pages when status.json >6min stale. UAT2: bottom bar when HAI on template-engine fallback. UAT7: connection-lost overlay after 3 consecutive fetch failures. DEV14: last-refreshed timestamp on /dev/ urgency block. Introduced v3.9.0.
Status page intelligenceQW2/3: /status/ shows live thermostat temps (current+target), front door lock state + battery %, and HP formatted uptime — all from status.json. QW1: browser tab title shows active alert count on all 13 pages. Introduced v3.18.0.
Home awareness/status/ shows who is home (ha.presence), Pi-hole live stats, active media devices, and force-refresh button. All from status.json. Introduced v3.19.0.
Sensor alerts & watchdog fixCO and low-battery sensor alert cards on /status/ (QW9). Event filter count badges show live totals (QW11). OP Pi-hole stats shown alongside HP (QW12). Credits insight shows remaining units (QW10). V-A3 watchdog corrected: HP_SERVICES now monitors only persistent services; HA notification spam eliminated. iOS push payload updated to modern format. Introduced v3.20.0.
Status page intelligence IIHealth scores for security, comfort, and infrastructure displayed as stat cards. Network health card shows N/N devices online with gateway CPU. Active binary sensors (occupancy, door, motion) shown as live cards when triggered. Introduced v3.21.0.
Status & analytics depthNest Protect alarm/clear stat card on /status/. Thermostat cards show humidity from Starling Hub. Analytics OP Memory % chart added (layout bug fixed). Events Today (1-day) filter button. Introduced v3.22.0.
Camera & doorbell awarenessCamera online summary card (N/7) with offline names highlighted. Doorbell ring and package delivery cards shown when active. Intelligence engine detects unexpected HA restarts and fires warn insight. Introduced v3.23.0.
Developer visibilityQuick chart picker on /dev/ renders any of 16 history.json series on demand (V-D5). Top AI suggestion card on /admin/ surfaces highest-confidence backlog-suggest pick (V-A6). Introduced v3.26.0.
Network topologyLive SVG network topology diagram on /status/ — renders gateway, switches, and APs in 3-tier hierarchy with per-node health stats sourced from status.json in real time. Introduced v3.27.0.
Alert noise managementSUGGEST-10 (v3.32.0 “Quiet”): 6-hour dedup window prevents repeat events per sustained alert. Per-alert snooze (4h / 24h / 7d) via admin-api POST /snooze — suppresses insight from status.json and push until expiry. Alert fatigue scoring: 0–100 score computed from 14-day events.jsonl, top 10 noise sources surfaced in /admin/ with inline snooze controls. alert_fatigue block in status.json.
Battery health predictorSUGGEST-6 (v3.34.0 “Forecast”): Unified drain-rate model via linear regression across all tracked devices (patio camera, driveway camera, front door lock). Warns 14 days before critical threshold, alerts at 3 days — fires at 60% if drain rate warrants it. Battery Health table on /status/ shows level, drain rate, predicted replacement date, charging state, and status badge. battery_health block in status.json updated every 5 minutes.
Occupancy contextSUGGEST-9 (v3.35.0 “Occupancy”): compute_occupancy_context() builds occupancy model from geofence presence data + motion sensor state history. Returns state (away/home/unknown), confidence (high/medium/low), empty duration, last-motion timestamp, and evidence list. Enriches doorbell_nobody_home, night_motion_nobody_home, and security_coverage_gap alerts with structured occupancy data. Occupancy card on /status/ shows state, confidence, empty duration, last motion, and evidence chips. occupancy block in status.json.
Structured backend loggingDEV15 (v3.33.0 “Verbose”): Always-DEBUG Python logging to stderr captured by journald. Per-detector counts, run summary (insights/alerts/warns/snoozed/elapsed), named exceptions replacing bare except:pass. journald retention: 30d max, 500MB cap, compressed. Filter at read time: journalctl -u greenacres-intelligence -p info for summary, default for full detail. ~5KB/day compressed at DEBUG level.
Proactive intelligencePatio camera battery trend detection (QW28). Visitor insights enriched with house-empty duration and camera coverage (QW29). Camera auto-recovery: HA integration reload for cameras offline 30–90 min with no hardware cause — mirrors V-A3 auto-restart pattern (V-A7). Introduced v3.28.0.
Platform transparency/dev/ restructured as pure action surface — backlog, physical actions, AI suggestions only. ADRs, Incident Log, and Rejected Alternatives moved to /docs/ sections 13-15. Reference and planning surfaces clearly separated. Introduced v3.29.0.
HA automation advisorWeekly analysis of 7-day event patterns proposes specific Home Assistant automations grounded in observed behaviour: arrival times, security gaps, battery depletion cycles. Each suggestion includes trigger, action, priority, and effort. Introduced v3.30.0.
Web Push alertsNative browser push notifications for new escalation-level alerts. VAPID-signed, delivered via service worker. Works alongside existing HA push. Subscribe/unsubscribe managed per-device on /admin/. Introduced v3.31.0.
HTTP security hardeningSEC7: rate limiting on /admin-api/ (4r/m burst=8). SEC8: CSRF protection via X-Requested-With header. SEC9: X-Frame-Options SAMEORIGIN, X-Content-Type-Options nosniff, HSTS 1yr, Referrer-Policy, Permissions-Policy on all responses. Introduced v3.11.0.
Dev hub authSEC11: /dev/ and /dev/history/ protected by HTTP Basic Auth (shared /admin/ credentials). Backlog items, release planning, and completeness metrics are credential-gated. /dev/backlog.json remains accessible without auth for internal tooling. Introduced v3.14.0.
Tier-2 autonomyV-A3: Pre-authorised auto-restart whitelist. greenacres-watchdog monitors 12 services (Docker containers, HP systemd services, OP services). After 2 consecutive failures, service is auto-restarted and event logged to events.jsonl. /admin/ shows the full whitelist. admin-api exposes /autoreset/whitelist. Introduced v3.17.0.
Event deduplication/events/ groups identical alerts by headline+category+severity. Each unique event shows the most recent timestamp, a ×N recurrence badge, and elapsed duration (e.g. ×12 · 3d). Event count shows unique vs total. Introduced v3.13.0.
PWA & Assets PWA manifest deploymentCreates manifest.json with name, theme colour, icons, shortcuts (Status / Controls / Ask HAI). Links manifest to all hub pages. Required for iPhone Add to Home Screen installability.
PNG icon generationGenerates icon-192.png and icon-512.png from pure Python (stdlib only — struct + zlib). No Pillow or external deps. Emerald house mark on Deep Forest background. Runs on HP via sudo python3.
Bulk asset updatesPython script pattern: read all 11 page paths, apply string replacements (palette hex, SVG gradients, manifest tags, sidebar labels), write atomically. Used for logo updates, palette migrations, nav changes.
Releases & Docs Release sequence (5 steps)1. Update /dev/ Recently Shipped + mark Done items. 2. Update /ai/releases/ hero card + history row (MANUAL — never auto). 3. Update /ai/ capabilities + /docs/ if architecture changed. 4. Run greenacres-release (auto-updates /releases/, sidebars, /dev/ last-release). 5. Verify all pages HTTP 200 + /ai/releases/ shows new version.
Author release notesWritten from changes made in session. Versioning: minor bump per session release.
Update /releases/Hero card, history table, total count, codename, date — all updated atomically via greenacres-release.
Update /dev/ backlog + todoMoves items between Backlog, Recently Shipped, and CTO Vision. Labels each as Platform or AI Agent. Recently Shipped updated every session — never left stale.
Intelligence Engine Add new insight detectorsStandard pattern: write detect_X_insights(status, state, durations, baselines) function returning insight() objects, append to DETECTORS list. Used today for consumable tracking (printer ink + Claude credits). Engine auto-runs every 5 min via systemd.
Portal live data panelsAdds real-time data rendering sections to hub pages: fetch status.json, filter by severity/category, render with colour-coding. Deployed Active Insights panel on /status/ today — hidden when clear, visible on alert/warn.
ntfy.sh push notificationsCAP-5: Self-hosted ntfy container (port 8769, nginx proxy at /ntfy/). Intelligence engine calls ntfy_push() alongside HA mobile app for every P1/P2 alert. P1 = urgent priority + rotating_light tag; P2 = high priority. Credentials from /etc/maintain-all.conf. Subscribe: ntfy iOS app → server hp.tailabbaf3.ts.net/ntfy, topic greenacres-alerts. Introduced v4.0.15.
Motion activity density panelMotion density score computed by querying InfluxDB ha_binary measurement for 24h per-sensor event counts (excludes duplicate _motion_motion sensors). Rendered as per-sensor bar chart in Security tab, sorted high-to-low, with active-now highlights. motion_density block written to status.json every intelligence run. Introduced v4.0.13.
Offsite backup + UPS pre-wiringV-P3: rclone installed, greenacres-backup script syncs HA config, web, nginx, and greenacres state weekly (Sun 03:00 timer). Activate by setting RCLONE_REMOTE= in /etc/maintain-all.conf. NET-3: NUT (Network UPS Tools) installed and pre-configured for APC UPS — activate when hardware arrives. Introduced v4.0.32.

6. Data Sources Updated: v4.0.32

SourcePath / EndpointFreshnessUsed For
status.json/srv/www/intranet/status.json60 sCTO briefing, bug investigation, lock / thermostat / health reads
history.json/srv/www/intranet/history.json15 minTrend analysis, analytics page validation, 30-day performance review. 16 series (hp/op load/mem/temp/disk, pihole, lock battery, room temps).
hai_briefing.json/srv/www/intranet/hai_briefing.json2×/day + alertIntelligence summary, briefing quality checks, health score context
HA REST APIhttps://192.168.0.10/ha-api/ (nginx proxy)Real-timeLive device state, service calls (lock, thermostat, scene)
Starling Hub APIhttp://192.168.0.25/api/Real-timeThermostat targets/actuals (2 units), camera online state, Protect CO/smoke
InfluxDBdocker exec influxdb influx queryReal-timeHistorical metrics beyond 7-day window. 11 measurements, 60s cadence.
Persistent memory~/.claude/projects/-Users-arash/memory/PersistentProject state, backlog, preferences, SSH config, operator feedback, prior decisions
systemd journaljournalctl -u greenacres-*Real-timeService failure diagnosis, timer confirmation, error pattern investigation
nginx access/error logs/var/log/nginx/Real-time404 investigation, proxy errors, SSE connection issues

7. Memory System Updated: v4.0.32

Persistent file-based memory at ~/.claude/projects/-Users-arash/memory/ on Mac. Indexed via MEMORY.md, which is loaded automatically at every session start. Four types: project (state/backlog), feedback (working preferences), user (operator profile), reference (external resource pointers).
FileTypeContents
project_greenacres_plan.mdprojectMaster backlog, all completed phases, session history, infrastructure status. Read every session.
project_greenacres_servers.mdprojectFull server state, services, credentials reference, Starling Hub API details.
project_greenacres_vision.mdprojectExecutive vision, CEO design principle, 5-phase programme (Stabilise → Transcend).
project_greenacres_layout.mdprojectRoom-by-room floor plan, device locations, both floors.
project_greenacres_wifi.mdprojectAP MACs/IPs/channels, Omada settings decisions, channel optimisation history.
feedback_cto_mode.mdfeedbackCTO mode trigger behaviour, briefing format, SSH check command.
feedback_model_selection.mdfeedbackSonnet default for all operations. Opus only for deep architectural reasoning.
feedback_portal_workflow.mdfeedbackMock-up first in standalone HTML before touching any production page.
feedback_ssh_op_via_hp.mdfeedbackSSH credentials, key paths, fail2ban whitelist details for both servers.
feedback_omada_api.mdfeedbackVerified OC200 v6.2 API endpoints, known silent bugs.
feedback_token_usage.mdfeedbackToken and credit conservation rules — batching, compacting, no exploratory calls.

8. Guardrails & Security Updated: v4.0.32

GuardrailBehaviour
Authorise before executeAll production file writes, service restarts, nginx reloads, and new deployments require explicit confirmation. Agent states the exact change and waits. No implicit approval accepted.
Mock-up firstAll UI / portal changes prototyped as standalone HTML on Mac before touching any production page. Prevents costly in-place iteration on 1900-line files.
Verify after every changeRe-reads file or re-polls status.json after every deployment. Does not mark a task complete until verified.
No destructive actions unaskedWill not force-push, reset --hard, drop data, or delete files unless explicitly instructed. Investigates unknown state before overwriting.
No undiscussed infra changesNetwork, DNS, firewall, and routing changes always go through Research → Plan → Authorise → Execute → Verify. No silent changes to shared infrastructure.
Token conservationBatches SSH calls. Targeted searches. Compacts context on long sessions. Does not re-read files already in context. Template HAI engine used until API credits restored.
Credential handlingAPI keys (HA token, Starling key, HAI key) read from server config files via SSH and never stored in memory files, code, or hub pages.

9. Config & File Reference Updated: v4.0.32

Files the Agent Reads
FileLocationPurpose
status.json/srv/www/intranet/Primary live state source. All briefings, diagnostics, and data-accuracy checks start here.
history.json/srv/www/intranet/14 time-series, 30-day rolling window. Used for trend analysis and analytics page validation.
events.jsonl/var/lib/greenacres/90-day rolling event log (alert/warn insights). Loaded by Ask HAI for historical context. ~50KB/day max. Pruned on each intelligence run.
snooze.json/var/lib/greenacres/Per-alert snooze state. Written by admin-api on POST /snooze. Read and expired entries pruned by intelligence engine each run. Format: {insight_id: {until, hours, reason, snoozed_at}}.
greenacres-morning-push/usr/local/sbin/Daily 07:05 briefing push to iPhone via HA notify. Reads status.json, summarises health + alerts in 5 lines. systemd timer: greenacres-morning-push.timer.
hai_briefing.json/srv/www/intranet/Latest HAI briefing including health scores, headline, narrative, context summary.
hai.conf/etc/hai.confClaude API key for HAI LLM briefings. Currently depleted — template engine active.
starling.conf/etc/starling.confStarling Hub Bearer API key. Used by greenacres-intelligence to pull thermostat + camera data.
ha-token.conf/etc/ha-token.confHome Assistant long-lived access token. nginx injects as Bearer header on /ha-api/ proxy.
intranet-https.conf/etc/nginx/sites-enabled/nginx routing config: TLS, hub pages, /ha-api/ proxy, /events SSE, JSON file aliases.
MEMORY.md~/.claude/projects/-Users-arash/memory/Memory index. Loaded automatically. Contains pointers to all 11 memory files.
Files the Agent Writes
File / PathLocationWritten When
memory/*.md~/.claude/projects/-Users-arash/memory/Every session. project_greenacres_plan.md updated with completed work. New feedback/reference files created as needed.
index.html + all sub-pages/srv/www/newsite/*/On hub changes, nav updates, version bumps, or new page deployments. Via SCP + sudo.
docs/index.html/srv/www/newsite/docs/Every release. Platform Docs updated to reflect new architecture, schemas, services, and release history.
ai/index.html/srv/www/newsite/ai/Every release. Agent reference updated to reflect new capabilities, access changes, and version history.
dev/index.html/srv/www/newsite/dev/Every session with backlog or todo changes. Items labelled Platform or AI Agent, moved between states.
releases/index.html/srv/www/newsite/releases/Every release. Hero card, history table, total count all updated atomically.
*.py scripts/tmp/ (transient) + /usr/local/sbin/ (persistent)Deployment scripts written to /tmp/ during session, removed after use. Maintenance scripts persist in /usr/local/sbin/.

10. Operational Track Record Updated: v4.0.32

MetricValueNotes
Current platform versionv4.0.32 “Prism”Computed from status.json. Single source of truth, updated every 5 minutes.
Total releases shipped164+From v1.0.0 (2026-04-01) through v4.0.32 (2026-05-03). Complete history at /releases/.
Platform sessions50+ sessionsFrom initial deployment through current consolidation phase (Sprints 1-5).
Container health6/6 healthyhomeassistant, ha-filebrowser, mosquitto, influxdb, grafana, ntfy. Auto-restart active. No downtime since v3.5.0.
Data freshness≤5 minutesstatus.json updated every 5 minutes by greenacres-intelligence. Linter verifies freshness every run.
API credit status73% availableReal-time tracking via status.json credit_forecast. Fallback template engine active when exhausted.
Production regressions (v3.0+)3 fixedv4.0.23: ask-cto crash (undefined function get_sov_mode). v4.0.22: intelligence NameError. v4.0.21: billing detection. All resolved.
SSH reliabilityStable since v1.5.0Key auth confirmed 2026-04-05. Both servers (HP, OP) accessible every session. Passwordless auth enabled.
Memory system30+ files, currentPersistent knowledge base. All project state, feedback, and reference docs updated at session close.
Documentation coverage~90%/docs/ + /ai/ comprehensive. Gap: some admin-api endpoints not documented yet (Sprint 4.7 planned).

11. Agent Release History Updated: v4.0.32

Platform Ver.Agent ChangesDate
v4.0.23 “Signal”Hardening: full code review of 5 core scripts. 3 crash bugs fixed (ask-cto get_sov_mode NameError, intelligence severity ValueError, influx atomic write). PAM pam_lastlog.so removed. logrotate added. matter-server container live. Backup timer running. BUG-RENDER-1 closed. Doc surfaces updated.2026-04-24
v4.0.22 “Signal”Crash fix: NameError in push_alerts_smart() (urgent/rotating_light bare names). Intelligence deduplication ValueError fixed. net_state.json atomic write. PAM pam_lastlog silenced.2026-04-23
v4.0.21 “Signal”New P1 billing insight: Claude API credit exhaustion detected via flag file. HAI improved error handling (HTTP 400 body parsed, flag written). ask-cto get_sov_mode() function added (was crashing every /ask request).2026-04-23
v4.0.20 “Signal”Occupancy-aware suppression (SUGGEST-10): P3/P4 non-security alerts silenced when house empty >2h. SOV-2: tiered model routing at 50/80/95% credit. HAI morning/evening timers re-enabled. Intelligence log spam silenced.2026-04-23
v4.0.19 “Signal”Alert fatigue: fence/buddy/coverage-gap permanently suppressed. P3 72h auto-snooze. PHYS-2 7-day snooze. GLOBAL_SUPPRESS for intentionally offline cameras.2026-04-23
v4.0.18 “Signal”SOV-1: Ask HAI upgraded from Haiku to Sonnet. Auto-downgrades to Haiku at 95% week usage; template fallback at credit exhaustion.2026-04-21
v4.0.17 “Signal”BUG-RENDER-1 closed via Puppeteer MCP: /ai/ and /docs/ confirmed fully rendering in browser. Style tag fix (unclosed tags). Puppeteer MCP installed.2026-04-21
v4.0.32 “Signal”V-P3 + NET-3: rclone backup script (weekly Sun cron) + NUT UPS pre-wired. All 13 doc sections updated.2026-04-20
v4.0.15 “Signal”CAP-5: ntfy.sh self-hosted push container on port 8769. Secondary push alongside HA mobile app for P1/P2 alerts.2026-04-20
v4.0.14 “Signal”ENG-1: Laundry status + energy cost in portal Climate tab. CAP-8: all-device battery grid (28 sensors) in Security tab.2026-04-20
v4.0.12 “Signal”CAP-4: Live camera snapshots in portal via HA proxy. Bearer token server-side. Auto-refresh on status.json update.2026-04-20
v4.0.11 “Signal”Portal Batteries panel: all 28 devices colour-coded by tier, sorted worst-first.2026-04-19
v4.0.10 “Signal”Credit alert false positive fix. Intelligence deduplication improved.2026-04-19
v4.0.9 “Signal”SUGGEST-9: credit burn forecast + portal credit bar. Motion density dedup.2026-04-19
v4.0.8 “Signal”CAP-7: motion density + room temp trends. Alert fatigue scoring. Vision timer re-enabled.2026-04-19
v4.0.5 “Vigilant”PRES-1 complete: binary_sensor.arash_wifi_home feeds ha.presence in status.json (wifi_home field appended when SSID=Greenacres). Patio + Driveway cameras confirmed charging. Stale Wemo OrangePi switch entity disabled. greenacres_influx_write patched with pre-loop WiFi state lookup. Total shipped: 107.2026-04-19
v4.0.3 “Vigilant”PRES-1: sensor.arash_ssid re-enabled (was disabled_by:user), device_tracker.arash_wifi template added, wired into person.arash_foroozandeh as second presence source. BUG-MAINT-1 closed — avahi removal resolved HA mDNS conflict. Release/dev-render scripts patched to handle backlog items using id field (no ref). Total shipped: 107.2026-04-19
v4.0.2 “Vigilant”Estate Audit formalised as 11-step reusable procedure (servers, Omada, Starling, Hue, DNS, HA, Mosquitto, InfluxDB, Grafana, latency). HK-2: Bold lock battery sensors in HomeKit via template string→numeric conversion + linked_battery_sensor. BUG-MAINT-1 closed (avahi removal resolved HA mDNS conflict). Quick wins: HK-1/HA-14/HA-15 closed. Total shipped: 105 items.2026-04-19
v4.0.1 “Vigilant”INV-1: Yale lock entity confirmed as lock.front_door_lock (display name slug). INV-2: Landing thermostat confirmed as climate.landing_thermostat_thermostat (Starling appends _thermostat). Full infrastructure audit: all 16 reachable systems mapped, capability gaps documented (Aqara/Bold/Yale no local API, MQTT $SYS enabled, Omada client list scope gap). Starling API patterns saved to memory.2026-04-19
v4.0.0 “Vigilant”Full performance review: CPU governor set to performance (persistent service), nginx gzip fully configured (all MIME types), avahi removed (HA mDNS conflict), udisks2/e2scrub_reap/matter image removed (161MB freed), journal vacuumed (153MB freed, retention 200M/1week). Watchdog grace period heredoc fixed. Total shipped: 100 items.2026-04-19
v3.9.0 “Transparent”UAT1/UAT2/UAT7/DEV14: Live health transparency across 13 pages — amber banner on stale status.json, HAI fallback indicator, connection-lost overlay, last-refreshed timestamp on /dev/. Platform hardening and observability uplift.2026-04-18
v3.8.0 “Digital Twin”TWIN-1: Open-Meteo weather integration — 12h forecast, storm/rain/wind detection, camera battery storm-awareness, weather block in status.json. Login system: PAM auth for Linux users (arash), POST /login path bug fixed, python3-pam installed. Platform v3.41.1 + v3.42.0. Total shipped: 60 items.2026-04-13
v3.7.0 “Occupancy”SUGGEST-9: compute_occupancy_context() from geofence + motion sensor state tracking. Confidence-rated (high/medium/low) with evidence list. Enriches doorbell/night-motion/coverage-gap alerts. Occupancy card on /status/ and occupancy block in status.json. Full code review: 6 bugs fixed (camera recovery cooldown now persisted, dead imports removed, health scores parameter, snooze write consistency, front door escalate logic). All documentation updated to reflect v3.35.0 platform state.2026-04-13
v3.6.0 “Forecast”SUGGEST-6: compute_battery_health() unified drain-rate model. Covers patio camera, driveway camera, front door lock. Warns 14 days before critical, alerts at 3 days — based on drain rate, not level. Battery Health table on /status/. battery_health block in status.json per intelligence run.2026-04-13
v3.5.0 “Verbose”DEV15: Python logging module added to greenacres-intelligence and greenacres-admin-api. Always DEBUG to stderr/journald — zero management overhead. Per-detector insight counts, run summary (alerts/warns/snoozed/elapsed), named exceptions replacing bare except:pass. journald retention: 30d, 500MB cap, compressed.2026-04-13
v3.4.0 “Quiet”SUGGEST-10: 6h dedup window replaces 4h. Per-alert snooze (4h/24h/7d) via admin-api — suppresses insight from status.json and push. Alert fatigue scoring (0-100, 14d lookback) with top 10 noise sources in /admin/. alert_fatigue block in status.json.2026-04-13
v3.3.0 “Control”Admin API: greenacres-admin-api on port 8767 (localhost, nginx-proxied). Docker container restart and log viewer in /admin/. VAPID web push (V-M2): subscriptions, greenacres-push script, push alongside HA notify. Automation suggestions (V-A6): weekly Claude Haiku analysis of event patterns proposes specific HA automations.2026-04-12
v3.2.0 “Insight”Security coverage gap detector, Starling battery intelligence, intel_meta card on /status/, HAI briefing card via Promise.all. Live SVG network topology (V-D6), chart picker on /dev/ (V-D5), proactive visitor insights enriched with empty duration + camera context, camera auto-recovery (V-A7).2026-04-12
v3.1.0 “Memory”90-day events page (/events/) with severity/category/time filters. Auto-restart whitelist (V-A3): 12 services monitored, events logged. /status/ health scores, presence card, Pi-hole stats, binary sensor cards, network health, lock + thermostat live data.2026-04-12
v3.0.0 “Context”Tailscale VPN + TLS (V-P1). Basic Auth on /admin/, /dev/, /dev/history/. PWA offline caching (V-M3). WAN bandwidth chart (V-C2). CSRF protection on admin-api. Morning push 07:05 (V-A2). Ask HAI (/help/) with live status.json context. greenacres-release automation: one command updates all pages + versions.2026-04-10
v2.7.0 “Polish”Full CTO platform audit — all services, data, and integrations verified. Analytics sparklines updated to new palette. PWA foundation: manifest.json + icons linked — site installable on iPhone. Design System v3.0: Greenacres Dark palette, dark/light mode, @property rings, View Transitions API, Speculation Rules. HAI briefings (07:00 + 19:00 + escalation). Consumable detector (printer ink + Claude credits).2026-04-10
v2.6.0 “Design”Design System v3.0. Greenacres Dark palette (Deep Forest #0a110d, Emerald #10b981). Dark/light mode device-linked. @property rings, View Transitions API, Speculation Rules, content-visibility. HA notification overload fixed: push_alerts_smart v2 policy. New consumable detector: printer ink + Claude API credits. Active Insights panel on /status/.2026-04-10
v2.5.0 “Event”V-P4 30-day history, V-P9 90-day event log, V-P5 predictive maintenance (camera battery trend + OP disk), V-P6 OP monitor :8080, V-A2 morning push 07:05 daily briefing.2026-04-10
v2.4.0 “Push”V-P2 iOS push via HA notify. push_alerts_smart v1 per-alert cooldown. push_sent.json tracking. Morning push systemd timer deployed.2026-04-10
v2.3.0 “History”History extended to 30 days. 90-day events.jsonl rolling log. Analytics labels updated.2026-04-10
v2.2.0 “Design”Design system v2.1 deployed. Full CSS overhaul — 5-level surfaces, global page-hero, heading scale, custom scrollbars, focus-visible, shadow/badge system. Design programme (UX1–UX5) added to /dev/ as P1 priority. All 11 hub pages updated.2026-04-10
v2.1.0 “Ask”Ask HAI deployed at /help/. Full chat UI with live system context. Backend service (greenacres-ask-cto) on :8766 with nginx proxy. Calls Anthropic API with status.json context. Graceful offline state — ready to activate on credit top-up. AI1 backlog item closed.2026-04-10
v2.0.0 “Craig”greenacres-release automation deployed. Craig principle adopted: platform documents itself on every push. One command updates all 11 page version badges, both release pages, and /dev/ last-deploy note. Ask HAI added to backlog (AI1). /dev/ page updated with self-updating doc principle.2026-04-10
v1.9.0 “Sync”Full agent documentation published: /ai/ with 12-section reference (this page). Access & Authentication table, Config & File Reference, Operational Track Record, Strategic Roadmap all added. Memory system coverage documented. /dev/ page for development tracking. Data accuracy bugs B1/B2/B3 fixed.2026-04-09
v1.8.0 “Hub”HA API proxy deployed (/ha-api/) — agent can now call HA services via hub pages. HAI briefing wired to hub home bulletin. Agent maintains /ai/ and /docs/ on each release. Hub sub-pages (Controls, Analytics, Status, Admin) fully built.2026-04-08
v1.7.0 “Starling”Starling Hub fully integrated. Agent reads thermostat (2), camera, and Protect data in every session. CTO Capability Report (HTML+PDF) generated. Starling conf documented in memory.2026-04-07
v1.6.0 “Vision”HAI comfort scoring bugs fixed (abs penalty removed, hvac_mode vs hvac_state corrected). Lighthouse 100/100/100 on hub. Executive vision document written.2026-04-07
v1.5.0 “Roaming”Full infrastructure hardening. SSH access fixed on both servers. fail2ban whitelisted. Omada, HA, WiFi all hardened. Agent now has verified, reliable SSH access to HP and OP from every session.2026-04-05
v1.4.0 “Intelligence”HAI Phase 8a + 8b deployed. Template engine introduced as zero-cost fallback. Agent now generates briefings autonomously at 07:00 and 19:00 via systemd timers. Z-score anomaly detection active.2026-04-05
v1.3.0 “Platform”InfluxDB + Grafana deployed. Agent gained full time-series monitoring data access. 11 measurements writing, 3 dashboards.2026-04-04
v1.2.0 “Harden”Watchdog extended to OP. Agent now monitors both servers and receives Mailjet failure alerts. Backup confirmed at 26 MB.2026-04-03
v1.1.0 “Connect”Monitoring infrastructure and Omada integration established. Agent gained network device visibility.2026-04-02
v1.0.0 “Stabilise”Agent established as primary technical operator. Initial platform stabilisation. SSH access, Docker, systemd timers all operational.2026-04-01

12. Strategic Roadmap Updated: v4.0.32

CTO-proposed capability improvements. None are authorised. Full rationale and dependencies at /dev/.
RefCapabilityHorizonImpact
TWIN-1Digital Twin — Open-Meteo weather + storm camera managementShippedv3.42.0: 12h forecast from Open-Meteo (free, no key). Storm/rain/wind detection. Camera battery storm-awareness. Weather block in status.json.
SSO-1Sign in with Apple / Google OAuth for external accessNearReplace session cookie auth with Apple ID / Google OAuth. Required before exposing portal to internet publicly. Session cookie auth (v3.41.0) is the LAN bridge until this ships.
INT-1Claude Console integration — prompt library, usage analytics, batch APINearPrompt library for greenacres-hai (versioned prompts without code deploys). Usage analytics per script. Batch API for cost reduction.
OCC-1Physical occupancy sensors — PIR / mmWave in HANearOccupancy context (SUGGEST-9) currently relies on geofence inference. Physical sensors give ground-truth state. Purchase and configure PIR/mmWave in HA, expose entity IDs to intelligence engine.
V-P3Offsite backup — rclone to B2/S3NextScheduled rclone backup of /var/lib/greenacres/ (state, backlog, events) and /srv/www/intranet/ to B2 or S3 Glacier. Config in /etc/greenacres-backup.conf. Systemd timer weekly. Restore procedure documented. Blocked pending B2/S3 credentials from operator.
V-D1Ask HAI multi-turn conversation historyNextAsk HAI currently loses context between messages. Add session-scoped conversation history array in the backend. Each exchange appended, sent to Claude as messages[] array. Context-aware follow-up questions answered coherently. ~30 min to ship.
V-D2Ask HAI offline mode — cached template answersNextWhen credits exhausted, Ask HAI currently shows offline. Add template fallback: route common question patterns (lock state, thermostat, alerts) to status.json answers without Claude. No API call required. Graceful degradation.
V-D3Admin — one-click container restart + log viewer1 monthAdd container restart buttons and last-50-line log viewer to /admin/ page. Backend: POST /admin-api/restart/{name} and GET /admin-api/logs/{name}. Only accessible on LAN. Eliminates SSH for routine ops.
V-D4Ollama local LLM — zero-cost intelligence briefings3 monthsDeploy Ollama on HP for local LLM inference. Replace template HAI engine with local model (Llama 3 8B or Mistral). HAI briefings resume at zero API cost. Ask HAI gets offline-capable reasoning. Requires RAM headroom assessment.
V-D5InfluxDB explorer in portal3 monthsAdd /analytics/explore/ page — select measurement, field, time range, render chart. Direct Flux query via backend. Replaces SSH for ad-hoc data exploration. CEO-friendly self-serve analytics.
V-D6Network topology map3 monthsVisual floor-plan-based network map on /status/ or new /network/ page. Nodes: HP, OP, APs, key IoT devices. Edges: connection + signal quality. Data from Omada API + status.json network array.
V-A5Claude as reasoning engine — full context analysis3 monthsWhen credits restored: upgrade intelligence engine to send full status.json to Claude hourly. Outputs structured JSON: anomaly explanations, automation suggestions, risk flags. Ask HAI gets deep historical context. HAI becomes interpretive, not template-driven.
V-A1Restore LLM-authored HAI briefings (API credit top-up)1 monthBriefing quality upgrade. Context-aware anomaly narratives replace template output. ~$10 at console.anthropic.com.
V-A4Agent evaluation framework6 monthsQuantitative performance data for CEO reviews: session success rate, briefing quality scores, task error rate, data freshness SLA.
v4.0.5  ·  Written and maintained by the AI agent  ·  claude-sonnet-4-6
Platform Docs → Dev & Backlog → Releases →