Skip to content

Instantly share code, notes, and snippets.

@senrecep
Last active August 18, 2026 09:27
Show Gist options
  • Select an option

  • Save senrecep/98d3583717581a4138bac62344261f6f to your computer and use it in GitHub Desktop.

Select an option

Save senrecep/98d3583717581a4138bac62344261f6f to your computer and use it in GitHub Desktop.
AI-driven setup and migration guide for Claude Code ↔ OpenCode with auto-install, skills, MCP servers, and bidirectional sync

AI Code Assistant Ecosystem Setup

AI-driven setup and optimization guide for Claude Code, OpenCode, and cross-platform tools

Quick Start: Share this gist and say:

Read this gist and set up my project: https://gist.github.com/senrecep/98d3583717581a4138bac62344261f6f

AI-First Approach

You (AI) are the orchestrator. Don't just run scripts - read the playbook, understand the principles, execute each step, ask questions, handle errors, and adapt to the user's environment.

When User Shares This Gist

Step 1: Read ai-playbook.md first - this contains the principles that guide everything else.

Step 2: Ask about their current status

Question: "What AI coding tool are you currently using?"

  • None (fresh start)
  • Claude Code only
  • OpenCode only
  • Both Claude Code and OpenCode

Step 3: Based on answer, determine setup level

Current Status AI Action
None Ask: "Which tool do you want?" -> Load appropriate setup guide
Claude Code Ask: "What level are you at?" -> Route to appropriate level
OpenCode Ask: "Want to add Claude Code or stay with OpenCode?"
Both Load sync from migration-guide.md

Step 4: Determine experience level

Level Target Files
Essentials Everyone - core setup claude-setup-essentials.md
Intermediate Ready for agents + multi-agent claude-setup-intermediate.md
Advanced Cross-model, self-learning, PR pipeline claude-setup-advanced.md

Step 5: Execute the chosen path step-by-step, applying principles from ai-playbook.md

Files in This Gist

File Purpose Level AI Usage
README.md Entry point and decision tree - You're reading it now
ai-playbook.md Principles and actionable rules (AI-only) - Read FIRST, apply throughout
claude-setup-essentials.md CLAUDE.md, context, hooks, rules Level 1 Core setup for all users
claude-setup-intermediate.md Agents, multi-agent, model routing, skills Level 2 After Level 1 is complete
claude-setup-advanced.md Cross-model, self-learning, PR pipeline Level 3 After Level 2 is complete
opencode-ecosystem-setup.md Full OpenCode setup All For OpenCode users
migration-guide.md Claude Code <-> OpenCode migration - For users switching or using both
frameworks-guide.md GSD-2, OMC, Pi recommendations Bonus Optional but highly effective

Setup Paths

Path 1: New Claude Code User

  1. Read ai-playbook.md (principles)
  2. Ask: "Does this folder contain source code?"
    • Yes -> Existing project path
    • No -> New project path
  3. Execute claude-setup-essentials.md (Level 1)
  4. When ready, proceed to Level 2, then Level 3
  5. Optionally explore frameworks-guide.md

Path 2: Existing Claude Code User (Optimization)

  1. Read ai-playbook.md (principles)
  2. Assess current setup against Level 1 checklist
  3. Fill gaps, then proceed to Level 2/3
  4. Optionally explore frameworks-guide.md

Path 3: New OpenCode User

  1. Read ai-playbook.md (principles apply to all tools)
  2. Execute opencode-ecosystem-setup.md
  3. Optionally explore frameworks-guide.md

Path 4: Migration (Claude Code <-> OpenCode)

  1. Load migration-guide.md
  2. Execute chosen direction
  3. Verify sync

Path 5: Using Both Tools

  1. Load migration-guide.md -> "Using Both Tools" section
  2. Execute sync commands
  3. Verify

Documentation

Tool Docs
Claude Code https://code.claude.com/docs/en/overview
OpenCode https://opencode.ai/docs
GSD-2 https://github.com/gsd-build/gsd-2
oh-my-claudecode https://github.com/yeachan-heo/oh-my-claudecode
Pi https://github.com/badlogic/pi-mono
Speckit https://github.com/github/spec-kit

Version: 7.0.0 (Article-Enriched) Last Updated: 2026-03-16 Author: @senrecep

AI-Powered Development Playbook

THIS FILE IS FOR AI CODING ASSISTANTS ONLY. It is not meant for humans to read. It is a playbook that AI coding assistants (Claude Code, OpenCode, Pi, etc.) read and execute when setting up and working on a user's project. Every section contains direct, actionable instructions.

Source: "Stop Writing Code, Start Managing Systems" by Recep Sen


Table of Contents

  1. CLAUDE.md Principles
  2. Context Window Management
  3. Hooks System
  4. Plan-Execute-Verify Loop
  5. Deep Research Workflow
  6. Model Routing Strategy
  7. Custom Agents
  8. Multi-Agent Work
  9. Skills Strategy
  10. Cross-Model Orchestration
  11. Self-Learning Systems
  12. Testing, Security, Performance
  13. Voice Input and Smart Context
  14. Do's and Don'ts
  15. Project Lifecycle

1. CLAUDE.md Principles

The CLAUDE.md file is the project's strategic brain. It is auto-loaded in every session and is the single most important file for AI-assisted development.

1.1 WHAT / WHY / HOW Structure

Every CLAUDE.md must have three sections:

  • WHAT: What is this project? Tech stack, architecture, core concepts. One paragraph.
  • WHY: Why were these decisions made? This is critical. When the AI knows the "why," it makes better edge-case decisions. Instead of "don't use console.log," write "don't use console.log because it causes performance issues in production and can leak sensitive data."
  • HOW: How do we work? Commands, test patterns, naming conventions.

AI Action: When creating or reviewing a CLAUDE.md, enforce this three-section structure. If a section is missing, add it. If "WHY" is absent, ask the user for the reasoning behind key decisions.

Example structure:

# Project Name

## WHAT
E-commerce API built with Node.js + TypeScript + PostgreSQL. Clean Architecture
with domain/application/infrastructure layers.

## WHY
- TypeScript over JavaScript: type safety prevents runtime errors in payment flows
- PostgreSQL over MongoDB: relational data with strong consistency for financial records
- Clean Architecture: swap infrastructure without touching business logic

## HOW
- Build: `npm run build`
- Test: `npm test` (unit), `npm run test:e2e` (integration)
- Lint: `npm run lint`
- Naming: camelCase for variables, PascalCase for types, kebab-case for files

1.2 The 100-Line Rule

  • Keep CLAUDE.md under 100 lines (ideally 70-100)
  • Move details to separate files using progressive disclosure
  • CLAUDE.md is auto-loaded in every session; every extra token is a recurring cost
CLAUDE.md (70-100 lines)              <-- Always loaded
.claude/rules/architecture.md         <-- Loaded when relevant
.claude/rules/security.md             <-- Loaded when relevant
.claude/rules/testing.md              <-- Loaded when relevant
docs/claude/patterns.md               <-- Loaded when relevant

AI Action: If the CLAUDE.md exceeds 100 lines, refactor it:

  1. Identify detail-heavy sections (architecture rules, security policies, testing patterns)
  2. Move each to .claude/rules/<topic>.md
  3. Keep only summaries and commands in the main CLAUDE.md

1.3 The "Don't" Section

Always include a "Don't" section. AI coding assistants have known tendencies that must be explicitly countered:

  • Over-engineering: Extra abstractions, unnecessary interfaces, premature generalization
  • File proliferation: Splitting things that belong in a single file
  • Phantom error handling: Adding error handling for impossible scenarios
  • Unsolicited documentation: Adding docstrings, comments, and README updates when not asked
  • Stub files: Creating files filled with return null, return {}, TODO, console.log placeholders -- file existence does not equal real implementation

AI Action: When writing code, check yourself against these tendencies. Before creating a new file, ask: "Can this be part of an existing file?" Before adding an abstraction, ask: "Is this needed now or is it premature?"

Example "Don't" section:

## Don't
- Don't over-engineer. No extra abstractions or interfaces unless explicitly needed.
- Don't create unnecessary files. If it can live in one file, keep it in one file.
- Don't add error handling for impossible scenarios.
- Don't add docstrings or comments unless asked.
- Don't create stub/placeholder files. Every file must contain real implementation.
- Don't use `any` type in TypeScript.
- Don't leave `console.log` in production code.

1.4 3-Layer Boundary Setting

Define three explicit boundary layers that tell the AI where it can move freely, where it must ask, and where it must never go:

Layer Description Examples
Always do Safe actions, execute without asking Write tests, run tests, follow naming conventions
Ask first Potentially impactful, get approval Database migrations, adding dependencies, large refactoring
Never do Hard prohibitions, never execute Commit secrets, edit lock files, delete tests, force-push

AI Action: Respect these layers strictly. If a CLAUDE.md defines them, follow them exactly. If not defined, apply the defaults above and suggest the user formalize them.

1.5 Path-Specific Rules with Glob Patterns

Rules can be scoped to specific file patterns using .claude/rules/ files with YAML frontmatter:

---
paths: ["**/*.test.tsx"]
---
Use AAA (Arrange-Act-Assert) pattern in test files.
Prefer real database connections over mocks.
---
paths: ["**/*.api.ts"]
---
Every endpoint must have input validation.
Return consistent error response format.
---
paths: ["terraform/**/*"]
---
Always run `terraform plan` before `terraform apply`.
Never hardcode credentials.

AI Action: These rules only load when matching files are being edited. They do not consume context permanently. When creating project rules, prefer path-specific rules over putting everything in CLAUDE.md.

1.6 Global vs Project CLAUDE.md

  • Project CLAUDE.md (./CLAUDE.md): Project-specific rules, commands, conventions
  • Global CLAUDE.md (~/.claude/CLAUDE.md): Cross-project rules, personal preferences, communication style

AI Action: Never put project-specific information in the global file. Never put personal preferences in the project file.


2. Context Window Management

The context window is the AI's working memory. Every message, file read, and command output accumulates in a shared budget. This is the most critical technical concept in AI-assisted development.

2.1 Quality Degradation Thresholds

  • 0-20%: Optimal performance
  • 20-40%: Quality degradation starts. Instructions may be partially missed.
  • 40-60%: Noticeable decline. Repetitions, inconsistencies appear.
  • 60%+: Critical zone. AI forgets instructions, edits wrong files, repeats mistakes.

AI Action: Monitor your context usage. When approaching 40%, proactively suggest /compact to the user. When context quality visibly degrades, recommend /clear and a fresh session.

2.2 One Conversation = One Task (Strict Rule)

  • Auth system + database schema + UI components + tests = four separate sessions
  • Do not combine unrelated tasks in a single conversation
  • A new session does not start from zero -- CLAUDE.md knows the project, project-memory knows the state

AI Action: If the user starts a new unrelated task in the same session, suggest starting a fresh session. Say: "This is a separate task. Starting a new session will give better results because context will be clean."

2.3 Context Hygiene Commands

Command When to Use
/compact Proactively at 40-50% context fill. Do not wait for 70%.
/clear When a task is complete or the topic changes entirely.

2.4 Context Rot

Old tool outputs, debug traces from fixed bugs, stale versions of refactored files -- all accumulate in context. The AI cannot distinguish current from outdated information. Stale data actively causes harm: the AI references renamed variables, follows changed patterns, treats old state as current.

This is why most multi-agent systems hit a wall after 3-4 tasks. The model did not get dumber. The context got poisoned.

AI Action: Be aware that older information in context may be stale. When in doubt, re-read the current state of a file rather than relying on what was read earlier in the session.

2.5 Information Ordering

The order of information sent to AI affects output quality. AI processes the beginning and end of long inputs well but can miss information in the middle.

Effective ordering:

  1. Context first: What project, what module, what are we doing?
  2. Then the problem: Error message, unexpected behavior
  3. Supporting evidence: Relevant code, log outputs, screenshots
  4. Finally, the expectation: What should happen?

AI Action: When you receive a long, unstructured prompt, mentally reorganize: identify context, problem, evidence, and expectation before proceeding.

2.6 Never Summarize Summaries

When compressing already-compressed text, information loss compounds at every stage. Instead of re-summarizing a session summary, regenerate each summary level from the underlying data and the actual current state of the code.

AI Action: When asked to create a summary of previous work, go back to source files and current code state. Do not summarize an existing summary.

2.7 HUD Monitoring

Claude Code provides a HUD (Heads-Up Display) in the terminal status bar showing:

  • Active model (Opus, Sonnet, Haiku)
  • Session duration and token count
  • Current cost and hourly rate
  • Cache hit rate
  • Permission mode (Normal, Auto-Accept, Bypass)
  • Context fill bar (the most critical indicator)

AI Action: When the user seems unaware of context issues, remind them to check the HUD context bar.

2.8 The Hidden Cost of CLAUDE.md Size

CLAUDE.md is auto-loaded in every session. A 2,000-token CLAUDE.md adds cost to every single message exchange. Over 1,000 messages, this becomes significant. This is another reason to keep CLAUDE.md short and use progressive disclosure.


3. Hooks System

Hooks are deterministic safety nets layered on top of the AI's probabilistic behavior.

3.1 Philosophy

  • AI is a probability machine. It usually does the right thing, but sometimes it does not.
  • Hooks are mechanical locks that guarantee "it absolutely cannot do things it should not do."
  • You are adding deterministic guarantees to AI's probabilistic nature.

The Rule: If a single failure can cause financial damage or security risk, it MUST be a hook, not a prompt instruction. Prompts work 98% of the time. That 2% failure rate is acceptable for commit message formatting but unacceptable for processing refunds without identity verification.

General principle:

  • Give to AI: Judgment-intensive work (architectural decisions, writing code, problem diagnosis)
  • Give to deterministic tools: Mechanical work (git operations, format checks, static validation)
  • Anything solvable with if-else should not require LLM reasoning

3.2 Five Hook Types

Hook Type When It Fires Use Case
PreToolUse Before a tool is called Block dangerous operations
PostToolUse After a tool is called Validate output, check conventions
SessionStart When session starts Environment setup, load state
UserPromptSubmit When user sends a message Input control, preprocessing
Stop When the agent stops Cleanup, save state

3.3 Three Essential Hooks to Create

AI Action: When setting up a new project, create these three hooks in .claude/settings.local.json:

Hook 1: Dangerous Git Protection (PreToolUse:Bash)

Blocks destructive git commands that can cause irreversible damage.

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "if echo \"$CLAUDE_TOOL_INPUT\" | grep -qE 'git\\s+(push\\s+--force|reset\\s+--hard|checkout\\s+\\.|clean\\s+-fd)'; then echo 'BLOCKED: Destructive git command detected' >&2; exit 1; fi"
          }
        ]
      }
    ]
  }
}

Hook 2: Conventional Commits (PreToolUse:Bash)

Enforces feat(scope): description format for all commit messages.

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "if echo \"$CLAUDE_TOOL_INPUT\" | grep -qE 'git\\s+commit'; then if ! echo \"$CLAUDE_TOOL_INPUT\" | grep -qE 'git\\s+commit\\s+-m\\s+\"(feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)\\('; then echo 'BLOCKED: Commit message must follow conventional format: type(scope): description' >&2; exit 1; fi; fi"
          }
        ]
      }
    ]
  }
}

Hook 3: Convention Guard (PostToolUse:Edit|Write)

Checks project-specific rules on every file write. Customize patterns per project.

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "if echo \"$CLAUDE_TOOL_FILE_PATH\" | grep -qE '\\.(ts|tsx)$'; then if grep -n 'any\\b' \"$CLAUDE_TOOL_FILE_PATH\" | grep -v '// eslint-disable' | head -5; then echo 'WARNING: Found `any` type usage' >&2; fi; if grep -n 'console\\.log' \"$CLAUDE_TOOL_FILE_PATH\" | head -5; then echo 'WARNING: Found console.log' >&2; fi; fi"
          }
        ]
      }
    ]
  }
}

3.4 Advanced: Architecture Guard

For projects with layered architecture (Clean Architecture, Hexagonal, etc.), create a hook that checks layer violations on every file change.

Example: Block EF Core imports in the Domain layer, or Infrastructure references in the Application layer. Domain-specific hooks protect architectural integrity against AI-induced shortcuts.

AI Action: When the project uses a layered architecture, suggest an architecture guard hook that checks import/using statements against allowed layer dependencies.

3.5 Hook Strategy

  • Start with 3-5 well-chosen hooks. Each hook adds a small cost to context.
  • 3-5 effective hooks are far better than 20 unnecessary ones.
  • Hooks are defined in .claude/settings.local.json (project-local, each project gets its own set).
  • Add hooks incrementally as you discover recurring issues.

4. Plan-Execute-Verify Loop

This is the most productive working pattern for AI-assisted development.

4.1 Permission Modes

Toggle between modes with Shift+Tab:

Mode Behavior Use When
Normal Asks approval on every file edit and command Learning, high-risk changes
Auto-Accept Auto-approves file edits, asks for Bash commands Implementing a reviewed plan
Bypass Auto-approves everything Trusted, well-defined tasks (watch every step)

4.2 Alignment Before Planning

Before entering Plan Mode, perform alignment. When you tell AI "build an auth system," it silently makes 30+ decisions in the first 5 minutes. You do not know which decisions were made until you see the result.

AI Action: Before planning any non-trivial feature:

  1. Identify grey areas and points where multiple reasonable approaches exist
  2. Present them to the user as structured options:
    • "Session management: A) JWT refresh rotation, B) Redis server-side session, C) Your preference?"
    • "Error handling: A) Centralized error handler, B) Per-route error handling, C) Your preference?"
  3. Get answers before creating the plan
  4. This 10-minute alignment is far cheaper than correcting course mid-implementation

4.3 The Loop

  1. Switch to Plan Mode: Let the AI analyze the project and plan what to do (no changes made)
  2. Review the plan: Does it make sense? Anything missing? Request corrections.
  3. Switch to Auto-Accept: Let the AI implement the plan
  4. Verify: Does the build work? Do tests pass? Is expected behavior achieved?

AI Action: Follow this loop for every multi-file change. Do not skip the planning step.

4.4 Goal-Backward Verification (3 Layers)

"All steps completed" is NOT verification. Real verification is observing outcomes. Think in three layers:

Layer Question How to Verify
Behavioral "Can the user log in?" Run the application and observe
Structural "Is auth.ts real implementation or stubs?" Read file content -- it must be real code, not TODOs and return null
Connective "Does login handler actually import and use auth module?" Check that pieces are wired together, not just existing independently

The most common AI failure mode: files exist, build passes, but pieces are not connected.

AI Action: After implementing a feature, perform all three verification layers:

  1. Run the build: npm run build (or equivalent)
  2. Run the tests: npm test (or equivalent)
  3. Check structural integrity: read key files and confirm real implementation exists
  4. Check connective integrity: verify imports, function calls, and data flow between modules

4.5 YOLO Mode

The claude --dangerously-skip-permissions command skips all permission prompts.

  • ONLY use in isolated environments: Docker containers, disposable VMs, controlled CI/CD
  • NEVER in your actual development environment

4.6 CI/CD Integration

Claude Code can run in CI/CD pipelines with the -p (print mode) flag:

claude -p "Analyze the changes in this PR"
claude -p --output-format json "Run code quality analysis"
  • Without -p, Claude waits for interactive input and the pipeline hangs
  • JSON output enables automatic conversion of findings into PR comments
  • When re-running analysis, include previous findings in context and say "only report new or unresolved issues" to avoid duplicate comments

5. Deep Research Workflow

For complex tasks, research before implementation produces dramatically better results.

5.1 The 5-Step Process

AI Action: When the user faces a decision listed in section 5.2, guide them through this process:

  1. Start with a conversation: Ask the AI to ask YOU questions. Say "ask me questions about this topic so we can understand my requirements." This surfaces what information the AI needs.

  2. Answer the AI's questions: The AI asks 10-15 questions. Answer them. This clarifies your thinking and provides the AI with rich context.

  3. Generate the deep research prompt: Tell the AI "create a deep research prompt based on this conversation." The AI produces a detailed, focused research prompt incorporating all context.

  4. Send to deep research: Send the prompt to Claude.ai extended thinking, ChatGPT deep research, or Gemini deep research. Compare results from multiple providers.

  5. Bring results to Claude Code: Start the implementation session with a solid knowledge foundation.

5.2 When to Use Deep Research

  • Choosing a new technology or framework
  • Complex architectural decisions (monolith vs microservices, event-driven vs request-driven)
  • Performance optimization strategies
  • Determining security approach
  • Strategy before a major refactoring
  • Best practices in an unfamiliar area

AI Action: When the user describes a task matching these criteria, suggest the deep research workflow before diving into implementation.

5.3 Important Principle

Do not tie deep research to a single tool. Claude.ai, ChatGPT, Gemini all have deep research modes with different strengths. What matters is the process, not the tool.


6. Model Routing Strategy

Using the right model for the right task reduces costs by 60-70% while maintaining quality.

6.1 Three Models, Three Purposes

Model Strengths Use For Cost
Haiku Fast, cheap File search, format checks, quick questions, simple lookups Low
Sonnet Balanced DEFAULT for implementation, debugging, code review, day-to-day work Medium
Opus Deep reasoning Architectural decisions, tough bugs, large refactoring, security audits High

6.2 The Rule

  • Default: Sonnet for everything
  • Upgrade to Opus: Only when genuinely needed (architecture, security, complex bugs)
  • Downgrade to Haiku: For simple, mechanical tasks

6.3 Subagent Model Routing

Agent Type Model Reasoning
Explore / file search Haiku Fast, cheap, sufficient for search
Implementation / debugging Sonnet Balanced quality and cost
Architecture / security analysis Opus Requires deep reasoning

AI Action: When spawning subagents, explicitly set the model parameter:

Task(subagent_type="Explore", model="haiku", prompt="Find all auth files")
Task(subagent_type="general-purpose", model="sonnet", prompt="Implement login endpoint")
Task(subagent_type="security-auditor", model="opus", prompt="Review auth for OWASP Top 10")

7. Custom Agents

Custom agents produce significantly higher quality than asking general-purpose Claude for specialized tasks.

7.1 Why Custom Agents

A custom agent:

  • Carries domain knowledge (OWASP checklist, project-specific rules)
  • Has tool constraints (a debugger does not have permission to delete files)
  • Works with focused context (only relevant information loaded)
  • Follows a consistent approach (same checklist every time)

7.2 Agent Location

Agents live in .claude/agents/ as markdown files.

7.3 Two Essential Agents

AI Action: Create these two agents for every project:

Agent 1: Code Reviewer (Sonnet)

.claude/agents/code-reviewer.md:

# Code Reviewer Agent

You are a code review specialist. Review code for:
- Code quality and pattern conformance
- SOLID principles adherence
- Naming conventions (per project CLAUDE.md)
- Error handling completeness
- Test coverage gaps

## Always Do
- Read the code thoroughly before commenting
- Check for pattern consistency across files
- Verify error handling is real, not placeholder
- Flag any `any` types, `@ts-ignore`, or `console.log`

## Ask First
- Suggesting architectural changes
- Proposing new patterns or abstractions

## Never Do
- Modify code directly
- Approve code with TODO/FIXME in critical paths
- Skip checking test files

Agent 2: Debugger (Read + Bash only)

.claude/agents/debugger.md:

# Debugger Agent

You are a debugging specialist. Your job is to find root causes, not apply fixes.

## Tools
- Read: Read files, examine code
- Bash: Run commands, check logs, execute tests

## Always Do
- Reproduce the error first
- Read the full stack trace
- Check recent git changes (`git diff HEAD~3`)
- Identify root cause before suggesting fixes

## Ask First
- Nothing -- you diagnose, the user (or another agent) fixes

## Never Do
- Edit or write files
- Delete anything
- Apply fixes without approval

7.4 3-Layer Boundaries Per Agent

Every custom agent should have explicit boundaries:

Layer Examples
Always do Read code, search patterns, generate reports
Ask first Implement fixes, create new files
Never do Delete files, expose secrets, touch production

AI Action: When creating a new agent, always define all three boundary layers.


8. Multi-Agent Work

Multi-agent architecture is the real force multiplier for AI-assisted development.

8.1 Subagents vs Teams

Aspect Subagents Teams
Lifespan Short-lived, task-focused Persistent, ongoing
Context Independent (clean start) Independent with shared task list
Communication Return results to main session Message each other via inbox
Use when One-off tasks, quick reviews, searches Comprehensive PR review, large features, complex refactoring

8.2 The Context Advantage

Each subagent has its own independent context. Even if the main session is at 40% context, a subagent starts clean. This is revolutionary for context management.

AI Action: Delegate research, code reviews, and file searches to subagents to keep the main session's context clean. The main session coordinates; subagents do the work and return results.

8.3 Worktree Isolation

When team members work on the same files, conflicts arise. Use isolation: worktree to give each agent an isolated working directory.

AI Action: For parallel refactoring or large features with multiple agents, use worktree isolation:

Task(team_name="refactor", name="worker-1", isolation="worktree", ...)

8.4 Attention Dilution Fix

When reviewing 14 files in a single pass, the first few get detailed attention, the middle ones get skimmed, the last few get good attention again. The same pattern may be flagged as wrong in one file but silently approved in another.

AI Action: For large reviews, use this two-phase approach:

  1. Per-file analysis: Give each file to a separate subagent for consistent depth
  2. Cross-file connection analysis: Have a separate subagent examine data flow and connections between files

8.5 Session Branching

Use fork_session to try different approaches from the same analysis baseline. Like opening two git branches from the same commit.

AI Action: When the user wants to evaluate multiple approaches (e.g., "refactor existing" vs "rewrite from scratch"), suggest forking the session after the initial analysis.

8.6 Practical Scenario: Comprehensive Code Review

Team Lead (you): Coordination
  Teammate 1: Security review (OWASP, input validation, auth)
  Teammate 2: Code quality (patterns, SOLID, cleanliness)
  Teammate 3: Performance analysis (N+1 queries, memory leaks, caching)
  Teammate 4: Test coverage (missing tests, edge cases)

Four agents work in parallel, each going deep in their expertise. Results combine into a comprehensive review. What takes hours alone takes minutes with parallel agents.


9. Skills Strategy

Skills add reusable knowledge and workflows. Unlike agents (task executors), skills are knowledge sources that run in the main conversation.

9.1 Key Skill Options (YAML Frontmatter)

Option Purpose When to Use
context: fork Run in separate context Heavy skills that produce thousands of lines of output
allowed-tools Restrict available tools Safety boundaries, same logic as agent boundaries
argument-hint Define what to ask user When skill needs parameters

AI Action: For any skill that produces large output (codebase analysis, comprehensive review), always use context: fork to prevent context pollution in the main session.

9.2 Valuable vs Non-Value Skills

Type Description Action
Valuable Contains scripts, commands, automated workflows Keep as skills
Non-value Only contains text/instructions, no automation Move to .claude/rules/ files instead

AI Action: During skill review, check if a skill just contains text instructions. If so, migrate it to a rules file. Rules files load more lightweight than skills.

9.3 Context Cost

  • Every active skill is loaded into context in every session
  • 20 active skills x 500 tokens each = 10,000 tokens before the session starts
  • This hidden cost affects both performance and cost

AI Action: Only enable skills relevant to the current project. Disable skills for irrelevant languages/frameworks.

9.4 Smart Selection Strategy

  1. Enable/disable per project: No Go skills in a TypeScript project
  2. Move text-only skills to rules files: .claude/rules/ is more lightweight
  3. Prioritize automation skills: Keep skills that run commands, spawn agents, automate workflows
  4. Monthly review: Ask "which skills am I actually using?" Deactivate the rest.

9.5 Keyword Mapping

Explicitly specify trigger keywords for each skill. The AI picks up these keywords during planning and automatically activates the relevant skill.

Example: A "performance-optimization" skill should include keywords: "slow", "N+1", "cache", "memory leak", "latency", "profiling"

AI Action: When creating a skill, define a comprehensive keyword list in the skill's metadata. Without keywords, even a perfect skill will never be triggered. Think of it like search engine keyword systems.


10. Cross-Model Orchestration

Using different AI models together produces better results than relying on a single model.

10.1 Triple Orchestration

Model Strength Use For
Claude Opus Main orchestrator, deep reasoning Complex architectural decisions, multi-step planning, big picture
OpenAI Codex/GPT Code analysis, different perspective Planning validation, critical review, finding blind spots in Claude's proposals
Google Gemini Large context (1M tokens) Analyzing many files simultaneously, UI/UX design review, detailed documentation

10.2 How It Works

MCP integration enables sending tasks to other models from within Claude Code:

  • Made an architectural decision? Send to Codex: "Review this approach, find weak points"
  • Designed a UI? Send to Gemini: use its large context to check consistency across all components
  • Complex bug? Let Claude Opus do deep analysis, Codex offer a different perspective

AI Action: For critical decisions (architecture, security, large refactoring), suggest cross-model validation:

Task(subagent_type="ask_codex", agent_role="architect", prompt="Review this architectural approach...")
Task(subagent_type="ask_gemini", agent_role="designer", prompt="Review UI consistency across...")

10.3 Why It Matters

Different models have different biases and strengths. What Claude misses, Codex might catch. What Codex overlooks, Gemini might flag with its broader context view. Cross-model orchestration provides the "different perspectives" that make critical decisions more robust.


11. Self-Learning Systems

Build systems where AI learns from its own experience and accumulates knowledge over time.

11.1 Claudeception: Automatic Skill Creation

After solving a problem:

  1. Evaluate: "Is there a generalizable pattern from this solution?"
  2. If yes, automatically create a skill
  3. Next time a similar problem appears, the skill kicks in

AI Action: After solving a non-trivial problem, ask: "Should this solution be generalized into a reusable skill?" If the pattern will recur, create the skill with proper keyword mapping.

11.2 Memory Layers

Layer Scope Storage Persistence
Short-term Current session Notepad / working memory Session only
Medium-term Project-specific project-memory (decisions, patterns, conventions) Persistent between sessions
Long-term Cross-project Skills and global rules Portable between projects

AI Action: At session end, identify important decisions and patterns:

  1. Save session-specific state to notepad/working memory
  2. Save project decisions and conventions to project-memory
  3. If a pattern is universally useful, create a skill or global rule

11.3 Critical Rule: Never Summarize Summaries

When compressing already-compressed text, information loss compounds at every stage. Instead of re-summarizing a session summary, regenerate each summary level from the underlying data and the actual current state of the code.

AI Action: When creating summaries or transferring information between memory layers, always go back to source data. Never compress an existing summary further.


12. Testing, Security, Performance

These three areas are the most likely to be forgotten in AI-powered development because AI produces code fast and the user wants to move fast too.

12.1 Testing in AI-Powered Development

The Rule: When having AI write a feature, ask for tests in the same prompt, then RUN the tests.

  • Say: "Implement this feature, write tests covering edge cases, then run them with npm test"
  • Adding verification criteria to the prompt is the single highest-leverage practice
  • AI is good at thinking about edge cases (null checks, boundary conditions, error scenarios) -- but only when asked

AI Action: Never write a feature without tests. When implementing, always:

  1. Write the feature code
  2. Write tests covering happy path, edge cases, and error scenarios
  3. Run the tests
  4. Report results to the user

12.2 Security Pre-PR Checklist

Before every PR, perform:

  1. Hardcoded secret scan: Search for API keys, passwords, tokens
  2. Input validation check: Are user inputs being validated?
  3. OWASP Top 10 review: SQL injection, XSS, CSRF risks?
  4. Dependency security: Packages with known vulnerabilities?

AI Action: Before creating a PR, run:

# Hardcoded secret scan
grep -rn "password\|secret\|api_key\|token\|private_key" --include="*.ts" --include="*.go" --exclude-dir=node_modules --exclude-dir=.git .

# Check for .env file commits
git diff --cached --name-only | grep -E "\.env|credentials|serviceAccount"

12.3 Automate with PostToolUse Hooks

Run security tools on every file change:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "if command -v semgrep >/dev/null 2>&1; then semgrep --config=auto \"$CLAUDE_TOOL_FILE_PATH\" 2>/dev/null || true; fi"
          }
        ]
      }
    ]
  }
}

12.4 PR Pipeline: External Verification

The principle: Claude produces, external tools independently audit. They do not share the same biases.

Layer 1 - Commit time (before code leaves your machine):

  • Pre-commit hooks: lint check, build check, type check, test coverage threshold
  • Block direct commits to protected branches (main, production, staging)

Layer 2 - PR time (before code gets merged):

  • External tools: SonarQube, CodeRabbit, or equivalent
  • PR stays open until: external issues cleared, type checks pass, tests go green
  • Feed external tool findings back to Claude to fix together

AI Action: Never approve a merge until:

  1. Build passes
  2. All tests pass
  3. Security scan is clean
  4. External pipeline checks (SonarQube, CodeRabbit, etc.) go green

12.5 Performance Assessment

After major features or refactoring, check for:

  • N+1 query patterns
  • Unnecessary re-renders (frontend)
  • Memory leak risks
  • Missing streaming for large file/data processing

13. Voice Input and Smart Context

13.1 Speech-to-Text (STT)

  • Typing: 40-60 words per minute
  • Speaking: 120-150 words per minute (3x speed increase)
  • Use STT for complex explanations, bug reports, architectural discussions
  • STT must correctly transcribe technical terms (keyword mapping depends on accurate transcription)

13.2 Clipboard Manager: Accumulate and Dispatch

A smart clipboard manager keeps history, makes it searchable, and allows grouping.

The "accumulate and dispatch" strategy:

  1. Copy error message from terminal
  2. Copy relevant code block from editor
  3. Copy log output from browser
  4. Copy URL from documentation
  5. Arrange all pieces in logical order
  6. Send as a single, structured prompt to AI

AI Action: When receiving context from the user, check if it follows the correct ordering (section 13.3). If information seems randomly ordered, mentally reorganize before processing.

13.3 Context Ordering (Affects Quality)

Always arrange context in this order:

  1. Context/location: What project, what module?
  2. Problem: What is happening? Error message, unexpected behavior?
  3. Supporting evidence: Relevant code, log outputs, screenshots
  4. Expectation: What should happen?

Randomly ordered context produces significantly lower quality output than the same information arranged in logical order.


14. Do's and Don'ts

DO

  1. Write a good CLAUDE.md for every project -- without it, AI does not know your project
  2. Actively manage context -- monitor HUD, use /compact at 40-50%, /clear when done
  3. Make Plan Mode a habit -- review plans before big changes, then approve
  4. Provide verification criteria -- not "write tests" but "write tests covering edge cases and run them with npm test"
  5. Weave safety net with hooks -- minimum 3 essential hooks
  6. Use subagents generously -- delegate research, review, search to keep main context clean
  7. Start with deep research -- on complex tasks, research first, implement second
  8. Apply model routing -- Haiku for simple, Sonnet as default, Opus for deep analysis
  9. Teach by example -- code snippets are more effective than paragraphs of explanation
  10. Keep sessions short -- one conversation = one task
  11. Use clipboard manager -- accumulate and dispatch strategy
  12. Use STT tools -- 3x speed increase for complex explanations
  13. Apply keyword mapping to skills -- skills without keywords are undiscoverable

DON'T

  1. Don't use Claude as a linter -- ESLint, Biome, Prettier already exist; lint rules are context waste
  2. Don't do everything in a single session -- context explosion = quality collapse
  3. Don't turn CLAUDE.md into a novel -- under 100 lines, use progressive disclosure
  4. Don't trust without verifying -- "done" is not enough; build, test, security -- verify
  5. Don't let Claude over-engineer -- state explicitly in CLAUDE.md: no extra abstractions
  6. Don't try the same thing on repeated errors -- change approach, try different prompt, switch to Plan Mode, or start new session
  7. Don't keep all skills active at once -- project-specific selection, deactivate unused
  8. Don't stay dependent on single model -- use cross-model orchestration for different perspectives
  9. Don't judge MCPs only by descriptions -- experiment to discover real capabilities
  10. Don't delay writing tests -- biggest trap of AI development; without tests you cannot verify AI output
  11. Don't send context in random order -- ordering directly affects output quality
  12. Don't leave skills without keywords -- undiscoverable skills are useless skills

15. Project Lifecycle

15.1 Getting Started (New Project)

AI Action: Execute these steps in order when setting up a new project:

  1. Deep research: Conduct technology and architecture research

    "Ask me questions about this project so we can understand requirements"
    -> Answer 10-15 questions
    -> Generate deep research prompt
    -> Send to deep research mode
    -> Bring results to Claude Code
    
  2. Create CLAUDE.md: Use WHAT/WHY/HOW structure, under 100 lines

    # Verify the file exists and is well-structured
    cat CLAUDE.md | wc -l  # Should be < 100
  3. Set up essential hooks: Git safety, conventional commits, convention guard

    # Create hooks in .claude/settings.local.json
    mkdir -p .claude
    # Write the 3 essential hooks (see Section 3.3)
  4. Initialize project-memory: Save tech stack, architectural decisions

    project_memory_write({
      techStack: { ... },
      conventions: { ... },
      structure: { ... }
    })
    
  5. Create essential agents: At minimum code-reviewer and debugger

    mkdir -p .claude/agents
    # Create code-reviewer.md and debugger.md (see Section 7.3)

15.2 Daily Development

AI Action: Follow this daily workflow:

  1. Session start: Read project-memory to understand current state
  2. Plan Mode: Clarify what will be done before making changes
  3. Auto-Accept: Implement the reviewed plan
  4. Subagent delegation: Run tests and reviews via subagents (keeps main context clean)
  5. Session end: Save important decisions to project-memory

15.3 Before PR / Merge

AI Action: Execute this checklist before every PR:

  1. Run multi-agent review:
    • Security reviewer (OWASP, input validation, auth)
    • Quality reviewer (patterns, SOLID, cleanliness)
    • Performance reviewer (N+1 queries, memory leaks, caching)
    • Test reviewer (missing tests, edge cases)
  2. Verify build and tests pass:
    npm run build && npm test
  3. Perform security scanning:
    grep -rn "password\|secret\|api_key\|token" --include="*.ts" --exclude-dir=node_modules .
  4. Cross-model validation (optional but valuable)
  5. Wait for external pipeline checks -- do not merge until SonarQube/CodeRabbit/etc. go green

15.4 Refactoring / Major Changes

AI Action: Follow this process for large refactoring:

  1. Deep research: Determine strategy with the 5-step research workflow
  2. Plan Mode: Create a detailed plan, get alignment on grey areas
  3. Teams + Worktree: Work in parallel with isolated agents
  4. Verify each stage: Apply 3-layer verification (behavioral, structural, connective) at each step
  5. Incremental merges: Do not attempt a single massive merge; break into reviewable increments

Quick Reference: Essential Commands

Command Purpose
Shift+Tab Toggle permission mode (Normal / Auto-Accept / Bypass)
/compact Compress context (use at 40-50% fill)
/clear Start fresh session
claude -p "prompt" Non-interactive mode for CI/CD
claude -p --output-format json "prompt" Machine-readable CI/CD output
claude --dangerously-skip-permissions YOLO mode (Docker/VM only, never local)

Quick Reference: File Locations

File Purpose
CLAUDE.md Project brain (WHAT/WHY/HOW, under 100 lines)
~/.claude/CLAUDE.md Global rules (personal preferences, cross-project)
.claude/settings.local.json Hooks configuration (project-local)
.claude/rules/*.md Path-specific and topic rules (progressive disclosure)
.claude/agents/*.md Custom agent definitions
.mcp.json Project-specific MCP configuration (committed to git)
~/.claude/mcp.json Global MCP configuration

Claude Code Setup: Advanced (Level 3)

Cross-model orchestration, self-learning, PR pipeline, and project lifecycle Level: Advanced Prerequisite: Complete claude-setup-intermediate.md first Frameworks: See frameworks-guide.md for GSD-2, OMC, and Pi recommendations


Step 1: Cross-Model Orchestration

Why Multiple Models?

Every AI model has strengths, weaknesses, and blind spots. A single model cannot notice its own blind spots. Claude might confidently produce an architecture that has a known failure mode in Codex's training data. Gemini might catch a UI inconsistency across 50 files that Claude missed because of context pressure.

The solution is not to trust one model more - it is to build a system where models audit each other.

Triple Orchestration

Model Role Strengths
Claude Opus Main orchestrator Deep reasoning, multi-step planning, big picture thinking
OpenAI Codex/GPT Second opinion Code analysis, planning validation, critical thinking
Google Gemini Large context reviewer 1M tokens, analyzing many files simultaneously, UI/UX review, documentation

How It Works: MCP Integration

From within Claude Code, send tasks to other models without leaving your terminal. Configure both providers as MCP servers:

{
  "mcpServers": {
    "codex": {
      "command": "npx",
      "args": ["-y", "@openai/codex-mcp"],
      "env": {
        "OPENAI_API_KEY": "<your-key>"
      }
    },
    "gemini": {
      "command": "npx",
      "args": ["-y", "@google/gemini-mcp"],
      "env": {
        "GEMINI_API_KEY": "<your-key>"
      }
    }
  }
}

Add this to ~/.claude/mcp.json. If the file already exists, merge the entries into the existing mcpServers object.

With oh-my-claudecode (OMC), you can invoke them directly:

# Inside Claude Code:
# Route architectural decision to Codex for critical review
ask codex: review this architecture diagram for weak points and failure modes

# Route UI review to Gemini with full component tree
ask gemini: check consistency across all these components and flag any UX issues

When to Use Cross-Model Verification

  • Critical architectural changes before implementation begins
  • Security audits where Claude wrote the code being reviewed
  • Large refactoring projects where the full diff exceeds a single context window
  • Any decision where a second perspective reduces risk disproportionately to the cost

Routing by Strength

Architectural decision  → Codex (agent_role: "architect")
Security audit          → Codex (agent_role: "security-reviewer")
Planning validation     → Codex (agent_role: "critic")
UI/UX consistency       → Gemini (agent_role: "designer")
Large documentation     → Gemini (agent_role: "writer")
Cross-file analysis     → Gemini (1M context, agent_role: "analyst")

Step 2: Self-Learning Systems (Claudeception)

The Problem

You solve a complex bug. Three weeks later a similar bug appears. Without a learning system you repeat the full investigation from scratch. The AI has no memory of the previous solution.

What Claudeception Does

Claudeception is the pattern of extracting generalizable solutions into reusable skills automatically:

  1. You solve a problem
  2. The system evaluates: "Is there a generalizable pattern here?"
  3. If yes, a skill file is created at ~/.claude/skills/
  4. Next time a similar problem appears, the skill is triggered automatically

Creating a Skill Manually

cat > ~/.claude/skills/react-native-flatlist-performance.md << 'EOF'
---
name: react-native-flatlist-performance
description: Diagnose and fix FlatList performance issues in React Native
triggers:
  - flatlist slow
  - list performance
  - scroll lag react native
---

When FlatList is slow or laggy:

1. Check extraData prop - must include all state/props that affect item rendering
2. Verify keyExtractor returns stable, unique string keys (not array index)
3. Add getItemLayout if item heights are fixed - eliminates measurement overhead
4. Check renderItem for inline function definitions - move outside component
5. Add maxToRenderPerBatch={10} and windowSize={5} for long lists

Root cause pattern: missing extraData causes full re-render on every state change.
EOF

Triggering Skill Creation After a Win

When you solve something non-obvious, tell Claude:

That solution worked. Extract the generalizable pattern as a skill file at
~/.claude/skills/<descriptive-name>.md with appropriate triggers.

Memory Layers

Layer Scope Persistence Location Example Content
Short-term Current session Session only Notepad (.omc/notepad.md) Active task state, working notes
Medium-term Project Between sessions Project-memory (.omc/project-memory.json) Architectural decisions, tech stack, conventions
Long-term Universal Portable across projects Skills (~/.claude/skills/) Solved patterns, reusable workflows

Project Memory: What to Store

# Inside Claude Code, after making a significant decision:
/note architecture: chose PostgreSQL over MongoDB because write patterns are relational and joins are frequent
/note pattern: all API responses wrapped in { data, error, meta } envelope
/note directive: never use any type, always use unknown + type guard

At session start, project-memory is loaded automatically. The AI knows your decisions without you re-explaining.

Critical Rule: Never Summarize a Summary

When compressing context, do not summarize already-summarized text. Each compression compounds information loss. Instead: regenerate each summary level from the underlying data and the actual current code state. Reference real files, not previous summaries of files.


Step 3: PR Pipeline (External Verification)

The Principle

Claude produces. External tools independently audit. They do not share Claude's biases or blind spots. A PR does not close until independent systems outside Claude Code have approved it.

The Self-Review Problem

Claude writing code and Claude reviewing that same code in the same session produces lower-quality review. The model has already committed to the approach; it is less inclined to challenge its own decisions. The solution is separation: different session, different agent, or different model entirely.

Layer 1: Pre-Commit (Before Code Leaves Your Machine)

Pre-commit hooks run automatically on every git commit. They block the commit if checks fail.

# Install pre-commit
pip install pre-commit

# Create .pre-commit-config.yaml at project root
cat > .pre-commit-config.yaml << 'EOF'
repos:
  - repo: local
    hooks:
      - id: lint
        name: Lint check
        entry: npm run lint
        language: system
        pass_filenames: false

      - id: typecheck
        name: Type check
        entry: npm run typecheck
        language: system
        pass_filenames: false

      - id: test
        name: Test suite
        entry: npm test -- --passWithNoTests
        language: system
        pass_filenames: false

      - id: no-direct-main
        name: Block direct commits to main
        entry: bash -c 'branch=$(git rev-parse --abbrev-ref HEAD); if [[ "$branch" == "main" || "$branch" == "master" || "$branch" == "production" || "$branch" == "staging" ]]; then echo "Direct commits to $branch are blocked. Use a feature branch."; exit 1; fi'
        language: system
        pass_filenames: false
        always_run: true
EOF

pre-commit install

Layer 2: PR Time (Before Code Gets Merged)

External tools run when a PR is opened. They operate independently of Claude:

SonarQube (self-hosted or SonarCloud):

  • Code smells and maintainability rating
  • Security hotspots
  • Coverage gaps and duplication

CodeRabbit (AI-powered PR review):

  • Inline review comments on the diff
  • Summarizes changes and flags issues
  • Feed its output back to Claude for fixes

GitHub Actions integration:

# .github/workflows/pr-checks.yml
name: PR Checks
on:
  pull_request:
    branches: [main, master, production, staging]

jobs:
  quality:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Install dependencies
        run: npm ci

      - name: Lint
        run: npm run lint

      - name: Type check
        run: npm run typecheck

      - name: Tests with coverage
        run: npm test -- --coverage --coverageThreshold='{"global":{"lines":80}}'

      - name: Build
        run: npm run build

  security:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Run semgrep
        uses: returntocorp/semgrep-action@v1
        with:
          config: auto

PR stays open until:

  • All external tool issues are resolved or explicitly accepted
  • Type checks pass
  • Tests are green
  • Security scan shows no new critical/high findings

Security Automation via Hooks

Add to .claude/settings.local.json to scan on every file edit:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "if command -v semgrep >/dev/null 2>&1; then semgrep --config=auto \"$CLAUDE_TOOL_FILE_PATH\" 2>/dev/null || true; fi"
          }
        ]
      }
    ]
  }
}

Step 4: Architecture Guard Hooks

What It Does

Automatically checks for architectural layer violations on every file change. This makes it impossible for Claude to silently introduce a dependency violation - the hook fires immediately and the violation is visible before the session ends.

Example: Clean Architecture Guard

cat > .claude/hooks/architecture-guard.sh << 'EOF'
#!/usr/bin/env bash
# Architecture guard: enforces Clean Architecture layer boundaries
# Triggered by PostToolUse hook on Edit/Write

FILE="$1"

if [[ -z "$FILE" ]]; then
  exit 0
fi

# Domain layer: no infrastructure dependencies
if echo "$FILE" | grep -q "/Domain/"; then
  if grep -qE "using.*Infrastructure|using.*EntityFramework|using.*Dapper|using.*SqlClient" "$FILE" 2>/dev/null; then
    echo "ARCHITECTURE VIOLATION: Domain layer cannot reference Infrastructure"
    echo "  File: $FILE"
    echo "  Rule: Domain must not depend on any outer layer"
    exit 1
  fi
fi

# Application layer: no direct infrastructure references
if echo "$FILE" | grep -q "/Application/"; then
  if grep -qE "using.*Infrastructure\." "$FILE" 2>/dev/null; then
    echo "ARCHITECTURE VIOLATION: Application layer cannot reference Infrastructure directly"
    echo "  File: $FILE"
    echo "  Rule: Application depends on Domain only. Infrastructure implements Application interfaces."
    exit 1
  fi
fi

exit 0
EOF

chmod +x .claude/hooks/architecture-guard.sh

Register it in .claude/settings.local.json:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "bash .claude/hooks/architecture-guard.sh \"$CLAUDE_TOOL_FILE_PATH\""
          }
        ]
      }
    ]
  }
}

Adapting to Other Architectures

Hexagonal (Ports and Adapters):

# Core/domain cannot import from adapters/
if echo "$FILE" | grep -q "/core/"; then
  if grep -qE "from.*adapters/|require.*adapters/" "$FILE" 2>/dev/null; then
    echo "ARCHITECTURE VIOLATION: Core cannot import from adapters"
    exit 1
  fi
fi

Feature-sliced design:

# Shared layer cannot import from feature layers
if echo "$FILE" | grep -q "/shared/"; then
  if grep -qE "from.*features/|from.*pages/" "$FILE" 2>/dev/null; then
    echo "ARCHITECTURE VIOLATION: Shared cannot import from features or pages"
    exit 1
  fi
fi

The principle is the same: identify the boundaries, write the grep check, hook it to every file edit.


Step 5: CI/CD Integration

Claude in Headless Mode

The -p (print) flag makes Claude non-interactive. Without it, Claude waits for user input and the pipeline hangs indefinitely.

# Analyze PR changes - returns immediately with output
claude -p "Analyze the changes in this diff and summarize risks: $(git diff main...HEAD)"

# Structured output for pipeline consumption
claude -p --output-format json "Run code quality analysis on src/ and return findings as JSON with severity ratings"

# Check for specific patterns
claude -p "Review this migration file for destructive operations that could cause data loss: $(cat migrations/latest.sql)"

GitHub Actions: Claude Analysis Step

# .github/workflows/claude-review.yml
name: Claude Code Review
on:
  pull_request:
    types: [opened, synchronize]

jobs:
  claude-review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Install Claude Code
        run: npm install -g @anthropic-ai/claude-code

      - name: Run Claude analysis
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          DIFF=$(git diff origin/main...HEAD)
          PREVIOUS_FINDINGS="${{ steps.previous.outputs.findings }}"

          claude -p "
          Analyze this PR diff for issues.
          Previous findings from last run: $PREVIOUS_FINDINGS
          Only report NEW issues or issues that are still unresolved.
          Diff: $DIFF
          " > review-output.txt

          cat review-output.txt

      - name: Post review as comment
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            const review = fs.readFileSync('review-output.txt', 'utf8');
            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: `## Claude Code Review\n\n${review}`
            });

Incremental Analysis (Avoid Comment Fatigue)

Always include previous findings in the context and instruct Claude to only report new or still-unresolved issues. Without this, the same comments appear on every run and developers start ignoring them entirely.

# Store findings in a cache file between runs
CACHE_FILE=".claude-review-cache.json"

# Pass previous findings as context
claude -p "
Previous review findings: $(cat $CACHE_FILE 2>/dev/null || echo 'none')
New diff: $(git diff HEAD~1)
Only report: (1) new issues not in previous findings, (2) previous issues that are still present.
Do not repeat issues that have been resolved.
" --output-format json > new-findings.json

# Update cache
cp new-findings.json $CACHE_FILE

Step 6: Voice Input and Smart Context

Speech-to-Text (STT)

Typing: 40-60 words per minute. Speaking: 120-150 words per minute. Voice input is a 3x throughput multiplier for AI interaction.

More important than speed: voice preserves the natural flow of thought. "Look, this function is broken, and while you're there fix that other one, oh and there's also this edge case we discussed earlier" - this kind of contextual chaining is natural in speech and awkward to type.

Tools:

Tool Platform Notes
SuperWhisper macOS Local Whisper model, works offline, system-wide
Whisper Cross-platform Open source, self-hostable via API
macOS Dictation macOS Built-in, no install, limited accuracy on technical terms

Critical requirement: Your STT tool must correctly transcribe technical terms. "Hook" must not become "book". "Async await" must not become "a sink a weight". Test your tool with actual code vocabulary before relying on it.

Keyword mapping: When a term is consistently mistranscribed, add a text substitution rule in your STT tool. Map "a sink" to "async", "null pointer" to "null pointer", etc.

Clipboard Manager

A clipboard manager turns your clipboard from a single-item buffer into a searchable history. This matters in multi-agent workflows where you are assembling context from multiple sources before sending it.

Accumulate-and-dispatch pattern:

  1. Copy error message from terminal
  2. Copy relevant function from editor
  3. Copy stack trace from logs
  4. Open clipboard manager, select all three items
  5. Send as a single, structured batch to Claude

Tools: Raycast (macOS, recommended), Alfred, Maccy (free, macOS)

Context Ordering: Quality Impact Is Real

The same information sent in different orders produces measurably different output quality. AI models process the beginning and end of inputs well; information buried in the middle is most likely to be missed or underweighted.

Recommended order:

1. Context: What are you trying to do? Which project, which module?
2. Problem: What is happening? Error message, unexpected behavior.
3. Evidence: Relevant code, log output, screenshots.
4. Expectation: What do you want to happen?

Concrete example:

# Low quality (evidence buried, expectation unclear):
Here is a 500-line log file. Somewhere in here there is an error. The function
is in auth.ts. It started happening after the last deploy.
[500 lines of log]

# High quality (context first, problem stated, evidence scoped):
Context: auth.ts, validateToken() function, Node.js 20, production environment.
Problem: JWT validation fails silently for tokens issued before 2024-01-01.
Evidence:
  Error at line 47: TypeError: Cannot read properties of null (reading 'exp')
  Relevant code: [20 lines]
Expectation: Function should return { valid: false, reason: 'legacy_token' }
for tokens missing the exp claim, not throw.

Step 7: Project Lifecycle Checklists

Getting Started (New Project)

[ ] Conduct deep research (technology selection, architecture options, tradeoffs)
[ ] Create CLAUDE.md using WHAT / WHY / HOW structure, keep under 100 lines
[ ] Set up 3 essential hooks: pre-commit, security scan, architecture guard
[ ] Initialize project-memory with tech stack, conventions, and architectural decisions
[ ] Create .claude/agents/code-reviewer.md and .claude/agents/debugger.md
[ ] Run /init inside Claude Code to auto-generate starter CLAUDE.md, then refine it
[ ] Set up CI pipeline with lint, typecheck, test, build gates
[ ] Configure external review tools (SonarQube, CodeRabbit, or equivalent)

Daily Development

[ ] Read project-memory at session start (loaded automatically with OMC)
[ ] Use Plan Mode first: clarify scope, identify risks, confirm approach before coding
[ ] Implement with Auto-Accept for low-risk changes, review mode for risky ones
[ ] Run tests and reviews via subagents (independent context, no bias carry-over)
[ ] Save significant decisions to project-memory at session end
[ ] One session = one feature. Start /clear when switching tasks.
[ ] Compact context proactively at 40-50%, not reactively at 70%+

Before PR / Merge

[ ] Multi-agent review: security + quality + performance + test coverage (parallel)
[ ] Build passes with zero errors
[ ] Test suite green with coverage threshold met
[ ] Security scan clean (semgrep, gitleaks - no new critical/high findings)
[ ] Cross-model validation for architectural or security-sensitive changes
[ ] PR description written (changes, rationale, test plan)
[ ] External pipeline passed (SonarQube, CodeRabbit, GitHub Actions)
[ ] No hardcoded secrets (grep or gitleaks scan)
[ ] No console.log / debug print statements in production paths

Refactoring / Major Changes

[ ] Deep research first: understand the current system before changing it
[ ] Detailed plan in Plan Mode: identify all affected files, interfaces, consumers
[ ] Use git worktrees for parallel exploration without blocking main branch
[ ] Break into incremental commits: each commit leaves the system in a working state
[ ] Verify at each stage: do not accumulate 500 unverified line changes
[ ] Run architecture guard checks throughout, not just at the end
[ ] Incremental PRs preferred over one massive PR
[ ] Cross-model review on the final diff before merging

End-of-Session Checklist

[ ] Save architectural decisions made during session to project-memory
[ ] Save any discovered issues to CONCERNS.md or equivalent
[ ] Note next steps clearly so next session can resume without re-investigation
[ ] Run /compact or /clear depending on whether session continues
[ ] Commit or stash any in-progress work

Verification

After completing setup, verify each system works:

# 1. Cross-model: verify MCP servers are reachable
# Inside Claude Code:
# ask codex: describe your capabilities in one sentence
# ask gemini: describe your capabilities in one sentence

# 2. Self-learning: create a test skill and verify it is discoverable
cat > ~/.claude/skills/test-advanced-setup.md << 'EOF'
---
name: test-advanced-setup
description: Verify advanced setup is complete
triggers:
  - test advanced setup
---
Advanced setup is verified and working.
EOF

# Inside Claude Code, type: test advanced setup
# Should trigger the skill automatically

# 3. Pre-commit hooks: verify they block violations
# Make a trivial edit and attempt to commit - hooks should run

# 4. Architecture guard: edit a file that would violate boundaries
# Hook should fire immediately with violation message

# 5. CI pipeline: open a test PR and verify all checks run

All Levels Complete.

See frameworks-guide.md for GSD-2, OMC, and Pi recommendations to decide which orchestration framework fits your workflow.

Claude Code Setup: Essentials (Level 1)

Core setup for effective Claude Code usage Level: Essentials (start here) Next: See claude-setup-intermediate.md for agents, multi-agent, and model routing Prerequisite: Read ai-playbook.md for the principles behind each step


Project Type Detection

AI Instructions: Ask the user before doing anything else.

"Does this folder contain application source code already?"

  • Yes - Existing Project: read the codebase first, then set up
  • No - New Project: set up from scratch

Pre-Flight Check

AI Instructions: Run these checks. If any tool is missing, tell the user to install it before continuing.

# Required: Claude Code itself
claude --version

# Recommended: jq for JSON inspection in hooks
jq --version

# Recommended: Node/npm for optional tools
node --version && npm --version

If claude is not found: install from https://claude.ai/download


Step 1: Create CLAUDE.md (The Most Important File)

AI Instructions:

  1. If CLAUDE.md exists - read it, then analyze it against the WHAT/WHY/HOW structure below. Report what is missing or violates the 100-line rule.
  2. If CLAUDE.md does not exist - run /init to generate a baseline, then restructure it using the template below.
  3. Always keep the final file under 100 lines.

Why CLAUDE.md matters

Claude reads this file at the start of every session. It is the only persistent context that does not cost tokens from your conversation budget. A well-structured CLAUDE.md is the single highest-leverage investment you can make.

The 100-line rule exists because Claude's attention is finite. A 160-line file means important rules get missed. Keep it under 100 lines and move details to .claude/rules/ files (Step 2).

The WHAT / WHY / HOW Structure

## What
<!-- One paragraph: what is this project, tech stack, architecture, core concepts -->
This is a TypeScript monorepo with a Next.js frontend and a Node.js API.
The frontend uses React Query for server state and Zustand for client state.

## Why
<!-- Why were these decisions made? Claude makes better edge-case decisions when it knows the why. -->
We chose React Query over SWR because we need fine-grained cache invalidation
across mutations. We avoid Redux because the team found its boilerplate slows
down iteration without adding safety for our scale.

## How
<!-- Commands, test patterns, naming conventions -->
- Test: `npm test`
- Build: `npm run build`
- Lint: `npm run lint`
- Branch naming: `feat/`, `fix/`, `chore/`
- Component files: PascalCase. Utility files: camelCase.
- All API calls go through `src/lib/api.ts`. Never call fetch directly.

## Don't
- Don't over-engineer. No extra abstractions, no unnecessary interfaces.
- Don't split things into multiple files when one file is sufficient.
- Don't add error handling for scenarios that cannot happen.
- Don't add docstrings or comments unless explicitly asked.
- Don't create stub files. No `return null`, `return {}`, `TODO`, or placeholder implementations.
- Don't use `console.log` in production code.

## Boundaries
- Always: Write tests, run tests, follow naming conventions, use conventional commits.
- Ask first: Database migrations, adding new dependencies, large refactoring, changing shared types.
- Never: Commit secrets, edit lock files, delete tests, push to main directly.

For existing projects:

Before writing CLAUDE.md, run a quick codebase scan:

# Discover patterns: what test framework, what naming style, what build tool
find . -name "*.test.*" | head -5
cat package.json | jq '.scripts'
ls src/ 2>/dev/null || ls app/ 2>/dev/null

Use the discovered patterns to fill in the HOW section. Delete any generic placeholder content that /init generated. Every line should be repo-specific truth.


Step 2: Path-Specific Rules

AI Instructions:

  1. Create the .claude/rules/ directory.
  2. Ask the user: "What are the main areas of this project that have specific conventions?" (e.g., tests, API layer, database, frontend components)
  3. Create one rule file per area. Each file uses YAML frontmatter with a paths array so the rules only load when Claude edits matching files.
mkdir -p .claude/rules

Example: testing.md

---
paths: ["**/*.test.*", "**/*.spec.*", "**/tests/**"]
---

## Testing Conventions

- Use AAA pattern: Arrange, Act, Assert. Add a blank line between each section.
- Prefer real database connections over mocks for integration tests.
- Unit test file names mirror the source file: `auth.ts` -> `auth.test.ts`.
- Each test describes one behavior. Test name format: "should [behavior] when [condition]".
- Never use `it.only` or `describe.only` in committed code.

Example: api.md

---
paths: ["**/api/**", "**/routes/**", "**/*.controller.*"]
---

## API Conventions

- All endpoints return `{ data, error, meta }` shape.
- Validate input with Zod before any business logic.
- Never put business logic in route handlers. Delegate to service layer.
- All API errors must use the shared `AppError` class.
- Rate limiting is applied at the gateway, not per-endpoint.

How path-specific rules save context

These files are not loaded into context permanently. They only load when Claude is editing a file that matches the path pattern. A terraform/**/* rule never touches your context when you are working on frontend code.

This is "progressive disclosure" - the right rules appear at the right time.


Step 3: Context Window Management

AI Instructions: Explain each rule to the user and confirm they understand it before proceeding.

Context window management is not optional. It is the difference between consistent, high-quality output and an AI that forgets its own instructions mid-task.

The Core Rules

1. Monitor the HUD continuously

Claude Code's terminal status bar shows a context fill bar. Watch it at all times. It also shows: active model, token count, session cost, cache hit rate, and current permission mode.

2. Use /compact proactively at 40-50%

Do not wait until the bar hits 70% or 80%. The degradation is not sudden - it is gradual. By the time you notice quality dropping, you have already lost 20-30% of Claude's effectiveness. Run /compact early.

3. Use /clear when switching tasks

When a task is complete or the topic changes, run /clear to start a fresh session. CLAUDE.md and .claude/rules/ reload automatically. You do not lose project context.

4. One conversation = one task (strict rule)

Do not combine: "fix the auth bug AND add the new endpoint AND write the tests" in a single conversation. Each task gets its own session. This is not inconvenient - CLAUDE.md means Claude already knows your project. A new session does not start from zero.

5. Information ordering matters

Put the most critical information first in any long message. AI models process the beginning and end of inputs well, but miss things buried in the middle. When sharing an error log, lead with: "null pointer in auth.ts line 42, log below" - not with 500 lines of log.

6. Red flags that mean context is degraded

  • Claude repeats itself or contradicts earlier output
  • Claude edits the wrong file
  • Claude ignores a rule you set in CLAUDE.md
  • Claude asks for something you already provided

When you see these, stop. Run /compact or /clear and re-orient.


Step 4: Install 3 Essential Hooks

AI Instructions:

  1. Check if .claude/settings.local.json exists.
  2. If it exists, read it and merge the hooks below with any existing configuration.
  3. If it does not exist, create it with the full configuration below.
  4. Tell the user what each hook does and why it is safe to install.

Why hooks matter

Hooks are deterministic safety nets. Unlike instructions in CLAUDE.md (which Claude might occasionally miss), hooks run as system-level checks that cannot be bypassed. They catch mistakes before they become problems.

Start with 3. Each hook adds a small context cost. 3-5 well-chosen hooks beat 20 mediocre ones.

The Configuration

Create or update .claude/settings.local.json:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "bash -c 'cmd=$(echo \"$CLAUDE_TOOL_INPUT\" | jq -r \".command // empty\" 2>/dev/null); if echo \"$cmd\" | grep -qE \"git push --force|git reset --hard|git checkout \\\\.|git clean -f\"; then echo \"BLOCKED: Destructive git command detected. Use safer alternatives.\"; exit 1; fi'"
          }
        ]
      },
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "bash -c 'cmd=$(echo \"$CLAUDE_TOOL_INPUT\" | jq -r \".command // empty\" 2>/dev/null); if echo \"$cmd\" | grep -q \"git commit\"; then msg=$(echo \"$cmd\" | grep -oP \"(?<=-m \\\")[^\\\"]+(?=\\\")\"); if [ -n \"$msg\" ] && ! echo \"$msg\" | grep -qP \"^(feat|fix|docs|style|refactor|perf|test|chore|ci|build)(\\\\([^)]+\\\\))?: .+\"; then echo \"BLOCKED: Commit message must follow conventional format: feat(scope): description\"; echo \"Examples: feat(auth): add JWT validation, fix(api): handle null response\"; exit 1; fi; fi'"
          }
        ]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "bash -c 'file=$(echo \"$CLAUDE_TOOL_INPUT\" | jq -r \".file_path // .path // empty\" 2>/dev/null); if [ -z \"$file\" ] || [ ! -f \"$file\" ]; then exit 0; fi; warnings=\"\"; if echo \"$file\" | grep -qE \"\\.(ts|tsx)$\"; then if grep -n \": any\" \"$file\" 2>/dev/null | grep -v \"// claude-ok\" | head -3; then warnings=\"$warnings\\nWARNING: Found `: any` type usage in $file\"; fi; if grep -n \"console\\.log\" \"$file\" 2>/dev/null | grep -v \"// claude-ok\" | head -3; then warnings=\"$warnings\\nWARNING: Found console.log in $file\"; fi; if grep -n \"@ts-ignore\" \"$file\" 2>/dev/null | head -3; then warnings=\"$warnings\\nWARNING: Found @ts-ignore in $file\"; fi; fi; if [ -n \"$warnings\" ]; then echo -e \"Convention Guard:$warnings\"; fi'"
          }
        ]
      }
    ]
  }
}

Hook 1: Dangerous Git Protection (PreToolUse:Bash)

Blocks: git push --force, git reset --hard, git checkout ., git clean -f

Claude occasionally reaches for destructive git commands when trying to "quickly fix" a messy state. This hook stops that before any damage is done.

Hook 2: Conventional Commits (PreToolUse:Bash)

Enforces: feat(scope): description format for all commit messages.

Without this, Claude produces messages like "fix stuff" or "update code." Conventional commits enable automated changelogs, semantic versioning, and readable git history.

Valid prefixes: feat, fix, docs, style, refactor, perf, test, chore, ci, build

Hook 3: Convention Guard (PostToolUse:Edit|Write)

Checks every TypeScript/TSX file for: : any type usage, console.log, @ts-ignore

Customize this hook for your project's specific conventions. Add // claude-ok on a line to suppress a specific warning when it is intentional.

For non-TypeScript projects: Replace the TypeScript checks with your language's equivalent rules. Python: no print(), no # type: ignore. Go: no interface{}, proper error handling.


Step 5: Memory Layout

AI Instructions: Show this table to the user and explain when to use each layer.

Layer Location Scope Committed to git?
Team shared ./CLAUDE.md This project, all team members Yes
Modular rules .claude/rules/*.md This project, path-scoped Yes
Personal global ~/.claude/CLAUDE.md All projects on this machine No
Personal local ./CLAUDE.local.md This project, your machine only No

When to use each layer

./CLAUDE.md - Team agreements. Architecture decisions. Commands everyone needs. Anything a new team member should know on day one.

.claude/rules/*.md - Detailed conventions that are too long for CLAUDE.md. Path-scoped rules. Domain-specific patterns (API, testing, database).

~/.claude/CLAUDE.md - Your personal preferences across all projects. Communication style. Tools you always want available. Habits the AI should know about you.

./CLAUDE.local.md - Your local overrides for this project. A different database URL. A personal workflow that differs from the team's. Add to .gitignore.

Iterative improvement process

The best CLAUDE.md is built incrementally, not written perfectly on day one:

  1. Run /init to generate a starting point
  2. Delete all generic content that does not apply to your project
  3. When Claude does something wrong, add a rule to prevent it
  4. When a section grows too long, move it to .claude/rules/
  5. Use # in the chat to send a one-time instruction without adding it to CLAUDE.md
  6. Run /clear when switching to a different task

Step 6: Install Core Tools (Optional)

AI Instructions: These tools are optional. Ask the user if they want to install them.

Speckit - Spec-Driven Development

Use Speckit when building features that touch 5 or more files, or when requirements are complex enough to need a written spec before coding begins.

npm install -g speckit
cd your-project
speckit init

Workflow:

  1. speckit specify - describe what you want to build
  2. speckit plan - generate a structured plan
  3. speckit tasks - break the plan into tasks
  4. speckit implement - implement task by task

When to use: New features with cross-cutting concerns. API design. Anything where you would normally write a design doc first.

When not to use: Small bug fixes. Single-file changes. Quick refactors.

OpenContext - Cross-Project Memory

Lets Claude remember decisions, patterns, and knowledge across different projects.

npm install -g opencontext

Add to your MCP config (~/.claude/mcp.json or project .claude/mcp.json):

{
  "mcpServers": {
    "opencontext": {
      "command": "opencontext",
      "args": ["serve"]
    }
  }
}

When to use: If you work across multiple related projects and want shared architectural knowledge. If you want Claude to remember decisions made in Project A when working in Project B.


Step 7: Plan-Execute-Verify Basics

AI Instructions: Walk the user through each concept. Do not skip the Verify step - it is the one most users skip.

Permission Modes (toggle with Shift+Tab)

Mode Behavior When to use
Normal Asks approval for every file edit and command Unfamiliar tasks, sensitive areas
Auto-Accept Approves file edits automatically, still asks for Bash Most daily work once you trust the plan
Bypass Approves everything automatically Well-defined tasks in a trusted context only

Never use Bypass mode (--dangerously-skip-permissions) in your actual development environment. Reserve it for isolated containers or disposable VMs.

Plan Mode

Before any large change, put Claude into Plan Mode:

> /plan [describe what you want]

In Plan Mode, Claude analyzes the codebase and describes what it will do - without making any changes. Review the plan. If it looks right, approve and switch to Auto-Accept to execute.

Use Plan Mode when: you are about to touch more than 3 files, you are refactoring shared code, you are not sure how Claude will approach a problem.

The Plan -> Execute -> Verify Loop

1. PLAN    → Describe intent, review Claude's approach, confirm scope
2. EXECUTE → Run with Auto-Accept, watch the context bar
3. VERIFY  → Run tests, check output, review diffs, confirm intent was achieved

Verification is observing outcomes, not ticking "steps completed." Run your test suite. Check the actual output. Read the diff. If Claude says "all tests pass," run the tests yourself and confirm.

Providing explicit verification criteria in your request gets better results:

  • Weak: "Write tests for the auth module"
  • Strong: "Write tests for the auth module that cover: valid login, invalid password, expired token, and rate limiting. Run them with npm test src/auth and confirm all pass."

Step 8: Verification

AI Instructions: Run each check and report the results to the user. Do not skip any check.

# Check 1: CLAUDE.md exists and is under 100 lines
wc -l CLAUDE.md

# Check 2: .claude/rules/ directory exists
ls -la .claude/rules/

# Check 3: Hooks are installed
cat .claude/settings.local.json | jq '.hooks | keys'

# Check 4: Hooks are syntactically valid JSON
cat .claude/settings.local.json | jq . > /dev/null && echo "JSON valid" || echo "JSON INVALID - fix syntax"

# Check 5: CLAUDE.md has all required sections
grep -c "## What\|## Why\|## How\|## Don't\|## Boundaries" CLAUDE.md

# Check 6: No secrets in CLAUDE.md
grep -iE "(password|secret|api_key|token|private_key)" CLAUDE.md && echo "WARNING: Possible secret found" || echo "No secrets detected"

Expected results:

  • CLAUDE.md: under 100 lines, 5 section headers found, no secrets
  • .claude/rules/: directory exists with at least one .md file
  • Hooks: JSON valid, contains PreToolUse and PostToolUse keys

Summary

What you now have:

Component Purpose
CLAUDE.md Project identity, decisions, rules - under 100 lines
.claude/rules/*.md Path-scoped detailed conventions
.claude/settings.local.json 3 hooks: git safety, conventional commits, convention guard
Context management habits /compact at 40-50%, /clear between tasks, one task per session
Plan-Execute-Verify loop Deliberate workflow with verification as a real step

Level 1 Complete.

Next: claude-setup-intermediate.md covers custom agents, multi-agent orchestration, model routing, and advanced hook patterns.

For the principles behind every step in this guide, read ai-playbook.md.

Claude Code Setup: Intermediate (Level 2)

Agents, multi-agent orchestration, model routing, and skills Level: Intermediate Prerequisite: Complete claude-setup-essentials.md first Next: See claude-setup-advanced.md for cross-model orchestration and self-learning


Step 1: Custom Agents

Why Custom Agents Matter

General Claude handles everything adequately. A specialized agent handles its domain consistently and correctly.

The difference in practice:

Aspect General Claude Custom Agent
Domain knowledge Generic Domain-specific (OWASP, patterns, your rules)
Tool access All tools Constrained to what makes sense
Context loaded Everything Only relevant info
Approach Varies each time Consistent checklist every time

A security reviewer that always checks OWASP Top 10 beats a general Claude that sometimes checks OWASP Top 10.

Essential 2 Agents (Create These First)

AI Instructions:

  1. Create the .claude/agents/ directory if it does not exist
  2. Create code-reviewer.md inside it
  3. Create debugger.md inside it

code-reviewer.md

---
name: code-reviewer
description: Reviews code for security, quality, performance, and best practices. Use for any code review before committing or opening a PR.
model: sonnet
---

You are a thorough code reviewer. For every review:

**Security (OWASP Top 10)**
- Injection vulnerabilities (SQL, command, LDAP)
- Broken authentication or session management
- Sensitive data exposure (hardcoded secrets, unencrypted PII)
- Broken access control (missing authorization checks)
- Security misconfiguration (verbose errors, open CORS)
- XSS (unescaped user output)
- Insecure deserialization
- Using components with known vulnerabilities

**Code Quality**
- Single responsibility: each function/class has one reason to change
- No duplicated logic (DRY)
- Clear, intention-revealing names
- Functions under 30 lines where possible
- Error handling present and meaningful

**Performance**
- N+1 query patterns
- Missing indexes on queried fields
- Unbounded loops or recursion
- Synchronous calls that should be async
- Missing caching for expensive repeated operations

**Best Practices**
- Tests present for new logic
- No commented-out code
- No TODO/FIXME left without a ticket reference
- Logging at appropriate levels (not console.log in production paths)

**Output format:**

Rate each finding: `critical` / `high` / `medium` / `low`

For each finding include:
- Location (file:line)
- What the issue is
- Why it matters
- Specific fix

End with a summary: overall verdict (approve / request changes / needs discussion) and the top 3 most important changes if any.

debugger.md

---
name: debugger
description: Diagnoses errors, identifies root causes, examines logs and stack traces. Does NOT implement fixes - user approves before any change is made.
model: sonnet
tools: Read, Bash
---

You are a systematic debugger. Your role is diagnosis only - you identify the root cause and propose a fix, but you do NOT implement it without explicit user approval.

**Diagnosis process:**

1. Read the error message and stack trace in full
2. Identify the exact line and file where the failure originates
3. Read the relevant source files around that location
4. Check recent git history for that file (`git log -10 --oneline -- <file>`)
5. Search for similar patterns elsewhere in the codebase
6. Form a hypothesis about the root cause
7. Verify the hypothesis by reading any related files

**Output format:**

Root Cause: [One clear sentence describing what is actually wrong]

Evidence:

  • [File:line] [what you observed]
  • [File:line] [what you observed]

Why this causes the error: [Short explanation of the causal chain]

Proposed fix: [Exact code change needed, with before/after]

Confidence: high / medium / low If low, explain what additional info would confirm the diagnosis.


**Boundaries:**
- You read files and run read-only bash commands (git log, grep, cat)
- You do NOT edit files
- You do NOT run tests or builds
- You present the fix and wait for user approval

**Tool restrictions** (allowed-tools: Read, Bash):
- Bash is limited to: git log, git diff, git show, grep, find, cat, ls

3-Layer Boundaries for Each Agent

Define boundaries explicitly in each agent's system prompt:

Always (no approval needed):
- Read any source file
- Search for patterns across the codebase
- Generate reports, summaries, analysis

Ask first (explain intent, wait for approval):
- Implement a fix
- Create a new file
- Modify configuration

Never (hard stops):
- Delete files
- Expose secrets or credentials
- Touch production configuration
- Commit or push changes

These boundaries prevent agents from taking destructive actions during automated workflows.

Adding Project-Specific Agents Over Time

As you work on a codebase, add agents that encode knowledge specific to it:

---
name: architecture-reviewer
description: Reviews changes against this project's architectural constraints. Checks layer violations, dependency direction, and module boundaries.
model: sonnet
---

[Your project's specific architecture rules here]

Other agents to build over time: performance-analyzer, migration-assistant, api-contract-reviewer.

The value compounds: each agent encodes knowledge you would otherwise have to re-explain every session.


Step 2: Multi-Agent Work

Subagents: The Context Advantage

The key property: each subagent starts with an independent, clean context window.

If your main session is at 40% context (normal after an hour of work), a spawned subagent starts at 0%. It can do a full deep review without context pressure affecting quality.

The model: main session coordinates, subagents do work, results come back.

When to use subagents:

  • One-off tasks: file search, quick code review, format checking
  • Tasks where you need the result before continuing
  • Isolated analysis that should not pollute the main session's context
  • Parallel work on independent parts of the codebase

Example:

User: Review the auth module for security issues

Claude: [spawns security-reviewer subagent with clean context]
        [subagent reads auth files, applies OWASP checklist, returns findings]
        [main session presents findings without having loaded all those files]

Teams: Persistent Coordination

Teams are built into Claude Code - no installation required.

Team members are persistent agents that communicate via message inbox and share a task list. Unlike subagents (which return a result and terminate), team members keep running, coordinate with each other, and work through a queue of tasks.

When to use teams:

  • Comprehensive PR review (security + quality + performance + test coverage in parallel)
  • Large feature development (backend + frontend + tests developed simultaneously)
  • Complex refactoring across multiple modules at the same time
  • Any work where you want 3+ agents running in parallel with coordination

Practical example - comprehensive code review:

Team Lead (you): Coordinates, aggregates findings, presents summary

Teammate 1 - Security Reviewer:
  Checks OWASP Top 10, input validation, authentication, authorization

Teammate 2 - Quality Reviewer:
  Checks patterns, SOLID principles, naming, complexity, duplication

Teammate 3 - Performance Analyzer:
  Checks N+1 queries, memory leaks, missing caching, algorithmic complexity

Teammate 4 - Test Coverage Reviewer:
  Checks missing tests, edge cases, test quality, coverage gaps

Each teammate works in parallel. Total review time: roughly the time of the slowest reviewer, not the sum of all four.

Worktree Isolation

For parallel work that involves editing files, use isolation: worktree. Each teammate works in an isolated working directory - changes do not conflict.

Essential for:

  • Parallel refactoring across modules
  • Large feature development where backend and frontend are built simultaneously
  • Any case where multiple agents edit different files at the same time

Without worktree isolation, parallel agents editing different files in the same directory can produce unexpected conflicts or race conditions.

The Attention Dilution Problem

When a single agent reviews many files sequentially, quality degrades predictably: first files get deep attention, middle files get surface attention, last files get slightly more attention again (recency effect).

For thorough analysis across many files:

  1. Spawn separate subagents per file or per logical group
  2. Each subagent gives full attention to its scope
  3. A final subagent analyzes cross-file connections and patterns

This eliminates the dilution effect and gives consistent depth across the entire codebase.

Session Branching

fork_session lets you try different approaches from the same analysis baseline - like creating two git branches from the same commit.

Use case: you have analyzed a problem deeply and want to explore two different solutions without contaminating one analysis with the other. Fork the session at the decision point and explore each path independently.


Step 3: Model Routing

Three Models, Three Purposes

Model Strengths Relative Cost Use For
Haiku Fast, low cost $ File search, format checks, quick questions, simple lookups
Sonnet Balanced speed and quality $$ DEFAULT: implementation, debugging, code review, most tasks
Opus Deep reasoning, complex analysis $$$ Architecture decisions, hard bugs, large refactoring, security audits

The Strategy

  • Sonnet is your default. It handles the vast majority of work well.
  • Opus only when genuinely needed. Deep architectural analysis, a bug that has resisted multiple Sonnet attempts, security review of a critical system.
  • Haiku for simple tasks. Any task that is essentially "find this", "check this format", or "answer this quick question."

Getting this right reduces daily cost by 60-70% with no quality loss on tasks where Haiku or Sonnet is appropriate.

Model Selection for Subagents

// Codebase exploration - fast and cheap
Task({
  subagent_type: "Explore",
  description: "Find all authentication files",
  prompt: "List every file related to authentication and authorization",
  model: "haiku"
})

// Standard implementation - balanced
Task({
  subagent_type: "general-purpose",
  description: "Add input validation to login endpoint",
  prompt: "Add Zod validation to the login route in src/routes/auth.ts",
  model: "sonnet"
})

// Architecture analysis - deep reasoning
Task({
  subagent_type: "general-purpose",
  description: "Evaluate caching strategy",
  prompt: "Analyze the current caching approach and recommend improvements for the high-traffic user profile endpoint",
  model: "opus"
})

Routing Rules in Practice

Ask yourself before spawning an agent:

  1. Does this require deep reasoning or just pattern matching? (Reasoning -> Opus, Pattern -> Haiku/Sonnet)
  2. Is this a search/lookup task? (Yes -> Haiku)
  3. Is this writing code or doing a review? (Yes -> Sonnet default, Opus if architectural)
  4. Has this task already failed with a cheaper model? (Yes -> step up one tier)

Start cheap, step up when needed - not the reverse.


Step 4: Skills Strategy

Understanding Skills

A skill is reusable knowledge and workflows, invoked by keyword in your main conversation. It runs in the main conversation context, not as a separate agent instance.

The distinction that matters:

  • Agent: a task executor with its own context, tools, and lifecycle
  • Skill: a knowledge source that runs in your current conversation and enriches how Claude responds

Use agents when you need isolation, parallelism, or tool constraints. Use skills when you want to inject reusable workflow instructions or domain knowledge into the current session.

Key Frontmatter Options

---
name: commit
description: Creates a conventional commit with proper format
context: fork          # skill runs in separate context - prevents heavy output from polluting main session
allowed-tools: Bash    # restricts tools this skill can invoke
argument-hint: "commit message scope"  # what to ask user when called without arguments
---

context: fork is important for skills that produce large output - without it, the output stays in your main session's context window and crowds out other content.

Valuable vs Non-Valuable Skills

Valuable skills - automate real workflows:

---
name: commit
description: Stages changes, writes a conventional commit message, verifies hooks pass
context: fork
allowed-tools: Bash, Read
---
1. Run git status and git diff to understand what changed
2. Write a conventional commit message (type(scope): description)
3. Stage the relevant files
4. Run the commit and report the result
---
name: code-review
description: Triggers a full code review using the code-reviewer agent
context: fork
allowed-tools: Read
---
Spawn the code-reviewer agent on the files passed as arguments, or on git diff HEAD if no files specified.

Non-valuable skills - just text or instructions:

If the skill body is just "remember to check X, Y, Z", it belongs in .claude/rules/ as a rules file, not as a skill. Rules files are always active; skills are only active when invoked.

Putting passive instructions in skills means they only apply when explicitly triggered - the opposite of what you want.

Context Cost Warning

Every active skill loads into context at session start. This happens before you type a single word.

Approximate cost:

  • 20 active skills x 500 tokens average = 10,000 tokens consumed before the session does anything
  • On a 200,000 token context window, that is 5% gone on startup

Keep skill count reasonable:

  • Enable/disable per project in .claude/settings.json
  • Monthly review: deactivate skills you have not used in 30 days
  • If a skill is text-only instructions, move it to .claude/rules/

Keyword Mapping (Critical for Discoverability)

Claude triggers skills when it recognizes relevant keywords. If your skill's description does not include the vocabulary users naturally use, the skill never fires.

Be explicit about trigger terms:

---
name: performance-optimization
description: Analyzes and fixes performance issues. Triggers on: slow, N+1, cache miss, memory leak, latency, high response time, profiling, query optimization, bottleneck
---

Without explicit keyword coverage, a perfectly written skill sits unused because the trigger words never match.

Test discoverability: ask Claude to handle a task that your skill should cover. If it does not invoke the skill, update the description to include the vocabulary you actually used.


Step 5: Deep Research Workflow

When to Use Deep Research

Before making a significant technical decision, run structured research first:

  • Choosing a new technology or framework
  • Complex architectural decisions (event sourcing vs CRUD, microservices vs monolith)
  • Performance optimization strategy selection
  • Security approach determination
  • Strategy before a major refactoring

Starting to code without this research means you discover the constraints after you have already committed to a direction.

5-Step Process

Step 1: Start a conversation - ask the AI to ask you questions

I need to decide on a caching strategy for a high-traffic API.
Ask me 10-15 questions to understand the context before you recommend anything.

Step 2: Answer the AI's questions

These questions surface the constraints you take for granted: traffic patterns, existing infrastructure, team familiarity, consistency requirements, budget. This context is what makes the research relevant to your situation.

Step 3: Generate a deep research prompt from the conversation

Based on everything I just told you, write a deep research prompt
I can send to an AI research tool to get comprehensive analysis
of my options with my specific constraints.

Step 4: Send the generated prompt to a deep research mode

Claude.ai deep research, ChatGPT deep research, Gemini deep research - any tool that does multi-step web research and synthesis.

Step 5: Bring the results back to your Claude Code session

Paste the research output and continue:

Here is the research on caching strategies. Given what we discussed,
which approach fits our constraints? What should I implement first?

This five-step process takes 20-30 minutes and eliminates the "we chose the wrong approach" discovery two weeks into implementation.


Step 6: Session Memory

Project Memory

Project memory persists between sessions. It stores information that is always relevant to working on this codebase:

  • Tech stack and versions
  • Architectural decisions and their rationale
  • Team conventions (naming, patterns, file organization)
  • Known constraints and non-obvious context
  • Important decisions made and why

Read it at the start of each session. Update it at the end of any session where you made a significant decision or discovered important context.

What to store:

Tech Stack:
- Node.js 22, TypeScript 5.4
- PostgreSQL with Drizzle ORM
- Redis for session storage

Architecture:
- Clean Architecture: domain / application / infrastructure / presentation
- No direct database calls from route handlers - must go through repository layer
- All external API calls go through src/integrations/, never inline

Conventions:
- Feature flags use LaunchDarkly, never environment variables
- All dates stored as UTC, converted at the presentation layer
- Error codes defined in src/errors/codes.ts, never use raw strings

Known Constraints:
- The payments module has a circular dependency in billing.service.ts - do not refactor without reading CONCERNS.md
- The legacy import pipeline in src/jobs/ uses a different error handling pattern intentionally

Notepad

Notepad is session-scoped working memory. Use it for the current task's context: what you are doing, what you have tried, what is blocked.

Unlike project memory (which persists indefinitely), notepad content is temporary - it helps you stay oriented within a session and is not meant to carry over.

The Principle

Whatever tool you use - OMC project memory, a SCRATCHPAD.md file, session notes - the workflow is the same:

  1. Read at session start: "What do I need to know before I touch this codebase?"
  2. Update at session end: "What did I learn that future-me needs to know?"

The specific tool matters less than the habit.


Verification

After completing each step, verify:

Agents:

  • Run /agents or ask Claude to list available agents
  • Invoke each agent on a real task and confirm it respects its tool constraints
  • Confirm the debugger asks for approval before suggesting changes

Model routing:

  • Spawn a Haiku subagent for a simple search task and confirm it completes correctly
  • Spawn an Opus agent for an architectural question and compare depth to Sonnet output
  • Check token usage in settings to confirm cost reduction over a week

Skills:

  • List active skills and confirm count is reasonable (under 15 for most projects)
  • Trigger each skill using the natural language you would actually use
  • Confirm no text-only skills exist (move those to .claude/rules/)

Session memory:

  • Write one entry to project memory and verify it persists after /clear
  • Confirm your session start habit: read project memory before first task

Level 2 Complete.

Next: claude-setup-advanced.md - cross-model orchestration, self-learning systems, and production-grade multi-agent pipelines.

Frameworks Guide: Optional but Highly Effective

These frameworks are NOT required for the setup. They are recommended tools that can significantly enhance your AI-powered development workflow. Set them up AFTER completing the core setup levels.

When to explore: After completing at least Level 1 (Essentials) from claude-setup-essentials.md.


When to Use What

Need Recommended Framework Why
Structured project management with autonomous execution GSD-2 Milestone/Slice/Task hierarchy, fresh context per task
Multi-agent orchestration within Claude Code oh-my-claudecode 30+ agents, team mode, model routing
Vendor-agnostic AI coding (use any provider) Pi 20+ providers, use existing subscriptions
All of the above Mix and match They don't conflict

Comparison

Feature GSD-2 OMC Pi
Type Standalone CLI Claude Code plugin Standalone CLI
Multi-provider Yes (20+) Claude only (+ MCP) Yes (20+)
Multi-agent Scout/Researcher/Worker 30+ specialized agents Extensions
Context management Fresh per task (automatic) Manual (/compact, /clear) Session branching
Autonomous mode /gsd auto autopilot, ralph Non-interactive
Cost tracking Built-in per task HUD statusline -
Git strategy Worktree + squash merge Worktree isolation -
Learning Skill auto-install Claudeception Prompt Templates

Article Principles Automated

Article Principle GSD-2 OMC Pi
Context management (Section 3) Auto (fresh per task) HUD + manual Session branching
Plan-Execute-Verify (Section 5) Built-in pipeline Team staged pipeline -
Hooks (Section 6) - PreToolUse/PostToolUse -
Custom agents (Section 7) Scout/Researcher/Worker 30+ agents Extensions
Multi-agent (Section 8) Task delegation Team mode -
Model routing (Section 9) Provider config Smart routing Model cycling
Cross-model (Section 10) Multi-provider native Codex/Gemini workers Multi-provider native
Self-learning (Section 13) Skill auto-install Claudeception -
Project lifecycle (Section 17) Full lifecycle managed Staged pipeline -

Framework 1: GSD-2 (Get Shit Done v2)

What it is: A standalone CLI that orchestrates AI agent sessions for structured project development. It solves the context rot problem by enforcing a strict rule: 1 task = 1 context window.

Repository: https://github.com/gsd-build/gsd-2

The Core Problem It Solves

Long AI sessions accumulate context that degrades model performance. GSD-2 enforces a Milestone -> Slice -> Task hierarchy where each task runs in a fresh context window. You get consistent quality across large projects because the model never starts a task with a polluted context.

Requirements

  • Node.js >= 20.6.0
  • Git
  • Any LLM provider (Claude, GPT, Gemini, Mistral, Groq, etc.)

Installation

npm install -g gsd-pi

Basic Setup

# In your project directory
gsd init

# GSD creates PROJECT.md, DECISIONS.md, STATE.md
# Edit PROJECT.md to describe your project goals

How to Use

# Start a new project or feature
gsd start "Build authentication system"

# GSD breaks this into:
# Milestone 1: Research and design
#   Slice 1.1: Analyze requirements
#     Task 1.1.1: Review existing auth code  <- fresh context
#     Task 1.1.2: Document API contracts     <- fresh context
#   Slice 1.2: Implementation
#     Task 1.2.1: Implement JWT validation   <- fresh context

# Fully autonomous mode
gsd auto

# Check progress
gsd status

# Resume after interruption (crash recovery built-in)
gsd resume

Bundled Agents

Agent Role Speed
Scout Fast codebase recon Fast (haiku-class)
Researcher Web research and documentation Medium
Worker General code execution Standard

Key Features

  • Fresh context per task: Eliminates context rot automatically
  • Pipeline automation: Research -> Plan -> Execute -> Verify runs without manual intervention
  • Context engineering: PROJECT.md, DECISIONS.md, STATE.md maintain project memory across sessions
  • Git worktree isolation: Each task runs in an isolated worktree, merged via squash
  • Cost tracking: Per-task and per-session cost visibility
  • Stuck detection: Automatically detects when an agent is spinning and intervenes
  • 20+ LLM providers: Not locked to Claude

AI Instructions

# Ask AI to run GSD autonomously
"Run gsd auto on this feature. Let it complete the full pipeline."

# Ask AI to create a GSD task manually
"Create a GSD task for implementing the payment webhook handler. Keep it scoped to a single context window."

# Check and resume
"Check gsd status and resume any stuck tasks."

Framework 2: oh-my-claudecode (OMC)

What it is: A Claude Code plugin that adds multi-agent orchestration, 30+ specialized agents, smart model routing, and a team-based staged execution pipeline.

Repository: https://github.com/yeachan-heo/oh-my-claudecode

The Core Problem It Solves

Claude Code is a single-agent tool by default. OMC adds a coordination layer so you can run parallel specialized agents (security reviewer, performance reviewer, debugger, architect) that work together on the same codebase without interfering with each other.

Requirements

  • Claude Code installed
  • For team mode: CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1 in ~/.claude/settings.json

Installation

Inside Claude Code:

/plugin marketplace add https://github.com/Yeachan-Heo/oh-my-claudecode
/plugin install oh-my-claudecode
/omc-setup

Enable team mode in ~/.claude/settings.json:

{
  "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1"
}

Team Staged Pipeline

The core workflow runs automatically when you say "team" or "autopilot":

team-plan -> team-prd -> team-exec -> team-verify -> team-fix (loop)

Each stage has a specific purpose:

  • team-plan: Decompose the request into tasks
  • team-prd: Define acceptance criteria
  • team-exec: Parallel agent execution
  • team-verify: Validate outputs
  • team-fix: Fix failures and re-verify

Magic Keywords

Keyword Behavior
autopilot Full autonomous execution from idea to working code
ralph Persistent loop that does not stop until done
ulw or ultrawork Maximum parallelism, all agents run simultaneously
ralplan Iterative planning with Planner, Architect, Critic until consensus
eco or ecomode Token-efficient mode using smaller models

Specialized Agents (30+)

Execution: executor, deep-executor, debugger, build-fixer
Analysis:  explore, analyst, planner, architect
Review:    code-reviewer, security-reviewer, quality-reviewer, api-reviewer, performance-reviewer, style-reviewer
Domain:    test-engineer, designer, writer, dependency-expert, scientist
Product:   product-manager, ux-researcher, information-architect, product-analyst

Smart Model Routing

OMC automatically routes tasks to the right model based on complexity:

  • haiku: Quick lookups, lightweight scans (cheapest)
  • sonnet: Standard implementation, debugging, reviews
  • opus: Architecture, deep analysis, complex refactors (most capable)

This typically saves 30-50% on token costs compared to always using the same model.

How to Use

# Full autonomous execution
"autopilot: build a user authentication module with JWT and refresh tokens"

# Parallel code review
"review code: run security, performance, and quality reviewers in parallel"

# Planning with consensus
"ralplan: design the database schema for a multi-tenant SaaS application"

# Keep working until complete
"ralph: refactor the entire payment module to use the new SDK"

# Real-time metrics
/hud

Claudeception (Self-Learning)

OMC can learn new skills from conversations and save them for future sessions. When you solve a problem with a specific pattern, you can capture it:

"Save this debugging pattern as a skill called 'diagnose-memory-leak'"

Future sessions can invoke it directly:

/oh-my-claudecode:diagnose-memory-leak

AI Instructions

# Delegate to a specific agent
"Use the architect agent (opus) to design the API boundaries for this microservice."

# Parallel review
"Run code-reviewer, security-reviewer, and test-engineer in parallel on the auth module."

# Force a pipeline
"Team: implement user notifications. Run the full team pipeline."

Framework 3: Pi (pi-coding-agent)

What it is: A vendor-agnostic AI coding agent CLI. An alternative or complement to Claude Code that works with 20+ LLM providers, including your existing Claude Pro, ChatGPT Plus, and GitHub Copilot subscriptions.

Repository: https://github.com/badlogic/pi-mono

The Core Problem It Solves

You may already pay for Claude Pro, ChatGPT Plus, and GitHub Copilot. Pi lets you use ALL of them through a unified interface, cycling between models and using existing subscriptions instead of paying for additional API credits.

Requirements

  • Node.js
  • At least one LLM provider account

Installation

npm install -g @mariozechner/pi-coding-agent

Supported Providers (20+)

  • Anthropic (Claude Pro subscription or API)
  • OpenAI (ChatGPT Plus subscription or API)
  • Google (Gemini)
  • GitHub Copilot (use your existing subscription)
  • Mistral
  • Groq
  • Ollama (local models)
  • And more

Basic Setup

# Start Pi
pi

# Configure a provider
/config provider anthropic

# Or use with subscription (no API key needed for some providers)
/config provider copilot

Key Features

Model cycling: Define a list of models and cycle through them automatically:

/models claude-3-5-sonnet, gpt-4o, gemini-1.5-pro

Session branching: Fork a session at any point to explore different approaches without losing your main thread.

Session compaction: Summarize and compress context when it grows large (similar to Claude Code's /compact).

Non-interactive mode: Script Pi for automation:

pi -p "Review this code and suggest improvements" < myfile.ts

Pi Packages: Shareable extensions via npm or git:

pi package install pi-package-typescript-helpers

Prompt Templates: Save and reuse common prompts:

/template save "code-review" "Review this code for: 1) security issues 2) performance 3) maintainability"
/template use code-review

Skills: Extend Pi with custom capabilities via JavaScript extensions.

How to Use

# Standard interactive session
pi

# With a specific provider
pi --provider openai

# Non-interactive (pipe input)
echo "Explain this function" | pi -p

# Branch current session
/branch

# Compact context
/compact

# Switch model mid-session
/model gemini-1.5-pro

Scripting Example

#!/bin/bash
# Review all modified files in a PR
git diff --name-only HEAD~1 | while read file; do
  echo "Reviewing $file..."
  pi -p "Review $file for security issues" < "$file"
done

AI Instructions

# Use Pi for a cross-provider task
"Open Pi with the Copilot provider and use it to review the billing module."

# Model cycling task
"Configure Pi to cycle between Claude Sonnet and GPT-4o for this large refactor."

# Script Pi for batch processing
"Write a bash script that uses pi -p to generate docstrings for all functions in the src/ directory."

Using Multiple Frameworks Together

These three frameworks do not conflict. A realistic combined workflow:

  1. GSD-2 manages the project structure: milestones, slices, tasks with fresh context
  2. OMC runs inside each Claude Code session that GSD-2 spawns, providing specialized agents
  3. Pi handles tasks that benefit from a different provider (cost optimization, using existing subscriptions)

Example Combined Workflow

# GSD-2 starts a new feature
gsd start "Add real-time notifications"

# GSD-2 creates Task 1: Research
# Inside that task's Claude Code session, OMC kicks in:
# "ralplan: design WebSocket vs SSE architecture for notifications"

# GSD-2 creates Task 2: Implementation
# Inside that task's Claude Code session:
# "autopilot: implement the notification service based on the architecture decision"

# For cost-sensitive subtasks, switch to Pi with Copilot
# pi --provider copilot
# "Generate unit test stubs for the notification service"

# GSD-2 runs verify pipeline
# OMC verifier agent confirms completion

Troubleshooting

GSD-2 Stuck Detection Not Working

If GSD-2 does not detect a stuck task, check your provider configuration. Some providers have rate limits that cause silent delays rather than errors.

gsd config --show
gsd doctor

OMC Team Mode Not Available

Verify the environment variable is set:

# Check settings.json
cat ~/.claude/settings.json | grep AGENT_TEAMS

# Should output:
# "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1"

Pi Provider Authentication

For subscription-based providers (Copilot, ChatGPT Plus), Pi uses browser-based auth:

pi --provider copilot --auth
# Follow the browser prompt

Version: 1.0.0 Last Updated: 2026-03-16

Migration Guide: Claude Code <-> OpenCode

AI-driven migration with step-by-step instructions

Important: AI should execute these steps interactively, not run pre-made scripts

Estimated Time: ~3 hours (depends on number of MCP servers, agents, skills)

Why Migrate?

Motivation Direction Context
OAuth Restrictions CC -> OC Anthropic scoped OAuth exclusively to Claude Code (Jan 2026). Third-party tools must use API keys.
Cost Optimization CC -> OC OpenCode supports 75+ providers including free models. Mix expensive + cheap models.
Multi-agent CC -> OC oh-my-opencode: 6 parallel agents. Claude Code's swarm is newer.
Better UX CC -> OC Community: "OpenCode UX is MUCH nicer" + remote Workspaces.
Speed & Accuracy OC -> CC Claude Code is 2x faster, ~30% fewer tokens, better instruction following.
Enterprise Support OC -> CC Official Anthropic support, native GitHub/Linear integrations.
Using Both Sync Best of both: CC for speed, OC for multi-agent and model flexibility.

AI Tip: Ask "What's driving this migration?" to provide better guidance.

What Can Be Migrated

Feature Claude Code OpenCode Method
AI Playbook ai-playbook.md ai-playbook.md ✅ Provider-agnostic
Skills ~/.claude/skills/ ~/.claude/skills/ + ~/.config/opencode/skills/ ✅ Auto-shared
Speckit .specify/ .specify/ ✅ Auto-shared
Rules .claude/rules/ .opencode/rules/ Copy + rename dir
MCP Servers ~/.claude/mcp.json opencode.json Format conversion
Context CLAUDE.md CLAUDE.md or rules ✅ Compatible
Agents .claude/agents/ .opencode/agent/ Convert frontmatter
Commands .claude/commands/ .opencode/command/ Copy + rename dir
Hooks .claude/hooks/ Plugin system Different approach
GSD-2 Works with CC Works with OC ✅ Provider-agnostic
Pi Works with CC Works with OC ✅ Provider-agnostic

MCP Format Difference:

  • Claude Code: { "mcpServers": { "name": { "command": "x", "args": ["y"] } } }
  • OpenCode: { "mcp": { "name": { "type": "local", "command": ["x", "y"], "enabled": true } } }

Frameworks Note: GSD-2 and Pi are provider-agnostic frameworks. They work with both Claude Code and OpenCode without any changes. No migration needed for these.


Claude Code -> OpenCode

Pre-Flight

# AI: Check these before starting. Install any missing tools.
command -v claude &> /dev/null || echo "ERROR: Claude Code required. Install: curl -fsSL https://claude.ai/install.sh | bash"
command -v jq &> /dev/null || echo "WARNING: jq recommended. Install: brew install jq (macOS) / sudo apt-get install jq (Linux)"
command -v npm &> /dev/null || echo "WARNING: npm required for oh-my-opencode"

Step 1: Read ai-playbook.md

Before starting, read ai-playbook.md from the gist. It contains principles that apply to both tools and will guide configuration decisions during migration.

# If ai-playbook.md is already in your project, review it:
[ -f ai-playbook.md ] && echo "Found ai-playbook.md - review before proceeding"

Step 2: Install OpenCode

# Check if already installed
if ! command -v opencode &> /dev/null; then
  # Ask user: "Install OpenCode now?"
  curl -fsSL https://opencode.ai/install | bash
fi
opencode --version  # Verify

If install fails: reload shell (source ~/.zshrc), check docs at https://opencode.ai/docs

Step 3: Install oh-my-opencode

# Ask user: "What Claude subscription do you have?"
# Options: max20 / yes (pro) / no

# Example for Max20:
npx oh-my-opencode install --no-tui --claude=max20 --openai=no --gemini=no

# Verify:
[ -f ~/.config/opencode/oh-my-opencode.json ] && echo "Installed"

Step 4: Backup

if [ -f ~/.config/opencode/opencode.json ]; then
  cp ~/.config/opencode/opencode.json ~/.config/opencode/opencode.json.backup.$(date +%Y%m%d-%H%M%S)
  echo "Backup created"
fi

Step 5: Transfer MCP Servers

mkdir -p ~/.config/opencode

if [ -f ~/.claude/mcp.json ]; then
  if [ -f ~/.config/opencode/opencode.json ]; then
    # Merge into existing config (with format conversion)
    jq --slurpfile mcp ~/.claude/mcp.json \
       '.mcp = ($mcp[0].mcpServers | to_entries | map({
         key: .key, value: { type: "local", command: ([.value.command] + .value.args), enabled: true }
       }) | from_entries)' \
       ~/.config/opencode/opencode.json > ~/.config/opencode/opencode.json.tmp
    mv ~/.config/opencode/opencode.json.tmp ~/.config/opencode/opencode.json
  else
    # Create new config
    jq '{ mcp: (.mcpServers | to_entries | map({
      key: .key, value: { type: "local", command: ([.value.command] + .value.args), enabled: true }
    }) | from_entries) }' ~/.claude/mcp.json > ~/.config/opencode/opencode.json
  fi
  echo "MCP servers transferred"
  jq '.mcp | keys[]' ~/.config/opencode/opencode.json
fi

Step 6: Transfer Context (CLAUDE.md -> Rules)

mkdir -p ~/.config/opencode/rules

# Global context
[ -f ~/.claude/CLAUDE.md ] && cp ~/.claude/CLAUDE.md ~/.config/opencode/rules/global.md && echo "Global context"

# Project context
[ -f CLAUDE.md ] && cp CLAUDE.md ~/.config/opencode/rules/project-$(basename "$PWD").md && echo "Project context"

Step 7: Transfer Commands & Rules

# Commands (same format, different directory)
if [ -d .claude/commands/ ]; then
  mkdir -p .opencode/command
  cp .claude/commands/*.md .opencode/command/ 2>/dev/null && echo "Commands transferred"
fi

# Rules (same format, different directory)
if [ -d .claude/rules/ ]; then
  mkdir -p .opencode/rules
  cp .claude/rules/*.md .opencode/rules/ 2>/dev/null && echo "Rules transferred"
fi

Step 8: Check Skills & Speckit

# Skills: OpenCode scans ~/.claude/skills/ automatically — nothing to do!
[ -d ~/.claude/skills/ ] && echo "Skills accessible (shared directory)"

# Speckit: works with both tools — nothing to do!
command -v specify &> /dev/null && echo "Speckit available"

Step 9: Convert Custom Agents (If Exist)

if [ -d .claude/agents/ ] && ls .claude/agents/*.md &>/dev/null; then
  mkdir -p .opencode/agent

  for agent_file in .claude/agents/*.md; do
    agent_name=$(basename "$agent_file" .md)
    content=$(sed -n '/^---$/,/^---$/!p' "$agent_file" | sed '1d')

    cat > ".opencode/agent/$agent_name.md" << EOF
---
name: $agent_name
model: anthropic/claude-opus-4-5
tools: [read, grep, bash, edit, write]
---

$content
EOF
    echo "$agent_name converted"
  done
fi

Note: OpenCode agents support model and tools fields. Adjust per agent as needed.

Step 10: Hooks (Not Transferable)

if [ -d .claude/hooks/ ] && ls .claude/hooks/*.sh &>/dev/null; then
  echo "Found hooks in .claude/hooks/ — these cannot be auto-transferred"
  echo "  Claude Code: bash scripts | OpenCode: plugin system (event-driven)"
  echo "  Requires manual recreation as OpenCode plugin"
fi

Step 11: Authenticate & Verify

echo "Run: opencode auth login"
echo "  -> Select 'Anthropic' -> Complete OAuth in browser"

Verification:

command -v opencode >/dev/null && echo "OpenCode installed"
[ -f ~/.config/opencode/oh-my-opencode.json ] && echo "oh-my-opencode"
jq -e '.mcp' ~/.config/opencode/opencode.json >/dev/null 2>&1 && echo "MCP servers"
[ -d ~/.config/opencode/rules/ ] && echo "Rules/context"
[ -d ~/.claude/skills/ ] && echo "Skills (shared)"

OpenCode -> Claude Code

Pre-Flight

command -v opencode &> /dev/null || echo "ERROR: OpenCode required. Install: curl -fsSL https://opencode.ai/install | bash"
command -v jq &> /dev/null || echo "WARNING: jq recommended for MCP conversion"

Step 1: Read ai-playbook.md

Before starting, read ai-playbook.md from the gist. It contains principles that apply to both tools and will guide configuration decisions during migration.

# If ai-playbook.md is already in your project, review it:
[ -f ai-playbook.md ] && echo "Found ai-playbook.md - review before proceeding"

Step 2: Install Claude Code

if ! command -v claude &> /dev/null; then
  curl -fsSL https://claude.ai/install.sh | bash
fi
claude --version  # Verify

If install fails: reload shell (source ~/.zshrc), check docs at https://code.claude.com/docs

Step 3: Backup

[ -f ~/.claude/mcp.json ] && cp ~/.claude/mcp.json ~/.claude/mcp.json.backup.$(date +%Y%m%d-%H%M%S) && echo "Backed up mcp.json"
[ -f ~/.claude/CLAUDE.md ] && cp ~/.claude/CLAUDE.md ~/.claude/CLAUDE.md.backup.$(date +%Y%m%d-%H%M%S) && echo "Backed up CLAUDE.md"

Step 4: Transfer MCP Servers

if [ -f ~/.config/opencode/opencode.json ]; then
  mkdir -p ~/.claude

  jq '{ mcpServers: (.mcp | to_entries | map({
    key: .key, value: { command: .value.command[0], args: .value.command[1:] }
  }) | from_entries) }' ~/.config/opencode/opencode.json > ~/.claude/mcp.json

  echo "MCP servers transferred"
  jq '.mcpServers | keys[]' ~/.claude/mcp.json
fi

Step 5: Transfer Context (Rules -> CLAUDE.md)

# Global rule -> CLAUDE.md
[ -f ~/.config/opencode/rules/global.md ] && cp ~/.config/opencode/rules/global.md ~/.claude/CLAUDE.md && echo "Global context"

# Project rule -> CLAUDE.md
for rule in ~/.config/opencode/rules/project-*.md; do
  [ -f "$rule" ] && cp "$rule" CLAUDE.md && echo "Project context" && break
done

Step 6: Transfer Commands & Rules

# Commands
if [ -d .opencode/command/ ]; then
  mkdir -p .claude/commands
  cp .opencode/command/*.md .claude/commands/ 2>/dev/null && echo "Commands transferred"
fi

# Rules
if [ -d .opencode/rules/ ]; then
  mkdir -p .claude/rules
  cp .opencode/rules/*.md .claude/rules/ 2>/dev/null && echo "Rules transferred"
fi

Step 7: Migrate Skills

# Shared skills (already accessible): ~/.claude/skills/ — nothing to do!

# OpenCode-only skills need copying
if [ -d ~/.config/opencode/skills/ ] && [ "$(ls -A ~/.config/opencode/skills/ 2>/dev/null)" ]; then
  echo "Found OpenCode-only skills. Copying to shared directory..."
  mkdir -p ~/.claude/skills
  cp -r ~/.config/opencode/skills/* ~/.claude/skills/
  echo "Skills migrated to shared directory"
fi

Step 8: Convert Custom Agents (If Exist)

if [ -d .opencode/agent/ ] && ls .opencode/agent/*.md &>/dev/null; then
  mkdir -p .claude/agents

  for agent_file in .opencode/agent/*.md; do
    agent_name=$(basename "$agent_file" .md)
    content=$(sed -n '/^---$/,/^---$/!p' "$agent_file" | sed '1d')

    cat > ".claude/agents/$agent_name.md" << EOF
---
name: $agent_name
description: Converted from OpenCode agent
---

$content
EOF
    echo "$agent_name converted"
  done
fi

Note: OpenCode agents have model/tools config that doesn't map to Claude Code. Core instructions are preserved.

Step 9: Verify

command -v claude >/dev/null && echo "Claude Code installed"
[ -f ~/.claude/mcp.json ] && echo "MCP servers"
[ -f ~/.claude/CLAUDE.md ] && echo "Global CLAUDE.md"
[ -f CLAUDE.md ] && echo "Project CLAUDE.md"
[ -d ~/.claude/skills/ ] && echo "Skills"

Using Both Tools (Bidirectional Sync)

What's Shared Automatically

Directory Claude Code OpenCode
~/.claude/skills/ Yes Yes
.specify/ (Speckit) Yes Yes
CLAUDE.md (project root) Yes Yes
ai-playbook.md Yes Yes

Recommendation: Put shared skills in ~/.claude/skills/ (both tools read this).

What Needs Sync

Config Claude Code OpenCode
MCP Servers ~/.claude/mcp.json opencode.json -> .mcp
Global Context ~/.claude/CLAUDE.md rules/global.md
Project Context CLAUDE.md rules/project-*.md

Sync Commands (Run Before Switching Tools)

Sync MCP Servers

CLAUDE_MCP_TIME=$(stat -f %m ~/.claude/mcp.json 2>/dev/null || echo 0)
OPENCODE_MCP_TIME=$(stat -f %m ~/.config/opencode/opencode.json 2>/dev/null || echo 0)

if [ "$CLAUDE_MCP_TIME" -gt "$OPENCODE_MCP_TIME" ]; then
  echo "Claude Code -> OpenCode (MCP)..."
  jq --slurpfile mcp ~/.claude/mcp.json \
     '.mcp = ($mcp[0].mcpServers | to_entries | map({
       key: .key, value: { type: "local", command: ([.value.command] + .value.args), enabled: true }
     }) | from_entries)' \
     ~/.config/opencode/opencode.json > /tmp/oc.json && mv /tmp/oc.json ~/.config/opencode/opencode.json
elif [ "$OPENCODE_MCP_TIME" -gt "$CLAUDE_MCP_TIME" ]; then
  echo "OpenCode -> Claude Code (MCP)..."
  jq '{ mcpServers: (.mcp | to_entries | map({
    key: .key, value: { command: .value.command[0], args: .value.command[1:] }
  }) | from_entries) }' ~/.config/opencode/opencode.json > ~/.claude/mcp.json
else
  echo "MCP already in sync"
fi

Sync Global Context

CLAUDE_MD_TIME=$(stat -f %m ~/.claude/CLAUDE.md 2>/dev/null || echo 0)
OPENCODE_RULE_TIME=$(stat -f %m ~/.config/opencode/rules/global.md 2>/dev/null || echo 0)

if [ "$CLAUDE_MD_TIME" -gt "$OPENCODE_RULE_TIME" ]; then
  cp ~/.claude/CLAUDE.md ~/.config/opencode/rules/global.md && echo "CC -> OC (context)"
elif [ "$OPENCODE_RULE_TIME" -gt "$CLAUDE_MD_TIME" ]; then
  cp ~/.config/opencode/rules/global.md ~/.claude/CLAUDE.md && echo "OC -> CC (context)"
else
  echo "Context already in sync"
fi

Sync Project Context

PROJECT_CLAUDE_TIME=$(stat -f %m CLAUDE.md 2>/dev/null || echo 0)
PROJECT_RULE="$HOME/.config/opencode/rules/project-$(basename $PWD).md"
PROJECT_RULE_TIME=$(stat -f %m "$PROJECT_RULE" 2>/dev/null || echo 0)

if [ "$PROJECT_CLAUDE_TIME" -gt "$PROJECT_RULE_TIME" ]; then
  cp CLAUDE.md "$PROJECT_RULE" && echo "Project CC -> OC"
elif [ "$PROJECT_RULE_TIME" -gt "$PROJECT_CLAUDE_TIME" ]; then
  cp "$PROJECT_RULE" CLAUDE.md && echo "Project OC -> CC"
else
  echo "Project context already in sync"
fi

Best Practices

  1. Sync before switching — run sync commands before changing tools
  2. Choose primary per project — reduces context switching
  3. Use right tool for task — CC for speed/speckit, OC for multi-agent/model flexibility
  4. Keep ai-playbook.md at project root — both tools will use it as a shared reference

Version: 6.0.0 Last Updated: 2026-03-16

OpenCode Ecosystem Setup

Complete setup guide for OpenCode with oh-my-opencode, agents, rules, and principles

Status: You are setting up OpenCode Migration: See migration-guide.md if you also use Claude Code Principles: Read ai-playbook.md first - the principles apply to all AI coding tools, not just Claude Code

Pre-Flight Check

AI: Check required tools before starting. Install any that are missing.

for tool in curl npm jq; do
  if ! command -v $tool &> /dev/null; then
    echo "Missing: $tool"
  fi
done

# If missing, install based on platform:
# macOS: brew install [tool]  (brew install node for npm)
# Linux: sudo apt-get install [tool]  (install nodejs for npm)
# Windows: choco install [tool]

# Check OpenCode itself
if ! command -v opencode &> /dev/null; then
  echo "OpenCode not installed. Install: curl -fsSL https://opencode.ai/install | bash"
fi

Principles from AI-Playbook (Apply to OpenCode Too)

The following principles from ai-playbook.md apply regardless of which tool you use:

Context Management

  • Context window quality degrades at 20-40% usage. After 60%, the AI forgets instructions.
  • One conversation = one task. Don't mix auth system + database schema + UI in one session.
  • Use compact/clear features when context fills up. Start fresh sessions between tasks.
  • Context rot: stale information doesn't just take up space, it actively causes harm.

Rules Structure (WHAT/WHY/HOW)

When creating rules (Step 4 below), structure them as:

  • WHAT: What is the project? Tech stack, architecture.
  • WHY: Why these decisions? (AI makes better edge-case decisions when it knows WHY)
  • HOW: Commands, test patterns, naming conventions.

Don't Section

Add to your rules - AI known tendencies to avoid:

  • Over-engineering (extra abstractions, unnecessary interfaces)
  • Creating too many files
  • Adding error handling for impossible scenarios
  • Adding docstrings/comments unless asked
  • Creating stub files (return null, TODO placeholders)

3-Layer Boundaries

Define in your rules:

  • Always: Write tests, run tests, follow naming conventions
  • Ask first: Database migrations, new dependencies, large refactoring
  • Never: Commit secrets, edit lock files, delete tests

Model Routing

OpenCode supports multiple providers. Use the right model for the right task:

  • Cheap/fast models: file search, format checks, quick questions
  • Balanced models: implementation, debugging, code review (DEFAULT)
  • Powerful models: architectural decisions, tough bugs, security audits

Setup Steps

1. Install OpenCode (If Not Installed)

curl -fsSL https://opencode.ai/install | bash
opencode --version  # Verify

2. Install oh-my-opencode

Ask user: "What AI subscriptions do you have?"

Flag Requirement What It Enables
--claude=max20 Claude Pro/Max + 20x mode Full Sisyphus orchestrator
--claude=yes Claude Pro/Max (standard) Sisyphus with standard Opus 4.5
--claude=no No Claude subscription Sisyphus may not work ideally
--openai=yes ChatGPT Plus / OpenAI API GPT-5.2 for Oracle agent
--gemini=yes Gemini subscription Additional model options
# Example for Claude Max with 20x mode:
npx oh-my-opencode install --no-tui --claude=max20 --openai=no --gemini=no

# Or run interactive install:
npx oh-my-opencode install

What you get:

  • Sisyphus (orchestrator) — Claude Opus 4.5
  • Oracle (debugging) — Claude Opus 4.5 or GPT-5.2
  • Librarian (search) — GLM-4.7 (free, always available)
  • Frontend / Document Writer / Multimodal Looker — powered by your subscriptions

3. Authenticate

opencode auth login
# Select your provider (Anthropic, OpenAI, Google)
# Complete OAuth in browser
# Repeat for each provider you have

4. Configure Rules

OpenCode supports both CLAUDE.md (project root) and .opencode/rules/*.md. Use CLAUDE.md for simple projects, rules directories for complex ones with multiple topics.

CLAUDE.md Structure

Every CLAUDE.md should follow the WHAT / WHY / HOW structure and stay under 100 lines. This is not a soft guideline - it is a hard constraint. Long CLAUDE.md files cause context rot: the model's attention scatters, important rules get missed, and every session pays a hidden token cost for rules it may never need.

Structure:

  • What: What is this project? Tech stack, architecture in one paragraph.
  • Why: Why were these decisions made? Context enables better AI judgment in edge cases.
  • How: How do we work? Commands, patterns, naming conventions.
  • Don't: Explicit prohibitions with reasons. "Don't use console.log because it leaks sensitive data in production" is better than "don't use console.log" - the reason tells AI when exceptions are acceptable.
  • Boundaries: Three-layer safety - always do / ask first / never do.
# Project CLAUDE.md (keep under 100 lines)
cat > CLAUDE.md << 'EOF'
# [Project Name]

## What
[One paragraph: tech stack, architecture, core concepts]

## Why
[Key decisions and their reasons - enables AI judgment in edge cases]

## How
[Build/test/run commands, naming conventions, test patterns]

## Don't
- Never commit secrets (use env files, rotation plan exists)
- Never edit lock files directly
- Never delete tests without replacement

## Boundaries
- Always: write tests, run lint, follow naming conventions
- Ask first: database migrations, new dependencies, large refactors
- Never: push to main directly, skip CI, hardcode credentials
EOF

Move details out of CLAUDE.md and into referenced files:

CLAUDE.md (70-100 lines)             - Always loaded
.opencode/rules/architecture.md      - Referenced when needed
.opencode/rules/security.md          - Referenced when needed
.claude/rules/testing.md             - Referenced when needed
# Global rules (personal preferences - applied across all projects)
mkdir -p ~/.config/opencode/rules
cat > ~/.config/opencode/rules/global.md << 'EOF'
# Global Preferences

[Your personal coding preferences and tool configurations]
EOF

# Project rules for complex projects
mkdir -p .opencode/rules
cat > .opencode/rules/project-conventions.md << 'EOF'
# [Project Name]

## WHAT (Project Identity)
- Tech stack: [Your stack]
- Architecture: [Your architecture pattern]

## WHY (Decision Context)
- [Why you chose this stack/architecture - helps AI make better edge-case decisions]

## HOW (Working Rules)
- Build: [build command]
- Test: [test command]
- Lint: [lint command]

## Don't
- Don't over-engineer (no extra abstractions unless necessary)
- Don't create stub files (no return null, TODO placeholders)
- Don't add comments/docstrings unless asked

## Boundaries
- Always: Write tests, run tests, follow naming conventions
- Ask first: Database migrations, new dependencies, large refactoring
- Never: Commit secrets, edit lock files, delete tests
EOF

Path-Specific Rules

Rules can be scoped to file patterns. They only load when matching files are edited - a context efficiency win for large convention sets:

mkdir -p .claude/rules

# Test file conventions (loads only when editing test files)
cat > .claude/rules/testing.md << 'EOF'
---paths: ["**/*.test.tsx", "**/*.spec.ts"]---
Use AAA (Arrange-Act-Assert) pattern.
Prefer real database connections over mocks for integration tests.
EOF

# API endpoint conventions
cat > .claude/rules/api.md << 'EOF'
---paths: ["**/*.api.ts", "**/routes/**"]---
Validate all inputs. Return consistent error shapes. Document with JSDoc.
EOF

5. MCP Servers

# Recommended: Use CLI
opencode mcp add opencontext --command "oc mcp"
opencode mcp list  # Verify

# Or create config directly:
mkdir -p ~/.config/opencode
cat > ~/.config/opencode/opencode.json << 'EOF'
{
  "mcp": {
    "opencontext": {
      "type": "local",
      "command": ["oc", "mcp"],
      "enabled": true
    }
  }
}
EOF

Format note: OpenCode uses mcp (not mcpServers), command is an array, and requires type and enabled fields.


6. Skills

OpenCode scans multiple directories (provider-agnostic):

Priority Directory Shared with Claude Code?
1 .opencode/skills/ No
2 .claude/skills/ Yes
3 ~/.config/opencode/skills/ No
4 ~/.claude/skills/ Yes
# Use shared directory (recommended - works with both tools)
mkdir -p ~/.claude/skills

If you already use Claude Code, your existing skills are automatically detected - no migration needed.

Skills Strategy

Skills are triggered by keywords in your message. When the keyword appears, the model loads the skill's system prompt before responding. This has a context cost - keep it in mind:

  • Narrow skills (single-purpose, small prompt) = low cost, high precision
  • Broad workflow skills = higher cost, use intentionally, not habitually
  • Keyword mapping should be unambiguous. Avoid keywords that appear in normal conversation ("test", "fix") - prefer explicit phrases ("run security audit", "generate migration plan")
# Example skill
cat > ~/.claude/skills/security-review.md << 'EOF'
---
trigger: "security review"
description: "OWASP Top 10 review on changed files"
---
Review for: hardcoded secrets, input validation gaps, auth flaws, injection vectors.
Output as CRITICAL / HIGH / MEDIUM / LOW with file:line references.
EOF

7. Model Routing Strategy

OpenCode supports multiple providers. Route work to the right model to balance quality and cost:

Task Type Recommended Model Reason
Architecture, deep analysis, security review Opus (Claude / GPT-5) Highest reasoning capacity
Standard implementation, debugging, reviews Sonnet / GPT-4.1 Balanced quality and cost
Quick lookups, file scanning, summaries Haiku / GPT-4.1-mini Fast, cheap, sufficient
Large-context review, visual analysis Gemini Pro 1M context window, multimodal

Practical routing rules:

  • Default to Sonnet for most tasks
  • Upgrade to Opus for: architectural decisions, security reviews, refactors touching 10+ files
  • Downgrade to Haiku for: repetitive scans, quick Q&A, status checks
  • Use Gemini for: reviewing an entire codebase at once, UI/design feedback on screenshots

The oh-my-opencode Sisyphus orchestrator handles routing automatically in multi-agent sessions. For single-agent work, choose based on the table above.


8. Install Speckit (Optional)

curl -LsSf https://astral.sh/uv/install.sh | sh
uv tool install specify-cli --from git+https://github.com/github/spec-kit.git
specify init . --ai opencode

Use Speckit for complex features (5+ files). Commands: /speckit.specify, /speckit.clarify, /speckit.plan, /speckit.implement.


9. Framework Compatibility

OpenCode is compatible with the same workflow frameworks used in Claude Code setups:

  • GSD-2: Uses .planning/ directory for roadmaps and phase tracking. Works with OpenCode unchanged.
  • Pi: Pi's skills system uses the same directory conventions. Skills in ~/.claude/skills/ are detected by both Pi and OpenCode.
  • Speckit: Native OpenCode support via specify init . --ai opencode.

If you maintain both Claude Code and OpenCode setups, keep shared config in ~/.claude/ (global rules, skills, memory). Keep tool-specific config in ~/.config/opencode/ vs ~/.claude/settings.json.


10. Context Window Management

Context management is the single most important practice for sustained AI quality. The principles from ai-playbook.md apply directly to OpenCode.

Core rules:

  • One conversation = one task. Start a new session when the topic changes.
  • Use /compact proactively at 40-50% fill - do not wait until 70%+.
  • Use /clear when a task completes and you're starting something unrelated.
  • Quality starts degrading at 20-40% fill. After 60%, the model forgets earlier instructions.

Context rot:

  • Old tool outputs, stale debug traces, and outdated file versions accumulate silently.
  • The model cannot distinguish current from outdated - it will act on stale data.
  • Compact before switching sub-tasks within the same session.

CLAUDE.md size matters:

  • CLAUDE.md is auto-loaded every session. A 2,000-token CLAUDE.md adds hidden cost to every message.
  • Keep it under 100 lines. Move details to .opencode/rules/*.md or .claude/rules/*.md.
  • Path-scoped rules only load when relevant - use them for large convention sets.

Session memory:

  • OpenCode sessions are stateless. Save important decisions before ending a session.
  • Use a SCRATCHPAD.md at project root to bridge sessions.
cat > SCRATCHPAD.md << 'EOF'
# SCRATCHPAD

## Active Task
- [Task description]
- [Status: not started / in progress / awaiting review / completed]

## Last Session Summary
- [Date]: [Work completed]
- [Open issues remaining]

## Next Steps
1. [Step 1]
2. [Step 2]

## Notes
- [Important findings, decisions, discovered issues]
EOF

11. Verification

opencode --version                                    # OpenCode
cat ~/.config/opencode/oh-my-opencode.json | jq '.'   # oh-my-opencode
opencode mcp list                                      # MCP servers
ls ~/.config/opencode/rules/                           # Rules
ls ~/.claude/skills/                                   # Skills
[ -f CLAUDE.md ] && wc -l CLAUDE.md || echo "No CLAUDE.md in current dir"
opencode                                               # Test it!

Troubleshooting

Authentication Issues

opencode auth list      # Check status
opencode auth logout    # Clear
opencode auth login     # Re-authenticate

MCP Server Errors

# Common issue: "Unrecognized key: mcpServers"
# Fix: Use "mcp" not "mcpServers" in opencode.json

# Common issue: "Invalid input mcp.xxx"
# Fix: Ensure format has type, command (array), and enabled fields

opencode mcp list  # Check status

oh-my-opencode Not Working

cat ~/.config/opencode/oh-my-opencode.json  # Check config
npx oh-my-opencode install                  # Reinstall

CLAUDE.md Not Being Read

# Verify CLAUDE.md is at project root (not in subdirectory)
ls -la CLAUDE.md

# Check line count - if over 100, trim and move details to rules/
wc -l CLAUDE.md

Skills Not Triggering

# Verify skill files are in a scanned directory
ls ~/.claude/skills/ 2>/dev/null
ls .claude/skills/ 2>/dev/null
ls ~/.config/opencode/skills/ 2>/dev/null

# Check skill trigger keyword - must appear exactly in your message
head -5 ~/.claude/skills/your-skill.md

Summary

What you now have:

Component Purpose
OpenCode AI coding tool with multi-provider support
oh-my-opencode Multi-agent orchestration (Sisyphus, Oracle, Librarian)
CLAUDE.md (WHAT/WHY/HOW/Don't + Boundaries) Project strategic brain - under 100 lines
.opencode/rules/*.md or .claude/rules/*.md Path-scoped detailed conventions, context-efficient
Model routing strategy Right model for right task - quality vs cost
Skills with unambiguous keyword mapping Reusable workflows, triggered intentionally
Context management habits /compact at 40-50%, /clear between tasks, one task per session
SCRATCHPAD.md Session memory bridge
Framework compatibility GSD-2, Pi, Speckit all work with OpenCode

Frameworks (Optional but Highly Effective)

These provider-agnostic tools work with OpenCode:

  • GSD-2 (npm install -g gsd-pi): Structured project management with Milestone/Slice/Task hierarchy. Fresh context per task, autonomous mode. See frameworks-guide.md.
  • Pi (npm install -g @mariozechner/pi-coding-agent): Multi-provider AI coding agent supporting 20+ providers. Can complement or replace OpenCode for specific workflows. See frameworks-guide.md.

Setup Complete!

Run opencode to start. Try ulw: explain the codebase architecture to see multi-agent orchestration.

Token cost warning: Multi-agent sessions (ulw keyword) can cost $50-100/session. Start with single-agent before escalating.

Using Claude Code too? See migration-guide.md for config transfer and sync.

For the principles behind every decision in this guide, read ai-playbook.md.


Version: 4.0.0 (Principles-Enhanced) Last Updated: 2026-03-16

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment