Spec

2.10 Legacy Data Integration Framework

Specification, workflow, and technical reference for the legacy data integration framework module.

TEXTBOOK SPECIFICATION

1. The Problem

Every organisation onboarding onto the RAIA (Real estate Artificial Intelligence Agent) platform brings a unique legacy data schema — a bespoke CRM (AppSheet, enterprise CRM, Streak, Zoho), a proprietary database (MySQL, PostgreSQL, SQL Server), or a web portal that must be scraped. Today, each sync pipeline is hand-written in Node.js with the field mapping hardcoded inside the script. There are no standardised mapping documents, no reusable sync engine, and no drift detection.

The audit in June 2026 revealed:

  • Contact data: 63,249 MySQL rows, 606 changes unsynced for 3 days
  • Junction tables: 23,132 Address_Contact rows, no timestamp column — delta sync impossible
  • Tenancies_Contact: 3,475 row gap between MySQL and Supabase, growing
  • Mapping knowledge: Scattered across ADR-044, sync.js, and tenancy-appsheet-sync.cjs — no single reference

This framework solves that. It defines a standardised, agent-executable architecture for mapping any legacy source system into the canonical RAIA (Real estate Artificial Intelligence Agent) schema, and keeping it in sync with drift detection and self-healing.

2. Architecture Overview

The framework splits into five layers. A declarative Mapping Specification is consumed by a Sync Engine that gates every record through a Compliance Layer before writing to the Canonical Schema. An Agentic Loop monitors for drift and auto-heals when schema changes are detected.

Legacy Data Integration Framework — Pipeline Architecture SOURCE SYSTEMS MySQL / API / Scraper Legacy CRM Database Web Portal (Scraped) MAPPING SPECIFICATION YAML / Git-versioned Field mappings + transforms PII tier + retention + provenance COMPLIANCE GATE PII Tier classification Retention schedule check Scraper quarantine OR pass Audit log emission CANONICAL SCHEMA tbl_persons tbl_tenancies tbl_addresses AGENTIC SELF-HEALING LOOP Schema fingerprint diff Drift classify (L1–3) Validate → Rewrite → Apply PER-ORG ISOLATION Each org gets its own Mapping YAML + credentials + schedule + watermark Legend: Source Mapping Compliance Target Agent Loop Per-Org
API

REST/gRPC endpoints with auth. Delta via updated_at or page tokens. Paginated, rate-limited, predictable schema.

DATABASE

MySQL / Postgres / SQL Server. Direct SELECT WHERE UpdatedAt > watermark. Full snapshots for tables without timestamps.

SCRAPER

HTTP scraper with headless browser. CSS selectors, session management, content-hash change detection, selector-success-rate monitoring.

Component Colour Purpose
Source SystemsIndigoLegacy CRM, database, or web portal being integrated
Mapping SpecPurpleDeclarative YAML: field mappings, transforms, PII tiers, retention, provenance
Compliance GateRosePII classification, retention check, scraper quarantine, audit log emission
Canonical SchemaEmeraldThe RAIA (Real estate Artificial Intelligence Agent) target: tbl_persons, tbl_tenancies, tbl_addresses, etc.
Agent LoopBlueSchema fingerprint diff → drift classify → validate → rewrite → apply
Per-Org IsolationOrangeEach org: own YAML, credentials (vault), schedule, watermark, error queue

3. Mapping Specification Format

After red-teaming the YAML-only approach across 5 LLM perspectives (Systems Architect, Data Engineer, Compliance Officer, AI Agent Developer, DevOps Engineer), the consensus is:

REJECTED: YAML-only
  • No PII tier annotation → GDPR violation
  • No retention or provenance fields
  • No schema fingerprint → no drift detection
  • No scraper-specific semantics
  • No version history or rollback
ACCEPTED: Declarative Mapping Spec
  • YAML as config artifact, not execution runtime
  • JSON Schema validated, SafeLoader parsed
  • Mandatory PII tier, retention, provenance blocks
  • Schema fingerprint hash baked in at generation time
  • Git-versioned, CI/CD gated, immutable audit trail

The canonical YAML format:

# Mapping Specification — v1.0
# Git-tracked, CI/CD validated, immutable audit trail

meta:
  mapping_schema_version: "1.0"
  org_id: "a0450010-0778-4000-8000-000000000010"
  source_system: "appsheet_dev"
  source_type: database              # api | database | scraper
  schema_fingerprint: sha256:abc123...  # of canonical Supabase schema
  generated_at: "2026-06-05T12:00:00Z"
  drift_policy:
    auto_resolve_up_to: 2            # Levels 1-2 auto-heal, Level 3 blocks
    conflict_strategy: merge_or_fail

source:
  type: database
  system: "appsheet_dev"
  host: "35.197.224.72"
  connection: vault://org-a/mysql-creds
  delta_default: updated_at
  schedule:
    expression: "0 */6 * * *"
    timezone: Europe/London
    retry:
      max_attempts: 3
      backoff_minutes: [5, 15, 60]

data_retention:
  default_class: standard
  policies:
    short_lived:  { retention_days: 365,  action: soft_delete }
    standard:     { retention_days: 2555, action: archive }
    regulatory:   { retention_days: 7300, action: immutable_log }

tables:
  Contact:
    target: tbl_persons
    delta_column: Updated
    watermark_key: "contact.last_updated"
    conflict_key: legacy_id
    fields:
      ContactID:
        target: legacy_id
        pii_tier: Tier0
        retention: regulatory
      FName:
        target: first_name
        pii_tier: Tier1
      LName:
        target: last_name
        pii_tier: Tier1
      Email01:
        target: tbl_persons_channels
        channel_type: email
        pii_tier: Tier0
        retention: standard
      Phone01:
        target: tbl_persons_channels
        channel_type: phone
        pii_tier: Tier0
        retention: standard
      Behavioural_Score:
        target: behavioural_score
        transform: parse_decimal
        pii_tier: Tier2

  Address_Contact:
    target: tbl_persons_addresses
    delta: full_reconcile             # no timestamp column
    conflict_key: legacy_address_contact_id
    fields:
      ContactID:
        target: person_id
        via_legacy: true
      AddressID:
        target: address_id
        via_legacy: true

provenance:
  type: api
  lawful_basis: contract
  data_controller: "RENTLONDONFLAT.COM LTD"
  authenticated: true

4. Agentic Self-Healing Loop

When the canonical Supabase schema evolves (column added/renamed/typed-changed), or the legacy source changes, a RAIA (Real estate Artificial Intelligence Agent) agent detects the drift, classifies it, and either auto-heals or raises an incident. The decision flow:

Fingerprint Diff schema_fingerprint vs live info_schema hash Classify Drift L1: Cosmetic → log only L2: Structural → auto-heal L3: Breaking → incident Branch + Dry-Run Supabase branch → dry-run → validate Apply & Rollout Merge YAML → promote branch Audit Log tbl_mapping_versions Levels: L1 Cosmetic L2 Structural L3 Breaking Data: Supabase branch covers full schema + 1000-row sample dry-run → row count parity

The agent stores every rewrite in tbl_mapping_versions — the full YAML as a blob, SHA256 hash, timestamp, and applied_by. Rollback is a single command: point current_symlink to the previous version and run a catchup backfill to revert data.

5. Compliance Layer & PII Controls

Every column mapping must carry a pii_tier annotation (ADR-PII-001). The engine rejects mappings that omit it. The tiers:

Tier Includes Controls Retention Default
Tier0 Phone, email, national ID, bank account AES-256-GCM per-row, all access audited, encrypted at rest 2555 days (7 yrs)
Tier1 Name, postcode, DOB, employment Pseudonymisation default, bulk-read audit 7300 days (20 yrs)
Tier2 Property type, price band, behavioural score Standard logging 365 days (1 yr)

Scraper-sourced PII is routed to a compliance quarantine table — not the live canonical schema — until a human compliance officer signs off. Every scraper run logs selector_success_rate, raw_hash (SHA256), and http_status to tbl_scraper_observations for drift detection.

6. Operational Tables

Every sync run writes to tbl_pipeline_runs. Failures go to tbl_pipeline_errors. Mapping versions are tracked in tbl_mapping_versions. Scraper observations in tbl_scraper_observations. These tables enable per-org billing, runbook automation, and Grafana alerting.

Table Logs Alert trigger
tbl_pipeline_runsPer-run: org, mapping SHA, source, type (incr/backfill/dry), status, watermark, counts, durationRunning > 2× p95 duration; error rate > 1%
tbl_pipeline_errorsPer-failed-row: run_id, source PK, target PK, error class, raw payloadAny row for Tier0 columns
tbl_mapping_versionsFull YAML blob, SHA256, deployed_by, rollback_of FKMapping SHA changed + no backfill triggered
tbl_scraper_observationsPer scrape: URL, HTTP status, raw_hash, selector success rate, rows extractedSelector success < 90% over rolling window

7. Per-Organisation Mapping Pages

Each organisation integrated onto the RAIA (Real estate Artificial Intelligence Agent) platform has its own mapping specification page, documenting the exact field-by-field mapping from their legacy schema to the canonical schema. These pages are linked below and serve as the single source of truth for that organisation's data integration.

8. Red Team Consensus Summary

Five independent LLM perspectives critiqued the initial YAML-only proposal. Key findings integrated into this spec:

Perspective Critical Finding Resolution in v1.0
Systems Architect No schema drift detection; YAML is a snapshot, not a living contract Schema fingerprint hash + three-level drift taxonomy + agentic loop
Data Engineer No per-row DLQ; no watermark tracking; multi-target field mapping ambiguous tbl_pipeline_errors DLQ; explicit channel_type for multi-target fields
Compliance Officer No PII tier annotation → GDPR violation; no retention/provenance/consent Mandatory pii_tier, retention, provenance, consent fields on every column mapping
AI Agent Developer No round-trip YAML; no branch-based dry-run; no table UID for renames Canonical JSON schema; Supabase branch + dry-run validation; canonical_uid
DevOps Engineer No alerting rules; no rollback; no scraper session mgmt; no per-org isolation Alert thresholds defined; mapping version store + rollback cmd; scraper observation table
Appendix A

Canonical Schema Reference

The canonical Supabase schema is defined in 04_datastores/database/ddl/live-supabase/ and is auto-generated by unify_docs.py. This page is a live reflection of that schema. When the schema changes, an agent detects the drift via schema_fingerprint, classifies it, and rewrites any affected mapping specifications.

Table Purpose Source Systems Synced By
tbl_personsIndividuals (tenants, landlords, leads)appsheet_dev.Contact → mappedFramework (planned)
tbl_persons_channelsPhone/email/WhatsApp per personappsheet_dev.Contact.Email01/Phone01 → mappedFramework (planned)
tbl_tenanciesRental tenancy agreementsappsheet_dev.Tenancies → syncedtenancy-appsheet-sync.cjs
tbl_depositsTenancy depositsappsheet_dev.Deposits → syncedtenancy-appsheet-sync.cjs
tbl_addressesPhysical locationsMultiple sourcesVarious
tbl_assetsManaged propertiesappsheet_dev.Address → syncedsync.js
tbl_keysPhysical keysappsheet_dev.Keys → syncedsync.js
tbl_keys_logKey custody eventsappsheet_dev.Keys_Log → syncedsync.js
tbl_tenancies_personsJunction: tenancy → personappsheet_dev.Tenancies_Contact → mappedFramework (planned)
tbl_persons_addressesJunction: person → addressappsheet_dev.Address_Contact → mappedFramework (planned)

Repository Code

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