# Deep Think: Memory Upgrade — Context-Aware Memory Injection

**Topic**: `context_aware_injection`
**Cycle**: 1
**Model**: gemini-2.5-pro
**Generated**: 2026-02-26T12:17:21.431832+00:00
**Elapsed**: 64.0s
**Thinking tokens**: 16384

---

## Generated Prompt (Phase 1 — Gemini Flash)

You are a world-class AI memory systems architect with deep expertise in vector database design, cognitive science, and production AI system optimization. Your task is to analyze AIVA's current auto-recall memory injection mechanism and propose a highly specific, actionable strategy for developing a context-aware injection layer. AIVA is a long-running personal AI assistant, meaning its memory profile will evolve significantly over time, encompassing diverse conversation types, memory age distributions, and importance score profiles.

**Current System State:**
The `api.on("before_agent_start", ...)` hook in `enhanced_index.ts` is responsible for auto-recalling memories. It takes the raw `event.prompt`, embeds it, and performs a `db.hybridSearch` using a fixed `RECALL_CANDIDATE_COUNT` (8) and `RECALL_MIN_SIMILARITY` (0.15). The results are then diversified using `applyMMR` with `MMR_LAMBDA` (0.7) to select `RECALL_INJECT_MAX` (6) memories, followed by `ensureCategoryDiversity`. These selected memories are then injected as a `prependContext` block formatted by `formatRelevantMemoriesContext`. The system lacks any explicit awareness of the current conversation's topic, the user's emotional state, the current task context (e.g., coding, personal chat, business planning), time of day, or dynamic relevance of a memory to the immediate dialogue turn. This results in potentially injecting high-scoring but contextually irrelevant memories, or missing highly relevant memories that are slightly lower-scoring but align perfectly with the current micro-context.

**Specific Weaknesses / Optimization Opportunities:**

1.  **Static Relevance Filtering:** The current `RECALL_MIN_SIMILARITY` (0.15) and `RECALL_INJECT_MAX` (6) are static. This can lead to injecting memories that are semantically similar but contextually irrelevant (e.g., a high-scoring "fact" about a past project when the current conversation is about scheduling a personal event). This results in a measured `~15%` of injected memories being ignored or actively detrimental to agent performance in qualitative user studies. We need a dynamic relevance threshold.

2.  **Lack of Conversation Topic Modeling:** The `event.prompt` is treated as a monolithic query. There's no mechanism to dynamically identify the evolving topic(s) of the conversation. For a personal assistant, this could include shifts between "coding help," "personal planning," "health advice," or "general chat." Without this, the `hybridSearch` might retrieve general facts that are not aligned with the *current phase* of the interaction, degrading the precision of injected context by `~20%` (estimated from user feedback on "noise" in recalled memories).

3.  **Absence of User/Task/Temporal Context:** The system does not leverage external context such as the user's current emotional state (e.g., detected from sentiment analysis of recent messages), the invoked tool context (e.g., if a `coding` tool was just called, prioritize `skill` or `decision` memories related to coding), or even simple temporal awareness (e.g., suppressing "event" memories from 2 years ago if the conversation implies immediate future events). This leads to a `P90` latency increase of `~50ms` on average due to the LLM processing irrelevant context, and a `P90` retrieval precision drop of `~10%` compared to a hypothetical ideal.

**Deep Think Prompt:**

Design and propose a **Context-Aware Memory Injection Layer** for AIVA. This layer should dynamically re-rank, filter, and strategically place memories to maximize their utility to the agent, minimizing "context stuffing" and improving conversational flow.

Your proposal should include:

1.  **Dynamic Relevance Thresholding & Re-ranking:**
    *   Propose an algorithm to dynamically adjust the `RECALL_MIN_SIMILARITY` and `RECALL_INJECT_MAX` based on the detected conversation topic and/or user intent.
    *   Introduce an additional re-ranking step after `applyMMR` that incorporates contextual signals (e.g., topic alignment, recency relative to task, user sentiment).
    *   Provide pseudocode or a TypeScript sketch for a new `dynamicRelevanceRerank(candidates: HybridSearchResult[], currentContext: ConversationContext): HybridSearchResult[]` function.
    *   Specify measurable improvement targets, e.g., "reduce the percentage of irrelevant injected memories (as judged by a human evaluator) from 15% to 5%."

2.  **Conversation Topic Modeling & Memory Filtering:**
    *   Propose a lightweight, real-time topic modeling approach for the ongoing conversation. This could involve an LLM call on the last N turns or a keyword extraction + clustering approach. Define a `ConversationContext` object to store this.
    *   Describe how the detected topic(s) would be used to filter or boost specific `MemoryCategory` types (e.g., if "coding" is the topic, boost "skill" or "decision" memories).
    *   Provide a TypeScript sketch for `detectConversationTopic(messages: Message[]): Promise<string[] | ConversationContext>`.
    *   Target: "Improve the `P90` precision of injected memories (where precision is defined as topic alignment with the current conversation) by 25%."

3.  **Multi-Dimensional Context Integration & Injection Placement Optimization:**
    *   Define an expanded `ConversationContext` data structure that captures not only topic but potentially user sentiment (e.g., `positive`, `neutral`, `negative`), task context (e.g., `coding`, `personal`, `business`), and temporal cues (e.g., `morning`, `afternoon`, `evening`). Describe how these could be derived.
    *   Propose strategies for intelligent injection placement within the `prependContext` block. Instead of always prepending, consider if some memories are better placed after a specific agent prompt, or if a "hint" is better than full text.
    *   Provide TypeScript sketches for modifying `formatRelevantMemoriesContext` or the `before_agent_start` hook to handle dynamic placement and summary generation.
    *   Target: "Reduce `P90` LLM processing latency attributed to irrelevant context by 20ms and improve perceived conversational fluency by 10% (measured via user survey)."

Provide a complete implementation roadmap with TypeScript code snippets suitable for direct integration into the `enhanced_index.ts` / `enhanced_config.ts` files.

---

## Thinking Process (Phase 2 — Gemini Pro)

**Context-Aware Memory Augmentation for AIVA: A World-Class Architecture**

Alright, let's break this down. The objective is to overhaul AIVA's memory injection, shifting it from a rudimentary RAG system to a genuinely context-aware, cognitive augmentation engine. My expertise as a world-class AI memory systems architect will shine through here. This needs to be a practical, production-ready solution, not just a theoretical exercise.

First, I'm identifying the current bottlenecks: static thresholds leading to irrelevant injections, a lack of conversation topic tracking, and an inability to leverage user/task/temporal context. These are critical flaws in a personal AI assistant designed for long-term use and diverse tasks. We're talking about precision, recall, and, crucially, latency here. We need a system that's both *effective* and *fast*.

The core architectural shift is from a single-stage retrieval process to a *multi-stage pipeline*: **Retrieve -> Filter -> Re-rank**. The lynchpin is the `ConversationContext` object. This isn’t a one-off; it’s the central data structure, feeding into and being updated by every stage.

The initial retrieval (`hybridSearch`) is adequate. The issue lies in the downstream processing. The scoring function must be refined to create a more dynamic and nuanced decision-making process. The goal is to move beyond MMR and integrate signals like: original similarity score from the vector DB, topic alignment, recency, category boosts, and sentiment alignment. Weighting each of these context vectors is where the intelligence comes in. The weights will also be dynamic and adapt over time.

For topic modeling, an LLM call is effective but could slow the system down, so a lightweight approach is requested. For rapid context, a hybrid approach of keyword/embedding-based filtering, with periodic, more costly, LLM-based summaries, seems like a sweet spot. The `ConversationContext` will now include `topics`, a `topic_summary`, and a `topic_embedding`. These will improve the performance of boosting and filtering.

To build out the `ConversationContext`, additional context will be added, including `sentiment`, `current_task`, and `temporal_focus`. Sentiment can be efficiently derived from sentiment analysis. Task identification can come from tool calls and keywords. Temporal aspects are important because an AI should be capable of understanding when to apply specific aspects of memory based on temporal cues. For example, memories from last year or the day before, are relevant at different times.

Placement is critical. Instead of dumping a block of text, let's create a *structured context* block, which gives the LLM clear signals on how to incorporate the information:

```xml
<AIVA_INTERNAL_CONTEXT>
    <RELEVANT_FACTS>...</RELEVANT_FACTS>
    <PAST_DECISIONS>...</PAST_DECISIONS>
    <RELATED_SKILLS>...</RELATED_SKILLS>
</AIVA_INTERNAL_CONTEXT>
```

This is where things get interesting from a cognitive architecture perspective. We’re structuring the *information* to guide the LLM's *reasoning*. Also, we need a method to create summarized versions of older, less-important memories.

Here's the plan:

*   **Phase 1:** Focus on the `ConversationContext` and `dynamicRelevanceRerank` function. Get the core scoring and thresholding in place.
*   **Phase 2:** Implement the lightweight `detectConversationTopic` functionality. Then, introduce the LLM-powered summary.
*   **Phase 3:** Refine memory formatting with the structured context and summaries.
*   **Phase 4:** A/B test everything, relentlessly tune the weights, and optimize.

The goal is to move beyond simple retrieval to genuinely *cognitive* augmentation. And, with these structured code blocks, the goals are fully met.

---

## Deep Think Response

Excellent. This is a fascinating and critical challenge in developing truly intelligent, long-running AI assistants. Moving from a stateless, semantic-only retrieval to a stateful, context-aware cognitive augmentation system is the next frontier. As a memory systems architect, here is my detailed proposal for AIVA's **Context-Aware Memory Injection Layer**.

This proposal is structured as a phased implementation plan, starting with the highest-impact changes and progressively adding layers of sophistication.

### Executive Summary: The Cognitive Re-ranking & Augmentation (CRA) Layer

We will replace the current static, single-pass retrieval mechanism with a multi-stage **Cognitive Re-ranking & Augmentation (CRA) Layer**. This layer operates between the initial candidate retrieval and the final context injection, transforming the process from simple RAG to a dynamic, context-sensitive cognitive function.

The core principle is to model AIVA's "working memory" and "attentional focus" by creating a rich `ConversationContext` object that is updated with every turn. This context will then be used to dynamically re-score, filter, and format memories for maximum relevance and minimal cognitive load on the downstream LLM.

**High-Level Flow:**

1.  **Context Generation:** Before retrieval, analyze the last `N` messages to generate a `ConversationContext` object.
2.  **Candidate Retrieval:** Perform the initial `db.hybridSearch` with a *wider* net than before (e.g., `RECALL_CANDIDATE_COUNT = 20`) to ensure we don't prematurely discard potentially relevant memories.
3.  **Cognitive Re-ranking:** Pass the candidates and the `ConversationContext` to a new `dynamicRelevanceRerank` function. This function calculates a new, context-aware score for each memory.
4.  **Dynamic Filtering & Selection:** Apply a dynamic threshold and budget based on the context's clarity and the scores of the re-ranked candidates. Use MMR on the *new* scores to ensure diversity among the top, contextually-relevant items.
5.  **Structured Augmentation:** Format the final, selected memories into a structured context block using a modified `formatRelevantMemoriesContext`, which may summarize memories or place them in specific categories for the LLM.

---

### 1. Dynamic Relevance Thresholding & Re-ranking

This phase tackles the core weakness of static filtering by introducing a scoring function that reflects a memory's true utility in the *current moment*.

#### **Algorithm: Context-Aware Composite Scoring**

Instead of relying solely on vector similarity, we will compute a `contextualScore` for each candidate memory. This score is a weighted sum of several relevance signals:

`contextualScore = w_sim * S_sim + w_topic * S_topic + w_temp * S_temp + w_cat * S_cat`

*   **`S_sim` (Similarity Score):** The original score from `hybridSearch`. This is our baseline relevance.
*   **`S_topic` (Topic Alignment Score):** Cosine similarity between the memory's embedding and the current conversation's topic embedding (from the `ConversationContext`).
*   **`S_temp` (Temporal Relevance Score):** A decay function based on memory age, but *dynamically adjusted* by the conversation's temporal focus. For example, if the user mentions "last week," recent memories get a boost. If they mention "childhood," very old memories get a boost. The default is a gentle logarithmic decay.
*   **`S_cat` (Category Boost Score):** A boost applied if the memory's `category` (e.g., `skill`, `decision`, `fact`) aligns with the current `task` (e.g., `coding`, `planning`).

**Dynamic Thresholds:**
*   `RECALL_INJECT_MAX` becomes a dynamic `injectionBudget`. If the top candidates have very high `contextualScore`, inject more. If scores are mediocre, inject fewer to avoid noise.
*   `RECALL_MIN_SIMILARITY` is replaced by a check on the final `contextualScore`.

#### **TypeScript Sketch: `dynamicRelevanceRerank`**

```typescript
// To be added in enhanced_index.ts or a new memory_utils.ts

import { HybridSearchResult, Memory } from './db'; // Assuming types
import { ConversationContext } from './context_engine'; // To be created

// Weights for the scoring function - these should be tuned
const SCORING_WEIGHTS = {
  similarity: 0.4,
  topic: 0.3,
  temporal: 0.15,
  category: 0.15,
};

interface MemoryCandidateWithContextScore extends HybridSearchResult {
  contextualScore: number;
  scores: {
    similarity: number;
    topic: number;
    temporal: number;
    category: number;
  };
}

// Simple cosine similarity utility
function cosineSimilarity(vecA: number[], vecB: number[]): number {
    // Implementation ...
    if (!vecA || !vecB || vecA.length !== vecB.length) return 0;
    let dotProduct = 0;
    let normA = 0;
    let normB = 0;
    for (let i = 0; i < vecA.length; i++) {
        dotProduct += vecA[i] * vecB[i];
        normA += vecA[i] * vecA[i];
        normB += vecB[i] * vecB[i];
    }
    if (normA === 0 || normB === 0) return 0;
    return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
}


function calculateTemporalScore(memory: Memory, context: ConversationContext): number {
    const memoryAgeDays = (Date.now() - new Date(memory.created_at).getTime()) / (1000 * 3600 * 24);
    
    // Default: Logarithmic decay - recent is better
    let score = Math.log(1000) / Math.log(memoryAgeDays + 10);

    // Dynamic adjustment based on context
    if (context.temporalFocus === 'past_distant' && memoryAgeDays > 365) {
        score *= 1.5; // Boost very old memories if context is nostalgic
    } else if (context.temporalFocus === 'recent' && memoryAgeDays < 7) {
        score *= 1.3; // Boost recent memories if context is about recent events
    }
    
    return Math.min(1.0, score);
}

function calculateCategoryBoost(memory: Memory, context: ConversationContext): number {
    const boostMap: { [task: string]: { [category: string]: number } } = {
        'coding': { 'skill': 1.5, 'decision': 1.3, 'fact': 1.1 },
        'planning': { 'decision': 1.5, 'event': 1.3, 'fact': 1.2 },
        'personal_chat': { 'experience': 1.4, 'opinion': 1.2, 'person': 1.3 },
    };
    const task = context.currentTask || 'general';
    const boosts = boostMap[task] || {};
    return boosts[memory.category] || 1.0;
}

export function dynamicRelevanceRerank(
  candidates: HybridSearchResult[],
  context: ConversationContext
): MemoryCandidateWithContextScore[] {
  const rerankedCandidates: MemoryCandidateWithContextScore[] = candidates.map(candidate => {
    const S_sim = candidate.score;
    const S_topic = cosineSimilarity(candidate.memory.embedding, context.topicEmbedding);
    const S_temp = calculateTemporalScore(candidate.memory, context);
    const S_cat_boost = calculateCategoryBoost(candidate.memory, context);

    const contextualScore =
      (SCORING_WEIGHTS.similarity * S_sim +
      SCORING_WEIGHTS.topic * S_topic +
      SCORING_WEIGHTS.temporal * S_temp) * S_cat_boost;
      
    return {
      ...candidate,
      contextualScore,
      scores: { similarity: S_sim, topic: S_topic, temporal: S_temp, category: S_cat_boost },
    };
  });

  // Sort by the new, more intelligent score in descending order
  return rerankedCandidates.sort((a, b) => b.contextualScore - a.contextualScore);
}
```

#### **Measurable Improvement Targets**

*   **Primary:** Reduce the percentage of irrelevant injected memories (judged by a human evaluator or a powerful LLM like GPT-4 as a judge) from **15% to under 5%**.
*   **Secondary:** Increase the Mean Reciprocal Rank (MRR) of the *most* relevant memory (if one exists) from the top 6 injected items. We target a **20% improvement in MRR**.

---

### 2. Conversation Topic Modeling & Memory Filtering

To power the re-ranking function, we need a robust, real-time understanding of the conversation's topic.

#### **Lightweight Topic Modeling Approach**

We'll use a hybrid, two-tiered approach to balance latency and accuracy:

1.  **Rolling Topic Embedding (Fast):** For every turn, maintain an exponentially weighted moving average (EWMA) of the embeddings of the last `~5` user/assistant messages. This creates a `topicEmbedding` that represents the *immediate* conversational focus. It's cheap and responsive.
2.  **LLM-Generated Topic Summary (Periodic):** Every `10` turns, or when a significant topic shift is detected (e.g., large change in the rolling embedding), make a single, fast LLM call (e.g., to `claude-haiku` or `gpt-3.5-turbo`) to summarize the recent conversation history into a concise `topicSummary` string (e.g., "Debugging a TypeScript issue related to database connections") and a list of `topicKeywords` (e.g., `['typescript', 'debug', 'prisma', 'database']`).

#### **TypeScript Sketch: `ConversationContext` and `detectConversationTopic`**

```typescript
// To be in a new file, e.g., context_engine.ts

import { Message } from './types'; // Assuming a Message type
import { getEmbedding } from './embedding'; // Your embedding function
import { llm } from './llm'; // Your LLM client

export interface ConversationContext {
  topicEmbedding: number[];
  topicSummary: string;
  topicKeywords: string[];
  sentiment: 'positive' | 'neutral' | 'negative';
  currentTask: 'coding' | 'planning' | 'personal_chat' | 'general';
  temporalFocus: 'past_distant' | 'past_recent' | 'present' | 'future';
  turnCountSinceLastUpdate: number;
}

// This would be a class that maintains state across requests
export class ContextEngine {
  private context: ConversationContext;

  constructor() {
    // Initialize with default/empty state
    this.context = { /* ... initial state ... */ };
  }
  
  // A simplified EWMA update for the embedding
  private async updateTopicEmbedding(newMessages: Message[]): Promise<void> {
    const latestMessage = newMessages[newMessages.length - 1];
    const newEmbedding = await getEmbedding(latestMessage.content);
    
    if (!this.context.topicEmbedding || this.context.topicEmbedding.length === 0) {
        this.context.topicEmbedding = newEmbedding;
        return;
    }
    
    const alpha = 0.4; // Weight for the new message
    this.context.topicEmbedding = this.context.topicEmbedding.map((val, i) => 
        (1 - alpha) * val + alpha * newEmbedding[i]
    );
  }

  public async getContext(messages: Message[]): Promise<ConversationContext> {
    await this.updateTopicEmbedding(messages);
    this.context.turnCountSinceLastUpdate++;
    
    // Periodically update the summary and keywords with an LLM call
    if (this.context.turnCountSinceLastUpdate > 10) {
        const history = messages.slice(-10).map(m => `${m.role}: ${m.content}`).join('\n');
        const prompt = `Analyze the following conversation history and provide a concise summary and keywords.
        CONVERSATION:
        ${history}
        
        RESPONSE FORMAT (JSON):
        {
          "summary": "A short, one-sentence summary of the main topic.",
          "keywords": ["keyword1", "keyword2"]
        }`;

        try {
            const result = await llm.generate(prompt, { json: true });
            this.context.topicSummary = result.summary;
            this.context.topicKeywords = result.keywords;
            this.context.turnCountSinceLastUpdate = 0;
        } catch (e) {
            console.error("Failed to update context summary:", e);
        }
    }
    
    // Logic for sentiment, task, temporal focus would go here...
    // ... (see section 3) ...
    
    return this.context;
  }
}
```

#### **Measurable Improvement Targets**

*   **Primary:** Improve the `P90` precision of injected memories by **25%**. Precision is defined as the percentage of injected memories whose content is topically aligned with a human-generated summary of the last 5 turns.
*   **Secondary:** Reduce user-reported "noisy" or "irrelevant" memory recalls in qualitative feedback surveys by **50%**.

---

### 3. Multi-Dimensional Context Integration & Injection Placement Optimization

This final phase graduates from simple text injection to structured, strategic context augmentation.

#### **Expanded `ConversationContext` Definition**

We will expand the context object to include signals derived from simple heuristics or lightweight models:

*   **`sentiment`:** Derived from a fast sentiment analysis library (e.g., `sentiment`) run on the last user message.
*   **`currentTask`:** Inferred from keywords and tool usage. If a message contains ````typescript`, the task is `coding`. If `plan`, `schedule`, or `organize` appear, it's `planning`.
*   **`temporalFocus`:** Inferred from keywords in the user's prompt (`"yesterday"`, `"next week"`, `"in the future"`).

This expanded context allows for highly nuanced re-ranking and, crucially, optimized injection formatting.

#### **Strategies for Intelligent Injection Placement & Formatting**

Instead of a single block of text, we will format the context into an XML-style block that the LLM is pre-trained to understand, giving it explicit instructions on the *nature* of the information.

1.  **Categorical Grouping:** Group injected memories by their category.
2.  **Dynamic Summarization:** For memories that are very old or very long but contextually relevant, inject a one-sentence, LLM-generated summary instead of the full text to save token space.
3.  **Confidence-Based Formatting:** If a memory has a very high `contextualScore`, present it as a "fact." If the score is lower, present it as a "potential hint."

#### **TypeScript Sketch: `formatRelevantMemoriesContext` (Modified)**

```typescript
// To be modified in enhanced_index.ts

// A new function to summarize long memories
async function summarizeMemory(memoryContent: string): Promise<string> {
    // This could be a cached call to a fast LLM
    const prompt = `Summarize the following text into a single, concise sentence: ${memoryContent}`;
    return await llm.generate(prompt);
}

export async function formatRelevantMemoriesContext(
    memories: MemoryCandidateWithContextScore[],
    context: ConversationContext
): Promise<string> {
  if (memories.length === 0) {
    return '';
  }

  const memoryGroups: { [category: string]: string[] } = {};

  for (const item of memories) {
    if (!memoryGroups[item.memory.category]) {
      memoryGroups[item.memory.category] = [];
    }

    let memoryText = item.memory.content;
    const memoryAgeDays = (Date.now() - new Date(item.memory.created_at).getTime()) / (1000 * 3600 * 24);

    // Summarize if the memory is too long or very old but still relevant
    if (memoryText.length > 500 || memoryAgeDays > 365) {
        memoryText = `(Summary of a past memory): ${await summarizeMemory(memoryText)}`;
    }
    
    // Add a confidence hint
    if (item.contextualScore < 0.6) {
        memoryText = `(Possible hint): ${memoryText}`;
    }

    memoryGroups[item.memory.category].push(`- ${memoryText}`);
  }

  const formattedBlocks = Object.entries(memoryGroups)
    .map(([category, items]) => {
      const tagName = category.toUpperCase().replace(/\s/g, '_');
      return `<RELEVANT_${tagName}>\n${items.join('\n')}\n</RELEVANT_${tagName}>`;
    })
    .join('\n');

  return `
<AIVA_INTERNAL_CONTEXT>
<CURRENT_FOCUS_SUMMARY>${context.topicSummary || 'General conversation'}</CURRENT_FOCUS_SUMMARY>
${formattedBlocks}
</AIVA_INTERNAL_CONTEXT>
`;
}
```

#### **Measurable Improvement Targets**

*   **Primary:** Reduce `P90` LLM processing latency attributed to context processing by **20ms** by injecting more concise and relevant information.
*   **Secondary:** Improve perceived conversational fluency and "intelligence" by **10%** in user satisfaction surveys (e.g., questions like "How often did AIVA seem to remember relevant past information?").

### Implementation Roadmap

1.  **Phase 1: Foundation (Context & Re-ranking - 1-2 Sprints)**
    *   Implement the `ContextEngine` class with the fast, rolling topic embedding (`updateTopicEmbedding`).
    *   Implement the `dynamicRelevanceRerank` function with initial weights.
    *   In `before_agent_start`, increase `RECALL_CANDIDATE_COUNT` to 20.
    *   Pipe the initial candidates through the re-ranker.
    *   Implement a dynamic `injectionBudget` based on the top re-ranked scores.
    *   A/B test this new re-ranking against the old static system, focusing on the "irrelevant injection" metric.

2.  **Phase 2: Intelligence Layer (LLM-Powered Context - 1 Sprint)**
    *   Integrate the periodic LLM call into the `ContextEngine` to generate `topicSummary` and `topicKeywords`.
    *   Add the derivation logic for `currentTask`, `sentiment`, and `temporalFocus`.
    *   Tune the scoring weights (`SCORING_WEIGHTS`) now that all context signals are available.

3.  **Phase 3: Optimization & Fluency (Structured Augmentation - 1 Sprint)**
    *   Modify `formatRelevantMemoriesContext` to implement the XML-style structured formatting.
    *   Implement the `summarizeMemory` function, including a caching layer to avoid re-summarizing the same memory.
    *   Deploy and measure the impact on LLM latency and conversational quality.

By following this roadmap, AIVA's memory system will evolve from a simple retrieval tool into a sophisticated cognitive architecture that dynamically understands context, focuses its attention, and provides the agent with precisely the right information at the right time.
