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.
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.
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
EXECUTION
Agent performs the action (sends email, updates database, calls API)
OBSERVATION
System monitors what actually happened (logs, webhooks, database state)
EVALUATION
Check if the outcome matches the expected state (compliance rules, business logic)
REMEDIATION (Self-Healing)
If something failed, automatically retry, escalate, or trigger corrective action
✅ Example: Open vs Closed Loop
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.
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.
Figure 1: The Closed-Loop Pipeline — Execution → Observation → Evaluation → Remediation with feedback loop for self-healing.
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.
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.
Observability: Logs every classification to tbl_comms_log with confidence scores. Dashboard shows misrouting rate.
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.
tbl_assets for expired/missing certstbl_compliance_chases, escalates to portal alert if no response in 48hObservability: Real-time compliance dashboard shows cert coverage %, open chase tasks, and landlord response SLA.
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.
tbl_media_hashes for existing matchObservability: Dashboard shows deduplication savings (GB saved, avoided Cloudinary charges).
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.
tbl_rents for outstanding invoices WHERE due_date < CURRENT_DATEtbl_tenancy_scores to get payment historyObservability: Arrears dashboard shows at-risk tenancies, auto-recovery success rate, and notice pipeline.
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.
tbl_agent_feedback and retrain prompt embeddingsObservability: HITL dashboard shows approval rate per agent, avg human review time, and rejection patterns (feeds back into fine-tuning).
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).
tbl_memory_l0 (session), l1 (person), l2 (org), l3 (global knowledge).agents skill file if reusable workflow discoveredObservability: Memory dashboard shows facts learned per week, memory layer distribution (L0/L1/L2/L3), and skill generation rate.
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.cjsscans 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%.
⚡ 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-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); }
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.
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 |
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.