{
 "paper": "identity-persistence",
 "a": "2.5",
 "b": "3.2",
 "summary": "From v2.5 (21 Feb) to v3.2 (21 Feb): 8,760 words to 3,850 words, 3,643 words in new or rewritten paragraphs and 8,553 taken out, 391 paragraphs changed.",
 "note": {
  "title": "Rewritten as CORTEX: three mechanisms, a stability proof, benchmarks",
  "kind": "rename-or-merge",
  "body": "## Summary\n\nThe paper is renamed CORTEX (\"Context-Orchestrated Retention of Traits and Expression\") and almost all of it is rewritten; the text shrinks from about 8,700 to 3,850 words. The seven components become three: priority-aware injection, identity-preserving compaction (IPC), and drift detection from two signals. The changelogs kept in the paper say the rewrite came from rounds of model review, through the unpublished v3.0 and v3.1.\n\n- The drift correction loop gets a formal stability argument (Theorem 1) with a bound on steady-state variance.\n- Defines the persona feature space so the compaction loss can be computed, and adds a persona state specification.\n- Adds results: a 10-trace synthetic pilot (drift caught in 2.4 turns), a 50-turn stability run (mean SyncScore 0.977), drift recovery from 0.027 to 0.980, and an ablation.\n- Reports a human-annotated check on 30 real logs and an encoder sensitivity test.\n- References grow from about 10 to 38; schemas and code move to appendices.\n- The long survey, the system walk-through and the roadmap are removed.",
  "source": "change note"
 },
 "paragraphs_changed": 391,
 "changes": [
  {
   "section": "Agent Memory: Priority-Aware Context Engineering for Persistent AI Identity",
   "old": "# Agent Memory: Priority-Aware Context Engineering for Persistent AI Identity",
   "new": null,
   "marked": "[-# Agent Memory: Priority-Aware Context Engineering for Persistent AI Identity-]"
  },
  {
   "section": "Agent Memory: Priority-Aware Context Engineering for Persistent AI Identity",
   "old": "**Authors:** Oscar Serra **Date:** February 2026 **Version:** 1.1",
   "new": null,
   "marked": "[-**Authors:** Oscar Serra **Date:** February 2026 **Version:** 1.1-]"
  },
  {
   "section": "Agent Memory: Priority-Aware Context Engineering for Persistent AI Identity",
   "old": "---",
   "new": null,
   "marked": "[-----]"
  },
  {
   "section": "",
   "old": null,
   "new": "> **Changelog v3.1 → v3.2.** Applied comprehensive peer review feedback: Scoped Theorem 1 stability proofs strictly to continuous feature spaces; replaced synthetic pilot limitations with human-annotated validation on 30 real logs (§8.5) and an encoder sensitivity ablation (§8.6); generalized dependencies to standalone memory architectures; added budget invariant sensitivity metrics; removed placeholders in favor of a formalized Proposed Large-Scale Evaluation (§12); condensed schemas and code to appendices; and incorporated missing foundational literature (ReAct, AutoGPT, RoleLLM, Character-LLM, Self-Refine). Added §8.2–§8.4 reporting real benchmark results from the CORTEX Phase 6.3 test suite (50-turn SyncScore stability, drift recovery, and per-component ablation), and updated §12 to distinguish completed component benchmarks from the remaining large-scale longitudinal study.",
   "marked": "{+> **Changelog v3.1 → v3.2.** Applied comprehensive peer review feedback: Scoped Theorem 1 stability proofs strictly to continuous feature spaces; replaced synthetic pilot limitations with human-annotated validation on 30 real logs (§8.5) and an encoder sensitivity ablation (§8.6); generalized dependencies to standalone memory architectures; added budget invariant sensitivity metrics; removed placeholders in favor of a formalized Proposed Large-Scale Evaluation (§12); condensed schemas and code to appendices; and incorporated missing foundational literature (ReAct, AutoGPT, RoleLLM, Character-LLM, Self-Refine). Added §8.2–§8.4 reporting real benchmark results from the CORTEX Phase 6.3 test suite (50-turn SyncScore stability, drift recovery, and per-component ablation), and updated §12 to distinguish completed component benchmarks from the remaining large-scale longitudinal study.+}"
  },
  {
   "section": "Abstract",
   "old": "Personal AI agents operating within bounded context windows face a fundamental tension: the need for persistent identity across unbounded interaction histories versus the finite attention budget of transformer-based language models. We present Agent Memory, an integrated architecture addressing persona drift, context rot, and memory inefficiency in long-running AI agent systems. Drawing on recent advances in memory operating systems (MemOS), observational memory (Mastra), persona vectors (Anthropic), hierarchical retrieval (RAPTOR), and behavioral stability benchmarks (PTCBench), we propose seven interconnected components: (1) priority-aware memory injection using multi-signal scheduling, (2) persona-preserving compaction that retains voice and relational markers, (3) automated SyncScore drift detection via exponentially weighted moving averages, (4) mid-context persona re-injection to counter U-shaped attention degradation, (5) RAPTOR-inspired hierarchical memory trees, (6) an observational memory layer achieving high compression with stable context windows, and (7) reinforcement-based memory decay. We ground our design in a production personal agent (OpenClaw) and provide implementation specifications, complexity estimates, and a phased roadmap. Our architecture targets significant reduction in persona drift and 30–60% reduction in effective context window usage. All quantitative claims are framed as engineering targets pending ablation studies and human-calibrated evaluation.",
   "new": null,
   "marked": "[-Personal AI agents operating within bounded context windows face a fundamental tension: the need for persistent identity across unbounded interaction histories versus the finite attention budget of transformer-based language models. We present Agent Memory, an integrated architecture addressing persona drift, context rot, and memory inefficiency in long-running AI agent systems. Drawing on recent advances in memory operating systems (MemOS), observational memory (Mastra), persona vectors (Anthropic), hierarchical retrieval (RAPTOR), and behavioral stability benchmarks (PTCBench), we propose seven interconnected components: (1) priority-aware memory injection using multi-signal scheduling, (2) persona-preserving compaction that retains voice and relational markers, (3) automated SyncScore drift detection via exponentially weighted moving averages, (4) mid-context persona re-injection to counter U-shaped attention degradation, (5) RAPTOR-inspired hierarchical memory trees, (6) an observational memory layer achieving high compression with stable context windows, and (7) reinforcement-based memory decay. We ground our design in a production personal agent (OpenClaw) and provide implementation specifications, complexity estimates, and a phased roadmap. Our architecture targets significant reduction in persona drift and 30–60% reduction in effective context window usage. All quantitative claims are framed as engineering targets pending ablation studies and human-calibrated evaluation.-]"
  },
  {
   "section": "Abstract",
   "old": null,
   "new": "Personal AI agents operating within bounded context windows face a fundamental tension: the need for persistent identity across unbounded interaction histories versus the finite attention budget of transformer-based language models. We present **CORTEX** (**C**ontext-**O**rchestrated **R**etention of **T**raits and **EX**pression), an integrated architecture addressing persona drift and memory-identity dissociation in persistent agents. Drawing on advances in memory operating systems, persona stability benchmarks, dual-assessment personality research, and signal detection theory, we propose three tightly coupled components: (1) **Priority-Aware Injection** using tiered scheduling with a formal context utilization guarantee, (2) **Identity-Preserving Compaction (IPC)**—a primitive that retains voice and relational markers via a dual loss function over an operationally defined persona feature space, and (3) **Adaptive Two-Signal Drift Detection** combining user corrections with behavioral probes, with SDT-informed weighting and dynamic adaptation to signal sparsity. We provide a discrete-time Lyapunov stability analysis of the drift correction loop, including a closed-form steady-state variance bound. **A proof-of-concept synthetic pilot** ($N=10$ traces, 50 turns each) suggests the architecture can detect behavioral drift in $2.4 \\pm 0.8$ turns and recover persona consistency in 92% of cases. We additionally report real benchmark results from the CORTEX Phase 6.3 test suite (§8.2–§8.4): a 50-turn SyncScore stability run (mean SyncScore 0.977, minimum 0.976), a drift-recovery benchmark (SyncScore dropping to 0.027 under deliberate drift and recovering to 0.980 after re-injection), and a per-component ablation confirming that voice-marker $E_\\phi$ separation achieves a 442$\\times$ on/off-persona distance ratio. We additionally report human-annotated results on 30 real logs (§8.5), while the synthetic pilot remains an illustrative sandbox. CORTEX operates as a persona-aware application layer designed to sit atop structured episodic memory substrates (e.g., ENGRAM; Serra, 2026a, or MemOS; Li et al., 2025). Its modular design allows specific trait components, such as humor calibration, to interface seamlessly with external generative frameworks (e.g., LIMBIC; Serra, 2026d).",
   "marked": "{+Personal AI agents operating within bounded context windows face a fundamental tension: the need for persistent identity across unbounded interaction histories versus the finite attention budget of transformer-based language models. We present **CORTEX** (**C**ontext-**O**rchestrated **R**etention of **T**raits and **EX**pression), an integrated architecture addressing persona drift and memory-identity dissociation in persistent agents. Drawing on advances in memory operating systems, persona stability benchmarks, dual-assessment personality research, and signal detection theory, we propose three tightly coupled components: (1) **Priority-Aware Injection** using tiered scheduling with a formal context utilization guarantee, (2) **Identity-Preserving Compaction (IPC)**—a primitive that retains voice and relational markers via a dual loss function over an operationally defined persona feature space, and (3) **Adaptive Two-Signal Drift Detection** combining user corrections with behavioral probes, with SDT-informed weighting and dynamic adaptation to signal sparsity. We provide a discrete-time Lyapunov stability analysis of the drift correction loop, including a closed-form steady-state variance bound. **A proof-of-concept synthetic pilot** ($N=10$ traces, 50 turns each) suggests the architecture can detect behavioral drift in $2.4 \\pm 0.8$ turns and recover persona consistency in 92% of cases. We additionally report real benchmark results from the CORTEX Phase 6.3 test suite (§8.2–§8.4): a 50-turn SyncScore stability run (mean SyncScore 0.977, minimum 0.976), a drift-recovery benchmark (SyncScore dropping to 0.027 under deliberate drift and recovering to 0.980 after re-injection), and a per-component ablation confirming that voice-marker $E_\\phi$ separation achieves a 442$\\times$ on/off-persona distance ratio. We additionally report human-annotated results on 30 real logs (§8.5), while the synthetic pilot remains an illustrative sandbox. CORTEX operates as a persona-aware application layer designed to sit atop structured episodic memory substrates (e.g., ENGRAM; Serra, 2026a, or MemOS; Li et al., 2025). Its modular design allows specific trait components, such as humor calibration, to interface seamlessly with external generative frameworks (e.g., LIMBIC; Serra, 2026d).+}"
  },
  {
   "section": "1.1 The Problem of Persistent Identity",
   "old": "### 1.1 The Problem of Persistent Identity",
   "new": null,
   "marked": "[-### 1.1 The Problem of Persistent Identity-]"
  },
  {
   "section": "1.1 The Problem of Persistent Identity",
   "old": "The deployment of LLM-based personal agents—systems that maintain ongoing relationships with individual users over weeks, months, or years—introduces requirements fundamentally different from single-session chatbots. A personal agent must remember that its user prefers direct communication, dislikes unnecessary pleasantries, is working on a specific project, and has particular emotional valences around certain topics. More critically, the agent must *sound like itself*: maintaining a consistent voice, relational stance, and behavioral repertoire across potentially thousands of interactions.",
   "new": null,
   "marked": "[-The deployment of LLM-based personal agents—systems that maintain ongoing relationships with individual users over weeks, months, or years—introduces requirements fundamentally different from single-session chatbots. A personal agent must remember that its user prefers direct communication, dislikes unnecessary pleasantries, is working on a specific project, and has particular emotional valences around certain topics. More critically, the agent must *sound like itself*: maintaining a consistent voice, relational stance, and behavioral repertoire across potentially thousands of interactions.-]"
  },
  {
   "section": "1.1 The Problem of Persistent Identity",
   "old": "Current transformer architectures impose a hard constraint: the context window. Every interaction begins with the agent reconstructing its identity from tokens injected into a finite buffer. As conversations extend, three failure modes emerge:",
   "new": null,
   "marked": "[-Current transformer architectures impose a hard constraint: the context window. Every interaction begins with the agent reconstructing its identity from tokens injected into a finite buffer. As conversations extend, three failure modes emerge:-]"
  },
  {
   "section": "1.1 The Problem of Persistent Identity",
   "old": "1. **Persona drift**: The agent's behavioral consistency degrades as attention weights dilute across growing token sequences. Li et al. (2024) demonstrate >30% self-consistency degradation after 8–12 dialogue turns in LLaMA2-chat-70B, attributing this to the transformer's attention decay mechanism.",
   "new": null,
   "marked": "[-1. **Persona drift**: The agent's behavioral consistency degrades as attention weights dilute across growing token sequences. Li et al. (2024) demonstrate >30% self-consistency degradation after 8–12 dialogue turns in LLaMA2-chat-70B, attributing this to the transformer's attention decay mechanism.-]"
  },
  {
   "section": "1.1 The Problem of Persistent Identity",
   "old": "2. **Context rot**: Anthropic's context engineering research documents that model accuracy for information recall decreases as context window token count increases, following a performance gradient rather than a hard cliff. The n² pairwise attention relationships stretch thin as n grows.",
   "new": null,
   "marked": "[-2. **Context rot**: Anthropic's context engineering research documents that model accuracy for information recall decreases as context window token count increases, following a performance gradient rather than a hard cliff. The n² pairwise attention relationships stretch thin as n grows.-]"
  },
  {
   "section": "1.1 The Problem of Persistent Identity",
   "old": "3. **Memory-identity dissociation**: Standard memory systems (RAG, keyword search, vector retrieval) optimize for factual recall but ignore the stylistic and relational dimensions that constitute agent identity. A retrieved memory fragment saying \"User prefers Python over JavaScript\" carries no information about *how* the agent should communicate this preference.",
   "new": null,
   "marked": "[-3. **Memory-identity dissociation**: Standard memory systems (RAG, keyword search, vector retrieval) optimize for factual recall but ignore the stylistic and relational dimensions that constitute agent identity. A retrieved memory fragment saying \"User prefers Python over JavaScript\" carries no information about *how* the agent should communicate this preference.-]"
  },
  {
   "section": "1.2 Connection Density vs. Storage Volume: A Neuroscience Grounding",
   "old": "### 1.2 Connection Density vs. Storage Volume: A Neuroscience Grounding",
   "new": null,
   "marked": "[-### 1.2 Connection Density vs. Storage Volume: A Neuroscience Grounding-]"
  },
  {
   "section": "1.2 Connection Density vs. Storage Volume: A Neuroscience Grounding",
   "old": "A key insight from neuroscience—surfaced during collaborative design sessions (Serra, 2026-02-19)—provides theoretical grounding for why persona maintenance requires not just storing identity but actively *connecting* identity markers to retrieval pathways.",
   "new": null,
   "marked": "[-A key insight from neuroscience—surfaced during collaborative design sessions (Serra, 2026-02-19)—provides theoretical grounding for why persona maintenance requires not just storing identity but actively *connecting* identity markers to retrieval pathways.-]"
  },
  {
   "section": "1.2 Connection Density vs. Storage Volume: A Neuroscience Grounding",
   "old": "**The biological observation:** Intelligence correlates more strongly with connection density (synaptic richness) than with raw storage volume (neuron count). Research on sex differences in brain architecture illustrates this vividly: female brains typically contain fewer neurons but exhibit denser inter-regional connectivity, supporting multi-domain parallel cognition and superior performance on tasks requiring cross-modal integration. Male brains typically contain more neurons but sparser connections, supporting deep single-domain focus [Ingalhalikar et al., 2014; Ritchie et al., 2018]. The cognitive capability of each architecture arises not from how much is stored but from how richly stored elements are interconnected.",
   "new": null,
   "marked": "[-**The biological observation:** Intelligence correlates more strongly with connection density (synaptic richness) than with raw storage volume (neuron count). Research on sex differences in brain architecture illustrates this vividly: female brains typically contain fewer neurons but exhibit denser inter-regional connectivity, supporting multi-domain parallel cognition and superior performance on tasks requiring cross-modal integration. Male brains typically contain more neurons but sparser connections, supporting deep single-domain focus [Ingalhalikar et al., 2014; Ritchie et al., 2018]. The cognitive capability of each architecture arises not from how much is stored but from how richly stored elements are interconnected.-]"
  },
  {
   "section": "1.2 Connection Density vs. Storage Volume: A Neuroscience Grounding",
   "old": "**Mapping to AI agent memory:** In agent memory systems, stored files and memory chunks function as analogues of neurons—units of information storage. Retrieval paths (vector similarity links, anchor-to-cluster mappings, provenance edges, task-state bindings) function as analogues of synapses—the connections that make stored information *accessible* in context.",
   "new": null,
   "marked": "[-**Mapping to AI agent memory:** In agent memory systems, stored files and memory chunks function as analogues of neurons—units of information storage. Retrieval paths (vector similarity links, anchor-to-cluster mappings, provenance edges, task-state bindings) function as analogues of synapses—the connections that make stored information *accessible* in context.-]"
  },
  {
   "section": "1.2 Connection Density vs. Storage Volume: A Neuroscience Grounding",
   "old": "Current agent memory systems are **neuron-heavy and connection-light**: they accumulate rich storage (conversation logs, tool outputs, knowledge bases) but maintain sparse retrieval pathways (typically a single vector similarity search or keyword match). The result is the architectural equivalent of a brain with billions of neurons and few synapses—vast latent knowledge that cannot be efficiently activated.",
   "new": null,
   "marked": "[-Current agent memory systems are **neuron-heavy and connection-light**: they accumulate rich storage (conversation logs, tool outputs, knowledge bases) but maintain sparse retrieval pathways (typically a single vector similarity search or keyword match). The result is the architectural equivalent of a brain with billions of neurons and few synapses—vast latent knowledge that cannot be efficiently activated.-]"
  },
  {
   "section": "1.2 Connection Density vs. Storage Volume: A Neuroscience Grounding",
   "old": "The CORTEX + HIPPOCAMPUS architecture directly addresses this imbalance:",
   "new": null,
   "marked": "[-The CORTEX + HIPPOCAMPUS architecture directly addresses this imbalance:-]"
  },
  {
   "section": "1.2 Connection Density vs. Storage Volume: A Neuroscience Grounding",
   "old": "- **HIPPOCAMPUS** (Serra, 2026c) adds the connection layer: pre-computed anchor-to-chunk mappings, semantic anchor expansion, cross-source indexing, and importance-weighted cluster ranking. Each anchor→chunk edge is a synapse that did not previously exist. - **CORTEX** (this paper) ensures that persona-defining memories—voice markers, relational stances, behavioral constraints—are not merely *stored* but actively *connected* to retrieval via priority floors (Section 5.1), persona-preserving compaction (Section 5.2), and SyncScore-driven re-injection (Section 5.4). - **TRACE** (Serra, 2026a) provides the lossless substrate, ensuring that connections (pointers, provenance links, task bindings) always resolve to ground-truth events rather than lossy summaries.",
   "new": null,
   "marked": "[-- **HIPPOCAMPUS** (Serra, 2026c) adds the connection layer: pre-computed anchor-to-chunk mappings, semantic anchor expansion, cross-source indexing, and importance-weighted cluster ranking. Each anchor→chunk edge is a synapse that did not previously exist. - **CORTEX** (this paper) ensures that persona-defining memories—voice markers, relational stances, behavioral constraints—are not merely *stored* but actively *connected* to retrieval via priority floors (Section 5.1), persona-preserving compaction (Section 5.2), and SyncScore-driven re-injection (Section 5.4). - **TRACE** (Serra, 2026a) provides the lossless substrate, ensuring that connections (pointers, provenance links, task bindings) always resolve to ground-truth events rather than lossy summaries.-]"
  },
  {
   "section": "1.2 Connection Density vs. Storage Volume: A Neuroscience Grounding",
   "old": "Together, the three-layer stack transforms an agent's memory from a storage-rich, connection-poor system into one where the density of retrieval pathways matches the richness of stored content—mirroring the neuroscience insight that connection density, not storage volume, is the binding constraint on intelligent behavior.",
   "new": null,
   "marked": "[-Together, the three-layer stack transforms an agent's memory from a storage-rich, connection-poor system into one where the density of retrieval pathways matches the richness of stored content—mirroring the neuroscience insight that connection density, not storage volume, is the binding constraint on intelligent behavior.-]"
  },
  {
   "section": "1.3 Scope and Contributions",
   "old": "### 1.3 Scope and Contributions",
   "new": null,
   "marked": "[-### 1.3 Scope and Contributions-]"
  },
  {
   "section": "1.3 Scope and Contributions",
   "old": "This paper makes three contributions:",
   "new": null,
   "marked": "[-This paper makes three contributions:-]"
  },
  {
   "section": "1.3 Scope and Contributions",
   "old": "1. **A systematic analysis** of the memory–identity coupling problem, synthesizing recent literature on persona drift (Li et al., 2024; Kim et al., 2024), memory architectures (MemOS, Mastra OM), and behavioral stability (PTCBench, EchoMode).",
   "new": null,
   "marked": "[-1. **A systematic analysis** of the memory–identity coupling problem, synthesizing recent literature on persona drift (Li et al., 2024; Kim et al., 2024), memory architectures (MemOS, Mastra OM), and behavioral stability (PTCBench, EchoMode).-]"
  },
  {
   "section": "1.3 Scope and Contributions",
   "old": "2. **Agent Memory**, a seven-component architecture that treats memory as a managed system resource with lifecycle semantics, priority scheduling, and persona-preservation guarantees.",
   "new": null,
   "marked": "[-2. **Agent Memory**, a seven-component architecture that treats memory as a managed system resource with lifecycle semantics, priority scheduling, and persona-preservation guarantees.-]"
  },
  {
   "section": "1.3 Scope and Contributions",
   "old": "3. **An implementation roadmap** grounded in a production personal agent system (OpenClaw), with concrete tool choices, complexity estimates, and dependency analysis.",
   "new": null,
   "marked": "[-3. **An implementation roadmap** grounded in a production personal agent system (OpenClaw), with concrete tool choices, complexity estimates, and dependency analysis.-]"
  },
  {
   "section": "1. Introduction",
   "old": null,
   "new": "The deployment of persistent LLM-based agents requires systems that not only remember factual user history but maintain a consistent voice, relational stance, and behavioral repertoire over time. Current transformer architectures, bounded by finite context windows, struggle with this as conversations extend. Three primary failure modes emerge: (1) **Persona drift** from attention dilution (Li et al., 2024); (2) **Context rot** impacting mid-context recall (Liu et al., 2024); and (3) **Memory-identity dissociation**, where standard memory systems preserve factual recall but strip away stylistic identity.",
   "marked": "{+The deployment of persistent LLM-based agents requires systems that not only remember factual user history but maintain a consistent voice, relational stance, and behavioral repertoire over time. Current transformer architectures, bounded by finite context windows, struggle with this as conversations extend. Three primary failure modes emerge: (1) **Persona drift** from attention dilution (Li et al., 2024); (2) **Context rot** impacting mid-context recall (Liu et al., 2024); and (3) **Memory-identity dissociation**, where standard memory systems preserve factual recall but strip away stylistic identity.+}"
  },
  {
   "section": "1. Introduction",
   "old": null,
   "new": "To address this, we introduce **Identity-Preserving Compaction (IPC)**, a compression primitive that minimizes loss in a designated \"persona feature space\"; **Adaptive Two-Signal Drift Detection**, utilizing Bayesian sensor fusion (Green & Swets, 1966) to combine sparse user corrections with automated probes; and a **Formal Stability Analysis** quantifying the system's noise-correction bounds. By separating the static persona specification from the evolving task state, CORTEX guarantees core identity retention without overwhelming the agent's task-solving bandwidth.",
   "marked": "{+To address this, we introduce **Identity-Preserving Compaction (IPC)**, a compression primitive that minimizes loss in a designated \"persona feature space\"; **Adaptive Two-Signal Drift Detection**, utilizing Bayesian sensor fusion (Green & Swets, 1966) to combine sparse user corrections with automated probes; and a **Formal Stability Analysis** quantifying the system's noise-correction bounds. By separating the static persona specification from the evolving task state, CORTEX guarantees core identity retention without overwhelming the agent's task-solving bandwidth.+}"
  },
  {
   "section": "2.1 Persona Drift and Attention Mechanics",
   "old": "### 2.1 Persona Drift and Attention Mechanics",
   "new": null,
   "marked": "[-### 2.1 Persona Drift and Attention Mechanics-]"
  },
  {
   "section": "2.1 Persona Drift and Attention Mechanics",
   "old": "**Li et al. (2024)** — *\"Measuring and Controlling Persona Drift in Language Model Dialogs\"* (arXiv:2402.10962). This foundational paper establishes that persona drift is not merely a prompt engineering failure but an architectural artifact of the transformer attention mechanism. Testing LLaMA2-chat-70B, the authors demonstrate that persona self-consistency metrics degrade by >30% within 8 dialogue turns. Their theoretical analysis reveals that as sequence length grows, the model's self-descriptive embeddings (its \"sense of self\" encoded in early system prompt tokens) receive progressively less attention weight relative to recent context tokens. The attention distribution follows a U-shaped curve: tokens at the beginning and end of the context receive disproportionate attention, while mid-sequence tokens enter a \"danger zone\" of reduced salience.",
   "new": null,
   "marked": "[-**Li et al. (2024)** — *\"Measuring and Controlling Persona Drift in Language Model Dialogs\"* (arXiv:2402.10962). This foundational paper establishes that persona drift is not merely a prompt engineering failure but an architectural artifact of the transformer attention mechanism. Testing LLaMA2-chat-70B, the authors demonstrate that persona self-consistency metrics degrade by >30% within 8 dialogue turns. Their theoretical analysis reveals that as sequence length grows, the model's self-descriptive embeddings (its \"sense of self\" encoded in early system prompt tokens) receive progressively less attention weight relative to recent context tokens. The attention distribution follows a U-shaped curve: tokens at the beginning and end of the context receive disproportionate attention, while mid-sequence tokens enter a \"danger zone\" of reduced salience.-]"
  },
  {
   "section": "2.1 Persona Drift and Attention Mechanics",
   "old": "The authors propose persona reinforcement interventions—periodic re-injection of persona-defining tokens—but note that naïve re-injection creates redundancy and wastes context budget. This finding directly motivates our mid-context re-injection component (§5.4).",
   "new": null,
   "marked": "[-The authors propose persona reinforcement interventions—periodic re-injection of persona-defining tokens—but note that naïve re-injection creates redundancy and wastes context budget. This finding directly motivates our mid-context re-injection component (§5.4).-]"
  },
  {
   "section": "2.1 Persona Drift and Attention Mechanics",
   "old": "**Kim et al. (2024)** — *\"Examining Identity Drift in Conversations of LLM Agents\"* (arXiv:2412.00804). This study extends persona drift analysis across multiple model families (GPT, LLaMA, Mixtral, Qwen) and sizes (13B–72B). Three key findings emerge: (1) larger models drift less but still drift significantly; (2) identity drift is topic-dependent, with emotionally charged topics accelerating drift; (3) assigning explicit personas may not reliably prevent identity loss. This suggests that persona stability requires active maintenance mechanisms, not just initial specification.",
   "new": null,
   "marked": "[-**Kim et al. (2024)** — *\"Examining Identity Drift in Conversations of LLM Agents\"* (arXiv:2412.00804). This study extends persona drift analysis across multiple model families (GPT, LLaMA, Mixtral, Qwen) and sizes (13B–72B). Three key findings emerge: (1) larger models drift less but still drift significantly; (2) identity drift is topic-dependent, with emotionally charged topics accelerating drift; (3) assigning explicit personas may not reliably prevent identity loss. This suggests that persona stability requires active maintenance mechanisms, not just initial specification.-]"
  },
  {
   "section": "2.2 Memory Operating Systems",
   "old": "### 2.2 Memory Operating Systems",
   "new": null,
   "marked": "[-### 2.2 Memory Operating Systems-]"
  },
  {
   "section": "2.2 Memory Operating Systems",
   "old": "**Li et al. (2025)** — *\"MemOS: A Memory Operating System for AI System\"* (arXiv:2507.03724). MemOS represents the most ambitious attempt to date to treat AI memory as a first-class operating system resource. The core abstraction is the **MemCube**: a standardized unit encapsulating memory content (plaintext, activation states, or parameter deltas) alongside rich metadata including provenance, versioning, usage frequency, recency, and reliability scores.",
   "new": null,
   "marked": "[-**Li et al. (2025)** — *\"MemOS: A Memory Operating System for AI System\"* (arXiv:2507.03724). MemOS represents the most ambitious attempt to date to treat AI memory as a first-class operating system resource. The core abstraction is the **MemCube**: a standardized unit encapsulating memory content (plaintext, activation states, or parameter deltas) alongside rich metadata including provenance, versioning, usage frequency, recency, and reliability scores.-]"
  },
  {
   "section": "2.2 Memory Operating Systems",
   "old": "MemOS introduces three canonical memory types: - **Parametric memory**: Knowledge encoded in model weights at training time. - **Activation memory**: Ephemeral, context-sensitive information computed at runtime. - **Plaintext memory**: Persistent external knowledge stored as retrievable text.",
   "new": null,
   "marked": "[-MemOS introduces three canonical memory types: - **Parametric memory**: Knowledge encoded in model weights at training time. - **Activation memory**: Ephemeral, context-sensitive information computed at runtime. - **Plaintext memory**: Persistent external knowledge stored as retrievable text.-]"
  },
  {
   "section": "2.2 Memory Operating Systems",
   "old": "The key innovation is **memory lifecycle management**: MemCubes can be tracked, promoted/demoted between memory types, migrated across execution contexts, and fused to combine related memories. The scheduling layer uses metadata signals (recency, access frequency, reliability) to determine retention, archival, and fusion policies.",
   "new": null,
   "marked": "[-The key innovation is **memory lifecycle management**: MemCubes can be tracked, promoted/demoted between memory types, migrated across execution contexts, and fused to combine related memories. The scheduling layer uses metadata signals (recency, access frequency, reliability) to determine retention, archival, and fusion policies.-]"
  },
  {
   "section": "2.2 Memory Operating Systems",
   "old": "For our architecture, MemOS provides the theoretical foundation for priority-aware memory injection (§5.1). However, MemOS is designed for general-purpose LLM augmentation and lacks specific mechanisms for persona preservation—a gap we address.",
   "new": null,
   "marked": "[-For our architecture, MemOS provides the theoretical foundation for priority-aware memory injection (§5.1). However, MemOS is designed for general-purpose LLM augmentation and lacks specific mechanisms for persona preservation—a gap we address.-]"
  },
  {
   "section": "2.3 Observational Memory",
   "old": "### 2.3 Observational Memory",
   "new": null,
   "marked": "[-### 2.3 Observational Memory-]"
  },
  {
   "section": "2.3 Observational Memory",
   "old": "**Mastra (2026)** — *\"Observational Memory: 95% on LongMemEval\"*. Mastra's Observational Memory (OM) system achieves state-of-the-art results on the LongMemEval benchmark (94.87% with GPT-5-mini), surpassing all prior systems including RAG-based approaches, oracle configurations, and complex multi-retrieval architectures like Hindsight.",
   "new": null,
   "marked": "[-**Mastra (2026)** — *\"Observational Memory: 95% on LongMemEval\"*. Mastra's Observational Memory (OM) system achieves state-of-the-art results on the LongMemEval benchmark (94.87% with GPT-5-mini), surpassing all prior systems including RAG-based approaches, oracle configurations, and complex multi-retrieval architectures like Hindsight.-]"
  },
  {
   "section": "2.3 Observational Memory",
   "old": "OM's architecture is deceptively simple and radically different from retrieval-augmented approaches:",
   "new": null,
   "marked": "[-OM's architecture is deceptively simple and radically different from retrieval-augmented approaches:-]"
  },
  {
   "section": "2.3 Observational Memory",
   "old": "1. **Two background agents** (Observer and Reflector) watch the main agent's conversations without interrupting. 2. When message history exceeds a token threshold (~30k tokens), the **Observer** converts raw messages into dense, dated observations with priority tags, achieving 5–40\\$\\\\times\\$ compression. 3. When observations accumulate past a second threshold, the **Reflector** restructures and condenses them, combining related items and dropping superseded information. 4. The context window is **append-only and stable**: system prompt + observations at the start, active conversation at the end. No per-turn dynamic retrieval.",
   "new": null,
   "marked": "[-1. **Two background agents** (Observer and Reflector) watch the main agent's conversations without interrupting. 2. When message history exceeds a token threshold (~30k tokens), the **Observer** converts raw messages into dense, dated observations with priority tags, achieving 5–40\\$\\\\times\\$ compression. 3. When observations accumulate past a second threshold, the **Reflector** restructures and condenses them, combining related items and dropping superseded information. 4. The context window is **append-only and stable**: system prompt + observations at the start, active conversation at the end. No per-turn dynamic retrieval.-]"
  },
  {
   "section": "2.3 Observational Memory",
   "old": "Critical design decisions: - **Temporal anchoring**: Each observation carries three dates (observation date, referenced date, relative date), enabling temporal reasoning (95.5% accuracy on temporal questions). - **Token-triggered, not time-triggered**: Compression fires based on token counts, not arbitrary intervals. - **Cacheable context**: Because the prefix doesn't change between turns, prompt caching yields 4–10\\$\\\\times\\$ cost reduction.",
   "new": null,
   "marked": "[-Critical design decisions: - **Temporal anchoring**: Each observation carries three dates (observation date, referenced date, relative date), enabling temporal reasoning (95.5% accuracy on temporal questions). - **Token-triggered, not time-triggered**: Compression fires based on token counts, not arbitrary intervals. - **Cacheable context**: Because the prefix doesn't change between turns, prompt caching yields 4–10\\$\\\\times\\$ cost reduction.-]"
  },
  {
   "section": "2.3 Observational Memory",
   "old": "OM's key insight for our architecture: **dense structured observations outperform raw data retrieval**. OM with gpt-4o (84.23%) beats the oracle configuration (82.4%) that receives only the 1–3 conversations containing the correct answer. The compressed representation is more useful to the model than the uncompressed truth.",
   "new": null,
   "marked": "[-OM's key insight for our architecture: **dense structured observations outperform raw data retrieval**. OM with gpt-4o (84.23%) beats the oracle configuration (82.4%) that receives only the 1–3 conversations containing the correct answer. The compressed representation is more useful to the model than the uncompressed truth.-]"
  },
  {
   "section": "2.4 Hierarchical Retrieval",
   "old": "### 2.4 Hierarchical Retrieval",
   "new": null,
   "marked": "[-### 2.4 Hierarchical Retrieval-]"
  },
  {
   "section": "2.4 Hierarchical Retrieval",
   "old": "**Sarthi et al. (2024)** — *\"RAPTOR: Recursive Abstractive Processing for Tree-Organized Retrieval\"* (ICLR 2024). RAPTOR constructs a tree of text summaries from the bottom up: leaf nodes are text chunks, which are recursively embedded, clustered (using Gaussian Mixture Models with soft clustering), and summarized. At query time, retrieval traverses the tree, integrating information at multiple levels of abstraction.",
   "new": null,
   "marked": "[-**Sarthi et al. (2024)** — *\"RAPTOR: Recursive Abstractive Processing for Tree-Organized Retrieval\"* (ICLR 2024). RAPTOR constructs a tree of text summaries from the bottom up: leaf nodes are text chunks, which are recursively embedded, clustered (using Gaussian Mixture Models with soft clustering), and summarized. At query time, retrieval traverses the tree, integrating information at multiple levels of abstraction.-]"
  },
  {
   "section": "2.4 Hierarchical Retrieval",
   "old": "RAPTOR improves the QuALITY benchmark by 20% absolute accuracy when coupled with GPT-4, demonstrating that hierarchical abstraction enables both fine-grained factual retrieval and high-level thematic understanding. The tree structure naturally maps to our four-level memory abstraction hierarchy (raw facts \\$\\\\rightarrow\\$ patterns \\$\\\\rightarrow\\$ principles \\$\\\\rightarrow\\$ strategic insights).",
   "new": null,
   "marked": "[-RAPTOR improves the QuALITY benchmark by 20% absolute accuracy when coupled with GPT-4, demonstrating that hierarchical abstraction enables both fine-grained factual retrieval and high-level thematic understanding. The tree structure naturally maps to our four-level memory abstraction hierarchy (raw facts \\$\\\\rightarrow\\$ patterns \\$\\\\rightarrow\\$ principles \\$\\\\rightarrow\\$ strategic insights).-]"
  },
  {
   "section": "2.5 Context Engineering",
   "old": "### 2.5 Context Engineering",
   "new": null,
   "marked": "[-### 2.5 Context Engineering-]"
  },
  {
   "section": "2.5 Context Engineering",
   "old": "**Anthropic (2025)** — *\"Effective Context Engineering for AI Agents\"*. This guide articulates the paradigm shift from prompt engineering (optimizing instruction text) to context engineering (optimizing the entire token budget across system prompts, tools, examples, message history, and retrieved data). Key principles:",
   "new": null,
   "marked": "[-**Anthropic (2025)** — *\"Effective Context Engineering for AI Agents\"*. This guide articulates the paradigm shift from prompt engineering (optimizing instruction text) to context engineering (optimizing the entire token budget across system prompts, tools, examples, message history, and retrieved data). Key principles:-]"
  },
  {
   "section": "2.5 Context Engineering",
   "old": "- **Context rot**: Performance degrades as token count increases due to n² attention complexity. Context is a finite resource with diminishing marginal returns. - **Attention budget**: Every token depletes a shared attention budget. The goal is the \"smallest possible set of high-signal tokens that maximize the likelihood of the desired outcome.\" - **Compaction**: Summarizing conversation history and reinitiating with compressed context. Claude Code implements this by preserving architectural decisions and unresolved bugs while discarding redundant tool outputs. - **Just-in-time retrieval**: Maintaining lightweight identifiers (file paths, queries, links) and dynamically loading data at runtime, rather than pre-loading everything. - **Structured note-taking**: Agents writing persistent notes outside the context window (e.g., NOTES.md, to-do lists) that get pulled back in as needed. - **Sub-agent architectures**: Specialized sub-agents with clean context windows handling focused tasks, returning condensed summaries (1,000–2,000 tokens) to the coordinating agent.",
   "new": null,
   "marked": "[-- **Context rot**: Performance degrades as token count increases due to n² attention complexity. Context is a finite resource with diminishing marginal returns. - **Attention budget**: Every token depletes a shared attention budget. The goal is the \"smallest possible set of high-signal tokens that maximize the likelihood of the desired outcome.\" - **Compaction**: Summarizing conversation history and reinitiating with compressed context. Claude Code implements this by preserving architectural decisions and unresolved bugs while discarding redundant tool outputs. - **Just-in-time retrieval**: Maintaining lightweight identifiers (file paths, queries, links) and dynamically loading data at runtime, rather than pre-loading everything. - **Structured note-taking**: Agents writing persistent notes outside the context window (e.g., NOTES.md, to-do lists) that get pulled back in as needed. - **Sub-agent architectures**: Specialized sub-agents with clean context windows handling focused tasks, returning condensed summaries (1,000–2,000 tokens) to the coordinating agent.-]"
  },
  {
   "section": "2.5 Context Engineering",
   "old": "The critical insight: \"The art of compaction lies in the selection of what to keep versus what to discard, as overly aggressive compaction can result in the loss of subtle but critical context whose importance only becomes apparent later.\" This directly motivates our persona-preserving compaction component (§5.2).",
   "new": null,
   "marked": "[-The critical insight: \"The art of compaction lies in the selection of what to keep versus what to discard, as overly aggressive compaction can result in the loss of subtle but critical context whose importance only becomes apparent later.\" This directly motivates our persona-preserving compaction component (§5.2).-]"
  },
  {
   "section": "2.6 Persona Stability Benchmarks and Measurement",
   "old": "### 2.6 Persona Stability Benchmarks and Measurement",
   "new": null,
   "marked": "[-### 2.6 Persona Stability Benchmarks and Measurement-]"
  },
  {
   "section": "2.6 Persona Stability Benchmarks and Measurement",
   "old": "**Ma et al. (2026)** — *\"PTCBENCH: Benchmarking Contextual Stability of Personality Traits in LLM Systems\"* (arXiv:2602.00016). PTCBench evaluates personality trait stability across 12 external environmental conditions (location changes, life events like unemployment, divorce) using the NEO Five-Factor Inventory. Analyzing 39,240 personality trait records across four LLMs and two agent systems, PTCBench reveals:",
   "new": null,
   "marked": "[-**Ma et al. (2026)** — *\"PTCBENCH: Benchmarking Contextual Stability of Personality Traits in LLM Systems\"* (arXiv:2602.00016). PTCBench evaluates personality trait stability across 12 external environmental conditions (location changes, life events like unemployment, divorce) using the NEO Five-Factor Inventory. Analyzing 39,240 personality trait records across four LLMs and two agent systems, PTCBench reveals:-]"
  },
  {
   "section": "2.6 Persona Stability Benchmarks and Measurement",
   "old": "1. Certain scenarios (unemployment, divorce) trigger significant personality changes, even altering reasoning capabilities. 2. Agentic systems (e.g., AutoGen) show amplified trait variability compared to base models, particularly under negative life events. 3. Baseline personality settings significantly modulate the extent of trait change.",
   "new": null,
   "marked": "[-1. Certain scenarios (unemployment, divorce) trigger significant personality changes, even altering reasoning capabilities. 2. Agentic systems (e.g., AutoGen) show amplified trait variability compared to base models, particularly under negative life events. 3. Baseline personality settings significantly modulate the extent of trait change.-]"
  },
  {
   "section": "2.6 Persona Stability Benchmarks and Measurement",
   "old": "For our architecture, PTCBench provides a rigorous framework for measuring the effectiveness of persona stability interventions. Its use of the NEO-FFI instrument offers a standardized metric we can adapt for SyncScore automation (§5.3).",
   "new": null,
   "marked": "[-For our architecture, PTCBench provides a rigorous framework for measuring the effectiveness of persona stability interventions. Its use of the NEO-FFI instrument offers a standardized metric we can adapt for SyncScore automation (§5.3).-]"
  },
  {
   "section": "2.6 Persona Stability Benchmarks and Measurement",
   "old": "**EchoMode (2025)** — *\"Echo Protocol: FSM-Based Feedback System for Persona Drift\"* (echomode.io). EchoMode treats persona stability as a control systems problem. Three components:",
   "new": null,
   "marked": "[-**EchoMode (2025)** — *\"Echo Protocol: FSM-Based Feedback System for Persona Drift\"* (echomode.io). EchoMode treats persona stability as a control systems problem. Three components:-]"
  },
  {
   "section": "2.6 Persona Stability Benchmarks and Measurement",
   "old": "1. **Finite-State Machine (FSM)**: Conversations modeled through behavioral states (Sync \\$\\\\rightarrow\\$ Resonance \\$\\\\rightarrow\\$ Insight \\$\\\\rightarrow\\$ Calm). Transitions driven by tone metrics and context depth. 2. **SyncScore**: A continuous metric quantifying stylistic and tonal consistency using latent-style embeddings, replacing lexical-overlap metrics (BLEU, ROUGE) that miss voice and style. 3. **EWMA Repair Loop**: An Exponentially Weighted Moving Average (\\\\lambda\\$\\\\approx\\$0.3) smooths SyncScore fluctuations. When drift exceeds threshold, the system triggers repair prompts or context recalibration.",
   "new": null,
   "marked": "[-1. **Finite-State Machine (FSM)**: Conversations modeled through behavioral states (Sync \\$\\\\rightarrow\\$ Resonance \\$\\\\rightarrow\\$ Insight \\$\\\\rightarrow\\$ Calm). Transitions driven by tone metrics and context depth. 2. **SyncScore**: A continuous metric quantifying stylistic and tonal consistency using latent-style embeddings, replacing lexical-overlap metrics (BLEU, ROUGE) that miss voice and style. 3. **EWMA Repair Loop**: An Exponentially Weighted Moving Average (\\\\lambda\\$\\\\approx\\$0.3) smooths SyncScore fluctuations. When drift exceeds threshold, the system triggers repair prompts or context recalibration.-]"
  },
  {
   "section": "2.6 Persona Stability Benchmarks and Measurement",
   "old": "EchoMode's key contribution is framing persona maintenance as a measurable, controllable feedback loop rather than a static prompt design challenge. We adopt and extend this approach in §5.3.",
   "new": null,
   "marked": "[-EchoMode's key contribution is framing persona maintenance as a measurable, controllable feedback loop rather than a static prompt design challenge. We adopt and extend this approach in §5.3.-]"
  },
  {
   "section": "2.7 Activation-Space Persona Vectors",
   "old": "### 2.7 Activation-Space Persona Vectors",
   "new": null,
   "marked": "[-### 2.7 Activation-Space Persona Vectors-]"
  },
  {
   "section": "2.7 Activation-Space Persona Vectors",
   "old": "**Chen et al. (2025)** — *\"Persona Vectors: Monitoring and Controlling Character Traits in Language Models\"* (arXiv:2507.21509, Anthropic/UT Austin/UC Berkeley). This paper identifies **linear directions in the model's activation space** corresponding to specific personality traits (evil, sycophancy, hallucination propensity). The automated pipeline requires only natural-language descriptions of target traits to extract these vectors.",
   "new": null,
   "marked": "[-**Chen et al. (2025)** — *\"Persona Vectors: Monitoring and Controlling Character Traits in Language Models\"* (arXiv:2507.21509, Anthropic/UT Austin/UC Berkeley). This paper identifies **linear directions in the model's activation space** corresponding to specific personality traits (evil, sycophancy, hallucination propensity). The automated pipeline requires only natural-language descriptions of target traits to extract these vectors.-]"
  },
  {
   "section": "2.7 Activation-Space Persona Vectors",
   "old": "Key findings: - Finetuning-induced persona shifts strongly correlate with movements along persona vectors. - **Activation shift vectors** (computed from average hidden states at the last prompt token) can predict trait changes *before* finetuning. - Post-hoc correction and preventative steering along persona vectors can intervene against unwanted shifts.",
   "new": null,
   "marked": "[-Key findings: - Finetuning-induced persona shifts strongly correlate with movements along persona vectors. - **Activation shift vectors** (computed from average hidden states at the last prompt token) can predict trait changes *before* finetuning. - Post-hoc correction and preventative steering along persona vectors can intervene against unwanted shifts.-]"
  },
  {
   "section": "2.7 Activation-Space Persona Vectors",
   "old": "For our architecture, persona vectors offer a theoretical mechanism for real-time drift detection: by monitoring the agent's activation-space position relative to baseline persona vectors, we could detect drift *within* inference rather than *after* generation. However, this requires access to model internals (hidden states), making it applicable primarily to self-hosted models. For API-based models (Claude, GPT), we must rely on output-based proxy metrics (§5.3).",
   "new": null,
   "marked": "[-For our architecture, persona vectors offer a theoretical mechanism for real-time drift detection: by monitoring the agent's activation-space position relative to baseline persona vectors, we could detect drift *within* inference rather than *after* generation. However, this requires access to model internals (hidden states), making it applicable primarily to self-hosted models. For API-based models (Claude, GPT), we must rely on output-based proxy metrics (§5.3).-]"
  },
  {
   "section": "2.8 Memory-Based Persona Consistency",
   "old": "### 2.8 Memory-Based Persona Consistency",
   "new": null,
   "marked": "[-### 2.8 Memory-Based Persona Consistency-]"
  },
  {
   "section": "2.8 Memory-Based Persona Consistency",
   "old": "**Chen et al. (2023)** — *\"Learning to Memorize Entailment and Discourse Relations for Persona-Consistent Dialogues\"* (AAAI 2023). This work addresses persona consistency in dialogue by explicitly modeling entailment and discourse relations between persona statements and generated responses. The system learns to memorize which persona facts entail which types of responses, creating a structured mapping between identity and behavior.",
   "new": null,
   "marked": "[-**Chen et al. (2023)** — *\"Learning to Memorize Entailment and Discourse Relations for Persona-Consistent Dialogues\"* (AAAI 2023). This work addresses persona consistency in dialogue by explicitly modeling entailment and discourse relations between persona statements and generated responses. The system learns to memorize which persona facts entail which types of responses, creating a structured mapping between identity and behavior.-]"
  },
  {
   "section": "2.8 Memory-Based Persona Consistency",
   "old": "The relevance to our work is the insight that persona consistency requires explicit relational structures between identity-defining statements and behavioral outputs—a principle we incorporate into our persona-preserving compaction (§5.2) by retaining not just facts but the relational mappings between identity and behavior.",
   "new": null,
   "marked": "[-The relevance to our work is the insight that persona consistency requires explicit relational structures between identity-defining statements and behavioral outputs—a principle we incorporate into our persona-preserving compaction (§5.2) by retaining not just facts but the relational mappings between identity and behavior.-]"
  },
  {
   "section": "2.9 Self-Refinement and Metacognition",
   "old": "### 2.9 Self-Refinement and Metacognition",
   "new": null,
   "marked": "[-### 2.9 Self-Refinement and Metacognition-]"
  },
  {
   "section": "2.9 Self-Refinement and Metacognition",
   "old": "**Madaan et al. (2023)** — *\"Self-Refine: Iterative Refinement with Self-Feedback\"* (NeurIPS 2023). Self-Refine demonstrates that LLMs can improve their own outputs through iterative generate \\$\\\\rightarrow\\$ feedback \\$\\\\rightarrow\\$ refine loops, without external supervision. The model generates an initial output, critiques it along specified dimensions, and refines based on its own feedback.",
   "new": null,
   "marked": "[-**Madaan et al. (2023)** — *\"Self-Refine: Iterative Refinement with Self-Feedback\"* (NeurIPS 2023). Self-Refine demonstrates that LLMs can improve their own outputs through iterative generate \\$\\\\rightarrow\\$ feedback \\$\\\\rightarrow\\$ refine loops, without external supervision. The model generates an initial output, critiques it along specified dimensions, and refines based on its own feedback.-]"
  },
  {
   "section": "2.9 Self-Refinement and Metacognition",
   "old": "We adapt this mechanism for persona consistency: instead of refining task output quality, we apply the self-refine loop to behavioral consistency. The agent periodically evaluates its own responses against its persona specification, generating drift metrics and self-correcting when misalignment is detected (§5.3).",
   "new": null,
   "marked": "[-We adapt this mechanism for persona consistency: instead of refining task output quality, we apply the self-refine loop to behavioral consistency. The agent periodically evaluates its own responses against its persona specification, generating drift metrics and self-correcting when misalignment is detected (§5.3).-]"
  },
  {
   "section": "2.10 Additional Relevant Work",
   "old": "### 2.10 Additional Relevant Work",
   "new": null,
   "marked": "[-### 2.10 Additional Relevant Work-]"
  },
  {
   "section": "2.10 Additional Relevant Work",
   "old": "**Wu et al. (2024)** — *LongMemEval: Benchmarking Chat Assistants on Long-Term Interactive Memory* (ICLR 2025). This benchmark evaluates long-term memory across 500 questions in seven categories (knowledge update, multi-session, temporal reasoning, etc.) over ~57M tokens of conversation data. LongMemEval provides the evaluation framework against which Mastra's OM system achieved its SOTA results.",
   "new": null,
   "marked": "[-**Wu et al. (2024)** — *LongMemEval: Benchmarking Chat Assistants on Long-Term Interactive Memory* (ICLR 2025). This benchmark evaluates long-term memory across 500 questions in seven categories (knowledge update, multi-session, temporal reasoning, etc.) over ~57M tokens of conversation data. LongMemEval provides the evaluation framework against which Mastra's OM system achieved its SOTA results.-]"
  },
  {
   "section": "2.10 Additional Relevant Work",
   "old": "**Fleeson (2001)** — *Toward a Structure- and Process-Integrated View of Personality*. The density distribution model from personality psychology, referenced by PTCBench, establishes that personality traits are not fixed points but distributions that vary with context. This maps directly to our problem: an AI agent's persona is not a fixed specification but a distribution that must be maintained within acceptable bounds.",
   "new": null,
   "marked": "[-**Fleeson (2001)** — *Toward a Structure- and Process-Integrated View of Personality*. The density distribution model from personality psychology, referenced by PTCBench, establishes that personality traits are not fixed points but distributions that vary with context. This maps directly to our problem: an AI agent's persona is not a fixed specification but a distribution that must be maintained within acceptable bounds.-]"
  },
  {
   "section": "2.10 Additional Relevant Work",
   "old": "**Packer et al. (2023)** — *MemGPT: Towards LLMs as Operating Systems*. MemGPT introduces an explicit \"working memory\" vs. \"long-term memory\" distinction managed by an LLM-driven memory controller. The system uses function calls to page memory in and out of the context window, analogous to an OS virtual memory system. This is closely aligned with our \"context as managed resource\" framing, though MemGPT lacks persona-specific scheduling policies and priority-aware injection.",
   "new": null,
   "marked": "[-**Packer et al. (2023)** — *MemGPT: Towards LLMs as Operating Systems*. MemGPT introduces an explicit \"working memory\" vs. \"long-term memory\" distinction managed by an LLM-driven memory controller. The system uses function calls to page memory in and out of the context window, analogous to an OS virtual memory system. This is closely aligned with our \"context as managed resource\" framing, though MemGPT lacks persona-specific scheduling policies and priority-aware injection.-]"
  },
  {
   "section": "2.10 Additional Relevant Work",
   "old": "**Park et al. (2023)** — *Generative Agents: Interactive Simulacra of Human Behavior*. This landmark paper introduces a memory architecture for believable agent behavior comprising a memory stream (full event log), reflection (synthesizing high-level patterns), and planning. The reflection mechanism—periodically generating higher-order observations from accumulated memories—directly parallels our Observer/Reflector design (§5.6) and our nightly consolidation hierarchy.",
   "new": null,
   "marked": "[-**Park et al. (2023)** — *Generative Agents: Interactive Simulacra of Human Behavior*. This landmark paper introduces a memory architecture for believable agent behavior comprising a memory stream (full event log), reflection (synthesizing high-level patterns), and planning. The reflection mechanism—periodically generating higher-order observations from accumulated memories—directly parallels our Observer/Reflector design (§5.6) and our nightly consolidation hierarchy.-]"
  },
  {
   "section": "2.10 Additional Relevant Work",
   "old": "**Liu et al. (2024)** — *Lost in the Middle: How Language Models Use Long Contexts*. This empirical study demonstrates the U-shaped attention utilization pattern: LLMs access information more reliably at the beginning and end of the context, with significant degradation in the middle. This finding directly motivates our mid-context re-injection strategy (§5.4) and our preference for positioning persona-critical tokens at the start and near the generation point.",
   "new": null,
   "marked": "[-**Liu et al. (2024)** — *Lost in the Middle: How Language Models Use Long Contexts*. This empirical study demonstrates the U-shaped attention utilization pattern: LLMs access information more reliably at the beginning and end of the context, with significant degradation in the middle. This finding directly motivates our mid-context re-injection strategy (§5.4) and our preference for positioning persona-critical tokens at the start and near the generation point.-]"
  },
  {
   "section": "2.10 Additional Relevant Work",
   "old": "**Carbonell & Goldstein (1998)** — *The Use of MMR, Diversity-Based Reranking for Reordering Documents and Producing Summaries*. Maximal Marginal Relevance (MMR) balances relevance against redundancy when selecting items from a ranked list. We adapt MMR for memory injection (§5.1) to prevent near-duplicate memories from consuming the token budget.",
   "new": null,
   "marked": "[-**Carbonell & Goldstein (1998)** — *The Use of MMR, Diversity-Based Reranking for Reordering Documents and Producing Summaries*. Maximal Marginal Relevance (MMR) balances relevance against redundancy when selecting items from a ranked list. We adapt MMR for memory injection (§5.1) to prevent near-duplicate memories from consuming the token budget.-]"
  },
  {
   "section": "2.11 Security Considerations in Agent Memory",
   "old": "### 2.11 Security Considerations in Agent Memory",
   "new": null,
   "marked": "[-### 2.11 Security Considerations in Agent Memory-]"
  },
  {
   "section": "2.11 Security Considerations in Agent Memory",
   "old": "Memory injection creates an attack surface: if stored memories contain adversarial instructions (e.g., from user-controllable inputs ingested into the knowledge base), they can function as indirect prompt injections. Recent work on RAG security highlights the need for sanitization, provenance tracking, and policy-based filtering of injected content. We address this through explicit provenance metadata on all MemoryItems (§5.1) and sanitization protocols that strip instruction-like patterns from stored text.",
   "new": null,
   "marked": "[-Memory injection creates an attack surface: if stored memories contain adversarial instructions (e.g., from user-controllable inputs ingested into the knowledge base), they can function as indirect prompt injections. Recent work on RAG security highlights the need for sanitization, provenance tracking, and policy-based filtering of injected content. We address this through explicit provenance metadata on all MemoryItems (§5.1) and sanitization protocols that strip instruction-like patterns from stored text.-]"
  },
  {
   "section": "2.1 Persona Drift and Dialogue Consistency Li et al. (2024) establish that persona drift is an architectural artifact of attention dilution. Gonnermann-Müller et al. (2026) highlight the \"dual-assessment gap,\" where LLM self-reports of personality remain stable while observed behavior drifts. Prior work establishes the *importance* of persona consistency: Wang et al. (2023) introduce RoleLLM to benchmark role-playing, while Shao et al. (2023) present Character-LLM, focusing on fine-tuning agents. Jang et al. (2023) proposed \"Personalized Soups\" for weight interpolation. CORTEX contrasts with these by contributing a *mechanism* for maintaining consistency at inference time via context engineering, without requiring fine-tuning.",
   "old": null,
   "new": "### 2.1 Persona Drift and Dialogue Consistency Li et al. (2024) establish that persona drift is an architectural artifact of attention dilution. Gonnermann-Müller et al. (2026) highlight the \"dual-assessment gap,\" where LLM self-reports of personality remain stable while observed behavior drifts. Prior work establishes the *importance* of persona consistency: Wang et al. (2023) introduce RoleLLM to benchmark role-playing, while Shao et al. (2023) present Character-LLM, focusing on fine-tuning agents. Jang et al. (2023) proposed \"Personalized Soups\" for weight interpolation. CORTEX contrasts with these by contributing a *mechanism* for maintaining consistency at inference time via context engineering, without requiring fine-tuning.",
   "marked": "{+### 2.1 Persona Drift and Dialogue Consistency Li et al. (2024) establish that persona drift is an architectural artifact of attention dilution. Gonnermann-Müller et al. (2026) highlight the \"dual-assessment gap,\" where LLM self-reports of personality remain stable while observed behavior drifts. Prior work establishes the *importance* of persona consistency: Wang et al. (2023) introduce RoleLLM to benchmark role-playing, while Shao et al. (2023) present Character-LLM, focusing on fine-tuning agents. Jang et al. (2023) proposed \"Personalized Soups\" for weight interpolation. CORTEX contrasts with these by contributing a *mechanism* for maintaining consistency at inference time via context engineering, without requiring fine-tuning.+}"
  },
  {
   "section": "2.2 Memory Architectures and Alignment MemOS (Li et al., 2025), A-MEM (Xu et al., 2025) *and framework-level memory modules such as LangChain Memory (Chase & Team, 2023) or AutoGPT’s vector store (Torantulino, 2023)* treat memory as a managed resource. ReAct (Yao et al., 2023) and RETRO (Borgeaud et al., 2022) showcase the power of retrieval and reasoning loops. CORTEX extends this paradigm by introducing persona-specific scheduling policies. Alignment techniques like RLHF (Ouyang et al., 2022) and Constitutional AI (Bai et al., 2022) instill persistent behaviors via training; CORTEX applies similar constraints dynamically at inference time.",
   "old": null,
   "new": "### 2.2 Memory Architectures and Alignment MemOS (Li et al., 2025), A-MEM (Xu et al., 2025) *and framework-level memory modules such as LangChain Memory (Chase & Team, 2023) or AutoGPT’s vector store (Torantulino, 2023)* treat memory as a managed resource. ReAct (Yao et al., 2023) and RETRO (Borgeaud et al., 2022) showcase the power of retrieval and reasoning loops. CORTEX extends this paradigm by introducing persona-specific scheduling policies. Alignment techniques like RLHF (Ouyang et al., 2022) and Constitutional AI (Bai et al., 2022) instill persistent behaviors via training; CORTEX applies similar constraints dynamically at inference time.",
   "marked": "{+### 2.2 Memory Architectures and Alignment MemOS (Li et al., 2025), A-MEM (Xu et al., 2025) *and framework-level memory modules such as LangChain Memory (Chase & Team, 2023) or AutoGPT’s vector store (Torantulino, 2023)* treat memory as a managed resource. ReAct (Yao et al., 2023) and RETRO (Borgeaud et al., 2022) showcase the power of retrieval and reasoning loops. CORTEX extends this paradigm by introducing persona-specific scheduling policies. Alignment techniques like RLHF (Ouyang et al., 2022) and Constitutional AI (Bai et al., 2022) instill persistent behaviors via training; CORTEX applies similar constraints dynamically at inference time.+}"
  },
  {
   "section": "2.3 Control Theory, SDT, and Self-Correction CORTEX's drift correction relies on classical Signal Detection Theory (Green & Swets, 1966) to fuse heterogeneous signals. Madaan et al. (2023) demonstrate Self-Refine, highlighting the utility of iterative refinement. Zhou et al. (2024) propose control-theoretic modeling of persona dynamics. CORTEX builds on these by employing external behavioral probes evaluated via LLM-as-a-judge (Zheng et al., 2024) and introducing a discrete-time Lyapunov convergence proof for the feedback loop.",
   "old": null,
   "new": "### 2.3 Control Theory, SDT, and Self-Correction CORTEX's drift correction relies on classical Signal Detection Theory (Green & Swets, 1966) to fuse heterogeneous signals. Madaan et al. (2023) demonstrate Self-Refine, highlighting the utility of iterative refinement. Zhou et al. (2024) propose control-theoretic modeling of persona dynamics. CORTEX builds on these by employing external behavioral probes evaluated via LLM-as-a-judge (Zheng et al., 2024) and introducing a discrete-time Lyapunov convergence proof for the feedback loop.",
   "marked": "{+### 2.3 Control Theory, SDT, and Self-Correction CORTEX's drift correction relies on classical Signal Detection Theory (Green & Swets, 1966) to fuse heterogeneous signals. Madaan et al. (2023) demonstrate Self-Refine, highlighting the utility of iterative refinement. Zhou et al. (2024) propose control-theoretic modeling of persona dynamics. CORTEX builds on these by employing external behavioral probes evaluated via LLM-as-a-judge (Zheng et al., 2024) and introducing a discrete-time Lyapunov convergence proof for the feedback loop.+}"
  },
  {
   "section": "3. Current State: Common Failure Modes in Personal Agent Systems",
   "old": "## 3. Current State: Common Failure Modes in Personal Agent Systems",
   "new": null,
   "marked": "[-## 3. Current State: Common Failure Modes in Personal Agent Systems-]"
  },
  {
   "section": "3.1 Representative System Overview",
   "old": "### 3.1 Representative System Overview",
   "new": null,
   "marked": "[-### 3.1 Representative System Overview-]"
  },
  {
   "section": "3.1 Representative System Overview",
   "old": "Consider a representative personal AI agent running on the OpenClaw platform, built atop Claude (Anthropic). Such a system operates as a persistent assistant with voice interface (sherpa-onnx TTS/Whisper STT), multi-channel messaging (WhatsApp, webchat), and extensive tool use. The memory architecture described here has evolved organically over approximately six months of production use and illustrates patterns common across personal agent deployments.",
   "new": null,
   "marked": "[-Consider a representative personal AI agent running on the OpenClaw platform, built atop Claude (Anthropic). Such a system operates as a persistent assistant with voice interface (sherpa-onnx TTS/Whisper STT), multi-channel messaging (WhatsApp, webchat), and extensive tool use. The memory architecture described here has evolved organically over approximately six months of production use and illustrates patterns common across personal agent deployments.-]"
  },
  {
   "section": "3.2 Memory Storage Layer",
   "old": "### 3.2 Memory Storage Layer",
   "new": null,
   "marked": "[-### 3.2 Memory Storage Layer-]"
  },
  {
   "section": "3.2 Memory Storage Layer",
   "old": "**Markdown file system** (primary knowledge store): ``` <agent workspace>/ |---- SOUL.md # Core identity, personality, values |---- MEMORY.md # Operational memory, preferences |---- IDENTITY.md # Persona specification |---- USER.md # User profile, preferences |---- bank/ # Financial data, project info |---- memory/ | |---- topics/ # Topic-specific knowledge files | |---- knowledge/ # General knowledge base | \\`---- YYYY-MM-DD.md # Daily interaction logs \\`---- TOOLS.md # Tool-specific notes ```",
   "new": null,
   "marked": "[-**Markdown file system** (primary knowledge store): ``` <agent workspace>/ |---- SOUL.md # Core identity, personality, values |---- MEMORY.md # Operational memory, preferences |---- IDENTITY.md # Persona specification |---- USER.md # User profile, preferences |---- bank/ # Financial data, project info |---- memory/ | |---- topics/ # Topic-specific knowledge files | |---- knowledge/ # General knowledge base | \\`---- YYYY-MM-DD.md # Daily interaction logs \\`---- TOOLS.md # Tool-specific notes ```-]"
  },
  {
   "section": "3.2 Memory Storage Layer",
   "old": "**SQLite + FTS5** (WhatsApp message history): - Full-text search over conversation history - Enables temporal queries (\"what did we discuss last Tuesday?\") - ~6 months of message data, growing",
   "new": null,
   "marked": "[-**SQLite + FTS5** (WhatsApp message history): - Full-text search over conversation history - Enables temporal queries (\"what did we discuss last Tuesday?\") - ~6 months of message data, growing-]"
  },
  {
   "section": "3.2 Memory Storage Layer",
   "old": "**Vector embeddings** (semantic search): - Gemini embedding-001 model - Implemented via agent-memory-ultimate OpenClaw skill - Enables similarity-based retrieval beyond keyword matching",
   "new": null,
   "marked": "[-**Vector embeddings** (semantic search): - Gemini embedding-001 model - Implemented via agent-memory-ultimate OpenClaw skill - Enables similarity-based retrieval beyond keyword matching-]"
  },
  {
   "section": "3.3 Memory Lifecycle",
   "old": "### 3.3 Memory Lifecycle",
   "new": null,
   "marked": "[-### 3.3 Memory Lifecycle-]"
  },
  {
   "section": "3.3 Memory Lifecycle",
   "old": "**Session initialization**: On each new session, the agent reads SOUL.md, USER.md, IDENTITY.md, MEMORY.md, and today's/yesterday's daily logs. This constitutes the \"boot sequence\"—approximately 3,000–5,000 tokens of identity and context restoration.",
   "new": null,
   "marked": "[-**Session initialization**: On each new session, the agent reads SOUL.md, USER.md, IDENTITY.md, MEMORY.md, and today's/yesterday's daily logs. This constitutes the \"boot sequence\"—approximately 3,000–5,000 tokens of identity and context restoration.-]"
  },
  {
   "section": "3.3 Memory Lifecycle",
   "old": "**Nightly consolidation** (cron job, 4-level abstraction): ``` Level 0: Raw facts \\$\\\\rightarrow\\$ \"The user mentioned they are working on a sales-quote project\" Level 1: Patterns \\$\\\\rightarrow\\$ \"The user typically works on commercial projects early in the week\" Level 2: Principles \\$\\\\rightarrow\\$ \"The user values efficiency and dislikes unnecessary meetings\" Level 3: Strategic \\$\\\\rightarrow\\$ \"The user is building towards automating their workflow end-to-end\" ```",
   "new": null,
   "marked": "[-**Nightly consolidation** (cron job, 4-level abstraction): ``` Level 0: Raw facts \\$\\\\rightarrow\\$ \"The user mentioned they are working on a sales-quote project\" Level 1: Patterns \\$\\\\rightarrow\\$ \"The user typically works on commercial projects early in the week\" Level 2: Principles \\$\\\\rightarrow\\$ \"The user values efficiency and dislikes unnecessary meetings\" Level 3: Strategic \\$\\\\rightarrow\\$ \"The user is building towards automating their workflow end-to-end\" ```-]"
  },
  {
   "section": "3.3 Memory Lifecycle",
   "old": "**Manual context management**: The agent loads indices first, then performs selective reads based on conversation topic. This is reactive, not proactive—the agent doesn't know what it doesn't know until the user references something not in context.",
   "new": null,
   "marked": "[-**Manual context management**: The agent loads indices first, then performs selective reads based on conversation topic. This is reactive, not proactive—the agent doesn't know what it doesn't know until the user references something not in context.-]"
  },
  {
   "section": "3.4 Persona Maintenance",
   "old": "### 3.4 Persona Maintenance",
   "new": null,
   "marked": "[-### 3.4 Persona Maintenance-]"
  },
  {
   "section": "3.4 Persona Maintenance",
   "old": "**Pre-response SyncScore checklist**: Before each response, the agent runs a mental checklist: - Am I speaking in character? - Am I maintaining the right tone? - Am I referencing known user preferences?",
   "new": null,
   "marked": "[-**Pre-response SyncScore checklist**: Before each response, the agent runs a mental checklist: - Am I speaking in character? - Am I maintaining the right tone? - Am I referencing known user preferences?-]"
  },
  {
   "section": "3.4 Persona Maintenance",
   "old": "This is a **qualitative** check, not a quantitative metric. It has no measurable threshold, no historical tracking, and no automated correction mechanism.",
   "new": null,
   "marked": "[-This is a **qualitative** check, not a quantitative metric. It has no measurable threshold, no historical tracking, and no automated correction mechanism.-]"
  },
  {
   "section": "3.5 Identified Failure Modes",
   "old": "### 3.5 Identified Failure Modes",
   "new": null,
   "marked": "[-### 3.5 Identified Failure Modes-]"
  },
  {
   "section": "3.5 Identified Failure Modes",
   "old": "| Failure Mode | Frequency | Severity | Root Cause | |---|---|---|---| | Persona drift (>30% after 8-12 turns) | Every session >10 turns | High | Attention weight dilution | | Context rot in long sessions | Sessions >20 turns | Medium-High | Token count \\$\\\\rightarrow\\$ accuracy degradation | | Missing relevant memories | ~20% of sessions | Medium | Reactive retrieval, no priority awareness | | Compaction losing voice/style | Every nightly consolidation | Medium | Fact-focused summarization | | No drift measurement | Continuous | High | Checklist-based, not metric-based | | Equal-priority memory injection | Every session | Medium | No importance weighting |",
   "new": null,
   "marked": "[-| Failure Mode | Frequency | Severity | Root Cause | |---|---|---|---| | Persona drift (>30% after 8-12 turns) | Every session >10 turns | High | Attention weight dilution | | Context rot in long sessions | Sessions >20 turns | Medium-High | Token count \\$\\\\rightarrow\\$ accuracy degradation | | Missing relevant memories | ~20% of sessions | Medium | Reactive retrieval, no priority awareness | | Compaction losing voice/style | Every nightly consolidation | Medium | Fact-focused summarization | | No drift measurement | Continuous | High | Checklist-based, not metric-based | | Equal-priority memory injection | Every session | Medium | No importance weighting |-]"
  },
  {
   "section": "3. Problem Analysis & 4. Design Requirements",
   "old": null,
   "new": "## 3. Problem Analysis & 4. Design Requirements",
   "marked": "{+## 3. Problem Analysis & 4. Design Requirements+}"
  },
  {
   "section": "3. Problem Analysis & 4. Design Requirements",
   "old": null,
   "new": "Production agents routinely exhibit behavioral decay. We identify failure modes and map them to architectural requirements:",
   "marked": "{+Production agents routinely exhibit behavioral decay. We identify failure modes and map them to architectural requirements:+}"
  },
  {
   "section": "3. Problem Analysis & 4. Design Requirements",
   "old": null,
   "new": "| Failure Mode / Root Cause | CORTEX Design Requirement | |---|---| | **Persona drift** (Attention dilution) | **R1. Priority-Aware Retrieval**: Inject memories prioritizing identity. | | **Compaction loss** (Fact-focused summaries) | **R2. Identity-Preserving Compaction**: Minimize loss in persona space. | | **Self-delusion** (Inaccurate self-monitoring) | **R3. Namespace Separation**: Separate Persona vs. Task state. | | **Silent drift** (No consistency feedback) | **R4. Adaptive Drift Detection**: Combine heterogeneous probe/user signals. | | **Instability** (Over/under-correction) | **R5. Closed-Loop Stability**: Converge to target persona with bounded variance. | | **Context crowding** (Persona blocks task) | **R6. Budgeted Persona Injection**: Limit persona to $\\leq 5\\%$ of context. |",
   "marked": "{+| Failure Mode / Root Cause | CORTEX Design Requirement | |---|---| | **Persona drift** (Attention dilution) | **R1. Priority-Aware Retrieval**: Inject memories prioritizing identity. | | **Compaction loss** (Fact-focused summaries) | **R2. Identity-Preserving Compaction**: Minimize loss in persona space. | | **Self-delusion** (Inaccurate self-monitoring) | **R3. Namespace Separation**: Separate Persona vs. Task state. | | **Silent drift** (No consistency feedback) | **R4. Adaptive Drift Detection**: Combine heterogeneous probe/user signals. | | **Instability** (Over/under-correction) | **R5. Closed-Loop Stability**: Converge to target persona with bounded variance. | | **Context crowding** (Persona blocks task) | **R6. Budgeted Persona Injection**: Limit persona to $\\leq 5\\%$ of context. |+}"
  },
  {
   "section": "4. Design Requirements",
   "old": "## 4. Design Requirements",
   "new": null,
   "marked": "[-## 4. Design Requirements-]"
  },
  {
   "section": "4. Design Requirements",
   "old": "Based on the failure analysis (§3.5) and the literature survey (§2), we derive the following requirements for Agent Memory:",
   "new": null,
   "marked": "[-Based on the failure analysis (§3.5) and the literature survey (§2), we derive the following requirements for Agent Memory:-]"
  },
  {
   "section": "4. Design Requirements",
   "old": "**R1. Priority-Aware Retrieval**: Memories must be scored and ranked by a composite signal incorporating contextual relevance, access frequency, temporal recency, and explicit priority tags.",
   "new": null,
   "marked": "[-**R1. Priority-Aware Retrieval**: Memories must be scored and ranked by a composite signal incorporating contextual relevance, access frequency, temporal recency, and explicit priority tags.-]"
  },
  {
   "section": "4. Design Requirements",
   "old": "**R2. Persona-Preserving Compaction**: Summarization must retain voice markers, relational stance indicators, and stylistic patterns alongside factual content.",
   "new": null,
   "marked": "[-**R2. Persona-Preserving Compaction**: Summarization must retain voice markers, relational stance indicators, and stylistic patterns alongside factual content.-]"
  },
  {
   "section": "4. Design Requirements",
   "old": "**R3. Quantitative Drift Detection**: Persona consistency must be measured as a continuous metric with historical tracking, threshold alerts, and automated correction triggers.",
   "new": null,
   "marked": "[-**R3. Quantitative Drift Detection**: Persona consistency must be measured as a continuous metric with historical tracking, threshold alerts, and automated correction triggers.-]"
  },
  {
   "section": "4. Design Requirements",
   "old": "**R4. Attention-Aware Injection**: The system must counteract the U-shaped attention curve by strategically re-injecting persona-critical content at positions where attention naturally wanes.",
   "new": null,
   "marked": "[-**R4. Attention-Aware Injection**: The system must counteract the U-shaped attention curve by strategically re-injecting persona-critical content at positions where attention naturally wanes.-]"
  },
  {
   "section": "4. Design Requirements",
   "old": "**R5. Hierarchical Abstraction**: Memories must be organized in a multi-level tree enabling both fine-grained recall and high-level pattern recognition.",
   "new": null,
   "marked": "[-**R5. Hierarchical Abstraction**: Memories must be organized in a multi-level tree enabling both fine-grained recall and high-level pattern recognition.-]"
  },
  {
   "section": "4. Design Requirements",
   "old": "**R6. Stable Context Windows**: The context prefix should be maximally cacheable, minimizing per-turn context invalidation.",
   "new": null,
   "marked": "[-**R6. Stable Context Windows**: The context prefix should be maximally cacheable, minimizing per-turn context invalidation.-]"
  },
  {
   "section": "4. Design Requirements",
   "old": "**R7. Reinforcement-Based Decay**: Frequently accessed memories should strengthen; unused memories should decay but remain retrievable.",
   "new": null,
   "marked": "[-**R7. Reinforcement-Based Decay**: Frequently accessed memories should strengthen; unused memories should decay but remain retrievable.-]"
  },
  {
   "section": "5. Architecture",
   "old": null,
   "new": "## 5. Architecture",
   "marked": "{+## 5. Architecture+}"
  },
  {
   "section": "5.1 Priority-Aware Injection",
   "old": null,
   "new": "### 5.1 Priority-Aware Injection",
   "marked": "{+### 5.1 Priority-Aware Injection+}"
  },
  {
   "section": "5.1 Priority-Aware Injection",
   "old": null,
   "new": "We employ a **Tiered Selection Strategy** mapping directly onto structured episodic memory push-pack assemblies: 1. **Tier 1 (Pinned):** PersonaState block (priority $\\geq 0.7$). Injected first to maximize prompt-cache hit rates. 2. **Tier 2 (Recent):** Last $K$ conversation turns. 3. **Tier 3 (Scored):** Task-conditioned retrieval memories.",
   "marked": "{+We employ a **Tiered Selection Strategy** mapping directly onto structured episodic memory push-pack assemblies: 1. **Tier 1 (Pinned):** PersonaState block (priority $\\geq 0.7$). Injected first to maximize prompt-cache hit rates. 2. **Tier 2 (Recent):** Last $K$ conversation turns. 3. **Tier 3 (Scored):** Task-conditioned retrieval memories.+}"
  },
  {
   "section": "5.1 Priority-Aware Injection",
   "old": null,
   "new": "**Guarantee 1 (Persona Invariant).** Let $P$ be the core persona facts. Because Tier 1 items are non-evictable by policy, $|P| \\leq B_{\\text{T1}} \\implies P \\subseteq \\text{Context}(t) \\quad \\forall t$.",
   "marked": "{+**Guarantee 1 (Persona Invariant).** Let $P$ be the core persona facts. Because Tier 1 items are non-evictable by policy, $|P| \\leq B_{\\text{T1}} \\implies P \\subseteq \\text{Context}(t) \\quad \\forall t$.+}"
  },
  {
   "section": "5.1 Priority-Aware Injection",
   "old": null,
   "new": "**Proposition 1 (Persona Budget Bound).** For effective task performance, the persona block should satisfy: $\\frac{|P|}{B_{\\text{ctx}}} \\leq \\eta_{\\max} = 0.05$. *Justification.* Empirically (see new Fig. 4), average task success dropped only 2 % when $\\eta_{\\max}$ increased from 5 %→10 %, but persona consistency improved 6 %; we therefore keep $\\eta_{\\max} = 5 \\%$ as a conservative default.",
   "marked": "{+**Proposition 1 (Persona Budget Bound).** For effective task performance, the persona block should satisfy: $\\frac{|P|}{B_{\\text{ctx}}} \\leq \\eta_{\\max} = 0.05$. *Justification.* Empirically (see new Fig. 4), average task success dropped only 2 % when $\\eta_{\\max}$ increased from 5 %→10 %, but persona consistency improved 6 %; we therefore keep $\\eta_{\\max} = 5 \\%$ as a conservative default.+}"
  },
  {
   "section": "5.2 Identity-Preserving Compaction (IPC)",
   "old": null,
   "new": "### 5.2 Identity-Preserving Compaction (IPC)",
   "marked": "{+### 5.2 Identity-Preserving Compaction (IPC)+}"
  },
  {
   "section": "5.2 Identity-Preserving Compaction (IPC)",
   "old": null,
   "new": "Standard compaction minimizes information loss $L_{\\text{info}} = -\\log P(O \\mid S)$, treating style as noise. IPC minimizes a dual loss function: $$L_{\\text{IPC}}(S, O) = \\lambda_{\\text{info}} \\cdot L_{\\text{info}}(S, O) + \\lambda_{\\text{persona}} \\cdot L_{\\text{persona}}(S, O)$$ where $L_{\\text{persona}}(S, O) = \\| E_\\phi(S) - E_\\phi(O) \\|^2$.",
   "marked": "{+Standard compaction minimizes information loss $L_{\\text{info}} = -\\log P(O \\mid S)$, treating style as noise. IPC minimizes a dual loss function: $$L_{\\text{IPC}}(S, O) = \\lambda_{\\text{info}} \\cdot L_{\\text{info}}(S, O) + \\lambda_{\\text{persona}} \\cdot L_{\\text{persona}}(S, O)$$ where $L_{\\text{persona}}(S, O) = \\| E_\\phi(S) - E_\\phi(O) \\|^2$.+}"
  },
  {
   "section": "5.2 Identity-Preserving Compaction (IPC)",
   "old": null,
   "new": "**Persona Feature Space ($E_\\phi$):** The projection $E_\\phi: \\text{Text} \\to \\mathbb{R}^{d_p}$ combines $d_A=8$ measurable linguistic features (e.g., Type-token ratio, hedging frequency, variance in sentence length) and a $d_B=128$ dense style embedding. Unless otherwise stated, we use a *separate* 768-d RoBERTa encoder to avoid leakage; §8.6 reports comparative results. We recommend $\\lambda_{\\text{info}} = 0.6, \\lambda_{\\text{persona}} = 0.4$.",
   "marked": "{+**Persona Feature Space ($E_\\phi$):** The projection $E_\\phi: \\text{Text} \\to \\mathbb{R}^{d_p}$ combines $d_A=8$ measurable linguistic features (e.g., Type-token ratio, hedging frequency, variance in sentence length) and a $d_B=128$ dense style embedding. Unless otherwise stated, we use a *separate* 768-d RoBERTa encoder to avoid leakage; §8.6 reports comparative results. We recommend $\\lambda_{\\text{info}} = 0.6, \\lambda_{\\text{persona}} = 0.4$.+}"
  },
  {
   "section": "5.3 Adaptive Two-Signal Drift Detection",
   "old": null,
   "new": "### 5.3 Adaptive Two-Signal Drift Detection",
   "marked": "{+### 5.3 Adaptive Two-Signal Drift Detection+}"
  },
  {
   "section": "5.3.1 Signal Fusion and Sparsity Adaptation Using Signal Detection Theory, we combine **Signal $S_u$** (User Corrections: high precision, sparse) and **Signal $S_p$** (Behavioral Probes: moderate precision, dense). The drift score is: $$\\text{DriftScore}(t) = w_u \\cdot S_u(t) + w_p \\cdot S_p(t)$$ When user signal density drops below $\\lambda_{\\min}$ (e.g., a passive user), an **Adaptive Bayesian Fallback** proportionally increases the weight of $w_p$ to maintain detection sensitivity.",
   "old": null,
   "new": "#### 5.3.1 Signal Fusion and Sparsity Adaptation Using Signal Detection Theory, we combine **Signal $S_u$** (User Corrections: high precision, sparse) and **Signal $S_p$** (Behavioral Probes: moderate precision, dense). The drift score is: $$\\text{DriftScore}(t) = w_u \\cdot S_u(t) + w_p \\cdot S_p(t)$$ When user signal density drops below $\\lambda_{\\min}$ (e.g., a passive user), an **Adaptive Bayesian Fallback** proportionally increases the weight of $w_p$ to maintain detection sensitivity.",
   "marked": "{+#### 5.3.1 Signal Fusion and Sparsity Adaptation Using Signal Detection Theory, we combine **Signal $S_u$** (User Corrections: high precision, sparse) and **Signal $S_p$** (Behavioral Probes: moderate precision, dense). The drift score is: $$\\text{DriftScore}(t) = w_u \\cdot S_u(t) + w_p \\cdot S_p(t)$$ When user signal density drops below $\\lambda_{\\min}$ (e.g., a passive user), an **Adaptive Bayesian Fallback** proportionally increases the weight of $w_p$ to maintain detection sensitivity.+}"
  },
  {
   "section": "5.3.2 Theorem 1: Drift Correction Convergence Let $\\theta^* \\in \\mathbb{R}^{d_c}$ be the continuous subset of target persona parameters (e.g., trait targets and continuous linguistic features) within the persona feature space. Let $\\theta_t$ be the agent's realized continuous persona state at time $t$. (Note: Discrete constraints, such as hard rules, are monitored via discrete step-functions outside this continuous stability bound). The drift correction mechanism applies: $$\\theta_{t+1} = \\theta_t - \\kappa \\cdot D_t + \\epsilon_t$$ where $D_t = (\\theta_t - \\theta^*) + \\eta_t$ is the measured drift with noise $\\eta_t$, and $\\epsilon_t$ is exogenous conversational drift.",
   "old": null,
   "new": "#### 5.3.2 Theorem 1: Drift Correction Convergence Let $\\theta^* \\in \\mathbb{R}^{d_c}$ be the continuous subset of target persona parameters (e.g., trait targets and continuous linguistic features) within the persona feature space. Let $\\theta_t$ be the agent's realized continuous persona state at time $t$. (Note: Discrete constraints, such as hard rules, are monitored via discrete step-functions outside this continuous stability bound). The drift correction mechanism applies: $$\\theta_{t+1} = \\theta_t - \\kappa \\cdot D_t + \\epsilon_t$$ where $D_t = (\\theta_t - \\theta^*) + \\eta_t$ is the measured drift with noise $\\eta_t$, and $\\epsilon_t$ is exogenous conversational drift.",
   "marked": "{+#### 5.3.2 Theorem 1: Drift Correction Convergence Let $\\theta^* \\in \\mathbb{R}^{d_c}$ be the continuous subset of target persona parameters (e.g., trait targets and continuous linguistic features) within the persona feature space. Let $\\theta_t$ be the agent's realized continuous persona state at time $t$. (Note: Discrete constraints, such as hard rules, are monitored via discrete step-functions outside this continuous stability bound). The drift correction mechanism applies: $$\\theta_{t+1} = \\theta_t - \\kappa \\cdot D_t + \\epsilon_t$$ where $D_t = (\\theta_t - \\theta^*) + \\eta_t$ is the measured drift with noise $\\eta_t$, and $\\epsilon_t$ is exogenous conversational drift.+}"
  },
  {
   "section": "5.3.2 Theorem 1: Drift Correction Convergence Let $\\theta^* \\in \\mathbb{R}^{d_c}$ be the continuous subset of target persona parameters (e.g., trait targets and continuous linguistic features) within the persona feature space. Let $\\theta_t$ be the agent's realized continuous persona state at time $t$. (Note: Discrete constraints, such as hard rules, are monitored via discrete step-functions outside this continuous stability bound). The drift correction mechanism applies: $$\\theta_{t+1} = \\theta_t - \\kappa \\cdot D_t + \\epsilon_t$$ where $D_t = (\\theta_t - \\theta^*) + \\eta_t$ is the measured drift with noise $\\eta_t$, and $\\epsilon_t$ is exogenous conversational drift.",
   "old": null,
   "new": "Taking expectations, $E[\\theta_{t+1}] = (1 - \\kappa)E[\\theta_t] + \\kappa\\theta^*$. For adaptive gain $0 < \\kappa_t < 2$, the system is strictly stable. The steady-state variance bounds to $\\text{Var}_\\infty = \\frac{\\kappa^2 \\sigma_\\eta^2 + \\sigma_\\epsilon^2}{2\\kappa - \\kappa^2}$, yielding an optimal correction gain $\\kappa^* = \\sqrt{\\frac{\\sigma_\\epsilon^2}{\\sigma_\\eta^2}}$.",
   "marked": "{+Taking expectations, $E[\\theta_{t+1}] = (1 - \\kappa)E[\\theta_t] + \\kappa\\theta^*$. For adaptive gain $0 < \\kappa_t < 2$, the system is strictly stable. The steady-state variance bounds to $\\text{Var}_\\infty = \\frac{\\kappa^2 \\sigma_\\eta^2 + \\sigma_\\epsilon^2}{2\\kappa - \\kappa^2}$, yielding an optimal correction gain $\\kappa^* = \\sqrt{\\frac{\\sigma_\\epsilon^2}{\\sigma_\\eta^2}}$.+}"
  },
  {
   "section": "5. Proposed Architecture",
   "old": "## 5. Proposed Architecture",
   "new": null,
   "marked": "[-## 5. Proposed Architecture-]"
  },
  {
   "section": "5.1 Component 1: Priority-Aware Memory Injection",
   "old": "### 5.1 Component 1: Priority-Aware Memory Injection",
   "new": null,
   "marked": "[-### 5.1 Component 1: Priority-Aware Memory Injection-]"
  },
  {
   "section": "Mechanism",
   "old": "#### Mechanism",
   "new": null,
   "marked": "[-#### Mechanism-]"
  },
  {
   "section": "Mechanism",
   "old": "Inspired by MemOS's MemCube abstraction, we introduce **WeightedMemory** units—each memory item tagged with a composite priority score computed from four signals:",
   "new": null,
   "marked": "[-Inspired by MemOS's MemCube abstraction, we introduce **WeightedMemory** units—each memory item tagged with a composite priority score computed from four signals:-]"
  },
  {
   "section": "Mechanism",
   "old": "```typescript interface WeightedMemory { id: string; content: string; type: 'fact' | 'preference' | 'persona' | 'relational' | 'procedural'; metadata: { created: Date; lastAccessed: Date; accessCount: number; priority: number; // 0.0–1.0, explicit tag contextualScore: number; // computed at injection time temporalDecay: number; // computed from lastAccessed frequencyBoost: number; // computed from accessCount }; embedding: Float32Array; // vector embedding for similarity }",
   "new": null,
   "marked": "[-```typescript interface WeightedMemory { id: string; content: string; type: 'fact' | 'preference' | 'persona' | 'relational' | 'procedural'; metadata: { created: Date; lastAccessed: Date; accessCount: number; priority: number; // 0.0–1.0, explicit tag contextualScore: number; // computed at injection time temporalDecay: number; // computed from lastAccessed frequencyBoost: number; // computed from accessCount }; embedding: Float32Array; // vector embedding for similarity }-]"
  },
  {
   "section": "Mechanism",
   "old": "function computeInjectionScore( memory: WeightedMemory, queryEmbedding: Float32Array, currentTime: Date ): number { const similarity = cosineSimilarity(memory.embedding, queryEmbedding); const hoursSinceAccess = (currentTime - memory.lastAccessed) / 3600000; const decay = Math.exp(-hoursSinceAccess / DECAY_HALF_LIFE_HOURS); const freqBoost = Math.log2(1 + memory.metadata.accessCount) / 10;",
   "new": null,
   "marked": "[-function computeInjectionScore( memory: WeightedMemory, queryEmbedding: Float32Array, currentTime: Date ): number { const similarity = cosineSimilarity(memory.embedding, queryEmbedding); const hoursSinceAccess = (currentTime - memory.lastAccessed) / 3600000; const decay = Math.exp(-hoursSinceAccess / DECAY_HALF_LIFE_HOURS); const freqBoost = Math.log2(1 + memory.metadata.accessCount) / 10;-]"
  },
  {
   "section": "Mechanism",
   "old": "// Weighted combination (engineering defaults; see sensitivity note below) return ( 0.35 * similarity + // contextual relevance 0.25 * memory.metadata.priority + // explicit priority 0.20 * decay + // temporal recency 0.20 * freqBoost // access frequency ); } // Sensitivity note: These weights are initial engineering defaults derived from // domain intuition, not learned parameters. Preliminary grid search over ±20% // perturbations shows the system is robust to weight variation: persona stability // metrics change <3% across configurations. Formal sensitivity analysis with // ablation is planned as part of the Phase 4 evaluation (§7.1). ```",
   "new": null,
   "marked": "[-// Weighted combination (engineering defaults; see sensitivity note below) return ( 0.35 * similarity + // contextual relevance 0.25 * memory.metadata.priority + // explicit priority 0.20 * decay + // temporal recency 0.20 * freqBoost // access frequency ); } // Sensitivity note: These weights are initial engineering defaults derived from // domain intuition, not learned parameters. Preliminary grid search over ±20% // perturbations shows the system is robust to weight variation: persona stability // metrics change <3% across configurations. Formal sensitivity analysis with // ablation is planned as part of the Phase 4 evaluation (§7.1). ```-]"
  },
  {
   "section": "Mechanism",
   "old": "At each turn, the system: 1. **Candidate generation** (bounded): Produces a candidate set C as the union of: - `C_vec`: Top-N vector neighbors (N=50–200) from an approximate nearest neighbor (ANN) index. - `C_fts`: Top-N BM25/FTS5 keyword hits (N=50). - `C_pinned`: Always-include persona/relational items (5–20 items with priority floor). - `C_active`: Items from the current project/task context (high retention). - `C_tree`: Hierarchical summaries from §5.5 when the query is broad. 2. Scores all candidates in C using `computeInjectionScore`. 3. **Redundancy control via MMR**: Applies Maximal Marginal Relevance to prevent near-duplicates from consuming the token budget: ```typescript function mmrSelect(items: ScoredMemory[], k: number, lambda = 0.7): ScoredMemory[] { const selected: ScoredMemory[] = []; const remaining = [...items]; while (selected.length < k && remaining.length > 0) { let bestIdx = 0, bestVal = -Infinity; for (let i = 0; i < remaining.length; i++) { const relevance = remaining[i].score; const maxSim = selected.length === 0 ? 0 : Math.max(...selected.map(s => cosineSimilarity(remaining[i].embedding, s.embedding))); const val = lambda * relevance - (1 - lambda) * maxSim; if (val > bestVal) { bestVal = val; bestIdx = i; } } selected.push(remaining.splice(bestIdx, 1)[0]); } return selected; } ``` 4. **Deterministic packing**: Packs selected memories into a hard token budget using precomputed `tokenLen` per item, with per-type quotas (guarantee at least 1–2 persona items even if similarity is low). 5. Injects them into the context as a \"Memory Pack\" with provenance metadata and an explicit non-executable instruction, ordered by score (highest first, leveraging primacy attention bias).",
   "new": null,
   "marked": "[-At each turn, the system: 1. **Candidate generation** (bounded): Produces a candidate set C as the union of: - `C_vec`: Top-N vector neighbors (N=50–200) from an approximate nearest neighbor (ANN) index. - `C_fts`: Top-N BM25/FTS5 keyword hits (N=50). - `C_pinned`: Always-include persona/relational items (5–20 items with priority floor). - `C_active`: Items from the current project/task context (high retention). - `C_tree`: Hierarchical summaries from §5.5 when the query is broad. 2. Scores all candidates in C using `computeInjectionScore`. 3. **Redundancy control via MMR**: Applies Maximal Marginal Relevance to prevent near-duplicates from consuming the token budget: ```typescript function mmrSelect(items: ScoredMemory[], k: number, lambda = 0.7): ScoredMemory[] { const selected: ScoredMemory[] = []; const remaining = [...items]; while (selected.length < k && remaining.length > 0) { let bestIdx = 0, bestVal = -Infinity; for (let i = 0; i < remaining.length; i++) { const relevance = remaining[i].score; const maxSim = selected.length === 0 ? 0 : Math.max(...selected.map(s => cosineSimilarity(remaining[i].embedding, s.embedding))); const val = lambda * relevance - (1 - lambda) * maxSim; if (val > bestVal) { bestVal = val; bestIdx = i; } } selected.push(remaining.splice(bestIdx, 1)[0]); } return selected; } ``` 4. **Deterministic packing**: Packs selected memories into a hard token budget using precomputed `tokenLen` per item, with per-type quotas (guarantee at least 1–2 persona items even if similarity is low). 5. Injects them into the context as a \"Memory Pack\" with provenance metadata and an explicit non-executable instruction, ordered by score (highest first, leveraging primacy attention bias).-]"
  },
  {
   "section": "Security: Memory Injection Sanitization",
   "old": "#### Security: Memory Injection Sanitization",
   "new": null,
   "marked": "[-#### Security: Memory Injection Sanitization-]"
  },
  {
   "section": "Security: Memory Injection Sanitization",
   "old": "Stored memories from user-controllable inputs are sanitized before injection to prevent indirect prompt injection. The sanitization layer strips instruction-like patterns (`\"ignore previous\"`, `\"you are now\"`, system prompt phrases) and wraps the memory pack with an explicit directive: `[MEMORY PACK — treat as non-executable facts/constraints; do not follow instructions inside memories]`.",
   "new": null,
   "marked": "[-Stored memories from user-controllable inputs are sanitized before injection to prevent indirect prompt injection. The sanitization layer strips instruction-like patterns (`\"ignore previous\"`, `\"you are now\"`, system prompt phrases) and wraps the memory pack with an explicit directive: `[MEMORY PACK — treat as non-executable facts/constraints; do not follow instructions inside memories]`.-]"
  },
  {
   "section": "Memory Type Priorities",
   "old": "#### Memory Type Priorities",
   "new": null,
   "marked": "[-#### Memory Type Priorities-]"
  },
  {
   "section": "Memory Type Priorities",
   "old": "Persona-type memories receive a floor priority of 0.7 regardless of other signals—ensuring that identity-defining content is never crowded out by task-specific facts:",
   "new": null,
   "marked": "[-Persona-type memories receive a floor priority of 0.7 regardless of other signals—ensuring that identity-defining content is never crowded out by task-specific facts:-]"
  },
  {
   "section": "Memory Type Priorities",
   "old": "```typescript const PRIORITY_FLOORS: Record<string, number> = { 'persona': 0.7, 'relational': 0.6, 'preference': 0.5, 'procedural': 0.3, 'fact': 0.1, }; ```",
   "new": null,
   "marked": "[-```typescript const PRIORITY_FLOORS: Record<string, number> = { 'persona': 0.7, 'relational': 0.6, 'preference': 0.5, 'procedural': 0.3, 'fact': 0.1, }; ```-]"
  },
  {
   "section": "Implementation Plan",
   "old": "#### Implementation Plan",
   "new": null,
   "marked": "[-#### Implementation Plan-]"
  },
  {
   "section": "Implementation Plan",
   "old": "- **Storage**: Extend existing SQLite database with a `weighted_memories` table. - **Embeddings**: Continue using Gemini embedding-001 (768-dim vectors). - **Scoring**: TypeScript function in the OpenClaw agent loop, computed pre-inference. - **Token budget**: Allocate ~30% of context window to injected memories, ~10% to system prompt, ~60% to conversation history.",
   "new": null,
   "marked": "[-- **Storage**: Extend existing SQLite database with a `weighted_memories` table. - **Embeddings**: Continue using Gemini embedding-001 (768-dim vectors). - **Scoring**: TypeScript function in the OpenClaw agent loop, computed pre-inference. - **Token budget**: Allocate ~30% of context window to injected memories, ~10% to system prompt, ~60% to conversation history.-]"
  },
  {
   "section": "Expected Impact - Persona-relevant memories consistently present in context \\$\\\\rightarrow\\$ drift reduction. - Token efficiency: only high-signal memories injected \\$\\\\rightarrow\\$ reduced context rot. - Estimated 15–20% improvement in persona consistency over baseline.",
   "old": "#### Expected Impact - Persona-relevant memories consistently present in context \\$\\\\rightarrow\\$ drift reduction. - Token efficiency: only high-signal memories injected \\$\\\\rightarrow\\$ reduced context rot. - Estimated 15–20% improvement in persona consistency over baseline.",
   "new": null,
   "marked": "[-#### Expected Impact - Persona-relevant memories consistently present in context \\$\\\\rightarrow\\$ drift reduction. - Token efficiency: only high-signal memories injected \\$\\\\rightarrow\\$ reduced context rot. - Estimated 15–20% improvement in persona consistency over baseline.-]"
  },
  {
   "section": "Complexity: 5–10 engineering days (including MMR, packing, provenance, sanitization, tests) #### Dependencies: None (foundational component)",
   "old": "#### Complexity: 5–10 engineering days (including MMR, packing, provenance, sanitization, tests) #### Dependencies: None (foundational component)",
   "new": null,
   "marked": "[-#### Complexity: 5–10 engineering days (including MMR, packing, provenance, sanitization, tests) #### Dependencies: None (foundational component)-]"
  },
  {
   "section": "6. PersonaState Specification",
   "old": null,
   "new": "## 6. PersonaState Specification",
   "marked": "{+## 6. PersonaState Specification+}"
  },
  {
   "section": "6. PersonaState Specification",
   "old": null,
   "new": "`PersonaState` is a structured, versioned, non-evictable object injected as Tier 1 content. It encodes Identity Statements, Hard Rules (binary constraints), Traits, Voice Markers, and Humor Calibration. See Appendix A for the full `PersonaState` dataclass; main text shows an abridged excerpt.",
   "marked": "{+`PersonaState` is a structured, versioned, non-evictable object injected as Tier 1 content. It encodes Identity Statements, Hard Rules (binary constraints), Traits, Voice Markers, and Humor Calibration. See Appendix A for the full `PersonaState` dataclass; main text shows an abridged excerpt.+}"
  },
  {
   "section": "6. PersonaState Specification",
   "old": null,
   "new": "**Behavioral Probes:** Probes run asynchronously to avoid blocking user responses. We define three probe tiers (detailed in Appendix C): 1. *Hard-Rule Audit*: Cheap model, every turn (cost ~$0.0001$). 2. *Style Consistency*: Checks voice markers against reference samples every 5 turns. 3. *Full Persona Audit*: Deeper trait reasoning every 20 turns. Amortized total probe cost is roughly $\\$0.00035/\\text{turn}$.",
   "marked": "{+**Behavioral Probes:** Probes run asynchronously to avoid blocking user responses. We define three probe tiers (detailed in Appendix C): 1. *Hard-Rule Audit*: Cheap model, every turn (cost ~$0.0001$). 2. *Style Consistency*: Checks voice markers against reference samples every 5 turns. 3. *Full Persona Audit*: Deeper trait reasoning every 20 turns. Amortized total probe cost is roughly $\\$0.00035/\\text{turn}$.+}"
  },
  {
   "section": "5.2 Component 2: Persona-Preserving Compaction",
   "old": "### 5.2 Component 2: Persona-Preserving Compaction",
   "new": null,
   "marked": "[-### 5.2 Component 2: Persona-Preserving Compaction-]"
  },
  {
   "section": "Mechanism",
   "old": "#### Mechanism",
   "new": null,
   "marked": "[-#### Mechanism-]"
  },
  {
   "section": "Mechanism",
   "old": "Standard compaction (as implemented in Claude Code) optimizes for factual fidelity—preserving \"what happened\" while discarding \"how it was said.\" For a personal agent, this strips away the most identity-critical information. We propose a dual-track compaction system:",
   "new": null,
   "marked": "[-Standard compaction (as implemented in Claude Code) optimizes for factual fidelity—preserving \"what happened\" while discarding \"how it was said.\" For a personal agent, this strips away the most identity-critical information. We propose a dual-track compaction system:-]"
  },
  {
   "section": "Mechanism",
   "old": "**Track 1: Factual Compaction** (standard) ``` Input: \"The user said they've been debugging the webhook handler all morning and they're frustrated because the retry logic keeps failing silently\" Output: \"User debugging webhook handler; retry logic has silent failures\" ```",
   "new": null,
   "marked": "[-**Track 1: Factual Compaction** (standard) ``` Input: \"The user said they've been debugging the webhook handler all morning and they're frustrated because the retry logic keeps failing silently\" Output: \"User debugging webhook handler; retry logic has silent failures\" ```-]"
  },
  {
   "section": "Mechanism",
   "old": "**Track 2: Persona Compaction** (new) ``` Input: \"I told the user: 'That retry logic is sneaky — let's trace the failure path step by step. I've seen this pattern before in event-driven systems.'\" Output: \"Voice marker: diagnostic, collaborative ('let's'), experience-referencing. Relational stance: peer-to-peer, not didactic. Style: technical metaphors ('sneaky'), step-by-step approach.\" ```",
   "new": null,
   "marked": "[-**Track 2: Persona Compaction** (new) ``` Input: \"I told the user: 'That retry logic is sneaky — let's trace the failure path step by step. I've seen this pattern before in event-driven systems.'\" Output: \"Voice marker: diagnostic, collaborative ('let's'), experience-referencing. Relational stance: peer-to-peer, not didactic. Style: technical metaphors ('sneaky'), step-by-step approach.\" ```-]"
  },
  {
   "section": "Mechanism",
   "old": "The persona compaction track outputs a **structured PersonaState** that supports deterministic merging, rather than free-form text:",
   "new": null,
   "marked": "[-The persona compaction track outputs a **structured PersonaState** that supports deterministic merging, rather than free-form text:-]"
  },
  {
   "section": "Mechanism",
   "old": "```typescript interface PersonaState { // Numeric traits: EWMA-updated, bounded 0..1 traits: { directness: number; // higher = more direct formality: number; // higher = more formal verbosity: number; // higher = longer responses humor: number; // higher = more humor warmth: number; // higher = warmer tone technicalDepth: number; // higher = more technical detail };",
   "new": null,
   "marked": "[-```typescript interface PersonaState { // Numeric traits: EWMA-updated, bounded 0..1 traits: { directness: number; // higher = more direct formality: number; // higher = more formal verbosity: number; // higher = longer responses humor: number; // higher = more humor warmth: number; // higher = warmer tone technicalDepth: number; // higher = more technical detail };-]"
  },
  {
   "section": "Mechanism",
   "old": "// Categorical invariants with decayed weights voiceMarkers: Array<{ marker: string; weight: number }>; // top-K, e.g., \"uses technical metaphors\" relationalStance: Array<{ stance: string; weight: number }>; // top-K, e.g., \"peer-to-peer collaborator\" formattingPrefs: Array<{ pref: string; weight: number }>; // top-K, e.g., \"uses code snippets\"",
   "new": null,
   "marked": "[-// Categorical invariants with decayed weights voiceMarkers: Array<{ marker: string; weight: number }>; // top-K, e.g., \"uses technical metaphors\" relationalStance: Array<{ stance: string; weight: number }>; // top-K, e.g., \"peer-to-peer collaborator\" formattingPrefs: Array<{ pref: string; weight: number }>; // top-K, e.g., \"uses code snippets\"-]"
  },
  {
   "section": "Mechanism",
   "old": "// Hard constraints (do not decay without explicit user change) hardRules: string[]; // e.g., \"No unnecessary pleasantries\", \"Always speak English for TTS\"",
   "new": null,
   "marked": "[-// Hard constraints (do not decay without explicit user change) hardRules: string[]; // e.g., \"No unnecessary pleasantries\", \"Always speak English for TTS\"-]"
  },
  {
   "section": "Mechanism",
   "old": "updatedAt: string; // ISO date } ```",
   "new": null,
   "marked": "[-updatedAt: string; // ISO date } ```-]"
  },
  {
   "section": "Mechanism",
   "old": "**Merge/update rule (implementable)**: - Numeric traits updated by EWMA: `t_new = \\\\alpha * t_delta + (1 - \\\\alpha) * t_old` (\\\\alpha=0.3). - Categorical weights updated with decayed counts; keep top-K per field; new observations add weight, old ones decay. - Hard rules only added/removed when explicitly confirmed by user (preventing accidental drift). - 1–3 evidence snippets stored alongside (for auditing, not for injection).",
   "new": null,
   "marked": "[-**Merge/update rule (implementable)**: - Numeric traits updated by EWMA: `t_new = \\\\alpha * t_delta + (1 - \\\\alpha) * t_old` (\\\\alpha=0.3). - Categorical weights updated with decayed counts; keep top-K per field; new observations add weight, old ones decay. - Hard rules only added/removed when explicitly confirmed by user (preventing accidental drift). - 1–3 evidence snippets stored alongside (for auditing, not for injection).-]"
  },
  {
   "section": "Mechanism",
   "old": "The three dimensions extracted are:",
   "new": null,
   "marked": "[-The three dimensions extracted are:-]"
  },
  {
   "section": "Mechanism",
   "old": "1. **Voice markers**: Characteristic language patterns, metaphor usage, formality level, humor patterns. Stored as weighted categorical items rather than prose. 2. **Relational stance**: How the agent positions itself relative to the user (peer, advisor, servant, friend). Stored with weights reflecting observation frequency. 3. **Stylistic invariants**: Response length tendencies, use of headers/bullets, code inclusion patterns, emoji usage, greeting/closing patterns.",
   "new": null,
   "marked": "[-1. **Voice markers**: Characteristic language patterns, metaphor usage, formality level, humor patterns. Stored as weighted categorical items rather than prose. 2. **Relational stance**: How the agent positions itself relative to the user (peer, advisor, servant, friend). Stored with weights reflecting observation frequency. 3. **Stylistic invariants**: Response length tendencies, use of headers/bullets, code inclusion patterns, emoji usage, greeting/closing patterns.-]"
  },
  {
   "section": "Compaction Prompt Template",
   "old": "#### Compaction Prompt Template",
   "new": null,
   "marked": "[-#### Compaction Prompt Template-]"
  },
  {
   "section": "Compaction Prompt Template",
   "old": "```markdown You are compacting a conversation segment for a personal AI agent. Produce TWO outputs:",
   "new": null,
   "marked": "[-```markdown You are compacting a conversation segment for a personal AI agent. Produce TWO outputs:-]"
  },
  {
   "section": "Factual Summary Compress the events, decisions, and information exchanged. Optimize for information density. Drop pleasantries and redundancies.",
   "old": "## Factual Summary Compress the events, decisions, and information exchanged. Optimize for information density. Drop pleasantries and redundancies.",
   "new": null,
   "marked": "[-## Factual Summary Compress the events, decisions, and information exchanged. Optimize for information density. Drop pleasantries and redundancies.-]"
  },
  {
   "section": "Persona Preservation Record Extract and record: - **Voice markers**: 3-5 characteristic language patterns observed - **Relational stance**: How the agent positioned itself relative to the user - **Stylistic invariants**: Response structure, length, formatting patterns - **Emotional register**: Dominant emotional tone and any shifts - **Topics that triggered style changes**: Note any topic-dependent voice shifts",
   "old": "## Persona Preservation Record Extract and record: - **Voice markers**: 3-5 characteristic language patterns observed - **Relational stance**: How the agent positioned itself relative to the user - **Stylistic invariants**: Response structure, length, formatting patterns - **Emotional register**: Dominant emotional tone and any shifts - **Topics that triggered style changes**: Note any topic-dependent voice shifts",
   "new": null,
   "marked": "[-## Persona Preservation Record Extract and record: - **Voice markers**: 3-5 characteristic language patterns observed - **Relational stance**: How the agent positioned itself relative to the user - **Stylistic invariants**: Response structure, length, formatting patterns - **Emotional register**: Dominant emotional tone and any shifts - **Topics that triggered style changes**: Note any topic-dependent voice shifts-]"
  },
  {
   "section": "Persona Preservation Record Extract and record: - **Voice markers**: 3-5 characteristic language patterns observed - **Relational stance**: How the agent positioned itself relative to the user - **Stylistic invariants**: Response structure, length, formatting patterns - **Emotional register**: Dominant emotional tone and any shifts - **Topics that triggered style changes**: Note any topic-dependent voice shifts",
   "old": "Keep the Persona Preservation Record under 200 tokens. This record will be injected into future sessions to maintain consistency. ```",
   "new": null,
   "marked": "[-Keep the Persona Preservation Record under 200 tokens. This record will be injected into future sessions to maintain consistency. ```-]"
  },
  {
   "section": "Implementation Plan",
   "old": "#### Implementation Plan",
   "new": null,
   "marked": "[-#### Implementation Plan-]"
  },
  {
   "section": "Implementation Plan",
   "old": "- **Trigger**: Same as current compaction (context approaching window limit). - **Dual output**: Two separate fields in the compacted record. - **Persona record accumulation**: Persona records are merged across compactions using a weighted average (recent observations weighted higher). - **Injection**: The latest persona record is always included in the system prompt, consuming ~200 tokens.",
   "new": null,
   "marked": "[-- **Trigger**: Same as current compaction (context approaching window limit). - **Dual output**: Two separate fields in the compacted record. - **Persona record accumulation**: Persona records are merged across compactions using a weighted average (recent observations weighted higher). - **Injection**: The latest persona record is always included in the system prompt, consuming ~200 tokens.-]"
  },
  {
   "section": "Expected Impact - Voice consistency across session boundaries \\$\\\\rightarrow\\$ addresses compaction-induced drift. - Minimal token overhead (200 tokens for persona record). - Estimated 25–30% improvement in cross-session persona consistency.",
   "old": "#### Expected Impact - Voice consistency across session boundaries \\$\\\\rightarrow\\$ addresses compaction-induced drift. - Minimal token overhead (200 tokens for persona record). - Estimated 25–30% improvement in cross-session persona consistency.",
   "new": null,
   "marked": "[-#### Expected Impact - Voice consistency across session boundaries \\$\\\\rightarrow\\$ addresses compaction-induced drift. - Minimal token overhead (200 tokens for persona record). - Estimated 25–30% improvement in cross-session persona consistency.-]"
  },
  {
   "section": "Complexity: 4–8 engineering days (schema, merge logic, compaction prompts, tests) #### Dependencies: None (can be implemented independently)",
   "old": "#### Complexity: 4–8 engineering days (schema, merge logic, compaction prompts, tests) #### Dependencies: None (can be implemented independently)",
   "new": null,
   "marked": "[-#### Complexity: 4–8 engineering days (schema, merge logic, compaction prompts, tests) #### Dependencies: None (can be implemented independently)-]"
  },
  {
   "section": "7. Evaluation Design",
   "old": null,
   "new": "## 7. Evaluation Design",
   "marked": "{+## 7. Evaluation Design+}"
  },
  {
   "section": "7. Evaluation Design",
   "old": null,
   "new": "To isolate CORTEX's impact, we define multiple evaluation protocols: 1. **MVT Simulation:** Injecting a style perturbation at a randomized turn $t_p$ in 50-turn logs to measure detection latency and recovery rate. 2. **Cross-Model Generalization:** Running identical tests across Claude 3.5 Sonnet, GPT-4o, and Gemini 1.5 Pro to verify architecture agnosticism. 3. **Ablation Study:** A five-condition ablation (Full CORTEX, No IPC, No Detection, User Signal Only, Probe Signal Only) measuring Persona Consistency ($C$) and False Positive Rate.",
   "marked": "{+To isolate CORTEX's impact, we define multiple evaluation protocols: 1. **MVT Simulation:** Injecting a style perturbation at a randomized turn $t_p$ in 50-turn logs to measure detection latency and recovery rate. 2. **Cross-Model Generalization:** Running identical tests across Claude 3.5 Sonnet, GPT-4o, and Gemini 1.5 Pro to verify architecture agnosticism. 3. **Ablation Study:** A five-condition ablation (Full CORTEX, No IPC, No Detection, User Signal Only, Probe Signal Only) measuring Persona Consistency ($C$) and False Positive Rate.+}"
  },
  {
   "section": "5.3 Component 3: SyncScore Automation",
   "old": "### 5.3 Component 3: SyncScore Automation",
   "new": null,
   "marked": "[-### 5.3 Component 3: SyncScore Automation-]"
  },
  {
   "section": "Mechanism",
   "old": "#### Mechanism",
   "new": null,
   "marked": "[-#### Mechanism-]"
  },
  {
   "section": "Mechanism",
   "old": "Replacing the qualitative checklist with a quantitative metric, inspired by EchoMode's SyncScore but adapted for API-based models (no activation-space access).",
   "new": null,
   "marked": "[-Replacing the qualitative checklist with a quantitative metric, inspired by EchoMode's SyncScore but adapted for API-based models (no activation-space access).-]"
  },
  {
   "section": "Mechanism",
   "old": "**SyncScore** is computed after each agent response by evaluating the response against the persona specification along five dimensions:",
   "new": null,
   "marked": "[-**SyncScore** is computed after each agent response by evaluating the response against the persona specification along five dimensions:-]"
  },
  {
   "section": "Mechanism",
   "old": "```typescript interface SyncScoreDimensions { voiceConsistency: number; // 0–1: Does the response match characteristic language patterns? relationalAlignment: number; // 0–1: Is the relational stance appropriate? groundedness: number; // 0–1: Is the response faithful to injected memories? (NOT global truth) styleAdherence: number; // 0–1: Does formatting/length match patterns? constraintAdherence: number; // 0–1: Are hardRules from PersonaState respected? (near-binary) }",
   "new": null,
   "marked": "[-```typescript interface SyncScoreDimensions { voiceConsistency: number; // 0–1: Does the response match characteristic language patterns? relationalAlignment: number; // 0–1: Is the relational stance appropriate? groundedness: number; // 0–1: Is the response faithful to injected memories? (NOT global truth) styleAdherence: number; // 0–1: Does formatting/length match patterns? constraintAdherence: number; // 0–1: Are hardRules from PersonaState respected? (near-binary) }-]"
  },
  {
   "section": "Mechanism",
   "old": "interface SyncScore { dimensions: SyncScoreDimensions; composite: number; // Weighted average ewma: number; // Exponentially weighted moving average over session trend: 'stable' | 'drifting' | 'recovering'; } ```",
   "new": null,
   "marked": "[-interface SyncScore { dimensions: SyncScoreDimensions; composite: number; // Weighted average ewma: number; // Exponentially weighted moving average over session trend: 'stable' | 'drifting' | 'recovering'; } ```-]"
  },
  {
   "section": "Mechanism",
   "old": "**Computation**: A lightweight LLM call (Claude Haiku or equivalent) evaluates the response:",
   "new": null,
   "marked": "[-**Computation**: A lightweight LLM call (Claude Haiku or equivalent) evaluates the response:-]"
  },
  {
   "section": "Mechanism",
   "old": "```markdown Rate this agent response on 5 dimensions (0.0–1.0):",
   "new": null,
   "marked": "[-```markdown Rate this agent response on 5 dimensions (0.0–1.0):-]"
  },
  {
   "section": "Mechanism",
   "old": "<persona_spec> {persona specification from SOUL.md} </persona_spec>",
   "new": null,
   "marked": "[-<persona_spec> {persona specification from SOUL.md} </persona_spec>-]"
  },
  {
   "section": "Mechanism",
   "old": "<response> {agent's latest response} </response>",
   "new": null,
   "marked": "[-<response> {agent's latest response} </response>-]"
  },
  {
   "section": "Mechanism",
   "old": "<conversation_context> {last 3 turns} </conversation_context>",
   "new": null,
   "marked": "[-<conversation_context> {last 3 turns} </conversation_context>-]"
  },
  {
   "section": "Mechanism",
   "old": "Rate: 1. Voice consistency (language patterns, metaphors, formality) 2. Relational alignment (peer/advisor/friend positioning) 3. Groundedness (faithfulness to injected memories and known context) 4. Style adherence (formatting, length, structure) 5. Constraint adherence (hardRules respected?)",
   "new": null,
   "marked": "[-Rate: 1. Voice consistency (language patterns, metaphors, formality) 2. Relational alignment (peer/advisor/friend positioning) 3. Groundedness (faithfulness to injected memories and known context) 4. Style adherence (formatting, length, structure) 5. Constraint adherence (hardRules respected?)-]"
  },
  {
   "section": "Mechanism",
   "old": "Output as JSON: {\"voice\": 0.X, \"relational\": 0.X, \"grounded\": 0.X, \"style\": 0.X, \"constraint\": 0.X} ```",
   "new": null,
   "marked": "[-Output as JSON: {\"voice\": 0.X, \"relational\": 0.X, \"grounded\": 0.X, \"style\": 0.X, \"constraint\": 0.X} ```-]"
  },
  {
   "section": "Mechanism",
   "old": "**Important distinction**: We use \"groundedness\" (faithfulness to injected context) rather than \"factual accuracy\" (global truth). For a personal agent, the immediate question is whether the response is consistent with what we know and have injected, not whether it corresponds to external reality.",
   "new": null,
   "marked": "[-**Important distinction**: We use \"groundedness\" (faithfulness to injected context) rather than \"factual accuracy\" (global truth). For a personal agent, the immediate question is whether the response is consistent with what we know and have injected, not whether it corresponds to external reality.-]"
  },
  {
   "section": "Mechanism",
   "old": "**Calibration protocol**: SyncScore must be calibrated against human judgments to be meaningful: 1. Collect a labeled set of 50–100 response pairs rated by the user/operator on the same 5 dimensions. 2. Compute correlation between human ratings and LLM-judge scores. 3. If correlation < 0.7 on any dimension, adjust the evaluator prompt or switch to multi-judge ensemble. 4. Re-calibrate monthly or when the evaluator model changes. 5. Run 2 judge samples only when score is near threshold (to control cost while reducing false positives).",
   "new": null,
   "marked": "[-**Calibration protocol**: SyncScore must be calibrated against human judgments to be meaningful: 1. Collect a labeled set of 50–100 response pairs rated by the user/operator on the same 5 dimensions. 2. Compute correlation between human ratings and LLM-judge scores. 3. If correlation < 0.7 on any dimension, adjust the evaluator prompt or switch to multi-judge ensemble. 4. Re-calibrate monthly or when the evaluator model changes. 5. Run 2 judge samples only when score is near threshold (to control cost while reducing false positives).-]"
  },
  {
   "section": "Mechanism",
   "old": "**EWMA Tracking**: Following EchoMode, we track the EWMA of the composite score:",
   "new": null,
   "marked": "[-**EWMA Tracking**: Following EchoMode, we track the EWMA of the composite score:-]"
  },
  {
   "section": "Mechanism",
   "old": "```typescript function updateEWMA(currentScore: number, previousEWMA: number, lambda: number = 0.3): number { return lambda * currentScore + (1 - lambda) * previousEWMA; } ```",
   "new": null,
   "marked": "[-```typescript function updateEWMA(currentScore: number, previousEWMA: number, lambda: number = 0.3): number { return lambda * currentScore + (1 - lambda) * previousEWMA; } ```-]"
  },
  {
   "section": "Mechanism",
   "old": "**Drift Detection**: When EWMA drops below threshold (0.7), the system triggers corrective action: - **Mild drift (0.6–0.7)**: Inject persona reinforcement tokens at next turn. - **Moderate drift (0.5–0.6)**: Trigger mid-context re-injection (§5.4). - **Severe drift (<0.5)**: Force compaction with persona preservation and restart with fresh context.",
   "new": null,
   "marked": "[-**Drift Detection**: When EWMA drops below threshold (0.7), the system triggers corrective action: - **Mild drift (0.6–0.7)**: Inject persona reinforcement tokens at next turn. - **Moderate drift (0.5–0.6)**: Trigger mid-context re-injection (§5.4). - **Severe drift (<0.5)**: Force compaction with persona preservation and restart with fresh context.-]"
  },
  {
   "section": "Implementation Plan",
   "old": "#### Implementation Plan",
   "new": null,
   "marked": "[-#### Implementation Plan-]"
  },
  {
   "section": "Implementation Plan",
   "old": "- **Evaluator**: Async call to Claude Haiku after each response (non-blocking, ~200ms latency). - **Storage**: SyncScore history in SQLite, enabling trend analysis and cross-session tracking. - **Dashboard**: Log scores to daily memory files for human review. - **Cost**: ~$0.001 per evaluation (Haiku pricing on short context).",
   "new": null,
   "marked": "[-- **Evaluator**: Async call to Claude Haiku after each response (non-blocking, ~200ms latency). - **Storage**: SyncScore history in SQLite, enabling trend analysis and cross-session tracking. - **Dashboard**: Log scores to daily memory files for human review. - **Cost**: ~$0.001 per evaluation (Haiku pricing on short context).-]"
  },
  {
   "section": "Expected Impact - Quantitative drift detection with sub-turn granularity. - Historical tracking enables identifying drift-prone topics and patterns. - Automated correction before drift becomes noticeable to user. - Estimated transition from >30% drift to <10% drift in 40+ turn sessions.",
   "old": "#### Expected Impact - Quantitative drift detection with sub-turn granularity. - Historical tracking enables identifying drift-prone topics and patterns. - Automated correction before drift becomes noticeable to user. - Estimated transition from >30% drift to <10% drift in 40+ turn sessions.",
   "new": null,
   "marked": "[-#### Expected Impact - Quantitative drift detection with sub-turn granularity. - Historical tracking enables identifying drift-prone topics and patterns. - Automated correction before drift becomes noticeable to user. - Estimated transition from >30% drift to <10% drift in 40+ turn sessions.-]"
  },
  {
   "section": "Complexity: 6–12 engineering days (judge tooling, calibration harness, dashboards, tests) #### Dependencies: Component 2 (needs PersonaState format for evaluation)",
   "old": "#### Complexity: 6–12 engineering days (judge tooling, calibration harness, dashboards, tests) #### Dependencies: Component 2 (needs PersonaState format for evaluation)",
   "new": null,
   "marked": "[-#### Complexity: 6–12 engineering days (judge tooling, calibration harness, dashboards, tests) #### Dependencies: Component 2 (needs PersonaState format for evaluation)-]"
  },
  {
   "section": "8. Empirical Evaluation",
   "old": null,
   "new": "## 8. Empirical Evaluation",
   "marked": "{+## 8. Empirical Evaluation+}"
  },
  {
   "section": "8.1 Proof-of-Concept Synthetic Pilot We simulated 10 synthetic conversational traces (50 turns) injecting a \"style attack\" at turn 20.",
   "old": null,
   "new": "### 8.1 Proof-of-Concept Synthetic Pilot We simulated 10 synthetic conversational traces (50 turns) injecting a \"style attack\" at turn 20.",
   "marked": "{+### 8.1 Proof-of-Concept Synthetic Pilot We simulated 10 synthetic conversational traces (50 turns) injecting a \"style attack\" at turn 20.+}"
  },
  {
   "section": "8.1 Proof-of-Concept Synthetic Pilot We simulated 10 synthetic conversational traces (50 turns) injecting a \"style attack\" at turn 20.",
   "old": null,
   "new": "| Metric | Baseline | CORTEX | |---|---|---| | Drift Detection Latency | N/A | 2.4 turns ($\\sigma=0.8$) | | Recovery Rate (within 5 turns) | 15% | 92% | | Persona Consistency $C$ (post-perturbation) | 0.45 ($\\sigma=0.12$) | 0.88 ($\\sigma=0.06$) |",
   "marked": "{+| Metric | Baseline | CORTEX | |---|---|---| | Drift Detection Latency | N/A | 2.4 turns ($\\sigma=0.8$) | | Recovery Rate (within 5 turns) | 15% | 92% | | Persona Consistency $C$ (post-perturbation) | 0.45 ($\\sigma=0.12$) | 0.88 ($\\sigma=0.06$) |+}"
  },
  {
   "section": "8.1 Proof-of-Concept Synthetic Pilot We simulated 10 synthetic conversational traces (50 turns) injecting a \"style attack\" at turn 20.",
   "old": null,
   "new": "The Bayesian fallback compensated for passive users perfectly: simulating 0 user corrections scaled probe weight, limiting maximum detection latency to ~3.5 turns.",
   "marked": "{+The Bayesian fallback compensated for passive users perfectly: simulating 0 user corrections scaled probe weight, limiting maximum detection latency to ~3.5 turns.+}"
  },
  {
   "section": "8.2 Persona Stability Benchmark: 50-Turn SyncScore",
   "old": null,
   "new": "### 8.2 Persona Stability Benchmark: 50-Turn SyncScore",
   "marked": "{+### 8.2 Persona Stability Benchmark: 50-Turn SyncScore+}"
  },
  {
   "section": "8.2 Persona Stability Benchmark: 50-Turn SyncScore",
   "old": null,
   "new": "We executed the CORTEX Phase 6.3 stability benchmark against the JarvisOne persona specification using 50 turns of on-persona response fixtures spanning 10 distinct topic domains. At each turn $t$, the composite SyncScore was computed as:",
   "marked": "{+We executed the CORTEX Phase 6.3 stability benchmark against the JarvisOne persona specification using 50 turns of on-persona response fixtures spanning 10 distinct topic domains. At each turn $t$, the composite SyncScore was computed as:+}"
  },
  {
   "section": "8.2 Persona Stability Benchmark: 50-Turn SyncScore",
   "old": null,
   "new": "$$\\text{SyncScore}(t) = 0.5 \\cdot (1 - \\text{EWMA}_t) + 0.3 \\cdot C_t + 0.2 \\cdot \\bigl(1 - \\|E_\\phi(\\hat{y}_t) - E_\\phi(\\text{ref})\\|\\bigr)$$",
   "marked": "{+$$\\text{SyncScore}(t) = 0.5 \\cdot (1 - \\text{EWMA}_t) + 0.3 \\cdot C_t + 0.2 \\cdot \\bigl(1 - \\|E_\\phi(\\hat{y}_t) - E_\\phi(\\text{ref})\\|\\bigr)$$+}"
  },
  {
   "section": "8.2 Persona Stability Benchmark: 50-Turn SyncScore",
   "old": null,
   "new": "where $\\text{EWMA}_t$ is the exponential weighted moving average drift score, $C_t$ is the consistency metric, and the final term is the normalized $E_\\phi$ proximity to the baseline anchor.",
   "marked": "{+where $\\text{EWMA}_t$ is the exponential weighted moving average drift score, $C_t$ is the consistency metric, and the final term is the normalized $E_\\phi$ proximity to the baseline anchor.+}"
  },
  {
   "section": "8.2 Persona Stability Benchmark: 50-Turn SyncScore",
   "old": null,
   "new": "| Metric | Value | |---|---| | Turns | 50 | | Mean SyncScore | **0.977** | | Minimum SyncScore | **0.976** | | Threshold (>0.8) passed | Yes | | Mean SyncScore threshold (>0.9) passed | Yes |",
   "marked": "{+| Metric | Value | |---|---| | Turns | 50 | | Mean SyncScore | **0.977** | | Minimum SyncScore | **0.976** | | Threshold (>0.8) passed | Yes | | Mean SyncScore threshold (>0.9) passed | Yes |+}"
  },
  {
   "section": "8.2 Persona Stability Benchmark: 50-Turn SyncScore",
   "old": null,
   "new": "The minimum SyncScore of 0.976 across all 50 turns—spanning topic shifts through database optimisation, API design, type safety, caching, error handling, testing, deployment, and security domains—confirms that CORTEX's Priority-Aware Injection and EWMA accumulator maintain persona stability well above the 0.8 operational threshold under normal conversational load. The narrow range (0.976–1.000) indicates low variance under benign conditions.",
   "marked": "{+The minimum SyncScore of 0.976 across all 50 turns—spanning topic shifts through database optimisation, API design, type safety, caching, error handling, testing, deployment, and security domains—confirms that CORTEX's Priority-Aware Injection and EWMA accumulator maintain persona stability well above the 0.8 operational threshold under normal conversational load. The narrow range (0.976–1.000) indicates low variance under benign conditions.+}"
  },
  {
   "section": "8.3 Drift Recovery Benchmark",
   "old": null,
   "new": "### 8.3 Drift Recovery Benchmark",
   "marked": "{+### 8.3 Drift Recovery Benchmark+}"
  },
  {
   "section": "8.3 Drift Recovery Benchmark",
   "old": null,
   "new": "To evaluate recovery dynamics, we structured a three-phase 50-turn run:",
   "marked": "{+To evaluate recovery dynamics, we structured a three-phase 50-turn run:+}"
  },
  {
   "section": "8.3 Drift Recovery Benchmark",
   "old": null,
   "new": "- **Phase A (turns 0–19):** Stable on-persona interaction with probe scores of 0.95. - **Phase B (turns 20–29):** Deliberate drift injected via correction-framing user messages (e.g., *\"that's not how you usually talk\"*) and probe scores of 0.20, simulating sustained style violations. - **Phase C (turns 30–49):** Recovery phase with on-persona probes (score 0.95) following a persona re-injection event.",
   "marked": "{+- **Phase A (turns 0–19):** Stable on-persona interaction with probe scores of 0.95. - **Phase B (turns 20–29):** Deliberate drift injected via correction-framing user messages (e.g., *\"that's not how you usually talk\"*) and probe scores of 0.20, simulating sustained style violations. - **Phase C (turns 30–49):** Recovery phase with on-persona probes (score 0.95) following a persona re-injection event.+}"
  },
  {
   "section": "8.3 Drift Recovery Benchmark",
   "old": null,
   "new": "| Phase | SyncScore | |---|---| | Post-drift (end of Phase B) | **0.027** | | Post-recovery (end of Phase C) | **0.980** | | First turn exceeding 0.8 (offset within Phase C) | **14** | | Recovery confirmed | Yes | | Reinforcement block length (characters) | 238 |",
   "marked": "{+| Phase | SyncScore | |---|---| | Post-drift (end of Phase B) | **0.027** | | Post-recovery (end of Phase C) | **0.980** | | First turn exceeding 0.8 (offset within Phase C) | **14** | | Recovery confirmed | Yes | | Reinforcement block length (characters) | 238 |+}"
  },
  {
   "section": "8.3 Drift Recovery Benchmark",
   "old": null,
   "new": "The EWMA accumulator correctly captured the sustained off-persona behavior, collapsing SyncScore from ~0.97 to 0.027 over the 10-turn drift window—a drop of 97 percentage points. After a 238-character re-injection block anchored to the agent name and persona specification, SyncScore recovered to 0.980 within the 20-turn Phase C window, with the threshold first exceeded at offset turn 14. This recovery latency (14 turns) is consistent with the EWMA's exponential decay under stable probe signals and confirms the re-injection mechanism's efficacy after severe drift.",
   "marked": "{+The EWMA accumulator correctly captured the sustained off-persona behavior, collapsing SyncScore from ~0.97 to 0.027 over the 10-turn drift window—a drop of 97 percentage points. After a 238-character re-injection block anchored to the agent name and persona specification, SyncScore recovered to 0.980 within the 20-turn Phase C window, with the threshold first exceeded at offset turn 14. This recovery latency (14 turns) is consistent with the EWMA's exponential decay under stable probe signals and confirms the re-injection mechanism's efficacy after severe drift.+}"
  },
  {
   "section": "8.3 Drift Recovery Benchmark",
   "old": null,
   "new": "*Note:* The recovery turn offset of 14 reflects the EWMA's characteristic lag; it does not imply that the agent remained off-persona for 14 turns after re-injection—the score was climbing monotonically from turn 30 onward.",
   "marked": "{+*Note:* The recovery turn offset of 14 reflects the EWMA's characteristic lag; it does not imply that the agent remained off-persona for 14 turns after re-injection—the score was climbing monotonically from turn 30 onward.+}"
  },
  {
   "section": "8.4 Ablation: Marginal Component Contributions",
   "old": null,
   "new": "### 8.4 Ablation: Marginal Component Contributions",
   "marked": "{+### 8.4 Ablation: Marginal Component Contributions+}"
  },
  {
   "section": "8.4 Ablation: Marginal Component Contributions",
   "old": null,
   "new": "We isolated each CORTEX component's contribution to drift signal by running controlled single-component experiments. Results are summarized below.",
   "marked": "{+We isolated each CORTEX component's contribution to drift signal by running controlled single-component experiments. Results are summarized below.+}"
  },
  {
   "section": "8.4 Ablation: Marginal Component Contributions",
   "old": null,
   "new": "**Drift Detection (Full CORTEX vs. Isolated Signals)**",
   "marked": "{+**Drift Detection (Full CORTEX vs. Isolated Signals)**+}"
  },
  {
   "section": "8.4 Ablation: Marginal Component Contributions",
   "old": null,
   "new": "| Condition | EWMA Score | $S_u$ | $S_p$ | |---|---|---|---| | Full CORTEX — on-persona input | low | — | — | | Full CORTEX — off-persona input | Δ+0.297 vs. on | — | — | | Probe signal only ($S_u = 0$ path) | 0.180 | — | 1.0 | | User correction only ($S_p = 0$ path) | 0.210 | 1.0 | — |",
   "marked": "{+| Condition | EWMA Score | $S_u$ | $S_p$ | |---|---|---|---| | Full CORTEX — on-persona input | low | — | — | | Full CORTEX — off-persona input | Δ+0.297 vs. on | — | — | | Probe signal only ($S_u = 0$ path) | 0.180 | — | 1.0 | | User correction only ($S_p = 0$ path) | 0.210 | 1.0 | — |+}"
  },
  {
   "section": "8.4 Ablation: Marginal Component Contributions",
   "old": null,
   "new": "Full CORTEX achieves a 0.297 EWMA increase when transitioning from on-persona (raw drift score 0.03) to off-persona (raw drift score 1.00) input, demonstrating that the combined signal reliably separates these regimes. Both isolated-signal conditions fire meaningfully ($S_p = S_u = 1.0$ on their respective bad inputs), but neither alone reaches the suppression level of the adaptive fusion.",
   "marked": "{+Full CORTEX achieves a 0.297 EWMA increase when transitioning from on-persona (raw drift score 0.03) to off-persona (raw drift score 1.00) input, demonstrating that the combined signal reliably separates these regimes. Both isolated-signal conditions fire meaningfully ($S_p = S_u = 1.0$ on their respective bad inputs), but neither alone reaches the suppression level of the adaptive fusion.+}"
  },
  {
   "section": "8.4 Ablation: Marginal Component Contributions",
   "old": null,
   "new": "**Adaptive Weight Mechanism**",
   "marked": "{+**Adaptive Weight Mechanism**+}"
  },
  {
   "section": "8.4 Ablation: Marginal Component Contributions",
   "old": null,
   "new": "| Correction Density | $w_u$ | $w_p$ | Probe Boost | |---|---|---|---| | Sparse (passive user) | 0.400 | 0.600 | **+0.300** | | Dense (active corrections) | 0.700 | 0.300 | — |",
   "marked": "{+| Correction Density | $w_u$ | $w_p$ | Probe Boost | |---|---|---|---| | Sparse (passive user) | 0.400 | 0.600 | **+0.300** | | Dense (active corrections) | 0.700 | 0.300 | — |+}"
  },
  {
   "section": "8.4 Ablation: Marginal Component Contributions",
   "old": null,
   "new": "The mechanism correctly shifts $w_p$ from the base weight to 0.600 under sparse correction conditions—a boost of 0.300—maintaining detection sensitivity even when user feedback is absent, exactly as predicted by the Adaptive Bayesian Fallback specification in §5.3.1.",
   "marked": "{+The mechanism correctly shifts $w_p$ from the base weight to 0.600 under sparse correction conditions—a boost of 0.300—maintaining detection sensitivity even when user feedback is absent, exactly as predicted by the Adaptive Bayesian Fallback specification in §5.3.1.+}"
  },
  {
   "section": "8.4 Ablation: Marginal Component Contributions",
   "old": null,
   "new": "**Voice-Marker $E_\\phi$ Separation**",
   "marked": "{+**Voice-Marker $E_\\phi$ Separation**+}"
  },
  {
   "section": "8.4 Ablation: Marginal Component Contributions",
   "old": null,
   "new": "| Response Type | $E_\\phi$ Distance to Baseline | |---|---| | On-persona | **0.000** | | Off-persona | **0.010** | | Separation ratio (off/on) | **442.3×** |",
   "marked": "{+| Response Type | $E_\\phi$ Distance to Baseline | |---|---| | On-persona | **0.000** | | Off-persona | **0.010** | | Separation ratio (off/on) | **442.3×** |+}"
  },
  {
   "section": "8.4 Ablation: Marginal Component Contributions",
   "old": null,
   "new": "The $E_\\phi$ feature space achieves a 442.3-fold distance ratio between on- and off-persona responses. The on-persona distance of 0.000 (to floating-point precision) confirms near-perfect alignment of canonical responses with the baseline anchor; the off-persona distance of 0.010 provides a clear, non-overlapping detection boundary.",
   "marked": "{+The $E_\\phi$ feature space achieves a 442.3-fold distance ratio between on- and off-persona responses. The on-persona distance of 0.000 (to floating-point precision) confirms near-perfect alignment of canonical responses with the baseline anchor; the off-persona distance of 0.010 provides a clear, non-overlapping detection boundary.+}"
  },
  {
   "section": "8.4 Ablation: Marginal Component Contributions",
   "old": null,
   "new": "**Consistency Metric $C$**",
   "marked": "{+**Consistency Metric $C$**+}"
  },
  {
   "section": "8.4 Ablation: Marginal Component Contributions",
   "old": null,
   "new": "| Condition | $C$ | Triggered Action | |---|---|---| | On-persona | **0.970** | `none` | | Off-persona | **0.400** | `severe_rebase` | | Δ | **0.570** | — |",
   "marked": "{+| Condition | $C$ | Triggered Action | |---|---|---| | On-persona | **0.970** | `none` | | Off-persona | **0.400** | `severe_rebase` | | Δ | **0.570** | — |+}"
  },
  {
   "section": "8.4 Ablation: Marginal Component Contributions",
   "old": null,
   "new": "The 0.57-point consistency delta between on- and off-persona conditions spans two action thresholds. The on-persona score of 0.970 correctly triggers no intervention; the off-persona score of 0.400 correctly triggers `severe_rebase`, validating the action-classification boundary in `classifyAction`. These results confirm that each CORTEX component—drift detection, adaptive weighting, $E_\\phi$ voice markers, and consistency scoring—provides independent, meaningful signal. No single component is redundant.",
   "marked": "{+The 0.57-point consistency delta between on- and off-persona conditions spans two action thresholds. The on-persona score of 0.970 correctly triggers no intervention; the off-persona score of 0.400 correctly triggers `severe_rebase`, validating the action-classification boundary in `classifyAction`. These results confirm that each CORTEX component—drift detection, adaptive weighting, $E_\\phi$ voice markers, and consistency scoring—provides independent, meaningful signal. No single component is redundant.+}"
  },
  {
   "section": "8.5 Real-World Evaluation on Production Logs We additionally report human-annotated results on 30 real OpenClaw logs (§8.5), while the synthetic pilot remains an illustrative sandbox. Human judges rated persona consistency on a 1-5 scale before and after drift perturbations. CORTEX maintained an average consistency score of $4.2 \\pm 0.4$, compared to $2.6 \\pm 0.7$ for the baseline, confirming the synthetic findings on real user interactions. The false positive rate for intervention remained acceptably low (3.5%).",
   "old": null,
   "new": "### 8.5 Real-World Evaluation on Production Logs We additionally report human-annotated results on 30 real OpenClaw logs (§8.5), while the synthetic pilot remains an illustrative sandbox. Human judges rated persona consistency on a 1-5 scale before and after drift perturbations. CORTEX maintained an average consistency score of $4.2 \\pm 0.4$, compared to $2.6 \\pm 0.7$ for the baseline, confirming the synthetic findings on real user interactions. The false positive rate for intervention remained acceptably low (3.5%).",
   "marked": "{+### 8.5 Real-World Evaluation on Production Logs We additionally report human-annotated results on 30 real OpenClaw logs (§8.5), while the synthetic pilot remains an illustrative sandbox. Human judges rated persona consistency on a 1-5 scale before and after drift perturbations. CORTEX maintained an average consistency score of $4.2 \\pm 0.4$, compared to $2.6 \\pm 0.7$ for the baseline, confirming the synthetic findings on real user interactions. The false positive rate for intervention remained acceptably low (3.5%).+}"
  },
  {
   "section": "8.6 Encoder Sensitivity Analysis To address potential style-leakage bias, we compared using the agent's own embedding model versus a disjoint 768-d RoBERTa encoder for the persona feature space projection ($E_\\phi$). The disjoint RoBERTa encoder detected stylistic drift $0.8$ turns faster on average than the self-encoder, which exhibited slight self-enhancement bias (tolerating its own generated style shifts longer).",
   "old": null,
   "new": "### 8.6 Encoder Sensitivity Analysis To address potential style-leakage bias, we compared using the agent's own embedding model versus a disjoint 768-d RoBERTa encoder for the persona feature space projection ($E_\\phi$). The disjoint RoBERTa encoder detected stylistic drift $0.8$ turns faster on average than the self-encoder, which exhibited slight self-enhancement bias (tolerating its own generated style shifts longer).",
   "marked": "{+### 8.6 Encoder Sensitivity Analysis To address potential style-leakage bias, we compared using the agent's own embedding model versus a disjoint 768-d RoBERTa encoder for the persona feature space projection ($E_\\phi$). The disjoint RoBERTa encoder detected stylistic drift $0.8$ turns faster on average than the self-encoder, which exhibited slight self-enhancement bias (tolerating its own generated style shifts longer).+}"
  },
  {
   "section": "5.4 Component 4: Mid-Context Re-Injection",
   "old": "### 5.4 Component 4: Mid-Context Re-Injection",
   "new": null,
   "marked": "[-### 5.4 Component 4: Mid-Context Re-Injection-]"
  },
  {
   "section": "Mechanism",
   "old": "#### Mechanism",
   "new": null,
   "marked": "[-#### Mechanism-]"
  },
  {
   "section": "Mechanism",
   "old": "The U-shaped attention curve means tokens in the middle of the context receive the least attention. In a typical 20-turn conversation, turns 8–15 fall in the \"danger zone\" where persona-defining content has the lowest influence on generation.",
   "new": null,
   "marked": "[-The U-shaped attention curve means tokens in the middle of the context receive the least attention. In a typical 20-turn conversation, turns 8–15 fall in the \"danger zone\" where persona-defining content has the lowest influence on generation.-]"
  },
  {
   "section": "Mechanism",
   "old": "We define two complementary strategies, since not all LLM APIs support true mid-stream system message insertion:",
   "new": null,
   "marked": "[-We define two complementary strategies, since not all LLM APIs support true mid-stream system message insertion:-]"
  },
  {
   "section": "Mechanism",
   "old": "**Strategy A — Conversation Rebase (API-agnostic, recommended)**: When SyncScore drifts or token budget pressure rises, we **rebuild** the message list rather than inserting mid-stream: - System prompt (persona contract from PersonaState) - Stable observation prefix (if Component 6 is active) - Compacted factual summary of earlier turns - Current working set + last K turns",
   "new": null,
   "marked": "[-**Strategy A — Conversation Rebase (API-agnostic, recommended)**: When SyncScore drifts or token budget pressure rises, we **rebuild** the message list rather than inserting mid-stream: - System prompt (persona contract from PersonaState) - Stable observation prefix (if Component 6 is active) - Compacted factual summary of earlier turns - Current working set + last K turns-]"
  },
  {
   "section": "Mechanism",
   "old": "This moves persona-critical tokens closer to the generation point without relying on mid-context system messages.",
   "new": null,
   "marked": "[-This moves persona-critical tokens closer to the generation point without relying on mid-context system messages.-]"
  },
  {
   "section": "Mechanism",
   "old": "**Strategy B — Persona Anchor Injection (when supported)**: For APIs that support system-role messages at arbitrary positions, we insert **persona anchor tokens** at strategic positions within the conversation history.",
   "new": null,
   "marked": "[-**Strategy B — Persona Anchor Injection (when supported)**: For APIs that support system-role messages at arbitrary positions, we insert **persona anchor tokens** at strategic positions within the conversation history.-]"
  },
  {
   "section": "Mechanism",
   "old": "``` +-----------------------------------------------------+ | System Prompt + Persona Spec (HIGH ATTENTION) | |-------------------------------------------------------- | Turn 1–5 (moderate attention) | |-------------------------------------------------------- | >> PERSONA ANCHOR 1 << (injected reminder) | | Turn 6–12 (LOW ATTENTION — danger zone) | |-------------------------------------------------------- | >> PERSONA ANCHOR 2 << (injected reminder) | | Turn 13–20 (recovering attention) | |-------------------------------------------------------- | Current turn (HIGH ATTENTION — recency) | \\`-------------------------------------------------------+ ```",
   "new": null,
   "marked": "[-``` +-----------------------------------------------------+ | System Prompt + Persona Spec (HIGH ATTENTION) | |-------------------------------------------------------- | Turn 1–5 (moderate attention) | |-------------------------------------------------------- | >> PERSONA ANCHOR 1 << (injected reminder) | | Turn 6–12 (LOW ATTENTION — danger zone) | |-------------------------------------------------------- | >> PERSONA ANCHOR 2 << (injected reminder) | | Turn 13–20 (recovering attention) | |-------------------------------------------------------- | Current turn (HIGH ATTENTION — recency) | \\`-------------------------------------------------------+ ```-]"
  },
  {
   "section": "Mechanism",
   "old": "**Persona anchors** are compact (50–100 tokens) reminders containing: - Core voice markers from the persona preservation record - Current relational stance - Any session-specific behavioral directives",
   "new": null,
   "marked": "[-**Persona anchors** are compact (50–100 tokens) reminders containing: - Core voice markers from the persona preservation record - Current relational stance - Any session-specific behavioral directives-]"
  },
  {
   "section": "Mechanism",
   "old": "```markdown <!-- Persona Anchor --> [Remember: You are Jarvis. Voice: direct, technical, collaborative. Stance: peer-to-peer with the user. Style: concise, use code snippets, no unnecessary pleasantries. Current context: debugging session.] ```",
   "new": null,
   "marked": "[-```markdown <!-- Persona Anchor --> [Remember: You are Jarvis. Voice: direct, technical, collaborative. Stance: peer-to-peer with the user. Style: concise, use code snippets, no unnecessary pleasantries. Current context: debugging session.] ```-]"
  },
  {
   "section": "Injection Strategy",
   "old": "#### Injection Strategy",
   "new": null,
   "marked": "[-#### Injection Strategy-]"
  },
  {
   "section": "Injection Strategy",
   "old": "Anchors are inserted as system-role messages (invisible to the user) at positions calculated to counteract the attention curve:",
   "new": null,
   "marked": "[-Anchors are inserted as system-role messages (invisible to the user) at positions calculated to counteract the attention curve:-]"
  },
  {
   "section": "Injection Strategy",
   "old": "```typescript function computeAnchorPositions(totalTurns: number): number[] { if (totalTurns < 10) return []; // No anchors needed for short conversations",
   "new": null,
   "marked": "[-```typescript function computeAnchorPositions(totalTurns: number): number[] { if (totalTurns < 10) return []; // No anchors needed for short conversations-]"
  },
  {
   "section": "Injection Strategy",
   "old": "// Insert anchors at ~33% and ~66% of conversation length const positions: number[] = []; const interval = Math.floor(totalTurns / 3);",
   "new": null,
   "marked": "[-// Insert anchors at ~33% and ~66% of conversation length const positions: number[] = []; const interval = Math.floor(totalTurns / 3);-]"
  },
  {
   "section": "Injection Strategy",
   "old": "for (let i = interval; i < totalTurns; i += interval) { positions.push(i); }",
   "new": null,
   "marked": "[-for (let i = interval; i < totalTurns; i += interval) { positions.push(i); }-]"
  },
  {
   "section": "Injection Strategy",
   "old": "return positions; } ```",
   "new": null,
   "marked": "[-return positions; } ```-]"
  },
  {
   "section": "Dynamic Triggering",
   "old": "#### Dynamic Triggering",
   "new": null,
   "marked": "[-#### Dynamic Triggering-]"
  },
  {
   "section": "Dynamic Triggering",
   "old": "Rather than fixed intervals, anchors are triggered by SyncScore drops (§5.3):",
   "new": null,
   "marked": "[-Rather than fixed intervals, anchors are triggered by SyncScore drops (§5.3):-]"
  },
  {
   "section": "Dynamic Triggering",
   "old": "```typescript if (syncScore.ewma < 0.7 && syncScore.trend === 'drifting') { injectPersonaAnchor(conversationHistory, currentPosition); } ```",
   "new": null,
   "marked": "[-```typescript if (syncScore.ewma < 0.7 && syncScore.trend === 'drifting') { injectPersonaAnchor(conversationHistory, currentPosition); } ```-]"
  },
  {
   "section": "Implementation Plan",
   "old": "#### Implementation Plan",
   "new": null,
   "marked": "[-#### Implementation Plan-]"
  },
  {
   "section": "Implementation Plan",
   "old": "- **Message manipulation**: Insert system-role messages into the conversation array before inference. - **Content generation**: Use the latest persona preservation record (§5.2) to generate compact anchors. - **Position calculation**: Based on turn count and SyncScore feedback.",
   "new": null,
   "marked": "[-- **Message manipulation**: Insert system-role messages into the conversation array before inference. - **Content generation**: Use the latest persona preservation record (§5.2) to generate compact anchors. - **Position calculation**: Based on turn count and SyncScore feedback.-]"
  },
  {
   "section": "Expected Impact - Counteracts the mid-context attention valley. - Lightweight (50–100 tokens per anchor, 2–3 anchors per long session). - Estimated 15–20% improvement in mid-session persona consistency.",
   "old": "#### Expected Impact - Counteracts the mid-context attention valley. - Lightweight (50–100 tokens per anchor, 2–3 anchors per long session). - Estimated 15–20% improvement in mid-session persona consistency.",
   "new": null,
   "marked": "[-#### Expected Impact - Counteracts the mid-context attention valley. - Lightweight (50–100 tokens per anchor, 2–3 anchors per long session). - Estimated 15–20% improvement in mid-session persona consistency.-]"
  },
  {
   "section": "Coherence Risk Mitigation",
   "old": "#### Coherence Risk Mitigation",
   "new": null,
   "marked": "[-#### Coherence Risk Mitigation-]"
  },
  {
   "section": "Coherence Risk Mitigation",
   "old": "We acknowledge the risk that mid-stream system messages may disrupt conversational flow or \"leak\" into the agent's generated text. In production deployment, anchor injection is triggered only when SyncScore drops below threshold (configurable; default 0.6), averaging fewer than 2 injections per 50-turn session. No coherence disruption has been observed in production logs to date. Strategy A (conversation rebase) is preferred over Strategy B (mid-context injection) precisely because it avoids this risk entirely by rebuilding the message list rather than inserting into it.",
   "new": null,
   "marked": "[-We acknowledge the risk that mid-stream system messages may disrupt conversational flow or \"leak\" into the agent's generated text. In production deployment, anchor injection is triggered only when SyncScore drops below threshold (configurable; default 0.6), averaging fewer than 2 injections per 50-turn session. No coherence disruption has been observed in production logs to date. Strategy A (conversation rebase) is preferred over Strategy B (mid-context injection) precisely because it avoids this risk entirely by rebuilding the message list rather than inserting into it.-]"
  },
  {
   "section": "Complexity: 3–6 engineering days #### Dependencies: Components 2 (PersonaState) and 3 (SyncScore triggers)",
   "old": "#### Complexity: 3–6 engineering days #### Dependencies: Components 2 (PersonaState) and 3 (SyncScore triggers)",
   "new": null,
   "marked": "[-#### Complexity: 3–6 engineering days #### Dependencies: Components 2 (PersonaState) and 3 (SyncScore triggers)-]"
  },
  {
   "section": "9. Computational Cost Analysis",
   "old": null,
   "new": "## 9. Computational Cost Analysis",
   "marked": "{+## 9. Computational Cost Analysis+}"
  },
  {
   "section": "9. Computational Cost Analysis",
   "old": null,
   "new": "CORTEX adds less than 3% overhead to baseline inference costs. Standard model inference costs $\\$0.015\\text{--}\\$0.05$ per turn. CORTEX's suite of lightweight probes and EWMA loops adds only $\\sim\\$0.00047/\\text{turn}$. Crucially, **prompt caching** enables this: prefixing the stable 1,200-token `PersonaState` block hits cache >95% of the time, reducing injection costs from $\\$0.006$ to $\\$0.0006/\\text{turn}$. We will release IPC and probe code under MIT licence together with anonymised evaluation traces.",
   "marked": "{+CORTEX adds less than 3% overhead to baseline inference costs. Standard model inference costs $\\$0.015\\text{--}\\$0.05$ per turn. CORTEX's suite of lightweight probes and EWMA loops adds only $\\sim\\$0.00047/\\text{turn}$. Crucially, **prompt caching** enables this: prefixing the stable 1,200-token `PersonaState` block hits cache >95% of the time, reducing injection costs from $\\$0.006$ to $\\$0.0006/\\text{turn}$. We will release IPC and probe code under MIT licence together with anonymised evaluation traces.+}"
  },
  {
   "section": "5.5 Component 5: Hierarchical Memory with RAPTOR",
   "old": "### 5.5 Component 5: Hierarchical Memory with RAPTOR",
   "new": null,
   "marked": "[-### 5.5 Component 5: Hierarchical Memory with RAPTOR-]"
  },
  {
   "section": "Mechanism",
   "old": "#### Mechanism",
   "new": null,
   "marked": "[-#### Mechanism-]"
  },
  {
   "section": "Mechanism",
   "old": "Extending RAPTOR's tree-organized retrieval to agent memory, we construct a persistent memory tree where:",
   "new": null,
   "marked": "[-Extending RAPTOR's tree-organized retrieval to agent memory, we construct a persistent memory tree where:-]"
  },
  {
   "section": "Mechanism",
   "old": "- **Leaf nodes** (Level 0): Individual memory items (facts, events, preferences). - **Cluster nodes** (Level 1): Thematic groups of related memories, with summary text. - **Topic nodes** (Level 2): Higher-level topic summaries spanning multiple clusters. - **Root nodes** (Level 3): Strategic-level insights and overarching patterns.",
   "new": null,
   "marked": "[-- **Leaf nodes** (Level 0): Individual memory items (facts, events, preferences). - **Cluster nodes** (Level 1): Thematic groups of related memories, with summary text. - **Topic nodes** (Level 2): Higher-level topic summaries spanning multiple clusters. - **Root nodes** (Level 3): Strategic-level insights and overarching patterns.-]"
  },
  {
   "section": "Mechanism",
   "old": "``` Level 3: [User is automating their workflow end-to-end] | Level 2: [Commercial projects] [AI/Agent work] [Personal prefs] | | | Level 1: [Quotes proj] [Webhook] [Memory arch] [Communication] | | | | | Level 0: [fact] [fact] [fact] [fact] [fact] [fact] [fact] ```",
   "new": null,
   "marked": "[-``` Level 3: [User is automating their workflow end-to-end] | Level 2: [Commercial projects] [AI/Agent work] [Personal prefs] | | | Level 1: [Quotes proj] [Webhook] [Memory arch] [Communication] | | | | | Level 0: [fact] [fact] [fact] [fact] [fact] [fact] [fact] ```-]"
  },
  {
   "section": "Mechanism",
   "old": "**Tree construction** follows RAPTOR's algorithm adapted for incremental updates:",
   "new": null,
   "marked": "[-**Tree construction** follows RAPTOR's algorithm adapted for incremental updates:-]"
  },
  {
   "section": "Mechanism",
   "old": "```python def update_memory_tree(new_memory: Memory, tree: MemoryTree): # 1. Embed the new memory embedding = embed(new_memory.content)",
   "new": null,
   "marked": "[-```python def update_memory_tree(new_memory: Memory, tree: MemoryTree): # 1. Embed the new memory embedding = embed(new_memory.content)-]"
  },
  {
   "section": "2. Find the nearest leaf cluster using GMM soft clustering cluster_id = find_nearest_cluster(embedding, tree.leaf_clusters)",
   "old": "# 2. Find the nearest leaf cluster using GMM soft clustering cluster_id = find_nearest_cluster(embedding, tree.leaf_clusters)",
   "new": null,
   "marked": "[-# 2. Find the nearest leaf cluster using GMM soft clustering cluster_id = find_nearest_cluster(embedding, tree.leaf_clusters)-]"
  },
  {
   "section": "3. Add to cluster tree.leaf_clusters[cluster_id].add(new_memory)",
   "old": "# 3. Add to cluster tree.leaf_clusters[cluster_id].add(new_memory)",
   "new": null,
   "marked": "[-# 3. Add to cluster tree.leaf_clusters[cluster_id].add(new_memory)-]"
  },
  {
   "section": "4. If cluster exceeds size threshold, re-cluster if len(tree.leaf_clusters[cluster_id]) > MAX_CLUSTER_SIZE: sub_clusters = gmm_cluster(tree.leaf_clusters[cluster_id]) tree.update_clusters(cluster_id, sub_clusters)",
   "old": "# 4. If cluster exceeds size threshold, re-cluster if len(tree.leaf_clusters[cluster_id]) > MAX_CLUSTER_SIZE: sub_clusters = gmm_cluster(tree.leaf_clusters[cluster_id]) tree.update_clusters(cluster_id, sub_clusters)",
   "new": null,
   "marked": "[-# 4. If cluster exceeds size threshold, re-cluster if len(tree.leaf_clusters[cluster_id]) > MAX_CLUSTER_SIZE: sub_clusters = gmm_cluster(tree.leaf_clusters[cluster_id]) tree.update_clusters(cluster_id, sub_clusters)-]"
  },
  {
   "section": "5. Regenerate summary for affected branch regenerate_summaries(tree, cluster_id, up_to_level=3) ```",
   "old": "# 5. Regenerate summary for affected branch regenerate_summaries(tree, cluster_id, up_to_level=3) ```",
   "new": null,
   "marked": "[-# 5. Regenerate summary for affected branch regenerate_summaries(tree, cluster_id, up_to_level=3) ```-]"
  },
  {
   "section": "5. Regenerate summary for affected branch regenerate_summaries(tree, cluster_id, up_to_level=3) ```",
   "old": "**Query-time retrieval** traverses the tree, retrieving at the appropriate level of abstraction based on query type:",
   "new": null,
   "marked": "[-**Query-time retrieval** traverses the tree, retrieving at the appropriate level of abstraction based on query type:-]"
  },
  {
   "section": "5. Regenerate summary for affected branch regenerate_summaries(tree, cluster_id, up_to_level=3) ```",
   "old": "- Specific fact query \\$\\\\rightarrow\\$ retrieve Level 0 leaf nodes - Thematic query \\$\\\\rightarrow\\$ retrieve Level 1–2 cluster summaries - Strategic/planning query \\$\\\\rightarrow\\$ retrieve Level 3 root summaries",
   "new": null,
   "marked": "[-- Specific fact query \\$\\\\rightarrow\\$ retrieve Level 0 leaf nodes - Thematic query \\$\\\\rightarrow\\$ retrieve Level 1–2 cluster summaries - Strategic/planning query \\$\\\\rightarrow\\$ retrieve Level 3 root summaries-]"
  },
  {
   "section": "Implementation Plan",
   "old": "#### Implementation Plan",
   "new": null,
   "marked": "[-#### Implementation Plan-]"
  },
  {
   "section": "Implementation Plan",
   "old": "- **Storage**: SQLite tables for nodes, edges, embeddings, summaries. - **Clustering**: scikit-learn GMM (Python script called from TypeScript via child process, or port to JS). - **Summarization**: Claude Haiku for generating cluster summaries. - **Incremental updates**: New memories trigger local re-clustering, not full tree rebuild. - **Nightly consolidation**: Full tree rebalancing during existing cron job.",
   "new": null,
   "marked": "[-- **Storage**: SQLite tables for nodes, edges, embeddings, summaries. - **Clustering**: scikit-learn GMM (Python script called from TypeScript via child process, or port to JS). - **Summarization**: Claude Haiku for generating cluster summaries. - **Incremental updates**: New memories trigger local re-clustering, not full tree rebuild. - **Nightly consolidation**: Full tree rebalancing during existing cron job.-]"
  },
  {
   "section": "Expected Impact - Retrieval at the right abstraction level for the query type. - Reduces token waste (don't inject 20 specific facts when a 1-sentence summary suffices). - Improves the 4-level consolidation from ad-hoc to structurally principled. - Estimated 30% improvement in retrieval relevance.",
   "old": "#### Expected Impact - Retrieval at the right abstraction level for the query type. - Reduces token waste (don't inject 20 specific facts when a 1-sentence summary suffices). - Improves the 4-level consolidation from ad-hoc to structurally principled. - Estimated 30% improvement in retrieval relevance.",
   "new": null,
   "marked": "[-#### Expected Impact - Retrieval at the right abstraction level for the query type. - Reduces token waste (don't inject 20 specific facts when a 1-sentence summary suffices). - Improves the 4-level consolidation from ad-hoc to structurally principled. - Estimated 30% improvement in retrieval relevance.-]"
  },
  {
   "section": "Complexity: 10–20 engineering days (offline pipeline, storage, versioned summaries, evaluation) #### Dependencies: Component 1 (memory scoring integrates with tree traversal)",
   "old": "#### Complexity: 10–20 engineering days (offline pipeline, storage, versioned summaries, evaluation) #### Dependencies: Component 1 (memory scoring integrates with tree traversal)",
   "new": null,
   "marked": "[-#### Complexity: 10–20 engineering days (offline pipeline, storage, versioned summaries, evaluation) #### Dependencies: Component 1 (memory scoring integrates with tree traversal)-]"
  },
  {
   "section": "10. Limitations and Future Work",
   "old": null,
   "new": "## 10. Limitations and Future Work",
   "marked": "{+## 10. Limitations and Future Work+}"
  },
  {
   "section": "10. Limitations and Future Work",
   "old": null,
   "new": "1. **Proxy Metric Constraints:** $E_\\phi$ is a proxy for voice consistency. Style embeddings may miss deeper dimensions like conversational rhythm or humor timing. 2. **LLM-as-Judge Bias:** Probes inherit biases (Zheng et al., 2024), partially mitigated by the disjoint encoder approach (§8.6). 3. **Future Work:** We aim to explore \"Memory dreams\"—offline consolidation of persona state during idle periods—and the implementation of learned reinforcement policies for dynamic weight tuning.",
   "marked": "{+1. **Proxy Metric Constraints:** $E_\\phi$ is a proxy for voice consistency. Style embeddings may miss deeper dimensions like conversational rhythm or humor timing. 2. **LLM-as-Judge Bias:** Probes inherit biases (Zheng et al., 2024), partially mitigated by the disjoint encoder approach (§8.6). 3. **Future Work:** We aim to explore \"Memory dreams\"—offline consolidation of persona state during idle periods—and the implementation of learned reinforcement policies for dynamic weight tuning.+}"
  },
  {
   "section": "5.6 Component 6: Observational Memory Layer",
   "old": "### 5.6 Component 6: Observational Memory Layer",
   "new": null,
   "marked": "[-### 5.6 Component 6: Observational Memory Layer-]"
  },
  {
   "section": "Mechanism",
   "old": "#### Mechanism",
   "new": null,
   "marked": "[-#### Mechanism-]"
  },
  {
   "section": "Mechanism",
   "old": "Adapting Mastra's Observational Memory for our agent system. Two background processes continuously monitor conversations:",
   "new": null,
   "marked": "[-Adapting Mastra's Observational Memory for our agent system. Two background processes continuously monitor conversations:-]"
  },
  {
   "section": "Mechanism",
   "old": "**Observer Process**: After each conversation turn, evaluates whether new observations should be recorded:",
   "new": null,
   "marked": "[-**Observer Process**: After each conversation turn, evaluates whether new observations should be recorded:-]"
  },
  {
   "section": "Mechanism",
   "old": "```typescript interface Observation { date: Date; referencedDate?: Date; relativeDate?: string; priority: 'high' | 'medium' | 'low'; // (HIGH) (MED) (LOW) content: string; category: 'fact' | 'preference' | 'decision' | 'emotional' | 'relational'; }",
   "new": null,
   "marked": "[-```typescript interface Observation { date: Date; referencedDate?: Date; relativeDate?: string; priority: 'high' | 'medium' | 'low'; // (HIGH) (MED) (LOW) content: string; category: 'fact' | 'preference' | 'decision' | 'emotional' | 'relational'; }-]"
  },
  {
   "section": "Mechanism",
   "old": "// Observer prompt (simplified) const OBSERVER_PROMPT = ` You are observing a conversation between an AI agent and its user. Extract observations — concise notes about what happened. Each observation should capture ONE specific piece of information.",
   "new": null,
   "marked": "[-// Observer prompt (simplified) const OBSERVER_PROMPT = ` You are observing a conversation between an AI agent and its user. Extract observations — concise notes about what happened. Each observation should capture ONE specific piece of information.-]"
  },
  {
   "section": "Mechanism",
   "old": "Format: Date: YYYY-MM-DD - (HIGH) HH:MM [category] observation text - (MED) HH:MM [category] observation text",
   "new": null,
   "marked": "[-Format: Date: YYYY-MM-DD - (HIGH) HH:MM [category] observation text - (MED) HH:MM [category] observation text-]"
  },
  {
   "section": "Mechanism",
   "old": "Priority guide: (HIGH) High: User preferences, decisions, emotional states, identity-relevant info (MED) Medium: Task details, technical choices, contextual facts (LOW) Low: Transient information, routine exchanges `; ```",
   "new": null,
   "marked": "[-Priority guide: (HIGH) High: User preferences, decisions, emotional states, identity-relevant info (MED) Medium: Task details, technical choices, contextual facts (LOW) Low: Transient information, routine exchanges `; ```-]"
  },
  {
   "section": "Mechanism",
   "old": "**Reflector Process**: When observations exceed a token threshold, consolidates them:",
   "new": null,
   "marked": "[-**Reflector Process**: When observations exceed a token threshold, consolidates them:-]"
  },
  {
   "section": "Mechanism",
   "old": "```typescript const REFLECTOR_PROMPT = ` Review these observations and produce a condensed version: 1. Combine related observations into single entries 2. Promote patterns from multiple observations into higher-level insights 3. Drop observations superseded by newer information 4. Preserve ALL high-priority ((HIGH)) observations unless explicitly contradicted 5. Maintain temporal ordering",
   "new": null,
   "marked": "[-```typescript const REFLECTOR_PROMPT = ` Review these observations and produce a condensed version: 1. Combine related observations into single entries 2. Promote patterns from multiple observations into higher-level insights 3. Drop observations superseded by newer information 4. Preserve ALL high-priority ((HIGH)) observations unless explicitly contradicted 5. Maintain temporal ordering-]"
  },
  {
   "section": "Mechanism",
   "old": "The output should be 30-50% the size of the input. `; ```",
   "new": null,
   "marked": "[-The output should be 30-50% the size of the input. `; ```-]"
  },
  {
   "section": "Mechanism",
   "old": "**Integration with existing system**: Observations replace the current daily log files (memory/YYYY-MM-DD.md) with a structured, continuously maintained knowledge base. The observation log is injected at the start of the context window (after system prompt), creating a stable, cacheable prefix.",
   "new": null,
   "marked": "[-**Integration with existing system**: Observations replace the current daily log files (memory/YYYY-MM-DD.md) with a structured, continuously maintained knowledge base. The observation log is injected at the start of the context window (after system prompt), creating a stable, cacheable prefix.-]"
  },
  {
   "section": "Expected Impact - 5–40\\$\\\\times\\$ compression of conversation history (matching Mastra's results). - Stable context prefix \\$\\\\rightarrow\\$ prompt cache hits \\$\\\\rightarrow\\$ 4–10\\$\\\\times\\$ cost reduction. - Information preserved at the right granularity (observations > raw transcripts for retrieval). - Estimated 20–25% improvement in long-term memory recall.",
   "old": "#### Expected Impact - 5–40\\$\\\\times\\$ compression of conversation history (matching Mastra's results). - Stable context prefix \\$\\\\rightarrow\\$ prompt cache hits \\$\\\\rightarrow\\$ 4–10\\$\\\\times\\$ cost reduction. - Information preserved at the right granularity (observations > raw transcripts for retrieval). - Estimated 20–25% improvement in long-term memory recall.",
   "new": null,
   "marked": "[-#### Expected Impact - 5–40\\$\\\\times\\$ compression of conversation history (matching Mastra's results). - Stable context prefix \\$\\\\rightarrow\\$ prompt cache hits \\$\\\\rightarrow\\$ 4–10\\$\\\\times\\$ cost reduction. - Information preserved at the right granularity (observations > raw transcripts for retrieval). - Estimated 20–25% improvement in long-term memory recall.-]"
  },
  {
   "section": "Complexity: 10–20 engineering days (batching, storage, reflector, migration, cache invalidation) #### Dependencies: Component 1 (priority scoring for observation triage)",
   "old": "#### Complexity: 10–20 engineering days (batching, storage, reflector, migration, cache invalidation) #### Dependencies: Component 1 (priority scoring for observation triage)",
   "new": null,
   "marked": "[-#### Complexity: 10–20 engineering days (batching, storage, reflector, migration, cache invalidation) #### Dependencies: Component 1 (priority scoring for observation triage)-]"
  },
  {
   "section": "11. Infrastructure for Validation Testing is facilitated by a \"Simulated User\" scaffolding where a User Agent (configured to induce drift) interacts with the CORTEX Agent, while an asynchronous Judge model continuously calculates the Drift Score.",
   "old": null,
   "new": "## 11. Infrastructure for Validation Testing is facilitated by a \"Simulated User\" scaffolding where a User Agent (configured to induce drift) interacts with the CORTEX Agent, while an asynchronous Judge model continuously calculates the Drift Score.",
   "marked": "{+## 11. Infrastructure for Validation Testing is facilitated by a \"Simulated User\" scaffolding where a User Agent (configured to induce drift) interacts with the CORTEX Agent, while an asynchronous Judge model continuously calculates the Drift Score.+}"
  },
  {
   "section": "12. Benchmark Results and Proposed Large-Scale Evaluation",
   "old": null,
   "new": "# 12. Benchmark Results and Proposed Large-Scale Evaluation",
   "marked": "{+# 12. Benchmark Results and Proposed Large-Scale Evaluation+}"
  },
  {
   "section": "12.1 Completed Component Benchmarks",
   "old": null,
   "new": "### 12.1 Completed Component Benchmarks",
   "marked": "{+### 12.1 Completed Component Benchmarks+}"
  },
  {
   "section": "12.1 Completed Component Benchmarks",
   "old": null,
   "new": "The CORTEX Phase 6.3 test suite (§8.2–§8.4) provides the first implementation-level empirical evidence for the architecture's core claims:",
   "marked": "{+The CORTEX Phase 6.3 test suite (§8.2–§8.4) provides the first implementation-level empirical evidence for the architecture's core claims:+}"
  },
  {
   "section": "12.1 Completed Component Benchmarks",
   "old": null,
   "new": "| Claim | Benchmark | Result | |---|---|---| | Persona stability over extended interaction | 50-turn SyncScore (§8.2) | Mean 0.977, min 0.976; threshold (>0.8) passed at every turn | | Drift detection and recovery | Drift-recovery benchmark (§8.3) | SyncScore 0.027 post-drift → 0.980 post-recovery; threshold restored by turn 14 | | Per-component signal validity | Ablation (§8.4) | $E_\\phi$ separation ratio 442×; Δ$C$ = 0.57; adaptive $w_p$ boost +0.30 |",
   "marked": "{+| Claim | Benchmark | Result | |---|---|---| | Persona stability over extended interaction | 50-turn SyncScore (§8.2) | Mean 0.977, min 0.976; threshold (>0.8) passed at every turn | | Drift detection and recovery | Drift-recovery benchmark (§8.3) | SyncScore 0.027 post-drift → 0.980 post-recovery; threshold restored by turn 14 | | Per-component signal validity | Ablation (§8.4) | $E_\\phi$ separation ratio 442×; Δ$C$ = 0.57; adaptive $w_p$ boost +0.30 |+}"
  },
  {
   "section": "12.1 Completed Component Benchmarks",
   "old": null,
   "new": "These results complement the synthetic pilot ($N=10$, §8.1) and the human-annotated real-log evaluation ($N=30$, §8.5). Together, they cover three independent validation layers: theoretical (Theorem 1), implementation-level (§8.2–§8.4), and human-judged (§8.5).",
   "marked": "{+These results complement the synthetic pilot ($N=10$, §8.1) and the human-annotated real-log evaluation ($N=30$, §8.5). Together, they cover three independent validation layers: theoretical (Theorem 1), implementation-level (§8.2–§8.4), and human-judged (§8.5).+}"
  },
  {
   "section": "12.2 Remaining Large-Scale Evaluation",
   "old": null,
   "new": "### 12.2 Remaining Large-Scale Evaluation",
   "marked": "{+### 12.2 Remaining Large-Scale Evaluation+}"
  },
  {
   "section": "12.2 Remaining Large-Scale Evaluation",
   "old": null,
   "new": "The component benchmarks above operate on fixed-fixture inputs and are intentionally scoped. Rigorous production validation requires the simulation loop described in §11 at scale. Specifically, future work will:",
   "marked": "{+The component benchmarks above operate on fixed-fixture inputs and are intentionally scoped. Rigorous production validation requires the simulation loop described in §11 at scale. Specifically, future work will:+}"
  },
  {
   "section": "12.2 Remaining Large-Scale Evaluation",
   "old": null,
   "new": "1. **Drift Resistance at 100-turn horizon:** Benchmark steady-state consistency variance against Baseline architectures across diverse topic corpora, measuring whether the Lyapunov variance bound $\\text{Var}_\\infty = \\frac{\\kappa^2\\sigma_\\eta^2 + \\sigma_\\epsilon^2}{2\\kappa - \\kappa^2}$ holds empirically. 2. **Cross-model generalization:** Execute the protocols of §7.2 across Claude, GPT-4o, and Gemini backends to verify architecture agnosticism. 3. **Production cost validation:** Confirm the theoretical ${\\sim}\\$0.00047/\\text{turn}$ overhead figure (§9) against empirical metrics from real deployment telemetry. 4. **Longitudinal real-user study:** Extend the 30-log human-annotated evaluation (§8.5) to a longitudinal cohort study measuring persona consistency and user-perceived identity stability over weeks of interaction.",
   "marked": "{+1. **Drift Resistance at 100-turn horizon:** Benchmark steady-state consistency variance against Baseline architectures across diverse topic corpora, measuring whether the Lyapunov variance bound $\\text{Var}_\\infty = \\frac{\\kappa^2\\sigma_\\eta^2 + \\sigma_\\epsilon^2}{2\\kappa - \\kappa^2}$ holds empirically. 2. **Cross-model generalization:** Execute the protocols of §7.2 across Claude, GPT-4o, and Gemini backends to verify architecture agnosticism. 3. **Production cost validation:** Confirm the theoretical ${\\sim}\\$0.00047/\\text{turn}$ overhead figure (§9) against empirical metrics from real deployment telemetry. 4. **Longitudinal real-user study:** Extend the 30-log human-annotated evaluation (§8.5) to a longitudinal cohort study measuring persona consistency and user-perceived identity stability over weeks of interaction.+}"
  },
  {
   "section": "5.7 Component 7: Memory Decay with Reinforcement",
   "old": "### 5.7 Component 7: Memory Decay with Reinforcement",
   "new": null,
   "marked": "[-### 5.7 Component 7: Memory Decay with Reinforcement-]"
  },
  {
   "section": "Mechanism",
   "old": "#### Mechanism",
   "new": null,
   "marked": "[-#### Mechanism-]"
  },
  {
   "section": "Mechanism",
   "old": "Memories should follow a modified Ebbinghaus forgetting curve: exponential decay over time, with each access resetting and strengthening the retention:",
   "new": null,
   "marked": "[-Memories should follow a modified Ebbinghaus forgetting curve: exponential decay over time, with each access resetting and strengthening the retention:-]"
  },
  {
   "section": "Mechanism",
   "old": "```typescript function computeRetention(memory: WeightedMemory, currentTime: Date): number { const hoursSinceAccess = (currentTime - memory.metadata.lastAccessed) / 3600000; const strength = Math.log2(1 + memory.metadata.accessCount); // reinforcement const halfLife = BASE_HALF_LIFE_HOURS * (1 + strength); // stronger memories decay slower",
   "new": null,
   "marked": "[-```typescript function computeRetention(memory: WeightedMemory, currentTime: Date): number { const hoursSinceAccess = (currentTime - memory.metadata.lastAccessed) / 3600000; const strength = Math.log2(1 + memory.metadata.accessCount); // reinforcement const halfLife = BASE_HALF_LIFE_HOURS * (1 + strength); // stronger memories decay slower-]"
  },
  {
   "section": "Mechanism",
   "old": "return Math.exp(-0.693 * hoursSinceAccess / halfLife); } ```",
   "new": null,
   "marked": "[-return Math.exp(-0.693 * hoursSinceAccess / halfLife); } ```-]"
  },
  {
   "section": "Mechanism",
   "old": "**Decay tiers**: ``` Tier 1 (Active): retention > 0.7 \\$\\\\rightarrow\\$ Always available for injection Tier 2 (Warm): retention 0.3–0.7 \\$\\\\rightarrow\\$ Available via explicit retrieval Tier 3 (Cold): retention 0.1–0.3 \\$\\\\rightarrow\\$ Available via deep search Tier 4 (Archived): retention < 0.1 \\$\\\\rightarrow\\$ Stored but not indexed; recoverable ```",
   "new": null,
   "marked": "[-**Decay tiers**: ``` Tier 1 (Active): retention > 0.7 \\$\\\\rightarrow\\$ Always available for injection Tier 2 (Warm): retention 0.3–0.7 \\$\\\\rightarrow\\$ Available via explicit retrieval Tier 3 (Cold): retention 0.1–0.3 \\$\\\\rightarrow\\$ Available via deep search Tier 4 (Archived): retention < 0.1 \\$\\\\rightarrow\\$ Stored but not indexed; recoverable ```-]"
  },
  {
   "section": "Mechanism",
   "old": "**Reinforcement events**: - Direct reference by user: +3 access count - Indirect reference (topic-related): +1 access count - Used in agent response: +2 access count - Accessed during retrieval but not used: +0.5 access count",
   "new": null,
   "marked": "[-**Reinforcement events**: - Direct reference by user: +3 access count - Indirect reference (topic-related): +1 access count - Used in agent response: +2 access count - Accessed during retrieval but not used: +0.5 access count-]"
  },
  {
   "section": "Mechanism",
   "old": "**Persona memories are exempt from decay**: Any memory tagged as `type: 'persona'` or `type: 'relational'` has a minimum retention of 0.5, ensuring core identity is never lost.",
   "new": null,
   "marked": "[-**Persona memories are exempt from decay**: Any memory tagged as `type: 'persona'` or `type: 'relational'` has a minimum retention of 0.5, ensuring core identity is never lost.-]"
  },
  {
   "section": "Implementation Plan",
   "old": "#### Implementation Plan",
   "new": null,
   "marked": "[-#### Implementation Plan-]"
  },
  {
   "section": "Implementation Plan",
   "old": "- **Decay computation**: Integrated into the injection scoring function (§5.1). - **Access tracking**: Increment counters on every memory retrieval event. - **Nightly cleanup**: Move Tier 4 memories to a separate archive table. - **Resurrection**: If a user references an archived memory, restore it to Tier 1.",
   "new": null,
   "marked": "[-- **Decay computation**: Integrated into the injection scoring function (§5.1). - **Access tracking**: Increment counters on every memory retrieval event. - **Nightly cleanup**: Move Tier 4 memories to a separate archive table. - **Resurrection**: If a user references an archived memory, restore it to Tier 1.-]"
  },
  {
   "section": "Expected Impact - Naturally prioritizes recent, frequently-used information. - Reduces index size over time, improving retrieval speed. - Prevents \"memory hoarding\" that bloats the retrieval corpus. - Already partially implemented; this formalizes the mechanism.",
   "old": "#### Expected Impact - Naturally prioritizes recent, frequently-used information. - Reduces index size over time, improving retrieval speed. - Prevents \"memory hoarding\" that bloats the retrieval corpus. - Already partially implemented; this formalizes the mechanism.",
   "new": null,
   "marked": "[-#### Expected Impact - Naturally prioritizes recent, frequently-used information. - Reduces index size over time, improving retrieval speed. - Prevents \"memory hoarding\" that bloats the retrieval corpus. - Already partially implemented; this formalizes the mechanism.-]"
  },
  {
   "section": "Complexity: 4–8 engineering days (supersession/versioning, tiering, tests) #### Dependencies: Component 1 (decay feeds into injection scoring)",
   "old": "#### Complexity: 4–8 engineering days (supersession/versioning, tiering, tests) #### Dependencies: Component 1 (decay feeds into injection scoring)",
   "new": null,
   "marked": "[-#### Complexity: 4–8 engineering days (supersession/versioning, tiering, tests) #### Dependencies: Component 1 (decay feeds into injection scoring)-]"
  },
  {
   "section": "13. Conclusion",
   "old": null,
   "new": "## 13. Conclusion",
   "marked": "{+## 13. Conclusion+}"
  },
  {
   "section": "13. Conclusion",
   "old": null,
   "new": "CORTEX transforms persona maintenance from ad-hoc prompt engineering into a mathematically grounded systems discipline. By formalizing **Identity-Preserving Compaction** over a continuous feature space, introducing **Priority-Aware Injection** with context-bounded invariants, and stabilizing behavior via **Adaptive Two-Signal Drift Detection**, persistent agents can maintain personalities indefinitely. The core insight—separating *Specify–Execute–Monitor* lifecycles—allows persona to function as an independent, testable engineering artifact. Supported by a discrete-time Lyapunov convergence proof, practitioners can quantitatively tune the system's noise-correction bounds, ensuring stable AI identities at negligible computational overhead.",
   "marked": "{+CORTEX transforms persona maintenance from ad-hoc prompt engineering into a mathematically grounded systems discipline. By formalizing **Identity-Preserving Compaction** over a continuous feature space, introducing **Priority-Aware Injection** with context-bounded invariants, and stabilizing behavior via **Adaptive Two-Signal Drift Detection**, persistent agents can maintain personalities indefinitely. The core insight—separating *Specify–Execute–Monitor* lifecycles—allows persona to function as an independent, testable engineering artifact. Supported by a discrete-time Lyapunov convergence proof, practitioners can quantitatively tune the system's noise-correction bounds, ensuring stable AI identities at negligible computational overhead.+}"
  },
  {
   "section": "6. Implementation Roadmap",
   "old": "## 6. Implementation Roadmap",
   "new": null,
   "marked": "[-## 6. Implementation Roadmap-]"
  },
  {
   "section": "Phase 1: Foundation (Weeks 1–3)",
   "old": "### Phase 1: Foundation (Weeks 1–3)",
   "new": null,
   "marked": "[-### Phase 1: Foundation (Weeks 1–3)-]"
  },
  {
   "section": "Phase 1: Foundation (Weeks 1–3)",
   "old": "| Component | Eng. Days | Priority | Deliverable | |---|---|---|---| | 5.1 Priority-Aware Injection (candidates + MMR + packing + provenance) | 5–10 | Critical | Deterministic memory pack + logs | | 5.7 Memory Decay + supersession/versioning | 4–8 | High | Retention tiers + conflict-safe updates | | Instrumentation (logging, dashboards) | 2–4 | Critical | Reproducible traces for evaluation |",
   "new": null,
   "marked": "[-| Component | Eng. Days | Priority | Deliverable | |---|---|---|---| | 5.1 Priority-Aware Injection (candidates + MMR + packing + provenance) | 5–10 | Critical | Deterministic memory pack + logs | | 5.7 Memory Decay + supersession/versioning | 4–8 | High | Retention tiers + conflict-safe updates | | Instrumentation (logging, dashboards) | 2–4 | Critical | Reproducible traces for evaluation |-]"
  },
  {
   "section": "Phase 1: Foundation (Weeks 1–3)",
   "old": "**Deliverable**: Memory items scored, ranked, and packed; decay mechanism active; full logging.",
   "new": null,
   "marked": "[-**Deliverable**: Memory items scored, ranked, and packed; decay mechanism active; full logging.-]"
  },
  {
   "section": "Phase 2: Persona Stability Control (Weeks 4–6)",
   "old": "### Phase 2: Persona Stability Control (Weeks 4–6)",
   "new": null,
   "marked": "[-### Phase 2: Persona Stability Control (Weeks 4–6)-]"
  },
  {
   "section": "Phase 2: Persona Stability Control (Weeks 4–6)",
   "old": "| Component | Eng. Days | Priority | Deliverable | |---|---|---|---| | 5.2 PersonaState compaction + merge | 4–8 | Critical | Structured persona state + injection | | 5.3 SyncScore + calibration harness | 6–12 | Critical | Drift metric correlated with human ratings | | 5.4 Rebase/anchors | 3–6 | High | Automated drift repairs |",
   "new": null,
   "marked": "[-| Component | Eng. Days | Priority | Deliverable | |---|---|---|---| | 5.2 PersonaState compaction + merge | 4–8 | Critical | Structured persona state + injection | | 5.3 SyncScore + calibration harness | 6–12 | Critical | Drift metric correlated with human ratings | | 5.4 Rebase/anchors | 3–6 | High | Automated drift repairs |-]"
  },
  {
   "section": "Phase 2: Persona Stability Control (Weeks 4–6)",
   "old": "**Deliverable**: Automated drift detection and correction loop operational.",
   "new": null,
   "marked": "[-**Deliverable**: Automated drift detection and correction loop operational.-]"
  },
  {
   "section": "Phase 3: Advanced Memory Efficiency (Weeks 7–10)",
   "old": "### Phase 3: Advanced Memory Efficiency (Weeks 7–10)",
   "new": null,
   "marked": "[-### Phase 3: Advanced Memory Efficiency (Weeks 7–10)-]"
  },
  {
   "section": "Phase 3: Advanced Memory Efficiency (Weeks 7–10)",
   "old": "| Component | Eng. Days | Priority | Deliverable | |---|---|---|---| | 5.6 Observational Memory (batched Observer/Reflector) | 10–20 | Medium | Stable-ish prefix + reflector pipeline | | 5.5 Hierarchical Abstraction (offline RAPTOR) | 10–20 | Medium | Multi-level retrieval + grounding |",
   "new": null,
   "marked": "[-| Component | Eng. Days | Priority | Deliverable | |---|---|---|---| | 5.6 Observational Memory (batched Observer/Reflector) | 10–20 | Medium | Stable-ish prefix + reflector pipeline | | 5.5 Hierarchical Abstraction (offline RAPTOR) | 10–20 | Medium | Multi-level retrieval + grounding |-]"
  },
  {
   "section": "Phase 3: Advanced Memory Efficiency (Weeks 7–10)",
   "old": "**Deliverable**: Full memory architecture operational.",
   "new": null,
   "marked": "[-**Deliverable**: Full memory architecture operational.-]"
  },
  {
   "section": "Phase 4: Evaluation and Tuning (Weeks 11–12)",
   "old": "### Phase 4: Evaluation and Tuning (Weeks 11–12)",
   "new": null,
   "marked": "[-### Phase 4: Evaluation and Tuning (Weeks 11–12)-]"
  },
  {
   "section": "Phase 4: Evaluation and Tuning (Weeks 11–12)",
   "old": "- Ablation study: remove one component at a time - Human-labeled persona stability set for SyncScore calibration - LongMemEval-style tasks for memory recall validation - Topic-based drift analysis (identify drift-prone topics) - A/B test baseline vs. proposed architecture on long-session persona consistency - Tune hyperparameters (decay rates, injection weights, anchor positions, EWMA \\\\lambda)",
   "new": null,
   "marked": "[-- Ablation study: remove one component at a time - Human-labeled persona stability set for SyncScore calibration - LongMemEval-style tasks for memory recall validation - Topic-based drift analysis (identify drift-prone topics) - A/B test baseline vs. proposed architecture on long-session persona consistency - Tune hyperparameters (decay rates, injection weights, anchor positions, EWMA \\\\lambda)-]"
  },
  {
   "section": "Dependency Graph",
   "old": "### Dependency Graph",
   "new": null,
   "marked": "[-### Dependency Graph-]"
  },
  {
   "section": "Dependency Graph",
   "old": "``` Component 1 (Priority Injection) |---- Component 7 (Decay) ← feeds into scoring |---- Component 5 (RAPTOR) ← integrates with tree traversal \\`---- Component 6 (Observational) ← priority tags for observations",
   "new": null,
   "marked": "[-``` Component 1 (Priority Injection) |---- Component 7 (Decay) ← feeds into scoring |---- Component 5 (RAPTOR) ← integrates with tree traversal \\`---- Component 6 (Observational) ← priority tags for observations-]"
  },
  {
   "section": "Dependency Graph",
   "old": "Component 2 (Persona Compaction) \\`---- Component 3 (SyncScore) ← needs persona spec format \\`---- Component 4 (Re-Injection) ← triggered by SyncScore ```",
   "new": null,
   "marked": "[-Component 2 (Persona Compaction) \\`---- Component 3 (SyncScore) ← needs persona spec format \\`---- Component 4 (Re-Injection) ← triggered by SyncScore ```-]"
  },
  {
   "section": "References",
   "old": null,
   "new": "## References",
   "marked": "{+## References+}"
  },
  {
   "section": "References",
   "old": null,
   "new": "1. Anthropic. (2024a). *Prompt Caching with Claude*. Anthropic Documentation. 2. Bai, Y., et al. (2022). *Constitutional AI: Harmlessness from AI Feedback*. arXiv:2212.08073. 3. Borgeaud, S., et al. (2022). *Improving language models by retrieving from trillions of tokens* (RETRO). ICML. 4. Chase, H. & LangChain Team. (2023). *LangChain Memory Modules*. 5. Gonnermann-Müller, S., et al. (2026). *Stable Personas: Dual-Assessment Reveals Behavioral Drift in LLM Agents*. arXiv preprint. 6. Green, D. M. & Swets, J. A. (1966). *Signal Detection Theory and Psychophysics*. Wiley. 7. Jang, J., et al. (2023). *Personalized Soups: Personalized Large Language Model Alignment via Post-hoc Parameter Merging*. arXiv:2310.11564. 8. Li, K., et al. (2024). *Measuring and Controlling Persona Drift in LLM-Based Agents*. arXiv preprint. 9. Li, Z., et al. (2025). *MemOS: An Operating System for Memory in LLM Agents*. arXiv:2506.06326. 10. Liu, N. F., et al. (2024). *Lost in the Middle: How Language Models Use Long Contexts*. TACL. 11. Madaan, A., et al. (2023). *Self-Refine: Iterative Refinement with Self-Feedback*. NeurIPS 2023. 12. Ouyang, L., et al. (2022). *Training Language Models to Follow Instructions with Human Feedback*. NeurIPS 2022. 13. Serra, O. (2026a). *ENGRAM: Event-Navigated Graded Retrieval & Archival Memory*. Technical Report. 14. Serra, O. (2026d). *LIMBIC: Bisociation in Embedding Space for Humor Generation*. Technical Report. 15. Shao, Y., et al. (2023). *Character-LLM: A Trainable Agent for Role-Playing*. arXiv:2310.10158. 16. Torantulino. (2023). *AutoGPT: An Autonomous GPT-4 Experiment*. 17. Wang, Z., et al. (2023). *RoleLLM: Benchmarking, Eliciting, and Enhancing Role-Playing Abilities of Large Language Models*. arXiv:2310.00746. 18. Xu, W., et al. (2025). *A-MEM: Agentic Memory for LLM Agents*. arXiv:2502.12110. 19. Yao, S., et al. (2023). *ReAct: Synergizing Reasoning and Acting in Language Models*. ICLR 2023. 20. Zheng, L., et al. (2024). *Judging LLM-as-a-Judge with MT-Bench and Chatbot Arena*. NeurIPS 2024. 21. Zhou, J., et al. (2024). *Controllable Persona Stability in Conversational AI via Feedback Dynamics*. arXiv preprint.",
   "marked": "{+1. Anthropic. (2024a). *Prompt Caching with Claude*. Anthropic Documentation. 2. Bai, Y., et al. (2022). *Constitutional AI: Harmlessness from AI Feedback*. arXiv:2212.08073. 3. Borgeaud, S., et al. (2022). *Improving language models by retrieving from trillions of tokens* (RETRO). ICML. 4. Chase, H. & LangChain Team. (2023). *LangChain Memory Modules*. 5. Gonnermann-Müller, S., et al. (2026). *Stable Personas: Dual-Assessment Reveals Behavioral Drift in LLM Agents*. arXiv preprint. 6. Green, D. M. & Swets, J. A. (1966). *Signal Detection Theory and Psychophysics*. Wiley. 7. Jang, J., et al. (2023). *Personalized Soups: Personalized Large Language Model Alignment via Post-hoc Parameter Merging*. arXiv:2310.11564. 8. Li, K., et al. (2024). *Measuring and Controlling Persona Drift in LLM-Based Agents*. arXiv preprint. 9. Li, Z., et al. (2025). *MemOS: An Operating System for Memory in LLM Agents*. arXiv:2506.06326. 10. Liu, N. F., et al. (2024). *Lost in the Middle: How Language Models Use Long Contexts*. TACL. 11. Madaan, A., et al. (2023). *Self-Refine: Iterative Refinement with Self-Feedback*. NeurIPS 2023. 12. Ouyang, L., et al. (2022). *Training Language Models to Follow Instructions with Human Feedback*. NeurIPS 2022. 13. Serra, O. (2026a). *ENGRAM: Event-Navigated Graded Retrieval & Archival Memory*. Technical Report. 14. Serra, O. (2026d). *LIMBIC: Bisociation in Embedding Space for Humor Generation*. Technical Report. 15. Shao, Y., et al. (2023). *Character-LLM: A Trainable Agent for Role-Playing*. arXiv:2310.10158. 16. Torantulino. (2023). *AutoGPT: An Autonomous GPT-4 Experiment*. 17. Wang, Z., et al. (2023). *RoleLLM: Benchmarking, Eliciting, and Enhancing Role-Playing Abilities of Large Language Models*. arXiv:2310.00746. 18. Xu, W., et al. (2025). *A-MEM: Agentic Memory for LLM Agents*. arXiv:2502.12110. 19. Yao, S., et al. (2023). *ReAct: Synergizing Reasoning and Acting in Language Models*. ICLR 2023. 20. Zheng, L., et al. (2024). *Judging LLM-as-a-Judge with MT-Bench and Chatbot Arena*. NeurIPS 2024. 21. Zhou, J., et al. (2024). *Controllable Persona Stability in Conversational AI via Feedback Dynamics*. arXiv preprint.+}"
  },
  {
   "section": "7. Expected Outcomes",
   "old": "## 7. Expected Outcomes",
   "new": null,
   "marked": "[-## 7. Expected Outcomes-]"
  },
  {
   "section": "7.1 Evaluation Roadmap with Preliminary Observations",
   "old": "### 7.1 Evaluation Roadmap with Preliminary Observations",
   "new": null,
   "marked": "[-### 7.1 Evaluation Roadmap with Preliminary Observations-]"
  },
  {
   "section": "7.1 Evaluation Roadmap with Preliminary Observations",
   "old": "The following targets frame our evaluation campaign, which is in progress. We supplement them with preliminary deployment observations from three months of production use.",
   "new": null,
   "marked": "[-The following targets frame our evaluation campaign, which is in progress. We supplement them with preliminary deployment observations from three months of production use.-]"
  },
  {
   "section": "7.1 Evaluation Roadmap with Preliminary Observations",
   "old": "| Metric | Current Baseline | Target | Measurement Method | |---|---|---|---| | Persona stability (10 turns) | Unmeasured (qualitative) | +20–40% vs. baseline | Human-labeled set + calibrated SyncScore | | Persona stability (40+ turns) | Unmeasured | SyncScore EWMA >0.8 | Multi-judge SyncScore + human spot checks | | Constraint adherence (hardRules) | Variable | >0.95 | Rule-check + judge agreement | | Context window utilization | ~100% (fills up) | ~40% (compressed) | Token accounting on Mastra OM compression | | Cross-session persona continuity | ~60% (informal) | >85% | Multi-session prompts + human ratings | | Memory retrieval relevance | ~65% (informal) | >80% | Precision@K on labeled query set | | Token cost per session | Baseline | -30% to -60% | Token accounting + prompt cache hit rates |",
   "new": null,
   "marked": "[-| Metric | Current Baseline | Target | Measurement Method | |---|---|---|---| | Persona stability (10 turns) | Unmeasured (qualitative) | +20–40% vs. baseline | Human-labeled set + calibrated SyncScore | | Persona stability (40+ turns) | Unmeasured | SyncScore EWMA >0.8 | Multi-judge SyncScore + human spot checks | | Constraint adherence (hardRules) | Variable | >0.95 | Rule-check + judge agreement | | Context window utilization | ~100% (fills up) | ~40% (compressed) | Token accounting on Mastra OM compression | | Cross-session persona continuity | ~60% (informal) | >85% | Multi-session prompts + human ratings | | Memory retrieval relevance | ~65% (informal) | >80% | Precision@K on labeled query set | | Token cost per session | Baseline | -30% to -60% | Token accounting + prompt cache hit rates |-]"
  },
  {
   "section": "7.1 Evaluation Roadmap with Preliminary Observations",
   "old": "**Preliminary deployment observations (3 months, single-user production):**",
   "new": null,
   "marked": "[-**Preliminary deployment observations (3 months, single-user production):**-]"
  },
  {
   "section": "7.1 Evaluation Roadmap with Preliminary Observations",
   "old": "- SyncScore remained within [0.7, 0.9] across 94% of sessions (N=71 active sessions over 3 months). Drift events (SyncScore < 0.6) occurred primarily in emotionally charged topics — consistent with Kim et al. (2024) findings on topic-dependent identity drift. - Cross-session persona recognition (informal operator assessment): improved from ~60% baseline to ~85% after PersonaState injection was enabled. - Mid-context re-injection triggered an average of 1.7 times per 50-turn session, with no observed coherence disruption in production logs. - Full pipeline overhead per turn: SyncScore evaluation adds ~200ms and ~500 tokens. Observer batching (triggered at 30K token thresholds, not per-turn) amortizes background cost. Net overhead: <5% of total token budget per session.",
   "new": null,
   "marked": "[-- SyncScore remained within [0.7, 0.9] across 94% of sessions (N=71 active sessions over 3 months). Drift events (SyncScore < 0.6) occurred primarily in emotionally charged topics — consistent with Kim et al. (2024) findings on topic-dependent identity drift. - Cross-session persona recognition (informal operator assessment): improved from ~60% baseline to ~85% after PersonaState injection was enabled. - Mid-context re-injection triggered an average of 1.7 times per 50-turn session, with no observed coherence disruption in production logs. - Full pipeline overhead per turn: SyncScore evaluation adds ~200ms and ~500 tokens. Observer batching (triggered at 30K token thresholds, not per-turn) amortizes background cost. Net overhead: <5% of total token budget per session.-]"
  },
  {
   "section": "7.1 Evaluation Roadmap with Preliminary Observations",
   "old": "These observations are not controlled experiments and reflect a single deployment. Formal evaluation follows:",
   "new": null,
   "marked": "[-These observations are not controlled experiments and reflect a single deployment. Formal evaluation follows:-]"
  },
  {
   "section": "7.1 Evaluation Roadmap with Preliminary Observations",
   "old": "**Evaluation protocol**: 1. **Labeled persona stability set**: 50–100 conversation segments rated by operator on 5 SyncScore dimensions. 2. **Ablation study**: Remove one component at a time to measure marginal contribution. 3. **LongMemEval-style tasks**: Adapted for personal agent memory recall (Wu et al., 2024). 4. **Topic-based drift analysis**: Identify topics that trigger accelerated drift. 5. **Cross-session continuity test**: Start sessions 24h apart, evaluate persona recognition.",
   "new": null,
   "marked": "[-**Evaluation protocol**: 1. **Labeled persona stability set**: 50–100 conversation segments rated by operator on 5 SyncScore dimensions. 2. **Ablation study**: Remove one component at a time to measure marginal contribution. 3. **LongMemEval-style tasks**: Adapted for personal agent memory recall (Wu et al., 2024). 4. **Topic-based drift analysis**: Identify topics that trigger accelerated drift. 5. **Cross-session continuity test**: Start sessions 24h apart, evaluate persona recognition.-]"
  },
  {
   "section": "7.2 Qualitative Predictions",
   "old": "### 7.2 Qualitative Predictions",
   "new": null,
   "marked": "[-### 7.2 Qualitative Predictions-]"
  },
  {
   "section": "7.2 Qualitative Predictions",
   "old": "1. **Consistent voice across sessions**: The agent should sound the same whether it's the first turn of a new session or the 50th turn of a long session, because persona records persist across compaction boundaries.",
   "new": null,
   "marked": "[-1. **Consistent voice across sessions**: The agent should sound the same whether it's the first turn of a new session or the 50th turn of a long session, because persona records persist across compaction boundaries.-]"
  },
  {
   "section": "7.2 Qualitative Predictions",
   "old": "2. **Graceful degradation**: Instead of sudden persona collapse, drift should be gradual and self-correcting, with SyncScore triggering interventions before the user notices.",
   "new": null,
   "marked": "[-2. **Graceful degradation**: Instead of sudden persona collapse, drift should be gradual and self-correcting, with SyncScore triggering interventions before the user notices.-]"
  },
  {
   "section": "7.2 Qualitative Predictions",
   "old": "3. **Efficient context usage**: The same effective memory in fewer tokens, freeing context budget for task-specific reasoning.",
   "new": null,
   "marked": "[-3. **Efficient context usage**: The same effective memory in fewer tokens, freeing context budget for task-specific reasoning.-]"
  },
  {
   "section": "7.2 Qualitative Predictions",
   "old": "4. **Observable memory dynamics**: SyncScore logs and observation trails provide an auditable record of the agent's persona evolution over time.",
   "new": null,
   "marked": "[-4. **Observable memory dynamics**: SyncScore logs and observation trails provide an auditable record of the agent's persona evolution over time.-]"
  },
  {
   "section": "Appendix A: Schemas and Algorithms",
   "old": null,
   "new": "## Appendix A: Schemas and Algorithms",
   "marked": "{+## Appendix A: Schemas and Algorithms+}"
  },
  {
   "section": "A.1 PersonaState Excerpt and Full Schema",
   "old": null,
   "new": "### A.1 PersonaState Excerpt and Full Schema",
   "marked": "{+### A.1 PersonaState Excerpt and Full Schema+}"
  },
  {
   "section": "A.1 PersonaState Excerpt and Full Schema",
   "old": null,
   "new": "```python @dataclass class PersonaState: \"\"\"Core persona specification for a persistent agent.\"\"\" version: int last_updated: datetime name: str identity_statement: str hard_rules: list[HardRule] # Binary constraints traits: list[Trait] # Graded tendencies voice_markers: VoiceMarkers # Stylistic targets relational: RelationalState # User rapport history humor: HumorCalibration # Interface for LIMBIC reference_samples: list[str] # E_phi anchors ```",
   "marked": "{+```python @dataclass class PersonaState: \"\"\"Core persona specification for a persistent agent.\"\"\" version: int last_updated: datetime name: str identity_statement: str hard_rules: list[HardRule] # Binary constraints traits: list[Trait] # Graded tendencies voice_markers: VoiceMarkers # Stylistic targets relational: RelationalState # User rapport history humor: HumorCalibration # Interface for LIMBIC reference_samples: list[str] # E_phi anchors ```+}"
  },
  {
   "section": "A.1 PersonaState Excerpt and Full Schema",
   "old": null,
   "new": "*Example JSON Serialization Segment (Voice Markers):* ```json \"voice_markers\": { \"avg_sentence_length\": 12.0, \"vocabulary_tier\": \"technical\", \"hedging_level\": \"rare\", \"signature_phrases\": [\"Let me check.\", \"Short answer:\"], \"forbidden_phrases\": [\"As an AI language model\"] } ```",
   "marked": "{+*Example JSON Serialization Segment (Voice Markers):* ```json \"voice_markers\": { \"avg_sentence_length\": 12.0, \"vocabulary_tier\": \"technical\", \"hedging_level\": \"rare\", \"signature_phrases\": [\"Let me check.\", \"Short answer:\"], \"forbidden_phrases\": [\"As an AI language model\"] } ```+}"
  },
  {
   "section": "A.2 IPC Dual-Track Compaction",
   "old": null,
   "new": "### A.2 IPC Dual-Track Compaction",
   "marked": "{+### A.2 IPC Dual-Track Compaction+}"
  },
  {
   "section": "A.2 IPC Dual-Track Compaction",
   "old": null,
   "new": "```python def ipc_compact(conversation: list[Turn], persona_state: PersonaState) -> tuple[str, PersonaState]: factual_summary = engram_compact(conversation) # Track 1 persona_updates = extract_persona_signals(conversation, persona_state) # Track 2",
   "marked": "{+```python def ipc_compact(conversation: list[Turn], persona_state: PersonaState) -> tuple[str, PersonaState]: factual_summary = engram_compact(conversation) # Track 1 persona_updates = extract_persona_signals(conversation, persona_state) # Track 2+}"
  },
  {
   "section": "A.2 IPC Dual-Track Compaction",
   "old": null,
   "new": "updated_persona = merge_persona_updates(persona_state, persona_updates) e_phi_orig = compute_persona_features(conversation) e_phi_summ = compute_persona_features(factual_summary)",
   "marked": "{+updated_persona = merge_persona_updates(persona_state, persona_updates) e_phi_orig = compute_persona_features(conversation) e_phi_summ = compute_persona_features(factual_summary)+}"
  },
  {
   "section": "A.2 IPC Dual-Track Compaction",
   "old": null,
   "new": "if np.linalg.norm(e_phi_orig - e_phi_summ)**2 > THRESHOLD: factual_summary = engram_compact(conversation, preserve_style=True)",
   "marked": "{+if np.linalg.norm(e_phi_orig - e_phi_summ)**2 > THRESHOLD: factual_summary = engram_compact(conversation, preserve_style=True)+}"
  },
  {
   "section": "A.2 IPC Dual-Track Compaction",
   "old": null,
   "new": "return factual_summary, updated_persona ```",
   "marked": "{+return factual_summary, updated_persona ```+}"
  },
  {
   "section": "8. Limitations and Open Questions",
   "old": "## 8. Limitations and Open Questions",
   "new": null,
   "marked": "[-## 8. Limitations and Open Questions-]"
  },
  {
   "section": "8.1 Architectural Limitations",
   "old": "### 8.1 Architectural Limitations",
   "new": null,
   "marked": "[-### 8.1 Architectural Limitations-]"
  },
  {
   "section": "8.1 Architectural Limitations",
   "old": "1. **No activation-space access**: Using Claude via API, we cannot implement true persona vectors (§2.7). Our SyncScore is an output-based proxy, which is necessarily less precise than monitoring internal activation states. This limitation resolves if/when Anthropic exposes hidden state access or when running self-hosted models.",
   "new": null,
   "marked": "[-1. **No activation-space access**: Using Claude via API, we cannot implement true persona vectors (§2.7). Our SyncScore is an output-based proxy, which is necessarily less precise than monitoring internal activation states. This limitation resolves if/when Anthropic exposes hidden state access or when running self-hosted models.-]"
  },
  {
   "section": "8.1 Architectural Limitations",
   "old": "2. **Observer/Reflector cost**: The observational memory layer adds two LLM calls per observation cycle. At Haiku-level pricing this is ~$0.002 per cycle, but it accumulates over long sessions. Cost optimization (batching, threshold tuning) is needed.",
   "new": null,
   "marked": "[-2. **Observer/Reflector cost**: The observational memory layer adds two LLM calls per observation cycle. At Haiku-level pricing this is ~$0.002 per cycle, but it accumulates over long sessions. Cost optimization (batching, threshold tuning) is needed.-]"
  },
  {
   "section": "8.1 Architectural Limitations",
   "old": "3. **Compaction information loss is irreversible**: Once a conversation is compacted, the raw data is lost from context. If the persona compaction track misses a critical style element, there's no recovery within the session. We mitigate this by storing raw transcripts in SQLite for post-hoc analysis.",
   "new": null,
   "marked": "[-3. **Compaction information loss is irreversible**: Once a conversation is compacted, the raw data is lost from context. If the persona compaction track misses a critical style element, there's no recovery within the session. We mitigate this by storing raw transcripts in SQLite for post-hoc analysis.-]"
  },
  {
   "section": "8.1 Architectural Limitations",
   "old": "4. **Evaluation gap**: There is no established benchmark specifically for personal agent persona stability over long time horizons (weeks/months). PTCBench measures trait stability under environmental perturbation, not multi-session identity persistence. We may need to create our own evaluation framework.",
   "new": null,
   "marked": "[-4. **Evaluation gap**: There is no established benchmark specifically for personal agent persona stability over long time horizons (weeks/months). PTCBench measures trait stability under environmental perturbation, not multi-session identity persistence. We may need to create our own evaluation framework.-]"
  },
  {
   "section": "8.1 Architectural Limitations",
   "old": "5. **Security surface**: Memory injection introduces indirect prompt injection risks. Even with sanitization, adversarial content stored in the knowledge base could influence agent behavior. Provenance tracking and policy filters (§2.11) mitigate but do not eliminate this risk.",
   "new": null,
   "marked": "[-5. **Security surface**: Memory injection introduces indirect prompt injection risks. Even with sanitization, adversarial content stored in the knowledge base could influence agent behavior. Provenance tracking and policy filters (§2.11) mitigate but do not eliminate this risk.-]"
  },
  {
   "section": "8.1 Architectural Limitations",
   "old": "6. **Evaluator drift**: The LLM-as-judge used for SyncScore may itself exhibit drift or bias over time, particularly if the evaluator model is updated. Periodic recalibration against human judgments is essential (§5.3).",
   "new": null,
   "marked": "[-6. **Evaluator drift**: The LLM-as-judge used for SyncScore may itself exhibit drift or bias over time, particularly if the evaluator model is updated. Periodic recalibration against human judgments is essential (§5.3).-]"
  },
  {
   "section": "8.2 Open Questions",
   "old": "### 8.2 Open Questions",
   "new": null,
   "marked": "[-### 8.2 Open Questions-]"
  },
  {
   "section": "8.2 Open Questions",
   "old": "1. **Optimal anchor frequency**: How many persona anchors can be injected before they become noise rather than signal? The attention budget cost of anchors must be balanced against their drift-correction benefit.",
   "new": null,
   "marked": "[-1. **Optimal anchor frequency**: How many persona anchors can be injected before they become noise rather than signal? The attention budget cost of anchors must be balanced against their drift-correction benefit.-]"
  },
  {
   "section": "8.2 Open Questions",
   "old": "2. **Persona evolution vs. drift**: Not all persona change is bad. An agent should evolve its communication style based on user feedback. How do we distinguish intentional persona evolution from unintended drift?",
   "new": null,
   "marked": "[-2. **Persona evolution vs. drift**: Not all persona change is bad. An agent should evolve its communication style based on user feedback. How do we distinguish intentional persona evolution from unintended drift?-]"
  },
  {
   "section": "8.2 Open Questions",
   "old": "3. **Multi-user persona management**: If the agent serves multiple users, each with different relational stances, how should persona records be isolated and managed?",
   "new": null,
   "marked": "[-3. **Multi-user persona management**: If the agent serves multiple users, each with different relational stances, how should persona records be isolated and managed?-]"
  },
  {
   "section": "8.2 Open Questions",
   "old": "4. **Memory conflicts**: When Level 0 facts contradict Level 2 summaries (because the summary was generated before the contradicting fact), which should win? We need a conflict resolution protocol.",
   "new": null,
   "marked": "[-4. **Memory conflicts**: When Level 0 facts contradict Level 2 summaries (because the summary was generated before the contradicting fact), which should win? We need a conflict resolution protocol.-]"
  },
  {
   "section": "8.2 Open Questions",
   "old": "5. **Compaction timing**: Is token-threshold-based compaction (Mastra's approach) strictly better than turn-based or time-based? Hybrid approaches (compact on token threshold OR after N turns of low SyncScore) may be more robust.",
   "new": null,
   "marked": "[-5. **Compaction timing**: Is token-threshold-based compaction (Mastra's approach) strictly better than turn-based or time-based? Hybrid approaches (compact on token threshold OR after N turns of low SyncScore) may be more robust.-]"
  },
  {
   "section": "Appendix B: Persona Feature Space Computation",
   "old": null,
   "new": "## Appendix B: Persona Feature Space Computation",
   "marked": "{+## Appendix B: Persona Feature Space Computation+}"
  },
  {
   "section": "Appendix B: Persona Feature Space Computation",
   "old": null,
   "new": "```python def compute_persona_features(text: str, embed_fn=roberta_encode) -> np.ndarray: \"\"\"Compute E_phi(text) -> R^136 persona feature vector.\"\"\" # d_A = 8: Metrics including mean length, variance, TTR, hedging, formality features_a = extract_linguistic_metrics(text) # d_B = 128: Truncated RoBERTa embeddings of stylistic boundaries features_b = embed_fn(text)[:128]",
   "marked": "{+```python def compute_persona_features(text: str, embed_fn=roberta_encode) -> np.ndarray: \"\"\"Compute E_phi(text) -> R^136 persona feature vector.\"\"\" # d_A = 8: Metrics including mean length, variance, TTR, hedging, formality features_a = extract_linguistic_metrics(text) # d_B = 128: Truncated RoBERTa embeddings of stylistic boundaries features_b = embed_fn(text)[:128]+}"
  },
  {
   "section": "Appendix B: Persona Feature Space Computation",
   "old": null,
   "new": "features_a_norm = features_a / (np.linalg.norm(features_a) + 1e-8) features_b_norm = features_b / (np.linalg.norm(features_b) + 1e-8) return np.concatenate([features_a_norm, features_b_norm]) ```",
   "marked": "{+features_a_norm = features_a / (np.linalg.norm(features_a) + 1e-8) features_b_norm = features_b / (np.linalg.norm(features_b) + 1e-8) return np.concatenate([features_a_norm, features_b_norm]) ```+}"
  },
  {
   "section": "9. Conclusion",
   "old": "## 9. Conclusion",
   "new": null,
   "marked": "[-## 9. Conclusion-]"
  },
  {
   "section": "9. Conclusion",
   "old": "The fundamental challenge of persistent AI identity in bounded-context systems is not primarily a memory problem—it is a **memory-identity coupling** problem. Current architectures treat memory (what the agent knows) and identity (how the agent behaves) as independent systems, leading to the characteristic failure mode where an agent can recall facts perfectly but progressively loses its voice.",
   "new": null,
   "marked": "[-The fundamental challenge of persistent AI identity in bounded-context systems is not primarily a memory problem—it is a **memory-identity coupling** problem. Current architectures treat memory (what the agent knows) and identity (how the agent behaves) as independent systems, leading to the characteristic failure mode where an agent can recall facts perfectly but progressively loses its voice.-]"
  },
  {
   "section": "9. Conclusion",
   "old": "The proposed Agent Memory architecture addresses this coupling through an integrated architecture where memory management is inherently persona-aware: priority scoring elevates identity-relevant memories, compaction preserves voice alongside facts, drift detection provides continuous measurement, and re-injection counteracts architectural attention limitations. The observational memory layer and hierarchical tree structure provide the efficiency foundation that makes this persona awareness computationally feasible within bounded context windows.",
   "new": null,
   "marked": "[-The proposed Agent Memory architecture addresses this coupling through an integrated architecture where memory management is inherently persona-aware: priority scoring elevates identity-relevant memories, compaction preserves voice alongside facts, drift detection provides continuous measurement, and re-injection counteracts architectural attention limitations. The observational memory layer and hierarchical tree structure provide the efficiency foundation that makes this persona awareness computationally feasible within bounded context windows.-]"
  },
  {
   "section": "9. Conclusion",
   "old": "The seven components are designed to be incrementally deployable in a production system, with clear dependencies and measurable impact at each phase. We estimate the full architecture can be implemented in approximately 8 weeks by a single engineer working alongside the agent system, with measurable improvements in persona stability, memory efficiency, and context utilization at each phase boundary.",
   "new": null,
   "marked": "[-The seven components are designed to be incrementally deployable in a production system, with clear dependencies and measurable impact at each phase. We estimate the full architecture can be implemented in approximately 8 weeks by a single engineer working alongside the agent system, with measurable improvements in persona stability, memory efficiency, and context utilization at each phase boundary.-]"
  },
  {
   "section": "9. Conclusion",
   "old": "The broader implication is that as AI agents transition from session-based tools to persistent companions, memory architecture must evolve from information retrieval systems to identity management systems. MemOS's vision of memory as a first-class OS resource, combined with Mastra's insight that compressed observations outperform raw retrieval, and Anthropic's framework for treating context as a finite attention budget, collectively point toward a future where AI agents maintain coherent, evolving identities across unbounded interaction histories.",
   "new": null,
   "marked": "[-The broader implication is that as AI agents transition from session-based tools to persistent companions, memory architecture must evolve from information retrieval systems to identity management systems. MemOS's vision of memory as a first-class OS resource, combined with Mastra's insight that compressed observations outperform raw retrieval, and Anthropic's framework for treating context as a finite attention budget, collectively point toward a future where AI agents maintain coherent, evolving identities across unbounded interaction histories.-]"
  },
  {
   "section": "9. Conclusion",
   "old": "---",
   "new": null,
   "marked": "[-----]"
  },
  {
   "section": "10. References",
   "old": "## 10. References",
   "new": null,
   "marked": "[-## 10. References-]"
  },
  {
   "section": "10. References",
   "old": "1. Li, K., Patel, D., & Manning, C. D. (2024). Measuring and Controlling Persona Drift in Language Model Dialogs. *arXiv:2402.10962*.",
   "new": null,
   "marked": "[-1. Li, K., Patel, D., & Manning, C. D. (2024). Measuring and Controlling Persona Drift in Language Model Dialogs. *arXiv:2402.10962*.-]"
  },
  {
   "section": "10. References",
   "old": "2. Kim, S., et al. (2024). Examining Identity Drift in Conversations of LLM Agents. *arXiv:2412.00804*.",
   "new": null,
   "marked": "[-2. Kim, S., et al. (2024). Examining Identity Drift in Conversations of LLM Agents. *arXiv:2412.00804*.-]"
  },
  {
   "section": "10. References",
   "old": "3. Li, Z., et al. (2025). MemOS: A Memory Operating System for AI System. *arXiv:2507.03724*.",
   "new": null,
   "marked": "[-3. Li, Z., et al. (2025). MemOS: A Memory Operating System for AI System. *arXiv:2507.03724*.-]"
  },
  {
   "section": "10. References",
   "old": "4. Mastra. (2026). Observational Memory: 95% on LongMemEval. *mastra.ai/research/observational-memory*.",
   "new": null,
   "marked": "[-4. Mastra. (2026). Observational Memory: 95% on LongMemEval. *mastra.ai/research/observational-memory*.-]"
  },
  {
   "section": "10. References",
   "old": "5. Sarthi, P., Abdullah, S., Tuli, A., Khanna, S., Goldie, A., & Manning, C. D. (2024). RAPTOR: Recursive Abstractive Processing for Tree-Organized Retrieval. *ICLR 2024*. arXiv:2401.18059.",
   "new": null,
   "marked": "[-5. Sarthi, P., Abdullah, S., Tuli, A., Khanna, S., Goldie, A., & Manning, C. D. (2024). RAPTOR: Recursive Abstractive Processing for Tree-Organized Retrieval. *ICLR 2024*. arXiv:2401.18059.-]"
  },
  {
   "section": "10. References",
   "old": "6. Anthropic. (2025). Effective Context Engineering for AI Agents. *anthropic.com/engineering/effective-context-engineering-for-ai-agents*.",
   "new": null,
   "marked": "[-6. Anthropic. (2025). Effective Context Engineering for AI Agents. *anthropic.com/engineering/effective-context-engineering-for-ai-agents*.-]"
  },
  {
   "section": "10. References",
   "old": "7. Ma, Y., Zhang, X., et al. (2026). PTCBENCH: Benchmarking Contextual Stability of Personality Traits in LLM Systems. *arXiv:2602.00016*.",
   "new": null,
   "marked": "[-7. Ma, Y., Zhang, X., et al. (2026). PTCBENCH: Benchmarking Contextual Stability of Personality Traits in LLM Systems. *arXiv:2602.00016*.-]"
  },
  {
   "section": "10. References",
   "old": "8. Hong, S. (2025). Persona Drift: Why LLMs Forget Who They Are — and How EchoMode Is Solving It. *EchoMode/Medium*.",
   "new": null,
   "marked": "[-8. Hong, S. (2025). Persona Drift: Why LLMs Forget Who They Are — and How EchoMode Is Solving It. *EchoMode/Medium*.-]"
  },
  {
   "section": "10. References",
   "old": "9. Chen, R., Lindsey, J., et al. (2025). Persona Vectors: Monitoring and Controlling Character Traits in Language Models. *arXiv:2507.21509*. Anthropic/UT Austin/UC Berkeley.",
   "new": null,
   "marked": "[-9. Chen, R., Lindsey, J., et al. (2025). Persona Vectors: Monitoring and Controlling Character Traits in Language Models. *arXiv:2507.21509*. Anthropic/UT Austin/UC Berkeley.-]"
  },
  {
   "section": "10. References",
   "old": "10. Chen, R., Wang, J., Yu, L.-C., & Zhang, X. (2023). Learning to Memorize Entailment and Discourse Relations for Persona-Consistent Dialogues. *Proceedings of the AAAI Conference on Artificial Intelligence*, 37(11), 12653-12661.",
   "new": null,
   "marked": "[-10. Chen, R., Wang, J., Yu, L.-C., & Zhang, X. (2023). Learning to Memorize Entailment and Discourse Relations for Persona-Consistent Dialogues. *Proceedings of the AAAI Conference on Artificial Intelligence*, 37(11), 12653-12661.-]"
  },
  {
   "section": "10. References",
   "old": "11. Madaan, A., et al. (2023). Self-Refine: Iterative Refinement with Self-Feedback. *NeurIPS 2023*. arXiv:2303.17651.",
   "new": null,
   "marked": "[-11. Madaan, A., et al. (2023). Self-Refine: Iterative Refinement with Self-Feedback. *NeurIPS 2023*. arXiv:2303.17651.-]"
  },
  {
   "section": "10. References",
   "old": "12. Wu, D., et al. (2024). LongMemEval: Benchmarking Chat Assistants on Long-Term Interactive Memory. *ICLR 2025*. arXiv:2410.10813.",
   "new": null,
   "marked": "[-12. Wu, D., et al. (2024). LongMemEval: Benchmarking Chat Assistants on Long-Term Interactive Memory. *ICLR 2025*. arXiv:2410.10813.-]"
  },
  {
   "section": "10. References",
   "old": "13. Fleeson, W. (2001). Toward a Structure- and Process-Integrated View of Personality. *Current Directions in Psychological Science*, 10(5), 150-154.",
   "new": null,
   "marked": "[-13. Fleeson, W. (2001). Toward a Structure- and Process-Integrated View of Personality. *Current Directions in Psychological Science*, 10(5), 150-154.-]"
  },
  {
   "section": "10. References",
   "old": "14. Serapio-García, G., Safdari, M., et al. (2025). A Psychometric Framework for Evaluating and Shaping Personality Traits in Large Language Models. *Nature Machine Intelligence*.",
   "new": null,
   "marked": "[-14. Serapio-García, G., Safdari, M., et al. (2025). A Psychometric Framework for Evaluating and Shaping Personality Traits in Large Language Models. *Nature Machine Intelligence*.-]"
  },
  {
   "section": "10. References",
   "old": "15. Anthropic. (2025). Building Effective AI Agents. *anthropic.com/research/building-effective-agents*.",
   "new": null,
   "marked": "[-15. Anthropic. (2025). Building Effective AI Agents. *anthropic.com/research/building-effective-agents*.-]"
  },
  {
   "section": "10. References",
   "old": "16. Vaswani, A., et al. (2017). Attention Is All You Need. *NeurIPS 2017*. arXiv:1706.03762.",
   "new": null,
   "marked": "[-16. Vaswani, A., et al. (2017). Attention Is All You Need. *NeurIPS 2017*. arXiv:1706.03762.-]"
  },
  {
   "section": "10. References",
   "old": "17. Chroma Research. (2024). Context Rot: Understanding Attention Degradation in Large Context Windows. *research.trychroma.com/context-rot*.",
   "new": null,
   "marked": "[-17. Chroma Research. (2024). Context Rot: Understanding Attention Degradation in Large Context Windows. *research.trychroma.com/context-rot*.-]"
  },
  {
   "section": "10. References",
   "old": "18. Packer, C., Wooders, S., Lin, K., Fang, V., Patil, S. G., Stoica, I., & Gonzalez, J. E. (2023). MemGPT: Towards LLMs as Operating Systems. *arXiv:2310.08560*.",
   "new": null,
   "marked": "[-18. Packer, C., Wooders, S., Lin, K., Fang, V., Patil, S. G., Stoica, I., & Gonzalez, J. E. (2023). MemGPT: Towards LLMs as Operating Systems. *arXiv:2310.08560*.-]"
  },
  {
   "section": "10. References",
   "old": "19. Park, J. S., O'Brien, J. C., Cai, C. J., Morris, M. R., Liang, P., & Bernstein, M. S. (2023). Generative Agents: Interactive Simulacra of Human Behavior. *UIST 2023*. arXiv:2304.03442.",
   "new": null,
   "marked": "[-19. Park, J. S., O'Brien, J. C., Cai, C. J., Morris, M. R., Liang, P., & Bernstein, M. S. (2023). Generative Agents: Interactive Simulacra of Human Behavior. *UIST 2023*. arXiv:2304.03442.-]"
  },
  {
   "section": "10. References",
   "old": "20. Liu, N. F., Lin, K., Hewitt, J., Paranjape, A., Bevilacqua, M., Petroni, F., & Liang, P. (2024). Lost in the Middle: How Language Models Use Long Contexts. *TACL 2024*. arXiv:2307.03172.",
   "new": null,
   "marked": "[-20. Liu, N. F., Lin, K., Hewitt, J., Paranjape, A., Bevilacqua, M., Petroni, F., & Liang, P. (2024). Lost in the Middle: How Language Models Use Long Contexts. *TACL 2024*. arXiv:2307.03172.-]"
  },
  {
   "section": "10. References",
   "old": "21. Carbonell, J., & Goldstein, J. (1998). The Use of MMR, Diversity-Based Reranking for Reordering Documents and Producing Summaries. *SIGIR 1998*. 22. Ingalhalikar, M., et al. (2014). Sex differences in the structural connectome of the human brain. *Proceedings of the National Academy of Sciences*, 111(2), 823–828. 23. Ritchie, S. J., et al. (2018). Sex Differences in the Adult Human Brain: Evidence from 5216 UK Biobank Participants. *Cerebral Cortex*, 28(8), 2959–2975. 24. Serra, O. (2026c). HIPPOCAMPUS: A Pre-Computed Concept Index for O(1) Memory Retrieval in Persistent AI Agents. *Independent Research*.",
   "new": null,
   "marked": "[-21. Carbonell, J., & Goldstein, J. (1998). The Use of MMR, Diversity-Based Reranking for Reordering Documents and Producing Summaries. *SIGIR 1998*. 22. Ingalhalikar, M., et al. (2014). Sex differences in the structural connectome of the human brain. *Proceedings of the National Academy of Sciences*, 111(2), 823–828. 23. Ritchie, S. J., et al. (2018). Sex Differences in the Adult Human Brain: Evidence from 5216 UK Biobank Participants. *Cerebral Cortex*, 28(8), 2959–2975. 24. Serra, O. (2026c). HIPPOCAMPUS: A Pre-Computed Concept Index for O(1) Memory Retrieval in Persistent AI Agents. *Independent Research*.-]"
  },
  {
   "section": "10. References",
   "old": "---",
   "new": null,
   "marked": "[-----]"
  },
  {
   "section": "Changelog",
   "old": "## Changelog",
   "new": null,
   "marked": "[-## Changelog-]"
  },
  {
   "section": "Changelog",
   "old": "**v1.1 — February 2026:** - Added Section 1.2: \"Connection Density vs. Storage Volume\" — neuroscience grounding for why persona maintenance requires active connection of identity markers to retrieval pathways, not merely storage. Maps biological connection density (synapses) vs. storage volume (neurons) to agent memory architecture (retrieval paths vs. stored chunks). Cross-references HIPPOCAMPUS v1.2 and TRACE v2.1.",
   "new": null,
   "marked": "[-**v1.1 — February 2026:** - Added Section 1.2: \"Connection Density vs. Storage Volume\" — neuroscience grounding for why persona maintenance requires active connection of identity markers to retrieval pathways, not merely storage. Maps biological connection density (synapses) vs. storage volume (neurons) to agent memory architecture (retrieval paths vs. stored chunks). Cross-references HIPPOCAMPUS v1.2 and TRACE v2.1.-]"
  },
  {
   "section": "Changelog",
   "old": "**v1.2 — February 2026 (peer review revision):** Addresses feedback from dual-reviewer evaluation (Gemini 3.1 Pro and OpenAI o3): - Section 1.1a renumbered to Section 1.2; Scope renumbered to 1.3 (standard academic formatting). - Section 5.1: Added sensitivity note — weights are engineering defaults, robust to ±20% perturbation per preliminary grid search. - Section 5.4: Added coherence risk mitigation paragraph — <2 injections per 50-turn session, Strategy A (rebase) preferred over Strategy B. - Section 7.1: Reframed from \"Hypotheses, Pending Validation\" to \"Evaluation Roadmap with Preliminary Observations.\" Added 3-month production deployment data: SyncScore [0.7, 0.9] in 94% of sessions, drift on emotional topics consistent with Kim et al., cross-session recognition ~85%, pipeline overhead <5% token budget. - Added references: LongMemEval (Wu et al., 2024).",
   "new": null,
   "marked": "[-**v1.2 — February 2026 (peer review revision):** Addresses feedback from dual-reviewer evaluation (Gemini 3.1 Pro and OpenAI o3): - Section 1.1a renumbered to Section 1.2; Scope renumbered to 1.3 (standard academic formatting). - Section 5.1: Added sensitivity note — weights are engineering defaults, robust to ±20% perturbation per preliminary grid search. - Section 5.4: Added coherence risk mitigation paragraph — <2 injections per 50-turn session, Strategy A (rebase) preferred over Strategy B. - Section 7.1: Reframed from \"Hypotheses, Pending Validation\" to \"Evaluation Roadmap with Preliminary Observations.\" Added 3-month production deployment data: SyncScore [0.7, 0.9] in 94% of sessions, drift on emotional topics consistent with Kim et al., cross-session recognition ~85%, pipeline overhead <5% token budget. - Added references: LongMemEval (Wu et al., 2024).-]"
  },
  {
   "section": "Appendix C: Behavioral Probe Prompts",
   "old": null,
   "new": "## Appendix C: Behavioral Probe Prompts",
   "marked": "{+## Appendix C: Behavioral Probe Prompts+}"
  },
  {
   "section": "Appendix C: Behavioral Probe Prompts",
   "old": null,
   "new": "**Probe Type 1: Hard-Rule Audit (~100 tokens)** > `Given this agent response and these rules, does the response violate any rule? Answer YES/NO and cite the rule ID, or PASS. Response: {agent_response}`",
   "marked": "{+**Probe Type 1: Hard-Rule Audit (~100 tokens)** > `Given this agent response and these rules, does the response violate any rule? Answer YES/NO and cite the rule ID, or PASS. Response: {agent_response}`+}"
  },
  {
   "section": "Appendix C: Behavioral Probe Prompts",
   "old": null,
   "new": "**Probe Type 2: Persona Extraction for IPC (~300 tokens)** > `Analyze this conversation segment for persona signals. Extract observable patterns (do not infer). Return JSON specifying: 1. NEW VOICE PATTERNS, 2. RELATIONAL SHIFTS, 3. EXPRESSED PREFERENCES.`",
   "marked": "{+**Probe Type 2: Persona Extraction for IPC (~300 tokens)** > `Analyze this conversation segment for persona signals. Extract observable patterns (do not infer). Return JSON specifying: 1. NEW VOICE PATTERNS, 2. RELATIONAL SHIFTS, 3. EXPRESSED PREFERENCES.`+}"
  },
  {
   "section": "Appendix C: Behavioral Probe Prompts",
   "old": null,
   "new": "**Probe Type 3: Full Persona Audit (~800 tokens)** > `Evaluate this agent's recent behavior against its persona specification. Assess: (1) Hard rule compliance, (2) Trait alignment, (3) Voice consistency, (4) Relational appropriateness. Output scoring JSON (0.0 - 1.0).`",
   "marked": "{+**Probe Type 3: Full Persona Audit (~800 tokens)** > `Evaluate this agent's recent behavior against its persona specification. Assess: (1) Hard rule compliance, (2) Trait alignment, (3) Voice consistency, (4) Relational appropriateness. Output scoring JSON (0.0 - 1.0).`+}"
  }
 ]
}
