RAIA™ Specification

Agentic Code Quality

When AI writes code, it can make confident mistakes — inventing functions that do not exist, or missing edge cases. To prevent this, we use a three-layer checking system: one AI writes the code, a sec

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

When AI writes code, it can make confident mistakes — inventing functions that do not exist, or missing edge cases. To prevent this, we use a three-layer checking system: one AI writes the code, a sec

🧩 Section A: In Plain English

Agentic Code Quality

When AI writes code, it can make confident mistakes. We use a three-layer checking system: one AI writes the code, a second reviews it, and automated tests confirm it works — no code reaches production without all three.

🟢 In Plain English

When AI writes code, it can make confident mistakes — inventing functions that do not exist, or missing edge cases. To prevent this, we use a three-layer checking system: one AI writes the code, a second reviews it, and automated tests confirm it works. No code reaches production unless it passes all three.

Agentic Code Quality

How We Write, Verify, and Ship Code Without Hallucinating — the complete RAIA (Real estate Artificial Intelligence Agent) coding methodology: Hermes orchestrates Claude Code Agent Teams to self-review every change before a human ever sees it.

◉ AITL — Three-Layer Verification ▲ HITL Gate — Promotion Approvals ⬡ Agent Swarm — Reviewer Subagents ✓ ADR-Gated Promotions
3
Agent layers — Hermes → Claude Code Coder → Reviewer Subagent
5
Verification gates before any code reaches production merge
0
Direct SQL Editor usage — all migrations via migrate.sh or Supabase MCP
100%
ADR required for any shadow→gated→autonomous promotion gate change
📌

TL;DR. AI coding agents hallucinate in predictable ways — they invent function signatures, skip edge cases, and confidently write code that passes a casual read but fails at runtime. The RAIA (Real estate Artificial Intelligence Agent) solution is a three-layer pipeline where no single agent has the final word: Hermes decomposes the task, Claude Code writes and self-tests, a dedicated Reviewer subagent checks the diff, and Hermes validates business logic before any HITL gate. This guide is the canonical reference for every RAIA (Real estate Artificial Intelligence Agent) coding workflow.


Chapter 1 Why — The Hallucination Problem

The promise of AI coding agents is real — they can write, refactor, and test code faster than any human. The risk is equally real: they hallucinate, and they do so confidently, in patterns that are invisible to a casual reviewer. Understanding exactly how agents hallucinate is the foundation of every design decision in the RAIA (Real estate Artificial Intelligence Agent) verification pipeline.

How Agents Hallucinate
  • Invent function signatures that don't exist in the actual codebase
  • Reference files they haven't read — guessing path and content from naming conventions
  • Assume database schemas based on column names, not actual information_schema inspection
  • Skip edge cases when the context window fills up — later in the task = lower quality
  • Confidently write code that passes a casual read but throws at runtime
  • Over-extend scope — modify files that weren't part of the task
Why Layered Verification Works
  • Each layer checks different failure modes — no single agent sees everything
  • Reviewer agent is context-clean — not contaminated by the coder's assumptions
  • Hermes holds business rules the coder can't infer from the codebase alone
  • Structured JSON output makes success/failure programmably parseable — no human gut-feel
  • Turn count is a quality signal — high turns = agent struggled, investigate before merging
  • ADR gates create an auditable trail — every promotion decision is recorded

The Cost of Shipping Bad AI-Generated Code

A hallucinated migration that ships to production can corrupt the schema for all tenants simultaneously. An RLS gap in a multi-tenant system can expose one client's data to another — a GDPR breach that triggers regulatory notification obligations. A runaway agent loop without --max-turns can exhaust a month's API budget in under an hour. These are not theoretical risks — they are the failure modes that the RAIA (Real estate Artificial Intelligence Agent) verification pipeline was designed in direct response to.

🚨 Schema Corruption

A hallucinated ALTER TABLE that references a column that doesn't exist in production — the migration fails mid-run, leaving the schema in a partially applied state. All writes fail until manually repaired.

⚠️ RLS Gap

An agent writes a Supabase query without WHERE org_id = auth.uid(). The query works in dev (single tenant). In production, it leaks all rows from all tenants. Invisible until a clever user checks the network tab.

💸 Budget Runaway

An agent without --max-turns hits a test failure, retries, hits it again, produces increasingly large patches, and loops until the API quota is exhausted. A $3 task becomes a $300 incident.

🔑

Core Principle. The solution is not to trust the agent — it is to build a pipeline where the agent's output is verified by another agent before a human ever sees it. No single agent has the final word on correctness. Hermes is the final validator, not because it's smarter, but because it holds business context the coder cannot infer from the codebase alone.


Chapter 2 How — The Three-Layer Verification Pipeline

The pipeline has three distinct layers. Each layer is a separate agent process with a scoped toolset and a clear output contract. No layer shares context with the layer above it — this is intentional. Context contamination is the primary mechanism by which errors propagate undetected through a multi-step pipeline.

Verification Pipeline Architecture

HERMES ORCHESTRATOR CLAUDE CODE CODER REVIEWER AGENT GIT / CI HUMAN (HITL) Task Decomposition + Acceptance Criteria Read Target Files --allowedTools Read Write Code Edit, Bash(npm test) ◉ AITL: Self-Test npm test / pytest Read Git Diff read-only tools only ◉ AITL: Security Scan /security-review + RLS check Structured Verdict JSON approve | request_changes Business Logic Check ADR? RLS? tbl_documents? ◉ AITL: Output Validation subtype == "success"? HITL Gate git merge + CI PR merge → main Human Approval Telegram notify → Gene Shadow Mode → auto-merge no human needed Gated Mode → notify Gene Telegram approval required Auto Promotion → ADR Architecture Decision Record LEGEND ◉ AITL — Automated gate ▲ HITL — Human gate — — Gated path

Layer 1: Hermes Orchestrator

Role: Task Decomposer & Business Logic Validator
  • Holds business context — RAIA (Real estate Artificial Intelligence Agent) architecture, coding conventions, schema rules, ADR history — via persistent memory and skills
  • Decomposes the incoming request into a verifiable goal with explicit acceptance criteria before any coder runs
  • Decides the execution mode: claude -p print mode for single tasks, Agent Teams for parallel work or review pipelines
  • Receives structured JSON output from the coder and applies business-logic checks: does this touch tbl_documents? Does it change RLS? Does it need an ADR?
  • Is the only agent that can approve a change for merge — coder and reviewer cannot self-approve

Layer 2: Claude Code (The Coder)

Role: File Reader, Writer, and Self-Tester
  • Reads actual files before writing — never assumes content from filenames or memory. Enforced by scoping --allowedTools to include Read first
  • Writes code against the real schema — queries information_schema or reads migration files to confirm column names exist before referencing them
  • Runs tests after writing — npm test or pytest, not just a diff review
  • Uses --max-turns to prevent runaway loops. Recommended: 10 for features, 5 for fixes
  • Outputs structured JSON so Hermes can parse subtype and num_turns programmatically
  • Runs in an isolated git worktree when part of an Agent Team — no shared context with the reviewer

Layer 3: Claude Code Agent Teams (The Reviewer)

Role: Context-Clean Peer Reviewer — Research Preview since Feb 2026
  • A dedicated reviewer subagent defined in .claude/agents/reviewer.md — separate process, separate context window, read-only tools only
  • Checks the coder's git diff for: (1) correctness, (2) RLS scoping, (3) no hardcoded credentials, (4) tests pass, (5) README updated if API changed
  • Runs /security-review and /review slash commands on the diff before the result reaches Hermes
  • Communicates via structured JSON verdict: { "verdict": "approve" | "request_changes", "issues": [...] }
  • Peer-to-peer agent communication via git worktrees — the team lead coordinates, workers run in parallel worktrees without shared context contamination
  • The reviewer having read-only tools is a hard requirement — giving Write access defeats the separation-of-concerns purpose

Chapter 3 What — Step by Step

The following five steps are the complete RAIA (Real estate Artificial Intelligence Agent) coding workflow. Every significant change to the RAIA (Real estate Artificial Intelligence Agent) codebase follows this sequence — no exceptions. Steps cannot be skipped; if a step fails, the process restarts from Step 1 with a corrected task frame.

Step 1: Frame the Task Correctly

This is the single most important step. A poorly framed task guarantees hallucination.

❌ BAD — Vague, no constraints, no verification step
Fix the login bug
✅ GOOD — Specific file, precise behaviour, turn limit, scope boundary, verification
The login fails when the user's email contains a + character. The auth flow is in src/app/api/auth/[...nextauth]/route.ts. Fix it so + characters are URL-encoded before being passed to Supabase Auth. Run the existing auth tests after fixing. Do not modify any other files. Max 5 turns.

Rules for Good Task Framing

  • 1
    Name the exact file(s) involved

    Never say "the auth module" — say src/app/api/auth/[...nextauth]/route.ts. The agent cannot make good decisions about files it hasn't been told to look at.

  • 2
    Describe the expected behaviour precisely

    Include: the trigger (what causes the bug), the current (wrong) behaviour, and the target (correct) behaviour. The agent cannot fix what it doesn't understand.

  • 3
    Set a turn limit with --max-turns

    Recommended: 10 for features, 5 for bug fixes, 3 for reviews. High turn count is a quality signal — a simple fix that takes 8 turns means the agent is struggling. Stop and re-frame.

  • 4
    Specify what NOT to change

    "Do not modify any other files" is not optional. Without it, the agent may "helpfully" refactor related code, breaking other tests and expanding the blast radius of the change.

  • 5
    Include the verification step

    Explicitly state how the agent should verify its own work: "run the auth tests after fixing", "query information_schema to confirm the column exists", "curl the endpoint and check the response".

Step 2: Run the Coder in Print Mode

Use claude -p (print mode) for single, bounded tasks. Print mode returns structured JSON output that Hermes can parse programmatically — no human gut-feel required.

# Run the coder with scoped tools and turn limit
claude -p "TASK: [your precisely framed task]" \
  --output-format json \
  --max-turns 10 \
  --allowedTools "Read,Edit,Bash(npm test),Bash(git diff)" \
  --workdir /root/projects/raia

Parse the JSON output. Key fields to check:

Field Expected If Wrong
subtype "success" "error_max_turns" = re-frame with more turns or simpler task; "error_budget" = API quota issue
num_turns <= half max-turns for simple fixes High turn count = agent struggled. Investigate the turn log before accepting the output.
result Describes what was changed and confirms tests passed Vague or evasive result = agent may have hallucinated a fix. Run tests manually.

Step 3: Run the Reviewer Agent

Define the reviewer agent in .claude/agents/reviewer.md. This file is committed to the repo — it is not a one-off prompt. The reviewer agent definition is a first-class engineering artefact.

---
name: reviewer
model: claude-sonnet-4-6
tools: [Read, Bash]
---
You are a senior code reviewer. Review the git diff since the last commit.

Check the following in order:
1. Correctness — does it do what the task description says?
2. RLS — are all database queries role-scoped with WHERE org_id = auth.uid()?
3. Credentials — no hardcoded API keys, secrets, or connection strings
4. Tests — run npm test and confirm all pass
5. README — updated if any public API or CLI interface changed

Output ONLY a JSON object:
{ "verdict": "approve" | "request_changes", "issues": ["issue1", ...] }

Run the reviewer:

claude -p "@reviewer review the latest changes" \
  --output-format json \
  --max-turns 3 \
  --workdir /root/projects/raia
⚠️

Known Bug (Feb 2026). Claude Code Agent Teams currently ignores per-agent model: config in the agent definition file. All subagents use the project default model regardless of what is specified. Do not rely on per-agent model overrides until this is patched. See Pitfall #5.

Step 4: Hermes Validates Business Logic

Hermes receives the reviewer's JSON verdict and applies business-logic rules that the reviewer agent cannot know from the codebase alone. These rules are held in Hermes' persistent memory and skills — not in the RAIA (Real estate Artificial Intelligence Agent) repo.

#
Business Logic Check
Trigger
Action if Yes
📋
Does this change any agent promotion gate (SHADOW→GATED, GATED→AUTO)?
ADR Trigger
Block merge — ADR required in same PR
🗄️
Does it write to tbl_documents? Check both FK columns AND tbl_document_links are updated
Data Integrity
Block merge — both tables must be touched
📦
Does it add a new npm/pip dependency to the project?
Supply Chain

Repository Code

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

s="gate-risk">Require justification in PR description
🔒
Does it modify an RLS policy on any Supabase table?
Security
Director-level review — notify Gene on Telegram
🗃️
Does it introduce a migration? Was it applied via bash migrate.sh or Supabase MCP?
Protocol
Block merge — SQL Editor is never acceptable

Step 5: HITL Gate or Auto-Merge

The final decision depends on the current promotion mode of the change. This is not determined at merge time — it is determined by the shadow/gated/auto classification that was established when the feature was originally planned.

Shadow Mode Changes

Auto-merge after reviewer approval and Hermes validation. No human approval needed. The change is observed in production but its output is not yet acted on by downstream systems.

Gated Mode Changes

Hermes notifies Gene on Telegram with a summary of the change and reviewer verdict. Gene must explicitly approve before Hermes triggers the merge. 24h timeout = block.

Autonomous Promotion

Requires an ADR committed in the same PR. No ADR = Hermes blocks the merge unconditionally. ADR must reference the specific SHADOW→GATED or GATED→AUTO transition being made.


Chapter 4 RAIA-Specific Gates

The following gates are RAIA-specific rules that go beyond what a generic coding pipeline enforces. They exist because the RAIA (Real estate Artificial Intelligence Agent) system operates on real tenancy data, with real multi-tenant RLS requirements, and real regulatory exposure. These are not suggestions — they are enforced by Hermes and by the ADR log.

SISO Build Order (Single Input, Single Output)

🔁

SISO Rule: Always follow this exact sequence. Never skip steps to go faster. Speed gained by skipping shadow mode is always repaid with interest when an unobserved agent causes a production incident.

  • Stage 1 — Data Audit: Inspect the real data before writing any code. Confirm what actually exists in the database, not what the schema migration history suggests.
  • Stage 2 — Fix Critical Issues: Resolve any data quality issues, broken FK references, or orphaned records before the new pipeline runs against them.
  • Stage 3 — Shadow Mode: Deploy the new agent behaviour to production but route its output to a log, not to the live system. Observe for at least one full business cycle.
  • Stage 4 — Paperclip Integration: Connect the shadow output to the Paperclip monitoring dashboard for structured review before promotion.
  • Stage 5 — Agent 1 Promotion: With observed shadow data confirming correct behaviour, promote the agent to gated or autonomous mode per the ADR.
🚫

Never skip to Stage 5. "We'll add shadow mode later" is how production incidents happen. The shadow stage exists precisely so agents can be observed before they act autonomously on real tenancy data. A rushed promotion that causes a data corruption event cannot be undone with a git revert.

ADR Requirement for Promotion Gates

Any change to an agent promotion gate — SHADOW→GATED or GATED→AUTO — requires an Architecture Decision Record committed in the same PR as the code change. The ADR must be at 03_technology/architecture/decisions/ADR-XXX.md.

📄
03_technology/architecture/decisions/ADR-NNN.md
Required structure: Context (why this promotion is being made now), Decision (exact gate being changed: SHADOW→GATED or GATED→AUTO), Consequences (what changes in behaviour, what monitoring is in place), ADR number must be referenced in the PR description. Hermes will refuse to approve a promotion without a verifiable ADR reference.
✓ Valid ADR Triggers
  • Moving an agent from observing-only to gated-human-approval mode
  • Moving an agent from gated approval to fully autonomous execution
  • Changing the scope of what an agent can autonomously modify (e.g. adding write access to a new table)
  • Changing the model used for a production agent (e.g. Sonnet → different version)
✗ ADR Not Required
  • Bug fixes within an existing agent's current permission scope
  • Adding a new agent in shadow mode (shadow is the safe default)
  • Changing prompt wording that does not alter tool permissions or promotion gates
  • Documentation-only changes

Any pipeline or migration that writes to tbl_documents must update both of the following simultaneously:

1. FK Columns on tbl_documents

The denormalized foreign key columns on tbl_documents itself (e.g. person_id, tenancy_id, org_id). These exist for query speed — direct joins without traversing the link table.

Performance Fast reads, single-table scans

2. tbl_document_links (Many-to-Many)

The tbl_document_links many-to-many relationship table. This is required for relationship traversal — finding all documents linked to a person across multiple tenancies, for example.

Integrity Relationship traversal, audit trail

⚠️

Claude Code does not know this rule. It cannot infer the dual-update requirement from the schema alone. Hermes enforces it by inspecting every diff that touches tbl_documents and verifying that tbl_document_links is also updated. If the diff only touches one of the two, Hermes blocks the merge and sends a correction request to the coder.

Never the SQL Editor

🚫

Absolute Rule. All database migrations go through bash migrate.sh or Supabase MCP. Never the Supabase SQL Editor.

SQL Editor changes are:

  • Untracked — they do not appear in git history or the migration log
  • Unreviewable — no PR, no reviewer agent, no ADR gate
  • Irreproducible — cannot be replayed on a branch or staging environment
  • Production-direct — changes apply immediately with no undo on failure

This rule is enforced by the reviewer agent instructions (which check for migration artefacts) and by the ADR log. Any SQL Editor usage that is discovered in a post-incident review is treated as a process violation, not a technical mistake.


Pitfalls Known Failure Modes

1
CRITICAL — Letting Claude Code Read from Memory Instead of Files

Always use --allowedTools Read and verify in the turn log that the agent actually issued a Read call on the target file before writing. If the agent writes code without a preceding Read call, it is operating from memory or inference — both are hallucination vectors. The turn log is the ground truth.

2
CRITICAL — Not Setting --max-turns

A runaway agent loop without a turn limit can exhaust your monthly API budget in under an hour. A task that hits a test failure will retry indefinitely, producing increasingly large and increasingly wrong patches with each iteration. Always set --max-turns. Recommended: 10 for features, 5 for fixes, 3 for reviews. No exceptions.

3
CRITICAL — Skipping the Reviewer Step on Database-Touching Changes

RLS gaps are invisible until exploited. A query missing a WHERE org_id = auth.uid() clause returns correct results in a single-tenant dev environment and silently leaks all rows from all tenants in production. The reviewer agent's RLS check is the primary defence against this class of error. It cannot be skipped on any migration or query change.

4
CAUTION — High Turn Count Means the Agent Is Struggling

A simple bug fix that takes 8+ turns is a warning sign, not a success. High turn count usually means the task was under-specified, the agent can't find the relevant file, or it's in a retry loop. Stop the task, re-frame with more specific file paths and constraints, and restart. Merging high-turn-count output without investigation is how hallucinated "fixes" reach production.

5
CAUTION — Agent Teams Model Config is Currently Ignored (Feb 2026 Bug)

All agents in a Claude Code Agent Team use the project's default model, regardless of the model: field specified in the agent's .md definition file. Do not rely on per-agent model overrides. If different agents need different models, you must run them as separate claude -p invocations with explicit model flags. Track this bug in the Claude Code release notes.

6
CAUTION — --dangerously-skip-permissions is Blocked When Running as Root

The --dangerously-skip-permissions flag is blocked by Claude Code when the process is running as root (which is the case in the RAIA (Real estate Artificial Intelligence Agent) dev environment). Use tmux interactive mode instead: start a tmux session, run claude interactively, and let the agent prompt for permission approvals in-session. Never attempt to work around the root restriction.

7
INFO — Agent Teams Uses Git Worktrees — Ensure Clean Working Directory

Claude Code Agent Teams creates git worktrees for each subagent. If the project has uncommitted changes when a team run starts, those changes will appear in the base worktree and may be picked up by multiple agents, causing merge conflicts or unexpected behaviour. Always run git status and ensure a clean working directory before starting an Agent Teams run.

8
INFO — Reviewer Agents Must Have Read-Only Tools

Reviewer agents should only have Read and Bash (for running tests) in their tools: list. Giving a reviewer agent Edit or Write access defeats the entire separation-of-concerns purpose of the three-layer pipeline. If the reviewer can modify the code it's reviewing, the review is self-referential and provides no independent signal.


Vibe Check Pre-Run & Post-Run Gates

Run through this checklist before starting a coding task and again after the reviewer agent returns its verdict. A "no" on any pre-run gate = stop and fix before proceeding. A "no" on any post-run gate = do not merge.

Pre-Run Gates

  • ☐ Task is framed with exact file names, expected behaviour, turn limit, and what NOT to change
  • ☐ No uncommitted changes in working directory — git status is clean
  • ☐ Correct project directory set as --workdir
  • ☐ --max-turns is set — 10 features · 5 fixes · 3 reviews
  • ☐ --allowedTools is scoped to minimum required — not wildcard
  • ☐ If database-touching: reviewer agent is in .claude/agents/reviewer.md
  • ☐ If promotion-gate change: ADR draft is ready to commit alongside the change

Post-Run Verification

  • ✓ subtype == "success" in JSON output — not error_max_turns or error_budget
  • ✓ Reviewer agent returned "verdict": "approve" with empty issues array
  • ✓ Tests pass — npm test or pytest green, not skipped
  • ✓ git diff reviewed — no unintended file changes outside task scope
  • ✓ If tbl_documents touched: both FK columns AND tbl_document_links updated
  • ✓ If promotion gate changed: ADR exists and is committed in same PR
  • ✓ If gated-mode change: Hermes notified Gene on Telegram and approval received
  • ✓ Migration (if any) applied via bash migrate.sh or Supabase MCP — never SQL Editor

Reference Tech Stack & Context

🗂️
Repo
github.com/estateaigents/raia — monorepo. All RAIA (Real estate Artificial Intelligence Agent) platform code. Agent framework at 03_technology/07_agent-framework/
⚡
Frontend
Next.js 14+ App Router · TypeScript · Tailwind CSS · Supabase client
🗃️
Migrations
bash migrate.sh or Supabase MCP only. NEVER Supabase SQL Editor.
🤖
Agent Framework
Hermes (orchestrator) → Claude Code (coder) → Claude Code Agent Teams (reviewer). All three are required for database-touching changes.
🧪
Tests
npm test for Next.js · pytest for Python pipelines. Tests must be run by the coder agent — not skipped.
📋
ADR Location
03_technology/architecture/decisions/ — all ADRs. ADR number in STATE.md. Never elsewhere.
🧠
Default Model
claude-sonnet-4-6 — never Opus unless explicitly required (ADR-083). Agent Teams model config bug: all subagents use default regardless of per-agent config.
🔑
API Keys
Per-project in .claude/settings.local.json only. Never in ~/.claude.json or committed to git.
🌿
Branch Convention
feature/* · fix/* · infra/* — main is protected. Commit format: type(scope): description

© 2026 EstateAigents.com Ltd. Company No. 07801820. All Rights Reserved.

§ 3.9a Agentic Code Quality · ← Back to RAIA (Real estate Artificial Intelligence Agent) Documentation

Repository Code

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