RAIA™ Specification

PII Data Lifecycle: Schema Design, Collection Gates & SJT Integration

Most of the people in our system — around 51,000 — are just enquiries who emailed about a flat. We do not store their date of birth or passport details because we do not need to. We only collect ident

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

Most of the people in our system — around 51,000 — are just enquiries who emailed about a flat. We do not store their date of birth or passport details because we do not need to. We only collect ident

🧩 Section A: In Plain English

PII Data Lifecycle: Schema Design, Collection Gates & SJT Integration

Most people in our system — around 51,000 — are just enquiries who emailed about a flat. We do not store their date of birth or passport details. This page explains the rules for when we collect what, and where it gets stored.

🟢 In Plain English

Most of the people in our system — around 51,000 — are just enquiries who emailed about a flat. We do not store their date of birth or passport details because we do not need to. We only collect identity information when someone actually becomes a tenant or landlord. This page explains the rules for when we collect what, and where it gets stored.

PII Data Lifecycle: Schema Design, Collection Gates & SJT Integration

The complete specification for how RAIA (Real estate Artificial Intelligence Agent) handles personally identifiable information across the lead-to-tenancy journey. Covers the three-tier data model, SJT gate enforcement, Sumsub integration, landlord AML, referral exclusion rules, and GDPR-compliant retention policy.

▲ HITL Gate — Stage 4 Referencing ⚖ GDPR Article 5(1)(e) ✓ INSERT-only audit log ◉ Retention cron automated
3
Data tiers
Tier 0 flags · Tier 1 portrait · Tier 2 structured PII
0
PII records for leads
tbl_persons_identity must be empty for person_status = lead
5
Document types under retention policy
passport · visa · RTR cert · proof_of_address · face_match
1
Audit log entry per access
Every read of Tier 2 PII inserts one row in tbl_pii_access_log
📋

Scope of this document. This guide covers the data design and collection gate logic for PII. For access-control policies, RLS rules, and the GDPR-justified-access workflow, see § 3.5a GDPR PII Access Architecture. This document is the upstream companion: it tells you what gets stored, where, and under what gate conditions.


CH 1 Why: The PII Separation Problem

1.1 The Lead-vs-Tenant PII Separation Problem

RAIA (Real estate Artificial Intelligence Agent) manages two fundamentally different person-states within the same tbl_persons table: leads (people who have enquired, viewed, or been added to a shortlist) and tenants (people in an active or completed tenancy). The distinction matters enormously for GDPR.

🚫 Lead — No PII Permitted
  • person_status = 'lead'
  • Only name, phone, email are held
  • No passport data, visa, nationality (structured), address proof
  • No row in tbl_persons_identity
  • Legal basis: legitimate interest (marketing / enquiry)
  • Retention: 12 months from last contact if no tenancy progresses
✓ Tenant — Full Tier 2 PII Permitted
  • person_status = 'tenant' (or 'prospective_tenant' after Stage 4)
  • Identity documents in Tier 2 GCS bucket
  • Row exists in tbl_persons_identity
  • Legal basis: contractual obligation (tenancy agreement) + legal obligation (Right to Rent Act)
  • Retention: tenancy_end + 1–7 years depending on doc type

The failure mode is an automated system that creates identity-collection tasks the moment any person record is linked to a property, regardless of status. This has happened in legacy estate-agent CRMs. RAIA (Real estate Artificial Intelligence Agent) prevents it through the Stage 4 referencing gate — no PII collection task is ever created until a human operator has manually approved progression to referencing.

🔴

The cardinal rule: tbl_persons_identity must have zero rows for any person_id where the associated person has person_status = 'lead'. This is enforced by a Postgres trigger and checked nightly by the compliance cron. Violations are surfaced as P0 alerts.

1.2 The Landlord AML Day-1 Requirement

Under the UK Money Laundering, Terrorist Financing and Transfer of Funds Regulations 2017 (MLR 2017), estate agents (as relevant persons under MLR 2017 Reg. 8(1)(f)) must perform Customer Due Diligence (CDD) on landlords and beneficial owners before or during establishing a business relationship — not when a tenancy is created. This creates an asymmetry:

⚠ AML Timing Difference: Landlords vs Tenants

Landlords: PII (passport, proof of address, company documents) is collected at organisation signup. This is Tier 2 data stored against the tbl_organisations record, not against a tenancy. There is no SJT stage gate for landlords — the gate is the onboarding flow itself.

Tenants: PII is collected only after SJT Stage 4 referencing gate is passed. Any attempt to collect tenant PII before Stage 4 must be blocked by the Paperclip guard layer.

The practical consequence: when a property manager creates a new tenancy for an existing landlord, the landlord's AML check may already be on file from org signup months earlier. The system must check tbl_organisations.aml_verified_at IS NOT NULL before allowing a new tenancy to proceed, rather than re-collecting AML data per tenancy.

1.3 The Partner/Referral Tenancy Gap

RAIA (Real estate Artificial Intelligence Agent) supports a tenancy model where a partner agency (introducer) finds a tenant and introduces them to a landlord, but the referencing is handled entirely by the landlord or their own agent. In this model, RAIA's role is purely introductory — we never receive, store, or process the tenant's identity documents.

ℹ Tenant Introduction Model

When tbl_tenancies.referral_type = 'tenant_introduction', RAIA (Real estate Artificial Intelligence Agent) has acted as an introducer only. We facilitated the match but do not hold Right to Rent obligations. The tenancy row exists for commission tracking and CRM completeness, but the tenant must be permanently excluded from all PII collection workflows, chase lists, and compliance gap reports.

This is distinct from a full management tenancy (where RAIA (Real estate Artificial Intelligence Agent) does reference, verify, and manage) and a let only tenancy (where we collect PII up to move-in, then hand off). The referral_type column is the authoritative field governing these workflows.


CH 2 How: Schema Design & the Three-Tier Model

2.1 The Three-Tier Data Model

RAIA (Real estate Artificial Intelligence Agent) separates personal data into three tiers based on sensitivity, legal basis, and access frequency. Each tier has its own storage location, access control surface, and retention rule.

Tier 0 — Status Flags
Non-PII Metadata
Stored in: tbl_persons (Postgres / Supabase)
  • Name, phone, email (low-sensitivity contact)
  • person_status: lead / prospective / tenant / former
  • identity_verified: boolean
  • aml_checked: boolean
  • Nationality (free-text, display only)
  • avatar_url (portrait link to Tier 1)
Tier 1 — Portrait
Biometric Proxy
Stored in: rcf-public/portraits/{person_id}.webp
  • Face photo extracted from ID document or Sumsub
  • Public-readable GCS bucket (URL signed only)
  • Used for face-match at move-in (Stage 6)
  • Not a full biometric template — pixel image only
  • Separate retention from Tier 2 docs
Tier 2 — Structured PII
Full Identity Data
DB: tbl_persons_identity & raia-gb-private/identity/…
  • Document numbers (passport, BRP, visa)
  • Date of birth (structured)
  • Nationality (ISO structured — not the free-text field)
  • Expiry dates & visa conditions
  • Sumsub applicant_id & check result
  • Document image files (GCS private bucket)

2.2 tbl_persons — What IS and IS NOT Stored Here

tbl_persons is the central person registry. It is not a PII table — it is a CRM table. The distinction is critical for GDPR data mapping.

✓ IS stored in tbl_persons
  • id — UUID primary key
  • org_id — FK to tbl_organisations
  • first_name, last_name
  • email, phone
  • person_status — lead / prospective_tenant / tenant / former_tenant / landlord
  • avatar_url — GCS URL to portrait (Tier 1)
  • nationality — free-text display only
  • identity_verified — boolean flag
  • aml_checked — boolean flag
  • created_at, updated_at
  • last_contacted_at
  • source — referral / portal / direct
🚫 IS NOT stored in tbl_persons
  • Document numbers (passport, BRP, visa)
  • Date of birth (structured)
  • Nationality ISO code (structured — see tbl_persons_identity)
  • Document expiry dates
  • Visa category or conditions
  • Sumsub applicant_id
  • ID document image URLs
  • NI number or tax identifiers
  • Bank account details
  • Right to Rent check result
⚠️

The nationality trap. tbl_persons.nationality is a user-entered free-text field intended for CRM display (e.g., "British", "French"). It is not a structured identity field and does not satisfy Right to Rent or AML reporting requirements. Structured nationality (ISO 3166-1 alpha-2) lives in tbl_persons_identity.nationality_iso. Never query tbl_persons.nationality for compliance reporting.

2.3 tbl_persons_identity — New Schema

This table holds all Tier 2 structured identity fields. It is created only for persons who have passed Stage 4 referencing. Row-level security ensures this table is never accessible by default — all reads must pass through the justified-access layer and emit an audit log entry.

tbl_persons_identity NEW TABLE Supabase Postgres · schema: public · RLS: enabled
CREATE TABLE tbl_persons_identity (

  -- Identity
  id                      UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  person_id               UUID NOT NULL UNIQUE
                            REFERENCES tbl_persons(id) ON DELETE CASCADE,

  -- Document type & numbers
  document_type           TEXT NOT NULL,        -- passport | brp | visa | national_id
  document_number         TEXT,                 -- encrypted at rest
  document_expiry_date    DATE,
  document_country        CHAR(2),              -- ISO 3166-1 alpha-2 issuing country

  -- Visa / immigration
  visa_category           TEXT,                 -- Tier 1 / Tier 2 / ILR / BNO / EU-settled etc.
  visa_conditions         TEXT,                 -- free text from visa endorsement
  visa_expiry_date        DATE,
  right_to_rent_unlimited BOOLEAN NOT NULL DEFAULT FALSE,

  -- Person core (structured)
  date_of_birth           DATE,
  nationality_iso         CHAR(2),              -- ISO 3166-1 alpha-2  ← NOT tbl_persons.nationality
  gender                  TEXT,                 -- M / F / X / not_stated

  -- GCS document URLs (private bucket paths)
  gcs_passport_url        TEXT,                 -- raia-gb-private/identity/{person_id}/passport.*
  gcs_visa_url            TEXT,
  gcs_brp_url             TEXT,
  gcs_proof_of_address_urlTEXT,
  gcs_face_match_url      TEXT,                 -- snapshot taken at Stage 6 move-in

  -- Sumsub eIDV integration
  sumsub_applicant_id     TEXT UNIQUE,
  sumsub_review_result    TEXT,                 -- GREEN / YELLOW / RED
  sumsub_reviewed_at      TIMESTAMPTZ,
  sumsub_archived_to_gcs  BOOLEAN NOT NULL DEFAULT FALSE, -- must be TRUE before retention purge

  -- Right to Rent check
  rtr_check_date          DATE,
  rtr_check_method        TEXT,                 -- manual | sumsub | idsp
  rtr_follow_up_date      DATE,                 -- for time-limited right to rent only

  -- Lifecycle
  collected_at_sjt_stage  INTEGER NOT NULL,     -- must be >= 4
  collected_by_user_id    UUID REFERENCES auth.users(id),
  verified_at             TIMESTAMPTZ,
  verified_by_user_id     UUID REFERENCES auth.users(id),
  purge_after             DATE,                 -- computed by retention policy, set at tenancy_end
  purged_at               TIMESTAMPTZ,

  created_at              TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at              TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Guard: no identity rows for leads
CREATE OR REPLACE FUNCTION prevent_lead_identity_insert()
RETURNS TRIGGER AS $$
BEGIN
  IF (SELECT person_status FROM tbl_persons WHERE id = NEW.person_id) = 'lead'
  THEN
    RAISE EXCEPTION 'PII guard: cannot insert tbl_persons_identity for person_status=lead';
  END IF;
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER trg_prevent_lead_pii
  BEFORE INSERT OR UPDATE ON tbl_persons_identity
  FOR EACH ROW EXECUTE FUNCTION prevent_lead_identity_insert();

2.4 tbl_pii_access_log — Audit Schema

Every read of Tier 2 data must create exactly one row in this table. The table is INSERT-only — no UPDATE or DELETE is permitted for any role including service_role. This immutability is enforced via RLS and is a GDPR Article 30 requirement.

tbl_pii_access_log AUDIT TABLE — INSERT ONLY RLS: INSERT allowed · SELECT: admin only · UPDATE/DELETE: denied all roles
CREATE TABLE tbl_pii_access_log (
  id              BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  accessed_at     TIMESTAMPTZ NOT NULL DEFAULT NOW(),

  -- Who accessed
  accessed_by     UUID NOT NULL REFERENCES auth.users(id),
  accessed_by_roleTEXT NOT NULL,               -- property_manager | admin | system | cron
  session_id      TEXT,                        -- Supabase auth session token (truncated)

  -- What was accessed
  person_id       UUID NOT NULL REFERENCES tbl_persons(id),
  resource_type   TEXT NOT NULL,               -- identity_record | document_url | portrait
  resource_id     TEXT,                        -- tbl_persons_identity.id or GCS object name
  data_fields     TEXT[],                      -- which columns were read, e.g. ['document_number','dob']

  -- Justification
  access_reason   TEXT NOT NULL,               -- rtw_check | aml_check | tenancy_renewal | admin_review
  tenancy_id      UUID REFERENCES tbl_tenancies(id),
  ip_address      INET,
  user_agent      TEXT
);

-- RLS: authenticated users may INSERT their own rows only
ALTER TABLE tbl_pii_access_log ENABLE ROW LEVEL SECURITY;

CREATE POLICY "insert_own_access_log" ON tbl_pii_access_log
  FOR INSERT TO authenticated
  WITH CHECK (accessed_by = auth.uid());

CREATE POLICY "select_admin_only" ON tbl_pii_access_log
  FOR SELECT TO authenticated
  USING (auth.jwt() ->> 'role' = 'admin');

-- No UPDATE or DELETE policy exists — revocation is structural
🔒

Immutability guarantee. Because no UPDATE or DELETE RLS policy exists on tbl_pii_access_log, any attempt by any role — including service_role — to modify or remove a log entry will fail. This is intentional. The audit trail must be tamper-proof to satisfy GDPR Article 30 records-of-processing and ICO audit requirements. Do not add a delete policy "for testing" — use a separate staging project.

2.5 tbl_pii_retention_policy — GB Values

Retention periods are jurisdiction-specific. The table holds named policy records keyed by jurisdiction + document_type. The GB seed values below reflect current ICO guidance, the Immigration Act 2014 Part 3 / Home Office Right to Rent Code of Practice 2022 requirement (retain for 1 year post-tenancy), and HMRC landlord record-keeping rules.

tbl_pii_retention_policy SEED DATA jurisdiction = 'GB' · 5 document types
CREATE TABLE tbl_pii_retention_policy (
  id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  jurisdiction    CHAR(2) NOT NULL,           -- ISO 3166-1 alpha-2
  document_type   TEXT NOT NULL,
  retain_years_post_tenancy INTEGER NOT NULL,  -- years after tenancy_end
  legal_basis     TEXT NOT NULL,
  notes           TEXT,
  UNIQUE(jurisdiction, document_type)
);

-- GB seed values
INSERT INTO tbl_pii_retention_policy
  (jurisdiction, document_type, retain_years_post_tenancy, legal_basis, notes)
VALUES
  ('GB', 'passport',          1, 'Immigration Act 2014, Part 3, s.22-37; Home Office Right to Rent Code of Practice 2022; ICO Retention Schedule',
   'Minimum 1 year post-tenancy. Recommended 2 years for dispute protection.'),

  ('GB', 'visa',              1, 'Immigration Act 2014, Part 3; Home Office RTR Code of Practice 2022',
   'Must retain copy of visa/BRP for 1 year after tenancy ends.'),

  ('GB', 'rtr_certificate',   1, 'Immigration Act 2014, Part 3, s.22-37; Home Office Right to Rent Code of Practice 2022',
   'Right to Rent check record must be kept for 1 year after tenant vacates.'),

  ('GB', 'proof_of_address',  5, 'MLR 2017 reg.18; HMRC record-keeping',
   '5 years from relationship end per MLR 2017 Reg. 40; the default here should be at least 1825 days (5yr) not 3yr'),

  ('GB', 'face_match',        1, 'GDPR Art.5(1)(e) storage limitation; ICO biometric guidance',
   'Move-in face-match snapshot. Biometric proxy — minimise retention. Purge 1yr post-tenancy.');

2.6 referral_type on tbl_tenancies — The Exclusion Rule

The referral_type column was added to tbl_tenancies to support the partner introduction model. Its values drive the exclusion logic throughout RAIA's compliance reporting.

tbl_tenancies — referral_type column EXISTING TABLE — NEW COLUMN
ALTER TABLE tbl_tenancies
  ADD COLUMN referral_type TEXT NOT NULL DEFAULT 'full_management'
  CHECK (referral_type IN (
    'full_management',      -- RAIA (Real estate Artificial Intelligence Agent) references, manages, holds PII
    'let_only',             -- RAIA (Real estate Artificial Intelligence Agent) references + finds tenant, landlord self-manages
    'tenant_introduction'   -- RAIA (Real estate Artificial Intelligence Agent) introduces only — NO PII COLLECTION
  ));

-- Exclusion view used by compliance reports
CREATE OR REPLACE VIEW v_tenancies_requiring_pii AS
  SELECT * FROM tbl_tenancies
  WHERE referral_type != 'tenant_introduction'
    AND status NOT IN ('cancelled', 'draft');
referral_type RAIA (Real estate Artificial Intelligence Agent) collects PII? In photo_id_gap report? In ID chase list? RTR obligation
full_management ✓ YES ✓ YES ✓ YES RAIA (Real estate Artificial Intelligence Agent) holds
let_only ✓ YES ✓ YES ✓ YES Landlord holds after handoff
tenant_introduction ✗ NEVER ✗ EXCLUDED ✗ EXCLUDED Landlord holds (we never had it)

2.7 PII Collection Pipeline — Swim Lane Diagram

The diagram below shows the full lifecycle from initial enquiry to stored & verified PII. Human-in-the-loop (HITL) gates are shown in amber. PII collection is structurally impossible before Stage 4.

SWIM LANES System Stage Lead Stage No PII — Tier 0 only HITL Gate Human decision required PII Collection Tier 2 forms open Verification Sumsub / IDSP / manual Stored & Audited tbl_persons_identity + GCS SJT STAGE 1 Enquiry name · phone · email SJT STAGE 2 Viewing still lead status SJT STAGE 3 Offer Made offer details only ↓ ▲ HITL GATE — STAGE 4 Referencing Decision Human must approve progression ↓ approved STATUS UPGRADE lead → prospective tbl_persons UPDATE PII COLLECTION OPEN Forms + Document Upload raia-gb-private GCS · Sumsub SDK ↓ SJT STAGE 5 Identity Verification Sumsub review · IDSP · manual RTR SJT STAGE 6 Move-in Face Match live vs portrait comparison ↓ ↓ STORED · VERIFIED · AUDITED tbl_persons_identity row created tbl_pii_access_log INSERT · person_status = 'tenant' · identity_verified = true ← NO PII ZONE

CH 3 What: Step-by-Step Operation

3.1 How a New Tenancy Collects PII

The following sequence assumes referral_type is full_management or let_only. All steps are blocked if referral_type = 'tenant_introduction'.

  • 1
    SJT Stage 1–3: Lead record only

    Person exists in tbl_persons with person_status = 'lead'. Only contact fields collected: first_name, last_name, email, phone. No forms displayed for identity docs. tbl_persons_identity has zero rows for this person.

  • 2
    HITL Gate: Stage 4 Referencing Approval

    A property manager manually clicks "Approve Referencing" in the SJT panel. This is the only action that advances sjt_stage to 4 for this tenancy. Paperclip validates the transition and blocks if referral_type = 'tenant_introduction' or if the person is still person_status = 'lead' (the status upgrade happens atomically in the same transaction).

  • 3
    person_status upgraded: lead → prospective_tenant

    Atomic Postgres transaction: UPDATE tbl_persons SET person_status = 'prospective_tenant' WHERE id = $person_id. This unlock is what permits subsequent INSERT into tbl_persons_identity (the trigger will now pass).

  • 4

    Repository Code

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

    ">PII collection form opens — Tier 2 fields

    Front-end renders the identity collection form. Fields map directly to tbl_persons_identity columns: document_type, document_number, document_expiry_date, document_country, date_of_birth, nationality_iso. Free-text tbl_persons.nationality is pre-filled from form input but is NOT the authoritative field.

  • 5
    Document upload → GCS private bucket

    Document images are uploaded to raia-gb-private/identity/{person_id}/{document_type}/{uuid}.{ext}. The GCS object name is stored as the corresponding gcs_*_url column in tbl_persons_identity. No public URLs. All access via signed URLs with 15-minute expiry, and every signed-URL generation must INSERT into tbl_pii_access_log.

  • 6
    Sumsub eIDV initiated (optional)

    If eIDV is enabled for the org, a Sumsub applicant is created. The sumsub_applicant_id is stored in tbl_persons_identity. Sumsub performs liveness + document verification. On webhook callback, sumsub_review_result and sumsub_reviewed_at are updated.

  • 7
    Stage 5 complete: identity_verified = true

    After verification: UPDATE tbl_persons SET identity_verified = true WHERE id = $person_id. tbl_persons_identity.verified_at and verified_by_user_id are set. collected_at_sjt_stage must be 4 or higher — checked by constraint.

  • 8
    Stage 6: Move-in face match (portrait vs live)

    At move-in, RAIA (Real estate Artificial Intelligence Agent) captures a live photo and compares against the Tier 1 portrait (rcf-public/portraits/{person_id}.webp). Match result + snapshot stored as gcs_face_match_url. This is the final PII collection event for the tenancy lifecycle.

  • 3.2 Landlord AML — Day 1 at Org Signup

    Landlord AML is collected once at organisation signup — not per tenancy. This is a deliberate design to avoid redundant CDD and to reflect the MLR 2017 requirement that CDD applies to the business relationship (the estate agent–landlord relationship), not individual transactions.

    ⚠ AML Data Lives on tbl_organisations, Not tbl_tenancies
    • tbl_organisations.aml_verified_at — timestamp of completed CDD
    • tbl_organisations.aml_document_type — passport / company_cert / etc.
    • tbl_organisations.gcs_aml_docs_prefix — GCS path to AML document package
    • When creating a new tenancy, system checks aml_verified_at IS NOT NULL
    • If NULL, onboarding flow is blocked and AML collection is triggered before tenancy creation proceeds
    • AML data follows the proof_of_address retention rule: 5 years post-relationship-end (MLR 2017 Reg. 40)
    • 1
      Org signup triggers AML collection workflow

      When a new landlord org is created, the onboarding wizard presents AML document collection before any property can be listed. Collection is the same Tier 2 form used for tenants, stored to raia-gb-private/aml/{org_id}/.

    • 2
      Pre-tenancy check: aml_verified_at

      Before any tenancy is created under an org, a guard function checks tbl_organisations.aml_verified_at IS NOT NULL. If not verified, the tenancy creation endpoint returns a 422 with code AML_REQUIRED and a redirect to the AML completion flow.

    • 3
      AML renewal (high-risk or time-based)

      For high-risk profiles or when 5 years have elapsed since last AML check, the system flags the org for enhanced due diligence. Renewal triggers the same collection flow. The old AML documents are not deleted — retained per the 5-year post-relationship policy (MLR 2017 Reg. 40). The new check creates a new record.

    3.3 The referral_type Exclusion in Compliance Reports

    The photo_id_gap compliance report identifies tenancies where PII is expected but not yet collected. Tenant introduction tenancies must be permanently excluded from this report or they will generate false-positive chase tasks.

    photo_id_gap compliance query — referral_type exclusion QUERY PATTERN
    -- Returns tenancies that need ID but don't have it yet
    -- CRITICAL: referral_type = 'tenant_introduction' is excluded
    SELECT
      t.id             AS tenancy_id,
      p.first_name,
      p.last_name,
      p.email,
      t.sjt_stage,
      t.referral_type
    FROM tbl_tenancies t
    JOIN tbl_persons p ON p.id = t.primary_tenant_id
    LEFT JOIN tbl_persons_identity pi ON pi.person_id = p.id
    WHERE
      t.referral_type != 'tenant_introduction'   -- EXCLUSION RULE
      AND t.sjt_stage >= 4                        -- only after referencing gate
      AND t.status NOT IN ('cancelled', 'draft')
      AND p.identity_verified = FALSE
      AND pi.id IS NULL                            -- no identity record at all
    ORDER BY t.created_at;
    ⚠️

    Always filter by referral_type != 'tenant_introduction' in any query that drives PII chase workflows, ID gap reports, or Right to Rent compliance dashboards. Failing to add this filter will cause incorrect compliance alerts and potentially inappropriate PII collection requests being sent to tenants whose landlord explicitly handles their own referencing.


    CH 4 SJT & Paperclip Integration

    4.1 SJT Stages That Gate PII Collection

    SJT (Staged Journey Tracker) is RAIA's tenancy progression model. PII collection is only permitted at specific stages. The table below maps each stage to its PII gate behaviour.

    Stage
    Name & Description
    PII Gate
    Stage 1
    Enquiry — Initial contact. Person is lead. Only name/email/phone.
    🚫 No PII
    Stage 2
    Viewing — Property viewed. Person remains lead. Still no PII.
    🚫 No PII
    Stage 3
    Offer Made — Tenant makes offer. Offer amount and conditions only. No identity data.
    ⚠ Offer only
    Stage 4 ▲
    Referencing Gate — HITL. Human approves referencing. person_status upgrades. PII collection unlocked. This is the single gate controlling all Tier 2 data access.
    ▲ HITL Required
    Stage 5 ✓
    Identity Verification — Sumsub or manual RTR check. Documents uploaded. identity_verified set to true. tbl_persons_identity row completed.
    ✓ PII Active
    Stage 6 ✓
    Move-in & Face Match — Tenant physically present. Live photo vs Tier 1 portrait comparison. gcs_face_match_url populated. Tenancy becomes active.
    📸 Face match

    4.2 How Paperclip Enforces the Lead Separation Rule

    Paperclip is RAIA's guard layer that wraps all database mutations involving PII. It acts as a middleware layer between the API and Supabase, enforcing the following rules at write-time:

    🔐 Paperclip PII Guard Rules
    • Rule 1 — Lead block: Any attempt to INSERT into tbl_persons_identity where the referenced person_id has person_status = 'lead' is rejected with PAPERCLIP_LEAD_PII_BLOCKED. Backed by Postgres trigger as a second line of defence.
    • Rule 2 — Stage gate: PII collection API endpoints check that tbl_tenancies.sjt_stage >= 4 for the tenancy in context. Requests before Stage 4 return 403 STAGE_GATE_NOT_PASSED.
    • Rule 3 — Introduction exclusion: Any tenancy with referral_type = 'tenant_introduction' causes Paperclip to return 403 INTRODUCTION_TENANCY_NO_PII on all identity-collection routes.
    • Rule 4 — Audit mandatory: All reads of tbl_persons_identity rows or raia-gb-private GCS signed URLs must be accompanied by a tbl_pii_access_log INSERT. Paperclip wraps the read in a transaction; if the audit INSERT fails, the read is rolled back.
    • Rule 5 — Cross-org isolation: A user from org A cannot read identity records for persons in org B. Paperclip enforces this at the API layer; RLS enforces it at the database layer.

    4.3 The Retention Cron — Hooking into tenancy_end Events

    PII retention purge is driven by a scheduled cron job that runs nightly. It does not delete on a fixed schedule — it computes a purge_after date per document type at the moment of tenancy end, then purges when that date is reached.

    • 1
      tenancy_end event fires

      When a tenancy moves to status = 'ended', a Postgres trigger fires fn_set_pii_purge_dates(tenancy_id). This function JOINs against tbl_pii_retention_policy and sets tbl_persons_identity.purge_after for each applicable document type, using tenancy_end_date + retention.retain_years_post_tenancy * interval '1 year'.

    • 2
      Sumsub archive check before purge

      Before any Sumsub-related data is purged, the cron verifies sumsub_archived_to_gcs = TRUE. If false, it triggers the Sumsub data export (all applicant documents + results downloaded to raia-gb-private/sumsub-archive/{person_id}/) and sets the flag. Only then does purge proceed. This is critical — Sumsub may delete applicant data on their end independently.

    • 3
      Nightly cron: purge where purge_after < NOW()

      Cron queries SELECT * FROM tbl_persons_identity WHERE purge_after < NOW() AND purged_at IS NULL AND sumsub_archived_to_gcs = TRUE. For each row: nullify sensitive columns in the DB, delete GCS objects, set purged_at = NOW(). The row itself is retained (tombstone) for audit trail — only PII fields are nullified.

    • 4
      Access log not purged

      tbl_pii_access_log is never purged by the retention cron. Audit records must be retained for the duration of GDPR Article 30 obligations. The access log contains no PII — only metadata (who accessed, when, what resource type) — so GDPR storage limitation does not apply in the same way.


    ⚠ Pitfalls

    Eight known hazard points, prioritised by severity.

    1
    CRITICAL — Never populate tbl_persons_identity for person_status = lead

    Inserting a row into tbl_persons_identity for a lead is a GDPR violation (excessive collection without legal basis) and a P0 compliance incident. The Postgres trigger trg_prevent_lead_pii will block this at the DB layer, but the API layer must also check — never rely solely on DB-level guards. If you see the trigger error in logs, it means something upstream bypassed the Paperclip guard and must be treated as a security incident.

    2
    CRITICAL — referral_type = tenant_introduction excludes from ALL ID chase lists

    Any query that drives PII collection workflows, compliance gap reports, ID chase emails, or RTR follow-up reminders must filter WHERE referral_type != 'tenant_introduction'. A missed filter causes: (1) incorrect compliance alerts, (2) inappropriate PII requests sent to tenants whose referencing is handled by a third party, (3) potential GDPR breach if tenant data is collected without a lawful basis in this context. Use the view v_tenancies_requiring_pii as the canonical source for all such queries.

    3
    CRITICAL — tbl_pii_access_log must be INSERT-only via RLS

    Never add an UPDATE or DELETE policy to tbl_pii_access_log, even temporarily for testing, migration, or "cleanup". The immutability of the audit trail is a legal requirement under GDPR Article 30 and ICO audit guidance. If bad rows are accidentally inserted in development, document them with an additional corrective INSERT row. For production incidents, consult your DPO. Use a separate Supabase project or branch for any testing that might generate audit log noise.

    4
    CAUTION — Sumsub applicant data must be downloaded to GCS before Sumsub deletes it

    Sumsub operates its own data retention policy and may delete applicant records independently of RAIA's schedule. The retention cron includes a Sumsub archive step, but you must ensure sumsub_archived_to_gcs is set to TRUE before any tenancy ends, especially if using Sumsub's own retention settings. If Sumsub deletes data before RAIA (Real estate Artificial Intelligence Agent) archives it and a compliance check requires that data, there is no recovery path. Monitor the sumsub_archived_to_gcs = FALSE count on ended tenancies via the compliance dashboard.

    5
    CAUTION — tbl_persons.nationality is a free-text display field, NOT structured identity

    tbl_persons.nationality is what a user typed into a CRM form — "British", "French national", "UK/Irish". It has no ISO validation, no structured format, and must never be used in Right to Rent reports, AML checks, or compliance queries. Structured nationality (ISO 3166-1 alpha-2 country code) lives in tbl_persons_identity.nationality_iso. Any query that selects tbl_persons.nationality for compliance output is wrong. This distinction has tripped up multiple integrations.

    6
    INFO — Landlord AML is collected at org signup, not at tenancy creation

    AML data for landlords lives on tbl_organisations, not on tbl_tenancies. The pre-tenancy guard checks tbl_organisations.aml_verified_at IS NOT NULL. Do not design tenancy creation flows that attempt to collect landlord AML in-line — the onboarding flow handles this. For existing landlords who predate the AML requirement, a one-off backfill campaign was run; check aml_verified_at before assuming compliance.

    7
    CAUTION — collected_at_sjt_stage constraint must be enforced at INSERT

    The tbl_persons_identity.collected_at_sjt_stage column has a CHECK (collected_at_sjt_stage >= 4) constraint. Ensure that the value passed during INSERT reflects the actual tbl_tenancies.sjt_stage at time of collection — do not hardcode 4. If a tenancy was already at stage 5 when PII was collected (e.g., partial backfill), the correct stage must be recorded for audit integrity.

    8
    INFO — Tier 1 portrait (rcf-public) has different retention than Tier 2 docs

    The face portrait at rcf-public/portraits/{person_id}.webp follows the face_match retention rule (1 year post-tenancy), not the passport rule. However, because it is in a public bucket (access-controlled by signed URLs), its purge must be coordinated separately from the raia-gb-private purge. The retention cron currently handles portrait deletion separately. Check the cron config — portrait purge is a distinct job from Tier 2 document purge.


    🎯 Vibe Check

    Use these checklists before collecting PII (pre-gate) and after verifying it (post-verification). If any item fails, stop and escalate.

    🔴 Pre-Collection Gates — Before opening any PII form
    • ✓person_status is NOT lead — must be prospective_tenant or higher
    • ✓tbl_tenancies.sjt_stage >= 4 confirmed for the tenancy in context
    • ✓referral_type != 'tenant_introduction' — introduction tenancies must be blocked
    • ✓HITL approval recorded in SJT panel for Stage 4 transition
    • ✓No existing tbl_persons_identity row in an inconsistent state (partial, unverified, from a previous tenancy)
    • ✓Paperclip guard layer is active (check health endpoint before bulk operations)
    • ✓Tenant has been notified via GDPR privacy notice before submitting documents
    • ✓tbl_organisations.aml_verified_at IS NOT NULL for the landlord org
    ✅ Post-Verification Checklist — After Sumsub / manual RTR completes
    • ✓tbl_persons_identity.verified_at and verified_by_user_id populated
    • ✓tbl_persons.identity_verified = TRUE set in the same transaction
    • ✓All GCS document URLs stored in gcs_*_url columns (not null where applicable)
    • ✓Sumsub review_result is GREEN or case-reviewed YELLOW (RED blocks move-in)
    • ✓sumsub_applicant_id stored and sumsub_archived_to_gcs status checked
    • ✓rtr_check_date populated; rtr_follow_up_date set if time-limited right to rent
    • ✓Every access to Tier 2 data during verification has a corresponding tbl_pii_access_log row
    • ✓Tenancy SJT stage advanced to 5 (identity_verified) in SJT tracker
    • ✓nationality_iso (ISO code) matches the document scanned — not copied from free-text tbl_persons.nationality
    • ✓Retention cron will auto-set purge_after on tenancy end — no manual date needed now
    🚀

    You're compliant when: every Tier 2 PII row has a Stage 4+ gate in its history, every access has a log entry, every introduction tenancy is cleanly excluded from ID chase lists, every landlord has AML on file from signup, and the retention cron has purge dates set for all ended tenancies. Run SELECT * FROM v_compliance_health_check to get a single-row summary of system state.


    Related Documents

    📄
    Justified access on demand, session-scoped PII retrieval, access audit log, legacy GCS migration path, Sumsub integration, and modular jurisdiction design.
    📄
    Layer 2 API rate limits, secure content masking guards, and enterprise PII protection shielding.
    🗄
    Supabase migration: 20240601_pii_identity_schema.sql
    Creates tbl_persons_identity, tbl_pii_access_log, tbl_pii_retention_policy, adds referral_type to tbl_tenancies, seeds GB retention values.
    🔧
    Paperclip guard layer — /src/middleware/paperclip.ts
    Implements all 5 PII guard rules including lead-block, stage-gate, introduction-exclusion, audit-mandatory, and cross-org isolation.

    § 3.5b · PII Data Lifecycle · RAIA (Real estate Artificial Intelligence Agent) RAIA (Real estate Artificial Intelligence Agent) Documentation · Last updated June 2025 · ← Back to index

    Repository Code

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