Token Optimization Guide

Optimizing Token Usage Practices

Actualizing token optimization across AGENTS.md, CLAUDE.md and friends across five coding agent tools

Token Optimization for Coding Agents β€” Three-Layer Reference

Token spend on agentic coding workflows compounds fast β€” through context re-sent every turn, tool output bloat, and code architecture that forces agents to read more than they need. The list below consolidates the practices that actually move the needle, from API-level mechanics down to how you structure your codebase.

Core principle

  • Treat context as a finite, precious resource β€” the goal is the smallest set of high-signal tokens that gets the job done, not the most complete one.

Layer 1 β€” Agent/Platform Mechanics

Set once, at the system level. Applies uniformly across every session; a developer rarely touches these turn-by-turn.

  • Keep the request prefix stable (tools β†’ system prompt β†’ static context β†’ variable tail) so prompt caching actually hits.
  • Avoid mid-session MCP config churn β€” server connect/disconnect is the most common silent cache-buster.
  • Use 1-hour cache TTL for long-lived main-agent loops; leave short-lived/one-shot subagent calls on the 5-minute default.
  • Enable MCP “code mode” once running 3+ servers or heavy tools (search, docs, DB).
  • Keep toolsets small, non-overlapping, and clearly scoped.
  • Design multi-agent setups with clean, isolated context windows per subagent β€” but only split when the boundary genuinely reduces total context moved, since decomposition itself carries token overhead.
  • Route by model tier (Haiku/Sonnet/Opus) based on task complexity, built into the harness rather than decided per-query.
  • At team scale, sit a gateway/router layer (caching, model routing, observability) in front of raw API calls.

Layer 2 β€” Agent Operation (how you drive a session)

Behavioral. Same underlying agent can cost 3x more or less depending on discipline here β€” this is on the developer, every session.

  • Delegate verbose work (tests, logs, doc reads) to subagents so only a summary lands in the main thread.
  • Cap thinking budget (/effort, MAX_THINKING_TOKENS) when deep reasoning isn’t needed.
  • Run /compact deliberately at phase boundaries β€” don’t just wait for auto-compact.
  • Use /clear, not just /compact, when switching to an unrelated task.
  • Extract large file/log reads to disk; have the agent report a path + one-line summary instead of piping everything into context.
  • Use plan mode to catch an over-broad approach before it executes, not after.
  • Audit and disable unused MCP servers regularly.
  • Batch anything non-interactive.
  • Check /usage / /cost periodically rather than assuming.

Layer 3 β€” Codebase Architecture (the target, not the tool)

Orthogonal to the agent entirely β€” good engineering with or without AI, but doubly rewarded here since it shrinks what any agent ever needs to load.

  • Apply SRP: small, single-purpose classes/functions let an agent read only what’s relevant instead of a whole God Function.
  • Keep coupling low (DIP/ISP) β€” high fan-out drags a wide dependency graph into context for even a small change.
  • Avoid Bloaters (Long Method, Large Class) β€” they blow past file-view truncation limits, invalidate more cache per edit, and dilute attention even when they still technically fit.
  • Don’t over-atomize either β€” fragmenting one behavior across too many tiny files trades a size tax for an indirection tax. Aim for locality of behavior, not minimum size.
  • Organize hierarchically by feature/domain so one task touches a small, co-located set of files.

Closing

The three layers compound rather than substitute for each other: platform mechanics set the ceiling on efficiency, operational discipline determines whether you actually reach it session to session, and codebase architecture determines how much work either layer even has to do in the first place. In practice, Layer 3 is the one teams skip because it doesn’t look like an “AI cost” problem β€” but it’s also the one that keeps paying off silently in every future session, agent, and tool that ever touches the code.


Tool-Specific Implementation Guide

This guide provides detailed implementation strategies for each of the five coding agent tools, showing how to map the three layers to platform-specific mechanics. Each section includes practical, copy-pasteable examples from real-world configurations.

The Coding Agents landscape, in one table

ToolNative file(s)Discovery / precedenceProgressive disclosurePer-subagent model routingPlan gate
Claude CodeCLAUDE.md (richer, preferred); also reads AGENTS.md as of spring 2026Project root + parents; user-level ~/.claude/CLAUDE.mdSkills in ~/.claude/skills/ or .claude/skills/Yes, per subagent definitionPlan mode
Codex CLIAGENTS.md (native, OpenAI-originated)AGENTS.override.md > AGENTS.md > configurable fallback names; walks project root β†’ cwd, concatenates one file per directory[[skills.config]] per-skill enable/disableYes β€” ~/.codex/agents/*.toml or .codex/agents/*.toml, each with its own model/reasoning effort/sandboxplan_mode_reasoning_effort config key
Antigravity CLI (Gemini)GEMINI.md (Antigravity-only) + AGENTS.md (cross-tool, added v1.20.3)Global ~/.gemini/GEMINI.md, ~/.gemini/AGENTS.md; project-level of both, plus .agent/rules/Skills in ~/.gemini/config/skills/Yes β€” YAML agents in .antigravity/agents/ or ~/.config/antigravity/agents/Native Implementation Plan artifact
Devin CLIAGENTS.md (recommended) / AGENT.md / CLAUDE.md (compatible) / .windsurfrules (legacy)Project root + subdirectories, lazily loaded only when the agent touches files there; global ~/.config/devin/AGENTS.md; also reads ~/.claude/CLAUDE.md globally if presentDevin’s own docs: prefer Skills over Rules explicitlyNot per-subagent, but Playbooks can chain (--child-playbook-id)Playbooks act as a procedure gate
Cursor.cursor/rules/*.mdc (current format) + AGENTS.md (root & subdirectories, read as fallback); legacy single-file .cursorrules still works but is deprecatedPrecedence: Team Rules β†’ Project Rules β†’ User Rules, merged, earlier wins on conflict. .mdc frontmatter (alwaysApply, globs, description) controls four activation modes: always / auto-attached / agent-decided / manual @mentionSkills in .cursor/skills/; can also load Claude’s Skills/plugins directly (treated as agent-decided)Yes β€” subagents in .cursor/agents/*.md, isolated context, can run in parallel (Cursor 2.4+)No dedicated plan-mode artifact; enforcement instead via Hooks (block risky ops before they run)

Three details worth flagging because they’re easy to get wrong: Claude Code only gained AGENTS.md support in spring 2026 and still treats CLAUDE.md as the richer format for anything Claude-specific β€” don’t assume parity. On any machine running both Google’s Gemini CLI and Antigravity CLI, both currently write to the same ~/.gemini/GEMINI.md path, which silently pollutes one tool’s context with the other’s rules unless you separate them deliberately. And Cursor is the only tool here where the scoped rule (glob-matched or agent-decided) is the primary mechanism rather than an optional extra layered on top of one flat file β€” treating .cursor/rules/ like a second CLAUDE.md and writing one giant always-apply rule defeats the entire point of the format.

Tool-Specific Implementation Guides

This guide provides detailed implementation strategies for each of the five coding agent tools, showing how to map the three layers to platform-specific mechanics. Each section includes practical, copy-pasteable examples from real-world configurations.

πŸ€– PART I: Claude Code

Claude Code-specific token optimization strategies including compaction guidance, subagent routing, and session hygiene practices.

Learn more β†’
πŸ”§ PART II: Codex CLI

OpenAI's Codex CLI implementation patterns including directory-walk concatenation, model tier assignment, and profile configuration.

Learn more β†’
πŸ’Ž PART III: Antigravity CLI

Antigravity CLI (Gemini) optimization strategies including GEMINI.md separation, Implementation Plan artifacts, and hook-based guardrails.

Learn more β†’
πŸ› οΈ PART IV: Devin CLI

Devin CLI token optimization including Skills vs Rules preferences, Playbook workflows with practical examples, and lazy-loading mechanics.

Learn more β†’
πŸ‘† PART V: Cursor

Cursor-specific optimization including scoped .mdc rules with concrete examples, glob-based activation, Hooks-based enforcement, and subagent isolation.

Learn more β†’
πŸ“ PART VI: Repository Layout

Recommended repository structure with concrete file examples, setup checklist, and practical implementation patterns for all five tools.

Learn more β†’

Interactive Tools

Practical tools to help you think systematically, build better AI agents, and master prompt engineering.

Software Engineering Playbooks

Practical, End-to-End implementation guides for building Production-ready Software. Each playbook includes working code, architecture diagrams, and step-by-step instructions.

πŸ€–

Research Agent with Gateway

Build a production-ready AI research agent using Agent Gateway for unified traffic management, authentication, and observability across LLM providers.

Agent Gateway A2A Protocol Multi-Agent
πŸ”—

RAG Pipeline with Vector Database

Implement a complete Retrieval-Augmented Generation pipeline with vector embeddings, semantic search, and context injection for accurate AI responses.

RAG Vector DB Embeddings
πŸ”„

Multi-Agent Orchestration

Create a coordinated multi-agent system with specialized agents, task distribution, and result synthesis for complex problem-solving.

Orchestration Task Distribution Synthesis
1 / 2

Future References

Explore these resources for deeper learning on AI agent development, spec-driven development, and prompt engineering tools.

Spec-Driven Development

Comprehensive guide on Spec-Driven Development practices and methodologies.

Awesome Copilot

Curated list of GitHub Copilot resources, extensions, and best practices.

Promptfoo

Tool for testing, evaluating, and improving LLM prompts and applications.

Prompts.chat

Collection of prompt engineering resources and templates.

Agent Skills

Agent skills resources and documentation for building AI agent skills.

Awesome Skills

Curated list of awesome skill repositories and collections.

Agent Skills Topic

GitHub topic for discovering agent-related skills and repositories.

AI Agent Topic

Trendshift topic for discovering AI agents.

AI Skills Topic

Trendshift topic for discovering AI skills.

Agent Governance Toolkit

Agent governance toolkit.

Pattern Sources

Our patterns are curated from industry-leading sources with proper attribution and licensing compliance.

Refactoring.Guru

Classic GoF design patterns, code smells catalog, and refactoring techniques (https://refactoring.guru).

Enterprise Integration Patterns

65 messaging patterns for integrating enterprise applications by Gregor Hohpe and Bobby Woolf (CC BY 4.0).

Microservices.io

Comprehensive patterns for microservice architectures by Chris Richardson.

Agent Catalog Patterns

Patterns for agentic systems from agentpatternscatalog.org (CC BY 4.0).

OWASP Foundation

Security patterns from OWASP Top 10 for Web Applications, LLM Applications, and Agentic Applications (CC BY-SA 4.0).

Industry Research

ML/AI patterns from Microsoft, Google, Anthropic, and academic research.

AI Agent Patterns

Spec-driven development patterns from Claude, Gemini, OpenAI, and GitHub Copilot on github/spec-kit and OpenSpec.

Data Engineering Leaders

Data platform patterns from Martin Fowler (Data Mesh), Kimball Group (Dimensional Modeling), and cloud providers.

MLOps Best Practices

Data science patterns from MLflow, Great Expectations, and MLOps practitioners.

Streaming & Analytics

Real-time patterns from Confluent/Kafka, Apache projects, and serverless analytics platforms.

Academic Papers

Rigorous ML patterns from peer-reviewed research including data leakage prevention and active learning.

5-Day AI Agents Course

Intensive Vibe Coding Course With Google by Brenda Flynn et al. (2026) on Kaggle.

The Agent Loop

Foundational Agent Definition (Perceive + Act):
Russell, S. J., & Norvig, P. (1995). Artificial Intelligence: A Modern Approach. Prentice Hall. (Current edition: 4th Ed., Pearson, 2020)

Modern Iterative LLM Agent Loop:
Yao, S., Zhao, J., Yu, D., et al. (2022). ReAct: Synergizing Reasoning and Acting in Language Models. arXiv:2210.03629.

Historical Context:
Incorporating AIMA's perceive/act model, Classical robotics' Sense-Plan-Act loop (Brooks, 1986), and ReAct's Thought→Action→Observation cycle.