# Agent Memory System

Persistent memory for the multi-agent chat mode. Memories survive across sessions and are stored as markdown files in the workspace.

## Overview

The memory system provides three virtual tools — `save_memory`, `recall_memory`, and `enrich_memory` — available in **Multi-Agent Chat mode**. Each tool spawns an asynchronous background sub-agent that performs operations using shell commands. The manager agent is notified when the background agent completes via the same synthetic-turn mechanism used by `delegate()`.

## Tools

### save_memory

| Parameter | Required | Description |
|-----------|----------|-------------|
| `content`   | Yes      | The detailed information to save (including context, alternatives, and outcomes). |
| `context`   | No       | Additional context about why this is being saved. |

Returns immediately with an `agent_id`. A background agent (running with `medium` reasoning):
1. Creates the current day folder (e.g., `memories/YYYY-MM-DD/`)
2. Checks existing files for duplicates
3. Appends (or creates) a category file (like `decisions.md` or `general.md`) with a timestamped heading
4. Identifies up to 3 key entities in the text and updates their respective entity files in the `entities/` folder.

### recall_memory

| Parameter | Required | Description |
|-----------|----------|-------------|
| `query`     | Yes      | Topic, keyword, or question to search for. |

Returns immediately with an `agent_id`. A background agent (running with `low` reasoning):
1. **Priority 0 (Index):** If the query is broad or seeks orientation (e.g., "index"), it reads `index.md` first.
2. **Priority 1 (Entity Fast Path):** Checks the `entities.md` registry and directly reads matching entity files.
3. **Priority 2 (Date Search):** Greps across all chronological `YYYY-MM-DD/` folders.
4. Synthesizes a combined summary of all findings.

### enrich_memory

| Parameter | Required | Description |
|-----------|----------|-------------|
| `focus`                  | No | Optional topic to focus consolidation on (Phase 1–4). Chat-history extraction (Phase 0) still runs for all sessions. |
| `delete_older_than_days` | No | Delete chat sessions older than this many days after extraction (default `7`). Set to `0` to disable deletion. |

Returns immediately with an `agent_id`. A background agent (running with `medium` reasoning):
1. **Phase 0 — Distil chat history:** Reads every session in `{chat_history}/`, extracts lasting-value insights (preferences, decisions, what worked/failed, project context, recurring patterns, key facts) into today's date folder and entity files. After extraction, deletes session folders older than `delete_older_than_days` via `find -mtime +N -exec rm -rf`.
2. **Phase 1–3 — Consolidate:** Reads all date and entity files. Identifies redundant, superseded, duplicate, or overly verbose entries. Consolidates and deduplicates, rewriting the markdown files cleanly and removing empty folders / stale entities.
3. **Phase 4 — Regenerate Index:** Builds a fresh `index.md` file containing key decisions, project state, active entities, and orientation guidance for future sessions.

**Rule:** the agent does NOT save facts that can be looked up live from workflows, MCP servers, or APIs (e.g. current PR status, channel lists, live metrics). Memory is for things that cannot be rediscovered from live data — decisions, preferences, learned patterns.

## Storage Structure

The system uses parallel structures for different access patterns, defaulting to the workspace-root `memories/` folder (this path can be overridden per session via the `MemoryFolderKey` context key — for example, a per-project memory store):

```
memories/
  index.md               ← High-level snapshot (regenerated by enrich_memory)
  prompt.md              ← User-editable custom instructions (optional)
  entities.md            ← Entity registry (list of known entity names)
  entities/              ← Per-entity knowledge files (fast lookup)
    auth-service.md      ← Everything known about "auth-service"
    postgresql.md        ← Everything known about "postgresql"
  2026-04-11/            ← Daily date folders (chronological log)
    general.md
    decisions.md
    preferences.md
```

### 1. index.md (The Orientation File)
Generated by `enrich_memory`, this is the primary orientation file read at the start of a session or before making architectural decisions. It contains:
- **Key Decisions:** Settled decisions that shouldn't be re-litigated.
- **Project State:** Current progress and direction.
- **Active Entities:** A list of known entities.
- **What to Check:** Topics that warrant a deeper `recall_memory`.

### 2. Entity Files (entities/)
Entity files group all knowledge about a specific named thing (project, system, technology, person, feature). They provide O(1) lookup speed. They are updated by `save_memory` when it extracts relevant entities, and cleaned up by `enrich_memory`.

### 3. Chronological Log (YYYY-MM-DD/)
A full historical log of all memories stored by date. Categories include `decisions.md`, `general.md`, `preferences.md`, etc.

## Custom Instructions (prompt.md)

Users can customize memory agent behavior by creating `prompt.md` in the memory folder. This file is loaded dynamically via the workspace API and prepended to the background agent's system prompt.

Example `prompt.md`:
```markdown
- Always save memories in bullet-point format
- Categorize by project name (e.g., auth-service.md, data-pipeline.md)
- Never save code snippets — only decisions and rationale
- Use Spanish for all memory entries
```

## Architecture

### Execution Flow

The virtual tools map to handler functions in Go that spawn async sub-agents:

```
Manager Agent
  ↓ calls save_memory() / recall_memory() / enrich_memory()
  ↓
Handler Function (e.g., handleSaveMemory)
  ├── Reads {memoryFolder}/prompt.md via workspace API (if exists)
  ├── Builds highly specific instruction string for the sub-agent
  ├── Sets reasoning level (medium for save/compress, low for recall)
  ├── Calls BackgroundDelegateFunc(ctx, AgentName, instruction)
  └── Returns immediately with { agent_id, status: "running" }
        ↓
Background Sub-Agent (async)
  ├── Uses execute_shell_command for all file operations (mkdir, ls, cat, grep, rm)
  ├── Executes memory logic (writing files, grepping, consolidating)
  └── Manager is notified on completion
```

### Context Injection

The memory tool executors receive these context values:

| Context Key | Value | Purpose |
|-------------|-------|---------|
| `MemoryFolderKey` | `memory_folder` string | Overrides the default `Chats/memories` path |
| `WorkspaceClientKey` | `workspace.Client` | Reading `prompt.md` via API |
| `BackgroundDelegateKey` | `BackgroundDelegateFunc` | Spawning background agents |

## Files

| File | Purpose |
|------|---------|
| `agent_go/cmd/server/virtual-tools/memory_tools.go` | Tool definitions, async executors, agent instructions (`GetMemoryInstructions`) |
| `agent_go/cmd/server/server.go` | Tool registration and context injection for multi-agent chat |
