WiqAIa+ Implementation Plan — Overview
Audience: the WiqAIa+ engineering team (Melissa + cloud engineer + AI engineer + AI sub-agents). Read this first. Everything else in docs/plan/ is detail behind what’s framed here.
Status: Living document. Update it when reality changes.
1. What we’re building
WiqAIa+ is an AI-powered control room platform for buildings in Saudi Arabia. It turns existing IP cameras into a 24/7 intelligent safety layer that:
- Detects fire, smoke, crowd hazards, and other anomalies on every connected camera using a tiered AI pipeline.
- Correlates fire-alarm-panel events with live AI analysis of nearby cameras to suppress false alarms (the highest-value capability — Mecca-area incense / bakhoor smoke triggers fire alarms constantly).
- Presents operators with a spatially-aware view of every connected building through a 3D digital twin.
- Routes verified alerts to the right responders (Civil Defence, building managers, fire-department dispatchers) with evidence packages attached.
The platform is multi-tenant by design. Civil Defence is both an end-customer (national HQ view across all connected buildings) and a regulator-style stakeholder. Building owners (hotels, malls, Hajj accommodations, public buildings) are paying tenants.
2. Why this plan exists
The first paying pilot is Saudi Airlines at the Arafat Hajj 2026 site. The Hajj operational window (~May 25 – June 5) is non-negotiable: pilgrims arrive on a date set by the lunar calendar. The platform must be live and stable before they arrive.
We are building from scratch. The prior Electron prototype at C:/Development/WiqAIa/ informs design but is not the build target — the new platform is cloud-deployed, multi-tenant, production-hardened, and architected to scale to thousands of future tenants. (See docs/civil-defence-innovation-submission/ for the planning artifacts and submission docs that informed this.)
The risk profile is unusually severe: both the GCP/CNTXT cloud terms and the customer contract are described as “cut your head off” if we get it wrong. Liquidated damages, billing surprises, data leaks, and missed deadlines all have outsized consequences. This plan is built around protecting the project from those failure modes first, and chasing features second.
3. Operating principles
These govern every decision. When a tradeoff comes up, walk back to these.
- Safety-first AI sensitivity. False negatives are unacceptable; false positives are tolerable. Every tier of the AI pipeline is tuned to over-escalate, not under-escalate. Missing a fire is worse than crying wolf.
- Data sovereignty by design. All customer data — video frames, AI results, incident records, audit logs — stays inside the Kingdom of Saudi Arabia. AI models are self-hosted on GCP Dammam (not Vertex AI). Storage uses customer-managed encryption keys (CMEK) and, where possible, application-layer encryption with keys we hold.
- Cost discipline is a feature, not an afterthought. Budget caps, billing alerts, and quota guardrails are wired in before any GPU spins up. The plan treats cost guardrails as M01 deliverables, equal in weight to code. (Automated kill switches were considered and deferred at pilot scale — see decisions.)
- Production-hardened from day 1. Real authentication, real RBAC, real audit logging, real encryption, real Postgres (no SQLite-then-migrate), real testing. We do not ship a prototype and promise to harden later.
- Plug-and-play abstractions, one production driver per type for the pilot. Every external interface (cameras, fire panels, NVRs, AI models, message brokers) sits behind a clean contract. The pilot ships exactly one driver per slot, but the slot is real. New drivers slot in without code changes elsewhere.
- Test-as-you-build. Every milestone has explicit verification criteria — concrete observable behavior that proves the milestone is done. No milestone is “complete” until its verification passes.
- AI-agent-friendly structure. Tight conventions, named modules, typed wire contracts, explicit dependencies. Sub-agents working on different milestones in parallel should not collide. Code that’s easy for a competent human reviewer is easy for an LLM agent.
- Don’t trust the cloud. GCP/CNTXT’s terms grant them rights over stored data. We encrypt before upload, hold our own keys, and treat the cloud as a hostile transport layer for anything sensitive.
- Simple at the surface, sophisticated underneath. Operators see one button; behind it, the right thing happens. Engineering complexity exists to make operational simplicity possible, not the other way around.
4. Architecture in one paragraph
A small Go edge supervisor runs as a systemd service on one Linux box per building. It hosts a set of Python edge-app containers (camera manager, Tier-0 motion filter, anomaly autoencoder [CPU, ONNX INT8], fire-panel adapter, store-and-forward queue, local dashboard) and maintains a persistent outbound-only mTLS tunnel to the cloud platform. The cloud — running on GKE in GCP Dammam — hosts the multi-tenant API (Node + NestJS), the dashboard (React + Vite SPA, served as static assets), one AI worker service (Python; the Tier-2 multimodal-LLM on a single always-warm L4 GPU node), and the data layer (Postgres + PostGIS, Redis, Cloud Storage with CMEK, Pub/Sub for event distribution). Camera frames flow through the edge filter + autoencoder; flagged frames escalate to the cloud LLM; verdicts trigger spatial correlation against the digital twin (Three.js scene fed by PostGIS) to identify cameras with line-of-sight to alarm zones; correlated evidence packages drive alerts to operators and to a dedicated fire-department view. (Architecture revised 2026-05-13 from a 3-tier to a 2-tier pipeline; see docs/plan/01-architecture-summary.md §0.)
See docs/plan/01-architecture-summary.md for the locked-in tech stack and rationale, and docs/architecture/ for ADRs as they’re written.
5. Locked-in tech stack (summary)
Full table and rationale in docs/plan/01-architecture-summary.md. The short version:
| Layer | Choice |
|---|---|
| Frontend (all dashboards) | React + Vite (SPA) |
| Cloud API | Node + TypeScript + NestJS |
| Edge supervisor | Go (single static binary) |
| Edge application containers | Python |
| AI worker (cloud) | Python + vLLM (Tier-2 multimodal LLM, one always-warm L4) |
| AI on the edge | Python + OpenCV + ONNX Runtime (Tier 0 motion filter + anomaly autoencoder, CPU only) |
| Database | PostgreSQL 15 + PostGIS (Cloud SQL Dammam, HA + read replica) |
| Cache + sessions | Redis (Memorystore) |
| Event bus | Google Pub/Sub |
| Object storage | Google Cloud Storage (Dammam, CMEK) |
| Time-series / analytics | BigQuery |
| Orchestration | Google Kubernetes Engine (Dammam) |
| Media server | MediaMTX |
| Auth / IDP | Keycloak (self-hosted Dammam, leaning) |
| Multimodal LLM | Gemma 4 behind a swappable LLM-provider interface (Gemma 3 / Qwen 2.5-VL as fallbacks; verify Gemma 4 vision-capable before final wiring) |
| Object detection | YOLOv8 demoted out of pilot critical path (2026-05-13); the cloud LLM produces person counts + bounding boxes directly. May return as a parallel metadata feed if LLM person-counting fidelity is insufficient. |
| Edge OS | Ubuntu 22.04 LTS Server |
| Repo layout | Monorepo at wiqaia/, pnpm workspaces + Turborepo |
| Source hosting | Self-hosted Gitea at git.rizoma.sa (in-Kingdom from day 1) |
| Container registry | Google Artifact Registry (Dammam) from day 1 |
| Error tracking | Sentry SaaS for dev/staging; self-hosted Sentry or GlitchTip in Dammam for production |
| Logs / monitoring | Google Cloud Logging + Cloud Monitoring |
| Secrets — runtime | Google Secret Manager |
| Secrets — local dev | .env via direnv, never committed |
6. Guardrails — the things that protect us
Two non-negotiable guardrails. Both are M01 deliverables, before any application code ships:
- Cost guardrails. GCP billing budget caps with alert thresholds at 25/50/75/90/100/110/120%, hard quota caps on critical SKUs (GPU, vCPUs, disks, logging ingestion), daily anomaly-spike detection. Cost estimates accompany every infrastructure change. See
docs/plan/02-cost-guardrails. - Data protection. Encryption-before-upload for sensitive blobs, CMEK on every GCS bucket and Cloud SQL instance, mTLS on every internal connection, tamper-evident audit log with hash chaining, RBAC enforced at both API and database layers. Plan assumes NCA Critical/Sensitive System classification (to be confirmed) and is built to satisfy NCA ECC + CCC controls. See
docs/plan/03-data-protection.md.
These docs are not optional reading for anyone touching infrastructure.
7. Plug-and-play abstractions
The pilot ships one driver per type. The architecture supports more without code changes. See docs/plan/04-abstractions-and-contracts.md.
| Abstraction | Pilot driver | Future drivers slot into the same interface |
|---|---|---|
| Camera transport | ONVIF/RTSP via MediaMTX | NVR-routed RTSP (ONVIF Profile G), Hikvision ISAPI, Dahua RPC, Milestone MIP |
| Fire-alarm panel | BACnet/IP (driver TBD on panel model) | Modbus TCP, Notifier proprietary, EST proprietary, MQTT, contact-closure |
| LLM provider | Gemma 4 (vision verified) | Gemma 3, Qwen 2.5-VL, Kimi, future SOTA |
| Object detector (optional, post-pilot) | None in pilot — LLM produces person counts directly | YOLOv8 (license-resolved), RT-DETR, custom-trained model, vendor-specific |
| Object storage | GCS with CMEK | S3-compatible self-hosted (MinIO), on-prem block storage |
| Identity provider | Keycloak | Azure AD, Okta, customer-supplied SAML / OIDC |
| 3D model format | (TBD, same as Clock Tower modeler) | BIM/IFC, glTF/glb, OBJ, manual extrusion |
The packages/contracts/ package (protobuf + JSON Schema) is the canonical home for these interfaces. Drivers depend on the contracts package; consumers depend on the contracts package; drivers and consumers never depend on each other.
8. Parallel tracks
The work parallelizes across roughly six tracks. Any milestone is assignable to one or more tracks; the dependency graph below tells you what can run concurrently.
| Track | Owner profile | What it covers |
|---|---|---|
| Cloud Infra | Cloud engineer | GCP project setup, GKE cluster, Terraform, CI/CD, secrets, observability, cost guardrails, KMS, networking |
| Backend API + Data | Backend engineer (or me) | NestJS API, Postgres schema + migrations, RBAC, audit log, building/camera/alert services, Pub/Sub plumbing |
| AI Worker | AI engineer | Edge-side Tier 0 + anomaly autoencoder (CPU, ONNX); cloud-side Tier 2 LLM serving; per-camera calibration; prompt templates; LLM provider interface |
| Frontend | Frontend engineer (or me) | Dashboard SPA, FD view, edge-local dashboard, Three.js digital twin, EN/AR + RTL |
| Edge | Whoever has Go + Linux comfort | Edge supervisor (Go), edge-app containers (Python), camera manager, fire-panel adapter, install script, auto-update |
| Integration + 3D | Anyone | 3D model handoff, camera placement UI, fire-zone mapping, site survey playbook, hardware procurement coordination |
Sub-agents can be assigned within any track. Cross-track work goes through the packages/contracts/ package — change a contract, and both sides of the wire follow.
9. Milestone roadmap
Milestones, not days. Each milestone defines what it delivers, how we verify it, and which tracks it occupies. Details live in docs/plan/M01-foundations.md through M10-hardening-and-uat.md.
| ID | Title | What it delivers | How we verify | Dependencies |
|---|---|---|---|---|
| M01 | Foundations | GCP project + Dammam region active, cost guardrails wired (budget caps, alerts, GPU quota cap), KMS keys, monorepo CI/CD running, Artifact Registry, hello-world Docker image per app pushed and deployable to GKE, secrets management bootstrapped, packages/contracts/ published. | A canary deployment of a hello-world API responds via an HTTPS endpoint authenticated by Keycloak (skeleton), is observable in Cloud Logging, and cannot exceed a $1/day GPU spend due to active quota caps. | — |
| M02 | Identity & Authorization | Keycloak deployed in Dammam, User / Role / Permission / UserBuilding schema in Postgres, NestJS auth middleware with JWT + RBAC, MFA scaffolded, login UI in the dashboard. | A test user logs in, receives a scoped token, can access only their assigned building’s resources via the API; non-scoped requests are denied with audit-logged 403s. | M01 |
| M03 | Multi-tenant Data Layer | Postgres + PostGIS deployed (Cloud SQL Dammam HA), full schema for Building / Floor / Zone / Camera / EdgeGateway / Sensor / AnalysisEvent / Alert / AlertAction / AuditLog, row-level security enforcing building scoping, migration system, hash-chained audit log. | A user from Building A cannot read or write Building B’s records even via direct SQL through an API; audit log records every state-changing call and verifies its hash chain on read. | M01 (parallel with M02) |
| M04 | Camera Ingestion & Live Viewing | ONVIF discovery, RTSP connection pool with reconnect-with-backoff, MediaMTX deployed (cloud + edge configurations), WebRTC live viewing in the dashboard, frame extraction at 1 fps to Pub/Sub, camera-online/offline alerting. | An operator opens the dashboard, sees a registered camera’s live feed within 2 seconds via WebRTC; pulling the camera’s network cable raises a camera-offline alert within 60 seconds; restoring it clears the alert. | M01 (parallel with M02/M03) |
| M05 | Edge AI (Tier 0 + anomaly autoencoder) | Tier 0 motion filter (OpenCV frame diff) running in the edge-app container, anomaly autoencoder (CPU, ONNX Runtime INT8) running in the same container — not on a cloud GPU (the original Tier 1 cloud GPU was moved here on 2026-05-13). Per-camera calibration scaffold (48-hour collect → embeddings → K-means clusters → stored baseline). AnalysisEvent persisted to monthly-partitioned Postgres tables for frames that escalate. | A camera that observes no motion produces 0 anomaly escalations; an injected anomaly produces a score >0.7 and an escalation event; the edge container’s CPU usage stays under 30% of one core at 40 cameras × 1 fps. A static camera over 48 hours produces a stable calibration baseline. | M04 |
| M06 | Tier 2 LLM Analysis | Multimodal LLM (Gemma 4, verified vision-capable; else Gemma 3 / Qwen 2.5-VL) self-hosted on one always-warm L4 GPU in GKE Dammam (T4 / A100 not available in-region — verified 2026-05-13). Swappable LLM-provider interface, versioned prompt templates, escalation pipeline from the edge, structured JSON output (threat_detected, confidence, severity, reasoning, false_alarm_likelihood, person_count, detected_objects). | A frame with visible smoke produces a Tier-2 threat_detected=true response with reasoning text within 10s; a frame of an empty corridor produces threat_detected=false. Swapping the model via config flag changes which model serves the next request without code changes. Sustained throughput on one L4: ≥5 inferences/sec with batching. | M05 |
| M07 | Spatial Correlation + Fire Panel + Alerts | 3D model import + per-camera spatial placement UI, PostGIS zone-to-camera lookup, BACnet/IP fire-panel adapter (driver #1), alert engine (rule + AI fusion), AlertAction lifecycle (acknowledge → dismiss → resolve), evidence-package generation. | A simulated FACP zone trigger produces an alert with attached evidence (camera screenshots + Tier-2 LLM verdict) for every camera with line-of-sight to that zone, within the design-target (alarm → operator-visible evidence < 30s). | M03, M06 |
| M08 | Dashboards Polish + FD View | Operator dashboard with 3D twin, camera grid, alert console, KPI panels; fire-department view (stripped down, only relevant cameras + active alerts); bilingual EN/AR with RTL; BI dashboard for operational metrics. | An operator UAT script (full happy-path + a couple of edge cases) executes successfully on a fresh test tenant; FD user sees only what they’re entitled to; Arabic RTL renders correctly throughout. | M02, M04, M07 |
| M09 | Edge Supervisor + Auto-Update | Go supervisor service as systemd unit on Ubuntu, persistent outbound mTLS tunnel to a cloud fleet-manager service, container lifecycle management (pull, run, health-check, blue/green swap, rollback), one-line bootstrap install script, telemetry to cloud. | A fresh Ubuntu box, given the bootstrap one-liner + a one-time token, comes online, registers, pulls and runs the edge containers; pushing a new container version from cloud triggers blue/green update with rollback on health-check failure. | M01 (parallel with M04+) |
| M10 | Hardening + UAT Prep | Production observability dashboards, runbooks (incident response, restart procedures, disaster recovery), backup & restore drill executed, on-prem-GPU contingency dry-run, KPI dashboards meeting the contract’s accuracy & latency targets, training materials for operators. | A scripted DR drill (kill the primary Cloud SQL instance) recovers within RTO; KPI targets verified against a recorded test set; operator training session completes with comprehension check; on-prem-GPU swap exercised end-to-end. | All prior |
10. Dependency graph
M01 ──┬──> M02 ──> M07 ──> M08 ──> M10
├──> M03 ──> M07
├──> M04 ──> M05 ──> M06 ──> M07
└──> M09 ──────────────────────> M10 After M01, M02 / M03 / M04 / M09 can run in parallel. M07 is the integration point; M08 polishes the user-facing surface; M10 closes everything out.
11. Contingencies
We plan for things to go wrong. Three concrete contingencies are wired into the plan from M01, not added when something breaks:
- Dammam GPU shortage. If CNTXT/GCP cannot provision a GPU node in Dammam by the time M06 starts, the Tier-2 LLM worker can deploy to a small on-prem GPU box (Lambda-class workstation or NUC + L4 / 4060-class card, ~$6–15K USD hardware) installed at the customer site, managed by the same edge supervisor. The Tier-2 worker is built with this deployment mode as a first-class option from M01, selected by config — not a last-minute reroute. Same code, different topology. (The edge-side Tier-0 + autoencoder is already on the customer site in both modes.) Detail in
docs/plan/05-contingencies.md. - LLM model swap. Gemma 4 is the target. If it’s not multimodal-capable on release or quality fails our test suite, the LLM-provider interface swaps to Gemma 3 or Qwen 2.5-VL (Apache 2.0, fully permissive) via a single config flag. Test suite includes a fixed set of ~20 evaluation scenarios that every model must pass before promotion.
- CNTXT account delay. If the GCP Dammam account isn’t live by the time we need it, M01 can be completed against a temporary GCP project in another region for dev/staging — never for real customer data. Production deployment is gated on the Dammam account being active; we don’t ship to it before then.
12. Open external dependencies
Resurfaced from Planning/Decisions & Context Log.md and our running reminders. These don’t block the plan but they shape specific milestones — chase them in parallel:
- Fire-panel make/model at the Saudi Airlines Arafat building. Affects M07 driver implementation. Saudi Airlines knows; we don’t yet.
- NVR vendor/model + whether we get access. Affects M04 — camera-direct vs. NVR-routed.
- 3D model file format from the modeler. Affects M07. Assume same as Clock Tower; confirm before delivery so we can request a different format if needed.
- CNTXT / GCP Dammam account activation timeline. Affects M01 critical path. Workaround if delayed: dev/staging in a temporary GCP project.
- Formal NCA classification of the system. Treat as Critical/Sensitive while planning; confirm before any production audit.
- LOA reconciliation. The Letter of Award currently in draft (Al Baddad ↔ Beam Wave) describes a scope materially broader than the actual plan (elevators / access control / PA / firefighting telemetry, on-prem GPU cluster, 100 TB storage server, etc.). Must be revised before either party signs or Beam Wave is contractually bound to deliver something different from what we’re building, with liquidated damages at 0.5%/day. Melissa is aware and chasing.
13. How to use this plan
- Read
00-overview.md(this file) first. - Then
01-architecture-summary.mdfor the tech stack rationale. - Then
02-cost-guardrails.mdand03-data-protection.mdbefore touching any infrastructure. Non-optional. - Then
04-abstractions-and-contracts.mdto understand the interface boundaries. - Then
05-contingencies.mdfor the on-prem-GPU / LLM-swap / CNTXT-delay fallbacks (these shape M01 + M05 + M06 decisions). - Then the milestone files (
M01-…throughM10-…) for the work itself. Each milestone file follows a consistent template: Goal · Tracks · Deliverables · Verification · Risks · Open questions. - Operational details (deployment runbooks, incident response, recovery procedures) live in
docs/runbooks/as they’re written, not in the plan.
This plan is a working document. If you find something out of date, fix it in place rather than working around it.