agent-memory
Add persistent memory to AI coding agents — file-based, vector, and semantic search memory systems that survive between sessions. Use when a user asks to "remember this", "add memory to my agent", "persist context between sessions", "build a knowledge base for my agent", "set up agent memory", or "make my AI remember things". Covers file-based memory (MEMORY.md), SQLite with embeddings, vector databases (ChromaDB, Pinecone), semantic search, memory consolidation, and automatic context injection.
What this skill does
# Agent Memory
## Overview
AI agents forget everything between sessions. This skill builds persistent memory systems — from simple file-based approaches to full vector-search architectures — so agents retain context, learn from past interactions, and make better decisions over time.
## When to Use
- User wants the agent to remember decisions, preferences, or project context
- Building a coding assistant that needs to recall past conversations
- Creating a knowledge base the agent can query semantically
- Agent needs to learn from mistakes and not repeat them
- Implementing memory consolidation (daily notes → long-term memory)
## Instructions
### Strategy 1: File-Based Memory (Zero Dependencies)
The simplest approach — write memories to structured markdown files. No database, no embeddings, no API keys. Works with any agent that can read/write files.
#### Architecture
```
memory/
├── MEMORY.md # Long-term curated knowledge
├── 2026-02-24.md # Daily session logs
├── 2026-02-23.md
├── entities/
│ ├── projects.md # Known projects and their state
│ ├── people.md # People, preferences, relationships
│ └── decisions.md # Key decisions and reasoning
└── heartbeat-state.json # Periodic check state
```
#### Memory File Format
```markdown
# MEMORY.md — Long-Term Agent Memory
## Projects
### Terminal Skills
- Repo: https://github.com/TerminalSkills/skills
- Stack: Next.js, TypeScript
- Status: Active, 295 skills published
- Key decision: Use-cases always come first, skills serve use-cases
## Preferences
- Language: TypeScript over JavaScript
- Testing: Vitest over Jest
- Deployment: Vercel for frontend, Railway for backend
## Lessons Learned
- Sub-agents limited to 5-6 tasks max (context window overflow at 10+)
- Always check for duplicates before creating new content
- Git branches from upstream/main, never local main
```
#### Implementation
```python
# agent_memory.py — File-based agent memory with search
"""
File-based memory system for AI agents.
Stores memories as structured markdown, supports fuzzy search
across all memory files without any external dependencies.
"""
import os
import re
from datetime import datetime, timedelta
from pathlib import Path
from typing import Optional
class FileMemory:
"""Persistent file-based memory for AI agents."""
def __init__(self, memory_dir: str = "memory"):
self.memory_dir = Path(memory_dir)
self.memory_dir.mkdir(parents=True, exist_ok=True)
self.long_term_file = self.memory_dir / "MEMORY.md"
self.entities_dir = self.memory_dir / "entities"
self.entities_dir.mkdir(exist_ok=True)
def log_today(self, content: str, section: str = "Notes") -> str:
"""Append to today's daily log file.
Args:
content: The memory content to log
section: Section header within the daily file
Returns:
Path to the updated file
"""
today = datetime.now().strftime("%Y-%m-%d")
daily_file = self.memory_dir / f"{today}.md"
if not daily_file.exists():
daily_file.write_text(f"# {today}\n\n")
with open(daily_file, "a") as f:
f.write(f"\n## {section}\n{content}\n")
return str(daily_file)
def remember(self, key: str, value: str, category: str = "General") -> None:
"""Store a key-value memory in long-term storage.
Args:
key: Short identifier for the memory
value: The content to remember
category: Section to file it under (Projects, Preferences, etc.)
"""
content = self.long_term_file.read_text() if self.long_term_file.exists() else "# Long-Term Memory\n"
# Find or create category section
section_header = f"## {category}"
if section_header not in content:
content += f"\n{section_header}\n"
# Append the memory entry
entry = f"- **{key}**: {value}\n"
insert_pos = content.index(section_header) + len(section_header) + 1
content = content[:insert_pos] + entry + content[insert_pos:]
self.long_term_file.write_text(content)
def search(self, query: str, max_results: int = 10) -> list[dict]:
"""Search all memory files for relevant content.
Args:
query: Search terms (supports multiple words)
max_results: Maximum number of matching lines to return
Returns:
List of dicts with 'file', 'line_number', 'content', 'score'
"""
terms = query.lower().split()
results = []
for md_file in self.memory_dir.rglob("*.md"):
lines = md_file.read_text().splitlines()
for i, line in enumerate(lines):
line_lower = line.lower()
score = sum(1 for term in terms if term in line_lower)
if score > 0:
results.append({
"file": str(md_file.relative_to(self.memory_dir)),
"line_number": i + 1,
"content": line.strip(),
"score": score / len(terms), # Normalize 0-1
})
results.sort(key=lambda x: x["score"], reverse=True)
return results[:max_results]
def get_recent_context(self, days: int = 3) -> str:
"""Load recent daily logs for context injection.
Args:
days: Number of recent days to include
Returns:
Combined content from recent daily files
"""
context_parts = []
for i in range(days):
date = (datetime.now() - timedelta(days=i)).strftime("%Y-%m-%d")
daily_file = self.memory_dir / f"{date}.md"
if daily_file.exists():
context_parts.append(daily_file.read_text())
return "\n---\n".join(context_parts)
def consolidate(self) -> str:
"""Review recent daily logs and extract key learnings into long-term memory.
Returns:
Summary of what was consolidated
"""
recent = self.get_recent_context(days=7)
# In practice, you'd send this to an LLM to extract key points
# Here we return the raw content for manual review
return f"Review these notes and update MEMORY.md:\n\n{recent}"
```
### Strategy 2: SQLite + Embeddings (Local Vector Search)
For agents that need semantic search — "find memories similar to X" rather than keyword matching. Uses SQLite for zero-infrastructure persistence and OpenAI embeddings for semantic similarity.
```typescript
// memory-store.ts — SQLite-backed semantic memory with vector search
/**
* Semantic memory store using SQLite + OpenAI embeddings.
* Stores memories with vector embeddings for similarity search.
* No external database required — everything in a single .db file.
*/
import Database from "better-sqlite3";
import OpenAI from "openai";
interface Memory {
id: number;
content: string;
category: string;
embedding: number[];
created_at: string;
metadata: Record<string, unknown>;
}
interface SearchResult {
content: string;
category: string;
similarity: number;
created_at: string;
}
export class MemoryStore {
private db: Database.Database;
private openai: OpenAI;
private model = "text-embedding-3-small"; // $0.02/1M tokens
constructor(dbPath: string = "agent-memory.db") {
this.db = new Database(dbPath);
this.openai = new OpenAI();
this.initSchema();
}
private initSchema(): void {
this.db.exec(`
CREATE TABLE IF NOT EXISTS memories (
id INTEGER PRIMARY KEY AUTOINCREMENT,
content TEXT NOT NULL,
category TEXT DEFAULT 'general',
embedding BLOB, -- Serialized float32 array
metadata TEXT DEFAULT '{}', -- JSON metadata
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
Related in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.