⌂ Home
Gemini CLI: From Zero to Production
Track 5 · Power Usage
Module 16 of 17 ~45 min Advanced
Module 15 · Track 5 — Power Usage

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 remove effectively
  • 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

Analogy — Personal Notes, Team Wiki, Standup Notes

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

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

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

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."

Animation — Memory Load Order on Session Start
gemini (session starts)
waiting
1. Load ~/.gemini/GEMINI.md (global preferences)
waiting
2. Walk up directory tree, find project GEMINI.md
waiting
3. Merge project GEMINI.md (overrides where specified)
waiting
4. Session Notes from previous /memory add calls available
waiting
Context assembled — session is personalized and project-aware
waiting
Understanding the load order tells you exactly where to put each piece of context. Now let's use the /memory commands to add context dynamically during a live session.

/memory Commands

Technical Definition — What /memory add Actually Does

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.

terminal — /memory commands
# 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
WHAT: Each entry gets a unique ID like 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

📄 ~/.gemini/GEMINI.md (after /memory add calls)
# 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..

Token Caching Tip

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

📄 ./GEMINI.md — project-level, backend API
# 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
WHAT: The MCP servers block registers the GitHub and Postgres MCP servers so they're available in every session without re-specifying them. WHY: Environment variables use ${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.
Memory tells Gemini what you know. Checkpoints protect what you've built. Together they make extended, complex refactoring sessions safe.

Checkpoints

Analogy — Git Stash for Your Entire AI Work Session

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

terminal — checkpoint workflow
# 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.
WHAT: Checkpoints are stored as file snapshots in %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.
Animation — Realistic Recovery Scenario
/checkpoint save "before auth refactor" → cp-001 created
waiting
Gemini: refactors 12 files across auth module
waiting
vitest: 4 tests fail — JWT validation broken
waiting
/restore list → cp-001 "before auth refactor" visible
waiting
/restore cp-001 → 12 files reverted
waiting
vitest: all 47 tests passing again — clean state
waiting
Why It Matters

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.

terminal — branching workflow
# 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:

strategy — weekly session structure
# 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\)
Tip — GEMINI.md as a Living Document

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?

A
To the project's ./GEMINI.md file
B
Only to the current session's in-memory context — not persisted
C
To ~/.gemini/GEMINI.md (global), under a ## Session Notes section
D
To a separate ~/.gemini/session-notes.md file
Correct! /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.
The note is written to the global ~/.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?

A
The global GEMINI.md always takes precedence
B
The project GEMINI.md overrides the global setting
C
The later-added /memory add always wins
D
They are merged additively — both models run in parallel
Correct! The load order is Global → Project → Session. Each level can override the previous. Project-level settings are more specific, so they take precedence over global defaults. This is the same layering principle as CSS specificity.
The project GEMINI.md is loaded after and overrides the global GEMINI.md. The order is: Global (base defaults) → Project (project-specific overrides) → Session notes (ephemeral additions). Later-loaded settings win for explicit overrides.

3. What does /checkpoint save "before refactor" actually store on disk?

A
A git commit with the message "before refactor"
B
A snapshot directory in ~/.gemini/checkpoints/ with copies of all modified files
C
The current conversation history and prompt context
D
A database snapshot including schema and data
Correct! Checkpoints are file-system snapshots stored in ~/.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.
Checkpoints store file-system snapshots in ~/.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?

A
The CLI only reads the first 1,000 tokens of GEMINI.md
B
It makes the file easier for humans to read
C
Gemini's context caching reuses the KV cache for stable content, reducing token cost and latency
D
Later content in GEMINI.md is automatically truncated by the CLI
Correct! Token caching works on the prefix of the context window. Stable content at the top of GEMINI.md creates a consistent prefix that gets cached after the first request. This can save tens of thousands of input tokens per day on active projects.
The reason is token caching. Gemini caches the KV computation for stable content prefixes. If stable content is at the top, it gets cached and reused across requests — reducing both cost and latency. Changing content at the top invalidates the cache.

5. You want to try two different approaches to implementing a feature and pick the better one. Which checkpoint workflow supports this?

A
Save a checkpoint after each approach, then use /restore diff to compare them
B
Implement both approaches in the same files using feature flags, then checkpoint once
C
Save a base checkpoint, implement Approach A, save a new checkpoint, restore base, implement Approach B, compare the two saved checkpoints
D
Session branching requires opening two separate terminal windows with different sessions
Correct! This is the session branching pattern. Save base → implement A → save A checkpoint → restore base → implement B → save B checkpoint. Now you have both implementations saved and can restore either one to make the final decision.
The session branching pattern works like this: save a base checkpoint, implement Approach A completely, save that as its own checkpoint, then restore the base checkpoint and implement Approach B. You now have both approaches saved and can restore either one.