> ## Documentation Index
> Fetch the complete documentation index at: https://kiro.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Memory

> How Crew automatically builds, retrieves, and manages memories across sessions. Six memory layers, decay mechanisms, and how lessons override defaults.

Memory is what makes Crew feel like it knows you. New sessions inherit preferences, project context, and learned corrections from every session that came before — without replaying old conversations token by token.

There are six independent memory layers, each with a specific purpose.

## The six memory layers

```mermaid
graph TD
    subgraph ContextWindow["Context Window (~55K tokens)"]
        direction TB

        subgraph TopLayer[" "]
            direction LR
            Prefs["Preferences<br/>(preferences.md)"] ~~~ Projects["Projects<br/>(projects.md)"] ~~~ History["Recent History<br/>(history/*.md)<br/>3-tier decay"]
        end

        Semantic["Semantic Memory (key-value)<br/>pref.*, project.*, user.* — confidence-gated writes"]

        Episodic["Episodic Memory (past events)<br/>FAISS vector search + time-decay + MMR reranking"]

        Lessons["Lessons (learned corrections)<br/>lesson.* keys — user-explicit always wins"]

        TopLayer --> Semantic
        Semantic --> Episodic
        Episodic --> Lessons
    end
```

### Preferences — how you like to work

User habits, tool preferences, communication style. Replaced wholesale by the consolidator every 30 messages — not append-only.

- Source: `~/.kiro/crew/workspace/memory/preferences.md`
- Injected every new session
- Cap: 4,250 chars

Example:
```markdown
- Prefers Slack for communication and monitoring
- Uses standard Python build system (setuptools/pip)
- Prefers deep code analysis with hidden information uncovered
- Wants diagrams in documentation for complex flows
```

### Projects — active work context

CRs, packages, branches, status. Same lifecycle as preferences.

- Source: `~/.kiro/crew/workspace/memory/projects.md`
- Injected every new session
- Cap: 6,400 chars

### Recent history — daily summaries with tiered decay

| Age | Detail level |
|---|---|
| 0–13 days | Full entries with timestamps |
| 14–60 days | First entry per day + count |
| 61–180 days | Date + entry count only |
| 181–364 days | Not loaded (kept on disk) |
| 365+ days | Deleted from disk |

- Source: `~/.kiro/crew/workspace/memory/history/`
- Updated on 3-hour idle per session
- Cap: 26,600 chars
- Pruned daily via the heartbeat service

### Semantic memory — structured key-value

Structured facts stored in SQLite. Always on — embeddings activate automatically once the model downloads.

- Storage: SQLite `semantic_memory` table + optional FAISS index
- Key prefixes: `pref.*`, `project.*`, `user.*` (plus user-configurable extras)
- Cap: 12,000 chars
- Retrieval: hybrid `0.6 × vector_score + 0.4 × keyword_score` (keyword-only fallback if the embedding model hasn't downloaded yet)

Example entries:
```
user.dev_desktop_host_current: dev-host.example.com
project.kirocrew.zoom_fix_implemented: True
pref.prefers_configregions_over_null_guards: True
```

**Confidence gating** prevents hallucinated writes. LLM writes require confidence ≥ 0.8. User-explicit writes always win regardless of confidence. On conflict, higher confidence wins; same confidence → newer wins.

### Episodic memory — past events

Short text snippets capturing specific past events — "fixed the zoom bug by adding CSS custom properties", "user prefers pytest-asyncio strict mode". Think of them as searchable bookmarks into past conversations.

- Storage: SQLite `episodic_memories` table + optional FAISS index
- Text length: 10–2,000 chars per entry
- Dedup: FAISS cosine > 0.88 rejects near-duplicates
- Cap: 3,000 chars, top-8 results per query
- Max entries: 10,000 (lowest-importance oldest pruned when exceeded)

Search uses **decay scoring** with **MMR diversity reranking** (Jaccard-based, λ=0.6) to avoid redundant results. A two-stage filter first drops irrelevant matches on raw cosine, then decay-adjusted scoring ranks the survivors.

### Lessons — learned corrections

User-taught rules that override default behavior. Created when you say "always do X" or when a correction pattern is detected in a conversation.

- Storage: `lesson.<md5hash>` semantic entries (confidence 1.0)
- Dedup: substring match + topic overlap (>50% keyword → replace)
- Cap: 37,250 chars, max 50 lessons
- Injected as a distinct `[Learned corrections]` block

Example:
```
- Dashboard auto-scroll should only trigger when the user is near bottom (within 80px).
- Task Runner resets the agent session after each step — the agent can't carry context forward.
```

## How memories get built

```
User Message
    │
    ├──► learn_add MCP tool ──► write_lesson() ──► Immediate lesson save
    │    (user says "remember X" or agent is corrected)
    │
    ├──► 30 messages ──► HistoryConsolidator (prefs path)
    │                    ├── Updates preferences.md (wholesale replace)
    │                    ├── Updates projects.md (wholesale replace)
    │                    └── Extracts semantic entries (max 20)
    │
    ├──► 3h idle ──► HistoryConsolidator (history path)
    │                ├── Appends to history/{date}.md
    │                ├── Extracts episodic entries (max 10)
    │                └── Extracts implicit lessons (corrections without "remember")
```

### Two independent consolidation paths

| Path | Trigger | Updates | Offset tracking |
|---|---|---|---|
| Preferences / projects | 30 messages | `preferences.md`, `projects.md`, semantic entries | In-memory offset dict |
| History + lessons | 3h idle | `history/.md`, episodic, implicit lessons | Persisted `last_consolidated` |

The prefs path does **not** advance the persisted `last_consolidated` marker — history consolidation always covers all messages, even if prefs consolidation fired earlier.

### Explicit vs. implicit lessons

- **Explicit** — user says "remember to always use pytest-asyncio strict mode" → saved immediately via `learn_add`
- **Implicit** — user corrects the agent without saying "remember" (e.g., "No, don't cache that — the value changes per request") → extracted during history consolidation

Both go through `write_lesson()` which provides substring dedup and topic-overlap dedup.

## Fading — three decay mechanisms

Three independent decay mechanisms prevent stale memories from consuming context.

### 1. History decay (time-based tiers)

Older history progressively loses detail (see table above). "Something happened" markers eventually replace full entries, then get dropped from context but kept on disk as backup, then are deleted altogether at 365 days.

### 2. Episodic decay (exponential time-decay scoring)

```
score = cosine_sim × (0.7 + 0.3 × importance) × exp(-0.03 × days_old)
```

- `cosine_sim` — semantic relevance to the current query
- `0.7 + 0.3 × importance` — high-importance memories decay slower
- `exp(-0.03 × days_old)` — exponential decay: 50% at ~23 days, 10% at ~77 days

### 3. Episodic cap enforcement

At 10,000 entries the lowest-importance, oldest ones are pruned first.

## Conflict resolution — priority order

```
1. Lessons (user-explicit, confidence 1.0)
2. Semantic memory (user-explicit writes)
3. Semantic memory (LLM writes, confidence ≥ 0.8)
4. Preferences / projects (consolidation-generated)
5. Episodic memory (relevance-scored fragments)
6. History (time-decayed summaries)
```

Lessons win the tie because they're injected in a distinct `[Learned corrections]` block that reads "ALWAYS follow these. They override default behavior."

## Context assembly

The context builder assembles all sources into the prompt. Different content is injected at different times.

### At session start

| Component | Cap |
|---|---|
| Critical rules | ~500 chars |
| Current date/time | ~50 chars |
| Agent system prompt | Variable |
| Thread conversation history | 45,000 chars (LLM-compressed) |
| Preferences | 4,250 chars |
| Projects | 6,400 chars |
| Recent history | 26,600 chars |
| Skills (always-on + summaries) | Variable |
| Lessons | 37,250 chars |
| Semantic memory | 12,000 chars |

### Per message (follow-up turns)

| Component | Source |
|---|---|
| Episodic memory | Queried by message text, top-8 fragments (up to 3,000 chars) |
| Channel history | Group-channel context (Slack observe mode) |
| Triggered skills | On-demand skills matching message keywords |
| Hook context | Config-driven context rules |

## Channel-aware memory

The same memory store is shared across every channel, but recording behavior varies:

| Channel | Activation | History buffer | Memory consolidation |
|---|---|---|---|
| DM | `always` | Session-based (ACP native) | ✅ Yes |
| Group channel | `mention` | 50 msg, 5-min TTL, in-memory | ✅ When @mentioned |
| Group channel | `observe` | 200 msg, 1-week TTL, disk-persisted | ✅ When @mentioned |
| Group channel | `off` | None | ❌ No |
| Dashboard tab | N/A | Session-based (ACP native) | ✅ Yes |

**Security in observe mode.** Only messages from authorized users (owner + allowlist) are recorded. Non-authorized messages are silently dropped to prevent prompt injection.

## Control memory writes and context

Four `config.json` switches separate what Crew records from what a new turn receives:

| Setting | Default | Effect when off |
|---|---|---|
| `memory.persistence_enabled` | `true` | Stops automatic memory writes and consolidation, and adds no stored memory or lessons to new sessions |
| `memory.inject_memory` | `true` | Omits stored memory from new-session context |
| `memory.inject_lessons` | `true` | Omits the learned-corrections and user-profile blocks |
| `memory.inject_activity` | `true` | Omits recent projects, history, task facts, and past episodes. Has no effect when `memory.inject_memory` is off |

These process-wide controls do not replace a session's Persistent, Incognito, or Temporary mode. Use a session mode for one conversation. Use these settings when the Gateway should change memory behavior for every new session.

## Teaching Crew

The CLI is the fastest path to add a lesson:

```bash
kirocrew learn add "always use TypeScript over JavaScript"
kirocrew learn add "prefer pytest over unittest" --category tool
kirocrew learn list
kirocrew learn remove "prefer pytest"
```

The `learn_add` MCP tool is the same interface exposed to the LLM — when the agent recognizes a correction, it calls the tool itself.

## Managing memory from the dashboard

The dashboard exposes memory management surfaces:

- **Memory Graph Explorer** — visualize semantic memory relationships (vis.js)
- **Edit saved memories** — open, edit, forget, and restore individual records (see [Editing saved memories](#editing-saved-memories))
- **Skills / Lessons CRUD** — add, edit, remove from the browser
- **Knowledge Library** — ingest external docs into a curated store (separate from episodic/semantic memory)

## Editing saved memories

Open **Settings → Overview**, select the **Memory** card, and expand **Edit saved memories** to open the records editor for the default store. Open a record to read its value, provenance, and **Revision history**.

### Restore an earlier version

In a record's **Revision history**, an earlier accepted version whose value differs from the current one offers a **Restore "…"** button that names that earlier value. It opens a dialog titled **Restore an earlier version** with a two-column preview: **Now** shows the value the record holds, and **After restoring** shows the value it will hold.

Confirming saves that value as a new version marked **Restored version**. Earlier versions stay in the history, so a restore is itself reversible.

## Knowledge Library

Distinct from the automatic memory layers, the Knowledge Library is a curated document store for external content — files, folders, or URLs you want the agent to be able to search.

- Sources: local files, local folders (recursive scan), URLs (fetched at ingest)
- Ingestion pipeline: chunking, entity extraction, embedding generation
- Search: `local_knowledge_search` MCP tool with strict trigger rules and a confidence threshold

The library is a **built-in surface** in the dashboard sidebar — not an App Store app.

## Named memory stores

`config.json` can declare named memory stores under `memory_stores`. Kiro Crew never creates a declared store's directory on first use, so a store whose directory was deleted stays missing until you create it:

```bash
kirocrew memory create-store research
```

The command prints `Created memory store 'research' at <path>.` When the directory already exists, it leaves it untouched and reports that nothing changed.

It refuses, with one line on stderr and exit code 1, the default store (which needs no create step), a name not declared under `memory_stores`, and a crewmate's store, which is created with its crewmate.

## Backing memory up

Memory is included in `kirocrew snapshot`:

```bash
kirocrew snapshot                     # ~/.kiro/crew/snapshots by default
kirocrew restore snapshot.tar.gz      # auto-detects replace vs merge
```

Snapshots include `memory.db` (episodic + semantic), `memory_index.db` (FTS5 index), and `workspace/memory/` (structured markdown). See [Snapshot & restore](https://kiro.dev/docs/crew/features/snapshot.md) for the full model.
