# Searching Past Conversations

How `chat_history` searches recent conversations by meaning and all history by keyword.

## 2. Semantic search — ToriiDB (recent conversations)

The `chat_history` tool with `mode=search` and `match=semantic` runs vector similarity search via ToriiDB `db.VSearch`. Each hit triggers a context window expansion: 2 entries before + 1 entry after.

ToriiDB entries are cleaned during `history.json` compaction — entries older than the compact cutoff are removed, keeping ToriiDB focused on recent conversations. Older data lives in SQLite (tier 3).

## 3. Full-text archive — SQLite FTS5 (all history)

Every message written to `history.json` is **dual-written** to SQLite (`~/.config/agenvoy/.store/history.db`) via go-sqlkit. SQLite always holds the complete conversation history, even after `history.json` is compacted.

The `chat_history` tool with `mode=search` and `match=keyword` runs FTS5 full-text search on the SQLite archive + ToriiDB substring match on recent entries, combining results.

**Compaction:** when `history.json` exceeds `max_history_bytes` (default 4 MiB since v1.0.12, when it became four times the 1 MiB document ceiling), the oldest messages are trimmed to 80% on a complete user+assistant pair boundary. The cutoff timestamp is recorded in SQLite `message_meta.start_at` so that keyword search excludes entries already present in `history.json` (avoiding duplicates). ToriiDB entries older than the cutoff are also removed.

**Backfill:** on first encounter (SQLite has no data for a session but `history.json` has content), the entire existing history is backfilled into SQLite.

**Timestamps:** stored as UTC unix nanoseconds. Timestamps in message content are parsed via `time.ParseInLocation` (local timezone) and converted to UTC for storage. Search queries use `time.Now().UnixNano()` (already UTC).
