# MudraForge Technical Architecture Notes — Day 3
**Topic:** Inside an Agent Execution Run — End-to-End Operational Lifecycle, Webhook Deduplication, and Deterministic Gating  
**Companion Video:** [Watch on YouTube](https://youtu.be/v2Y7wSJ5EM4)  
**Author:** Mondeep Engti, Founder @ MudraForge  
**Canonical Specification:** `https://mudraforge.in/series/day3`  
**Series:** MudraForge — Building Organizational AI (Day 3 of 7)

---

## 1. Executive Summary

Day 2 established the foundational architecture separating non-deterministic model reasoning from the deterministic execution runtime. Day 3 traces a single, concrete operational request through that runtime from end to end.

Using an illustrative operational scenario—an after-hours (11:30 PM) customer service reservation and state verification request on WhatsApp—this document details the 5-stage execution cycle: edge webhook verification, cryptographic deduplication, context grounding (Hybrid RAG), structured tool intent extraction, deterministic tenant permission gating, and tamper-evident audit logging with Ed25519 state signatures.

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                 5-STAGE RUNTIME LIFECYCLE FOR AN AGENT REQUEST              │
│                                                                             │
│  [Stage 1] Inbound Webhook ──▶ Edge Isolate & SHA-256 Deduplication Key     │
│                  │                                                          │
│  [Stage 2] Context Injection ──▶ Dynamic RAG (Customer History + Policy)    │
│                  │                                                          │
│  [Stage 3] Model Reasoning ──▶ Emits Structured Intent (<mudra_tool>)       │
│                  │                                                          │
│  [Stage 4] Deterministic Gate ──▶ tool_dispatch.js (VALID_TOOLS & RBAC)     │
│                  │                                                          │
│  [Stage 5] State & Outbound ──▶ agent_ledger Commit & WhatsApp Delivery     │
└─────────────────────────────────────────────────────────────────────────────┘
```

---

## 2. The 5-Stage Execution Sequence

Below is the complete sequence trace for a single operational transaction moving through the MudraForge runtime:

```
Customer (WhatsApp)     Edge Worker (/whatsapp)     Context Engine       Reasoning Model     tool_dispatch.js     Skill Executor     Database / Ledger
       │                          │                        │                    │                   │                   │                    │
[11:30 PM]                        │                        │                    │                   │                   │                    │
  ─────▶ Inbound Message ────────▶│                        │                    │                   │                   │                    │
       │                          ├─ 1. Verify HMAC Signature                   │                   │                   │                    │
       │                          ├─ 2. Deduplication Cache Check               │                   │                   │                    │
       │                          │                        │                    │                   │                   │                    │
       │                          │─── Fetch Session & ───▶│                    │                   │                   │                    │
       │                          │    Operating Rules     │                    │                   │                   │                    │
       │                          │◀── Verified Context ───│                    │                   │                   │                    │
       │                          │                        │                    │                   │                   │                    │
       │                          │─── Assemble Prompt & Messages ─────────────▶│                   │                   │                    │
       │                          │                                             │                   │                   │                    │
       │                          │                                             ├─ Parse Request    │                   │                    │
       │                          │                                             ├─ Plan Multi-Step  │                   │                    │
       │                          │                                             │  Resolution       │                   │                    │
       │                          │◀── Emits Structured <mudra_tool> Intent ────│                   │                   │                    │
       │                          │                                                                 │                   │                    │
       │                          │─── Intercept & Validate Tool Call ─────────────────────────────▶│                   │                    │
       │                          │                                                                 ├─ VALID_TOOLS?     │                    │
       │                          │                                                                 ├─ tenant.enabled?  │                    │
       │                          │                                                                 ├─ Schema Valid?    │                    │
       │                          │                                                                 │                   │                    │
       │                          │                                                                 │─── Execute ──────▶│                    │
       │                          │                                                                 │    Capability     │                    │
       │                          │                                                                 │                   ├─ Lock Bay / Slot   │
       │                          │                                                                 │                   ├─ Verify State      │
       │                          │                                                                 │◀── Result Data ───┤                    │
       │                          │                                                                 │                   │                    │
       │                          │                                                                 │─── Write Record ──────────────────────▶│
       │                          │                                                                 │    (agent_ledger, tool_logs, archive)  │
       │                          │                                                                 │    Signed with Ed25519                 │
       │                          │                                                                 │                                        │
       │                          │◀── Formatted Confirmation ──────────────────────────────────────│                                        │
       │                          │                                                                                                          │
  ◀───── Outbound WhatsApp ───────│                                                                                                          │
       │ Response Dispatched      │                                                                                                          │
```

---

## 3. Deep Dive into Runtime Subsystems

### Stage 1: Webhook Ingestion, Platform Trust & Deduplication
When a customer sends a message at 11:30 PM:
1. **Edge Route:** The webhook is received by the Cloudflare Worker at `/whatsapp`.
2. **Platform Trust Verification (HMAC-SHA256):** Meta's WhatsApp Cloud API signs inbound webhooks using symmetric HMAC-SHA256. Before parsing any body payload, `verifyPlatformIntegrity()` validates the `X-Hub-Signature-256` header against tenant app secrets to ensure authenticity.
3. **Idempotency Hash Index (`signature_lookup`):**
   * Mobile networks often retry HTTP webhook deliveries if a network spike occurs.
   * MudraForge hashes the message payload (`sha256(sender_id + timestamp + message_content)`).
   * It queries the fast KV cache and the unique `signature_lookup` sparse index on `chat_archive`.
   * If a duplicate hash is found, the runtime returns the previously cached response immediately without re-triggering reasoning or executing duplicate bookings.

---

### Stage 2: Context Grounding (Pre-Reasoning & Dynamic Retrieval)
Context grounding begins before reasoning and can be supplemented dynamically during the execution loop:
1. **User Identity Resolution:** The sender's phone number is mapped to `mudra_identities` to pull previous service history, vehicle tags, and cross-platform interaction state from `chat_archive`.
2. **Dynamic Rule Injection:** Active operational boundaries are retrieved from `mudra_knowledge_base` (e.g., maximum daily bay capacity, technician schedules, holiday calendars).
3. **Prompt Composition:** `lib/core/prompt_composer.js` injects the retrieved facts into the system context. The model reasons over established facts rather than statistical assumptions.

---

### Stage 3: Structured Model Intent Emission
The model parses natural language and formulates a plan. Crucially, the model **never executes an API or mutates a database directly**. It emits a structured tool tag wrapping a JSON parameter payload:

```xml
<mudra_tool name="book_automotive_service">
{
  "vehicle_id": "AS-01-EF-4921",
  "service_type": "periodic_40k",
  "preferred_slot": "2026-08-19T09:30:00Z"
}
</mudra_tool>
```

---

### Stage 4: Deterministic Dispatch & Tenant Validation Gate
The MudraForge runtime intercepts the stream before any external action occurs:
1. **Extraction (`extractToolCalls` in `tool_dispatch.js`):** Sanitizes and extracts the tool name and JSON parameters from the XML tag.
2. **Validation Gate (`validateToolCall`):**
   * Checks if `book_automotive_service` is registered in `VALID_TOOLS`.
   * Checks if the active tenant's policy (`tenant.enabledTools`) authorizes the tool.
   * Validates arguments against capability schemas (`capability_contracts.js`).
3. **Execution (`skill_registry.js`):** Routes parameters to `skills/book_automotive_service/index.js`, which locks the service bay slot in the database and reserves the booking.

```javascript
// Deterministic Tenant Gate in lib/tool_dispatch.js
export async function validateToolCall(toolCall, tenantContext) {
    if (!VALID_TOOLS.has(toolCall.name)) {
        return { valid: false, reason: `Tool '${toolCall.name}' is not registered in runtime.` };
    }
    if (!tenantContext.enabledTools.includes(toolCall.name)) {
        return { valid: false, reason: `Tenant '${tenantContext.tenantId}' lacks permission for '${toolCall.name}'.` };
    }
    return { valid: true };
}
```

---

### Stage 5: State Mutation, Ed25519 Signing & Outbound Delivery
Once the skill returns a successful result:
1. **Tamper-Evident Asymmetric Cryptographic Signing (Ed25519):** For sovereign auditability, the runtime signs the conversation archive record and execution trace using **Ed25519 asymmetric cryptography** (`ed25519Sign` in `lib/db/archive.js`). This allows external auditors or Adesha terminals to verify state authenticity using the public key without exposing private secrets.
2. **Verifiable Execution Trail (`agent_ledger` & `tool_logs`):** The runtime writes an execution record containing:
   * Correlation ID
   * Tenant ID & User ID
   * Tool Name & Validated Parameters
   * Execution Status & Duration (ms)
   * Ed25519 State Signature
3. **Conversation Archive (`chat_archive`):** Appends the user message, model reasoning trace, and tool result with the verified signature to durable storage.
4. **Outbound Dispatch:** Formats the user-friendly confirmation and sends it via WhatsApp Cloud API.

---

## 4. Four Distinct Security & Data Integrity Mechanisms

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                 FOUR DISTINCT SECURITY & INTEGRITY LAYERS                   │
│                                                                             │
│  1. HMAC-SHA256        ➔ Inbound Webhook Authenticity (Meta App Secret)     │
│  2. SHA-256 Hash       ➔ Idempotency Deduplication Key (signature_lookup)   │
│  3. Tenant Gate        ➔ Authorization & RBAC (VALID_TOOLS & enabledTools)  │
│  4. Ed25519 Signature  ➔ Tamper-Evident State Integrity (Public Key Verify) │
└─────────────────────────────────────────────────────────────────────────────┘
```

---

## 5. Production Failure Defenses

| Production Scenario | Failure Mode Prevented | Runtime Defense Mechanism |
| :--- | :--- | :--- |
| **Network Retry / Duplicate Webhook** | Double-booking slots or redundant charges | SHA-256 payload hash index (`signature_lookup`) returns cached response. |
| **External Dependency Timeout** | Process hangs / silent crash | Skill execution enforces timeout, logs error in `tool_logs`, and prompts model to offer alternative slots. |
| **Prompt Injection Attack** | Malicious user requesting free service / rule bypass | Deterministic gateway validates price/permission rules in code; model has no write access to bypass logic. |
| **Unauthorized Capability Call** | Malicious agent invoking unpermitted tools | Tenant validation gate rejects execution if tool is not in `tenant.enabledTools`. |

---

## 6. Philosophical Takeaway

> **"For this transaction, no human intervention is required."**

Routine operational transactions can execute autonomously when they satisfy the runtime's configured constraints, while the resulting execution events leave a verifiable operational record.

---

## 7. The Bridge to Day 4

This single-request trace demonstrates the mechanics of one autonomous agent operating for one organization.

**The Next Engineering Hurdle:**  
MudraForge was not designed to run for just one company. What happens when you deploy this autonomous engine across **50 different organizations** on the same shared edge infrastructure without their data, memory, or tools ever colliding?

**Next in the Series:** *Day 4: The Multi-Tenant Scaling Problem — Isolating 50 Agents on Shared Infrastructure.*
