6 The Building Blocks
Understanding the configuration layers helps you customize the workflow and debug when things go wrong. Antigravity’s power comes from five configuration layers that work together — think of them as the operating system for your academic project.
6.1 GEMINI.md — Your Project’s Constitution
GEMINI.md is the single most important file. Gemini reads it at the start of every session. But here is the critical insight: Gemini reliably follows about 100–150 custom instructions. Your system prompt already uses ~50, leaving ~100–150 for your project. GEMINI.md and always-on rules share this budget.
This means GEMINI.md should be a slim constitution — short directives and pointers, not comprehensive documentation. Aim for ~120 lines:
- Core principles — 4–5 bullets (plan-first, verify-after, quality gates, LEARN tags)
- Folder structure — where everything lives
- Commands — compilation, deployment, key tools
- Customization tables — Beamer environments, CSS classes
- Current state — what’s done, what’s in progress
- Skill quick reference — table of available skills
Move everything else into .agents/rules/ files (with path-scoping so they only load when relevant).
# GEMINI.MD --- My Project
**Project:** [Your Project Name]
**Institution:** [Your Institution]
## Core Principles
1. **Plan-first** — enter plan mode before non-trivial tasks
2. **Verify-after** — compile/render and check before reporting done
3. **Quality gates** — 80 to commit, 90 for PR, 95 for excellence
4. **LEARN tags** — persist corrections in MEMORY.md
5. **Single source of truth** — Beamer is authoritative; derive, don't duplicate
## Quick Reference
| Command | What It Does |
|---------|-------------|
| `compile-latex [file]` | 3-pass XeLaTeX compilation |
| `proofread [file]` | Grammar/typo review |
| `deploy [Lecture]` | Render and deploy to GitHub Pages |GEMINI.md loads every session. If it exceeds ~150 lines, Gemini starts ignoring rules silently. Put detailed standards in path-scoped rules (.agents/rules/) instead — they only load when Gemini works on matching files, so they don’t compete for attention.
6.2 Rules — Domain Knowledge That Auto-Loads
Rules are markdown files in .agents/rules/ that Gemini loads automatically. They encode your project’s standards. The key design principle is path-scoping: rules with a paths: YAML frontmatter only load when Gemini works on matching files.
Always-on rules (no paths: frontmatter) load every session. Keep these few and focused:
.agents/rules/
├── plan-first-workflow.md # ~83 lines — plan before you build
├── orchestrator-protocol.md # ~42 lines — contractor mode loop
├── session-logging.md # ~23 lines — three logging triggers
└── meta-governance.md # ~251 lines — template vs working project
Path-scoped rules load only when relevant:
.agents/rules/
├── r-code-conventions.md # paths: ["**/*.R"] — R standards
├── quality-gates.md # paths: ["*.tex", "*.qmd", "*.R"] — scoring
├── verification-protocol.md # paths: ["*.tex", "*.qmd", "docs/"] — verify before done
├── replication-protocol.md # paths: ["scripts/**/*.R"] — replicate first
├── exploration-folder-protocol.md # paths: ["explorations/**"] — sandbox rules
├── orchestrator-research.md # paths: ["scripts/**/*.R", "explorations/**"] — simple loop
└── ...20 path-scoped rules total
The first three always-on rules total ~148 lines of actionable instructions. meta-governance is a reference document for the template’s dual nature (working project vs. public template) and loads passively. Path-scoped rules add rich, domain-specific guidance exactly when Gemini needs it.
Sync vs. translate: The beamer-quarto-sync rule handles incremental edits — fix a typo in Beamer, same fix goes to Quarto. The translate-to-quarto skill is for full initial translation of a new lecture. Translate once, sync thereafter.
Why rules matter: Without them, Gemini will use generic defaults. With them, Gemini follows your standards consistently across sessions.
6.2.1 Example: Path-Scoped R Code Conventions Rule
---
paths:
- "**/*.R"
- "Figures/**/*.R"
- "scripts/**/*.R"
---# R Code Standards
## Reproducibility
- set.seed() called ONCE at top (YYYYMMDD format)
- All packages loaded at top via library()
- All paths relative to repository root
## Visual Identity
primary_blue <- "#012169"
primary_gold <- "#f2a900"The paths: block means this rule only loads when Gemini reads or edits an .R file. When Gemini works on a .tex file, this rule doesn’t consume any of the instruction budget.
6.3 Constitutional Governance (Optional)
As your project grows, some decisions become non-negotiable (to maintain quality, reproducibility, or collaboration standards). Others remain flexible.
The templates/constitutional-governance.md template helps you distinguish between:
- Immutable principles (Articles I-V): Non-negotiable rules that ensure consistency
- User preferences: Flexible patterns that can vary by context
6.3.1 Example Articles You Might Define
- Article I: Primary Artifact — Which file is authoritative (e.g.,
.texvs.qmd,.Rmdvs.html, notebook vs script) - Article II: Plan-First Threshold — When to enter plan mode (e.g., >3 files, >30 min, multi-step workflows)
- Article III: Quality Gate — Minimum score to commit (e.g., 80/100, all tests passing)
- Article IV: Verification Standard — What must pass before commit (e.g., compile, tests, render)
- Article V: File Organization — Where different file types live (prevents scattering)
The template includes examples for LaTeX, R, Python, Jupyter, and multi-language workflows.
Use constitutional governance after you’ve established 3-7 recurring patterns that you want to enforce consistently. Don’t create it on day one — let patterns emerge first, then codify them. Skip it for solo projects with evolving standards, or when you prefer case-by-case decisions.
Template: templates/constitutional-governance.md
6.4 Skills — Reusable Slash Commands
Skills are multi-step workflows invoked with /command. Each skill lives in .agents/skills/[name]/SKILL.md:
---
name: compile-latex
description: Compile LaTeX with 3-pass XeLaTeX + bibtex
argument-hint: "[filename without .tex extension]"
---
# Steps:
1. cd to Slides/
2. Run xelatex pass 1
3. Run bibtex
4. Run xelatex pass 2
5. Run xelatex pass 3
6. Check for errors
7. Report resultsSkills you get in the template:
| Skill | Purpose | When to Use |
|---|---|---|
compile-latex |
Build PDF from .tex | After any Beamer edit |
deploy |
Render Quarto + sync to docs/ | Before pushing to GitHub Pages |
proofread |
Grammar and consistency check | Before every commit |
qa-quarto |
Adversarial Quarto QA | After translating Beamer to Quarto |
slide-excellence |
Full multi-agent review | Before major milestones |
create-lecture |
New lecture from scratch | Starting a new topic |
commit |
Stage, commit, PR, merge | After any completed task |
Antigravity ships with built-in skills beyond this template’s 131: /batch orchestrates parallel refactoring across your codebase (using git worktrees for isolation), /simplify runs 3-agent code review and applies fixes, and /debug helps troubleshoot sessions. These complement the academic skills above.
6.5 Agents — Specialized Reviewers
Agents are the real power of this system. Each agent is an expert in one dimension of quality:
.agents/agents/
+-- proofreader.md # Grammar, typos, consistency
+-- slide-auditor.md # Visual layout, overflow, spacing
+-- pedagogy-reviewer.md # Narrative arc, notation clarity, pacing
+-- r-reviewer.md # R code quality and reproducibility
+-- tikz-reviewer.md # TikZ diagram visual quality
+-- quarto-critic.md # Adversarial Quarto vs Beamer comparison
+-- quarto-fixer.md # Applies critic's fixes
+-- beamer-translator.md # Beamer -> Quarto translation
+-- verifier.md # Task completion verification
+-- domain-reviewer.md # YOUR domain-specific substance review
+-- project-coordinator.md # Coordinator for theoretical workstreams
+-- prover.md # Drafts mathematical proofs
+-- literature-reviewer.md # Conducts verified literature reviews
+-- paper-reviewer.md # Gates workstream completion
+-- coder.md # Runs computational experiments
+-- lean-prover.md # Formalizes proofs in Lean 4
6.5.1 Agent Anatomy
Each agent file has YAML frontmatter + detailed instructions:
---
name: proofreader
description: Reviews slides for grammar, typos, and consistency
---
# Proofreader Agent
## Role
You are an expert academic proofreader reviewing lecture slides.
## What to Check
1. Grammar and spelling errors
2. Inconsistent notation
3. Missing or broken citations
4. Content overflow (text exceeding slide bounds)
## Report Format
Save findings to: quality_reports/[FILENAME]_report.md
## Severity Levels
- **Critical:** Math errors, broken citations
- **Major:** Grammar errors, overflow
- **Minor:** Style inconsistenciesA single Gemini prompt trying to check grammar, layout, math, and code simultaneously will do a mediocre job at all of them. Specialized agents focus on one dimension and do it thoroughly. The slide-excellence skill runs them all in parallel, then synthesizes results.
Antigravity also offers experimental Agent Teams — multiple independent sessions that coordinate, share findings, and challenge each other’s approaches. This is a research preview feature; the orchestrator + subagent pattern described here is more mature for academic workflows.
6.5.2 Multi-Model Strategy: Cost vs. Quality
In the Antigravity workflow, model selection is optimized around Google’s Gemini models:
- gemini-3.7-flash (High): The primary flagship model for high-judgment, reasoning, and complex coding tasks. Highly capable at complex instruction-following.
- gemini-3.1-pro: The stable mid-tier model in the current lineup. Ideal for review, critique, and general analysis.
- gemini-3.5-flash (Low): The stable, lowest-tier model in the current lineup. Extremely cost-efficient and ideal for mechanical operations, file checks, and routine formatting.
Not all agents need the same model. Each agent file has a model: field in its YAML frontmatter. By default, all agents use model: inherit (they use whatever model your main session runs). But you can customize this to optimize cost:
| Task Type | Recommended Model | Why | Examples |
|---|---|---|---|
| Complex review / audit | model: gemini-3.7-flash (High) |
Needs deep reasoning and synthesis | claim-verifier, editor, methods-referee |
| Review / critique | model: gemini-3.1-pro |
Good balance of reasoning ability and cost | r-reviewer, slide-auditor, proofreader |
| Fast, mechanical work | model: gemini-3.5-flash (Low) |
Speed and cost efficiency are paramount | quarto-fixer, TikZ extraction |
| Default | model: inherit |
Uses whatever the main session runs | any unrouted subagent |
The principle: Use the highest-tier gemini-3.7-flash (High) model for tasks that require holding multiple large contexts in mind simultaneously (translation, adversarial review, claim verification). Route review/critique tasks to gemini-3.1-pro, and mechanical tasks to the highly cost-efficient gemini-3.5-flash (Low) model. Let everything else inherit.
To change an agent’s model, edit its YAML frontmatter:
---
name: quarto-critic
model: gemini-3.7-flash (High) # was: inherit
---If you configure model-per-agent, a typical Beamer-to-Quarto translation runs the critic on gemini-3.7-flash (High) (2–4 rounds) while the fixer runs on gemini-3.5-flash (Low) (same rounds). This can save roughly 50–80% compared to running everything on the highest tier, with no quality loss on the fixing step.
6.5.3 Advanced Agent Configuration
Beyond model selection, agent definitions support several configuration fields:
| Field | Purpose | Example |
|---|---|---|
model |
Force a specific model | gemini-3.5-flash (Low), gemini-3.1-pro, gemini-3.7-flash (High) |
maxTurns |
Limit agent iterations | 10 (prevents runaway loops) |
isolation |
Run in a git worktree | worktree (see Pattern 12) |
effort |
Override reasoning effort | high |
permissionMode |
Restrict permissions | plan (read-only agent) |
tools |
Whitelist specific tools | ["view_file", "grep_search", "run_command"] |
disallowedTools |
Blacklist specific tools | ["replace_file_content", "write_to_file"] |
skills |
Make specific skills available | ["compile-latex"] |
background |
Run concurrently | true |
Example: a read-only proofreader that can’t edit files:
---
name: proofreader
model: gemini-3.7-flash (High)
maxTurns: 15
tools: ["view_file", "grep_search"]
---Use maxTurns to prevent review agents from looping indefinitely, and tools to enforce read-only behavior for agents that should only produce reports.
6.5.4 Cost-Conscious Composition: Caching, Routing, and Diagnostics
Cost is invisible until you look at the monthly invoice. Three levers, in order of impact:
1. Context caching. Google’s Context Caching for the Gemini API lets repeated prefix tokens (system instructions, personal memory, large codebase context, and reference documents) bypass active input token costs, running at a fraction of the standard price.
- Automatic management: Antigravity handles cache construction and prefix alignment automatically behind the scenes.
- Default TTL: Cached context typically persists for a default TTL of 1 hour, making it highly effective for rapid iterative session turns.
2. Per-agent model routing. The Multi-Model Strategy table above lists the principle; the 70/20/10 pattern is the operational form:
| Model | Share of subagent calls | Use for |
|---|---|---|
| gemini-3.5-flash (Low) | ~70% | Mechanical work: TikZ extraction, citation reformatting, bib validation, proofread fixes, simple file lookups |
| gemini-3.1-pro | ~20% | Review and critique: r-reviewer, slide-auditor, proofreader, humanize-auditor |
| gemini-3.7-flash (High) | ~10% | High-judgment work: editor, domain-referee, methods-referee, claim-verifier, manuscript review, quarto-critic |
Set per-agent via model: in .agents/agents/<name>.md frontmatter. Typical savings vs. all-Pro: 50–80% on routed skills, with no quality loss on the mechanical tier. This pattern aligns with industry-standard architect/editor splits.
3. Effort budgeting. Some Gemini models support customizable reasoning effort levels. Default to medium or standard modes for routine reviews and formatting, and reserve higher effort configurations for deep academic audits, comprehensive paper reviews, or complex codebase refactors.
You can monitor session token usage and costs via standard platform developer dashboards. Review your usage after any large review-paper --peer pipeline to verify that your Context Caching hit rate is healthy and your model routing is working correctly.
Headless subprocess runs (antigravity -p) and parallel subagent spawning can consume API rate limits (TPM/RPM) and quotas quickly. If your pipeline fails with rate-limiting errors (HTTP 429), configure exponential backoff in your client configuration or request a quota increase in Google AI Studio or GCP Console. See TROUBLESHOOTING.md for details.
6.6 Settings — Permissions and Hooks
.agents/settings.json controls what Gemini is allowed to do. Here is json { "permissions": { "defaultMode": "bypassPermissions", "allow": [ "view_file", "write_to_file", "replace_file_content", "multi_replace_file_content", "run_command", "list_dir", "grep_search", "invoke_subagent" ] } }
Permission modes. Antigravity has five permission modes that control how much autonomy Gemini gets:
| Mode | Internal Name | Behavior | When to Use |
|---|---|---|---|
| Normal | default |
Asks before risky actions | Day-to-day work — approve each edit |
| Auto-accept edits | acceptEdits |
Auto-approves file edits | Trusted batch operations (rename across 20 files) |
| Don’t ask | dontAsk |
Auto-denies tools unless pre-approved in allowlist | Restricted environments where only allowlisted tools run |
| Plan | plan |
Read-only — no edits allowed | Exploring code, reviewing before acting |
| Auto | auto |
Classifier-gated; everything runs unless flagged risky (Mar 2026 Week 13; the --enable-auto-mode flag is no longer required for Max + gemini-3.5-flash (High) users as of Apr 2026 Week 16) |
Long autonomous tasks with safety net — the recommended mode for trusted repos when bypass is too permissive |
| Bypass | bypassPermissions |
Skips all permission prompts | CI/CD pipelines, headless scripts (still prompts on protected paths: .git, .vscode, .idea, .husky, .agents minus carve-outs commands/agents/skills/worktrees) |
Set via CLI flag (antigravity --permission-mode plan), the /config command, or permissions.defaultMode in settings.json.
6.6.1 The Six-Layer Permission Stack
Permission mode is not resolved from a single file. Antigravity honors six layers, with later layers overriding earlier ones:
| # | Layer | Location | Key |
|---|---|---|---|
| 1 | VSCode user | ~/Library/Application Support/Code/User/settings.json (macOS), ~/.config/Code/User/settings.json (Linux), %APPDATA%/Code/User/settings.json (Windows) |
antigravity.initialPermissionMode |
| 2 | VSCode workspace | <repo>/.vscode/settings.json |
antigravity.initialPermissionMode |
| 3 | CLI user | ~/.agents/settings.json |
permissions.defaultMode |
| 4 | CLI project | <repo>/.agents/settings.json |
permissions.defaultMode |
| 5 | CLI project-local (gitignored) | <repo>/.agents/settings.local.json |
permissions.defaultMode |
| 6 | In-session runtime | (ephemeral) | toggled via Shift+Tab / /permission-mode |
Layer 6 is authoritative and catches most users off-guard. initialPermissionMode only fires at session start — if you (or Shift+Tab) change modes mid-session, every file-level layer is ignored until the session ends.
6.6.2 Troubleshooting: Prompts Fire Despite bypassPermissions
This is the single most common source of confusion. Work through the checklist in order:
- Look at the status line at the top of the Antigravity panel. With this repo’s
statusLineconfigured, it prints[BYPASS],[PLAN],[AUTO-EDIT], or[PROMPT]for the four standard modes. Any other mode Antigravity reports (e.g.,dontAsk) is shown as a bracketed raw name like[dontAsk]. If it doesn’t say[BYPASS], you have an in-session override — pressShift+Tabto cycle modes until you land on bypass. - Run
permission-checkto see every layer’s value, the resolved merged state, and any drift (e.g., project says bypass but project-local says default). - Check for stale sessions. If settings changed recently but the session predates the change, it still runs under the old mode. Reload the window (
Cmd+Shift+P→ “Developer: Reload Window”) and start a new session. - Check
denylists. A match in any layer’sdenyblocks the tool regardless ofallowentries elsewhere. - VSCode vs CLI split. If the VSCode layers say bypass but no CLI layer does, a terminal-launched Antigravity will still prompt. Align them.
6.6.3 The Plan → Bypass Handoff (Recommended Daily Driver)
Plan mode and bypass permissions sound like opposites, but they chain into a single workflow that gives you a review-before-execute convenience: you see the approach before any edits happen, then execution runs without per-tool prompts.
Approving an implementation plan artifact releases the session to your defaultMode — typically bypassPermissions. Once there, any subsequent tool call (replace_file_content, write_to_file, run_command) executes under the full allowlist in your settings.json, not a scope derived from the plan. A mistaken implementation can still edit unrelated files or run destructive shell commands with no second checkpoint.
Treat this flow as a convenience pattern, not a security control. If you need a hard enforcement boundary, keep defaultMode: "default" and approve each high-risk tool individually, or run the whole session in plan mode and copy actions out manually.
The flow:
Start session in plan mode (Shift+Tab at startup, or antigravity --permission-mode plan)
|
| Read-only exploration + planning
| Gemini can view_file, grep_search, run_command readonly, spawn Explore/Plan agents
| Gemini CANNOT edit files (except the plan artifact itself)
|
v
Plan drafted as implementation_plan.md artifact (with RequestFeedback: true)
|
v
User approves plan via interactive UI Proceed button
|
v
Antigravity proceeds with execution in defaultMode.
|
| If defaultMode = bypassPermissions, execution now runs
| without approval prompts.
v
Orchestrator executes the plan end-to-end --- no prompts.
Why this is the recommended daily flow:
- You always see the approach before any edits happen (plan mode is read-only).
- Once you approve, every downstream action — edits, bash, multi-file refactors — runs without interruption.
- No need to remember to toggle bypass mid-session. The handoff is automatic.
- Fits cleanly with the plan-first rule enforced by this repo.
Prerequisite: your defaultMode must be bypassPermissions in at least one CLI layer (typically the project or project-local layer). Without that, exiting plan mode returns you to default and you’re back to per-tool prompts.
6.6.4 Session Management
A handful of recent Mar–Apr 2026 commands cut friction in the actual editing loop. Worth knowing before you reach for them in a panic:
| Command / shortcut | What it does | When to reach for it |
|---|---|---|
/btw <question> |
Asks a side question whose answer appears in a dismissible overlay — never enters conversation history | Quick “what does X do?” / “is this version compatible?” questions you don’t want bloating context |
Esc Esc or /rewind |
Opens the rewind menu — restore conversation, code, or both to a prior checkpoint | Tried something risky, want to undo cleanly without git reset (checkpoints are NOT git — only Gemini-made changes are tracked) |
/clear |
Resets the conversation context entirely | Switching to an unrelated task; long session with cluttered context |
/compact <instruction> |
Guided summarization of the current conversation | “Compact, focusing on the API changes” — selective preservation before continuing on the same task |
Ctrl+G (in plan mode) |
Opens the in-progress plan file in $EDITOR for direct editing before approval |
You want to surgically tweak the plan without typing instructions back to Gemini |
antigravity --continue / antigravity --resume |
Resume the most recent conversation (--continue) or pick from recent (--resume); rename with /rename |
Picking up a multi-day project — treat sessions like branches |
checkpoint <slug> |
Writes a structured state snapshot to quality_reports/checkpoints/ (this template, not Anthropic’s) |
Before stopping or handing off — companion to the narrative session log |
/goal <verifiable condition> |
Sets an end-state condition; Gemini keeps working across turns until a fast model confirms it holds (Apr 2026 Week 20, v2.1.139) | “All R scripts pass without errors”, “Figure 3 renders to PDF without overflow” — pair with commit quality gates for verified-end-state runs |
Three patterns that compose well:
- Side question without polluting context:
/btw why does Quarto need ::: for callouts?— get the answer, dismiss, keep working. - Long session, want to switch tasks:
checkpoint current-workthen/clearthen start the new task. Resume the first withantigravity --resume. - Plan mid-edit: During plan mode,
Ctrl+Gto edit the plan file directly — faster than dictating revisions back to Gemini.
By default, Gemini saves plans to a global directory (~/.agents/plans/), not your project. To keep plans with your project (and in git), add this to .agents/settings.json:
{
"plansDirectory": "quality_reports/plans"
}The Stop hook runs a fast Python script after every response. No LLM call, no latency. It checks whether the session log is current and reminds Gemini to update it if not. Behavioral rules like verification and Beamer-Quarto sync are enforced via auto-loaded rules in .agents/rules/, which is the right tool for nuanced judgment that Gemini can evaluate in-context.
6.7 Effort Levels — Cost vs. Thoroughness
Antigravity lets you control how deeply it reasons about each task. Higher effort means more “thinking tokens” and better results — but higher cost.
| Level | Thinking Budget | Academic Use Case | Relative Cost |
|---|---|---|---|
low |
Minimal | Quick formatting, grep, file renames | $ |
medium |
Standard | Most tasks (default for gemini-3.7-flash (High)) | $$ |
high |
~10k tokens | Complex derivations, paper reviews | $$$ |
xhigh |
~20k tokens | Recommended for gemini-3.7-flash (High) coding (introduced Apr 2026 Week 16) | $$$ |
max / ultrathink |
~32k tokens | Deep proofs, multi-step analysis | $$$$$ |
How to set effort:
- Per-session: Type
/effort high(or/effort xhighfor gemini-3.7-flash (High) coding work). Typing/efforton its own opens an interactive slider (Apr 2026 Week 16). - Per-skill: Add
effort: highto skill frontmatter (see Skill Frontmatter Reference) - Keyboard toggle:
Option+T(Mac) /Alt+T(Windows/Linux) toggles extended thinking - In prompts: Include “ultrathink” in your prompt to enable extended thinking for that turn. Note: phrases like “think hard” are treated as regular instructions and do not allocate extra thinking tokens
- Environment variable:
ANTIGRAVITY_CODE_EFFORT_LEVEL=highfor all sessions - Hooks can read it: As of Apr 2026 Week 19, hook input includes
effort.leveland$ANTIGRAVITY_EFFORTis set in Bash subprocess env — useful for skipping expensive verification on low-effort runs
Effort levels compose with model selection for fine-grained cost control. For example, gemini-3.5-flash (Low) + high effort costs less than gemini-3.7-flash (High) + low effort but may produce comparable results for bounded tasks like formatting. Use gemini-3.7-flash (High) + max only for tasks that genuinely require deep multi-step reasoning — complex proofs, intricate data pipeline debugging, or comprehensive paper critique.
6.8 Memory — Cross-Session Persistence
Antigravity has an auto-memory system at ~/.agents/projects/[project]/memory/MEMORY.md. This file persists across sessions and is loaded into every conversation.
Use it for: - Key project facts that never change - Corrections you don’t want repeated ([LEARN:tag] format) - Current plan status
# Auto Memory
## Key Facts
- Project uses XeLaTeX, not pdflatex
- Bibliography file: Bibliography_base.bib
## Corrections Log
- [LEARN:r-code] Package X drops obs silently when covariate is missing
- [LEARN:citation] Post-LASSO is Belloni (2013), NOT Belloni (2014)
- [LEARN:workflow] Every Beamer edit must auto-sync to Quarto6.8.0.1 Two-tier memory architecture (MEMORY.md vs personal-memory.md)
The template splits memory into two tiers (see meta-governance.md):
MEMORY.md(committed, ≤ 200 lines) — generic learnings that help all forkers: workflow patterns, design principles, documentation standards, quality thresholds that transfer across domains..agents/state/personal-memory.md(gitignored, no size cap) — machine-specific and user-specific learnings: TeX install quirks, file paths, personal effort preferences, tool-version workarounds.
When a fork user does git clone, they get the generic MEMORY.md. Their own personal-memory.md builds up locally as they work.
6.8.0.2 promote-memory — graduating learnings (v1.9.0)
The two-tier split poses one question: who decides which [LEARN] entries graduate from personal-memory.md to MEMORY.md? The answer is a five-critic council.
promote-memory [filter] runs five critics in parallel, each reviewing one dimension:
- Generality — would a non-econ forker benefit?
- Staleness — does this contradict current code (
grepthe referenced files)? - Redundancy — is it already in MEMORY.md, GEMINI.md, or a rule?
- Evidence — does it cite the originating incident / file / why?
- Format — does it follow
[LEARN:category] wrong → right?
Majority (3+ of 5 YES) recommends promotion; the user approves the final move. Critics run in isolated forked contexts — they cannot see each other’s votes — so dimensions are reviewed independently, no groupthink. Critics use Haiku (per model-routing.md) since the review is mechanical-ish.
When to run: monthly as memory-maintenance, before sharing a fork, after a paper or course cycle ships, or wired as a /loop task.
6.8.1 Plans — Compression-Resistant Task Memory
While MEMORY.md stores long-lived project facts, plans store task-specific strategy. Every non-trivial plan is saved to quality_reports/plans/ with a timestamp. This means:
- Plans survive auto-compression (they are on disk, not just in context)
- Plans survive session boundaries (readable in any future session)
- Plans create an audit trail of design decisions
See Pattern 1 in Workflow Patterns for the full protocol.
6.8.2 Session Logs — Why-Not-Just-What History (with Automated Reminders)
Git commits record what changed, but not why. Session logs fill this gap. Gemini writes to quality_reports/session_logs/ at three points: right after plan approval, incrementally during implementation (as decisions happen), and at session end. This means the log captures reasoning as it happens, before auto-compression can discard it.
Because relying on instructions alone is fragile (Gemini forgets during long sessions), a Stop hook (.agents/hooks/log-reminder.py) fires after every response. It tracks how many responses have passed since the session log was last updated. After a threshold, it blocks Gemini from stopping until the log is current. This turns a best practice into an enforced behavior.
New sessions can read these logs to understand not just the current state of the project, but the reasoning behind it. See Pattern 1 in Workflow Patterns for the full protocol.
6.8.3 How It All Fits Together
With GEMINI.md, MEMORY.md, plans, and session logs, the system has four distinct memory layers. Here is what each one does and when it matters:
| Layer | File | Survives Compression? | Updated When | Purpose |
|---|---|---|---|---|
| Project context | GEMINI.md |
Yes (on disk) | Rarely | Project rules, folder structure, commands |
| Corrections | MEMORY.md |
Yes (on disk) | On [LEARN] tag |
Prevent repeating past mistakes |
| Task strategy | quality_reports/plans/ |
Yes (on disk) | Once per task | Plan survives planning-to-implementation handoff |
| Decision reasoning | quality_reports/session_logs/ |
Yes (on disk) | Incrementally | Record why decisions were made |
| Conversation | Gemini’s context window | No (compressed) | Every response | Current working memory |
The first four layers are your safety net. Anything written to disk survives indefinitely. The conversation context is ephemeral — auto-compression will eventually discard details. The workflow’s design ensures that anything worth keeping is written to one of the four persistent layers before compression can erase it.
6.8.4 Hooks — Automated Enforcement
The session log reminder above is one example of a broader pattern: using hooks to enforce rules that Gemini might otherwise forget during long sessions. Rules live in context and can be compressed away. Hooks live in .agents/settings.json and fire every time, regardless of context state.
The template includes hooks for logging, notifications, and context survival:
| Hook | Event | What It Does |
|---|---|---|
| Session log reminder | Stop |
Reminds about session logs after every response |
| Desktop notification | Notification |
Desktop alert when Gemini needs attention (macOS/Linux) |
| Context state capture | PreCompact |
Saves plan state before auto-compaction |
| Context restoration | SessionStart[compact|resume] |
Restores context after compaction or resume |
| Context monitor | PostToolUse[Bash|Task] |
Progressive warnings at 40%/55%/65%/80%/90% context |
| Verification reminder | PostToolUse[Write|Edit] |
Reminds to compile/render before marking done |
Verification and Beamer-Quarto sync are enforced via auto-loaded rules, which are the right tool for nuanced judgment. Hooks are reserved for enforcement that must survive context compression.
Hook handler types. The examples above use command hooks (shell scripts), but Antigravity supports four handler types:
| Type | How It Works | Best For |
|---|---|---|
command |
Runs a shell script. Exit 0 = allow, exit 2 = block (PreToolUse only) | File protection, state capture, notifications |
prompt |
Injects text into Gemini’s conversation — no script needed | Soft reminders: “Check that equations compile before saving” |
http |
POSTs to an external endpoint | CI/CD integration, logging to external services |
agent |
Spawns a subagent that can use tools to verify conditions | Complex validation requiring multi-step checks |
PreToolUse input modification. PreToolUse hooks can now modify tool inputs, not just block or allow. Your hook script can return modified JSON to rewrite parameters before the tool executes — for example, auto-correcting file paths or enforcing naming conventions.
Use command hooks for fast, mechanical checks (file exists? counter threshold?). Use prompt hooks for soft guidance that doesn’t need a script. Use rules for nuanced judgment (did Gemini verify correctly?). Avoid prompt hooks that fire on high-frequency events — the injected text adds up in context.
6.8.5 Context Survival System (Advanced)
When context compaction happens, Gemini loses working memory. The context survival system ensures you can recover seamlessly.
6.8.5.1 How It Works
Two hooks work together to preserve and restore state:
Session running → context fills up → PreCompact fires
↓
pre-compact.py saves:
• Active plan path
• Current task
• Recent decisions
↓
Auto-compaction happens
↓
SessionStart(compact|resume) fires
↓
post-compact-restore.py:
• Reads saved state
• Prints context summary
• Gemini knows where it left off
6.8.5.2 What Gets Saved
| State | Location | Purpose |
|---|---|---|
| Plan path | Session cache | So Gemini can read the plan file |
| Current task | Session cache | First unchecked - [ ] item |
| Recent decisions | Session cache | Last 3 decision-like entries from session log |
| Compaction note | Session log | Timestamp marker for reference |
6.8.5.3 Context Monitoring
The context-monitor.py hook tracks approximate context usage and provides progressive warnings:
| Threshold | Message | Purpose |
|---|---|---|
| 40%, 55%, 65% | Suggest learn |
Capture non-obvious discoveries before compaction |
| 80% | Info message | Auto-compact approaching, no rush |
| 90% | Caution | Complete current task with full quality |
Use /context-status to check current session health at any time.
Note: the monitor uses tool call count as a proxy for context usage, so warnings may appear earlier or later than actual compaction.
6.8.5.4 Recovery After Compaction
If compaction happens mid-task, Gemini will automatically see:
- Restoration message — what plan was active, what task was in progress
- Recovery actions — read the plan, check git status, continue
You can also manually point Gemini to the right context:
“We just had compaction. Read
quality_reports/plans/2026-02-06_translate-lecture5.mdand continue from where we left off.”
6.8.5.5 Distil before compaction: compress-session (v1.9.0)
Auto-compaction is lossy — it keeps recent turns and drops earlier ones, with no preservation of what was decided mid-session. For long pipelines (long debug sessions, multi-decision refactors, end-of-working-day handoffs), compress-session is the distil-not-truncate alternative: structured note with Active state, Decisions made, Files touched, Open questions, Next actions, and explicitly Discarded as noise (failed hypotheses that should NOT carry forward).
compress-session and checkpoint are companions, not substitutes:
checkpoint |
compress-session |
|
|---|---|---|
| When | Natural stop-points (end of day, model switch, collaborator handoff) | Forced compression (long pipeline, accumulated noise, approaching auto-compact) |
| What’s preserved | Active plan, decisions, file pointers, next actions | Same, plus explicit “discarded as noise” line |
| Output | quality_reportscheckpoints/ |
quality_reports/session_logs/YYYY-MM-DD_compression_<slug>.md |
[LEARN] proposals |
Optional | Always proposes (distillation is when lessons surface) |
The “Discarded as noise” section is the novel contribution: failed hypotheses and dead-end debugging paths are listed explicitly so they do NOT ghost-haunt future sessions. This defends against Drew Breunig’s “context poisoning” failure mode — hallucinated or wrong content from early turns getting quoted by later turns.
Now that you understand the building blocks, here’s what’s new: Antigravity has added effort levels for cost control, expanded hook events, skill frontmatter fields for fine-grained skill configuration, permission modes for controlling Gemini’s autonomy, advanced agent configuration, plugins, /batch for parallel refactoring, and headless CLI mode. Each is covered in its respective section above.