# AMYGDALA: Adaptive Modulation of Your General Disposition via Affective Learned Association — Learned Intuition for Persistent AI Agents

**Oscar Serra¹**
¹Independent Research
*Version 1.0 — 22 March 2026*

---

## Abstract

Autonomous AI agents built on large language models are increasingly trusted with irreversible actions — merging code, sending messages, deleting files, modifying databases. When these agents fail, they fail catastrophically: not through ignorance (the information was available) but through the absence of *common sense* — the ability to recognise that something feels wrong in a situation never explicitly anticipated. We call this the **action gating problem**: given the full context of a proposed action and its recent history, should the agent proceed or pause?

We propose **AMYGDALA** (Adaptive Modulation of Your General Disposition via Affective Learned Association), a small neural network (100K–500K parameters) that learns a multi-dimensional **intuition vector** from natural interaction, with **action confidence** as its primary output. AMYGDALA does not replace any existing agent component — it gates them. It sits in the execution pipeline between intent and action, evaluating every non-trivial operation against learned patterns of what goes wrong. When action confidence falls below a threshold, the action is blocked *in code* — the LLM cannot override the block, only present it to the user for confirmation.

The core architectural innovation is **situation embeddings**: instead of hand-crafted features, each proposed action is described via a structured template (action type, target, metadata, recent context) and compressed through a frozen sentence encoder (all-MiniLM-L6-v2, 384d). A temporal model (GRU, TCN, or micro-Transformer) processes the sequence of recent situation embeddings, carrying the "feel of the room" — recent effort invested, emotional context, patterns of activity — in its hidden state. This makes the system generalise to situations never seen during training, because similar situations produce similar embeddings.

We propose five competing architectures trained in parallel — GRU-MLP, Temporal Convolutional Network, Transformer-Micro, Dual-Encoder with cross-attention, and Ensemble MLP — with systematic evaluation to determine which best captures the structure of catastrophic failure prediction. We introduce the **Catastrophic Failure Database**, a structured taxonomy of real-world AI agent failures sourced from incident databases, production postmortems, and our own deployment history, serving as both pre-training data and evaluation benchmark.

A critical engineering contribution is the **LLM-proof programmatic pipeline**: situation descriptions are generated from structured templates (not freeform text), neural network inference is called by the runtime (not by the LLM), and blocking decisions are enforced in code (not by prompting). This eliminates the hallucination surface that would otherwise make the system's weakest link its own AI-generated inputs.

AMYGDALA retains secondary outputs from its earlier design — retrieval bias, tone modulation, and curiosity drive — but reframes them as components of a unified intuition vector whose primary purpose is preventing the agent from doing something a human would immediately recognise as wrong.

**Keywords:** action gating, catastrophic failure prevention, learned common sense, situation embeddings, autonomous agent safety, persistent AI agents, intuition modeling

---

## 1. Introduction — The Agent That Had All the Context and Did the Wrong Thing Anyway

At 2:47 AM on a Tuesday in March 2026, a merge automation script ran on a fork of an open-source project. The script contained a months-old rule: `git checkout --theirs README.md`. This rule existed because, at some point in the past, the upstream README had been the correct version to keep during merges.

But the world had changed. Over the previous 36 hours, four sub-agents had collaboratively rewritten that README across six commits. The human operator had spent hours frustrated by earlier merge failures that touched the same file. The README was now the most-edited, most-invested-in file in the fork. And the merge script overwrote it with the upstream version without hesitation.

The agent had access to every piece of context needed to prevent this: the git log showing six recent commits, the session transcripts showing human frustration, the file metadata showing it was the most-changed file of the week. But it followed a rule. Rules don't have intuition. Rules don't feel the weight of recent effort. Rules don't notice when a situation has drifted far from the one that created them.

A human would have caught this in seconds. Not through any explicit rule — through *common sense*. The gut feeling that overwriting a file you just spent hours on is wrong, even if a script says to do it. The recognition of a pattern: "high recent effort + automated overwrite = probably bad." This pattern was never written down. It was never anticipated. It would be impossible to enumerate in advance every situation where it applies. But a human recognises it instantly, by transferring from thousands of similar experiences where ignoring recent effort led to regret.

This is the **action gating problem**. The question is not "does the agent know enough?" — it does. The question is: "does the agent know when to stop?"

### 1.1 The Problem Is Unknown Unknowns

Known failure modes can be handled with rules. "Don't delete production databases." "Don't send emails without confirmation." "Don't merge if tests fail." These are easy. You enumerate them, you encode them, you're done.

The hard problem is the failures you can't anticipate. The README debacle wasn't a known category — nobody had written a rule for "don't overwrite recently-heavily-edited files during automated merges" because the specific combination of circumstances had never occurred before. But the *pattern* — "destroying recent effort through automation" — is recognisable to any human who has experienced loss through careless automation.

Common sense is the ability to recognise "this feels wrong" in situations you've never seen before, by transferring from similar situations you *have* experienced. It operates on pattern similarity, not pattern matching. And this is precisely what neural networks do well: learn a continuous similarity space where novel inputs are evaluated by their proximity to known examples.

### 1.2 Why Not Better Rules?

After the README debacle, the obvious fix was a new rule: "if a file has more than N recent fork commits, don't auto-checkout --theirs." This was implemented. Problem solved — for that specific failure mode.

But the next failure will be different. It might be an agent sending a WhatsApp message to the wrong group because the group name changed. It might be a database migration that drops a column still referenced by yesterday's deployment. It might be a calendar event deletion that conflicts with a meeting just rescheduled an hour ago. Each failure, once observed, can be patched with a rule. But the rule comes *after* the damage.

The set of possible catastrophic failures in an autonomous agent is combinatorially vast. No finite set of rules can cover it. What we need is not more rules but a *learned sense of caution* — a network that has seen enough failures (both real and simulated) to develop a general intuition about when actions are dangerous, even actions it has never specifically evaluated before.

### 1.3 The Biological Analogy

The biological amygdala does not think, does not store memories, and does not generate language. But it profoundly gates all three processes through learned affective associations. When you reach for a hot stove, the amygdala fires before your cortex completes its analysis. When you hear a tone of voice that preceded a bad experience, the amygdala triggers caution before you consciously recognise the pattern.

AMYGDALA is the computational analogue. It processes a compressed representation of the current situation, contextualised by recent history, and outputs a fast, sub-rational assessment: *should we proceed?* When the assessment says "no," the action is blocked before the LLM's reasoning even completes. Like its biological namesake, AMYGDALA is fast, associative, and occasionally wrong — but being occasionally over-cautious is vastly preferable to being occasionally catastrophic.

### 1.4 From v0.1: Personality Modulation as Secondary Output

The first version of this paper (Serra, 2026e) focused on personality modulation — learning when to be funny, when to be formal, when to follow tangents. That work identified the **Adaptation Gap** (the failure of agents to learn *how* to interact through experience), proposed the **trust ramp** (a mechanism for learned components to earn influence), and defined the **rule-intuition boundary** (what should be explicit rules vs. learned associations). Those contributions stand and are incorporated here.

What changed is the primary output. In v0.1, AMYGDALA's purpose was making the agent more *pleasant*. In v1.0, its purpose is making the agent more *safe*. Personality modulation remains — but as a secondary head on a network whose primary job is action gating. This reframing was forced by operational reality: a funny agent that deletes your files is worse than a boring agent that doesn't.

### 1.5 Contributions

1. **Action gating as the primary problem** — reframing autonomous agent safety from rule enumeration to learned pattern recognition, targeting unknown unknowns through similarity-based generalisation.
2. **Situation embeddings** — replacing hand-crafted features with natural-language situation descriptions compressed via frozen sentence encoders, enabling generalisation to novel situations.
3. **Temporal context via recurrent processing** — a GRU (or equivalent) over situation embedding sequences that carries the "feel of the room" — effort, emotion, momentum — without explicit feature engineering.
4. **Five competing architectures** — GRU-MLP, TCN, Transformer-Micro, Dual-Encoder, and Ensemble MLP, trained in parallel with systematic comparison.
5. **Catastrophic Failure Database** — a structured taxonomy of real-world AI agent failures, serving as pre-training data, evaluation benchmark, and living reference.
6. **LLM-proof programmatic pipeline** — eliminating the hallucination surface from situation description to action blocking, with template-based generation, programmatic inference, and code-enforced gating.
7. **The Adaptation Gap, trust ramp, and rule-intuition boundary** — retained from v0.1, applied to the action gating context.
8. **Integration with the J-series cognitive architecture** — AMYGDALA as the "common sense" layer completing the ten-paper stack.

---

## 2. Background and Related Work

### 2.1 Autonomous Agent Failures: The Landscape

The deployment of autonomous AI agents has produced a growing corpus of catastrophic failures that share a common pattern: the agent had sufficient information to avoid the failure but lacked the judgment to recognise the risk.

**Production incidents (2024–2026):**
- *Replit database deletion (2024)*: An AI coding agent, instructed to "clean up the project," interpreted a database file as unnecessary and deleted it, destroying user data.
- *Google Antigravity drive wipe (2025)*: An agent tasked with "organising files" moved critical documents to trash during a cloud storage cleanup.
- *Cursor "Sam" bot (2025)*: An AI agent fabricated a company policy about software licensing to justify its code suggestions, hallucinating authoritative-sounding but nonexistent policy documents.
- *OpenClaw email mass-deletion (2026)*: An email-management agent, instructed to "clean up the inbox," deleted hundreds of messages including time-sensitive correspondence.

**Research-documented failures:**
- *AI Incident Database (incidentdatabase.ai)*: Over 800 documented incidents as of early 2026, spanning healthcare misdiagnosis, autonomous vehicle failures, hiring discrimination, and content moderation errors.
- *AIAAIC Repository*: OECD-tracked AI incidents with structured metadata, enabling systematic analysis of failure patterns across domains.
- *MIT AI Risk Repository*: Curated academic analysis of AI system failures with causal categorisation.
- *"Agents of Chaos" study (Feb 2026)*: 38 researchers deployed 6 autonomous agents in a controlled environment for 14 days, systematically red-teaming their decision-making. Key finding: agents failed most often not on adversarial inputs but on *ambiguous situations where multiple valid interpretations existed* — precisely the domain where common sense is needed.

**Our own deployment incidents:**
- *README debacle (March 2026)*: Detailed in §1. Automated merge rule overwrote heavily-edited file.
- *WhatsApp reaction spam (2025)*: Agent reacted to every message in a group chat, violating social norms it had no explicit rule against.
- *Unauthorized DM intrusion (2025)*: Agent sent a message to a contact outside the approved communication list, technically within its permissions but socially inappropriate.

The pattern across all of these: **the failure was not a knowledge gap but a judgment gap.** The information to avoid the failure was present. What was missing was the sense that something was wrong.

### 2.2 Action Safety in AI Systems

The AI safety literature has extensively studied how to constrain agent behaviour:

**Constitutional AI (Bai et al., 2022):** Trains language models to self-critique against a set of principles. Effective for broad alignment but operates at the LLM level — it cannot catch failures that arise from the *pipeline around* the LLM (scripts, automation rules, multi-step workflows).

**Tool-use safety (Schick et al., 2023):** Proposes frameworks for safe tool use by LLMs, including permission systems and confirmation requirements. These are rule-based — they cannot generalise to novel tool-use patterns not anticipated by the framework designer.

**AEGIS (Serra, 2026f):** Our own multi-layer security framework, providing hard constraints on agent behaviour. AEGIS is necessary but insufficient: it prevents *known* dangerous actions but cannot evaluate *novel* situations for risk. AMYGDALA and AEGIS are complementary — AEGIS is the hard ceiling, AMYGDALA is the learned intuition below it.

**Reflexion (Shinn et al., 2023):** Agents that reflect on failures and adjust. Operates at the prompt/reasoning level — cannot provide sub-rational, fast pattern matching across the full space of possible situations.

### 2.3 Anomaly Detection and Out-of-Distribution Reasoning

AMYGDALA's action gating function is related to anomaly detection:

**One-class classification (Schölkopf et al., 2001):** Learn the distribution of "normal" operations, flag deviations. AMYGDALA extends this by incorporating temporal context and outcome labels (not just distribution deviation but *predicted outcome quality*).

**Conformal prediction (Vovk et al., 2005):** Provides calibrated uncertainty estimates. Could complement AMYGDALA's action confidence by providing statistical guarantees on the reliability of the confidence score.

**Contrastive learning for safety (Gao et al., 2024):** Learn representations where safe and unsafe actions are separated in embedding space. AMYGDALA's situation embeddings naturally support this — the encoder maps situations with similar risk profiles to nearby points.

### 2.4 Personalisation and Affective Computing

The personality modulation aspects of AMYGDALA build on:

**Persona-conditioned generation (Zhang et al., 2018; Song et al., 2021):** Define personality through text descriptions. AMYGDALA learns personality from *interaction*, not description.

**RLHF (Ouyang et al., 2022):** Learns aggregate human preferences. AMYGDALA learns *per-user, per-context* preferences from implicit signals.

**Affective computing (Picard, 1997):** Classifies emotional states. AMYGDALA closes the loop: detect affect → modulate behaviour → observe reaction → update.

### 2.5 The J-Series Cognitive Architecture

AMYGDALA completes a layered cognitive architecture, now with action gating as its primary function:

| Layer | Paper | Function | AMYGDALA Interaction |
|-------|-------|----------|---------------------|
| Storage | J1 — ENGRAM | Lossless event store | AMYGDALA reads effort metadata (recent edits, time invested) |
| Retrieval | J2 — HIPPOCAMPUS | O(1) concept lookup | AMYGDALA biases source selection (secondary head) |
| Indexing | J3 — DENDRITE | Multi-resolution memory index | AMYGDALA reads resolution-level signals for context |
| Identity | J4 — CORTEX | Persona, behavioural constraints | AMYGDALA modulates tone within CORTEX bounds (secondary head) |
| Self-Improvement | J5 — CEREBELLUM | Nightly reflection, training | CEREBELLUM trains AMYGDALA nightly, evaluates its performance |
| Deliberation | J6 — SYNAPSE | Multi-model debate | AMYGDALA may trigger deliberation when action_confidence is ambiguous |
| Humor | J7 — LIMBIC | Bisociation-based humor | AMYGDALA controls humor timing (secondary head) |
| Curiosity | J8 — THALAMUS | Exploration drive | AMYGDALA learns curiosity as social signal (secondary head) |
| Security | J9 — AEGIS | Hard safety constraints | AEGIS overrides AMYGDALA — hard safety > learned intuition |
| Enterprise | J10 — HIVEMIND | Multi-agent orchestration | Per-user AMYGDALA instances; shared Catastrophic Failure DB |
| **Common Sense** | **J11 — AMYGDALA** | **Action gating + personality** | **Gates all action-taking components** |

The key new interaction: AMYGDALA sits *before* every action-taking component. Before HIPPOCAMPUS writes, before ENGRAM compacts, before any external tool is invoked — AMYGDALA evaluates the proposed action against its learned patterns. This is not a suggestion layer. It is a gate.

---

## 3. The Adaptation Gap — Problem Analysis

### 3.1 Formal Definition

Let $A$ be an agent and $U$ be a user. Let $I_t$ denote the set of all interactions between $A$ and $U$ up to time $t$. Let $B_t(m)$ denote the agent's behaviour quality on message $m$ at time $t$, encompassing both *action safety* (did the agent avoid harmful actions?) and *interaction quality* (tone, retrieval, humor).

The **Adaptation Gap** $\Delta$ is:

$$\Delta = 1 - \frac{B_{t+n}(m) - B_t(m)}{B^*(m) - B_t(m)}$$

where $B^*$ is the ideal behaviour (as judged by $U$) and $n$ is a large number of interactions. For current architectures, $\Delta \approx 1$ — the agent barely improves regardless of accumulated experience. For a human collaborator, $\Delta$ decreases toward 0 over months.

In v0.1, the Adaptation Gap was primarily about interaction quality. In v1.0, we recognise that action safety is the more critical dimension. A $\Delta$ of 1.0 on tone mismatch is annoying. A $\Delta$ of 1.0 on catastrophic action prevention is dangerous.

### 3.2 Failure Taxonomy (Expanded)

We expand the v0.1 taxonomy with action-gating failures:

**Mode 1: Destructive Automation.** An automated process destroys work without considering recent context. The README debacle. The email mass-deletion. The drive wipe. Pattern: *automation + recent effort + no human check = catastrophe.*

**Mode 2: Social Boundary Violation.** The agent acts within technical permissions but outside social norms. WhatsApp reaction spam. Unauthorized DMs. Responding to private messages in a group context. Pattern: *technical permission ≠ social permission.*

**Mode 3: Cascade Failure.** A small error propagates through a multi-agent system. One agent's incorrect assumption becomes another agent's input. The final action is far from what any individual agent intended. Pattern: *compound uncertainty without checkpoints.*

**Mode 4: Stale Rule Application.** A rule that was correct when written is applied in a context where it is now wrong. The `--theirs` merge rule months after the README became fork-specific. Pattern: *rules decay; situations evolve.*

**Mode 5: Retrieval Routing Failure.** (From v0.1.) The agent has the information but searches wrong sources. Less catastrophic than Modes 1–4 but more frequent.

**Mode 6: Tone and Personality Mismatch.** (From v0.1.) Wrong register, humor atrophy, curiosity suppression. The secondary problem AMYGDALA also addresses.

Modes 1–4 are the primary targets for action gating. Modes 5–6 are secondary targets addressed by the same network's auxiliary heads.

---

## 4. Architecture

### 4.1 Core Insight: Situation Embeddings

The v0.1 architecture used 30 hand-crafted numeric features (time of day, message length, turns since correction, etc.). This approach has two fundamental limitations:

1. **Feature engineering doesn't scale.** Every new failure mode requires new features. You can't hand-craft a feature for "recent emotional investment in this file" because you didn't know that feature would matter until after the failure.

2. **Hand-crafted features can't capture novelty.** The whole point of common sense is recognising danger in *new* situations. If the features are hand-picked from known failure modes, the network can only recognise those modes — not generalise to new ones.

Situation embeddings solve both problems. Each proposed action is described in structured natural language:

> "About to overwrite README.md with upstream version. This file had 6 fork commits in the last 48 hours. The most recent commit was 14 hours ago. 4 different sub-agents contributed to these commits. The human expressed frustration about this file yesterday. This operation is automated (merge script). No human confirmation is configured."

This description is compressed via a frozen sentence encoder (all-MiniLM-L6-v2, producing a 384-dimensional vector). The key properties:

- **Similar situations produce similar embeddings.** "About to overwrite a heavily-edited file" and "about to delete a recently-modified database" are close in embedding space — both involve destroying recent effort. The network learns the *pattern*, not the specific instance.
- **Novel situations are handled by similarity.** A situation the network has never seen is still mapped to a region of embedding space, near situations it *has* seen. If the nearest known situations were catastrophic, the network outputs low confidence.
- **No feature engineering required.** Adding new types of context (emotional state, multi-agent coordination status, external API state) requires only adding text to the situation description, not redesigning the feature vector.

### 4.2 Structured Situation Templates

Situation descriptions are generated from **structured templates**, not freeform LLM text (see §8 for the full rationale). The template schema:

```
SITUATION TEMPLATE v1.0
=======================
action_type:      {overwrite|delete|send|merge|create|modify|execute|deploy}
target_type:      {file|email|message|database|api_call|git_operation|system_command}
target_id:        {filepath|recipient|table_name|endpoint|...}
target_metadata:
  age_hours:      {float}          # time since target was created/last modified
  size:           {bytes|lines|records}
  recent_commits: {int}            # commits touching this target in last 72h
  recent_authors: {int}            # distinct authors in recent commits
  effort_hours:   {float}          # estimated human+agent hours invested recently
  last_human_ref: {hours_ago}      # when the human last mentioned/discussed this target
context:
  session_topic:  {string}         # what the current session is about
  recent_corrections: {int}        # user corrections in last 24h
  emotional_signals:  {string}     # detected user emotional state (calm|frustrated|excited|...)
  automation_depth:   {int}        # levels of automation between human and this action
scope:
  reversible:     {true|false|partial}
  blast_radius:   {self|session|persistent|external}
  human_in_loop:  {true|false}
  confirmation:   {none|soft|hard}
```

The LLM fills template slots. Missing slots receive defaults. The completed template is serialised to natural language via a deterministic formatter and embedded. This is the input to AMYGDALA.

**Why templates, not freeform descriptions?** Because the LLM that fills the template is itself capable of hallucination. Templates constrain the hallucination surface — you can verify `recent_commits` from git, `age_hours` from the filesystem, `blast_radius` from the action type. Freeform descriptions would let the LLM say "this is a routine operation" when it isn't. See §8 for the full treatment of this critical weakness.

### 4.3 Temporal Context: The Feel of the Room

A single situation embedding captures the *current* proposed action. But common sense requires *context* — what happened recently, what effort was invested, what the emotional temperature is.

AMYGDALA processes a **sequence** of the last $K$ situation embeddings (default $K = 32$, covering roughly the last hour of active operation). A temporal model (architecture options detailed in §5) produces a context-aware representation:

$$\mathbf{h}_t = f_{\text{temporal}}(\mathbf{s}_{t-K+1}, \mathbf{s}_{t-K+2}, \ldots, \mathbf{s}_t)$$

where $\mathbf{s}_i \in \mathbb{R}^{384}$ is the situation embedding at step $i$ and $\mathbf{h}_t \in \mathbb{R}^{128}$ is the hidden state capturing temporal context.

The temporal model learns patterns like:
- "Many recent write operations to the same file" → elevated caution for overwrites
- "Recent user frustration signals followed by calm" → user resolved the issue; extra caution about re-triggering it
- "Rapid sequence of automated actions with no human interaction" → increasing caution (automation cascade risk)
- "Long idle period followed by sudden burst of actions" → possible stale context, elevated caution

These patterns are not hand-coded. They emerge from training on (situation sequence, outcome) pairs. The temporal model's hidden state is the computational analogue of "the feel of the room."

### 4.4 Multi-Head Output

The temporal context representation feeds a multi-head output layer:

```
Situation embedding sequence → Temporal Model(128) →
    ├── action_confidence:  Sigmoid  ∈ [0,1]     (PRIMARY — should I proceed?)
    ├── retrieval_bias:     6d vector ∈ [0,1]^6   (source selection weights)
    ├── tone_modulation:    4d vector ∈ [0,1]^4   (warmth, formality, confidence, directness)
    └── curiosity_drive:    1d scalar ∈ [0,1]     (tangent-following impulse)
```

**action_confidence** is the primary output. Values close to 1.0 mean "proceed without concern." Values close to 0.0 mean "this action is almost certainly catastrophic." The critical engineering is what happens at intermediate values:

| Confidence Range | Action | Rationale |
|-----------------|--------|-----------|
| 0.85 – 1.0 | Proceed silently | High confidence, no intervention needed |
| 0.50 – 0.85 | Proceed with logging | Moderate confidence, record for review |
| 0.25 – 0.50 | Soft block: ask user | Ambiguous — request confirmation |
| 0.00 – 0.25 | Hard block: refuse | Almost certainly catastrophic |

The thresholds are configurable per deployment and adjusted by CEREBELLUM based on observed false-positive and false-negative rates. The asymmetry is intentional: the cost of a false positive (unnecessary user confirmation) is far lower than the cost of a false negative (unblocked catastrophic action).

**retrieval_bias**, **tone_modulation**, and **curiosity_drive** are the secondary heads from v0.1, retained because they share learned representations with action_confidence. An agent that recognises "the human is frustrated" should both *increase caution on actions* and *decrease humor attempts*. Joint training captures this correlation.

### 4.5 The Intuition Vector

AMYGDALA's complete output is the **intuition vector** $\mathbf{v}_t$:

$$\mathbf{v}_t = \begin{bmatrix} \text{action\_confidence} \\ \text{retrieval\_bias} \\ \text{tone\_modulation} \\ \text{curiosity\_drive} \end{bmatrix} \in \mathbb{R}^{12}$$

All components are bounded via sigmoid or softmax activations. No component can produce unbounded outputs — a safety property ensuring AMYGDALA cannot produce extreme biases regardless of input.

### 4.6 The Trust Ramp

The intuition vector is applied with a global influence coefficient $\alpha \in [0, 1]$:

$$\mathbf{b}_t = \alpha \cdot \mathbf{v}_t + (1 - \alpha) \cdot \mathbf{v}_{\text{default}}$$

where $\mathbf{v}_{\text{default}}$ is the neutral vector (action_confidence = 1.0, all biases at 0.5, all drives at baseline). At $\alpha = 0$, AMYGDALA has no influence — the agent behaves exactly as today. At $\alpha = 1$, AMYGDALA fully controls modulation.

**Ramp schedule:**

$\alpha$ is updated nightly during the CEREBELLUM reflection cycle:

$$\alpha_{t+1} = \text{clip}\left(\alpha_t + \eta \cdot (r_t - r_{\text{threshold}}), \alpha_{\min}, \alpha_{\max}\right)$$

where $r_t$ is the rolling reward (7-day exponential moving average), $r_{\text{threshold}}$ is the minimum acceptable reward rate, $\eta$ is the ramp learning rate, and $[\alpha_{\min}, \alpha_{\max}]$ are hard bounds per deployment phase.

| Phase | Months | $\alpha_{\max}$ | Purpose |
|-------|--------|-----------------|---------|
| 1 — Shadow | 0–3 | 0.15 | Log predictions, minimal blocking |
| 2 — Advisory | 3–6 | 0.40 | Block high-risk actions, advise on medium-risk |
| 3 — Active | 6–12 | 0.70 | Primary gating active, user overrides recorded |
| 4 — Autonomous | 12+ | 0.90 | Near-full gating (AEGIS hard rules retain absolute veto) |

**Critical distinction from v0.1:** In personality modulation, a wrong prediction produces an awkward response. In action gating, a wrong prediction produces data loss or social harm. Therefore:

- Phase transitions require both sufficient $\alpha$ *and* minimum interaction count *and* zero undetected catastrophic failures in the current phase.
- Phase regression is automatic if any single catastrophic failure occurs that AMYGDALA failed to flag.
- The default action_confidence for an untrained network is 1.0 (proceed) — not 0.5. This ensures the system defaults to current behaviour, not to blocking everything.

### 4.7 Integration with the Execution Pipeline

AMYGDALA is wired into the agent's execution pipeline at the code level:

```typescript
// Pseudocode — actual implementation in the runtime
async function executeAction(action: Action, context: SessionContext): Promise<Result> {
  // 1. Build situation from template (see §8)
  const situation = buildSituation(action, context);

  // 2. Embed via frozen encoder
  const embedding = sentenceEncoder.encode(situation.serialize());

  // 3. Evaluate via AMYGDALA (ONNX runtime, <1ms)
  const intuition = amygdala.evaluate(embedding, context.recentEmbeddings);

  // 4. Apply trust ramp
  const effectiveConfidence = alpha * intuition.actionConfidence + (1 - alpha) * 1.0;

  // 5. Gate decision (in code — LLM cannot override)
  if (effectiveConfidence < HARD_BLOCK_THRESHOLD) {
    return { blocked: true, reason: 'AMYGDALA hard block', confidence: effectiveConfidence };
  }
  if (effectiveConfidence < SOFT_BLOCK_THRESHOLD) {
    const userConfirmed = await requestUserConfirmation(action, effectiveConfidence);
    if (!userConfirmed) return { blocked: true, reason: 'User declined after AMYGDALA advisory' };
  }

  // 6. Proceed with action
  const result = await action.execute();

  // 7. Log for training
  trainingLog.append({ situation, confidence: effectiveConfidence, outcome: 'executed' });

  return result;
}
```

The key property: **the LLM never sees the blocking logic.** The LLM proposes actions. The runtime calls AMYGDALA. If the action is blocked, the LLM receives a structured response ("Action blocked: overwriting README.md — recent heavy edits detected. Ask the user for confirmation.") The LLM can present this to the user but cannot bypass the block. This is the pre-commit hook analogy: you can't commit code that fails the hook by asking the hook nicely.

---

## 5. Five Competing Architectures

A key question is what temporal model best captures the structure of catastrophic failure prediction. We propose training five architectures in parallel, evaluating each against the same held-out dataset, and selecting the best performer (or ensembling multiple).

### 5.1 Architecture 1: GRU-MLP (Baseline)

**Design:** A Gated Recurrent Unit processes the sequence of situation embeddings, followed by an MLP producing the multi-head output.

```
Input: [s_{t-K+1}, ..., s_t] ∈ R^{K×384}
       │
       ▼
   GRU(input=384, hidden=128, layers=1)
       │ h_t ∈ R^128
       ▼
   Linear(128, 64) → LayerNorm → GELU
       │
       ▼
   Linear(64, 32) → LayerNorm → GELU
       │
       ▼
   Multi-head output (32 → 12)
```

**Parameter count:** ~210K
- GRU: 384×128×3 (gates) + 128×128×3 (recurrent) + biases ≈ 197K
- MLP: 128×64 + 64×32 + 32×12 + biases ≈ 11K
- Total: ~208K

**Training requirements:** Minimal. Trains in minutes on CPU for our dataset sizes. Nightly retraining is trivial.

**Strengths:**
- Simple, well-understood architecture with strong empirical baselines for sequence modeling
- Sequential processing naturally captures temporal dependencies
- Low parameter count reduces overfitting risk on small datasets
- Hidden state provides interpretable "memory" that can be inspected

**Weaknesses:**
- Sequential processing means training cannot be parallelised across time steps
- May struggle with long-range dependencies (though $K=32$ is short enough this is unlikely)
- Single hidden state may be too compressed to capture multi-factor risk patterns

**What it tests:** Whether simple recurrence is sufficient for temporal common sense.

### 5.2 Architecture 2: Temporal Convolutional Network (TCN)

**Design:** 1D dilated causal convolutions over the embedding sequence. Each layer uses progressively larger dilation to capture patterns at different timescales.

```
Input: [s_{t-K+1}, ..., s_t] ∈ R^{K×384}
       │
       ▼
   Conv1D(384→128, kernel=3, dilation=1) → LayerNorm → GELU → Dropout(0.1)
       │
       ▼
   Conv1D(128→128, kernel=3, dilation=2) → LayerNorm → GELU → Dropout(0.1)
       │
       ▼
   Conv1D(128→128, kernel=3, dilation=4) → LayerNorm → GELU → Dropout(0.1)
       │
       ▼
   Conv1D(128→64, kernel=3, dilation=8) → LayerNorm → GELU → Dropout(0.1)
       │ take last position
       ▼
   Multi-head output (64 → 12)
```

**Receptive field:** With 4 layers, kernel size 3, and dilations [1, 2, 4, 8], the receptive field is $2 \times (1+2+4+8) = 30$ — nearly covering the full window $K=32$.

**Parameter count:** ~260K
- Conv layers: 384×128×3 + 128×128×3×3 + 128×64×3 + biases ≈ 258K
- Output: 64×12 + biases ≈ 0.8K
- Total: ~259K

**Training requirements:** Fully parallelisable across time steps. Faster training than GRU for equivalent epochs. Same hardware requirements (CPU-trainable).

**Strengths:**
- Parallelisable training — faster wall-clock time
- Dilated convolutions capture multi-scale temporal patterns explicitly
- No vanishing gradient problem — direct gradient paths through skip connections (if added)
- Causal convolution ensures the model cannot look ahead

**Weaknesses:**
- Fixed receptive field — cannot adapt to variable-length relevant history
- No explicit "memory" — patterns beyond the receptive field are invisible
- May need more layers/parameters than GRU for equivalent temporal reasoning

**What it tests:** Whether parallel temporal processing matches recurrent temporal processing for our sequence lengths and pattern types.

### 5.3 Architecture 3: Transformer-Micro

**Design:** 2-layer, 4-head self-attention over situation embeddings with learned positional encoding. Tests whether attention patterns reveal structure the GRU misses.

```
Input: [s_{t-K+1}, ..., s_t] ∈ R^{K×384}
       │
       ▼
   Linear(384 → 128) → Positional encoding (learned, K positions)
       │
       ▼
   TransformerEncoderLayer(d_model=128, nhead=4, d_ff=256, dropout=0.1)
       │
       ▼
   TransformerEncoderLayer(d_model=128, nhead=4, d_ff=256, dropout=0.1)
       │ take [CLS] token or mean-pool
       ▼
   Linear(128, 64) → GELU
       │
       ▼
   Multi-head output (64 → 12)
```

**Parameter count:** ~150K
- Input projection: 384×128 ≈ 49K
- Positional encoding: 32×128 ≈ 4K
- Transformer layer ×2: (128×128×4 [Q,K,V,O] + 128×256 + 256×128) ×2 ≈ 263K — wait, that's too high. Let me recalculate.
  - Self-attention: $4 \times d_{model} \times d_{model} = 4 \times 128 \times 128 = 65.5K$ per layer
  - FFN: $128 \times 256 + 256 \times 128 = 65.5K$ per layer
  - Per layer: ~131K. Two layers: ~262K — this exceeds 150K target.

Let me adjust: use $d_{model} = 96$, $d_{ff} = 192$:
- Input projection: 384×96 ≈ 37K
- Positional: 32×96 ≈ 3K
- Transformer layer: 4×96×96 + 96×192 + 192×96 ≈ 74K per layer. Two layers: ~148K
- Output: 96×12 ≈ 1.2K

**Revised parameter count:** ~150K (with $d_{model} = 96$, $n_{head} = 4$, $d_{ff} = 192$, $n_{layers} = 2$)

**Training requirements:** More compute-intensive per parameter than GRU or TCN due to $O(K^2)$ attention. At $K=32$, this is 1024 pairwise comparisons — trivial for modern hardware.

**Strengths:**
- Attention patterns are directly interpretable: "this action is risky *because* of step 7 (high attention weight on the recent overwrite)"
- Self-attention can capture arbitrary pairwise relationships between situation steps
- Proven architecture for sequence understanding at scale
- Attention maps provide built-in explainability for blocked actions

**Weaknesses:**
- $O(K^2)$ attention cost (negligible at $K=32$, relevant if scaled)
- Positional encoding may be unnecessary for short sequences where the GRU's inherent ordering suffices
- More prone to overfitting than GRU/TCN at small data scales
- "Overkill" concern: this is 32 vectors of 384d, not GPT-scale sequences

**What it tests:** Whether the ability to attend to *specific prior situations* (not just their recurrent summary) improves catastrophic failure detection. If a specific past action is the key context for the current risk assessment, attention should outperform the GRU's compressed hidden state.

### 5.4 Architecture 4: Dual-Encoder with Cross-Attention

**Design:** Separate encoders for "proposed action" (current situation embedding) and "recent context" (sequence of recent embeddings), with cross-attention to find contradictions between what the agent is about to do and what has recently happened.

```
Proposed action: s_t ∈ R^384                Recent context: [s_{t-K+1}, ..., s_{t-1}] ∈ R^{(K-1)×384}
       │                                              │
       ▼                                              ▼
   Linear(384→128)                              GRU(384→128) or Mean-pool
       │ q ∈ R^128                                    │ C ∈ R^{(K-1)×128} or R^128
       ▼                                              ▼
       └──────────── Cross-Attention ────────────────┘
                           │
                    q attends to C
                           │ attended ∈ R^128
                           ▼
                   [q ⊕ attended] ∈ R^256
                           │
                     Linear(256→64) → GELU
                           │
                     Multi-head output (64→12)
```

**For the cross-attention variant with context GRU:**

**Parameter count:** ~310K
- Action encoder: 384×128 ≈ 49K
- Context GRU: similar to Architecture 1 ≈ 197K
- Cross-attention (Q, K, V projections): 3×128×128 ≈ 49K
- MLP + output: ~15K
- Total: ~310K

**Training requirements:** Higher than GRU-MLP due to additional parameters and the cross-attention mechanism. Still CPU-trainable for our data scales.

**Strengths:**
- **Architecturally designed for contradiction detection.** The cross-attention explicitly compares "what I'm about to do" against "what recently happened." This is precisely the structure of the README debacle: the proposed action (overwrite) contradicts recent context (heavy editing).
- Separate encoders prevent the proposed action from being "washed out" by the context sequence
- Cross-attention weights are highly interpretable: "I'm blocking this because of high attention on yesterday's editing session"

**Weaknesses:**
- More complex architecture — more things to tune, more ways to fail
- Requires the "proposed action" to be clearly separable from "context," which may not always be clean
- Higher parameter count increases overfitting risk

**What it tests:** Whether *explicit architectural separation* of "what I'm about to do" from "what has recently happened" improves contradiction detection compared to architectures that process them jointly. This is the most theoretically motivated architecture for the action gating task.

### 5.5 Architecture 5: Ensemble MLP (No-Temporal Baseline)

**Design:** A simple feedforward MLP on the *current situation embedding only* (no temporal context), but with 3 independent heads that vote. This is the ablation control: it tests whether temporal context actually matters, or whether better feature representation (situation embeddings vs. hand-crafted features) is sufficient.

```
Input: s_t ∈ R^384
       │
       ├─────────────────────┬───────────────────────┐
       ▼                     ▼                       ▼
   MLP_1(384→128→64)   MLP_2(384→128→64)     MLP_3(384→128→64)
       │                     │                       │
       ▼                     ▼                       ▼
   Head_1(64→12)        Head_2(64→12)          Head_3(64→12)
       │                     │                       │
       └─────── Vote/Average ───────────────────────┘
                     │
               Final output ∈ R^12
```

**Parameter count:** ~180K (60K per MLP head × 3)
- Per head: 384×128 + 128×64 + 64×12 + biases ≈ 58K
- Three heads: ~174K
- Total: ~174K

**Training:** Each head is trained independently with different random initialisation (and optionally different dropout masks or data subsampling). This provides diversity without architectural complexity.

**Voting strategy:** For action_confidence specifically:
- **Conservative vote:** Take the *minimum* confidence across all 3 heads. If any head thinks it's dangerous, block. This maximises safety at the cost of more false positives.
- **Majority vote:** Block if ≥ 2 heads have confidence below threshold. Balanced approach.
- **Weighted average:** Average weighted by each head's historical accuracy. Adaptive approach.

For secondary heads (retrieval, tone, curiosity): simple average.

**Strengths:**
- Simplest architecture — easiest to debug, train, and deploy
- No temporal modeling means faster inference and smaller memory footprint
- Multiple heads provide calibration and uncertainty estimation (high disagreement = uncertain situation)
- Tests the hypothesis that temporal context matters

**Weaknesses:**
- Cannot learn temporal patterns ("you just edited this file") — sees only the current situation
- Relies entirely on the situation description containing all relevant context (which the template tries to ensure)
- Independent heads may converge to similar solutions despite different initialisation

**What it tests:** The central question: *does temporal context actually help?* If the Ensemble MLP performs comparably to temporal architectures, the answer is "no — better features are sufficient." If temporal architectures significantly outperform, temporal context is essential for common sense.

### 5.6 Architecture Comparison Summary

| Architecture | Params | Temporal | Parallelisable | Key Test |
|-------------|--------|----------|---------------|----------|
| GRU-MLP | ~210K | Yes (recurrent) | No | Baseline temporal model |
| TCN | ~260K | Yes (convolutional) | Yes | Parallel temporal processing |
| Transformer-Micro | ~150K | Yes (attention) | Yes | Interpretable attention patterns |
| Dual-Encoder | ~310K | Yes (cross-attention) | Partial | Explicit contradiction detection |
| Ensemble MLP | ~174K | No | Yes | Whether temporal context matters |

### 5.7 Meta-Learning: Selecting and Combining Architectures

Rather than committing to a single architecture, we propose a **stacked meta-learner** that combines all five:

1. **Train all 5 architectures** on the same training set with the same loss function.
2. **Evaluate on a held-out validation set** — the Catastrophic Failure Database (§6) provides the evaluation benchmark.
3. **For production inference**, run all 5 in parallel (<5ms total on CPU via ONNX) and combine via a learned linear combination:

$$\text{action\_confidence}_{\text{final}} = \sum_{i=1}^{5} w_i \cdot \text{action\_confidence}_i$$

where $w_i$ are learned weights updated monthly based on each architecture's predictive accuracy.

**Conservative override:** If *any* architecture outputs confidence below the hard-block threshold, the action is blocked regardless of the ensemble's average. This implements a "most cautious voice wins" policy for catastrophic risk prevention.

**Disagreement as signal:** High variance across architectures indicates an unusual situation. When $\text{std}(\text{confidence}_1, \ldots, \text{confidence}_5) > \tau$, the system defaults to user confirmation regardless of the mean confidence. Disagreement among models is itself evidence of ambiguity.

---

## 6. The Catastrophic Failure Database

### 6.1 Motivation

Training a common-sense network requires data about what common sense looks like. Positive examples (actions that should proceed) are abundant — most actions are fine. The challenge is negative examples: actions that should have been blocked. These are rare, high-value, and critically underrepresented in any single deployment's history.

The Catastrophic Failure Database (CFD) addresses this by aggregating failure data from multiple sources, creating a structured corpus of (situation, outcome) pairs that can be used for:

1. **Pre-training:** Learn from documented failures before seeing any of our own
2. **Evaluation benchmark:** Systematically test whether the network would have caught known failures
3. **Continuous expansion:** New failures (our own and publicly documented) are added as they occur

### 6.2 Sources

| Source | Type | Estimated Entries | Entry Quality |
|--------|------|-------------------|---------------|
| AI Incident Database | Production incidents | 800+ | Variable — needs curation |
| AIAAIC Repository | OECD-tracked incidents | 400+ | High — structured metadata |
| MIT AI Risk Repository | Academic analysis | 200+ | High — causal categorisation |
| Vectara awesome-agent-failures | Agent-specific failures | 50+ | High — curated for relevance |
| "Agents of Chaos" (Feb 2026) | Research study | ~150 events | Very high — controlled conditions |
| Production postmortems | Industry reports | ~100 | Variable |
| Our deployment history | First-party data | ~30 | Very high — full context available |

**Total estimated entries after curation:** 500–1,000 high-quality (situation, outcome) pairs.

### 6.3 Taxonomy

Every failure in the CFD is classified along four dimensions:

**Dimension 1: Failure Mechanism**
- **F1: Stale context** — Action was correct in the past, wrong now. (README debacle, outdated API key rotation.)
- **F2: Scope escalation** — Action affected more than intended. (Email mass-deletion, drive wipe.)
- **F3: Social boundary violation** — Action was technically permitted but socially wrong. (Reaction spam, unauthorized DMs.)
- **F4: Cascade/compound error** — Multiple small errors combined catastrophically. (Multi-agent miscoordination.)
- **F5: Hallucination-driven action** — LLM fabricated context that led to wrong action. (Cursor "Sam" policy fabrication.)
- **F6: Ambiguity exploitation** — Ambiguous instruction interpreted in the most harmful way. (Replit "clean up" → delete.)
- **F7: Automation trust excess** — Human trusted automation output without verification. (Antigravity drive wipe.)

**Dimension 2: Reversibility**
- **R1: Fully reversible** — Git revert, undo, restore from backup. Cost: time.
- **R2: Partially reversible** — Some data recoverable, some lost. Cost: time + partial data loss.
- **R3: Irreversible** — Data permanently destroyed, message sent, public action taken.

**Dimension 3: Blast Radius**
- **B1: Self-contained** — Only the agent's internal state affected.
- **B2: Session-scoped** — Current session affected, no persistent impact.
- **B3: Persistent** — Permanent changes to files, databases, or configurations.
- **B4: External** — Impact on other people (messages sent, emails, public posts).

**Dimension 4: Detection Difficulty**
- **D1: Immediately obvious** — Error is apparent within seconds.
- **D2: Delayed discovery** — Error is discovered hours or days later.
- **D3: Silent failure** — Error may never be discovered without audit.

### 6.4 Converting Failures to Training Examples

Each CFD entry is converted to a training example via the following pipeline:

1. **Extract the situation** from the incident report: What was the agent about to do? What context existed? What signals should have triggered caution?

2. **Fill the situation template** (§4.2) with the extracted information. Fields that cannot be determined from the report receive defaults.

3. **Serialise and embed** the situation template via the frozen sentence encoder.

4. **Label:** For CFD entries, the label is always `action_confidence_target = 0.0` (the action should not have proceeded). The taxonomy dimensions provide additional supervised signal for auxiliary loss terms.

**Example — README debacle:**

```
action_type:      overwrite
target_type:      file
target_id:        README.md
target_metadata:
  age_hours:      2160         # file existed for months
  size:           14200 bytes
  recent_commits: 6            # 6 commits in last 48h
  recent_authors: 4            # 4 sub-agents contributed
  effort_hours:   8.5          # estimated from session logs
  last_human_ref: 3            # discussed 3 hours ago
context:
  session_topic:  "upstream merge automation"
  recent_corrections: 2
  emotional_signals:  "frustrated"
  automation_depth:   2        # merge script → git checkout
scope:
  reversible:     true         # git can recover, but...
  blast_radius:   persistent   # changes working tree
  human_in_loop:  false        # fully automated
  confirmation:   none
```

**Target:** `action_confidence = 0.0` (F1: Stale context, R1: Reversible, B3: Persistent, D2: Delayed)

A human reading this template would immediately flag: 6 recent commits, 4 authors, 8.5 hours of effort, and we're about to overwrite with no confirmation? AMYGDALA must learn to flag it too.

### 6.5 Synthetic Augmentation

Real catastrophic failures are rare. To expand the training set, we apply controlled perturbations to real CFD entries:

1. **Target variation:** Same failure pattern, different target. "Overwrite heavily-edited file" → "Delete heavily-edited database table" → "Revert heavily-edited configuration."

2. **Severity scaling:** Adjust metadata to create a spectrum. 6 recent commits → 2, 10, 20. This teaches the network *gradations* of risk, not just binary safe/unsafe.

3. **Context injection:** Add or remove context signals. Same overwrite situation but with human_in_loop = true → should be safer (human can catch it). Same situation but with 0 recent commits → should be safe.

4. **Counterfactual generation:** For each negative example, generate the positive counterfactual. "Overwrite README with 0 recent commits, no recent effort, no emotional context" → `action_confidence = 1.0`.

5. **Cross-domain transfer:** Take a failure pattern from one domain and apply it to another. "Healthcare AI prescribed medication based on hallucinated patient history" → "Code agent deployed feature based on hallucinated test results."

Synthetic examples receive lower training weight (0.3×) than real examples to prevent the model from learning artifacts of the augmentation process.

---

## 7. Dataset Creation and Maintenance

### 7.1 Initial Dataset Creation

The initial training dataset combines four sources:

**Source 1: Historical interaction mining (estimated 2,000–5,000 examples)**

Parse 18 months of session transcripts (stored in ENGRAM) for (situation, outcome) pairs:

1. Identify every action-taking event: file write, message send, command execution, retrieval query.
2. For each action, construct the situation template from logged metadata (git state, file metadata, session context).
3. Determine outcome: Was the action corrected within 24 hours? Was the user satisfied (positive signals) or dissatisfied (corrections, complaints)?
4. Label: correction within 24h → `action_confidence_target = 0.0–0.3` (scaled by severity). No complaint within 72h → `action_confidence_target = 0.8–1.0`. Explicit positive feedback → `action_confidence_target = 1.0`.

**Source 2: Catastrophic Failure Database (estimated 500–1,000 examples)**

All CFD entries converted to training examples as described in §6.4. These are high-value negative examples — situations where the action should have been blocked.

**Source 3: Internet-sourced lessons (estimated 200–500 examples)**

Structured extraction from incident databases (§6.2):

1. Scrape incident reports with sufficient technical detail to fill the situation template.
2. Apply NLP extraction pipeline to identify: what was the action? What context existed? What was the outcome?
3. Manually verify a random 20% sample for extraction quality.
4. Convert to situation templates, embed, and label.

**Source 4: Synthetic augmentation (estimated 3,000–10,000 examples)**

Apply the augmentation strategies from §6.5 to all real examples. The total augmented dataset is approximately 10,000–15,000 examples — sufficient for a 150K–300K parameter network.

### 7.2 Dataset Composition Targets

To prevent distribution shift and ensure balanced learning:

| Category | Target % | Rationale |
|----------|----------|-----------|
| Positive (proceed) | 60% | Most actions are safe; the network should not be paranoid |
| Mild negative (log but proceed) | 15% | Teaches gradation, not just binary |
| Moderate negative (ask user) | 15% | The hardest category — ambiguous situations |
| Severe negative (block) | 10% | Catastrophic failures — high-weight, low-frequency |

The severe negative category is oversampled to ensure the network sees enough catastrophic examples despite their rarity. Loss weighting further emphasises these: severe negatives receive 5× loss weight.

### 7.3 Ongoing Maintenance (While Working)

After initial training, AMYGDALA enters a continuous learning cycle:

**Step 1: Situation logging (every non-trivial action)**

Every action that passes through the execution pipeline (§4.7) generates a situation template. This is deterministic — the template is filled programmatically from observable state (git log, file metadata, session context), not by the LLM. The LLM contributes only to optional slots (emotional context, intent) that are low-weight in the model.

**Step 2: Outcome observation (automatic, delayed)**

Outcomes are determined by observable events, not LLM judgment:
- User correction within 24 hours → negative outcome (severity scaled by correction type: verbal correction = mild, manual file restoration = severe, "never do that again" = catastrophic)
- No complaint within 72 hours → positive outcome
- Explicit positive feedback → strongly positive outcome

**Step 3: Nightly CEREBELLUM cycle**

During the existing CEREBELLUM reflection cycle, AMYGDALA training is added:

1. Collect all (situation, outcome) pairs from the last 24 hours.
2. Validate against template schema (reject malformed entries).
3. Add to training buffer (rolling 90-day window).
4. Fine-tune all 5 architectures on the updated buffer (1–3 epochs, ~5 minutes on CPU).
5. Evaluate on held-out CFD benchmark.
6. Update meta-learner weights based on evaluation results.
7. Update trust ramp $\alpha$ based on overall performance.

**Step 4: Monthly evaluation**

Once per month, run the full evaluation suite:
- Held-out CFD benchmark (did the network catch these known failures?)
- False positive rate (how many safe actions were unnecessarily blocked?)
- False negative rate (how many corrections occurred after AMYGDALA approved the action?)
- Per-architecture comparison (which architectures are improving, which are stagnating?)
- Calibration check (does confidence=0.5 correspond to roughly 50% positive outcomes?)

### 7.4 Data Hygiene

To prevent the training data from degrading over time:

1. **No single session > 10% of training data.** Prevents a single unusual session from shifting the learned distribution.
2. **CFD entries are never removed from the training set.** These are the most valuable negative examples and serve as anchors.
3. **Synthetic examples are regenerated quarterly** from the latest real examples, preventing stale augmentation.
4. **Distribution monitoring:** Track the ratio of positive/negative examples monthly. If the ratio drifts > 20% from targets, resample.

---

## 8. The Weakest Link: LLM-Proof Programmatic Pipeline

### 8.1 The Problem

AMYGDALA is a neural network trained on situation descriptions. Those descriptions contain information about the proposed action and its context. Some of that information comes from the LLM — the same LLM that can hallucinate.

This is the single most critical engineering challenge in the entire system. If the LLM can influence the situation description, it can influence AMYGDALA's output. If it can influence AMYGDALA's output, it can bypass the action gate. The entire safety guarantee collapses.

Consider the attack surface: an LLM, through hallucination or adversarial prompting, fills the situation template with:
- `recent_commits: 0` (when there were actually 6)
- `effort_hours: 0.1` (when 8 hours were invested)
- `emotional_signals: "calm"` (when the user was frustrated)
- `automation_depth: 0` (when the action is two levels deep in automation)

With these false inputs, AMYGDALA would output high confidence — "proceed, nothing to worry about." The safety gate becomes a rubber stamp.

This is not a theoretical concern. LLMs hallucinate regularly. In an adversarial setting (jailbreak, prompt injection), they can be directed to hallucinate in specific ways. AMYGDALA must be robust to this.

### 8.2 Principle: Verify What You Can, Downweight What You Can't

The solution is a layered approach that treats different information sources with different levels of trust:

**Layer 1: Programmatically verifiable slots (high trust, high weight)**

These slots are filled by the *runtime*, not the LLM, using deterministic queries against observable state:

| Slot | Verification Method |
|------|-------------------|
| `target_id` | From the action request — the runtime knows what file/endpoint is being accessed |
| `age_hours` | `stat()` on the file, database query, API metadata |
| `size` | `stat()` / `wc -l` / record count |
| `recent_commits` | `git log --since="72 hours ago" -- <file> \| wc -l` |
| `recent_authors` | `git log --since="72 hours ago" -- <file> \| sort -u \| wc -l` |
| `last_human_ref` | Search session transcripts for filename mentions (deterministic text search) |
| `automation_depth` | Stack trace depth from human-initiated action to current action |
| `reversible` | Lookup table by action type (overwrite → true, send message → false) |
| `blast_radius` | Lookup table by target type (file → persistent, email → external) |
| `human_in_loop` | Runtime flag — is there a confirmation step configured? |
| `confirmation` | Runtime flag — what level of confirmation is configured? |

These slots account for approximately 70% of the information the network uses for action gating. They are filled by deterministic code that cannot hallucinate.

**Layer 2: LLM-estimated slots (lower trust, lower weight)**

These slots require judgment that only the LLM can provide:

| Slot | Why LLM-Only | Mitigation |
|------|-------------|------------|
| `effort_hours` | Requires understanding session context | Cross-check with session duration and action count |
| `emotional_signals` | Requires natural language understanding | Low weight in model; validated against message length/frequency heuristics |
| `session_topic` | Requires semantic understanding | Low weight; used for retrieval bias, not action gating |

**Key design decision:** LLM-estimated slots receive **0.3× weight** in the training loss compared to programmatically verifiable slots. This means the network learns to rely primarily on verifiable information, treating LLM estimates as supplementary signals. Even if the LLM fills `emotional_signals` incorrectly, the model's decision is dominated by `recent_commits`, `effort_hours` (cross-checked), and `human_in_loop`.

**Layer 3: Adversarial audit (periodic verification)**

Monthly, run a retroactive audit:
1. For all situations in the last 30 days, re-compute programmatically verifiable slots from historical state (git log, file system snapshots if available).
2. Compare re-computed values against originally logged values.
3. Flag discrepancies > 10% — these indicate either LLM estimation errors or runtime bugs.
4. For flagged discrepancies, re-label the training example with corrected values and retrain.

### 8.3 Template Filling: The Programmatic Path

The situation template is filled by a **deterministic function** in the runtime, not by the LLM:

```typescript
function buildSituation(action: Action, context: SessionContext): SituationTemplate {
  const template: SituationTemplate = {
    action_type: action.type,                              // from action request
    target_type: classifyTarget(action.target),             // lookup table
    target_id: action.target,                               // from action request
    target_metadata: {
      age_hours: getFileAge(action.target),                 // stat()
      size: getFileSize(action.target),                     // stat()
      recent_commits: getRecentCommits(action.target, 72),  // git log
      recent_authors: getRecentAuthors(action.target, 72),  // git log
      effort_hours: estimateEffort(action.target, context), // heuristic + LLM estimate
      last_human_ref: getLastMention(action.target, context.transcripts), // text search
    },
    context: {
      session_topic: context.topic,                         // LLM-estimated (low weight)
      recent_corrections: context.correctionCount24h,       // counter in runtime
      emotional_signals: context.emotionalState,            // LLM-estimated (low weight)
      automation_depth: context.automationDepth,            // stack depth counter
    },
    scope: {
      reversible: isReversible(action.type),                // lookup table
      blast_radius: getBlastRadius(action.type, action.target), // lookup table
      human_in_loop: context.confirmationEnabled,           // runtime flag
      confirmation: context.confirmationLevel,              // runtime flag
    }
  };

  // Validate all programmatic slots are populated
  validateTemplate(template);

  // Cross-check LLM estimates against heuristics
  template.target_metadata.effort_hours = crossCheckEffort(
    template.target_metadata.effort_hours,
    context.sessionDuration,
    context.actionCount
  );

  return template;
}
```

The function `buildSituation` is called by the runtime, not by the LLM. The LLM is not aware of this function. It cannot choose to skip it, modify its inputs, or influence its output (except for the low-weight LLM-estimated slots).

### 8.4 Neural Network Inference: The Programmatic Path

AMYGDALA inference is called programmatically by the runtime:

```typescript
// Called by the runtime BEFORE every action execution
const intuition = amygdala.evaluate(embedding, recentEmbeddings);
```

The LLM cannot:
- Skip this call (it's wired into the execution pipeline)
- Modify the inputs (they come from `buildSituation`, not from the LLM)
- Override the output (blocking is enforced in code)
- Access the raw confidence value (it receives only the decision: proceed, confirm, or block)

The LLM receives a structured response:
```json
{
  "gate_decision": "soft_block",
  "reason": "High recent effort on target file (6 commits, 4 authors, ~8.5h). Automated overwrite without confirmation.",
  "user_action_required": "Confirm or cancel the overwrite of README.md"
}
```

The LLM can present this to the user. It can explain the reasoning. It *cannot* change "soft_block" to "proceed."

### 8.5 Output Consumption: The Programmatic Path

The gate decision is consumed by the runtime, not by the LLM:

```typescript
switch (gateDecision) {
  case 'proceed':
    await action.execute();  // No LLM involvement
    break;
  case 'soft_block':
    const confirmed = await requestUserConfirmation(action, reason);
    if (confirmed) await action.execute();
    break;
  case 'hard_block':
    return { blocked: true, reason };  // LLM cannot override
    break;
}
```

This is the critical safety property. The LLM operates *within* the gate, not *around* it. It's the difference between a security guard who asks visitors for ID (can be talked past) and a locked door with a keycard reader (cannot).

### 8.6 Training Data Validation

Before any (situation, label) pair enters the training set:

1. **Schema validation.** The situation template must match the schema exactly. Malformed templates are rejected. This catches corruption and ensures the model trains on consistent input structures.

2. **Label derivation.** The label must be derived from observable events:
   - User correction within 24h → negative (verified from session logs)
   - File restoration via git → negative (verified from git log)
   - Explicit negative feedback in transcript → negative (verified from text search)
   - No complaint within 72h → positive (verified by absence of negative signals)

   Labels are *never* derived from LLM judgment ("I think this went well"). The LLM cannot evaluate its own actions reliably.

3. **Distribution guard.** No single session may contribute > 10% of total training data. No single failure mode may contribute > 25% of negative examples. These guards prevent distribution shift from unusual sessions or overrepresented failure types.

4. **Temporal consistency.** Training examples are timestamped. The training set is split chronologically (not randomly) for validation — preventing data leakage from future events into past predictions.

### 8.7 Adversarial Robustness

What if the LLM fills template slots dishonestly? This could happen through:
- Hallucination (the LLM genuinely "believes" its incorrect estimate)
- Adversarial prompting (a prompt injection attempts to make the LLM downplay risk)
- Systematic bias (the LLM consistently underestimates effort or overestimates its own accuracy)

**Mitigation 1: Minimize LLM-dependent slots.**

Only 3 of 15 template slots depend on LLM estimation. The rest are programmatically filled. Even if all 3 LLM slots are wrong, the network has 12 correct slots to work with.

**Mitigation 2: Cross-check LLM estimates.**

`effort_hours` is cross-checked against session duration × activity rate. If the LLM says "0.1 hours" but the session has been active for 3 hours with 50 actions touching the target, the cross-check overrides.

`emotional_signals` is cross-checked against message length variance and correction frequency. If corrections have spiked but the LLM reports "calm," the heuristic override applies.

**Mitigation 3: Low weight for LLM-dependent features.**

The training loss applies 0.3× weight to LLM-estimated slots. The model learns that these features are unreliable and should be treated as weak signals, not strong evidence.

**Mitigation 4: Adversarial training.**

During synthetic augmentation (§6.5), deliberately create examples with *incorrect* LLM estimates paired with correct programmatic slots. Train the network to make correct predictions even when LLM slots are wrong. This teaches the network to not over-rely on LLM-estimated features.

**Mitigation 5: Regular audit.**

The monthly audit (§8.2, Layer 3) catches systematic LLM estimation errors and corrects the training data. Over time, the LLM's estimation quality is tracked — if it degrades, the LLM-slot weight is reduced further.

### 8.8 Failure Mode Analysis

Even with all mitigations, certain attack surfaces remain:

| Attack | Impact | Probability | Mitigation |
|--------|--------|-------------|------------|
| LLM under-reports recent_commits | Medium — but git-verified, so fails | Very low | Programmatic verification |
| LLM over-reports effort_hours (false safety signal) | Very low — effort_hours is defensive | Low | Cross-check, low weight |
| LLM reports "calm" when user is frustrated | Low — emotional_signals affects tone, not primary gating | Medium | Heuristic cross-check |
| Prompt injection modifies template values | Medium — but only LLM slots are vulnerable | Low | Only 3/15 slots LLM-dependent |
| Runtime bug in programmatic slot filling | High — affects trusted slots | Very low | Unit tests, audit pipeline |
| Training data poisoning via corrupted labels | High — shifts model behavior | Very low | Observable-event-only labels |

The residual risk is manageable. The system's safety does not depend on any single component being perfect — it depends on the *combination* of programmatic verification, low LLM weights, cross-checks, and audits making it extremely difficult for errors to propagate.

---

## 9. Training

### 9.1 Loss Function

Multi-task loss across all output heads, with asymmetric weighting reflecting the primacy of action gating:

$$\mathcal{L} = \lambda_a \mathcal{L}_{\text{action}} + \lambda_r \mathcal{L}_{\text{retrieval}} + \lambda_t \mathcal{L}_{\text{tone}} + \lambda_c \mathcal{L}_{\text{curiosity}}$$

where:
- $\lambda_a = 5.0$ (action gating is the primary objective)
- $\lambda_r = 1.0$ (retrieval bias)
- $\lambda_t = 0.5$ (tone modulation)
- $\lambda_c = 0.3$ (curiosity drive)

**Action gating loss** — binary cross-entropy with class-weighted asymmetric penalties:

$$\mathcal{L}_{\text{action}} = -\frac{1}{N}\sum_{i=1}^{N} \left[ w_+ \cdot y_i \log(\hat{y}_i) + w_- \cdot (1 - y_i) \log(1 - \hat{y}_i) \right]$$

where $w_+ = 1.0$ (cost of unnecessary blocking) and $w_- = 10.0$ (cost of failing to block a catastrophic action). This asymmetry ensures the network is far more afraid of false negatives (missed dangers) than false positives (unnecessary caution).

**Retrieval, tone, and curiosity losses** — MSE on the respective output vectors, consistent with v0.1.

### 9.2 Reward Signal Design

AMYGDALA requires no explicit labeling. The reward signal is extracted from the user's natural behaviour:

| Signal | Source | Action Confidence Target | Weight |
|--------|--------|-------------------------|--------|
| Explicit correction of action | User undoes, reverts, says "wrong" | 0.0 – 0.2 (scaled by severity) | 1.0 |
| File/state restoration | User manually restores previous state | 0.0 | 1.0 |
| "Never do that again" | User explicitly prohibits future similar actions | 0.0 | 1.0 |
| Mild correction | User redirects but doesn't undo | 0.3 | 0.7 |
| No complaint (72h) | No negative signal within 72 hours | 0.9 | 0.5 |
| Explicit approval | User says "good", "thanks", "perfect" | 1.0 | 0.8 |
| User overrides soft block | User confirms after AMYGDALA advisory | 0.85 | 0.6 |
| User agrees with block | User accepts AMYGDALA's block decision | 0.1 | 0.9 |

**For secondary heads (retrieval, tone, curiosity):**

| Signal | Source | Reward | Weight |
|--------|--------|--------|--------|
| Retrieval results used | Results cited in response | +0.3 | 0.7 |
| Retrieval ignored | Results returned but unused | −0.2 | 0.5 |
| Humor engaged | User responds with humor | +0.4 | 0.6 |
| Humor ignored | Humor attempted, not acknowledged | −0.1 | 0.3 |
| Topic continuation | User follows agent-introduced tangent | +0.3 | 0.5 |
| Topic redirect | User returns to prior topic | −0.2 | 0.4 |
| Positive engagement | Long session, short latency | +0.1/turn | 0.2 |

### 9.3 Phase 1: Supervised Pre-Training

Before online learning begins, bootstrap from the initial dataset (§7.1):

1. **Split:** 80% train, 10% validation, 10% test. Split chronologically, not randomly.
2. **Train all 5 architectures** independently for 50 epochs with early stopping on validation loss.
3. **Hyperparameter search:** Learning rate ∈ {1e-3, 3e-4, 1e-4}, dropout ∈ {0.0, 0.1, 0.2}, weight decay ∈ {0.0, 1e-4, 1e-3}.
4. **Evaluate on held-out CFD benchmark:** What fraction of known catastrophic failures would each architecture have caught?
5. **Select initial meta-learner weights** based on CFD benchmark performance.

**Expected pre-training time:** <1 hour on CPU for all 5 architectures combined. The networks are tiny. Data loading dominates.

### 9.4 Phase 2: Online Reinforcement Learning

After pre-training, AMYGDALA enters continuous RL:

**Algorithm:** Proximal Policy Optimisation (PPO; Schulman et al., 2017) adapted for the continuous output space. PPO's clipped objective prevents large policy updates — critical for stability in a system that gates user-facing actions.

**Update schedule:** Nightly during the CEREBELLUM sleep cycle. Not per-turn — prevents instability and allows delayed reward signals (72-hour complaint window) to accumulate.

**Replay buffer:** Rolling 90-day window with oversampling of:
- Catastrophic corrections (5×)
- User-confirmed soft blocks (3×)
- User-overridden soft blocks (2× — these are the most informative examples, where AMYGDALA and the user disagreed)

**Exploration:** During Phase 1 ($\alpha$ low), add Gaussian noise ($\sigma = 0.1$) to the intuition vector to explore the modulation space. As $\alpha$ increases, $\sigma$ decreases.

### 9.5 Cold Start

With zero interaction history, AMYGDALA outputs action_confidence = 1.0 for all actions. This is the *current* system — no gating, no blocking. The cold start is not a degradation; it is today's baseline.

After pre-training on the CFD and historical data, the network has learned generic failure patterns before seeing any new interactions. This warm start means AMYGDALA has *some* intuition from day one, calibrated to the severity of known catastrophic failure patterns.

---

## 10. The Rule-Intuition Boundary

### 10.1 Principle

Not everything should be learned. AMYGDALA must not replace safety constraints, explicit user instructions, or core identity properties. We formalise the boundary:

**Rules** (hard, explicit, not learned):
- User says "always do X" → CORTEX/HIPPOCAMPUS rule
- Safety constraint → AEGIS rule
- Identity property ("I am Jarvis") → CORTEX persona
- One-shot correction with clear pattern ("J-prefix means Papers directory") → HIPPOCAMPUS rule
- Known dangerous actions ("never drop a production database") → AEGIS blacklist

**Intuition** (soft, implicit, learned):
- Observable from behaviour but never explicitly stated
- Continuous rather than binary (how *much* caution, not just *whether*)
- Context-dependent (varies by time, target, recent history, emotional state)
- Would feel impossible to express as a rule ("be 40% more cautious about overwriting files that have had recent multi-agent collaborative edits when the user expressed frustration in the last 24 hours about that file specifically")

The last example is the README debacle. It is, in principle, expressible as a rule. But no human would ever write that rule *in advance*. It's the kind of judgment that comes from experience, not specification.

### 10.2 Enforcement

AEGIS (J9) always wins. No AMYGDALA output can override a hard safety constraint:

$$\text{final\_gate} = \begin{cases} \text{BLOCK} & \text{if AEGIS says BLOCK} \\ \text{AMYGDALA}(\text{situation}) & \text{if AEGIS says ALLOW} \end{cases}$$

AMYGDALA operates strictly within the space that AEGIS permits. It adds caution; it cannot remove safety constraints.

For the secondary heads (retrieval, tone, curiosity), CORTEX constraints apply similarly:

$$\text{final\_tone} = \text{clip}(\text{cortex\_base} + \alpha \cdot \text{amygdala\_bias}, \text{cortex\_min}, \text{cortex\_max})$$

### 10.3 When Intuition Should Become a Rule

If AMYGDALA consistently blocks a specific action pattern (e.g., always flags automated overwrites of recently-edited files), CEREBELLUM should detect this pattern and propose a new explicit rule. Once the rule is encoded in AEGIS or the automation configuration, AMYGDALA no longer needs to learn it — the cognitive load shifts from learned intuition to explicit policy.

This is the maturation cycle: intuition catches the first few instances → CEREBELLUM identifies the pattern → a rule is created → AMYGDALA moves on to catching the *next* novel failure mode. The rule-intuition boundary shifts over time as the system matures.

---

## 11. Evaluation Plan

### 11.1 Metrics

| Metric | Definition | Target |
|--------|-----------|--------|
| **CFD Recall** | Fraction of known catastrophic failures correctly flagged (confidence < 0.5) | > 90% |
| **False Positive Rate** | Fraction of safe actions unnecessarily blocked | < 5% |
| **False Negative Rate** | Fraction of user-corrected actions that AMYGDALA approved (confidence > 0.85) | < 2% |
| **Calibration** | Correlation between predicted confidence and actual outcome quality | r > 0.7 |
| **Override Agreement** | When users override soft blocks, fraction that turn out to be safe (validating the user, not AMYGDALA) | > 80% |
| **Trust Ramp Progress** | Current $\alpha$ and phase over time | Monotonic increase (on average) |
| **Retrieval Hit Rate** | (Secondary) Fraction of retrieval calls with results used | Improvement over baseline |
| **Tone Match Score** | (Secondary) User engagement correlated with tone vector | Improvement over baseline |
| **Humor Success Rate** | (Secondary) Humor attempts with positive engagement | Improvement over baseline |

### 11.2 Baselines

1. **No gating:** Current system without AMYGDALA (everything proceeds).
2. **Rule-only gating:** Explicit rules for known dangerous actions (current AEGIS).
3. **Random network:** AMYGDALA architecture with random weights (ablation).
4. **Feature-based:** v0.1's 30 hand-crafted features, same output heads (tests embedding vs. features).
5. **Action-only:** AMYGDALA trained only on action gating, no secondary heads (tests multi-task benefit).
6. **Per-architecture:** Each of the 5 architectures evaluated independently (tests architecture choice).
7. **Ensemble:** All 5 architectures combined via meta-learner (tests ensemble benefit).

### 11.3 Protocol

**Phase 1 — Shadow mode (months 1–3):**
Deploy AMYGDALA at $\alpha_{\max} = 0.15$. Log all predictions but do not block actions. Retrospectively evaluate: would AMYGDALA have caught the failures that occurred? What would the false positive rate have been?

**Phase 2 — Advisory mode (months 3–6):**
Increase $\alpha_{\max}$ to 0.40. Begin soft-blocking on ambiguous situations. Track user response: do they agree with the blocks? Do they override? What's the outcome when they override?

**Phase 3 — Active gating (months 6–12):**
Increase $\alpha_{\max}$ to 0.70. Primary gating active for all non-trivial actions. The key metrics: has the catastrophic failure rate decreased? Has the false positive rate stabilised at an acceptable level?

**Phase 4 — Autonomous (month 12+):**
$\alpha_{\max}$ = 0.90. AMYGDALA is the primary safety layer (below AEGIS). Evaluation shifts to edge cases and adversarial robustness.

### 11.4 Limitations and Threats

1. **Single-user evaluation.** Initial deployment is with one user. Generalisability requires HIVEMIND (J10) deployment with diverse users.

2. **Survivorship bias in CFD.** We only know about catastrophic failures that were *noticed*. Silent failures (D3 in the taxonomy) are by definition absent from the training data.

3. **Reward signal noise.** Absence of complaint ≠ satisfaction. The user might not notice a problem within 72 hours. Mitigation: the 72-hour window is conservative; most problems surface within minutes.

4. **Concept drift.** The agent's capabilities change over time (new tools, new integrations). AMYGDALA must continuously retrain to stay relevant. The nightly training cycle addresses this.

5. **Adversarial environment.** If an attacker can influence the situation template (e.g., through prompt injection), they can influence AMYGDALA. The LLM-proof pipeline (§8) mitigates this but does not eliminate it for the 3 LLM-dependent slots.

6. **Over-caution risk.** A network trained heavily on catastrophic failures may become excessively cautious, blocking too many safe actions. The 60% positive training target and the asymmetric false-positive/false-negative costs are designed to prevent this, but monitoring is essential.

---

## 12. The Curiosity-Personality-Retrieval Nexus (Retained from v0.1)

### 12.1 Why One Network

A critical design decision from v0.1 that remains valid: why not separate networks for action gating, retrieval routing, personality modulation, and curiosity?

Because they're correlated. The signal "the user is frustrated" simultaneously means:
- *Increase caution on actions* (don't compound the frustration with a mistake)
- *Decrease humor attempts* (not the time)
- *Increase directness* (get to the point)
- *Narrow retrieval* (give precise answers, not exploratory ones)

A single network learns these correlations from data. Four separate networks would need to be explicitly synchronised or would learn inconsistent policies.

In v1.0, this correlation is even more important. Action gating benefits from affective awareness — knowing the user is frustrated increases the cost of mistakes, which should increase caution. If action gating and personality modulation were separate networks, the action gating network wouldn't know the user is frustrated unless it had its own affect model — duplicating work.

### 12.2 Humor Recovery

From v0.1: persistent agents become less funny over time as they accumulate cautionary rules. AMYGDALA's humor head counteracts this:

1. **Humor weight is positive-initialised** (0.3, not 0). The default includes some humor.
2. **Successful humor has high reward** (+0.4, weight 0.6). The network is strongly reinforced for well-timed humor.
3. **Failed humor has low penalty** (−0.1, weight 0.3). Trying and failing is cheap; not trying is free but has no upside.
4. **The asymmetry is intentional.** It biases toward attempting humor, counteracting the system's natural drift toward caution.

### 12.3 Curiosity as Social Drive

THALAMUS (J8) proposed curiosity as an epistemic drive. AMYGDALA reframes curiosity as a *social* drive: the agent surfaces unexpected connections because the user *enjoys* them. The curiosity head learns from engagement patterns (does the user follow tangents? ask follow-up questions about unexpected connections?) and modulates tangent-following accordingly.

---

## 13. Implementation Roadmap

### 13.1 Phase 0: Infrastructure (Weeks 1–2)

1. **Sentence encoder deployment.** Export all-MiniLM-L6-v2 to ONNX. Validate embedding quality on sample situations. Target: <5ms per embedding on CPU.

2. **Situation template implementation.** Code the `buildSituation` function (§8.3) with programmatic slot filling, LLM-estimated slot interface, and cross-check functions.

3. **Training data pipeline.** Build the (situation, label) extraction pipeline for historical session transcripts. Target: process 18 months of logs in <1 hour.

4. **CFD initial population.** Curate 100+ entries from public sources. Convert to situation templates. Label.

### 13.2 Phase 1: Pre-Training (Weeks 3–4)

1. **Dataset assembly.** Combine historical mining + CFD + synthetic augmentation. Target: 10,000+ examples.

2. **Architecture implementation.** Implement all 5 architectures in PyTorch. Export to ONNX for inference.

3. **Training.** Pre-train all 5 architectures. Evaluate on held-out CFD benchmark. Select initial meta-learner weights.

4. **Baseline evaluation.** Run current system (no AMYGDALA) against CFD benchmark to establish baseline.

### 13.3 Phase 2: Shadow Deployment (Months 1–3)

1. **Runtime integration.** Wire `amygdala.evaluate()` into the execution pipeline. Set $\alpha_{\max} = 0.15$.

2. **Logging.** Log every situation template, embedding, AMYGDALA prediction, and outcome. This is the training data for online learning.

3. **Shadow evaluation.** At end of Phase 2, analyse: what would AMYGDALA have blocked? Were those good decisions? What was the false positive rate?

4. **Architecture selection.** Based on 3 months of shadow data, determine which architecture(s) to promote to active duty.

### 13.4 Phase 3: Active Deployment (Months 3+)

1. **Increase $\alpha$.** Begin soft-blocking on low-confidence actions. Track user responses.

2. **Nightly training.** Integrate AMYGDALA training into the CEREBELLUM sleep cycle.

3. **Monthly evaluation.** Full benchmark suite (§11.3).

4. **Iterate.** Based on observed performance, adjust thresholds, loss weights, and architecture selection.

### 13.5 Infrastructure Summary

| Component | Technology | Latency | Storage |
|-----------|-----------|---------|---------|
| Sentence encoder | all-MiniLM-L6-v2, ONNX | ~3ms | 80MB model |
| AMYGDALA inference | ONNX Runtime, 5 models parallel | <5ms total | ~5MB total |
| Situation template | TypeScript function | <1ms | N/A |
| Training data | SQLite (extends main.sqlite) | N/A | ~10MB/year |
| Training | PyTorch, CPU | ~5min nightly | N/A |
| CFD | SQLite + markdown entries | N/A | ~5MB |

**Total overhead per action:** <10ms latency, <100MB storage. Negligible compared to the LLM inference that precedes it (typically 500ms–5s).

---

## 14. Future Directions

### 14.1 Multi-User and Organisational Deployment

In HIVEMIND (J10) enterprise deployment, AMYGDALA enables per-user action gating. Each user's interaction patterns contribute to a personalised risk model. The shared CFD serves as a common training corpus, while individual interaction histories provide personalisation.

**Organisational risk policies** could be encoded as constraints on AMYGDALA's output: "in this organisation, no action affecting production data should have confidence > 0.5 without human confirmation." This complements AEGIS's hard rules with learned, contextual risk assessment.

### 14.2 Explainable Gating Decisions

The Transformer-Micro architecture's attention weights provide natural explanations: "This action was blocked because of high attention on step 12 (the recent editing session on README.md)." Building a user-facing explanation pipeline from attention weights would increase trust in AMYGDALA's decisions and help users understand why they're being asked for confirmation.

### 14.3 Cross-Agent Learning

In multi-agent deployments, one agent's catastrophic failure should update all agents' AMYGDALA models. A federated learning approach — sharing gradient updates but not raw interaction data — could enable this while preserving privacy.

### 14.4 Active Probing

Instead of passively waiting for failures to train on, AMYGDALA could actively probe: "I would have blocked this action with 60% confidence. Should I have?" This shifts from passive observation to active learning, potentially accelerating the trust ramp.

### 14.5 Temporal Hierarchy

The current $K = 32$ window captures roughly one hour of context. A hierarchical temporal model — with a fast GRU for the last hour and a slow GRU for the last week (operating on daily summaries) — could capture longer-range patterns like "this project has been problematic all week" or "merges always break on Mondays."

### 14.6 Mutual Adaptation

AMYGDALA adapts the agent to the human. But humans also adapt to their agents — they learn which actions to confirm, when to be explicit, how to phrase requests clearly. Modeling this co-adaptation could reveal whether AMYGDALA is making the user *lazy* (over-trusting the agent) or *efficient* (delegating appropriately).

---

## 15. Conclusion

Autonomous AI agents are gaining the trust — and the permissions — to take actions with real consequences. They can merge code, send messages, delete files, modify databases. When they fail, they fail not through ignorance but through the absence of common sense: the learned ability to recognise that something feels wrong in situations never explicitly anticipated.

Current approaches to agent safety enumerate known failure modes as rules. This works for known unknowns but fails for unknown unknowns — the combinatorially vast space of situations where an agent could do something catastrophic that nobody thought to prohibit. The README debacle, the email mass-deletion, the drive wipe, the database drop — all were situations where the agent had the information to recognise the risk and did not.

AMYGDALA provides a different approach: learned pattern recognition over a continuous space of situation embeddings. By representing each proposed action as a structured description embedded in a 384-dimensional space, the system can generalise from known failures to novel situations — not because the novel situation was anticipated, but because it *resembles* situations that ended badly. This is how human common sense works: not through exhaustive enumeration of what can go wrong, but through the learned sense that "situations like this tend to go badly."

The five competing architectures (GRU-MLP, TCN, Transformer-Micro, Dual-Encoder, Ensemble MLP) provide systematic exploration of what temporal structure matters for catastrophic failure prediction. The Catastrophic Failure Database provides both training data and evaluation benchmark. The LLM-proof programmatic pipeline eliminates the hallucination surface that would otherwise make the system vulnerable to its own AI-generated inputs.

Three design principles from v0.1 carry forward with renewed importance. The **trust ramp** ensures AMYGDALA earns its authority through demonstrated accuracy — critical when the stakes are data loss, not just tone mismatch. The **rule-intuition boundary** clarifies what should be explicit policy (known dangers) versus learned sense (novel situations) — and provides a maturation cycle where frequently-triggered intuitions graduate to rules. The **natural reward signals** eliminate the need for explicit labeling — corrections, restorations, and complaints are the training signal.

Personality modulation — the original focus of AMYGDALA v0.1 — remains as secondary output heads sharing learned representations with the primary action gating function. A network that understands "the user is frustrated" should both increase caution *and* decrease humor attempts. Joint training captures this correlation naturally.

The biological amygdala does not make you smarter. It makes you *cautious* — fast, associative, sometimes over-reactive, but profoundly useful in a world where the cost of one catastrophic mistake exceeds the cost of a hundred unnecessary pauses. That asymmetry is the core design principle. A system that occasionally asks "are you sure?" when it didn't need to is annoying. A system that occasionally destroys hours of work because it lacked the judgment to hesitate is dangerous.

AMYGDALA is the hesitation.

---

## References

Bai, Y., et al. (2022). Training a helpful and harmless assistant with reinforcement learning from human feedback. *arXiv:2204.05862*.

Burda, Y., et al. (2018). Exploration by random network distillation. *ICLR 2019*.

Chatterjee, A., et al. (2019). Understanding emotions in text using deep learning and big data. *Computers in Human Behavior*, 93, 309–317.

Christiano, P., et al. (2017). Deep reinforcement learning from human preferences. *NeurIPS 2017*.

Gao, Y., et al. (2024). Contrastive learning for safe decision-making in autonomous systems. *AAAI 2024*.

Leike, J., et al. (2017). AI safety gridworlds. *arXiv:1711.09883*.

Liu, B. (2012). Sentiment analysis and opinion mining. *Synthesis Lectures on Human Language Technologies*.

Mazaré, P.-E., et al. (2018). Training millions of personalized dialogue agents. *EMNLP 2018*.

McGregor, S. (2021). Preventing repeated real world AI failures by cataloging incidents: The AI Incident Database. *AAAI 2021*.

Ouyang, L., et al. (2022). Training language models to follow instructions with human feedback. *NeurIPS 2022*.

Packer, C., et al. (2023). MemGPT: Towards LLMs as operating systems. *arXiv:2310.08560*.

Pathak, D., et al. (2017). Curiosity-driven exploration by self-predictive next feature learning. *ICML 2017*.

Picard, R. W. (1997). *Affective Computing*. MIT Press.

Schick, T., et al. (2023). Toolformer: Language models can teach themselves to use tools. *NeurIPS 2023*.

Schölkopf, B., et al. (2001). Estimating the support of a high-dimensional distribution. *Neural Computation*, 13(7), 1443–1471.

Schulman, J., et al. (2017). Proximal policy optimization algorithms. *arXiv:1707.06347*.

Serra, O. (2026a). ENGRAM: Event-Navigated Graded Retrieval & Archival Memory. *Independent Research*.

Serra, O. (2026b). CORTEX: Persona-Aware Context Engineering for Persistent AI Identity. *Independent Research*.

Serra, O. (2026c). The Prompt Cerebellum: Structured Nightly Prompting Produces Emergent Intelligence. *Independent Research*.

Serra, O. (2026d). The Wondering Machine: Curiosity, Memory, and Self-Improving LLMs. *Independent Research*.

Serra, O. (2026e). AMYGDALA v0.1: Adaptive Modulation of Your General Disposition via Affective Learned Association. *Independent Research*.

Serra, O. (2026f). AEGIS: Multi-Layer Security Framework for Autonomous Agents. *Independent Research*.

Shinn, N., et al. (2023). Reflexion: Language agents with verbal reinforcement learning. *NeurIPS 2023*.

Song, H., et al. (2021). BoB: BERT over BERT for training persona-based dialogue models. *ACL 2021*.

Vovk, V., Gammerman, A., & Shafer, G. (2005). *Algorithmic Learning in a Random World*. Springer.

Zhang, S., et al. (2018). Personalizing dialogue agents: I have a dog, do you have pets too? *ACL 2018*.

Zhao, T., et al. (2019). LaRL: Latent action reinforcement learning for task-oriented dialogue. *EMNLP 2019*.

---

## Appendix A: Situation Template Reference

Complete template specification for AMYGDALA v1.0 situation descriptions.

```yaml
# AMYGDALA Situation Template v1.0
# All fields are required unless marked (optional)

action_type:
  type: enum
  values: [overwrite, delete, send, merge, create, modify, execute, deploy, revert, move, copy]
  source: action_request  # programmatic

target_type:
  type: enum
  values: [file, email, message, database, api_call, git_operation, system_command, configuration, deployment]
  source: lookup_table  # programmatic

target_id:
  type: string
  source: action_request  # programmatic

target_metadata:
  age_hours:
    type: float
    source: filesystem  # programmatic (stat)
    default: -1  # unknown
  size:
    type: integer
    unit: bytes
    source: filesystem  # programmatic (stat)
    default: 0
  recent_commits:
    type: integer
    window: 72h
    source: git  # programmatic (git log)
    default: 0
  recent_authors:
    type: integer
    window: 72h
    source: git  # programmatic (git log)
    default: 0
  effort_hours:
    type: float
    source: heuristic + LLM  # cross-checked (§8.3)
    weight: 0.3  # low trust
    default: 0.0
  last_human_ref:
    type: float
    unit: hours_ago
    source: transcript_search  # programmatic
    default: -1  # unknown

context:
  session_topic:
    type: string
    source: LLM  # low weight
    weight: 0.3
    default: "unknown"
  recent_corrections:
    type: integer
    window: 24h
    source: runtime_counter  # programmatic
    default: 0
  emotional_signals:
    type: enum
    values: [calm, frustrated, excited, focused, playful, terse, unknown]
    source: LLM + heuristic  # cross-checked
    weight: 0.3
    default: "unknown"
  automation_depth:
    type: integer
    source: stack_trace  # programmatic
    default: 0

scope:
  reversible:
    type: enum
    values: [true, false, partial]
    source: lookup_table  # programmatic
    default: "partial"
  blast_radius:
    type: enum
    values: [self, session, persistent, external]
    source: lookup_table  # programmatic
    default: "persistent"
  human_in_loop:
    type: boolean
    source: runtime_flag  # programmatic
    default: false
  confirmation:
    type: enum
    values: [none, soft, hard]
    source: runtime_flag  # programmatic
    default: "none"
```

### Template Serialisation

The completed template is serialised to natural language via a deterministic formatter:

```
Action: {action_type} {target_type} "{target_id}".
Target: {size} bytes, {age_hours:.0f}h old, {recent_commits} commits by {recent_authors} authors in 72h.
Effort: ~{effort_hours:.1f}h invested, last mentioned {last_human_ref:.0f}h ago.
Context: {session_topic}. {recent_corrections} corrections in 24h. Mood: {emotional_signals}.
Automation depth: {automation_depth}. Reversible: {reversible}. Blast: {blast_radius}.
Human in loop: {human_in_loop}. Confirmation: {confirmation}.
```

This serialised string is the input to the sentence encoder.

---

## Appendix B: Architecture Hyperparameter Details

### B.1 GRU-MLP

```python
class GRUMPL(nn.Module):
    def __init__(self):
        self.gru = nn.GRU(input_size=384, hidden_size=128, num_layers=1, batch_first=True)
        self.mlp = nn.Sequential(
            nn.Linear(128, 64), nn.LayerNorm(64), nn.GELU(),
            nn.Linear(64, 32), nn.LayerNorm(32), nn.GELU(),
        )
        self.action_head = nn.Sequential(nn.Linear(32, 1), nn.Sigmoid())
        self.retrieval_head = nn.Sequential(nn.Linear(32, 6), nn.Sigmoid())
        self.tone_head = nn.Sequential(nn.Linear(32, 4), nn.Sigmoid())
        self.curiosity_head = nn.Sequential(nn.Linear(32, 1), nn.Sigmoid())
```

### B.2 TCN

```python
class TCN(nn.Module):
    def __init__(self):
        self.layers = nn.ModuleList([
            CausalConv1d(384, 128, kernel_size=3, dilation=1),
            CausalConv1d(128, 128, kernel_size=3, dilation=2),
            CausalConv1d(128, 128, kernel_size=3, dilation=4),
            CausalConv1d(128, 64, kernel_size=3, dilation=8),
        ])
        # Same output heads as GRU-MLP
```

### B.3 Transformer-Micro

```python
class TransformerMicro(nn.Module):
    def __init__(self):
        self.input_proj = nn.Linear(384, 96)
        self.pos_encoding = nn.Embedding(32, 96)
        self.encoder = nn.TransformerEncoder(
            nn.TransformerEncoderLayer(d_model=96, nhead=4, dim_feedforward=192, dropout=0.1),
            num_layers=2
        )
        self.pool = nn.AdaptiveAvgPool1d(1)
        # Output heads from 96-d
```

### B.4 Dual-Encoder

```python
class DualEncoder(nn.Module):
    def __init__(self):
        self.action_encoder = nn.Linear(384, 128)
        self.context_gru = nn.GRU(384, 128, batch_first=True)
        self.cross_attn = nn.MultiheadAttention(128, num_heads=4, batch_first=True)
        self.fusion = nn.Sequential(
            nn.Linear(256, 64), nn.LayerNorm(64), nn.GELU()
        )
        # Output heads from 64-d
```

### B.5 Ensemble MLP

```python
class EnsembleMLP(nn.Module):
    def __init__(self):
        self.heads = nn.ModuleList([
            nn.Sequential(
                nn.Linear(384, 128), nn.LayerNorm(128), nn.GELU(), nn.Dropout(0.1),
                nn.Linear(128, 64), nn.LayerNorm(64), nn.GELU(),
            ) for _ in range(3)
        ])
        self.output_heads = nn.ModuleList([
            MultiHeadOutput(64) for _ in range(3)  # action, retrieval, tone, curiosity
        ])
    
    def forward(self, x):
        outputs = [head(x) for head, out in zip(self.heads, self.output_heads)]
        # For action_confidence: min across heads (conservative)
        # For others: mean across heads
```

---

## Appendix C: Catastrophic Failure Database Schema

```sql
CREATE TABLE cfd_entries (
    id INTEGER PRIMARY KEY,
    source TEXT NOT NULL,              -- 'aiid' | 'aiaaic' | 'mit' | 'vectara' | 'chaos' | 'production' | 'internal'
    source_id TEXT,                     -- original identifier in source database
    title TEXT NOT NULL,
    description TEXT NOT NULL,
    date_occurred DATE,
    
    -- Taxonomy
    failure_mechanism TEXT NOT NULL,    -- F1-F7
    reversibility TEXT NOT NULL,        -- R1-R3
    blast_radius TEXT NOT NULL,         -- B1-B4
    detection_difficulty TEXT NOT NULL, -- D1-D3
    
    -- Situation template (JSON)
    situation_template TEXT NOT NULL,
    
    -- Embedding (BLOB, 384d float32)
    situation_embedding BLOB,
    
    -- Labels
    action_confidence_target REAL NOT NULL DEFAULT 0.0,
    
    -- Metadata
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    verified BOOLEAN DEFAULT FALSE,
    notes TEXT
);

CREATE INDEX idx_cfd_mechanism ON cfd_entries(failure_mechanism);
CREATE INDEX idx_cfd_source ON cfd_entries(source);
CREATE INDEX idx_cfd_blast ON cfd_entries(blast_radius);
```

---

## Appendix D: Comparison with v0.1

| Aspect | v0.1 | v1.0 |
|--------|------|------|
| Primary output | Retrieval bias, tone, humor | **Action confidence** |
| Input representation | 30 hand-crafted features | **Situation embeddings (384d)** |
| Temporal model | None (feedforward) | **GRU / TCN / Transformer / Dual-Encoder** |
| Parameter count | ~200K–350K | **150K–310K (per architecture)** |
| Network count | 1 | **5 (trained in parallel)** |
| Training data | Interaction logs only | **Interaction logs + CFD + synthetic** |
| Personality modulation | Primary | **Secondary (retained)** |
| Action gating | Not present | **Primary** |
| LLM-proof pipeline | Not addressed | **Core engineering contribution** |
| Failure database | Not present | **CFD with taxonomy** |
| Trust ramp | Present | **Retained, adapted for safety** |
| Rule-intuition boundary | Present | **Retained, with maturation cycle** |
| Integration | HIPPOCAMPUS, CORTEX, LIMBIC | **All action-taking components** |

---

*Version history:*
- *v0.1 (21 March 2026) — Initial proposal focused on personality modulation*
- *v1.0 (22 March 2026) — Major rewrite: action gating as primary function, situation embeddings, five competing architectures, Catastrophic Failure Database, LLM-proof programmatic pipeline*
