RAIA™ Specification

3.30 Universal Inbox Triage Rules — Labels SSOT & Conversation Type

The jurisdiction-aware triage rules system, PA agent boundary enforcement, triage admin UI, and completion verifier plugin built on 2026-07-23/24. Covers ADR-267, ADR-268, ADR-269, and ADR-270.

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

The jurisdiction-aware triage rules system, PA agent boundary enforcement, triage admin UI, and completion verifier plugin built on 2026-07-23/24. Covers ADR-267, ADR-268, ADR-269, and ADR-270.

For estate agency staff

The Smart Post Room

How automatic inbox sorting works, in plain English

Every message that arrives in your inbox — whether it comes by email, WhatsApp, or Telegram — now gets sorted automatically into one of nine categories before you ever see it. Think of it as a smart post room: when an envelope arrives, a staff member reads the return address and subject line, stamps it with the right label, and puts it in the correct tray. You pick up the right tray and work from there.

The nine labels your inbox can receive are:

Enquiries

Inbound leads from dominant listing aggregator, incumbent property portal, and other portals. Prospective tenant messages. Viewing requests and offers.

Maintenance

Repair requests, broken boilers, leaks, pest control. Any message about something needing fixing at a property.

Accounts

Invoices, rent payments, arrears chasers, deposit refunds, standing orders. All money-related correspondence.

Compliance

EPC, EICR, HMO licensing, TDS deposit scheme, gas safety certificates. Regulatory paperwork and certificates.

Legal

Section 21, Section 8, eviction notices, tribunal correspondence, solicitor letters, ombudsman referrals.

HR

Holiday requests, sick leave, payslips, P60, P45. Staff admin correspondence.

IT

GitHub notifications, Vercel deploy alerts, Supabase system messages, Sentry error reports. Platform infrastructure messages.

Marketing

Your agency's own promotional activity — listing boost confirmations, paid portal placement receipts, campaign reports.

Junk

Inbound noise requiring no action — newsletters, out-of-office replies, vendor promotional spam, automated SaaS digests.

What this means for you day-to-day

You no longer need to read every message to decide which category it belongs to. The system does that work. Known senders — dominant listing aggregator, incumbent property portal, your maintenance contractors — are sorted instantly at zero extra cost. Ambiguous messages go to an AI that reads them and assigns the best label. Either way, your inbox arrives pre-sorted.

Junk vs Marketing: the important distinction

Junk is things arriving at you that you did not ask for — newsletters, vendor promotions, unsubscribe confirmations. Marketing is your agency's own outbound promotional activity coming back as confirmations — listing boost receipts, campaign reports. They look similar but belong to different queues: Junk can be auto-archived; Marketing items may need your attention for budget tracking.

For operational staff and administrators

The Three-Layer Evaluation

Every message is tested against three layers in strict order. The first layer that matches wins; lower layers are never reached for that message. This design means that 99.6% of messages are classified without spending any AI tokens.

1

Layer 1 — Jurisdiction-Specific Rules

Rules stored in the database that apply only to your market — UK (GBLON) or Thailand (THBKK). For a UK agency, this layer knows that any email from rightmove.co.uk is an Enquiry, and that a subject containing "Section 21" is Legal. These rules fire instantly, at zero AI cost, and are correct 100% of the time for the patterns they cover. Within this layer, your organisation-specific overrides are evaluated before the jurisdiction-wide defaults.

2

Layer 2 — Universal Rules

Rules that apply to every agency in every market. The highest-coverage rules sit here: any subject containing a ticket reference like "MA-1234" or "JB-042" is labelled Accounts (this pattern alone covers 39.4% of all historical emails). Viewing requests, maintenance keywords, HR terms, and IT notification senders all live in this layer. Universal rules apply regardless of jurisdiction.

3

Layer 3 — AI Fallback

Only messages that passed through Layers 1 and 2 without a match reach this layer — approximately 0.4% of volume based on the backtest of 168,691 real emails. The existing AI classifier reads the message body and assigns the best label with a variable confidence score. This layer is the safety net, not the default.

The Rules Admin UI

Eugin and designated admins can view, edit, enable, and disable triage rules without writing any SQL. The admin panel lives inside the dashboard under "Triage Rules" in the sidebar navigation. No redeploy is needed when a rule is changed — the next inbound message picks it up immediately.

Active Rules Tab

View all rules grouped by jurisdiction — filter between GBLON (UK), THBKK (Thailand), Universal, or All. Each row shows priority, channel, match conditions, label, and a 7-day match count. Click any row to expand an inline editor with all editable fields. Toggle rules on/off with a single click.

Suggestions Tab

Every Monday, the system analyses last week's AI-classified messages. If the same sender or subject pattern appears 10 or more times without a matching rule, it surfaces as a suggestion here. Eugin reviews each candidate and clicks Approve or Reject. Approved suggestions become live rules immediately — no SQL, no deploy.

The Weekly Self-Improvement Loop

Every Monday at 06:00 UTC a background job runs automatically. It does four things:

Task A — Gap Detection

Finds sender/subject patterns that the AI classified 10+ times with no matching rule. These become rule suggestions.

Task B — Drift Detection

Re-classifies 50 sampled AI messages. If more than 10% produce a different label, it flags an AI model drift alert.

Task C — Distribution Alert

Checks if any label's share has shifted more than 15 percentage points from the 4-week average. Catches upstream portal format changes.

Task D — Backfill

Processes up to 50 older conversations that have no label yet. Clears the historical backlog safely at 50 per week.

When new rule suggestions are found or a distribution drift is detected, Eugin receives a Telegram notification with a direct link to review them in the admin panel. No manual log-checking is needed.

Developer guide

Diagram 1 — Triage Pipeline Flow

End-to-end flow from message arrival through three evaluation layers to label persistence and inbox display.

Message Arrives LAYER 1 Jurisdiction Rules GB: dominant listing aggregator, S21, EPC, EICR, HMO org-specific first MATCH no match LAYER 2 Universal Rules MA/JB ticket refs repair, invoice, HR 39.4% corpus no match LAYER 3 AI Fallback classifyIssue() gpt-4o-mini ~0.4% volume UPSERT tbl_conversation _labels assigned_by= rule | ai | manual Inbox UI label shown Rule match path No match / pass-through First MATCH WINS — evaluation stops immediately. AI fallback only when Layers 1 and 2 return no match.

Diagram 2 — Agent Governance Loop

The PA boundary enforcement system (ADR-268) and completion verifier plugin (ADR-270) form a closed governance loop around every development task.

PA Agent receives request from Eugin BOUNDARY GATE enforce-pa-boundary plugin (ADR-268) DESIGN VIOLATION Response Replaced BOUNDARY GATE msg + auto-dispatch Architect PASS Architect writes ADR dispatched profile Red Team reviews ADR kanban gate Programmer builds & commits dispatched profile Completion Verifier git push check origin/main 10min FAIL Block + remediation git push instruction injected into worker PASS Kanban Complete tbl_agent_violations logged Kanban hooks fire automatically at state transitions — no PA memory required. Plugin depth guard: only fires at HERMES_DELEGATION_DEPTH = 0. Boundary gate applies to pa and default profiles only. Architect, Programmer, and Red Team profiles are explicitly excluded.

tbl_triage_rules Schema

Created by migration V301. Every inbound message is evaluated against this table. RLS: service-role only — no tenant-facing access.

Column Type Nullable Notes
rule_idUUIDNOT NULLPK, gen_random_uuid()
jurisdiction_codeTEXTNOT NULLFK → tbl_jurisdictions(id), or '*' for universal. Application layer handles the '*' wildcard — no synthetic row in tbl_jurisdictions.
organisation_idUUIDNULLFK → tbl_organisations. NULL = applies to all orgs in jurisdiction. Non-null = org-specific override, evaluated first within same priority.
channelTEXTNOT NULL'email' | 'whatsapp' | '*'
sender_domainTEXTNULLCase-insensitive substring match against sender email domain.
to_addressTEXTNULLCase-insensitive equality match against tbl_conversations.inbound_address.
subject_regexTEXTNULLPOSIX regex, case-insensitive, tested against conversation subject.
body_regexTEXTNULLPOSIX regex tested against latest message body (truncated to 16KB). Total per-message regex budget: 1000ms via Promise.race().
labelTEXTNOT NULLCHECK in ('Maintenance','Accounts','Enquiries','Compliance','Legal','HR','IT','Marketing','Junk')
confidenceREALNOT NULLDEFAULT 1.0 for rule rows. Range 0.0–1.0.
assigned_byTEXTNOT NULLAlways 'rule' for rows in this table. Propagates to tbl_conversation_labels.assigned_by.
priorityINTEGERNOT NULLEvaluation order within jurisdiction scope. Lower = evaluated first.
is_activeBOOLEANNOT NULLDEFAULT true. Thai portal rules seeded with is_active=FALSE pending Eugin confirmation.
notesTEXTNULLRationale / source documentation for this rule.
created_atTIMESTAMPTZNOT NULLDEFAULT now()
updated_atTIMESTAMPTZNOT NULLDEFAULT now()

MANDATORY CHECK CONSTRAINT

A row with all-null match fields would match every message. V301 must include: CHECK (sender_domain IS NOT NULL OR to_address IS NOT NULL OR subject_regex IS NOT NULL OR body_regex IS NOT NULL)

Evaluation Order SQL

Fetch all active rules for a message in evaluation order. Application-layer regex matching (not SQL) is then applied row-by-row; first full match wins.

SELECT * FROM tbl_triage_rules
WHERE is_active = true
  AND (jurisdiction_code = $jurisdictionCode OR jurisdiction_code = '*')
  AND (channel = $channel OR channel = '*')
  AND (organisation_id = $orgId OR organisation_id IS NULL)
ORDER BY
  CASE WHEN jurisdiction_code = $jurisdictionCode THEN 0 ELSE 1 END,  -- Layer 1 before Layer 2
  CASE WHEN organisation_id = $orgId              THEN 0 ELSE 1 END,  -- Org-specific before wildcard
  priority ASC,
  created_at ASC  -- tiebreaker

Jurisdiction code is resolved from tbl_org_locations.un_locode via SUBSTRING(ol.un_locode FROM 1 FOR 2). Fallback: tbl_conversations.jurisdiction (VARCHAR(2), V285).

Pipeline Wire — Where Code Changes Land

src/lib/bridge/inbound-pipeline.ts

Primary change location. After resolveProperty() completes, call lookupTriageRule(message) (new function, Phase 2 gate). At the end of InboundPipeline.process() after Step 3 (ISSUE), UPSERT the label to tbl_conversation_labels. Conflict target: (conversation_id, label). If the pipeline label write fails, log and continue — label persistence is observability, not a blocker.

src/lib/gmail.ts

Phase 1: sync PORTAL_PATTERNS with conversations/route.ts (add Viewber, Sovereign Pilot Agency). Phase 2 (after ADR-269 Accepted): replace with DB lookup. Do not remove hardcoded patterns until 30 days of production validation confirm rule coverage.

src/app/api/cron/triage-review/route.ts

New file. Tasks A–D (gap detection, drift detection, distribution alert, backfill). Task D guard: check SELECT COUNT(*) FROM tbl_triage_rules WHERE is_active = TRUE before processing any unlabelled conversations — skip entirely if zero.

src/app/api/inbox/label/route.ts

Update VALID_LABELS array to include 'Junk'. Update assigned_by validation to accept 'rule' in addition to 'ai' and 'manual'. This is a separate application-layer change from the V301 DB CHECK constraint expansion — both must ship in the same PR.

vercel.json

Add cron: { "path": "/api/cron/triage-review", "schedule": "0 6 * * 1" } — fires every Monday at 06:00 UTC.

V301 / V302 / V303 Migration Sequence

V301 Schema Blocker — Deploy First
  • Create tbl_triage_rules with all columns and CHECK constraints above.
  • ALTER tbl_conversation_labels.assigned_by CHECK constraint to add 'rule'.
  • ALTER tbl_conversation_labels.label CHECK constraint to add 'Junk'.
  • ADD classifier_raw_output JSONB NULL column to tbl_conversation_labels.
  • Mandatory smoke test immediately after V301: INSERT a test row with assigned_by='rule', verify success, DELETE. If INSERT fails (CHECK violation), abort deployment — do NOT proceed to Phase 2 code.
V302 Operational Monitoring Tables
  • Create tbl_triage_rule_suggestions — weekly cron output, suggestion review queue.
  • Create tbl_triage_audit_log — append-only cron telemetry (ai_fallback_7d, rule_coverage_7d, drift_score, distribution_drift, suggestions_created, backfill_processed).
  • Create tbl_agent_violations — PA boundary enforcement violation log.
V303 Seed Data — Can Re-run Without Schema Changes
  • INSERT all GB (GBLON) rules: UK portals (priority 10–16), UK compliance regex (20–26), UK legal regex (30–36).
  • INSERT all TH (THBKK) rules with is_active=FALSE and confidence=0.8. Do NOT activate until Eugin confirms sender domains (kanban task t_f43381d5).
  • INSERT universal rules: MA/JB ticket refs (priority 5), Sovereign Node enquiry templates (10–15), maintenance keywords (20–23), financial keywords (30–32), HR keywords (40), IT sender domains (50–53), Junk keywords (60).

Deployment Gate (BLOCKER)

V301 MUST be applied before ANY application code referencing assigned_by='rule' is deployed. If Phase 2 code is deployed before V301, every rule-engine label write fails silently (CHECK constraint violation). Because the pipeline is designed not to fail on label write errors, this failure is undetectable — emails process normally, tbl_conversation_labels receives zero rows, and it may run undetected for days. Apply V301, run the smoke test, verify it passes — only then deploy Phase 2 code.

RLS & Index Requirements

Row Level Security

tbl_triage_rules — RLS enabled, service-role read/write only. All tenant-facing policies DENY.
tbl_triage_rule_suggestions — Same as above.
tbl_triage_audit_log — Same — platform internal only.
tbl_agent_violations — Same — platform internal only.

Required Indexes

tbl_triage_rules: composite (jurisdiction_code, is_active, channel, priority) — primary evaluation index.
tbl_triage_rules: partial (organisation_id) WHERE organisation_id IS NOT NULL — org-specific lookup.
tbl_triage_rule_suggestions: (status) — review workflow filtering.
tbl_triage_audit_log: (run_at DESC) — dashboard monitoring queries.

ADR Cross-References

ADR Title Status Relationship
ADR-267 Jurisdiction-Aware Inbound Triage Rules Proposed Core spec: tbl_triage_rules schema, 3-layer evaluation, seed data, weekly cron, V301–V303 migrations.
ADR-268 PA Agent Role Boundary Enforcement Proposed enforce-pa-boundary plugin: pre_tool_call deny, transform_llm_output replacement, pre_llm_call checklist injection. Governs pa and default profiles only.
ADR-269 Triage Rules Admin UI Proposed Gate condition for ADR-267 Phase 2. Must be Accepted and deployed before PORTAL_PATTERNS hardcoding is removed. TriageRulesAdminConsole component, Active Rules + Suggestions tabs, /api/admin/triage-rules endpoints.
ADR-270 Completion Verifier Plugin Proposed kanban_task_completed hook: verifies git push to origin/main within 10 minutes before allowing task completion. Blocks worker and injects remediation instruction on failure.
ADR-095 Unified Inbox & Communications Domain Split Accepted The inbox architecture this page extends.
ADR-241 Anti-Complexity Guardrails Accepted Deterministic-first doctrine: AI should be the last resort, not the first. 99.6% zero-token classification.
ADR-262 Actions Architecture / AI-First Triage Accepted classifyIssue() action-creation logic retained as Layer 3. Labels and actions remain orthogonal concerns.
ADR-259 Self-Alignment Loop Architecture Accepted ADR-268's weekly Red Team violation cron is one leaf of this broader self-improvement loop.

Related: 3.29 Universal Inbox Triage Architecture

The predecessor document covering the verified live email triage path, the seven-layer deterministic filter model, and the three Paperclips disambiguation. This page (3.30) documents the rules system built as a result of that gap analysis. Read 3.29 first for the architectural context.

View 3.29 Universal Inbox Triage Architecture
🔧 Section C: Developer Guide

Architecture Details

Multi-channel messaging architecture that routes inbound and outbound communications through a unified triage engine. The system normalises messages from email, SMS, voice, and app channels into a common format, applies routing rules, and delivers through the appropriate outbound channel with delivery tracking.

  • Core Component: Unified messaging and triage engine
  • Data Flow: Inbound Channel → Normalisation → Triage → Routing → Outbound Channel → Delivery Tracking
  • Integration Points: Email (Gmail IMAP), SMS (Twilio), Voice (Twilio), In-app notifications

Configuration Reference

Key configuration parameters for this system:

Parameter Type Default Description
channel_priority string[] email, sms, voice, in_app Channel priority for outbound delivery
max_retry_count integer 3 Delivery retry attempts per message
triage_rules_version string v1 Active triage rules version
MESSAGING ARCHITECTURE — CHANNEL → TRIAGE → ROUTE 1. CHANNEL LAYER Email / SMS / Voice Inbound Normalisation 📡 Inbound Channels 2. TRIAGE ENGINE Rule Evaluation Priority Routing ⚖️ Triage 3. DELIVERY LAYER Outbound Dispatch Delivery Tracking 📤 Outbound Multi-channel messaging: inbound normalisation → triage rule evaluation → outbound delivery with fallback Channel normalisation · Priority routing · Fallback chains · Delivery tracking Inbound / Channel Layer Triage / Routing Engine Outbound / Delivery Data flow →

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

Troubleshooting

Issue Cause Resolution
Message delivery failure Channel provider outage or invalid recipient address Fallback to next channel in priority list
Triage rule mismatch Rules version outdated for current message type Update to latest triage_rules_version
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.

2026-07-31 cutover · ADR-280/285/286 · V307/V309

Labels SSOT + Conversation Type — The Three-Axis Model

The 2026-07-31 cutover retired the overloaded 16-value conversation_type content mix and replaced it with a clean three-axis model. Content category lives exclusively in tbl_conversation_labels; audience lives in tbl_conversations.conversation_type (internal | external); transport lives in tbl_conversations.channel. This section is the canonical rules-engine reference for that model.

Axis Column / Table Values Consumer
Audience tbl_conversations.conversation_type internal | external Product visibility — staff threads vs customer threads
Routing tbl_conversations.thread_kind customer | staff_bot | system Code path — telegram webhook, staff DM, AI session exclusion
Content tbl_conversation_labels Enquiries, Maintenance, Accounts, Compliance, Legal, HR, IT, Marketing, Junk Human triage + sidebar counts + stats
Transport tbl_conversations.channel email, phone, whatsapp, aigent_telegram, … Channel chip in the UI

Product Locks (Eugin 2026-07-31)

  • Content chips SSOT = tbl_conversation_labels only. No other table stores "what this conversation is about."
  • conversation_type = audience only. Never write enquiry, maintenance, general, agent_aigent into it — V309 dropped those values.
  • Enquiries = sales + lettings only. Not a catch-all for enquiries@ mailbox. Portal tech alerts → IT; newsletters / Gumtree / digests → Junk.
  • Invalid multi-label: Enquiries+IT, Enquiries+Compliance. Engine drops all other candidates when Enquiries wins.
  • Channel chip ≠ category chip. "Email" is transport; "Enquiries" is content. Rendered as separate chips.
  • inbound_address = right-panel RECEIVED AT telemetry. Not a label; mailbox prior is only a weak input signal to the label engine, never its output.
  • Mechanical-first labels; AI residual only (DA1 Option A). No heuristic band. Manual labels never overwritten.
  • Org RLS separate from internal/external. organisation_id scoping unchanged; audience flag does not replace RLS.

Label Engine — Mechanical-First (ADR-280 DA1 Option A)

src/lib/email/label-engine.ts is a pure TypeScript module — no I/O, no DB access, no Next.js imports, no LLM calls. The caller (API route / cron) supplies the rule set and handles all persistence.

Layer Scope Inputs Output
1 — Jurisdiction GB, TH, … org-specific before wildcard sender_domain + subject_regex + to_address + body_regex (16KB truncated) label, assigned_by='rule', confidence=1.0
2 — Universal jurisdiction_code='*' same as Layer 1 label, assigned_by='rule', confidence=1.0
3 — AI Residue no rule matched existing /api/inbox/label path assigned_by='ai', raw output stored for drift diff
— HITL AI confidence < org threshold (default 0.5) — no label written; "Not sure" queue

DA1 Option A lock: no heuristic band. Rules miss → AI residue or HITL only. No shadow score ≥ 0.7 path. Token burn controlled by monthly per-org AI budget with circuit-breaker to HITL.

Enquiries Scope Lock — Sales + Lettings Only (ADR-286 D1/D2)

The Enquiries label fires ONLY on genuine sales/lettings intent. The mailbox prior (enquiries@, lettings@) is demoted from verdict to weak signal — it no longer independently applies the label.

Scenario Label Rule
dominant listing aggregator / incumbent property portal / alternative listings channel / SpareRoom / OpenRent enquiry, viewing, application, offer Enquiries Portal domain AND subject pattern (conjunction, not domain-only)
Portal tech alert — "photos not uploading", "system error", "listing alert" IT dominant listing aggregator tech-error regex extended (priority < enquiry rule)
Gumtree ad, newsletter, saved-search digest arriving at enquiries@ Junk Negative rule priority 4 catches bulk/marketing
Enquiries + any back-office label (IT, Compliance, Legal, HR, Marketing) Invalid Engine drops all other candidates when Enquiries wins

Re-running the Label Backfill (Staff API)

The one-shot backfill route populates labels for historical email conversations that have none. It uses the same mechanical engine as live ingest — no Gmail re-download, no AI spend on the mechanical slice.

POST /api/admin/inbox/label-backfill
Content-Type: application/json
Authorization: <staff session>

{
  "org_id": "optional — omit for all orgs",
  "limit": 500
}

→ Response: { processed: N, labelled: N, skipped_hitl: N, skipped_already: N }
  • Max 500 conversations per call; rate-limited to prevent runaway writes.
  • Skips conversations that already have at least one label.
  • Never overwrites assigned_by='manual' rows (M1 immutability).
  • hitl_needed verdicts are silently skipped — no row written.
  • Gate: T1 golden-set CI gate (170-row fixture) must pass before production backfill writes.

Migration Timeline — V307 + V309

Migration Date Change ADR
V2862026-07-30tbl_conversation_labels created (zero rows initially)ADR-280
V3072026-07-31CHECK hardening: assigned_by gains 'rule'; label CHECK gains 'Junk'; covering index (label, conversation_id)ADR-285
V308a2026-07-31thread_kind column added (routing axis)ADR-286
V3092026-08-01conversation_type repurposed: old 16 values → internal | external; COMMENT ON COLUMN; partial indexADR-286 (amended)

Source of Truth — ADRs & Briefs

  • ADR-273 — Universal Inbox distill doctrine (parent)
  • ADR-267 — Jurisdiction-aware triage rules (rules engine shape)
  • ADR-280 — Mechanical content labels + org email migration (DA1–DA4 delta)
  • ADR-285 — Conversation label SSOT phased retirement (amended: repurpose not drop)
  • ADR-286 — Enquiries scope lock + thread_kind (amended: V309 repurpose)
  • Briefs: architect-mechanical-labels-org-email-migration-2026-07-30.md, architect-inbox-label-ssot-schema-2026-07-31.md, architect-conversation-type-internal-external-2026-07-31.md, architect-mechanical-labels-DA1-DA4-delta-2026-07-31.md
  • Migrations: V307__conversation_labels_ssot_hardening.sql, V309__conversation_type_internal_external.sql
  • Code: portal/src/lib/email/label-engine.ts, portal/src/app/api/cron/gmail-sync/route.ts, portal/src/app/api/inbox/label/bulk/route.ts, portal/src/app/api/admin/inbox/label-backfill/route.ts