RAIA™ Specification

Loop Craft & Recursive Self-Improvement

Closed-loop architecture for agentic systems: execution, observation, evaluation, and remediation in a self-healing pipeline. The difference between a script and a real autonomous system.

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

Closed-loop architecture for agentic systems: execution, observation, evaluation, and remediation in a self-healing pipeline. The difference between a script and a real autonomous system.

A

ELI5: Why Top Agentic Engineers Build Loops, Not Chatbots

💡 The Core Insight

Most "AI agents" are just chatbots with API access. You ask, they make one API call, return the result, and stop. This is an open-loop architecture—like sending someone to do a task without ever checking if they actually did it right.

Top agentic engineers design closed-loop architectures. The agent doesn't just execute—it observes the result, evaluates if it worked, and if not, self-heals. This is the difference between a script and a real autonomous system.

∞ The Closed-Loop Architecture Pattern

1

EXECUTION

Agent performs the action (sends email, updates database, calls API)

2

OBSERVATION

System monitors what actually happened (logs, webhooks, database state)

3

EVALUATION

Check if the outcome matches the expected state (compliance rules, business logic)

4

REMEDIATION (Self-Healing)

If something failed, automatically retry, escalate, or trigger corrective action

✅ Example: Open vs Closed Loop

❌ Open-Loop (Chatbot Wrapper)
User: "Send invoice to tenant" Agent: calls sendEmail() Agent: "Done! ✓"

Problem: What if the email bounced? What if the tenant's email was wrong? The agent never knows.

✅ Closed-Loop (Real Agent)
1. calls sendEmail() 2. waits for webhook/bounce event 3. checks delivery status in logs 4. if bounced → fallback to SMS

Result: Self-healing. The agent ensures the message was delivered, or tries another channel.

CLOSED-LOOP PIPELINE — EXECUTION → OBSERVATION → EVALUATION → REMEDIATION 1. EXECUTION Agent performs action sends email, calls API, updates database 🤖 Agent acts → 2. OBSERVATION System monitors outcome reads logs, webhooks, database state 👁️ System observes 3. EVALUATION Check outcome vs expected compliance rules, business logic, confidence scores ✅ Pass / ❌ Fail 4. REMEDIATION Self-healing / escalate retry with backoff, escalate to human 🔄 Retry / Escalate ⤴ Feedback Loop — If remediation fails, re-enter Execution phase Closed-loop ensures every action is verified — if it didn't work, the system tries again or escalates, never assuming success. Open-loop agents fail silently · Closed-loop agents self-heal · This is the difference between a script and a real autonomous system

Figure 1: The Closed-Loop Pipeline — Execution → Observation → Evaluation → Remediation with feedback loop for self-healing.

B

User Guide: The 6 Live Closed-Loop Systems on RAiA

RAiA (Real estate Artificial Intelligence Agent) Platform runs six production-grade closed-loop systems right now. Each one follows the Execution → Observation → Evaluation → Remediation pattern.

1

The Ingest Triage Loop (T1–T2)

Multi-Channel Communication Router

What it does: Evaluates incoming communication from Gmail, Twilio Voice, WhatsApp webhooks, and classifies + routes them to the right handler.

EXECUTION: Webhook triggers on new email/call/message
OBSERVATION: Extracts sender, subject, body, attachments
EVALUATION: LLM classifies intent (viewing request, maintenance, rent payment, complaint)
REMEDIATION: Routes to specialist agent (MaintenanceAgent, ViewingAgent, PaymentAgent) or escalates to human if confidence < 0.7

Observability: Logs every classification to tbl_comms_log with confidence scores. Dashboard shows misrouting rate.

2

The Compliance Audit Loop (T4)

Safety Certificate & Identity Verification Scanner

What it does: Programmatically scans all properties for missing safety certificates (gas, electrical, EPC) and beneficial identity verification, then triggers landlord outreach asynchronously.

EXECUTION: Nightly cron queries tbl_assets for expired/missing certs
OBSERVATION: Checks GCS bucket + database for uploaded documents
EVALUATION: Expiry date < 30 days = WARNING, < 7 days = CRITICAL
REMEDIATION: Auto-generates chase email, logs to tbl_compliance_chases, escalates to portal alert if no response in 48h

Observability: Real-time compliance dashboard shows cert coverage %, open chase tasks, and landlord response SLA.

3

The Media Deduplication Loop (T4)

Cryptographic Image Hash Deduplicator

What it does: Runs cryptographic image hashing (MD5/SHA256) to deduplicate portal uploads and sync the media carousel.

EXECUTION: On image upload, compute perceptual hash
OBSERVATION: Query tbl_media_hashes for existing match
EVALUATION: If hash collision detected, check if same asset_id
REMEDIATION: If duplicate, skip upload + link existing media_id. If different asset, allow (same photo used for multiple properties)

Observability: Dashboard shows deduplication savings (GB saved, avoided Cloudinary charges).

4

The Rent Arrears Escalation Loop (T5)

Weekly Payment Latency Checker & Auto-Charge

What it does: Weekly cron checks expected vs actual rent payments, calculates tenant behavioral scores, and initiates direct payment card charges or reminder flows.

EXECUTION: Query tbl_rents for outstanding invoices WHERE due_date < CURRENT_DATE
OBSERVATION: Join with tbl_tenancy_scores to get payment history
EVALUATION: days_overdue < 3 = auto-charge saved card, > 3 = SMS reminder, > 7 = formal notice
REMEDIATION: Trigger Stripe charge API if card on file, else send SMS with payment link, log escalation path

Observability: Arrears dashboard shows at-risk tenancies, auto-recovery success rate, and notice pipeline.

5

The Paperclip Swarm Loop (T1–T6)

Multi-Agent Orchestration & HITL Approval Queue

What it does: Coordinates specialized subagents (EvictionAgent, MaintenanceAgent, ViewingAgent), aggregates their outputs, drafts replies, and gates them with Human-in-the-Loop (HITL) approval queues.

EXECUTION: Orchestrator delegates task to specialist agent (e.g., MaintenanceAgent for repair request)
OBSERVATION: Agent returns draft reply + confidence score + suggested next actions
EVALUATION: If confidence > 0.85 and task_type in AUTO_APPROVED_LIST → send. Else → queue for human review.
REMEDIATION: If human rejects, log rejection reason to tbl_agent_feedback and retrain prompt embeddings

Observability: HITL dashboard shows approval rate per agent, avg human review time, and rejection patterns (feeds back into fine-tuning).

6

The Memory-Sync & Self-Improvement Loop

Conversation Analysis → Skill Extraction → Memory Registry Update

What it does: Automatically analyzes completed conversation threads to extract durable facts and write new .agents skills or update L0→L1→L2→L3 memory registries (TencentDB).

EXECUTION: On conversation marked "completed", extract key facts (new property rules, tenant preferences, landlord quirks)
OBSERVATION: Check if similar fact exists in tbl_memory_l0 (session), l1 (person), l2 (org), l3 (global knowledge)
EVALUATION: If novel + confidence > 0.8 → promote to durable memory. If contradicts existing → flag for human review.
REMEDIATION: Write to TencentDB memory layer, update RAG embeddings, generate .agents skill file if reusable workflow discovered

Observability: Memory dashboard shows facts learned per week, memory layer distribution (L0/L1/L2/L3), and skill generation rate.

C

Developer Guide: Code Optimizations & Modular Architecture

🔐 Section C: Developer Access Only

This section contains implementation details, database schemas, and code optimization patterns. Visible only to developers with @estateaigents.com email addresses or local/Tailscale access.

⚙️ The Mirror Principle: Perfect 1:1 Mapping

RAiA enforces strict Mirror Principle: documentation, database schema, and repository structure are perfectly mapped 1:1. If a feature exists in code, it has a matching doc page, database table, and folder in the repo.

Programmatic Enforcement

  • ✓ Nightly CI workflow: nightly-doc-audit.yml
  • ✓ Doc link checker: doc-audit.cjs scans for broken refs
  • ✓ ADR validator: ensures every ADR updates corresponding README.md
  • ✓ Zero tolerance for documentation drift—builds fail if docs are stale

🚫 Hard 500-Line File Limit (Anti-Monolith Rule)

Rule: No single file may exceed 500 lines. Monoliths lead to agent hallucination (models lose context) and UI rendering lag (browser struggles with huge DOMs).

⚠️ Real Incident: Landlord Menu Monolith

The landlord menu component was originally 1,200 lines. Claude Sonnet 4 started hallucinating imports that didn't exist, and the browser took 800ms to render the page. We split it into 6 files under components/landlord/—render time dropped to 120ms, and agent accuracy went from 70% to 95%.

components/landlord/
├── LandlordMenuHeader.tsx (80 lines)
├── LandlordPropertiesList.tsx (150 lines)
├── LandlordCompliancePanel.tsx (180 lines)
├── LandlordPaymentSettings.tsx (120 lines)
├── LandlordNotificationPrefs.tsx (90 lines)
└── helpers/landlordUtils.ts (140 lines)

⚡ Performance Optimizations for Speed

Loop execution speed matters. We aggressively optimize hot paths with React hooks and cancellation policies.

useMemo Eliminate Rendering Lag on Logs

Compliance audit logs can be 10,000+ rows. Without memoization, React re-renders the entire table on every state change, causing 2-3 second UI freezes.

const filteredLogs = useMemo(() => {
  return logs.filter(log => 
    log.status === filter && 
    log.timestamp >= dateRange.start
  );
}, [logs, filter, dateRange]);

✓ Result: Render time reduced from 2.8s → 80ms

useCallback Stable Callbacks for Child Components

Parent component was creating new function instances on every render, causing child re-renders even when props didn't change.

const handleApprove = useCallback((taskId: string) => {
  approveTask(taskId);
  invalidateTasksQuery();
}, [approveTask, invalidateTasksQuery]);

✓ Result: Child component re-renders dropped 90%

AbortController Eliminate Memory Leaks on Org-Switch

When users switched organizations mid-fetch, old requests completed and tried to update unmounted components → memory leak + stale data corruption.

useEffect(() => {
  const controller = new AbortController();
  
  fetch('/api/compliance/audit', { 
    signal: controller.signal 
  })
    .then(res => res.json())
    .then(setAuditData)
    .catch(err => {
      if (err.name !== 'AbortError') throw err;
    });
  
  return () => controller.abort();
}, [orgId]);

✓ Result: Zero memory leaks, zero stale data bugs since deployment

📊 Observability: Metrics for Every Loop

Every closed-loop system emits structured logs to tbl_loop_metrics for real-time dashboards.

Standard Metrics Schema

loop_name: string (e.g., "rent_arrears_escalation")
execution_time_ms: integer
success: boolean
remediation_triggered: boolean
confidence_score: float (0.0-1.0)
human_review_required: boolean
error_message: string | null
timestamp: timestamptz

🔁 Loop-First Design Pattern (Code Template)

Every new autonomous feature should follow this template:

// 1. EXECUTION PHASE
async function executeAction(context: TaskContext) {
  const result = await performAction(context);
  await logExecution(result);
  return result;
}

// 2. OBSERVATION PHASE
async function observeOutcome(executionId: string) {
  const state = await querySystemState(executionId);
  const logs = await fetchRelevantLogs(executionId);
  return { state, logs };
}

// 3. EVALUATION PHASE
function evaluateSuccess(observation: Observation, expected: Expected) {
  const meetsGoal = observation.state === expected.state;
  const withinSLA = observation.elapsed < expected.maxTime;
  const confidence = calculateConfidence(observation);
  
  return { 
    success: meetsGoal && withinSLA, 
    confidence,
    needsRemediation: !meetsGoal 
  };
}

// 4. REMEDIATION PHASE
async function remediate(evaluation: Evaluation) {
  if (!evaluation.needsRemediation) return;
  
  if (evaluation.confidence < 0.5) {
    await escalateToHuman(evaluation);
  } else {
    await retryWithBackoff(evaluation);
  }
}

// MAIN LOOP
async function runClosedLoop(task: Task) {
  const exec = await executeAction(task);
  const obs = await observeOutcome(exec.id);
  const eval = evaluateSuccess(obs, task.expected);
  
  await remediate(eval);
  await emitMetrics(exec, obs, eval);
}
LOOP ARCHITECTURE — MODULAR COMPONENT MAP SERVICE LAYER — Closed-Loop Components 🔄 Ingest Triage Loop (T1–T2) Multi-channel comms routing 📋 Compliance Audit Loop (T4) Safety cert + ID verification 🖼️ Media Dedup Loop (T4) Cryptographic hash dedup 💰 Rent Arrears Loop (T5) Weekly payment latency + auto-charge ORCHESTRATION LAYER — Swarm Coordination 🤖 Paperclip Swarm Loop (T1–T6) Multi-agent orchestration 🧠 Memory-Sync Loop L0→L3 memory extraction 🎯 HITL Approval Queue Human review + feedback loop ⚡ Auto-escalation Engine Confidence-based routing OBSERVABILITY LAYER — Metrics & Monitoring 📊 Loop Metrics Dashboard tbl_loop_metrics in real-time 📝 Structured Logs Execution time, success, remediation 📈 Agent Feedback Pipeline Rejection patterns → fine-tuning 📋 Compliance Reports Coverage %, SLA metrics Three-layer architecture: isolated service loops → orchestrated swarm → real-time observability — every component emits metrics. Service loops are independently deployable · Orchestrator coordinates cross-loop workflows · Observability feeds back into agent fine-tuning

Figure 2: Three-Layer Loop Architecture — each service component is independently deployable and feeds metrics into the observability layer.

🎯 Key Takeaway for Developers

Never build a feature that executes and forgets. Every action must have observation, evaluation, and remediation paths. If you can't measure whether it worked, you can't deploy it. This is the difference between a script and a production-grade autonomous system.

🔧 Section C: Developer Guide

Architecture Details

Multi-agent architecture with a hierarchical orchestration model. The orchestrator agent manages task decomposition, worker agent dispatch, and result aggregation. Each agent runs in an isolated context with its own toolset and memory, communicating via a shared message bus. The closed-loop ensures every action is verified — if it didn't work, the system tries again or escalates, never assuming success.

  • Core Component: Agent orchestration engine with feedback loop
  • Data Flow: Execution → Observation → Evaluation → Remediation → (feedback loop back to Execution)
  • Integration Points: Tool registry, memory stores, LLM inference, delegation bus, observability pipeline

Configuration Reference

Key configuration parameters for closed-loop agent systems:

Parameter Type Default Description
max_loop_iterations integer 3 Maximum remediation loop iterations before escalation
observation_timeout_ms integer 30000 Max time to wait for observation feedback
evaluation_threshold float 0.85 Confidence threshold for pass/fail evaluation

Troubleshooting

Issue Cause Resolution
Infinite loop detected Remediation never reaches pass threshold Reduce max_loop_iterations or add escalation gate
Observation timeout Downstream system not responding to webhook Increase observation_timeout_ms or implement polling fallback
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.