5 The Building Blocks
In Chapter 4, we established the core principles of working memory, the three-tier memory hierarchy, and the power of Progressive Disclosure in preserving the LLM’s finite attention budget.
Now, we translate those principles into concrete code, configuration files, and workflows. Antigravity organizes progressive disclosure across five foundational configuration layers that work together like the operating system for your research repository:
- The Constitutional Core (
GEMINI.md): Always-on foundational standards and project layout (Tier 1 of Progressive Disclosure). - Domain Rules (
.agents/rules/): Path-scoped guidelines that load just-in-time when matching files are edited (Tier 2). - Modular Skills (
.agents/skills/): Multi-step procedural workflows invoked on-demand via slash commands (Tier 2). - Specialized Subagents (
.agents/agents/): Fresh-context reviewers deployed when tasks satisfy the Subagent Justification Test. - Settings & Lifecycle Hooks (
.agents/settings.json): Deterministic permission boundaries and event-driven automation that run outside the context window.
.md) is the Foundation of Agentic Workflows
Nearly every instruction, rule, memory log, and configuration file in agentic workflows uses Markdown (.md).
- What it is: Markdown is plain, human-readable text that uses simple keyboard characters for structure (
#for headings,-for bullet points,|for tables,**bold**for emphasis). - Zero Token Overhead: Unlike rich document formats that contain hidden XML tags and styling metadata,
.mdis pure text. Every token in the agent’s context window is spent strictly on substantive content and instructions. - Native LLM Alignment: Frontier LLMs are trained heavily on Markdown, making them exceptionally reliable at parsing structured headers, checklists, and tables.
- Clean Version Control & In-Place Editing: Plain text enables Git and AI agents to track precise line-by-line diffs, resolve merges cleanly, and perform surgical in-place edits without file corruption.
5.1 GEMINI.md — Your Project’s Constitution
GEMINI.md is the single most important file in your repository. It embodies Tier 1 (The Constitutional Core) of Progressive Disclosure. Gemini reads it at the start of every session.
As introduced in Chapter 4, LLMs operate under a finite rule budget: 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.
5.2 Rules — Domain Knowledge That Auto-Loads
Rules are markdown files in .agents/rules/ that Gemini loads automatically. They encode your project’s standards. Path-scoping is the practical mechanism that implements Tier 2 of Progressive Disclosure (introduced in Chapter 4): rules with a paths: YAML frontmatter only load when Gemini works on matching files, preventing context pollution and preserving the agent’s attention budget.
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.
5.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.
5.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
5.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
5.4 Skills — Reusable Slash Commands
Skills represent Tier 2 (Modular Execution) of Progressive Disclosure: multi-step, expert procedural workflows that remain dormant on disk until explicitly invoked via /command. By keeping deep recipes out of GEMINI.md, skills incur zero static prompt overhead until needed.
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.
5.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
5.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 inconsistenciesAs established in Chapter 4, your default architecture for active coding, data analysis, and manuscript drafting is a single, open-ended agent loop maintaining its own plan on disk. Splitting active implementation across multiple agents introduces the “Telephone Game” (handoff context degradation) and incurs cold-cache penalties.
However, once a major artifact is produced—such as a 50-page working paper or a 140-slide lecture deck—subagents earn their keep by satisfying Criterion #3 (Fresh-Context Adversarial Verification) and Criterion #2 (Parallel Fan-Out).
5.5.2 The Monolithic Audit Anti-Pattern vs. Fresh-Context Isolation
When presented with a comprehensive academic audit, the intuitive beginner approach is to give a single agent one massive prompt:
“Please review this paper for econometric identification, proofread all grammar, check that all 80 citations exist in the .bib file, verify the TikZ diagram layouts, and improve the writing style.”
This monolithic audit prompt inevitably fails due to two fundamental cognitive traps:
- Attention Splitting: Conditioned on a massive prompt with competing goals, the model skims the paper, catches a few surface typos, and completely overlooks the wrong subscript in Equation 14 or the missing citation in Section 4.
- Self-Confirmation Bias: If the same agent that wrote the text or derived the equations reviews them in the same session, it instinctively defends its earlier logic and rubber-stamps its own output.
5.5.2.1 Multi-Agent Context Isolation for Audits
The architectural solution is fresh-context subagent isolation. Instead of one agent doing five review jobs with divided attention and confirmation bias, the orchestrator dispatches multiple specialized subagents in parallel:
┌───────────────────────┐
│ Orchestrator Agent │
└──────────┬────────────┘
│
┌────────────────────────────┼────────────────────────────┐
│ │ │
┌────────▼─────────┐ ┌────────▼─────────┐ ┌────────▼─────────┐
│ proofreader │ │ domain-reviewer │ │ claim-verifier │
│ (Grammar Only) │ │(Econometrics/Math│ │(BibTeX Citations)│
└────────┬─────────┘ └────────┬─────────┘ └────────┬─────────┘
│ │ │
│ 100% Focused Context │ 100% Focused Context │ 100% Focused Context
│ │ │
└────────────────────────────┼────────────────────────────┘
│
┌──────────▼────────────┐
│ Synthesized QA Report │
└───────────────────────┘
Each subagent runs in its own isolated, fresh context window:
- The
proofreaderagent receives only the prose and grammar instructions (zero clutter from code or citations). - The
claim-verifieragent receives only the extracted factual claims and bibliography references. - The
domain-revieweragent focuses 100% of its attention budget on mathematical rigor and identification assumptions.
Because each subagent starts with a clean context window, it operates at maximum attention capacity, completely free from context pollution.
5.5.3 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.
5.5.4 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.
5.5.5 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. As detailed in Chapter 4, prompt caching slashes input token costs by 75%–90% and keeps latency under 3 seconds when preserving prefix stability within the 1-hour TTL window. Antigravity manages cache alignment automatically behind the scenes; keeping base rules stable and executing tasks in an unbroken loop maximizes cache hits.
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.
5.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.
5.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.
5.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.
5.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.
5.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.
5.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.
5.8 Memory — Cross-Session Persistence
In Chapter 4, we introduced the Three-Tier Memory Architecture that prevents catastrophic forgetting across research sessions: Level 1 (Ephemeral Working Memory / Context Window), Level 2 (Task Memory / quality_reports/plans/), and Level 3 (Persistent Project Memory / GEMINI.md, MEMORY.md, and session logs).
Here, we explore the concrete syntax, file structures, and automated enforcement mechanisms that implement Level 2 and Level 3 memory in your repository.
5.8.1 Level 3 Memory: Project Corrections (MEMORY.md)
Antigravity maintains persistent project memory at ~/.agents/projects/[project]/memory/MEMORY.md (or committed at your repository root as MEMORY.md). This file endures permanently across sessions and is injected into every active conversation.
Use it for: - Key project facts that never change - Corrections you don’t want repeated ([LEARN:category] format) - Concrete rules distilled from past debugging runs
# 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 Quarto5.8.1.1 Two-Tier Memory Architecture (MEMORY.md vs personal-memory.md)
The template splits Level 3 project memory into two tiers (see .agents/rules/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 collaborator clones your repo, they get the generic MEMORY.md. Their own personal-memory.md builds up locally as they work.
5.8.1.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, with zero groupthink. Critics use gemini-3.5-flash (Low) (per the 70/20/10 model routing pattern) since the review is largely mechanical.
When to run: monthly as memory-maintenance, before sharing a fork, after a paper or course cycle ships, or wired as a recurring automation.
5.8.2 Level 2 Memory: Plans as Task State (quality_reports/plans/)
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. As established in Chapter 4, writing plans to disk ensures:
- Plans survive auto-compaction (they live on disk as secondary storage, not just in volatile RAM).
- Plans survive session boundaries, window reloads, and computer restarts.
- Plans create an auditable record of design decisions and milestone progress.
See Pattern 1 in Workflow Patterns for the full protocol.
5.8.3 Level 3 Memory: Session Logs as “Why-Not-Just-What” History
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 ensures the log captures reasoning as it happens, before auto-compaction 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.
5.8.4 How It All Fits Together
With GEMINI.md, MEMORY.md, plans, and session logs, the system maps cleanly onto the three memory levels established in Chapter 4:
| Memory Tier | File / Storage | Survives Compaction? | Updated When | Research Purpose |
|---|---|---|---|---|
| Level 3: Project Memory | GEMINI.md |
Yes (on disk) | Rarely | Foundational rules, folder structure, core commands |
| Level 3: Project Memory | MEMORY.md |
Yes (on disk) | On [LEARN] tag |
Prevents repeating past mistakes across sessions |
| Level 3: Project Memory | quality_reports/session_logs/ |
Yes (on disk) | Incrementally | Records why decisions were made before details fade |
| Level 2: Task Memory | quality_reports/plans/ |
Yes (on disk) | Once per task | Preserves goals and checklists across compaction cycles |
| Level 1: Working Memory | Context Window | No (ephemeral RAM) | Every response | Active reasoning, in-flight code edits, and scratchpad dialogue |
The disk-based layers are your safety net. Anything written to disk survives indefinitely. The active context window is volatile RAM — auto-compaction will eventually discard conversational details. The workflow’s design ensures that anything worth keeping is written to Level 2 or Level 3 persistent storage before compaction can erase it.
5.8.5 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 | PreInvocation |
Restores active plan checklist and task state post-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.
5.8.6 Context Survival System (Advanced)
As introduced in Chapter 4, Antigravity coordinates context compaction through an automated pipeline paired with lifecycle hooks. This ensures the agent recovers seamlessly without losing its active plan or task orientation.
5.8.6.1 The Hook Pipeline Implementation
Two scripts located in .agents/hooks/ execute deterministically outside the model’s context window:
State Capture (
.agents/hooks/pre-compact.py): Fires on thePreCompactevent when context utilization reaches capacity (~80%–90%) or when/compactis called manually. It inspectsquality_reports/plans/, extracts the active plan path and the first unchecked- [ ]task, snapshots recent decision entries from the session log, and serializes this state to a local session cache.State Restoration (
.agents/hooks/post-compact-restore.py): Fires on thePreInvocationevent on the first turn following compaction or session resumption. It detects that compaction occurred, loads the cached state snapshot, and injects an ephemeral prompt message (injectSteps: [{"ephemeralMessage": "..."}]) re-anchoring the model to its plan checklist with zero task disorientation.
5.8.6.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 |
5.8.6.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.
5.8.6.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.”
5.8.6.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_reports/checkpoints/ |
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.