RAIA™ Specification

Private Specification

RAIA™ (Real estate Artificial Intelligence Agent) Protocol Security Private Specification This document contains proprietary B2B property management protocols and agentic swarm blueprints. For security and

← Back to Developer Hub TEXTBOOK SPECIFICATION
RAIA™ (Real estate Artificial Intelligence Agent) Specification

RAIA™ (Real estate Artificial Intelligence Agent) Protocol Security Private Specification This document contains proprietary B2B property management protocols and agentic swarm blueprints. For security and

🧩 Section A: In Plain English

Map Pin Architecture & BigQuery Speed Optimization

Like a private detective agency with a massive filing cabinet of GPS coordinates, this system retrieves and displays thousands of property map pins on the dashboard without slowing down — using BigQuery optimization.

RAIA™ (Real estate Artificial Intelligence Agent) Specification

Map Pin Architecture & BigQuery Speed Optimization

Let’s explain this with a simple analogy. Imagine we are running a private detective agency. We have a massive, super-smart filling cabinet (BigQuery) that stores the exact GPS map coordinates of every single property in our country. We want to show these properties as dots on a giant wall map (our dashboard). But there are three catch points:

← Back to Developer Hub TEXTBOOK SPECIFICATION

1. ELI5: How Does the Map Load Instantly?

Concept For Humans

Let’s explain this with a simple analogy. Imagine we are running a private detective agency. We have a massive, super-smart filling cabinet (BigQuery) that stores the exact GPS map coordinates of every single property in our country. We want to show these properties as dots on a giant wall map (our dashboard). But there are three catch points:

1

No Peeking! (Security)

We are a B2B platform. Agency A must never see Agency B's secret leads (like Farming or Lost properties). Our giant coordinate table has no "owner" labels. To keep it safe, the server acts as a guard. It first checks your ID badge, fetches a whitelist of properties your agency owns, and then whispers only those specific dots to your screen.

2

The Webhook Hot Path

Normally, a heavy robot sweeps through the entire database at midnight to rebuild the map table. But what if you edit a property name at 2:00 PM? You don't want to wait until midnight! We built a "hot path" webhook. The instant you click save, a target laser deletes just that single property from BigQuery and inserts its fresh details in 1 second.

3

The Speed Cheat Sheet

Why is it so fast? First, we don't load property pictures (thumbnails) when drawing the pins. We draw the pins instantly and fetch pictures in the background. Second, if a house is listed for rent AND sale, we don't draw overlapping duplicate pins; SQL magic merges them into one clean pin before sending.

2. Architectural Visualizations

Inline Interactive SVGs

A. Multi-Organisation Security Scoping & Pin Retrieval (ADR-097)

How `/api/pins` resolves roles, overrides default Supabase query limits, and injects scopes as whitelists into BigQuery parameter vectors.

Operator Client (Private Dashboard) GET /api/pins Cookie: Session JWT ❌ No Org ID passed HTTPS Request Next.js API (/api/pins) 1. Server-Side Guard Resolves role & orgId via DB Profile Lookup 2. Supabase Asset Lookup Enforces .limit(5000) (Bypasses default 1k truncation) 3. Parameterize SQL Injects Whitelist: @asset_ids Fetch IDs Supabase PG tbl_assets Authoritative Relational Query with @asset_ids BigQuery raia.spatial.map_pins SQL FILTER: asset_id IN UNNEST (@asset_ids)

B. Two-Speed ETL Architecture (Nightly Load vs Webhook Hot Path)

Comparing the heavy-duty nightly sync (optimized via Load Jobs) and the real-time hot path updates (optimized via single asset DML queries).

Supabase DB vw_assets vw_listings_rent Authoritative CRM State 1. Nightly Sync (04:00 AM) Full Dataset Rebuild sync-pins.js (ETL) Loads as NDJSON File TRUNCATE + WRITE_APPEND 2. Webhook Hot Path Triggered on Save (1s) /api/webhooks/asset-updated DELETE single asset_id INSERT fresh asset rows No Streaming Buffer Locks! BigQuery spatial.map_pins Loaded & Ready Sub-second Read

3. Technical Deep Dive

For Developers

A. Multi-Tenant Org Scoping without DB Pollution

Standard multi-tenant models pollute every single table with an organisation_id column. In BigQuery, our spatial datasets (specifically map_pins) are intentionally general-purpose, optimized for geography rather than tenancy. Keeping them decoupled prevents database drift and lets us run global spatial calculations without cross-org table contamination.

To secure the data on retrieval, the /api/pins endpoint acts as an active security mediator:

  1. The API never trusts a client-passed role or organisation identifier. It reads the caller's session token directly from the request headers/cookies.
  2. It looks up the user's verified profile in Supabase to extract their true role and organisation_id.
  3. If the user is an operator or branch manager, the API executes a server-side query on Supabase tbl_assets to compile a clean array of all asset IDs belonging to their organization.
  4. This array is passed to BigQuery as a parameter (@asset_ids), restricting the results instantly via: AND asset_id IN UNNEST(@asset_ids).
⚠️ Critical Optimization: Supabase PostgREST default limit override

Supabase enforces a strict default pagination limit of 1,000 rows. Our core Rescue Live Full (Sovereign Node) organization currently owns

Repository Code

The live codebase implementation for this specification sits within the following repository folder:

ong>1,491 assets. A standard .select("asset_id") query would silently truncate at 1,000, leaving out 491 properties from the map! The API explicitly overrides this with a 5,000-row buffer:

const { data: assets } = await supabaseAdmin
  .from("tbl_assets")
  .select("asset_id")
  .eq("organisation_id", orgId)
  .limit(5000); // Override default 1000 page size

B. The Webhook Hot Path vs Streaming Buffer Locks

Under standard BigQuery setups, developers push real-time updates via Streaming Inserts (table.insert()). However, this creates a major architectural flaw in active systems:

"Rows written via Streaming Inserts enter a temporary write buffer. These rows cannot be modified or deleted by Data Manipulation Language (DML) queries (like DELETE or UPDATE) for up to 90 minutes. Attempting to delete them throws a streaming buffer error."

This poses a serious challenge for our real-time updates. If an operator edits a property, and then edits it again 5 minutes later, the secondary webhook would fail with an active lock!

How RAIA (Real estate Artificial Intelligence Agent) (Real estate Artificial Intelligence Agent) (Real estate Artificial Intelligence Agent) (Real estate Artificial Intelligence Agent) solves this:

  • Nightly Batch ETL: The nightly sync script (sync-pins.js) compiles an NDJSON file, runs a TRUNCATE TABLE query, and loads the data via a formal BigQuery Load Job (table.load()). Load jobs write directly to permanent storage, bypassing the streaming buffer entirely.
  • Real-time Webhook Hot Path: Our webhook endpoint (/api/webhooks/asset-updated) is triggered on Supabase inserts, updates, and deletes. It executes a clean, standard DML DELETE FROM map_pins WHERE asset_id = @asset_id query (~1.5s execution) followed immediately by a DML INSERT INTO. This guarantees instant updates with zero locks.

C. Architectural Optimization Secrets for speed

Beyond datastore tuning, the map loads in milliseconds due to several front-end and query optimizations:

1. `QUALIFY ROW_NUMBER` COLLAPSING
If an asset is listed for rent and sale, it produces multiple rows. To prevent overlapping pins causing canvas rendering lag, BigQuery collapses duplicates instantly using:
QUALIFY ROW_NUMBER() OVER (
  PARTITION BY asset_id 
  ORDER BY service_type
) = 1
2. DECOUPLED THUMBNAIL LOADING
Loading thousands of base64/CDN images in a single pin query balloons the JSON payload size. `/api/pins` completely omits the thumbnailUrl key. The map plots immediately, and photos are lazy-loaded on hover/draw via /api/pins/thumbs.
3. REGIONAL DATASETS HOUSING
The BigQuery dataset is geographically configured in the EU multi-region (matches our Supabase database cluster in London/eu-west-2). Placing compute adjacent to storage cuts network hop times to ~10ms.
4. INTELLIGENT CACHING BOUNDARIES
Public/tenant endpoints only return Instructed live listings. This is non-confidential, slow-changing data, so it gets cached aggressively at the Cloudflare Edge. Operators get high-security, real-time data, so their lookups bypass CDN layers entirely.

D. Front-End Map Function Stack Explainer (useMapPins)

When a user loads our dashboard map, the client-side React code orchestrates a three-phase coordinate rendering stack to achieve near-instantaneous load times (under 600ms) with zero layout thrashing:

1
Phase 1: Fast Pin Plotting (BigQuery API Retrieval)

The custom React hook useMapPins immediately queries /api/pins. This endpoint fetches strictly coordinates, status indicators, and asset references from our BigQuery spatial dataset. It returns a lightweight JSON payload (no images/descriptions) in under 600ms. The Leaflet/Google Maps canvas immediately draws all interactive markers with lightweight placeholders in tooltips.

2
Phase 2: Lazy Media Backfilling (Supabase Thumbnails)

The moment Phase 1 resolves, the hook triggers a secondary background fetch to /api/pins/thumbs. This endpoint queries Supabase to fetch CDN thumbnail image URLs and alert states for those assets. They are dynamically backfilled into the React state. When an operator hovers over a pin, its image is displayed instantly without causing any page lag during initial loads.

3
Phase 3: Stale-While-Revalidate Local Storage Cache

To eliminate visual flickering when switching pages, the final merged pin payload is written to local storage. On return visits, the map reads the cache instantly. If the cache is under 2 minutes old, it serves it directly. If it is 2-30 minutes old, it serves the cached pins immediately and fetches fresh ones in the background, keeping our user experience flawlessly fast.

4. Code Highlights

Production Excerpts

A. Parameterized BigQuery SQL Builder with Distinct Collapsing

function buildQuery(
  unLocode: string,
  role: string,
  timeline: string,
  listingType: string,
  assetIds: string[] | null // Whitelist of verified, server-resolved asset IDs
): string {
  const isRestricted = role === "public" || role === "tenant";

  // Public/tenant users are restricted to 'Instructed' (live) assets only
  const roleFilter = isRestricted ? `AND asset_status = 'Instructed'` : "";
  const locodeFilter = unLocode ? `AND un_locode = @un_locode` : "";
  const assetFilter = assetIds ? `AND asset_id IN UNNEST(@asset_ids)` : "";

  // Collapses multi-listing properties into 1 pin to avoid map markers rendering on top of each other
  return `
    SELECT DISTINCT
      asset_id,
      asset_ref,
      property_tag,
      latitude,
      longitude,
      asset_status,
      fee_value,
      fee_currency,
      service_type
    FROM \`\${PROJECT}.\${DATASET}.\${TABLE}\`
    WHERE latitude IS NOT NULL
      AND longitude IS NOT NULL
      \${locodeFilter}
      \${assetFilter}
      \${roleFilter}
    QUALIFY ROW_NUMBER() OVER (PARTITION BY asset_id ORDER BY service_type) = 1
    ORDER BY asset_ref
  `;
}

5. Verification & Operations Guide

Testing & Commands

Developers can manually trigger coordinate syncs, trace webhook logs, or inspect the BigQuery table to verify changes are live.

A. Triggering a Dry Run Sync

To preview how many assets have valid GPS coordinates and what the schema shape is without writing to BigQuery:

node /root/projects/raia/03_technology/09_pipelines/programs/sync-pins.js --dry-run
B. Performing a Live Force-Sync

To manually clear the BigQuery table and load the latest authoritative Supabase assets:

node /root/projects/raia/03_technology/09_pipelines/programs/sync-pins.js
C. Testing the Live Webhook Handler

You can trigger a database webhook event from the Supabase admin panel or manually simulate a database payload locally via curl to test the instant delete/insert cycle.

🔧 Section C: Developer Guide

Architecture Details

The security architecture implements a defence-in-depth model with perimeter authentication, internal authorisation, data encryption, and audit logging at every layer. Access is gated through a two-gate system: Tailscale identity verification at the network level, followed by role-based access control within the application.

  • Core Component: Security gate guard and RBAC enforcement
  • Data Flow: Request → Tailscale Gate → Authentication → Authorisation → Audit Log → Response
  • Integration Points: Tailscale ACLs, Supabase Row-Level Security, session tokens, and audit log sinks

Configuration Reference

Key configuration parameters for this system:

Parameter Type Default Description
gate_enabled boolean true Enable Tailscale gate guard for all pages
allowed_hosts string[] dev.estateaigents.com, localhost Whitelist of permitted hostnames
session_ttl_minutes integer 60 Session token time-to-live
SECURITY ARCHITECTURE — DEFENCE IN DEPTH 1. NETWORK GATE Tailscale Identity Network-level Auth 🔐 Tailscale Gate 2. APPLICATION GATE RBAC Enforcement Session Validation 🛡️ Auth Layer 3. DATA GATE RLS & Encryption Audit Logging 🔒 Data Protection Defence-in-depth: network gate → application gate → data gate with audit logging at every layer Tailscale identity · Role-based access · Row-level security · Full audit trail Network / Identity Gate Application / Auth Layer Data / Encryption Layer Data flow →

Figure 2: Security architecture — component interaction and data flow.

Troubleshooting

Issue Cause Resolution
401 Unauthorized on tailnet Tailscale not running or wrong node Verify Tailscale is connected and node is authorised
Gate guard redirect loop Hostname not in allowed_hosts list Add hostname to the gate guard whitelist
Repo Reference RAIA

This component is part of the RAIA (Real estate Artificial Intelligence Agent) platform mono-repo. Implementation details, API contracts, and integration tests are available in the repository.