The version labels in this heading preserve existing links. For the current lineup, Opus 5.5, Sonnet 5, and Fable 5.1 use adaptive reasoning. Haiku 4.5 supports extended thinking but has no effort parameter. Model specifications.
Effort governs reasoning and can affect tool use, output length, latency, and cost. Use the current effort table rather than assuming every model has the same default. Opus 5.5 defaults to medium; Sonnet 5 and Fable 5.1 default to high.
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=16000,
thinking={"type": "adaptive"},
output_config={"effort": "high"},
messages=[{"role": "user", "content": "Analyze the failure modes."}],
)
Opus 4.7 and later, Sonnet 5, and Fable use adaptive reasoning only. CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING and a fixed MAX_THINKING_TOKENS budget do not apply to them. The fixed-budget compatibility switch remains specific to Opus 4.6 and Sonnet 4.6.
Choose supported effort; Enter saves per model, s applies to this session
--effort high
Set effort for the launched session
CLAUDE_CODE_EFFORT_LEVEL
Explicit environment override
modelSettings / effortLevel
Persistent settings support low through xhigh, not max
Option+T / Alt+T, /config, MAX_THINKING_TOKENS=0
Can disable thinking on supported models; no effect on Opus 5.5 or Fable
Ctrl+O
Open the transcript viewer; display does not change billing
Thinking tokens are billed even when their display is collapsed or redacted. Set showThinkingSummaries: true if full summaries should be available in the expanded view. Thinking controls.
ultrathink currently adds an instruction to reason more deeply for the turn. It does not set the API effort to max. think and think hard are ordinary prompt text. For a deterministic effort selection, use /effort or --effort.
Assistant prefill is unsupported on Opus 4.6. Check the target model’s migration guide before reusing prefill-based examples; use system instructions, examples, or supported structured outputs where prefill is unavailable.
For fast mode, use a supported Opus version and the current API fast-mode instructions. In Claude Code, /fast uses Opus 5.5 by default from v2.1.280. Standard Opus 5.5 costs $4/$20 per MTok and fast mode $8/$40. Older Opus 5 and 4.8 fast mode costs $10/$50. Availability, provider support, and usage-credit billing are separate from the speed setting.
📖 Complete Workflow Guide: See GitHub Actions Workflows for 5 production-ready patterns using the official anthropics/claude-code-action (PR review, triage, security, scheduled maintenance).
Code Review (Teams/Enterprise): For automated PR review without manual prompting, see Code Review, Anthropic’s multi-agent review feature that posts inline GitHub comments on every PR.
Billing: Anthropic announced that the workflows in this section (headless mode via claude -p, GitHub Actions, Agent SDK) would move to a separate monthly programmatic credit on June 15, 2026, then paused the change. As verified on 2026-09-30, they still draw from your subscription’s usage limits. Audit your CI/CD usage with ccusage so you are ready if the plan resumes. See §9.13: The Interactive/Programmatic Billing Split for the announced plan and a decision framework.
Windows Note: Git hooks run in Git Bash on Windows, so the bash syntax below works. Alternatively, you can create .cmd or .ps1 versions and reference them from a wrapper script.
Pre-commit hook:
.git/hooks/pre-commit
#!/bin/bash
# Run Claude Code for commit message validation
COMMIT_MSG=$(cat"$1")
claude-p"Is this commit message good? '$COMMIT_MSG'. Reply YES or NO with reason."
Pre-push hook:
.git/hooks/pre-push
#!/bin/bash
# Security check before push
claude-p"Scan staged files for secrets and security issues. Exit 1 if found."
Focus on security, performance, and code quality. \
Output as markdown." --bare
--bare flag for CI scripting (v2.1.81+): Add --bare to any claude -p call to get a deterministic, hermetic execution environment. It disables hooks, LSP, plugin sync, and skill directory scanning, ensuring local developer config never bleaks into CI. Requires ANTHROPIC_API_KEY (no OAuth/keychain). Also disables auto-memory.
Terminal window
# Without --bare: picks up local hooks, plugins, skills — non-deterministic in CI
An alternative to generating release notes from commits is to capture the context while implementing, not at release time. The “changelog fragments” pattern replaces a shared CHANGELOG.md with one YAML file per PR, accumulated in changelog/fragments/, assembled automatically at release.
Commit-based approaches lose context by the time you run git log to generate release notes. The developer who fixed a race condition three weeks ago is the only one who understood the impact. The commit message says fix SSE handling.
The fragments pattern solves this with 3 enforcement layers:
Layer 1 (CLAUDE.md rule): Load a git-workflow.md rule that encodes the full fragment workflow. When a developer asks Claude Code to “create the PR,” it reads the diff, infers type/scope/title, generates the YAML, validates it, and commits it as part of the branch. Claude handles it autonomously.
title: "Fix empty chat after starting activity due to SSE race condition"
description: |
SSE workplan fires before AI stream completes, causing ChatWrapper to mount
with 0 messages. Added isStartingActivityRef guard and await response.text().
breaking: false
migration: false
Layer 2 (UserPromptSubmit hook): Detects PR creation intent and checks whether the fragment was already mentioned.
Terminal window
# Tier 0 enforcement in smart-suggest.sh
ifecho"$PROMPT_LC"|grep-qE'(create.*pr|make.*pr|pull.?request)'; then
if!echo"$PROMPT_LC"|grep-qE'(changelog|fragment|skip-changelog)'; then
suggest"pnpm changelog:add""REQUIRED before merge — fragment missing"
else
suggest"/pr""PR creation with structured description"
fi
fi
The hook is non-blocking and shows one suggestion inline, before Claude processes the prompt. If the fragment is already mentioned, the hook stays silent and suggests the normal PR command.
Layer 3 (CI gate): Two independent GitHub Actions jobs. The first validates fragment existence and structure. The second checks that migration: true is set if the PR adds SQL migration files. This job runs regardless of bypass labels, because a “skip-changelog” PR can still add a migration that the deployment team needs to know about.
Assembly at release:
Terminal window
pnpmchangelog:assemble--version1.8.0 [--dry-run]
Reads all fragments, groups by type, inserts a versioned section into CHANGELOG.md replacing a ## [Next Release] placeholder, archives fragments to changelog/fragments/released/{version}/.
Benefits over commit-based generation:
Zero merge conflicts (each fragment is a unique file per PR)
Context written at implementation time, not reconstructed later
DB migrations surfaced explicitly in every fragment
Bypass is auditable (closed label list visible in PR history)
Claude Code can automate deployments to Vercel, GCP, and other platforms using stored credentials. The key is assembling three components: secret management, a deploy skill, and mandatory guardrails.
For multi-platform secrets (GitHub, Vercel, AWS simultaneously), Infisical provides centralized management with versioning and point-in-time recovery, a useful open-source alternative to HashiCorp Vault:
Terminal window
# Install infisical CLI
brewinstallinfisical/get-cli/infisical
# Inject secrets into Claude Code session
infisicalrun--claude
# Infisical automatically sets all project secrets as env vars
These guardrails are not optional. Production deployments without them create incidents:
Guardrail
Implementation
Why
Staging-first
Always deploy to staging before prod
Catch environment-specific failures
Human confirmation
Stop and ask before --prod flag
No autonomous production deploys
Smoke test
Verify HTTP 200 on key endpoints after deploy
Catch silent deployment failures
Rollback ready
Keep previous deployment ID before promoting
vercel rollback <deployment-id>
Hook for confirmation (prevent accidental production deploys):
.claude/settings.json
{
"hooks": {
"PreToolUse": [{
"matcher": "Bash",
"hooks": [{
"type": "command",
"command": "scripts/check-prod-deploy.sh"
}]
}]
}
}
#!/bin/bash
# check-prod-deploy.sh — exit 2 to block, exit 0 to allow
INPUT=$(cat)
ifecho"$INPUT"|grep-q"vercel deploy --prod\|gcloud deploy.*production"; then
echo"BLOCKED: Production deploy requires manual confirmation. Run the command directly from your terminal."
exit2
fi
exit0
Sources: Vercel deploy skill pattern documented by the community (lobehub.com, haniakrim21); Infisical multi-platform secrets management at infisical.com. No end-to-end automated deploy workflow exists in the community as of March 2026. The building blocks are available, but the staging-to-production promotion pattern is something each team assembles themselves.
New: Xcode 26.3 RC+ includes native Claude Agent SDK support, using the same harness as Claude Code:
Requirements: Xcode 26.3 RC or later (macOS)
Setup: Configure API key in Xcode → Preferences → Claude
Use:
Built-in code assistant powered by Claude
Same capabilities as Claude Code CLI
Native integration with Xcode workflows
Claude Agent SDK: Separate product from Claude Code, but shares the same agent execution framework. Enables Claude-powered development tools in IDEs beyond VS Code.
Note: Claude Agent SDK is Anthropic’s framework for building agent-powered developer tools, separate from Claude Code itself. Claude Code CLI and Xcode integration both use this SDK.
Problem: Fullstack development often requires long-running processes (dev servers, watchers) that block the main Claude session, preventing iterative frontend work.
Solution: Use Ctrl+B to background tasks and maintain tight feedback loops across the stack.
💡 Key insight: Background tasks optimize fullstack workflows by decoupling infrastructure (servers, watchers) from iterative development. Use them strategically to maintain tight feedback loops across the entire stack.
All the loops above validate code. None of them tell Claude whether the UI actually looks correct, whether a form works, or whether the page renders without errors. Without a browser connection, Claude can only infer: it writes code and assumes the result matches intent.
Claude in Chrome closes that gap. It’s a Chrome browser extension that gives Claude Code direct control over your browser: navigate to URLs, click elements, read the console, fill forms, take screenshots, and observe the rendered result of what it just built.
Setup:
Install the Claude in Chrome extension from the Chrome Web Store
Enable it for your session:
Terminal window
claude--chrome# start with Chrome integration enabled
claude--no-chrome# disable for this session
/chrome# check connection status / manage permissions
What Claude can do with Chrome access:
Capability
Practical use
Navigate to localhost
Verify the page renders after a change
Read console errors
No copy-paste; Claude sees errors directly
Click through flows
Test that a form submission actually works
Screenshot + compare
Check visual output against expectations
Fill inputs
Test validation, edge cases, empty states
The key insight from Boris Cherny (Claude Code creator): “If Claude can’t see the result, it can’t improve it.” Code feedback loops catch syntax and logic errors. Browser feedback loops catch the rest: layout, interactions, runtime errors.
When /chrome is hidden: Claude Code hides the /chrome command when no Chrome integration is available for your current auth setup (v2.1.87+). Verify the extension is installed and Chrome is running if it doesn’t appear.
Introduced in v2.0.72 as “Claude in Chrome Beta”. The --chrome/--no-chrome flags and /chrome command control the browser integration. This is separate from the claude-in-chrome MCP server, which is a different browser automation mechanism.
Control how Claude responds to match your workflow and learning preferences. Output styles are a built-in product feature (not a prompt trick) and apply at the session level.
Explanatory and Learning produce longer responses by design, increasing output tokens. Prompt caching can reduce repeated input cost; it does not discount generated output tokens.
Custom output styles are Markdown files. Store project styles in .claude/output-styles/ or user-wide styles in ~/.claude/output-styles/, then reference the filename without its extension as the outputStyle value.
.claude/output-styles/
└── strict-reviewer.md # Custom style definition
By default, a custom style omits the built-in Claude Code software engineering instructions. For a coding-oriented style, preserve them with keep-coding-instructions: true in the file YAML frontmatter. Selecting a style applies it to the next message. Restart to discover newly created style files.
{
"outputStyle": "strict-reviewer"
}
See examples/styles/ for a ready-to-use custom style template.
Claude Code can generate Mermaid diagrams for visual documentation. This is useful for architecture documentation, flow visualization, and system understanding.
Jens Rusitschka identifies “context overload” as the primary failure mode of vibe coding: dumping entire codebases into context, hoping Claude will figure it out.
Symptoms:
Pasting 5K+ lines of code in first prompt
“Read the entire repo and implement X”
Expecting Claude to maintain context across 20+ file changes
Performance degradation after context pollution (see §2.2 Fresh Context Pattern)
Why it fails:
Attention dilution across too many files and concerns
Lost architectural reasoning in noise
Failed attempts accumulate, further degrading quality
Context bleeding between unrelated tasks
The Phased Context Strategy:
Instead of big-bang context dump, use a staged approach that uses Claude Code’s native features:
Phase
Tool
Purpose
Context Size
1. Exploration
/plan mode
Read-only analysis, safe investigation
Controlled (plan writes findings)
2. Implementation
Normal mode
Execute planned changes
Focused (plan guides scope)
3. Fresh Start
Session handoff
Reset when context >75%
Minimal (handoff doc only)
Practical workflow:
Terminal window
# Phase 1: Exploration (read-only, safe)
/plan
You:"How should I refactor the auth system for OAuth?"
Rusitschka’s “Vibe Coding, Level 2” is Claude Code’s native workflow, needing only explicit framing as an anti-pattern antidote. Plan mode prevents context pollution during exploration, fresh context prevents accumulation during implementation, and handoffs enable clean phase transitions.
Vibe coding gets things built fast. The codebases it produces tend to rot in ways that are hard to see: abstractions drift, naming becomes inconsistent, error handling gets done three different ways. The code still works, but working in it gets progressively worse.
“Slop” (a term coined by Simon Willison in 2024 for unwanted, unreviewed AI-generated content) is the quality problem that vibe coding at scale inevitably produces.
Desloppify (github.com/peteromallet/desloppify) is a community tool that directly addresses this. It installs a workflow guide into Claude Code as a skill, then runs a prioritized fix loop: scan → get next issue → fix → resolve → repeat until a quality score target is hit. The scoring is designed to resist gaming: improving the number requires actually improving the code.
Terminal window
pipinstall--upgrade"desloppify[full]"
desloppifyupdate-skillclaude# installs workflow as a Claude Code skill
# Before scanning: exclude generated files, build output, vendored code
desloppifyexcludenode_modules
desloppifyexclude.next
desloppifyscan--path.
desloppifynext# get first prioritized fix
# fix it, then:
desloppifyresolve<issue-id>
desloppifynext# repeat
The loop handles both mechanical issues (dead code, duplication, complexity) and structural ones (naming clarity, abstraction design, module boundaries). A score above 98 is meant to correlate with what a senior engineer would call a clean codebase.
Status: Early-stage (released February 2026, ~2K GitHub stars; 2,996 as of 2026-07-27). Promising native Claude Code integration but not yet battle-tested at scale. Evaluate token cost before running on large codebases: multi-pass LLM review across a full codebase can be substantial.
Batch operations improve efficiency and reduce context usage when making similar changes across files. For cost-optimized bulk processing at scale via the API, the Anthropic Message Batches API (client.messages.batches) processes up to 100 requests asynchronously at 50% of the synchronous cost (see the API Patterns section for full usage).
Batch operations extend beyond code changes. The same pattern applies to file conversion pipelines using native macOS tooling, with no external dependencies.
Use case: Convert a folder of PPTX presentations to PDF using Keynote.
Terminal window
# Requirements: macOS + Keynote installed. No LibreOffice, no Python.
./pptx-to-pdf.sh~/Downloads/Prose# recursive, processes all subdirectories
Finds all .pptx files recursively under the target folder
Skips files where a .pdf already exists (idempotent, safe to re-run)
Opens each file via shell, exports to PDF via AppleScript, then closes Keynote
Prints a summary of all generated PDFs at the end
Critical gotcha: open via shell, not AppleScript:
The intuitive approach fails:
-- This triggers error -1719 "Index non valable" on ~12% of files
tellapplication"Keynote"to open pptx_file
-- document 1 is sometimes empty, AppleScript throws on access
The fix: use open -a "Keynote" "$pptx" from the shell before the AppleScript block, with an 8-second sleep to let Keynote fully register the document. When Keynote opens a file via its own open command, it doesn’t always add it to the documents list. When the shell hands it a file path via open -a, it does.
Terminal window
# Correct pattern
open-a"Keynote""$pptx"# shell open
sleep8# wait for Keynote to register the document
osascript<<EOF
tell application "Keynote"
if (count of documents) > 0 then
export document 1 to (POSIX file "$pdf") as PDF
close document 1 saving no
end if
end tell
EOF
This same shell-open-then-AppleScript pattern generalizes to any macOS app that supports scripting but has unreliable document registration via its own open command.
Skip project context (CLAUDE.md) - leads to repeated corrections
Use vague prompts like “fix this” or “check my code”
Ignore errors in logs or dismiss warnings
Automate workflows without testing in safe environments first
Accept changes blindly without reviewing diffs
Work without version control or backups
Mix multiple unrelated tasks in one session
Forget to commit after completing tasks
✅ Do:
Maintain and update CLAUDE.md regularly with:
Tech stack and versions
Coding conventions and patterns
Architecture decisions
Common gotchas specific to your project
Be specific and goal-oriented in prompts using WHAT/WHERE/HOW/VERIFY format
Monitor via logs or OpenTelemetry when appropriate
Test automation in dev/staging environments first
Always review agent outputs before accepting, especially polished ones (see Artifact Paradox below)
Use git branches for experimental changes
Break complex tasks into focused sessions
Commit frequently with descriptive messages
⚠️ The Artifact Paradox: Anthropic AI Fluency Index (Feb 2026)
Anthropic research on 9,830 Claude conversations reveals a critical counter-intuitive finding: when Claude produces a polished artifact (code, files, configs), users become measurably less critical, not more.
Compared to sessions without artifact production:
−5.2pp likelihood of identifying missing context
−3.7pp likelihood of fact-checking the output
−3.1pp likelihood of questioning the reasoning
Users do become more directive (+14.7pp clarifying goals, +14.5pp specifying format), but their critical evaluation drops precisely when the output looks finished.
For Claude Code, this is the nominal case. Every generated file, every written test, every created config is an artifact. The polished compile-and-run output is exactly when you should apply the most scrutiny, not the least.
Counter-measures:
Run tests before accepting generated code, not after
Explicitly ask: “What edge cases or requirements did you not address?”
Try to learn everything at once - overwhelming and inefficient
Skip the basics and jump to advanced features
Expect perfection from AI - it’s a tool, not magic
Blame Claude for errors without reviewing your prompts
Work in isolation without checking community resources
Give up after first frustration
Trust AI output without proportional verification - AI code has 1.75× more logic errors than human-written code (source). Match verification effort to risk level (see Section 1.7)
✅ Do:
Follow progressive learning path:
Week 1: Basic commands, context management
Week 2: CLAUDE.md, permissions
Week 3: Agents and commands
Month 2+: MCP servers, advanced patterns
Start with simple, low-risk tasks
Iterate on prompts based on results
Review this guide and community resources regularly
Join Claude Code communities (Discord, GitHub discussions)
Git worktrees (available since Git 2.5.0, July 2015) create multiple working directories from the same repository, each checked out to a different branch.
Traditional workflow problem:
Terminal window
# Working on feature A
gitcheckoutfeature-a
# 2 hours of work...
# Urgent hotfix needed
gitstash# Save current work
gitcheckoutmain
gitcheckout-bhotfix
# Fix the bug...
gitcheckoutfeature-a
gitstashpop# Resume work
Worktree solution:
Terminal window
# One-time setup
gitworktreeadd../myproject-hotfixhotfix
gitworktreeadd../myproject-feature-afeature-a
# Now work in parallel
cd../myproject-hotfix# Terminal 1
claude# Fix the bug
cd../myproject-feature-a# Terminal 2
claude# Continue feature work
When to use worktrees:
✅ Use worktrees when:
Working on multiple features simultaneously
Need to test different approaches in parallel
Reviewing code while developing
Running long CI/CD builds while coding
Maintaining multiple versions (v1 support + v2 development)
❌ Don’t use worktrees when:
Simple branch switching is sufficient
Disk space is limited (each worktree = full working directory)
Team is unfamiliar with worktrees (adds complexity)
Worktrees isolate changes, not behavior. Each worktree has its own files and branch, but all of them share the repository’s Git metadata, including the stash list (a git stash made in one worktree appears in git stash list in the others), plus your credentials, local services such as databases and dev servers, and network access. Agents sharing a single worktree are worse off: in Bun’s Zig-to-Rust port, parallel agents ran git stash and git reset over each other’s work until the workflow forbade those commands (case study). For trusted work that tradeoff is usually acceptable. Unattended agents consuming untrusted content need a real sandbox and scoped credentials (sandbox isolation).
Worktree lifecycle commands:
The full worktree lifecycle is covered by 4 companion commands:
Command
Purpose
/git-worktree
Create worktree with branch validation, symlinked deps, background checks
💡 Tip: Symlink node_modules: The /git-worktree command symlinks node_modules from the main worktree by default, saving ~30s per worktree creation and significant disk space. Use --isolated when you need fresh dependencies (e.g., testing upgrades).
Worktree management:
Terminal window
# List all worktrees
gitworktreelist
# Remove worktree (after merging feature)
gitworktreeremove.worktrees/feature/new-api
# Cleanup stale worktree references
gitworktreeprune
💡 Team tip: Shell aliases for fast worktree navigation: The Claude Code team uses single-letter aliases to hop between worktrees instantly:
Terminal window
# ~/.zshrc or ~/.bashrc
aliasza="cd .worktrees/feature-a"
aliaszb="cd .worktrees/feature-b"
aliaszc="cd .worktrees/feature-c"
aliaszlog="cd .worktrees/analysis"# Dedicated worktree for logs & queries
The dedicated “analysis” worktree is used for reviewing logs and running database queries without polluting active feature branches.
# --worktree / -w flag: creates a temporary worktree based on HEAD
claude--worktree
claude-w
The worktree is created automatically, Claude runs inside it, and it is cleaned up on exit (if no changes were made).
Breaking change (v2.1.133): worktree.baseRef now defaults to fresh, reverting the v2.1.128 behavior where EnterWorktree branched from local HEAD. If you have unpushed commits you need in the worktree branch, set worktree.baseRef: "head" explicitly.
worktree.baseRef (fresh | head, default: fresh): Controls the base commit for worktrees created via --worktree, EnterWorktree, and agent-isolation worktrees.
Value
Behavior
fresh
Branch from origin/<default-branch>, always a clean remote base
The ConfigChange hook fires whenever a configuration file changes during a session. Use it to audit or block unauthorized live configuration modifications, particularly useful in enterprise environments with managed policy hooks.
.claude/settings.json
{
"hooks": {
"ConfigChange": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "scripts/audit-config-change.sh"
}
]
}
]
}
}
Example audit-config-change.sh (log + optionally block):
Enterprise note: disableAllHooks (v2.1.49+) can no longer bypass managed hooks: hooks set via organizational policy always run regardless of this setting. Only non-managed hooks are affected.
Policy fragment deployment with managed-settings.d/ (v2.1.83+)
In multi-team organizations, editing a single managed-settings.json creates merge conflicts and coordination overhead. The managed-settings.d/ drop-in directory solves this: each file is an independent policy fragment that Claude Code merges alphabetically at startup.
/etc/claude-code/managed-settings.d/
├── 00-security-baseline.json # From security team
├── 10-allowed-tools.json # From platform team
└── 50-team-hooks.json # From individual team
Each fragment follows the same schema as managed-settings.json. Conflicts are resolved by merge order (alphabetical). This lets security provide a global baseline without blocking teams from deploying their own fragments independently.
By default, if Claude Code cannot start the sandbox (macOS Seatbelt / Linux seccomp unavailable), it silently falls back to running unsandboxed. In security-sensitive environments this silent fallback is a compliance risk.
Set sandbox.failIfUnavailable: true in managed-settings.json to fail hard instead:
{
"sandbox": {
"failIfUnavailable": true
}
}
Recommended for: regulated environments (SOC 2, HIPAA), CI runners where sandbox availability is guaranteed, any context where an unsandboxed fallback is not acceptable.
By default, subprocesses spawned by Claude Code (Bash tool, hooks, MCP stdio) inherit the full shell environment, including Anthropic API keys and cloud provider credentials. Set CLAUDE_CODE_SUBPROCESS_ENV_SCRUB=1 to strip those credentials before subprocess execution:
Terminal window
exportCLAUDE_CODE_SUBPROCESS_ENV_SCRUB=1
This scrubs ANTHROPIC_API_KEY, AWS_*, GOOGLE_*, AZURE_*, and similar cloud provider variables from the subprocess environment. Claude Code’s own API calls are unaffected. Only the child processes are restricted.
When to enable: any hook or MCP script that makes outbound network calls and should not have access to your API credentials.
When running multiple agents in parallel worktrees, the hardest problem is coordination, not setup. There is no built-in automatic dependency detection between worktree agents. You manage it explicitly.
The pattern: analyze files touched, then set blockedBy manually
Before spawning parallel agents, identify which tasks share files:
Terminal window
# Quick dependency check: list files each task will touch
In the Tasks API, create both tasks and use TaskUpdate to add the prerequisite task ID to the dependent task. This is a coordination instruction, not a JSON tool-call schema:
Create task A: implement and merge the auth change.
Create task B: implement the payment service.
Use TaskUpdate to make B depend on A using their returned IDs.
Decision matrix:
Scenario
Strategy
Tasks touch different files, different modules
Parallelize freely
Tasks touch same module, different files
Parallelize with explicit conflict resolution step
Tasks touch same files
Sequence them
Task B needs Task A’s API contract
Block Task B until Task A’s interface is defined
Practical rule: A 5-minute analysis to find file overlaps before spawning agents saves hours of merge conflict resolution.
Tooling: coderabbitai/git-worktree-runner provides a bash-based worktree manager with basic AI tool integration. It handles the worktree lifecycle but not dependency detection: that stays manual.
Note: Fully automatic dependency detection (where the system infers which tasks conflict) doesn’t exist in Claude Code or the broader ecosystem as of March 2026. The approaches above are the practical state of the art.
Important: Claude Code uses lazy loading - it doesn’t “load” your entire codebase at startup. Files are read on-demand when you ask Claude to analyze them. The main context consumers at startup are your CLAUDE.md files and auto-loaded rules.
CLAUDE.md Token Cost Estimation:
File Size
Approximate Tokens
Impact
50 lines
500-1,000 tokens
Minimal (recommended)
100 lines
1,000-2,000 tokens
Acceptable
200 lines
2,000-3,500 tokens
Upper limit
500+ lines
5,000+ tokens
Consider splitting
Note: These are loaded once at session start, not per request. A 200-line CLAUDE.md costs ~2K tokens upfront but doesn’t grow during the session. The concern is the cumulative effect when combined with multiple @includes and all files in .claude/rules/.
Research boundary: Gloaguen et al., section 4.2 report average inference-cost increases of 20% and 23% for LLM-generated files on SWE-bench Lite and AGENTbench, respectively. Those are results for the tested configurations, not a surcharge for every instruction file. Cost, reasoning tokens and success rate are different measures.
# ❌ Bloated CLAUDE.md (wastes tokens on every session)
- 500+ lines of instructions
- Multiple @includes importing other files
- Rarely-used guidelines
# ✅ Lean CLAUDE.md
- Essential project context only (<200 lines)
- Move specialized rules to .claude/rules/ (auto-loaded at session start)
- Split by concern: team rules in project CLAUDE.md, personal prefs in ~/.claude/CLAUDE.md
Research note: Human-written context files had mixed benefits across agents in Evaluating AGENTS.md. The experiment does not establish a universal line limit or show that every generated file is harmful. Evaluate a shorter candidate against the existing file on representative tasks, retaining necessary project constraints. Source evaluation.
2. Use targeted file references:
Terminal window
# ❌ Vague request (Claude reads many files to find context)
"Fix the authentication bug"
# ✅ Specific request (Claude reads only what's needed)
"Fix the JWT validation in @src/auth/middleware.ts line 45"
3. Compact proactively:
Terminal window
# ❌ Wait until 90% context
/status# Context: 92% - Too late, degraded performance
# ✅ Compact at 70%
/status# Context: 72%
/compact# Frees up context, maintains performance
4. Agent specialization:
---
name: test-writer
description: Generate unit tests (use for test generation only)
model: haiku
---
Generate comprehensive unit tests with edge cases.
Benefits:
Haiku costs less than Sonnet
Focused context (tests only)
Faster execution
5. Batch similar operations:
Terminal window
# ❌ Individual sessions for each fix
claude-p"Fix typo in auth.ts"
claude-p"Fix typo in user.ts"
claude-p"Fix typo in api.ts"
# ✅ Batch in single session
claude
You:"Fix typos in auth.ts, user.ts, and api.ts"
# Single context load, multiple fixes
6. Pre-structural indexing:
Instead of letting Claude read files on demand throughout a session, pre-build a structural index of your codebase before starting. Claude queries the index (1 call) rather than reading files sequentially (5-10 reads per task).
Terminal window
# With CodeXRay (npx setup, SQLite-backed, 15 languages):
npxcodexray# Interactive setup + first index build
cxrwatch & # Background sync on file changes
# Claude Code then queries the graph instead of reading files:
# "find the payment module" → 1 graph query vs 5-10 file reads
Tools built on this pattern replace 5-10 file reads with 1 structured query: roughly 75% fewer tool calls for discovery tasks.
Dead code and circular dependency detection:
A structural index also enables analysis that file-by-file reading cannot surface efficiently:
Dead code: Functions defined but never called, safe to delete, reducing future context noise
Circular dependencies: Module A imports B imports A, architectural debt that silently inflates Claude’s reasoning overhead
Hotspots: Files with the highest dependency count. Prioritize these for documentation or refactoring first
Terminal window
# With grepai (zero callers = dead code candidate):
grepaitracecallers"MyFunction"# Empty result → safe to investigate for deletion
# With a structural MCP tool (if available):
# Tools like CodeXRay expose: codexray_deadcode, codexray_circular, codexray_hotspots
Community tools: CodeXRay (Tree-sitter + SQLite, 16 MCP tools, 15 languages) and Claudette (Go binary, 4 languages) are early implementations of this approach. Both are alpha-stage as of March 2026. Use grepai for production workflows.
Caveman is a Claude Code skill (also available for Cursor, Windsurf, Codex, Gemini CLI, and 26 other agents) that rewrites the assistant’s output style into compressed, telegraphic fragments. Articles, pleasantries, transitional summaries, and verbose explanations are stripped. Code blocks, file paths, URLs, commands, headings, and version numbers are preserved verbatim.
/caveman lite # grammar intact, only filler removed
/caveman ultra # maximum telegraphic compression
stop caveman # return to normal
Also auto-triggers on phrases like “be brief” or “less tokens please.” Auto-disables for security-critical messages and destructive operations.
Four compression modes:
Mode
Style
Lite
Full grammar, pleasantries stripped
Full (default)
Fragmented sentences, articles dropped
Ultra
Maximum telegraphic compression
Wenyan (文言文)
Classical Chinese literary mode, experimental
How it saves tokens: two mechanisms:
Output compression: The current Caveman README (read 2026-09-30) no longer leads with a 65% or 75% headline. It reports a 50% median output-token reduction on ten developer questions against a plain Answer concisely. control (length only, not correctness), and cites JetBrains’ independent test on 86 real coding tasks (skill only, no proxy): 8.5% fewer output tokens, no detectable quality change. Earlier claims of “~75%” and “65%” (the v1.9.1 release notes call 65% an average output-token reduction versus default verbose replies on a 10-prompt benchmark, range 22–87%) are no longer in the README. Most effective on explanation-heavy back-and-forth: architecture discussions, debugging narratives, Q&A.
Input compression via /caveman-compress: Rewrites your CLAUDE.md and project memory files into compressed form in place, claimed ~46% reduction in session startup token cost. Code blocks, URLs, and paths are untouched.
Companion tools included:
/caveman-commit: conventional commit messages under 50 chars, focused on “why”
/caveman-review: one-line PR comments with emoji severity markers
/caveman-stats: session token usage and lifetime savings (Claude Code only)
caveman-shrink: MCP wrapper that compresses tool/prompt description fields before they load into context
Honest numbers: Per-response figures apply to prose-style prompts, not to a session. In agentic coding sessions, most tokens are code and tool calls that the skill does not touch: JetBrains measured 8.5% fewer output tokens. The README’s proxy benchmark (54 pinned Claude Code runs) reports 33.2% fewer input tokens (885,793 to 591,673) with 18 of 18 answers correct, 95% interval 14.6% to 48.5%; the README itself calls it a pinned report, not a public reproduction. Caveman pays off most on sessions heavy in conversational back-and-forth, and least on sessions dominated by file reads, tool calls, or code generation.
When NOT to use it:
Documentation generation: output is meant to be read by humans
Code review comments shared with non-technical stakeholders
Debugging sessions where reasoning transparency matters
Multi-agent chains where downstream agents parse prior responses to reconstruct state
Stats: 93.5K GitHub stars as of 2026-07-27 (was 53K) | Created 2026-04-04 | MIT | Benchmark harness (evals/) is still maturing, treat specific percentages as directional
RTK (Rust Token Killer) filters command output before it reaches the model. Its reported reductions concern processed shell output, not the whole session or invoice. rtk gain uses local token estimates; count retries and task outcomes separately.
Repository:rtk-ai/rtk | Website:rtk-ai.app | Disclosure: the author of this guide is a core contributor to RTK (not its creator), so this is not an independent recommendation; whole-task measurements from several studies, and the maintainers’ response to them, are in context-engineering-tools.md.
For broader hooks, code navigation and MCP interception, see the Tokenade comparison and evidence boundary. It covers a proprietary alternative with vendor-maintained benchmark results, not a universal replacement recommendation.
Installation:
Terminal window
# Option 1: Homebrew (macOS/Linux)
brewinstallrtk
# Option 2: Cargo (all platforms, use --git: another "rtk" crate exists on crates.io)
cargoinstall--githttps://github.com/rtk-ai/rtk
# Option 3: Install script (Linux/macOS, installs to ~/.local/bin)
Compare equivalent commands on the same repository state and retain raw output for diagnosis. rtk gain reports estimates for filtered shell output, not measured savings on the entire invoice. No universal session reduction follows from a smaller git log or test log. See how RTK measures savings.
Key features (listed as of v0.28.0; latest release is v0.50.0):
rtkrewrite<cmd># Single source of truth for hook rewrites
rtkverify# Validate TOML filter rules
Measure the effect on your workload:
Compare representative raw and filtered outputs, then inspect rtk gain for its estimated output reduction. RTK’s byte-based token estimate is not the provider’s token count or a measured reduction in the full session bill. Retain raw output when filtering hides information needed for diagnosis.
TOML Filter DSL (v0.28.0, add filters without writing Rust):
RTK now supports a declarative filter engine via TOML config. You can add custom output filters for any command without touching Rust code.
# .rtk/filters.toml (project-local) or ~/.config/rtk/filters.toml (user-global)
Available primitives: strip_ansi, replace, match_output, strip/keep_lines_matching, truncate_lines_at, head/tail_lines, max_lines, on_empty
Debug: RTK_NO_TOML=1 bypasses all TOML filters. RTK_TOML_DEBUG=1 shows which filter fires.
Integration Strategies:
Hook-first install (recommended):
Terminal window
rtkinit--global# Sets up PreToolUse hook + patches settings.json automatically
CLAUDE.md instruction (manual wrapper):
## Token Optimization
Use RTK for all supported commands:
-`rtk git log`
-`rtk git status`
-`rtk git diff`
Skill (auto-suggestion):
Template: examples/skills/rtk-optimizer/SKILL.md
Detects high-verbosity commands
Suggests RTK wrapper automatically
Hook (automatic wrapper):
Template: examples/hooks/bash/rtk-auto-wrapper.sh
PreToolUse hook intercepts bash commands
Applies RTK wrapper when beneficial
Configuration Options:
~/.config/rtk/config.toml
exclude_commands = ["my-interactive-tool", "fzf"] # Never rewrite these
Migration Note (v0.25.0+):
After upgrading from v0.24.0 or earlier, run rtk init --global to install the new thin-delegator hook. The old hook still works, but won’t pick up new command mappings automatically.
Terminal window
cargoinstall--githttps://github.com/rtk-ai/rtk# Upgrade the correct RTK project
RTK handles command outputs (what you run). Smart explore handles code reading (what you read). Together they cover both major token sinks in a Claude Code session.
The problem: When Claude explores a codebase, it reads files completely: 400 lines when it needed 3 function signatures. A typical 10-file module exploration costs 35,000 tokens. With progressive exploration, the same task costs 3,500.
The pattern (3 steps, 86-92% reduction):
Step 1 — Structure (~200 tokens per file)
Get function signatures, types, fields only
Claude answers "what exists?" without reading any body
Step 2 — Target (~350 tokens per function)
Read one specific function by line offset
Not the whole file — just lines 45-90
Step 3 — Cross-reference (~150 tokens)
Find callers of a function
rg "function_name" --type rust -n
This is the same pattern Aider uses for its repo map (47.7K stars as of 2026-07-27, was 40k+), validated at scale since 2023.
Approach A: No setup, CLAUDE.md discipline
The fastest path. Add to your project’s CLAUDE.md:
## Code exploration protocol
When exploring a codebase or understanding a module:
1.**Structure first** — run the appropriate command for the language:
code-review-graph (MIT, 26.9K stars as of 2026-07-27, was 10k+)
pip install code-review-graph
Symbol lookup
jCodeMunch (free non-commercial)
claude mcp add jcodemunch uvx jcodemunch-mcp
code-review-graph is the strongest standalone option: MIT, 26.9K stars as of 2026-07-27 (was 10k+), 8.2x average token reduction across real codebases (gin: 16x, flask: 9x, FastAPI: 8x, Next.js: 8x). Builds a Tree-sitter AST of your repo, tracks blast radius per change, and exposes 28 MCP tools so Claude reads only the files that matter. Supports 23 languages + Jupyter notebooks, auto-updates on every git commit (< 2s re-index), and ships a multi-repo daemon for editor-agnostic setups.
Terminal window
pipinstallcode-review-graph
code-review-graphinstall# auto-detects Claude Code, Cursor, Windsurf, Zed, Continue, Kiro...
code-review-graphbuild# first-time parse (~10s for 500 files)
Honest benchmarks:
Task
Without smart-explore
With smart-explore
Savings
Understand 5-file module
~18,000 tokens
~2,500 tokens
86%
Find where to add a feature
~8,000 tokens
~800 tokens
90%
PR review (10 changed files)
~25,000 tokens
~3,500 tokens
86%
Single function lookup
~3,000 tokens
~350 tokens
88%
RTK vs Smart Explore, complete picture:
RTK
Smart Explore
What it saves
Command output tokens
Code reading tokens
When
After running git, cargo, npm
Before reading source files
How
Regex + text filtering
AST parsing (signatures only)
Typical savings
60-90% on CLI outputs (RTK README: “up to 90%” of bash output, not of the bill)
86-92% in the per-task estimates above (no controlled measurement cited); 10.5% cache-token savings in a controlled 50-iteration A/B of a comparable tree-sitter tool (jCodeMunch)
Setup
rtk init --global (2 min)
CLAUDE.md rule (0 min) or script (5 min)
Use both, but do not extrapolate the per-command figures to a session. No source in this guide supports a whole-session total for RTK plus smart explore. Whole-task measurements of RTK alone differ by study: JetBrains measured +7.6% median cost per task at low reasoning effort and +0.1% at high effort, Dasein +13% total cost, THOL +7.1% with an interval that crosses zero, and Codepointer’s replay -0.5% of spend. RTK’s maintainers dispute the JetBrains design and report -4.8% on 13 dev tasks (p = 0.305) in their own re-run (see context-engineering-tools.md).
Spending 2 hours manually debugging to save $1 in API costs
Using Haiku for complex tasks, generating incorrect code
Over-compacting context, losing valuable history
✅ Smart optimization:
Use right model for the task (time saved >> cost)
Invest in good prompts and memory files (reduce iterations)
Automate with agents (consistent, efficient)
Perspective on ROI:
Time savings from effective Claude Code usage typically far outweigh API costs for most development tasks. Rather than calculating precise ROI (which depends heavily on your specific context, hourly rate, and task complexity), focus on whether the tool is genuinely helping you ship faster. For team-level measurement, see Contribution Metrics, Anthropic’s GitHub-integrated dashboard for tracking PR and code attribution (Team/Enterprise plans, public beta).
When to optimize aggressively:
High-volume operations (>1000 requests/day)
Automated pipelines running 24/7
Large teams (cost scales with users)
Budget-constrained projects
When productivity matters more:
Critical bug fixes
Time-sensitive features
Learning and experimentation
Complex architectural decisions
The Interactive/Programmatic Billing Split (Announced, Then Paused)
Status, verified 2026-09-30: Anthropic announced this change on May 13, 2026 (reported by Gigazine on May 14) for June 15, 2026, then paused it. Its help article states: “We’re pausing the changes to Claude Agent SDK usage described below. For now, nothing has changed: Claude Agent SDK, claude -p, and third-party app usage still draw from your subscription’s usage limits.” The monthly credit is not currently available, and Anthropic says it will share updates before any change takes effect (Claude Help Center). The rest of this section describes the plan as announced, so you can prepare if it resumes.
Anthropic planned to split subscription usage into two distinct buckets. The first, called interactive usage, covers the Claude Code terminal and IDE, plus the web, desktop, and mobile chat interfaces. These workflows would keep existing subscription limits.
The second bucket, programmatic usage, would be new and capped. It covers claude -p (headless mode), the Agent SDK (Python and TypeScript), GitHub Actions with Claude, and third-party harnesses including OpenClaw, Hermes, Conductor, and any custom orchestration pipeline that invokes Claude outside of Anthropic’s own interfaces. For a detailed breakdown of these third-party harnesses and how they compare to Claude Code, see Agent Tools: Beyond Claude Code. Each subscription plan would receive a monthly credit. The announcement described usage beyond that credit as billed at standard API token rates, with no rollover.
The planned split is not “human interaction vs automation.” The operative distinction is Anthropic’s interface vs your interface. Running Claude Code interactively in the terminal uses Anthropic’s interface and would stay unchanged. Running your own harness or orchestrator uses your interface, which would be capped. This reflects where Anthropic is capturing value as LLM models commoditize: at the harness and UX layer, not the model layer.
This table reflects the May 13 announcement. Nothing in it applies while the change is paused.
Would be affected (programmatic bucket)
Would not be affected (interactive bucket)
claude -p / claude --print
Claude Code terminal (interactive sessions)
Agent SDK (Python and TypeScript)
Claude Code IDE integrations (VS Code, JetBrains, Xcode)
GitHub Actions using anthropics/claude-code-action
Claude.ai web chat
Scheduled automation and cron-triggered jobs
Claude desktop app
Background agent loops
Claude mobile apps
OpenClaw, Hermes, Conductor, custom harnesses
Any workflow with a human reading responses in real time
CI/CD pipelines invoking Claude
/loop scheduled tasks triggered interactively
Recursive multi-agent workflows
Routines triggered by GitHub events (counted as interactive)
Note: Routines (cloud-based scheduled tasks via claude.ai/code/routines) run on Anthropic’s infrastructure using Anthropic’s agent system. Their billing classification was not explicitly confirmed in the May 13 announcement; verify with Anthropic support if your Routines usage is substantial.
Warning: If ANTHROPIC_API_KEY is set in your shell environment or a .env file, Claude Code bypasses the subscription entirely and bills every request at API token rates, including your interactive sessions. This is independent of the programmatic credit plan, and applies today. Users have received API bills of $400 or more on top of an active $200 Max plan because of this.
Diagnose:
Terminal window
echo$ANTHROPIC_API_KEY# Any output means you are on API billing, not subscription
claude/cost# Shows real-time spend in the current session
Fix: Unset the variable in your shell profile (~/.zshrc, ~/.bashrc) if you want to route usage through your subscription. Only set ANTHROPIC_API_KEY when you explicitly intend to use direct API billing.
Run this audit to know how much of your usage is programmatic, whether or not the credit plan resumes.
Step 1. Check session spend:
Terminal window
claude/cost# or /usage since v2.1.118
Step 2. Review cross-session history with ccusage:
Terminal window
npxccusage# Breakdown by model and session type
Look for sessions initiated by scripts, CI jobs, or automation: these are your programmatic sessions. Estimate total monthly token spend for those sessions and compare it with the planned credit for your plan.
Step 3. Identify programmatic workflows in your setup:
Terminal window
# Find all places you invoke claude -p or use headless flags
This framework applies if the credit plan resumes. Until then, programmatic usage competes with interactive usage for the same subscription limits, which is a reason to apply Paths A and B anyway.
If your programmatic usage would stay within the planned credit: No action needed. Continue as-is and monitor with /cost or ccusage.
If your programmatic usage would exceed the planned credit, choose one or more of the following paths:
Path A. Reduce scope or frequency:
Increase the interval on scheduled jobs
Gate CI/CD Claude invocations to run only on PRs that touch specific paths
Replace multi-step agentic loops with single focused invocations
Path B. Migrate to direct API billing with a budget cap:
# .github/workflows/claude-review.yml — with spend awareness
# Set ANTHROPIC_API_KEY explicitly to use API billing
# Add a monthly budget alert in the Anthropic Console
claude -p "Review changes for security issues" ...
Direct API billing gives you predictable per-call costs and Console budget alerts. For low-volume CI/CD (occasional PR reviews), per-token API cost is typically lower than dedicating monthly credit to it.
Path C. Diversify orchestrators:
Use case
Alternative
Rationale
Unattended background work
OpenAI Codex
Designed for async, unattended execution
Large-document retrieval and search
Gemini 2.0/2.5
2M context at lower per-token cost
Synthesis and summarization at volume
Local models (Ollama + Llama/Qwen)
Zero marginal cost if hardware is available
Writing, planning, interactive review
Claude (keep)
Still the strongest model for these tasks
These are not mutually exclusive. A common pattern: keep Claude for interactive work and writing-quality tasks, route high-volume automated pipelines to whichever provider offers the best cost-performance for that specific workload. See Section 11: AI Ecosystem for a full tool matrix and the LLM market snapshot for dated provider prices.
The economic driver behind the announced change is straightforward. At the time of the announcement, a heavy power user running continuous agent automation could extract roughly $2,000 per month in API-equivalent compute for a $200 subscription. Extreme cases reached approximately $5,000 per month. At that ratio, Anthropic was losing around $300 per month on each extreme profile. The massive adoption of agent automation in late 2025 made this unsustainable.
The timeline matters: on May 6, Anthropic doubled interactive rate limits (announced alongside the SpaceX partnership). On May 13, the programmatic billing split was announced. It was due on June 15 and was paused before taking effect. On July 13, the temporary +50% interactive bonus ended. These are parts of the same capacity rebalancing, not isolated changes.
For the majority of Claude Code users who use it interactively in the terminal, the plan would have no impact. For teams that have built significant automation on top of claude -p or the Agent SDK, it remains a material change to plan for, since Anthropic says it is working on a revised version.
Six levers control LLM costs. Some are directly accessible within Claude Code; others require building on the Anthropic API or SDK. The table maps each lever to what is already available and where to find it.
On model routing via the API: RouteLLM (lm-sys, ICLR 2025, arXiv 2406.18665) trains a lightweight router that decides per-call whether to invoke a strong model or a cheaper one. On MT-Bench it achieves 85% cost reduction vs always-strong routing while matching 95% of strong-model performance. The technique applies to automated pipelines built on the Anthropic API, not to interactive Claude Code sessions.
On batch processing: The Message Batches API is the highest-leverage lever for automated pipelines (nightly classification, bulk document analysis, large-scale data extraction). Not applicable to interactive use. For high-volume asynchronous work, compare the Message Batches API with your current subscription or API billing path. The announced June 15 programmatic billing split was paused; do not budget as if that separate credit is active.
Memorable named patterns for effective Claude Code interaction. These patterns have emerged from community best practices and help you communicate more effectively.
Reading time: 5 minutes
Skill level: Week 2+
Status: Research Preview (as of January 2026)
Session teleportation allows migrating coding sessions between cloud (claude.ai/code) and local (CLI) environments. This enables workflows where you start work on mobile/web and continue locally with full filesystem access.
TL;DR: Multi-instance orchestration = advanced pattern for teams managing 10+ concurrent features. Requires modular architecture + budget + monitoring. 95% of users don’t need this. Sequential workflows with 1-2 instances are more efficient for most contexts.
Before adding another process manager, identify the layer that owns each responsibility. The model generates text; the runtime harness owns a session’s model-and-tool loop; the repository harness supplies instructions and delivery gates; the orchestrator coordinates sessions. Agent Harness Engineering explains the boundaries. The Agent Harness Map compares strict runtime harnesses and keeps its wider sourced directory separate from the runtime table. Agent Tools: Beyond Claude Code covers frameworks and control planes; the glossary defines the terms.
Research Preview (available on Pro, Max, Team, Enterprise, and Claude API plans). Opt-in: claude agents.
Before setting up tmux grids or third-party orchestrators, try Agent View, Claude Code’s built-in session manager.
How to access:
claude agents from any terminal
Left arrow ← from within any active session
What you see: each row shows session name, status (working / waiting on you / done), last response preview, and time since last interaction.
Key commands:
Action
How
Open agent view
claude agents or ← from any session
Background current session
/bg
Launch new background session
claude --bg [task]
Peek at last turn
Select session
Reply inline (waiting session)
Select → type reply → session resumes
Attach to full transcript
Enter on any session
Workflow patterns (from early users):
Dispatch and return: Send multiple tasks with claude --bg, return to a list of PRs ready for review
Long-running agents: PR babysitters and looping jobs show next run time in the list
Quick context switch: Left arrow, start a related task or quick question, peek for the answer, right arrow back
Status scan: Status indicators tell you which sessions produced a PR without entering each one
Relation to third-party tools: Before Agent View, parallel session management required tmux, multiclaude, or apps like Conductor. Agent View covers the core “what’s running and what needs me” use case natively. Conductor and similar tools remain relevant for GitHub CI integration, PR workflows, and multi-repo management beyond what Agent View provides.
/goal <condition> sets a completion condition for the current session. A separate evaluator can continue the work, mark the condition met, or judge it impossible. Some unrecoverable errors also clear the goal. A completed goal is evidence about the stated condition; acceptance of the change still follows the project’s review policy.
How it works: After each turn, a small fast model (Haiku by default) reads the conversation and judges: “Is the condition met, based only on evidence already in this conversation?” If not, it generates a concise reason explaining the gap, which drives the next turn. If yes, the loop ends. The evaluator cannot independently run commands. It judges solely against what Claude has already surfaced in the conversation.
A live overlay tracks elapsed time, turn count, and token consumption throughout execution.
Manage an active goal:
Command
Effect
/goal <condition>
Set or replace the current goal
/goal clear
Cancel the active goal
/goal
Show condition, progress and evaluator’s last reason
Three elements of an effective condition:
Measurable end state: a specific output, test result, or file state. “All tests in test/auth pass” beats “improve the auth system.”
Verification mechanism: how success is demonstrated. “verified by npm test auth exit 0.”
Constraints: what must stay intact throughout. “no files outside src/services/auth modified.”
Full example: /goal all tests in test/auth pass, verified by npm test auth exit 0, no files outside src/services/auth modified
Bound the run: Include an explicit limit, for example or stop after 5 turns. The evaluator judges that clause from the conversation; it is not a deterministic execution counter. If exceeding a budget is unacceptable, enforce it in the controller outside the model. The bounded-loop example demonstrates a program-enforced attempt limit without invoking a model. Its test does not validate Claude Code’s runtime.
Resume and failure: An active goal is restored when the session resumes, but its turn count, timer and token-spend baseline reset. Keep a durable total budget outside those session counters when work spans resumes. The evaluator can clear an impossible goal; unrecoverable credit, context or model errors can clear it too. Inspect the recorded reason rather than treating every cleared goal as success.
/goal vs /loop:
/goal
/loop
Next turn starts when
Previous turn finishes and goal remains unmet; background work can defer evaluation
Scheduled interval elapses and the session can run it
Stops when
Condition met, judged impossible, cleared manually, or cleared after an unrecoverable error
Cancelled or expired; a self-paced loop can also finish its task
Evaluator
Separate model (Haiku default)
Primary model self-assesses
Best for
Task with a clear, measurable finish line
Ongoing monitoring without a defined end
Example
”Migrate all API calls, tests pass"
"Check the deploy every 5 minutes”
Anti-patterns (skip /goal when):
The objective is vague or qualitative (“make the code cleaner”)
Completion requires human judgment the AI cannot verify
Production data is involved and every step needs direct oversight
There is no concrete, checkable end state
Permissions: /goal does not expand the session’s permission boundary. If the session requires confirmation before executing shell commands, those confirmations still fire inside a goal loop. Configure permission mode deliberately before activating a goal.
Context on long tasks: Track progress and retained evidence instead of assuming a universal turn threshold for degradation. An orchestrator can start a fresh non-interactive session for each bounded subtask, but must supply the requirements, current artifact and previous results explicitly:
Terminal window
# Each call runs in a fresh session — no context accumulation
claude-p"Step N of migration: [specific sub-task with explicit context]"
Introduced in v2.1.139 (May 12, 2026). Current status, evaluation and resume behavior checked September 10, 2026 against Keep Claude working toward a goal.
The Boris pattern validation: Boris’s $500-1K/month cost and 259 PRs/month aligns with Anthropic’s enterprise data showing positive ROI at >3 parallel instances.
Anti-pattern alert (Anthropic findings):
Over-delegation (>5 agents): Coordination overhead > productivity gain
Critical context: Boris is the creator of Claude Code, working with perfect architecture, Anthropic resources, and ideal conditions. This is not representative of average teams.
Key insights from Boris:
On multi-clauding: “I use Cowork as a ‘doer,’ not a chat: it touches files, browsers, and tools directly. I think about productivity as parallelism: multiple tasks running while I steer outcomes.”
On CLAUDE.md: “I treat Claude.md as compounding memory: every mistake becomes a durable rule for the team.”
On plan-first workflow: “I run plan-first workflows: once the plan is solid, execution gets dramatically cleaner.”
On verification loops: “I give Claude a way to verify output (browser/tests): verification drives quality.”
Why evaluate Opus with adaptive thinking: Compare accepted outcomes, retries, latency, and total cost against Sonnet. A higher token price does not establish better results or lower cost per accepted task.
The supervision model: Boris describes his role as “tending to multiple agents” rather than “doing every click yourself.” The workflow becomes about steering outcomes across 5-10 parallel sessions, unblocking when needed, rather than sequential execution.
Team patterns (broader Claude Code team, Feb 2026):
The broader team extends Boris’s individual workflow with institutional patterns:
Skills as institutional knowledge: Anything done more than once daily becomes a skill checked into version control. Examples:
/techdebt: run at end of session to eliminate duplicate code
Context dump skills: sync 7 days of Slack, Google Drive, Asana, and GitHub into a single context
Analytics agents: dbt-powered skills that query BigQuery; one engineer reports not writing SQL manually for 6+ months
CLI and scripts over MCP: The team prefers shell scripts and CLI integrations over MCP servers for external tool connections. Rationale: less magic, easier to debug, and more predictable behavior. MCP is reserved for cases where bidirectional communication is genuinely needed.
Re-plan when stuck: Rather than pushing through a stalled implementation, the team switches back to Plan Mode. One engineer uses a secondary Claude instance to review plans “as a staff engineer” before resuming execution.
Claude writes its own rules: After each correction, the team instructs Claude to update CLAUDE.md with the lesson learned. Over time, this compounds into a team-specific ruleset that prevents recurring mistakes.
Separate architecture and implementation into distinct sessions when a task needs a clear design contract. The architect explores alternatives with the human; the engineer receives selected requirements and returns a reviewable change. This can compose with parallel worktrees.
The original practitioner example comes from Jon Williams, February 3, 2026. Sami Honkonen’s architect-engineer account, August 24, 2026, adds a concrete handoff protocol. These accounts do not establish general cost savings, defect reduction, or reviewer independence.
Use it when material requirements need resolution, architecture decisions should persist, or implementation will continue in another context. A bounded change with clear acceptance criteria may need only one session. Compare coordination and review overhead against the problems the separation actually prevents.
Use a planner session and an engineer session. A shared plan file or task comment carries the selected contract. Optional directories such as .claude/plans/Review/, Active/, and Completed/ organize that work; moving a file does not enforce approval or grant external-action permissions. Role prompts guide behavior; configure tool permissions separately.
Design: architect and human resolve objective, scope, constraints, and acceptance criteria.
Handoff: record the contract revision, base state, affected paths or symbols, implementation steps, tests, blockers, permitted actions, and assigned engineer. Link applicable ADRs for durable decisions.
Implement: engineer checks the live state, implements within scope, and returns a diff plus actual verification results.
Review: architect checks requirements, code, tests, and assumptions. Feedback identifies the reviewed revision and expected correction.
Close: authorized integration and required verification precede completion. Archive the task summary and preserve durable decisions and audit links.
In Honkonen’s setup, the initial handoff is a self-contained Linear comment; the reply is a GitHub PR. Review feedback goes through his custom eng review <run> --feedback "..." command, not through Linear. That command is not built into Claude Code. Adopt the contract using channels already available to your team.
Ticket status marks whose turn it is. Execution status records what a dispatched run is doing. ADR status records whether an architectural decision is proposed, accepted, or superseded. These states serve different purposes: an Accepted ADR can outlive many tickets, and an In Progress ticket does not prove that a run is healthy or uniquely assigned.
There is no demonstrated universal break-even point at two correction loops. Compare equivalent tasks under the same acceptance rule, including planning, failed attempts, coordination, human attention, review, and rework. Keep API billing, subscription spend, and quota use separate. See evaluation epochs and four clocks.
Provide selected decisions rather than the whole exploratory conversation. A plan should contain enough evidence and source routes for the engineer to proceed without reconstructing the architect’s context. Use real paths and symbols at an identified revision; line numbers are navigation hints that may drift.
For example, a CSV export contract can name the existing export service, require preservation of current filters and access boundaries, and specify fixtures covering quotes, commas, and inaccessible records. These are observable criteria; predicted line counts are not.
Bind approval to an identified contract revision. Reconcile old completion claims with live state when resuming. Do not repeat side effects blindly. Amend the contract when requirements change, and record who owns the next action.
A planner reviewing its own design can preserve a shared error. Separate context is not proof of independent judgment. Use independent acceptance criteria, executable checks, and risk-appropriate additional review. Evaluate the added coordination cost before extending the pattern.
While git worktrees are foundational, daily productivity improves with automation wrappers. Multiple professional teams have independently created worktree management tools, a validated pattern.
Alias feels limiting (want CI status, LLM commits, project hooks)
Volume increases to 15+ worktrees/week
Team adopts multi-instance workflows (need consistent tooling)
Bottom line: Most readers (80%) should start with vanilla git or alias. Worktrunk is for power users managing 5-10+ instances daily where typing friction and CI visibility matter.
+50% productivity (self-reported, vs +20% 12 months prior)
2-3x increase year-over-year in usage and output
59% of work involves Claude (vs 28% a year ago)
27% of work “wouldn’t have been done otherwise” (scope expansion, not velocity)
Autonomous actions:
21.2 consecutive tool calls without human intervention (vs 9.8 six months prior)
+116% increase in autonomous action chains
33% reduction in human interventions required
Average task complexity: 3.8/5 (vs 3.2 six months before)
Critical concerns (verbatim quotes from engineers):
“When producing is so easy and fast, it’s hard to really learn”
“It’s difficult to say what roles will be in a few years”
“I feel like I come to work each day to automate myself”
Implications: Even at Anthropic (perfect conditions: created the tool, ideal architecture, unlimited budget), engineers express uncertainty about long-term skill development and role evolution.
Five months after the internal study, Anthropic published updated productivity data alongside a new analytics feature for Team and Enterprise customers.
Updated metrics (Anthropic internal):
+67% PRs merged per engineer per day (vs Aug 2025 self-reported +50%)
70-90% of code now written with Claude Code assistance across teams
Methodological note: These figures are PR/commit-based (measured via GitHub integration), not self-reported surveys as in the Aug 2025 study. However, Anthropic discloses no baseline period, no team breakdown, and defines measurement only as “conservative — only code where we have high confidence in Claude Code’s involvement.” Treat as directional indicators, not rigorous benchmarks.
Product feature: Contribution Metrics dashboard:
Status: Public beta (January 2026)
Availability: Claude Team and Enterprise plans (exact add-on requirements unconfirmed)
Tracks: PRs merged and lines of code committed, with/without Claude Code attribution
Access: Workspace admins and owners only
Setup: Install Claude GitHub App → Enable GitHub Analytics in Admin settings → Authenticate GitHub organization
Positioning: Complement to existing engineering KPIs (DORA metrics, sprint velocity), not a replacement
Goal: Scale to 3-5 instances with orchestration framework.
Terminal window
# 1. Deploy orchestration framework (choose based on needs)
# - Headless PM (manual coordination)
# - Gas Town (parallel task execution)
# - multiclaude (self-hosted, tmux-based)
# - Multica (issue/chat control plane with local daemon execution)
# - Entire CLI (governance + sequential handoffs)
# 2. Define roles
# - Architect (reviews PRs)
# - Backend (API development)
# - Frontend (UI development)
# - QA (test automation)
# 3. Weekly retrospectives
# - Review conflict rate
# - Measure ROI (cost vs output)
# - Adjust instance count
Orchestration framework options:
Tool
Paradigm
Best For
Manual (worktrees)
No framework
2-3 instances, full control
Gas Town
Parallel coordination
5+ instances, complex parallel tasks
multiclaude
Self-hosted spawner
Teams needing on-prem/airgap
Multica
Issue-driven multi-provider control plane
Teams coordinating local agent CLIs through a server/daemon split
Entire CLI
Governance + handoffs
Sequential workflows with compliance
Multica keeps issues, chat, agent configuration, schedules, and run records in its coordination tier while connected computers execute Claude Code, Codex, and other CLIs through a local daemon. See the evidence-pinned Multica profile for deployment, data, security, Git, and licence boundaries.
Entire CLI (Feb 2026): Alternative to parallel orchestration, focuses on sequential agent handoffs with governance layer (approval gates, audit trails). Useful for compliance-critical workflows (SOC2, HIPAA) or multi-agent handoffs (Claude → Gemini). See AI Ecosystem Guide for details.
Success criteria: Sustained 3-5% productivity gain over 3 months.
Every API request Claude Code makes now includes an X-Claude-Code-Session-Id header. Reverse proxies and API gateways can use it to aggregate costs, latency, and quota usage by session without inspecting the request body.
nginx example:
map $http_x_claude_code_session_id $session_id {
default $http_x_claude_code_session_id;
}
log_format claude '$remote_addr - $session_id - $request_time - $status';
This lets you build per-session dashboards, enforce session-level rate limits, or attribute API costs to individual developers or CI jobs, all without modifying Claude Code’s configuration.
The paradigm shift: Traditional codebases are optimized for human developers. AI agents have different needs. They excel at pattern matching but struggle with implicit knowledge and scattered context.
Key principles:
Domain Knowledge Embedding: Put business logic and design decisions directly in code (CLAUDE.md, ADRs, comments)
Code Discoverability: Make code “searchable” like SEO: use synonyms, tags, complete terms
Documentation Formats: Use llms.txt for AI-optimized documentation indexing (complements MCP servers)
Token Efficiency: Split large files, remove obvious comments, use verbose flags for debug output
Testing for Autonomy: TDD is more critical for agents than humans: tests guide behavior
Guardrails: Hooks, CI checks, and PR reviews catch agent mistakes early
When to optimize for agents: High-impact files (core business logic, frequently modified modules) and greenfield projects. Don’t refactor stable code just for agents.
Why this matters: Agents read code sequentially and lack the “mental model” humans build over time. What’s obvious to you (e.g., “this service handles auth”) must be made explicit.
... (minimal context, rest is framework conventions)
Recommendation: For greenfield projects with AI-assisted development, prefer opinionated frameworks unless architectural constraints require custom design. The reduction in agent cognitive load often outweighs loss of flexibility.
Problem: Agents lack context about your business domain, design decisions, and project history. They can read code syntax but miss the “why” behind decisions.
Solution: Embed domain knowledge directly in discoverable locations.
-**Appointment**: External calendar system's term (Google/Outlook)
-**Sync Job**: Background process reconciling our DB with external calendars
-**Conflict Resolution**: Algorithm handling overlapping events (see `src/services/conflict-resolver.ts`)
## Gotchas
- Google Calendar API has 10 req/sec rate limit per user → batch operations in `syncEvents()`
- Outlook timezone handling is non-standard → use `normalizeTimezone()` helper
- Event deletion = soft delete (set `deletedAt`) to maintain audit trail for compliance
Why this works: When the agent encounters syncEvents(), it understands the rate limiting constraint. When it sees deletedAt, it knows not to use hard deletes.
This repository is moving from a hybrid machine-readable index toward stricter ownership boundaries. Today, reference.yaml mixes navigation with selected commands, templates, configuration values, counters, and operational facts. Dedicated release, Cowork, and distribution registries own some changing domains, but the separation is not complete. Coverage is also asymmetric: reference.yaml reaches every tracked file under guide/, while routes into docs/ and examples/ remain curated.
Machine-readable means parseable and addressable. It does not mean verified, current, exhaustive, or cleanly separated by domain. On 2026-09-04, check-index-coverage.py reached 104 of 104 tracked guide/ files. No equivalent exhaustive gate covers every file under docs/ or examples/; entries from those trees remain selected routes. Existing validators accept the hybrid reference.yaml contract and do not prove that every key belongs in its ideal target layer. Each validator below proves a narrower property.
Curated topic, path, anchor, template, command, and decision lookup, with exhaustive file-level coverage limited to tracked guide/ files
The main guide, focused guides, selected docs and examples, and root VERSION
A referenced heading or path changes; a new guide page or lookup concept lands; the guide version changes
validate-reference-yaml.py --ci, resync-reference-yaml.py --check, check-index-coverage.py --check --max-missing 0, plus the MCP mirror check
Proves YAML parsing, referenced path and anchor resolution, positional-reference alignment, and tracked guide/ file coverage. It does not prove factual accuracy or exhaustive docs/ and examples/ coverage.
machine-readable/claude-code-releases.yaml
Condensed, newest-first Claude Code release history
Anthropic’s official Claude Code changelog, manually condensed
A reviewed Claude Code release is added
YAML parsing in validate-reference-yaml.py --ci; MCP mirror check; the MCP documentation test compares latest with the version announced by all three llms.txt mirrors
Proves local structure, mirror equality, and version coupling. It does not prove upstream freshness or that every upstream note was retained.
machine-readable/cowork-reference.yaml
Local proxy index for the separate Claude Cowork guide
The Cowork guide’s canonical machine-readable/reference.yaml
The canonical Cowork index is reviewed and its version or routes change
YAML parsing in validate-reference-yaml.py --ci
Proves that the local snapshot parses. It does not contact the Cowork repository or prove that the proxy matches its current remote state.
machine-readable/distribution-channels.yaml
Dated state for assets, submissions, placements, attributed URLs, and outcome fields
Local distribution assets plus reviewed submission, placement, and measurement evidence
An asset or channel changes state, or a dated observation is collected
test-check-distribution-channels.py and check-distribution-channels.py, plus the MCP mirror check
Proves schema rules, allowed states and cross-field coherence, required dates, local ready-asset existence, and attribution fields. It does not prove external publication or replace missing outcomes with zero.
llms.txt
Short discovery index for humans, crawlers, and agents
Curated routes into repository documentation; the tracked Claude Code version comes from claude-code-releases.yaml
A primary entry point changes or the release registry’s latest value changes
mcp-server/test/render-product-docs.test.mjs, executed by npm run release:check in CI
Proves byte equality across root, machine-readable/, and the MCP bundle, plus release-version parity. It does not prove that every useful page is listed or that linked prose is current.
The repository keeps three byte-identical copies of llms.txt: root discovery, machine-readable/ source, and the MCP package bundle. A release update is incomplete until all three announce the same latest value as claude-code-releases.yaml.
The llms.txt proposal defines a Markdown-formatted entry point for LLM-oriented documentation. Keep this file short enough to scan before loading detailed sources. Prefer stable heading anchors over line numbers because inserted prose moves line positions.
# Project documentation
## Start
- Setup: docs/setup.md
- Architecture: docs/architecture.md#request-flow
## Operate
- Testing: docs/testing.md
- Deployment: docs/deployment.md
- Troubleshooting: docs/troubleshooting.md
CLAUDE.md has a different scope. It supplies active instructions and repository context to Claude Code. llms.txt routes a reader to documentation. A short instruction can point to the index without copying it:
## Project documentation
Start with `llms.txt`, then open only the source relevant to the task.
An MCP documentation server can expose the same sources through runtime search and resource APIs. That transport does not replace the static index, and the static index does not prove the server’s runtime behavior.
Catalog Pattern: CATALOG.yaml, INDEX.md, TOPICS.md, and llms.txt
For a repository with many documents, split inventory from navigation. The following layout is an illustrative pattern, not a public artifact from this guide:
docs/
INDEX.md human-readable inventory
TOPICS.md curated routes by reader intent
machine-readable/
CATALOG.yaml structured record for every document
llms.txt short discovery entry point
File
Owns
Must not own
CATALOG.yaml
Stable IDs, paths, titles, owners, status, and source dates
Long explanations copied from the documents
INDEX.md
Browsable list of catalog records
Independent status values that can drift from the catalog
TOPICS.md
Curated sequences such as start, build, operate, and troubleshoot
A second exhaustive inventory
llms.txt
Top entry points and links to INDEX.md and TOPICS.md
The complete catalog or active agent instructions
Choose one authoring direction and enforce it. If CATALOG.yaml is canonical, generate or check INDEX.md from it and reject drift in CI. Keep TOPICS.md editorial because ordering by reader intent requires judgment. Build llms.txt from stable routes, then test every path and mirror.
A structural check can prove that IDs are unique, paths exist, generated files match, and declared dates parse. Editorial accuracy, ownership, freshness, and the usefulness of topic ordering still require review.
Official Claude Code Machine-Readable Documentation
Anthropic publishes an official documentation index and an official full documentation export. Use the index to locate the relevant source, then open the specific page or full export when the claim requires more context. These endpoints are upstream sources for Claude Code behavior, not validators for this repository’s indexes.
Problem: Internal knowledge lives in catalog APIs, wikis, code comments, and the heads of senior engineers. Every agent builder reassembles the same context from scratch. A new agent onboarding to your codebase learns what weekly_active_users means by asking someone, not by reading a file.
Solution: OKF (Open Knowledge Format) is a vendor-neutral spec that turns your internal knowledge into a directory of markdown files with YAML frontmatter. Agents read it directly; humans author it in any editor; git versions it like code.
In April 2026, Andrej Karpathy published a GitHub gist describing a pattern he had been using: a structured markdown wiki giving LLMs reliable internal context. The post drew 16M+ views on X and the gist accumulated 5,000+ stars within days. Community implementations proliferated immediately under names like AGENTS.md, Obsidian-to-agent pipelines, and repos full of index.md files an agent reads before it does real work.
Google Cloud formalized the pattern into OKF v0.1 on June 12, 2026. The spec is minimal by design: it standardizes the structural conventions needed to make a knowledge corpus self-describing, and nothing more.
A bundle is a directory of markdown files. Each concept is one file; the file path is its identity. The directory becomes a graph when files link to each other.
sales/
├── index.md # optional directory listing
├── log.md # optional chronological history
├── tables/
│ ├── orders.md
│ └── customers.md
└── metrics/
└── weekly_active_users.md
A concept document has two parts: YAML frontmatter (structured, queryable) and a markdown body (prose, schema, examples):
---
type: database-table
title: orders
description: One row per completed customer order. Source of truth for revenue.
tags: [revenue, core]
timestamp: 2026-05-28T14:30:00Z
---
# Schema
| Column | Type | Description |
|--------|------|-------------|
| `order_id` | UUID | Primary key |
| `user_id` | UUID | FK to [customers](/tables/customers.md) |
Distribution: git repository (recommended), tarball, or a subdirectory within a larger repo
Permissive consumption: consumers must tolerate missing optional fields, unknown types, extra keys, and broken links. This is intentional. The format is designed to grow.
OKF does not replace the formats you already use. It fills a different slot in the knowledge stack:
Format
Scope
Purpose
CLAUDE.md
Session
Active instructions for this agent, this session
AGENTS.md
Behavior
Rules on what agents should and should not do
llms.txt
Discovery
Where to find documentation in this project
OKF bundle
Knowledge corpus
What the organization knows: schemas, metrics, runbooks, join paths
llms.txt tells an agent where to find docs. OKF tells it what weekly_active_users actually means at your company, why the orders table has a status field with four states, and which join path is correct. Different problem, different layer.
Pattern: reference your bundle from CLAUDE.md so agents know it exists:
## Domain knowledge
Internal knowledge bundle: `knowledge/`
- Type `database-table` → table schemas with business rules
- Type `metric` → business metric definitions and ownership
v0.1 is an invitation, not yet a standard. At launch, every producer and consumer was built by Google. Google Cloud’s own Knowledge Catalog already ingests OKF and serves it to agents. The vendors to watch for external adoption: Atlan, Alation, Collibra, Unity Catalog.
The adoption risk for you is near zero: OKF bundles are plain markdown files in a directory. If the spec never gains traction, the files remain readable by humans and agents regardless.
Enforce required human approval through repository policy on the paths that need it. Counting entries in reviews does not establish approval: entries can be comments, change requests, stale decisions or automation output.
Use native protected-branch review settings: require approving reviews and designated code owners for sensitive paths. Configure stale-approval handling or approval of the latest reviewable push. Inspect eligible reviewer identities, dismissal rights and bypass permissions; a review count alone cannot prove that a human owner approved.
Verify the effective policy with an unapproved PR, a change request, a new push after approval and an authorized approval. Keep required checks and integration-state validation alongside that policy. These are configuration and verification instructions, not a workflow that has been installed or exercised in your repository.
Why human review matters:
Agents miss context (business requirements not in code)
Agents may implement correct code for wrong problem
Security vulnerabilities AI doesn’t recognize (novel attack vectors)
Review checklist for agent PRs:
## Agent PR review checklist
- [ ] **Intent**: Does the code solve the actual problem (not just pass tests)?
Most developers pick one approach and stick with it. But Claude Code’s tooling supports systematic variation: testing multiple approaches to find the optimal solution.
Permutation Frameworks formalize this: instead of hoping your first approach works, you systematically generate and evaluate variations.
A permutation framework defines dimensions of variation and lets Claude generate all meaningful combinations. Each dimension represents a design choice; each combination is a distinct implementation approach.
Agent teams enable multiple Claude instances to work in parallel on a shared codebase, coordinating autonomously without human intervention. One session acts as team lead to break down tasks and synthesize findings from teammate sessions.
Key difference from Multi-Instance (§9.17):
Multi-Instance = You manually orchestrate separate Claude sessions (independent projects, no shared state)
Agent Teams = Claude coordinates through shared tasks and mailbox messages; source changes still need ownership and integration rules
Two distinct coordination patterns exist for multi-agent review, and the choice matters:
Dimension
Sequential Specialists
Swarm Mode
Structure
Predefined lead + members
Ad-hoc, no hierarchy
Coordination
Lead assigns tasks, synthesizes
Each reviewer works independently
Leadership
Team lead orchestrates
Human synthesizes findings
Task assignment
Lead delegates to specific agents
All relevant agents get the same input
Best for
Tasks with dependencies between reviewers
Independent review, final pre-merge pass
When to use
Complex workflows, state needs sharing
PR review, unfamiliar codebase, thoroughness
Swarm Mode in practice (Every.to compound-engineering pattern):
Launch all relevant specialist reviewers in parallel against the same diff or PR, with no coordination between them. Each produces independent findings. You read all findings and decide what to act on.
Terminal window
# Swarm: all reviewers see the same input, report independently
This is distinct from Agent Teams: there is no persistent team structure, no shared context between agents, no lead synthesizing in real time. It is faster to set up and appropriate when thoroughness matters more than coordination.
Rule of thumb: Use Agent Teams for workflows with sequential dependencies (agent A’s output feeds agent B). Use Swarm when each reviewer can work from the same starting point and you want maximum coverage with minimum setup overhead.
Standard multi-agent pipelines have a systematic flaw: audit agents over-report. When you ask three sub-agents to find contradictions, duplications, or coverage gaps in a set of artifacts, they will find them everywhere, including in patterns that are intentional, complementary, or simply not conflicting.
The solution is a fourth agent whose only job is to reject false positives from the first three.
How it works:
Phase 1: Artifact inventory (orchestrator builds the inventory)
Phase 2: Pairwise analysis (3 agents in parallel, each owns one pair-type)
├── Agent A: standards vs skills
├── Agent B: standards vs commands
└── Agent C: skills vs commands
Phase 3: Skeptical review (1 agent reviews all raw findings)
└── Applies false-positive filter criteria
└── Produces KEEP/REJECT log + final report
The skeptical reviewer agent operates with explicit anti-hallucination rules. From the Packmind playbook-audit implementation:
“Be skeptical. Audit agents tend to over-report; your job is to filter. A 50%+ rejection rate is normal and healthy.”
False positive criteria the reviewer applies before keeping a finding:
Intentional scope limits: The artifacts address different scopes (all files vs migration files only) and do not actually conflict within the narrower scope
Complementary content: One artifact defines a rule, the other implements it; this is design, not duplication
Different contexts: The artifacts address different situations, even if they use similar language
Trivial overlap: Both mention the same concept but neither prescribes conflicting rules about it
Delegation pattern: A command invoking a skill (or vice versa) is complementary, not a gap or contradiction
Evidence requirement: The reviewer only keeps a finding when it can point to specific passages in both artifacts. No evidence from both sides, no finding.
Detection-only scope: The skeptical reviewer produces a report. It does not modify any artifact. Fixing is a separate step triggered by a human reading the report.
When to apply this pattern:
Situation
Apply?
Auditing a set of N artifacts for cross-artifact consistency
Yes
Running a doc-vs-codebase audit across many files
Yes
Code review where you want coverage, not noise
Yes
Single-agent analysis of one file
No
Connection to Swarm Mode: Swarm Mode (above) sends the same input to multiple reviewers in parallel for coverage. The Skeptical Reviewer pattern adds a synthesis layer that filters swarm output before surfacing it. They compose naturally: run the swarm, pipe its output through the skeptical reviewer.
Paul Rayner (CEO Virtual Genius, EventStorming Handbook author):
“Running 3 concurrent agent team sessions across separate terminals. Pretty impressive compared to previous multi-terminal workflows without coordination.”
Workflows used (Feb 2026):
Job search app: Design research + bug fixing
Business ops: Operating system + conference planning
Context: In February 2026, Anthropic published a COBOL modernization playbook positioning Claude Code as a direct replacement for legacy consulting teams. The same day, IBM stock dropped -13% (its worst single-day performance since October 2000). The workflow described is validated by independent research. It applies to any large legacy codebase (COBOL, Fortran, VB6, PL/I), not just COBOL.
The real cost sits in the discovery phase, not the migration itself. Original developers have retired. Documentation is absent or wrong. Code has been patched for decades by engineers who never understood the full system. Finding what talks to what requires consultants billing by the hour.
AI changes the economics by automating this exact phase.
COBOL context (for scale reference):
~220 billion lines of COBOL still in production (IBM estimate)
~95% of US ATM transactions run on COBOL-based systems (Reuters/industry consensus, methodology varies by source)
Independent validation: Academic research (WJAETS 2025) shows -25 to -30% timeline reduction on average. Best-case: Airbnb migrated 3,500 test files in 6 weeks vs. an estimated 1.5 years. COBOL→Java accuracy: 93% in controlled studies (arXiv, April 2025).
Step 1: Automated Exploration & Discovery
Map the entire codebase:
- Identify all program entry points and execution paths
- Trace subroutine calls across hundreds of files
- Document implicit dependencies via shared files, databases, and global state
- Generate a dependency graph before touching a single line
Prompt pattern:
"Read the entire [COBOL/legacy] codebase. Map its structure:
and any implicit dependencies via shared data structures,
global variables, or file I/O. Output a dependency map."
Make the discovery survive the session. Write the map to a file, not to the chat: the next session, and the next agent, should not pay for the same archaeology again. For yellow and red zones (Step 2), Addy Osmani recommends a separate read-only pass that produces a short comprehension memo (entry points, owners, callers, existing abstractions, tests, production signals, relevant history, open questions), where every claim cites a file, issue, ownership record or dashboard. The research.md phase in plan-driven.md is the same pattern for a single feature.
Step 2: Risk Analysis & Opportunity Mapping
With the dependency map in hand:
- Assess coupling levels between modules (high coupling = high risk)
- Surface isolated components as safe modernization candidates
- Identify duplicated logic and dead code
- Flag shared state as the highest-risk zones
Prompt pattern:
"Based on the dependency map: rank modules by coupling level.
Which components can be modernized in isolation?
Which share state with 3+ other modules and should be touched last?"
Turn the risk map into zones the agent cannot redraw. Addy Osmani’s Brownfield Agentic Engineering (September 2026) makes the ranking operational with three zones, each with its own permitted verbs:
Zone
What lives there
How agents work there
Green
Modern, well-tested, isolated code
Tight agent loop
Yellow
Mixed quality, partial coverage
Characterization tests first, then changes
Red
Auth, billing, permissions, payroll, code few people understand
A human pairs on every step, or the work does not happen
Three rules keep the zones from being a metaphor. A person draws the map, not the agent: left to choose, it tends to start in the scariest file. A zone only moves when it is earned: yellow becomes green once characterization tests exist and the module owner has reviewed the agent’s first changes. And the zone sets the verbs, not the agent’s confidence. Osmani’s criterion: “Autonomy should follow blast radius, observability, and recoverability. A model’s confidence is a poor guide.” A surface that only production traffic really exercises, with no honest test suite, is red by definition until something stands in for that traffic (replay, shadow traffic, synthetic journeys).
Encode the map where it is enforced, not only where it is read: a permissions.deny entry or a PreToolUse hook on red paths, path-scoped rules for yellow ones (see 7. Hooks). A zone map that lives only in a planning document is advice.
Step 3: Strategic Planning
Human + AI collaboration:
- AI suggests prioritization based on risk/dependency analysis
- Team reviews against business priorities (what breaks = most expensive)
- Define target architecture and code standards
- Design function-level tests for validation before migration begins
This phase is not fully automatable: business context requires human judgment.
Hybrid human-AI workflows show 31% higher completion rates within initial time estimates
vs. purely automated approaches (WJAETS 2025).
Step 4: Incremental Implementation
Never migrate the whole system at once:
- Translate logic component by component
- Create API wrappers for legacy components still in use
- Run old and new code side-by-side in production
- Validate each component independently before proceeding to the next
Prompt pattern:
"Translate [module X] to [target language].
Preserve exact business logic: no optimization yet.
Add a compatibility wrapper so both versions can run in parallel.
Write tests that verify identical outputs for identical inputs."
Pin today’s behavior before the agent changes it, and not with the same session. Characterization tests lock what the module does now, ugly parts included, because in an old system some of that ugly behavior is what the business runs on. If the session that will make the change also writes the tests that judge it, the green suite encodes the implementation it just invented. Write the characterization tests in a separate pass, or have a person write them, then let the agent work (see TDD with Legacy Code).
A migration unit is complete when the old path is gone. Running old and new code side by side is a transition state, not the finish line. Osmani’s definition: “A migration is complete when the new path works and the old dependency is demonstrably gone.” Half-finished migrations are particularly confusing to agents, because search returns the old pattern in forty files, the new one in twelve, and a shim presenting both as current: the agent sees contradictory precedent. Finish one route end to end, deletion included, before converting the next thirty files.
Passing tests do not prove the migration happened. SWE Refactor Bench (August 2026, 20 whole-repository migrations) names this “Blindness”: a migration starts green, so a repository handed back untouched, or a replacement that still calls the original implementation, passes the behavioral suite. Its protocol adds a migration audit (is the old stack gone from the built artifact?) and independent agents hunting for behavioral differences. Across 520 runs from 8 frontier models, 28 passed all three stages (5.4%), 13 of the 20 tasks received no accepted solution, and language rewrites scored 5.6/100 against 31.4 for build-toolchain rewrites. Track migration progress with the numbers that can move: remaining old imports, share of traffic served by the new path, parity mismatches, legacy dependencies removed.
“Years to quarters” is real, but it’s the optimistic scenario, not the average:
Scenario
Timeline reduction
Source
Conservative estimate
-25 to -30%
WJAETS 2025 academic review
Automation-heavy phases
-40 to -50%
Fullstack Labs industry synthesis
Best-case (test migration)
-88% (6 weeks vs 1.5 yr)
Airbnb case study
COBOL→Java conversion accuracy
93%
arXiv, April 2025
The average gains are real and significant. The headline numbers require favorable conditions: good test coverage, isolated modules, and a team that understands both the legacy system and the target stack.
❌ Big bang migration: Rewriting everything at once. No company has survived this at scale.
❌ No parallel run: Cutting over without a fallback. One undiscovered edge case = production outage.
❌ Skipping discovery: Starting to translate before mapping. You will break things you didn’t know existed.
❌ Trusting AI on business logic: AI translates faithfully what it reads. If the original was wrong or context-dependent, the translation will be too.
❌ Half-finished migration: Thirty files converted, a compatibility shim left behind, deletion deferred to a cleanup ticket. Agents then copy whichever pattern search returns first.
❌ Letting the agent pick where to start: Without a human-drawn zone map, agents gravitate to the most interesting code, which is usually the riskiest.
Case Study: Bun’s Zig-to-Rust Port with Claude Code
Jarred Sumner’s Rewriting Bun in Rust (July 2026) is a first-party account of a Claude Code migration at scale: 535,496 lines of Zig across 1,448 files ported in 11 days (May 3 to 14, 2026), with about 50 dynamic workflows and a peak of about 64 concurrent Claude instances on a pre-release Claude Fable 5. The author prices the run at around $165,000 at API pricing (5.9 billion uncached input tokens, 690 million output tokens, 72 billion cached input token reads). Read it as one expert operator’s report on a codebase he knows best, not as a benchmark.
What transfers is the structure around the agents, not the scale:
Practice
What Bun did
What it buys you
Rulebook before any porting
About 3 hours producing PORTING.md (Zig patterns mapped to Rust patterns), then a workflow tracing every struct field’s lifetime into LIFETIMES.tsv, reviewed by adversarial agents and read by the author
One durable set of decisions every later agent reads, instead of each one re-deriving them
Pilot before the sweep
3 files first: 1 implementer, 2 adversarial reviewers, 1 fixer, before the 1,448-file run
The rulebook gets tested on a disposable unit
Oracle outside the change
The existing, language-independent test suite (1,386,826 expect() calls, 60,624 tests on one platform, “0 tests skipped or deleted”) was the merge gate, and the author “manually verified the tests were in fact running and not being skipped”
The tests are not part of what changes, and someone checked that they ran
Separate reviewers
Every generated unit reviewed by two adversarial reviewers before commit
Agents ran git stash and git reset over each other’s work, so the workflow forbade them; agents stubbed out functions to silence compile errors, so reviews rejected workarounds that needed a paragraph-long comment
Each false start became a harness rule, not a hand-fixed diff
Evidence limits. The author states the rewrite “introduced 19 known regressions, each of which has been fixed”, and publishes no post-release defect rate. He monitored the workflows “for most of those 11 days (and after)”. This was a mechanical, behavior-preserving port against a suite that did not depend on the implementation language, the most favorable case for agents. SWE Refactor Bench measured language rewrites as the weakest migration category, so the result does not transfer to a codebase without an equivalent oracle.
Feature-to-Code Anchoring: When You’re Not Rewriting
The 4-step workflow above assumes the goal is to replace the system. Often it isn’t. A team costing a change, auditing a claimed “still active” status, or deciding what’s safe to archive on a legacy fleet needs a narrower output: a verified pointer from every documented feature to the file and symbol that actually implements it, so the next person doesn’t re-explore dozens of repositories by hand each time the question comes up.
This is a four-layer problem, and only the first layer needs building for a pure audit.
Layer
Goal
Status
0 (Deterministic anchor)
Ground each feature on a real file and symbol, verifiable by direct read (ls, git grep, LSP). No interpretation, just location.
Buildable today, see below
1 (Semantic extraction)
Understand what the anchored code does (business rules, state machines, permissions).
Candidate tool: Anthropic’s official business-rules-extractor skill (Apache-2.0, file:line-line anchoring, Given/When/Then format, High/Medium/Low confidence rating)
2 (Deterministic gate)
Mechanically reject any layer-1 rule whose anchor doesn’t resolve against layer 0, instead of just labeling it “low confidence.”
Not offered by any tool surveyed here, has to be built
3 (Standardized output)
Serve the result as versionable, queryable files.
OKF fits directly: one concept per markdown file, a resource field for the code anchor
For each feature’s documented entry point, resolve in this order and never guess silently:
LSP (workspaceSymbol, documentSymbol) on the route or file name.
git grep fallback in the local clone.
If neither resolves: mark it unresolved, with the reason. Never a silent guess.
files:
- repo: <name>
path: <path relative to repo root>
symbol: <function/handler name, if identified>
method: grep | LSP
confidence: EXTRACTED | INFERRED
commit_ref: <short hash>
resolution_status: COMPLETE | PARTIAL | NOT_FOUND
EXTRACTED means a unique, exact match. INFERRED means multiple plausible candidates, left for a human to settle. The commit hash isn’t a permanent anchor, and a line number is worse: both are freshness markers for a point in time. Derive the line on demand via git grep when you need it; never store it as a fixed identifier, because it drifts with every unrelated edit above it.
On a fleet where the resolution can’t be inferred from clean route names, expect two rounds: a first pass that grabs the obvious cases via grep, then a targeted second pass on the unresolved subset, grouped by repository rather than by feature so each agent opens a given repo once instead of re-opening it for every feature that touches it.
Three tools were evaluated hands-on against a legacy fleet that includes a non-standard, in-house framework, the exact condition that breaks framework-signature detection.
Reversa (github.com/sandeco/reversa), a multi-agent framework (scout, archaeologist, detective, architect, writer, reviewer, curator) that turns a legacy repo into specs for coding agents. Rejected for this use case: one CRITICAL path-traversal vulnerability in its uninstall path, zero automated tests across 56 releases in three months, a bus factor of one, and a confidence seal (🟢🟡🔴) that nothing mechanically verifies; its own validator is 22 lines long. File:line traceability exists for non-functional requirements and tasks, then disappears exactly at the business-rule layer, the one place it matters most, where rules are bullet points followed by an emoji. When its framework detector doesn’t recognize a custom in-house framework, it invents a module split blindly and freezes that decision as immutable after the first pass. Every downstream step inherits a guess it can no longer revise.
code-graph-mcp (github.com/sdsrss/code-graph-mcp), a Rust MCP server building an AST knowledge graph (tree-sitter, 19 languages) with call graph, hybrid semantic search, and HTTP route tracing. Clean on security. Rejected on evidence, not on youth: measured 12/12 false “inferred” edges with maximum confidence on a modern, well-supported stack (Fastify), and zero routes extracted against the custom in-house framework. A tool that answers confidently and wrong is worse than one that answers nothing.
Graphify (github.com/safishamsi/graphify, full coverage in ecosystem/third-party-tools.md, Knowledge Graph) is the strongest deterministic building block found. Its EXTRACTED tag is architecturally enforced: source code never leaves the machine for the AST pass, a claim verified both in the tool’s own source and by cross-checking the artifacts it produced, edge by edge, against the real code. When it fails to recognize a framework, it produces no edge rather than inventing a plausible-looking one, so the failure shows up as a measurable disconnected-component count instead of a silent wrong answer. It still breaks on dynamic dispatch (readdirSync-based routing, a generic exported create() factory hiding the real handler name), so full coverage on a fleet with heavy custom-framework use needs a small dedicated pass layered on top for that gap alone.
Zero invention. No path gets written without direct proof, including in instructions handed to an agent. Unresolved means unresolved, never guessed.
Independent verification before acceptance. Every claim from an agent, a path, a symbol, a commit hash, a repo’s existence, gets checked by an independent command before it lands in a deliverable. This is what catches a hallucinated claim and, just as often, what stops a false accusation of one.
Strict scope discipline. A task scoped to one field never touches another, even after it surfaces an unrelated inaccuracy elsewhere. Flag those separately; never fix them quietly.
A confidence score that isn’t mechanically verified is cosmetic, and the reverse holds too. A decorative seal and an unverified inference tag both fail the same test. A tag that’s architecturally enforced and checkable edge-by-edge against source, like Graphify’s EXTRACTED, passes it. The only valid authority is reproducible mechanical verification, never a self-declared confidence level, honest or not.
It tells you where the code is, not what it does; no business rule gets extracted this way. Coverage is bounded by whatever feature inventory seeded it, an endpoint nobody documented upstream has no reason to appear in the anchor set either. And the stored commit hash is a snapshot at a point in time, not a live guarantee: without a periodic re-verification job, this layer ages at the same rate as the code underneath it.
Reading time: 7 minutes
Skill level: Week 2+
Status: Research Preview (as of February 2026)
Availability: Pro and Max plans only, not available on Team, Enterprise, or API keys
Remote Control lets you monitor and control a local Claude Code session from a phone, tablet, or web browser, without migrating anything to the cloud. Your terminal keeps running locally; the mobile/web interface is a remote window onto that session.
Key difference from Session Teleportation (§9.16): Teleportation migrates a session (web → local). Remote Control mirrors a local session to a remote viewer. Execution always stays on your local machine.
/new, /compact, etc. are treated as plain text in the remote UI
Plans
Pro, Max, Team, Enterprise; Team/Enterprise owner must enable access. API keys and cloud-provider gateways are unsupported
Remote-interface command support depends on the surface. Use the current Remote Control reference for restrictions; an old report that all slash commands become plain text is not a current global rule.
# Pane 1: claude → run /rc → share URL with your phone
# Pane 2: claude (local only)
# Pane 3: claude (local only)
# To switch which session you're controlling remotely:
# → Go to pane 2, run /rc (disconnects pane 1's remote, connects pane 2)
Each tmux pane hosts its own Claude session. Only one can use remote-control at a time, but you can switch between sessions by running /rc in different panes.
Remote Control works on remote machines (VMs, cloud servers) running in tmux:
Terminal window
# On your cloud server (e.g., Clever Cloud, AWS, etc.):
tmuxnew-session-sclaude-server
clauderemote-control
# → Scan QR code from your phone
# → Control a cloud-hosted Claude session from mobile
# → Sessions survive laptop reboots (tmux keeps them alive)
This gives you persistent sessions that survive closing your laptop. Combine 6-8 Claude sessions in tmux for continuous uninterrupted work while traveling.
Known bug (Research Preview): use claude.ai/code in Safari instead (see below)
QR code opens app but session not visible
Known bug on iOS: scan with native camera app, open in Safari rather than Claude app
QR code not showing
Press spacebar after starting remote-control
Slash commands not working
Type them in your local terminal instead
Session expired
Reconnect: run /rc again
Corporate firewall blocking
HTTPS outbound (port 443) must be allowed
”Not available” error
Verify Pro or Max subscription (not Team/Enterprise)
Known bug (Research Preview, March 2026): On iOS (confirmed iPhone), scanning the QR code opens the Claude app but the remote session doesn’t appear in the session list. The bug also affects automatic session discovery in the Claude mobile app. MacStories confirmed this is inconsistent on non-local machines.
Most reliable workaround: open claude.ai/code in Safari on your phone. Your active session appears in the list there. Alternatively, copy the session URL from the terminal and paste it directly in Safari. Both paths bypass the app’s sync bug entirely.
See also: §9.10 Continuous Improvement Mindset: the conceptual foundation for this section. §9.23 is the operational layer: detecting when to act, and how.
As your Claude Code setup matures (skills, agents, rules, CLAUDE.md), a silent failure mode emerges: your configuration drifts away from how you actually work. Skills accumulate assumptions that no longer hold. CLAUDE.md describes a codebase that has evolved. Rules cover edge cases that became the norm. The agent keeps making the same correctable mistakes because nothing captures what you learned last week.
This section covers how to detect that drift early and close the loop: turning session observations into concrete config improvements.
Skills accumulate. Without a lifecycle policy, you end up with 20+ skills where half are unused, two contradict each other, and none have version history.
When to create a skill:
A task is worth encoding as a skill when you’ve done it manually 3+ times and the steps are stable enough to write down. If you’re still figuring out the right approach, don’t encode it yet: premature skills crystallize bad patterns.
When to update a skill (patch):
A command in the skill fails because an API or path changed
The output needs a small clarification you keep adding manually
You added a convention and the skill doesn’t reflect it yet
When to version a skill (minor/major):
Add a version field and updated date to your skill frontmatter:
---
version: 1.2.0
updated: 2026-03-02
breaking_since: null
---
Use a simple policy:
patch (x.x.Z): rewording, clarification, examples added, no behavior change
minor (x.Y.z): new instructions, extended scope, new behavior opt-in
major (X.y.z): default behavior changes, annotate what broke and when in your CHANGELOG
When to deprecate a skill:
Add a deprecated: true flag and a note explaining what replaced it. Don’t delete immediately: other skills or commands may reference it.
CI staleness check: CLAUDE.md vs source modules:
If your CLAUDE.md is assembled from source modules (e.g., via a pnpm ai:configure pipeline), add a CI job to catch divergence before it causes silent failures:
The update loop formalizes what you already do informally: something doesn’t work well → you notice → you fix it. The difference is making the “notice” step systematic rather than accidental.
┌──────────────────────────────────────────────┐
│ THE UPDATE LOOP │
│ │
│ Session → Observe friction │
│ (repeated fixes, tool fails) │
│ ↓ │
│ Analyze root cause │
│ (which skill/rule is missing?) │
│ ↓ │
│ Delta update │
│ (targeted edit, not rewrite) │
│ ↓ │
│ Canary test │
│ (verify the fix holds) │
│ ↓ │
│ Next session → repeat │
└──────────────────────────────────────────────┘
The delta update principle: when updating a skill or rule, make the smallest targeted edit that fixes the observed problem. Don’t rewrite the whole skill: you’ll lose what was working. One problem, one edit, one test.
Integrating into /tech:handoff:
If you use a handoff command to persist session context, add a mandatory retrospective step before saving:
# Append to your handoff command prompt
Before saving context, answer:
- Which rules or skills were missing for today's work?
- Which corrections did you make more than once?
- What's the smallest edit that would prevent the most repeated friction?
Save conclusions via: write_memory("retro_[date]", your answers)
Canary testing a skill after update:
Before committing a skill change, verify it still produces the expected output on a known input:
Terminal window
# Example: test that typescript-aristote skill generates Zod validation
claude-p"Using the typescript-aristote skill: create a basic user tRPC router"\
If you want to automate prompt optimization beyond the manual update loop, two frameworks apply:
DSPy (Stanford, open-source): optimizes prompts programmatically given a metric and a set of examples. Requires 20+ labeled examples per skill for reliable results. Useful when you have a well-defined task and enough session history to build a dataset. dspy.ai
TextGrad: treats prompts as differentiable parameters and iterates using LLM-generated feedback as “gradients”. Better for creative or domain-specific tasks where the evaluation is qualitative. github.com/zou-group/textgrad
Both require more setup than the manual loop above, and neither eliminates the need for human judgment on what to optimize. Start with the update loop and canary tests: they’ll surface most of the value with a fraction of the overhead.
Relationship to §9.23: The Update Loop handles deliberate config maintenance: you notice drift, you fix it. Instinct-based learning handles incidental capture: useful observations you’d otherwise forget by end of session.
Standard session-end prompts (“what did you learn this session?”) produce verbose summaries that rarely get acted on. The friction between “observation” and “encoded rule” is high enough that most corrections never make it back into your config.
What actually gets encoded: corrections you make twice, then a third time, until the repetition forces you to write a rule. That’s too slow, and it only captures the painful patterns, not the useful ones.
Instincts are lightweight, low-commitment observations: candidate rules that haven’t been validated yet. They sit below skills (stable, tested, promoted) and below memory (project context, decisions):
Session observation
↓
Instinct (low confidence, 0.1–0.4)
↓ confirmed across multiple sessions
Candidate rule (medium confidence, 0.5–0.7)
↓ tested explicitly
Skill or CLAUDE.md rule (high confidence, 0.8+)
Each instinct tracks: content (the observation), confidence (0.0–1.0, starts low and grows with confirmation), source (which session/context), and decay (confidence drops if not confirmed over time).
The key design choice: capture at the Stop hook, not at UserPromptSubmit.
Why Stop, not UserPromptSubmit: UserPromptSubmit runs before every message: adding extraction logic there adds latency to every interaction. Stop runs once when the session ends: zero impact on session speed, and the full session context is available for pattern extraction.
.claude/hooks/capture-instincts.sh
#!/bin/bash
# Stop hook: extract candidate observations from the completed session
The promotion step stays manual by design: you decide what gets encoded. The pipeline reduces the friction of capturing observations, not the friction of validating them.
Add capture-instincts.sh as a Stop hook in settings.json
Review weekly (5 minutes maximum)
Promote 0–2 high-confidence instincts per week; delete the rest
What not to capture: project-specific context (use memory), patterns you’re already confident in (write the skill directly), one-off workarounds (let them go).
Credit: Instinct-based learning pipeline and the Stop hook capture pattern from Everything Claude Code v2 (Affaan Mustafa). The confidence scoring, decay model, and instinct → skill evolution pipeline are their original contribution.
Structural inventory, execution and acceptance need different evidence. A synthetic Walkinglabs fixture scored 100/100 while its verification failed; see the pinned evaluation. The local control exercise tests verdict handling, durable budgets and response loss against a simulated service. It does not prove a live merge gate. Use Agent Harness Engineering, Loop & Graph Engineering and Agent Evaluation for the full contracts and comparison method.
Reading time: 10 minutes
Skill level: Month 2+
The core insight: evaluate model capability together with the infrastructure that governs execution. A fixed model can behave differently when its context, tools or checks change; the effect depends on the task and budget. In this section, the repository harness is the project environment a runtime such as Claude Code operates inside.
The vocabulary is deliberately layered: the model generates text; the runtime harness runs its tool loop, context, permissions, and sessions; this repository harness supplies project instructions, setup, state, and feedback; an orchestrator coordinates multiple runtime sessions. See Agent Harness Engineering for the full distinction and the Agent Harness Landscape for the product landscape.
The repository harness is everything in the engineering environment around the agent: the instruction files, initialization scripts, state tracking, verification commands, and feedback loops. It is not a prompt file and not a list of guidelines. It is the workbench the runtime operates inside.
Five subsystems make up a complete harness:
Subsystem
Purpose
Core artifacts
Instructions
Defines what the agent should do and how to behave
AGENTS.md, CLAUDE.md
Tools
Shell access, file editing, command execution
Native Claude Code tools
Environment
Dependencies, versions, reproducible baseline
init.sh, lockfiles, devcontainers
State
Tracks scope and progress across sessions
feature_list.json, progress.md
Feedback
Signals whether work is correct before declaring done
Tests, lint, typecheck, E2E
The most common failure modes map directly to missing subsystems. Agents that forget context between sessions are missing State. Agents that redo completed work are missing State. Agents that declare done before tests pass are missing Feedback.
An agent can announce “done” while tests fail, types are broken or the build does not compile. The harness needs a completion boundary that checks execution evidence independently of that announcement. A model’s confidence cannot establish that a command ran on the candidate revision.
Define checks appropriate to the repository. For a web application, the following illustrates three layers; use the project’s actual commands and acceptance criteria:
Terminal window
# Layer 1: Static analysis
npmrunlint && npmruntypecheck
# Layer 2: Unit and integration tests
npmtest
# Layer 3: End-to-end smoke test
npmrune2e
Document the contract in CLAUDE.md so the agent knows what evidence to produce:
## Definition of done
A feature is NOT done until all three layers pass:
1.`npm run lint && npm run typecheck` — clean
2.`npm test` — all tests pass
3.`npm run e2e` — smoke test passes
Do NOT commit or report completion before running all three.
The instruction describes expected behavior. Enforcement requires a controller or required CI check that blocks the relevant completion or merge transition when a required result is failing, missing, stale or uninterpretable. Bind the result to the candidate revision and keep policy outside the change being judged. A local hook covers only the actions and clients it actually intercepts.
Test both decisions: a failing required check must block the transition, and a valid candidate with complete evidence must pass that policy step. Also exercise missing output and a result from an earlier revision. A policy that rejects everything can pass a negative-only test suite.
End-to-end checks can expose navigation, configuration and integration failures absent from unit coverage. Anthropic’s long-running agent account describes using browser checks after agents prematurely marked features complete. Treat that as a reported implementation experience, then retain your own reproducible scenario and result.
When multiple features are in progress simultaneously, verification becomes ambiguous (which feature broke the tests?), progress tracking becomes noisy, and context fills faster with no clear completion signal. The agent distributes attention across the full task list instead of closing one thing.
For a sequential feature workflow, WIP=1 is a useful starting policy: one feature enters active, completes its required checks and records its result before another starts. A controller must validate that transition if exclusivity matters. Measure completion and recovery locally; this guide does not establish a universal improvement rate from that policy.
A reliable session follows this sequence every time, not just at startup:
Step
Action
Subsystem
1. READ
Read AGENTS.md and CLAUDE.md
Instructions
2. INIT
Run ./init.sh: verify environment is healthy
Environment
3. RESUME
Read progress.md: what happened last session
State
4. SELECT
Pick one feature with not_started status from feature_list.json
State
5. EXECUTE
Implement only that feature
—
6. VERIFY
Run all three verification layers
Feedback
7. UPDATE
Set feature status to passing, record evidence
State
8. LOG
Update progress.md with what changed and what’s next
State
9. CLEANUP
Remove temp files, leave repo in restartable state
Environment
10. COMMIT
Commit only when verification passes and state is clean
—
Steps 2 (INIT) and 6 (VERIFY) are where most harness failures occur. INIT that silently continues past broken dependencies produces confusing errors for the rest of the session. VERIFY that runs but doesn’t block completion produces false positives that erode trust in the agent’s output.
A plain text task list is insufficient for reliable agent operation: no machine-readable state, no evidence field, no dependency ordering. feature_list.json adds structure that both the agent and your tooling can read.
Each feature needs three things: a description of the expected behavior, the verification command that proves it works, and a status field the agent updates throughout the session.
{
"features": [
{
"id": "feat-001",
"name": "Document Import",
"description": "User can import PDF and TXT files from the local filesystem",
"description": "Imported documents split into ~500-char chunks with position metadata",
"dependencies": ["feat-001"],
"status": "active",
"evidence": ""
},
{
"id": "feat-003",
"name": "Search Index",
"description": "Full-text search across all imported documents",
"dependencies": ["feat-002"],
"status": "not_started",
"evidence": ""
}
]
}
Status values follow a one-way flow: not_started → active → passing (or blocked if a dependency is unresolvable). The evidence field is the highest-signal part of the schema: it records what verification actually ran, not just that the code was written. An empty evidence field on a passing feature is a red flag.
Every session starts from an unknown environment state. Dependencies may have changed, build artifacts may be stale, or types may be broken from a previous incomplete session. init.sh establishes a known-good baseline before any work begins.
#!/bin/bash
set-e# Fail fast on any error
echo"=== Initialization ==="
npminstall
npmrunbuild
npmruntypecheck
npmtest
echo"=== Environment ready ==="
echo"Next: read feature_list.json and pick one not_started feature"
set -e is non-negotiable. If install fails, the script stops. An agent that proceeds past a broken environment produces confusing errors for the rest of the session, and the root cause becomes difficult to isolate. Run it idempotently: calling it five times should produce the same result as calling it once.
Context windows are finite. Every session that ends without a handoff note forces the next session to reconstruct context from scratch: reading git log, grepping for recent changes, inferring what was in progress. This reconstruction is expensive and imprecise, and it’s where subtle errors get introduced.
progress.md eliminates the reconstruction cost. It’s a short, structured note written at the end of every session, read at the start of the next.
# Session progress
## Last updated
2026-05-04 — Session 7
## Active feature
feat-002: Document Chunking
## Done this session
- [x] Implemented chunk() function in src/services/chunker.ts
- [x] Added position metadata (start_char, end_char, chunk_index)
- [x] Unit tests pass (8/8)
## In progress
- [ ] Chunker integration with DocumentService
- Status: function exists, wiring not complete
- Blocker: none
## Next steps
1. Wire chunker into DocumentService.import()
2. Add integration test covering full import-to-chunk flow
3. Update feat-002 status to passing once integration test passes
## Evidence
- lint: clean
- typecheck: clean
- unit tests: 8/8 pass
- integration tests: not yet (feat-002 not complete)
## Notes for next session
chunk() is in src/services/chunker.ts:42. DocumentService expects a
ChunkResult[] type (defined in src/types/documents.ts:18). The wiring
point is DocumentService.import() at line 67.
The “Notes for Next Session” section is the highest-ROI part: concrete file paths, line numbers, and specific wiring points that save 5-10 minutes of orientation at session start. Treat it as a message to a colleague who knows the codebase but has no memory of what happened today.
The most common failure pattern with instruction files: they start small and accumulate. Every team adds rules, guidelines, conventions, and exceptions. After three months the file is 800 lines. The agent reads all 800 lines every session, consuming context budget before any work starts. Rules that appear 600 lines in are effectively invisible. The file cannot be linted. Contradictions accumulate silently.
The failure mode is structural, not a content quality problem. A long AGENTS.md will degrade regardless of how carefully each rule is written.
The OpenAI Codex team’s approach: keep AGENTS.md to approximately 100 lines and make it a map, not a manual. The file tells the agent where to look, not everything it needs to know.
AGENTS.md
## Architecture
See docs/DESIGN.md for system architecture.
See docs/design-docs/core-beliefs.md for foundational decisions.
Taste invariants (enforced by linters): docs/RELIABILITY.md, docs/SECURITY.md
Frontend conventions: docs/FRONTEND.md
## External libraries
LLM-ready docs for external dependencies: docs/references/
Example: docs/references/nixpacks-llms.txt
## Verification
Before marking done: run `make verify` (lint + typecheck + tests + e2e).
Definition of Done: all layers pass, no skips.
The docs/ hierarchy does the heavy lifting. The agent reads only what it needs for the current task: the product spec for the feature it is implementing, the exec plan for the task it is executing, the reliability doc when touching infrastructure. Progressive disclosure through the file system.
CI enforcement: the knowledge base must be maintained like code. Linters check that docs/ references in AGENTS.md resolve, that exec plans in active/ are not stale, and that QUALITY_SCORE.md reflects the last cleanup run. A broken link in AGENTS.md is a build failure, not a documentation oversight.
An agent works from information in its context and sources it can actually discover and read through authorized tools. The repository is an important owner of stable contracts, but organizational knowledge and live operational state may belong elsewhere. A configured connector does not prove that a source was retrieved, is current, or is appropriate for the task.
Keep each kind of truth with its owner and provide a retrieval route:
For example, preserve a durable architecture decision in docs/decisions/ and link it from the issue that prompted it. Query current deployment health from its operational owner rather than presenting an old Markdown snapshot as current truth. Copying a source into the repo creates another surface to maintain and requires appropriate persistence and audience permissions.
When review changes a durable decision, update its authoritative record and retrieval route before the next session needs it. When a task changes, update its contract. Make missing or stale evidence explicit rather than assuming that a new engineer or agent can infer it.
A structured docs/ hierarchy makes repository-owned context discoverable. It can also route the agent to authorized external owners when the required information belongs elsewhere.
│ └── db-schema.md # Auto-generated from actual schema (never edited by hand)
├── product-specs/
│ └── index.md # One spec per feature
├── references/
│ └── nixpacks-llms.txt # LLM-ready docs for each external library
├── DESIGN.md # System architecture overview
├── FRONTEND.md # Frontend conventions
├── PLANS.md # Current planning status
├── PRODUCT_SENSE.md # Product judgment and principles
├── QUALITY_SCORE.md # Quality scores per domain/layer
├── RELIABILITY.md # Reliability requirements and taste invariants
└── SECURITY.md # Security requirements and patterns
Exec plans as first-class artifacts: for any non-trivial task, the agent creates a plan document before writing code. Simple changes get ephemeral plans: a short markdown file with the approach and expected outcome, created at the start of the task and moved to completed/ when done. Complex tasks get full exec plans with progress logs, decision records, and explicit notes on alternatives rejected. The separation of active/ and completed/ keeps the agent’s attention on current work while preserving a searchable history of past decisions. The tech-debt-tracker.md is the backlog for known quality issues; the background cleanup agents described in §9.25.5 populate it and address issues incrementally rather than through a disruptive periodic cleanup.
generated/ directory: certain documentation must track code exactly. Database schemas, API surface areas, generated type definitions. These go in generated/ and are produced by automated scripts, not written by hand. The doc-gardening agent (described below) enforces the invariant that generated/ files match the actual runtime state.
The doc-gardening agent: a recurring background agent that reads docs/ and compares documentation claims against actual code behavior. When it detects drift (a documented API that has changed signature, or a design record that contradicts current implementation), it opens a PR to fix the documentation. This treats the knowledge base as code: it has correctness requirements, and those requirements are enforced automatically. Without this agent, the knowledge base degrades as the codebase evolves. With it, the degradation is caught and corrected continuously rather than discovered when an agent acts on stale information.
references/ for external libraries: each significant external dependency gets a dedicated file in references/ (the library’s official llms.txt if available, or a curated summary of the relevant API surface). The agent reads the relevant reference file when implementing against that library rather than relying on its training data, which may be outdated or incomplete.
The verification stack in §9.25 (lint, typecheck, tests, e2e) covers correctness. A separate layer covers performance and runtime behavior: observability. Without it, the agent cannot answer whether a change meets performance requirements and can only inspect code and guess.
The OpenAI Codex team gave each git worktree its own ephemeral, isolated observability stack. The stack is created at task start and torn down after completion; it is never committed to the repository.
Data pipeline: app logs/metrics/traces → Vector (collector/router)
↓
Storage layer: VictoriaLogs (logs) VictoriaMetrics (metrics) trace store (traces)
↓
Query APIs: LogQL PromQL TraceQL
↓
Agent access: curl / CLI tools → structured data in agent context
The stack enables metric-based prompts that were previously impossible. Instead of “implement service startup,” the prompt becomes “ensure service startup completes in under 800ms.” Instead of “optimize the checkout flow,” it becomes “no UI journey through checkout should exceed 2 seconds.” The agent implements a change, restarts the application, runs the workload, queries the observability stack, reads the result, and iterates. The feedback loop is closed without human measurement.
This approach requires infrastructure that not every team has available. The pattern illustrates the direction: as harness investment increases, the agent can take on work that was previously impossible to delegate because verification required human judgment on runtime behavior. Teams without this stack can approximate it by making performance requirements explicit (run this benchmark before and after, compare output) and scripting the measurement, even if the infrastructure is not as complete.
Existing code supplies examples for later changes. Inconsistent patterns and unfinished migrations can leave competing precedents for an agent to follow. This motivates canonical examples and executable constraints where appropriate; it does not establish a fixed propagation rate or require the same architecture in every project.
Functional requirements alone leave choices about compatibility, accessibility, maintainability, and acceptable risk unresolved. Give each requirement an authoritative owner, an accessible representation, and evidence suited to the claim:
Local requirement
Authoritative owner
Representation
Evidence
Support a declared input format
Boundary schema or parser
Typed value and canonical example
Valid, malformed, and compatibility fixtures
Preserve keyboard access
Product accessibility requirement
Component example and interaction contract
Keyboard behavior checks and relevant human review
Keep generated versions aligned
Version manifest
Derived discovery files
Equality check plus navigation checks
Respect a latency budget
Service requirement
Benchmark procedure and workload
Measured result under declared conditions
One concept can have multiple derived representations without multiple competing definitions. Parse uncertain input at its boundary, then pass the validated representation to consumers. When migrating a pattern, repair the scoped existing population and add a check that prevents new violations. Once ownership removes the need for downstream duplicate checks, evaluate retiring those checks rather than stacking more controls indefinitely.
Adapted from Lopopolo’s domain-modeling synthesis. These are design practices to evaluate, not measured productivity gains. The following OpenAI architecture is one reported implementation.
Layered domain architecture
The OpenAI Codex team enforced a fixed layer order within each business domain:
Types → Config → Repo → Service → Runtime → UI
Each layer may depend only on layers below it. Cross-cutting concerns (auth, connectors, telemetry, feature flags) are available only through explicit Provider interfaces, not by importing directly. Violations are build failures enforced by custom linters and structural tests.
Choose dependency boundaries that fit the domain, then test the violations that matter. The reported layer order is an example, not a prerequisite for every agent-assisted project.
Taste invariants and custom linters
Taste invariants are opinionated rules that go beyond style. Examples: “prefer shared utility packages over ad-hoc helpers,” “validate at boundaries or use typed SDKs,” “use structured logging in all service-layer code,” “schemas and types follow the naming convention X.” These rules are not written as guidelines; they are encoded as custom linters.
The linter error messages are written specifically for agent consumption, not for human developers. A conventional linter message says what is wrong. A taste-invariant linter message says what is wrong and what to do instead, written in a form the agent can act on:
TASTE-003: Untyped API response found in services/payment.ts:47
Prefer typed SDK responses. Use PaymentClient from @internal/payment-sdk
instead of direct fetch(). See docs/RELIABILITY.md#api-boundaries for the pattern.
The error message injects the fix instruction directly into the agent’s context window. Once encoded, the rule applies instantly to every file in the codebase, including files the agent has never seen. This is the amplifier effect: one linter rule enforces consistent behavior across the entire project with zero additional per-file effort.
The custom linters were themselves generated by the Codex agents, not written by hand. A human describes the rule in plain language; the agent generates the linter implementation. This compounds the amplifier: taste invariants are cheap to create, so more of them get created, so more of the codebase behavior is enforced rather than documented.
Anti-entropy via background cleanup agents
The problem with architectural drift: it is incremental and invisible until it compounds. An agent replicates a slightly imperfect pattern. Another agent extends it. A third adds a dependency that should not exist. Three months in, the codebase has structural problems that are expensive to reverse, and no single change introduced them.
The OpenAI Codex team’s approach was to treat anti-entropy like garbage collection: continuous incremental cleanup rather than periodic disruptive rewrites. A team of background agents runs on a recurring schedule:
Scan for deviations from taste principles and architectural layer rules
Update QUALITY_SCORE.md with current scores per domain and layer
Open targeted refactor PRs for detected violations
The PRs are scoped to be reviewable in under a minute and auto-merged when they pass verification. Each addresses one deviation, not a broad refactor. The cumulative effect is that tech debt is paid down continuously rather than in a disruptive periodic cleanup. The tech-debt-tracker.md in docs/exec-plans/ records known issues, and the background agents work through them incrementally.
QUALITY_SCORE.md tracks health over time per architectural layer and business domain. A quality score that is declining is a signal before the decline becomes a problem.
High-throughput merge philosophy
At 3.5 PRs per engineer per day, conventional merge gates become the bottleneck. A PR that waits two hours for a flaky CI run is a two-hour delay in a workflow that produces multiple PRs per hour. The OpenAI team’s approach: minimal merge blocks, fixes applied via follow-up runs rather than blocking merges.
The reasoning: at genuine agent throughput levels, a broken test is fixed faster by a follow-up agent run than by blocking the current PR. “Fixes are cheap; waiting is expensive” inverts the usual risk calculus that is correct at human development throughput.
This philosophy only applies when throughput is genuinely high. At normal development throughput, blocking merges on failing tests is correct: the cost of a merge block is low, and the cost of merging broken code is high. The inversion happens only when the agent can produce a fix faster than a human can review and unblock the PR. Applying this philosophy prematurely, without the throughput to support it, produces a codebase with accumulated failures rather than one with efficient flow.
Sources: Session lifecycle, Verification Gap, WIP=1, feature_list.json, init.sh, and progress.md patterns are presented here as guide recommendations. The earlier attribution to “Learn Harness Engineering” (HumanLayer, 2026) could not be verified. AGENTS.md-as-TOC, knowledge boundary principle, exec plans, docs/ structure, ephemeral observability stack, taste invariants, doc-gardening agent, anti-entropy model, layered domain architecture, and high-throughput merge philosophy from “Harness engineering: exploiting Codex in the agent era,” Ryan Lopopolo, OpenAI Engineering blog, Feb 11, 2026 (https://openai.com/index/harness-engineering/).
Relationship to §9.24: Instinct-based learning captures observations passively from session logs. Review-driven optimization captures structured human corrections actively (what you explicitly marked wrong during a review cycle). Both feed the same destination (CLAUDE.md and .claude/rules/), from different signal sources.
When you finish a Claude Code session and ask “what should I add to CLAUDE.md?”, you’re working from memory. You remember the frustrating moments, but you lose the specifics: which file, which line, what the agent produced versus what you wanted. The gap between observation and encoded rule stays wide.
Review-driven optimization changes the capture point. Instead of extracting lessons at session end, you extract them from the structured feedback you left during the review: inline comments attached to specific lines, on specific files, at specific points in the agent’s output. The signal is richer and already scoped to a location.
The round-to-round diff (delta between agent iterations, not between commits) is the verification step: it tells you whether the agent actually applied your correction, or just acknowledged it. If round 2 still contains the same issue you flagged in round 1, that is a strong signal the rule needs to be explicit in CLAUDE.md, since the agent can’t infer it from context alone.
crit is a local review interface built for this loop. It provides inline commenting on git diffs, markdown/plan files, and live web apps, with native Claude Code integration:
Terminal window
brewinstallcrit
critinstallclaude-code# writes config snippets for the project
Basic review flow:
Terminal window
# After Claude Code produces a diff or plan:
crit# auto-detects uncommitted changes
critplan.md# review a plan before Claude executes it
# After Claude iterates (round 2):
crit# shows round-to-round diff alongside your comments
The programmatic comment API lets you annotate from the CLI, useful when scripting the extraction step:
Terminal window
critcommentsrc/file.go:42"wrong approach, see rule X"
After a review session, dump the accumulated comments and look for recurrence across files and sessions:
Terminal window
# Extract rule candidates from recent crit threads
cat.crit/threads/*.json|claude--print"
Analyze these review comments.
Identify patterns that recur across multiple locations or sessions.
For each pattern, draft a one-line rule for CLAUDE.md that would prevent the issue.
Format:
- pattern: <what kept appearing>
rule: <the CLAUDE.md rule that prevents it>
confidence: <low|medium|high>
Only include patterns with 2+ occurrences. Skip one-off corrections."
The confidence field matters. A pattern that appeared twice across two sessions might be coincidence; one that appeared five times across different files and different days is a systematic gap in your context.
The extraction produces candidates. The promotion stays manual:
Pattern type
Action
Recurs 4+ times, same type of mistake
Promote to CLAUDE.md rule immediately
Recurs 2-3 times, related to a specific file type
Add to .claude/rules/ scoped rule
Appeared once, highly specific
Discard: one-off correction, not a pattern
Appeared once, high cost if repeated
Add to .claude/rules/ with a note
The rule should encode the constraint, not the correction. “Don’t use em dashes in prose files” is a good rule. “Fix the em dash on line 47 of guide.md” is not.
The diff between rounds 1 and 2 answers a different question than the comments themselves. Comments tell you what was wrong. The diff tells you whether the agent understood the correction and applied it correctly.
If you flagged an issue in round 1 and the diff shows it was addressed, that correction may not need a rule: the agent understood and adapted. If you flagged the same issue and the diff shows no change (or a partial change), that pattern belongs in CLAUDE.md. The agent cannot reliably infer it from prompt context alone.
This is the verification step that distinguishes review-driven optimization from pure instinct capture. You’re not just observing, you’re testing whether an explicit instruction was sufficient, and encoding it as a permanent rule when it wasn’t.
Run a review cycle after any multi-iteration Claude Code session
After 3-5 sessions, dump comment threads and run the extraction prompt above
Promote 0-2 rules per week to CLAUDE.md or .claude/rules/
Discard the rest: candidate rules that didn’t reach threshold have already served their purpose
The compounding effect: each rule added from review feedback removes a class of corrections from future sessions. After a few months, the review comments shift from “you did X wrong” to “this is a design question,” which signals that the mechanical patterns are covered and the remaining gaps require judgment.
Tool: crit by tomasz-tomczyk, MIT, active maintenance, native crit install claude-code support.
Two Claude Code sessions do not need to have spawned each other to talk. ListAgents discovers which sessions Claude can reach; SendMessage delivers a short text message to one of them by name. Two sessions running in parallel on the same machine, on different repositories or the same one, see each other automatically, with nothing to configure.
This is distinct from Agent Teams (§9.20): a team lead spawns and supervises its own teammates, with task assignment and synthesis. Cross-session messaging targets sessions that already exist independently, that a human started and steers, and simply cuts the copy-paste out of relaying information between them.
Run /list-agents (alias /peers) to see what a session can reach: subagents, agent-team teammates, other local sessions on this machine, cloud sessions, and Remote Control sessions on other machines. Claude then addresses a message by name, either on its own initiative (after a change that affects another session’s work) or because you asked:
Ask the session running in my other terminal whether the migration finished
Or name the target directly with an @-mention, the same mechanism used for subagents (v2.1.232+):
Let @api-worker know the schema migration finished
Whether the message ever leaves the machine depends on where the target runs: same-machine delivery goes over a local Unix socket or named pipe and never touches Anthropic’s servers; a session on another of your machines or on the web is reached through Anthropic servers via the Remote Control connection.
A message from a peer session carries information, never authority. Claude Code tells the receiving Claude explicitly that the text came from another session, not from the user, and constrains it: it cannot approve a pending permission prompt, it cannot change CLAUDE.md or any other configuration, and a command embedded in the message’s text arrives as plain text rather than something that runs. If acting on the message needs a permission the receiving session doesn’t already have, the normal prompt fires, exactly as it would for anything else.
Each session controls what it accepts from peers via crossSessionInbound (accept / hold / refuse, configurable in /config), and isolatePeerMachines: true forces explicit approval before any message leaves the current machine at all, even in bypassPermissions mode.
Coordinate sessions you already have open and steer yourself: hand a finding from one worktree to a sibling worktree, tell the backend session when the database migration finished, push a documentation session the answer that just unblocked the frontend one. No TeamCreate, no team lead, no shared task list, just two (or more) independent sessions cutting the human out of the relay.
Reading time: 3 minutes (overview) | Full guide → (~12 min, sources, boundaries, and Codex workflow)
Skill level: Advanced
Claude Code offers several ways to observe an event, but none turn incoming text into authority: Monitor command source (v2.1.98+), native WebSocket source (v2.1.195+), plugin monitors (v2.1.105+), and MCP Channels (v2.1.80+, research preview). Routines run as separate sessions on Anthropic-managed cloud infrastructure or an organization’s self-hosted environment, triggered by schedules, APIs, or GitHub events.
The safe shape is narrow and deliberate: verify the GitHub webhook signature, repository, event type, schema, and delivery ID; relay only typed metadata over an approved WebSocket; classify with read-only codex exec; then require an explicit human or policy gate before a separate isolated task can use --sandbox workspace-write. Raw comments, issue bodies, logs, and WebSocket frames remain data, never instructions or permission grants.
Full reference: Monitor, Channels and Safe Delegation to Codex covers Monitor input limits, plugin and Channel trust boundaries, GitHub delivery handling, and a split-job openai/codex-action@v1 pattern for GitHub Actions.