Memory & Checkpoints
Every conversation with Gemini CLI starts fresh — unless you design it not to. Memory and checkpoints are the architecture that turns ephemeral sessions into a coherent, long-running AI pair programmer that knows your project deeply, remembers your conventions, and can recover from any misstep without losing your work.
What You'll Learn
- Understand the three-level memory hierarchy: Global, Project, and Session
- Use
/memory add,/memory list, and/memory removeeffectively - Author an advanced GEMINI.md with model selection, MCP blocks, and caching hints
- Create manual checkpoints and restore project state after a bad refactor
- Use session branching to explore alternative implementation strategies safely
- Build a cross-session memory strategy for multi-week projects
Three-Level Memory Architecture
Think of the three memory levels like a developer's note-taking system. Your personal dotfiles and IDE config (global GEMINI.md) travel everywhere you go — your preferred code style, your timezone, your name. The team wiki for a specific project (project GEMINI.md) lives in the repo and contains project-specific rules everyone working on it should follow. Your daily standup sticky notes (/memory add in session) capture what's relevant right now — "today I'm focusing on the auth module, ignore the legacy endpoints." The pain without this structure: you repeat yourself every single session, re-establishing context that should be permanent.
Global GEMINI.md
Path: %USERPROFILE%\.gemini\GEMINI.md (Windows) / ~/.gemini/GEMINI.md (Unix). Loaded for every Gemini CLI session, regardless of directory. Ideal for: your name, coding preferences, preferred languages, default model, recurring MCP servers.
Project GEMINI.md
Path: ./GEMINI.md in the current working directory (or any parent up to the repo root). Loaded only when Gemini CLI is run from within that directory tree. Ideal for: project stack, coding standards, database schema summaries, team contacts, deployment targets.
Session Memory
Added via /memory add "..." during an active session. Appended to ~/.gemini/GEMINI.md under a ## Session Notes section. Persists across sessions once written. Ideal for: transient context like "currently debugging the payment webhook," "ignore the legacy v1 endpoints for now."
/memory Commands
The /memory add commandA Gemini CLI built-in command that appends a text entry to the ## Session Notes section of your global ~/.gemini/GEMINI.md file. The entry is immediately active in the current session and persists to all future sessions until removed with /memory remove <id>. is not just a conversational hint — it writes to your filesystem. The text is appended to ~/.gemini/GEMINI.md under a ## Session Notes section with a timestamp and auto-generated ID. It survives session restarts because it becomes part of the global GEMINI.md that's loaded at the start of every session.
# Add a persistent context note
/memory add "Use TypeScript strict mode for all new files"
# Add project-specific database context
/memory add "DB: Postgres 16, connection string in .env as DATABASE_URL"
# Add a temporary focus note
/memory add "Currently working on auth module — ignore legacy v1 endpoints"
# List all active session notes with their IDs
/memory list
# Output:
# [mem-1] Use TypeScript strict mode for all new files
# [mem-2] DB: Postgres 16, connection string in .env as DATABASE_URL
# [mem-3] Currently working on auth module — ignore legacy v1 endpoints
# Remove a note by ID when no longer relevant
/memory remove mem-3
mem-1, mem-2. WHY: The ID lets you surgically remove individual notes without editing the GEMINI.md file manually. GOTCHA: /memory add only writes to the global GEMINI.md — it does NOT write to the project GEMINI.md. Put project-wide rules in the project file directly.
What Gets Written to GEMINI.md
# Global Gemini CLI Config
## Preferences
- Name: Vara Srinivas
- Default model: gemini-2.5-pro
- Timezone: America/New_York
## Session Notes
<!-- Added 2026-06-09 -->
- [mem-1] Use TypeScript strict mode for all new files
- [mem-2] DB: Postgres 16, connection string in .env as DATABASE_URL
What Just Happened?
The two /memory add calls above created two bullet points under ## Session Notes. These are now part of the system context for every future Gemini CLI session on this machine — until you explicitly remove them with /memory remove. Think of it as writing to your AI's long-term memory.
Advanced GEMINI.md
A well-crafted GEMINI.md does far more than list preferences. It configures model behavior, registers MCP servers, and provides stable context that benefits from token cachingGemini's context caching feature reuses the computed KV cache for stable content (like a long GEMINI.md) across multiple requests. This reduces both latency and token cost when the same prefix appears in many prompts..
Put your most stable content (project description, schema, style rules) at the top of GEMINI.md. Gemini's context caching computes the KV cache once for stable content, then reuses it across requests in the same project. A well-structured 2,000-token GEMINI.md loaded 50 times per day saves roughly 100,000 input tokens — that's real cost reduction at scale.
Backend API Project Template
# Project: TaskFlow API
## Stack
- Runtime: Node.js 22 LTS, TypeScript 5.4 (strict mode)
- Framework: Express 5 + Zod for validation
- Database: PostgreSQL 16 via Prisma ORM
- Auth: JWT (RS256), tokens in Authorization header
- Testing: Vitest + Supertest, coverage target ≥ 80%
- Linting: ESLint flat config + Prettier
## Conventions
- All new files: TypeScript strict mode, no `any` without comment
- Error handling: always return { error: string, code: string } shape
- Database queries: use Prisma transactions for multi-step writes
- Environment variables: all in .env, validated with zod at startup
- Branch naming: feat/*, fix/*, chore/*
- Commit style: Conventional Commits
## MCP Servers
```json
{
"mcpServers": {
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": { "GITHUB_TOKEN": "${GITHUB_TOKEN}" }
},
"postgres": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres"],
"env": { "DATABASE_URL": "${DATABASE_URL}" }
}
}
}
```
## Model Config
- model: gemini-2.5-pro
- temperature: 0.2 # Low for consistent code generation
## Contacts (for GitHub issue assignment)
- vara = @vara-srinivas
- devops = @devops-team
${VAR} syntax so secrets never appear in GEMINI.md itself. GOTCHA: The temperature setting in GEMINI.md overrides the CLI default but can still be overridden per-prompt with --temperature.
Checkpoints
Imagine a surgeon who, before making any major incision, takes a complete photograph of the patient's current state. Before every significant change in Plan Mode, Gemini CLI does exactly this. The pain of working without checkpoints: Gemini makes 8 correct file edits, then on edit 9 breaks something critical — and you have to manually undo or git checkout file by file, hoping you remember which ones changed. The mapping: checkpoints snapshot the entire working state — every file, every pending change — so you can restore to any previous moment in seconds.
Auto-Checkpoints in Plan Mode
In Plan Mode (/plan), Gemini CLI automatically saves a checkpoint before executing each step. The checkpoint ID appears in the Plan output so you always know what to restore if something goes wrong.
Manual Checkpoint Commands
# Save a named checkpoint before a risky refactor
/checkpoint save "before refactor"
# Output: Checkpoint saved: cp-20260609-143201 "before refactor"
# Location: %USERPROFILE%\.gemini\checkpoints\cp-20260609-143201\
# ... Gemini makes changes, something breaks ...
# List all available checkpoints
/restore list
# Output:
# cp-20260609-143201 "before refactor" 3 min ago 47 files
# cp-20260609-131055 "auto: plan step 3/7" 1 hour ago 44 files
# cp-20260609-094422 "before auth refactor" 4 hours ago 38 files
# Restore to the named checkpoint
/restore cp-20260609-143201
# Output: Restoring 47 files to state "before refactor"...
# Restored successfully. Your working directory matches checkpoint cp-20260609-143201.
%USERPROFILE%\.gemini\checkpoints\. Each checkpoint is a directory containing copies of every file that was modified since the previous checkpoint. GOTCHA: Checkpoints do NOT snapshot your database state, only files. If Gemini ran migrations, you'll need to handle those separately.
The average multi-file refactor with Gemini CLI touches 8–15 files. Without checkpoints, a broken refactor requires reading each modified file, understanding what changed, and manually reverting. With checkpoints, recovery is one command and takes under 5 seconds. Teams using checkpoints report 3x faster iteration on large refactors because the fear of "what if it breaks" disappears.
Session Branching
Session branchingThe practice of saving a checkpoint, exploring one implementation approach to completion, then restoring the checkpoint and trying an alternative approach. Like git branches but for AI-assisted work sessions — you can compare two approaches before committing to one. is the technique of using checkpoints to explore multiple implementation strategies in parallel — the same way you'd use git branches for code, but for the AI work session itself.
# Starting point: working rate-limiter implementation needed
/checkpoint save "before rate-limiter — clean state"
# → cp-branch-base created
# ── APPROACH A: in-memory rate limiting with Map ──
# Ask Gemini to implement using in-memory Map + sliding window
# Gemini modifies: src/middleware/rateLimiter.ts, src/app.ts, tests/
# After implementation, run tests to evaluate
# vitest: 52/52 passing, no Redis dependency
/checkpoint save "approach-A: in-memory sliding window"
# → cp-branch-A created
# ── Restore and try Approach B ──
/restore cp-branch-base
# Back to clean state
# APPROACH B: Redis-backed rate limiting with ioredis
# Ask Gemini to implement using Redis + sliding window
# Gemini modifies: src/middleware/rateLimiter.ts, docker-compose.yml, src/app.ts
# vitest: 52/52 passing, requires Redis sidecar
/checkpoint save "approach-B: Redis sliding window"
# → cp-branch-B created
Comparing the Two Approaches
| Criterion | Approach A (In-Memory) | Approach B (Redis) |
|---|---|---|
| Dependencies | None | ioredis + Redis sidecar |
| Multi-instance support | No (per-process state) | Yes (shared state) |
| Restart behavior | State lost on restart | Persistent |
| Local dev complexity | Zero setup | Requires Docker |
| Production suitability | Single-instance only | Production-ready |
What Just Happened?
You explored two complete implementations in the same session without permanently committing to either. The comparison table above was generated by asking Gemini to compare the two checkpoints — it read both cp-branch-A and cp-branch-B and produced the analysis. You then chose Approach B and restored that checkpoint as your working state.
Cross-Session Strategy for Long Projects
A multi-week project spanning many Gemini CLI sessions needs deliberate memory architecture. Here's a practical pattern that keeps context sharp and sessions efficient:
# Weekly Cross-Session Pattern
## Start of week (Monday session)
1. Review /memory list — prune stale notes
2. Update project GEMINI.md with any new decisions from last week
3. /checkpoint save "week-N start"
## During the week (each session)
- /memory add for any new constraints discovered
- /checkpoint save before any significant refactor
- Keep session notes current ("now implementing X, skip Y")
## End of week (Friday session)
1. /memory list — document key decisions made
2. Update project GEMINI.md ## Status section with progress
3. /checkpoint save "week-N end — <summary of state>"
4. Prune old checkpoints older than 2 weeks:
/restore list --older-than 14d
(manual deletion from %USERPROFILE%\.gemini\checkpoints\)
Treat your project GEMINI.md the same way you'd treat a team ADR (Architecture Decision Record). Every significant decision made with Gemini CLI — "we chose Redis over in-memory," "the webhook endpoint is /api/webhooks/stripe," "auth tokens expire in 15 minutes" — gets a one-line entry in GEMINI.md. This means the next session starts with full institutional memory, not just code.
Checkpoint — You Now Have Production-Grade Memory and Recovery
You have a three-level memory hierarchy, /memory commands for live context, an advanced GEMINI.md template, checkpoint-based recovery, and a session branching pattern for safe experimentation. These are the tools that separate occasional Gemini CLI users from power users who use it as their primary coding environment.
Knowledge Check
Five questions on memory architecture, /memory commands, and checkpoints.
1. You run /memory add "Ignore the legacy v1 endpoints". Where is this note written?
./GEMINI.md file
~/.gemini/GEMINI.md (global), under a ## Session Notes section
~/.gemini/session-notes.md file
/memory add always writes to the global GEMINI.md, not the project one. This ensures the note persists across sessions. Use /memory remove <id> to clean up when the note is no longer relevant.~/.gemini/GEMINI.md file under ## Session Notes. It persists across sessions because it becomes part of the global context file loaded at every session start.2. In the memory load order, if both the global GEMINI.md and the project GEMINI.md specify a model setting, which one takes precedence?
/memory add always wins
3. What does /checkpoint save "before refactor" actually store on disk?
~/.gemini/checkpoints/ with copies of all modified files
~/.gemini/checkpoints/<id>/. They do NOT create git commits (though you should still commit to git separately). They also do NOT snapshot database state — only files.~/.gemini/checkpoints/. They are independent of git (no git commits are made). They do not include database state. Think of them as a quick "undo everything" mechanism for files only.4. Why should you place stable, long-lived content (project description, schema) at the TOP of GEMINI.md?
5. You want to try two different approaches to implementing a feature and pick the better one. Which checkpoint workflow supports this?
/restore diff to compare them