Rules: AGENTS.md / GEMINI.md Hierarchical Discovery & Context Budgets
Most teams start writing Agent rules the same way: drop an AGENTS.md into the repository root and let it grow unchecked. Code style, Git conventions, frontend component guidelines, backend migration scripts, and release checklists all end up packed into a single 500-line file.
After a few weeks, two subtle failure modes show up:
- The longer the file gets, the more silently the tail breaks: once a single rule file crosses its byte limit, it is silently truncated—so critical guardrails near the bottom never reach the model.
- Every new session burns context for nothing: when changing two lines of frontend CSS, the runtime still injects database sharding rules and release checklists into the System Prompt, wasting tokens and diluting model attention.
Antigravity’s Rules system is designed from the start around hierarchical discovery, conditional triggers, and an isolated budget with graceful fallback. Aligned with the official rules reference and verified locally on agy v1.5.19, this guide breaks down how rules are discovered, how to split them cleanly, what happens when you exceed the budget, and how to coexist with an existing CLAUDE.md.

1. Where Rules Live and How They Load
Antigravity does not scan your entire disk. It discovers rules from a fixed three-tier directory hierarchy:
| Tier | Default Path | Scope | Typical Use Cases |
|---|---|---|---|
| Directory-scoped | AGENTS.md / GEMINI.md in any directory |
That directory and all subdirectories | Module-specific conventions (e.g., frontend/, migrations/) |
| Repository-scoped | .agents/rules/*.md and .agents/rules.json |
Current repository (commit to Git) | Shared team standards, file-type or scenario-triggered rules |
| Global | ~/.gemini/config/AGENTS.md (plus GEMINI.md, rules/*.md) |
All workspaces on this machine | Personal preferences (reply language, minimalism, general habits) |
Four directory details are easy to miss:
- Directory-name compatibility: Use
.agents/for repository-level configuration. The runtime also remains backward-compatible with.agent/,_agents/, and_agent/(older docs may still mention~/.gemini/GEMINI.mdor~/.gemini/AGENTS.md, whereas newer releases consolidate global rules under~/.gemini/config/). - Upward traversal to the repository root: Suppose your Git root is
repo/and you launchagyinsiderepo/services/billing/. Antigravity walks upward from the current working directory (CWD) to the directory containing.git, collectingAGENTS.md,GEMINI.md, and.agents/rules/at every level along the way. - Additive layering, closer wins: Subdirectory rules do not clear parent or global rules—they stack. Only when two rules directly conflict does the runtime break the tie using this precedence order (highest to lowest):
- Workspace directory hierarchy (directories closer to CWD take priority, walking upward to the repo root);
- Explicit workspace manifests (such as
.agents/rules.json,skills.json,plugins.json); - Global auto-discovery (
~/.gemini/config/); - Built-in customizations (built-in Plugin rules bundled with the client and mounted by name);
- Explicit global manifests (paths manually registered in global JSON manifests).
- Deduplication by
realpath: If the same rule file is discovered through multiple paths (for example, via a symlink or overlapping triggers), Antigravity deduplicates by resolved real file path (realpath) and never injects the same file twice in a single turn.
The full discovery and injection pipeline looks like this:
flowchart TD
S["Start session in CWD"] --> W["Walk upward from CWD to .git root<br/>Collect AGENTS.md / GEMINI.md / .agents/rules/"]
W --> G["Merge global ~/.gemini/config/ and enabled plugin rules"]
G --> D["Deduplicate by resolved realpath"]
D --> T{"Check trigger mode"}
T -- "Standalone file / always_on" --> E["Expand @[label](path) references"]
T -- "model_decision" --> M["Inject name and description only<br/>Model loads full text on demand"]
T -- "glob" --> GL["Load only when reading/writing matching paths"]
T -- "manual" --> MN["Silent by default; load only when @-mentioned"]
E --> C{"Expanded size exceeds 24,000 bytes?"}
C -- "Yes" --> TR["Silently truncate at line boundary within 24 KB"]
C -- "No" --> B
TR --> B{"Count against 20,000-token rules budget<br/>(Built-in plugin rules exempt)"}
B -- "Within budget" --> IN["Inline full text into System Prompt"]
B -- "Over budget" --> PT["Degrade to file-path pointer<br/>Model calls read_file if needed"]
2. Two Authoring Formats and Four Trigger Modes
Both formats are plain Markdown, which often confuses newcomers: when should you put rules in root AGENTS.md versus .agents/rules/*.md? The distinction comes down to two things—YAML frontmatter support and conditional triggering.
1. Standalone AGENTS.md / GEMINI.md: Simple and Always Active in Scope
An AGENTS.md or GEMINI.md placed in any directory is treated as raw Markdown:
- No YAML frontmatter parsing: Adding
trigger: globat the top will not be interpreted as metadata—it is passed straight to the model as ordinary text. - Always active: Whenever the session’s working directory is that folder or any subfolder beneath it, the file unconditionally enters the always-on rule set.
Use standalone files for compact, near-universal rules that apply to almost every turn—core repo commands, communication language, and module boundaries.
2. .agents/rules/*.md: Modular Splitting + Four Triggers
When you want domain-specific rules split into focused files, place them in .agents/rules/ (or globally in ~/.gemini/config/rules/) and declare trigger in YAML frontmatter:
trigger Value |
Required Extra Field | When It Fires | Best For |
|---|---|---|---|
always_on |
None | Injected unconditionally on every turn | Repo-wide baselines, security conventions |
model_decision |
description |
Only the description is injected; the model reads the full file when relevant | Troubleshooting guides, DB change workflows, release rules |
glob |
globs |
Auto-loaded when reading or writing files matching the path globs | Frontend style rules, SQL migration rules, test conventions |
manual |
None | Not injected by default; loaded only when @-mentioned in chat |
Emergency hotfix SOPs, specialized audit checklists |
Here are two high-leverage, token-saving patterns. First, a glob rule that only activates when touching frontend components or stylesheets (.agents/rules/frontend-style.md—note that AGY matches against absolute paths, so prefix relative directories with **/):
1 | --- |
Second, a model_decision rule that the model pulls in only when working on schema changes (.agents/rules/db-migration.md):
1 | --- |
Pitfall alert: trigger must be written in exact snake_case (always_on, model_decision, glob, manual) alongside its required companion field (description for model_decision, globs for glob). If you misspell a field name or omit a required key, the client does not show an error dialog—the rule is silently skipped.
3. @[label](path) Reference Expansion and rules.json
When multiple modules share the same API error-code table or style spec, do not copy-paste it across files. Antigravity supports @[label](path) references inside rule files:
1 | # Backend Service Rules |
At load time, the runtime automatically inlines and expands the target file’s contents directly into the rule.
If your shared rules live outside .agents/rules/ (for instance, tools/agent-rules/ at the top of a monorepo), declare them explicitly in .agents/rules.json. It uses the same manifest schema as skills.json—supporting entries, inherits, include_only, and exclude for inheritance and filtering—so teammates pick up updates immediately on git pull without custom copy scripts.
3. Two Hard Limits and Budget Fallback Mechanics
Understanding this section explains why dumping every convention into one giant file always breaks down. The official rules docs enforce two hard ceilings:
1. Per-File Cap: 24 KB (24,000 bytes)
- How it is measured: Not just the
.mdfile on disk, but the final byte count after expanding every@[label](path)reference. - Overflow behavior: Past
24,000bytes, the runtime silently truncates at a line boundary; everything below the cut never enters the prompt. - UTF-8 / CJK note: Each CJK character takes 3 bytes in UTF-8, so a Chinese-language rule file hits the 24 KB ceiling at roughly 7,500–8,000 characters. Even in English, referencing a 15 KB design doc via
@[label](path)can quietly push the bottom of your main rule file past the cutoff.
Before a release or large rule edit, a quick wc -c check prevents silent truncation:
1 | wc -l -c ~/.gemini/config/AGENTS.md ./AGENTS.md ./.agents/rules/*.md 2>/dev/null |
2. Total Budget Cap: 20,000 Tokens (defaultRulesBudget)
All always-on rules combined—global rules, directory-level AGENTS.md / GEMINI.md, and trigger: always_on files—share a dedicated 20,000-token budget (defaultRulesBudget).
Three architectural details matter here:
- Fully isolated from Skills and MCP budgets: This 20,000-token quota belongs exclusively to Rules and does not compete with metadata for Skills, Workflows, Subagents, or MCP tools.
- Overflow degrades to path pointers rather than hard drops: When always-on rules exceed 20,000 tokens, the overflow is not discarded outright. Instead, those files degrade from full inline text into file-path pointers in the prompt. The model sees that the rule file exists and can call
read_filewhen needed. - Built-in Plugin rules are exempt: Rules bundled with first-party client plugins (such as the collaboration rules shipped with the built-in
swarmplugin) do not count against the 20,000-token budget and are always inlined in full.
Graceful degradation is not a safety net you should lean on. Once a high-frequency rule gets downgraded to a pointer, the model has to decide on every turn whether to invoke read_file—costing an extra tool round-trip and making it easy to miss constraints under tight execution loops. Keep all always-on rules combined within 3,000–5,000 tokens in practice, and move everything else into glob, model_decision, or dedicated Skills.
4. Real-World Local Setup and Coexisting with CLAUDE.md
Specs stay abstract until you look at a working setup. Here is the actual rule footprint running on my Linux workstation (agy v1.5.19).

1. Inside My Global ~/.gemini/config/AGENTS.md
Running wc -l -c ~/.gemini/config/AGENTS.md reports 82 lines and 3,473 bytes—just 14.5% of the 24 KB per-file cap and under 1,000 tokens, putting negligible pressure on the 20,000-token budget.
Here is the sanitized skeleton (strictly cross-project behavioral principles, with zero repo-specific commands):
1 | # AGENTS.md |
You feel the difference immediately: roughly 80 lines total, zero platitudes like “write clean, elegant code,” and every single rule can be verified directly against a git diff.
2. Coexisting with an Existing CLAUDE.md
This blog repository is a concrete example: the root already contains a 163-line, 4,972-byte CLAUDE.md (documenting Hexo + Butterfly conventions, Front Matter fields, and common yarn commands), originally authored for Claude Code. When you alternate between agy and Claude Code—or work on a team mixing Cursor, Codex, Claude Code, and Antigravity—how do you keep rules in sync without maintaining duplicate copies?
Here is how the three common coexistence patterns compare:
| Approach | How It Works | Pros | Trade-offs & Best Fit |
|---|---|---|---|
| Symlink reuse | Make AGENTS.md the source of truth and run ln -s AGENTS.md CLAUDE.md (or vice versa) |
Zero duplication, edit once for all tools; Antigravity deduplicates by realpath so it never double-loads |
Git symlinks often trip up Windows contributors; tool-specific directives (such as Claude-only commands) leak across tools |
| Shared doc + thin entrypoints | Put shared repo rules in docs/agent-guide.md; reference it in AGENTS.md via @[Repo Guidelines](docs/agent-guide.md) (with AGY-only rules below) and in CLAUDE.md via @docs/agent-guide.md |
Single source of truth for shared rules, clean isolation for tool-specific instructions, cross-platform with no symlinks | Expanded byte size still counts toward the 24 KB per-file cap (best default for mixed-tool team repos) |
| Full separation | Keep CLAUDE.md for Claude Code; split AGY rules into .agents/rules/*.md |
Takes full advantage of glob and model_decision triggers for fine-grained loading |
Shared basics like build commands drift easily if duplicated across both setups |
My own rule of thumb depends on the repo:
- Linux/macOS personal repos: When core repo rules stay small (under 100 lines), keep
AGENTS.mdas the single source of truth and symlinkCLAUDE.mdwhen needed. - Team or complex repos: Consolidate shared architecture conventions and build/test commands into
docs/agent-common.md, keep rootAGENTS.mdandCLAUDE.mdas thin entrypoints under 10 lines, and move fine-grained frontend, backend, and SQL migration rules intoglob-triggered.agents/rules/*.mdfiles.
5. Five Common Pitfalls When Writing Rules
After months of writing rules for agy, the mistakes that waste the most time and tokens fall into five buckets:
- Stuffing multi-step SOPs into Rules instead of Skills
Release workflows, load-testing procedures, and incident playbooks running hundreds of lines burn tokens on every single turn if pasted into an always-onAGENTS.md. Reserve Rules for standing constraints and preferences that can be violated at any moment. Put on-demand multi-step procedures in.agents/skills/<name>/SKILL.md(covered in the next post), where they cost only a line or two of description until progressively disclosed on demand. - Silently crossing 24 KB and losing the redlines at the bottom
This happens most often with@[label](path)pulling in large external docs: a 30-line main file easily expands past 24,000 bytes. Whenever a rule file grows beyond 300 lines—or the model seems to *”always forget the rule at the very bottom”*—runwc -cacross the file and every referenced document. - Filling the budget with true-but-useless platitudes
Lines like “write high-quality, maintainable code following best practices” or “ensure there are no security vulnerabilities” barely move model behavior and just consume budget. Effective Rules are falsifiable, concrete constraints—for example, “validate all API request payloads withzod; never hand-write nestedif (!req.body.x)checks” or “never modify historical files undermigrations/already merged intomain.” - Hardcoding project-specific commands in global
~/.gemini/config/AGENTS.md
Putting “always runyarn buildbefore committing” or “run all tests withpytest -n auto“ in your global rules means switching to a Go service or documentation repo sends the model searching for nonexistentyarnorpytestbinaries. Keep global rules strictly language-, framework-, and repo-agnostic, and push concrete commands down to each repository root. - Relying on Rules alone for 100%-enforced hard boundaries
Rules remain prompt-layer soft constraints—in long contexts or complex tasks, the model can still drift or misjudge. Hard redlines like “never runrm -rf,” “never read~/.sshor.env,” or “never rungit push --force“ cannot rely on ten exclamation marks inAGENTS.md. Enforce them at the execution layer usingpermissions.denyinsettings.json, the terminal sandbox, or aPreToolUsehook in.agents/hooks.json.



















