My Claude Code Setup - Technical Reference

May 4, 2026 · View on GitHub

GitHub stars GitHub forks GitHub issues

May 4, 2026 — CLAUDE.md template updated. The CLAUDE.md template has been modernized with 3 new variants (CLAUDE-template-1.md, CLAUDE-template-2.md, CLAUDE-template-3.md) following official Anthropic best practices — including dual-memory architecture, progressive disclosure, and standalone behavioral rules. Existing users: use CLAUDE-migrate-to-new-template.md as an AI prompt to migrate your current CLAUDE.md to any of the new templates while preserving all your project-specific content. See 4.5 CLAUDE.md Templates for details.

My Claude Code Setup - Technical Reference

Overview

Purpose & Scope

This repository provides a comprehensive starter kit for Claude Code projects, including:

  • Memory Bank System: Structured context files for persistent memory across sessions
  • Pre-configured Settings: Optimized .claude/settings.json with fast tools
  • Custom Extensions: Hooks, skills, subagents, and slash commands
  • MCP Server Integration: Curated external tool connections
  • Alternative Provider Support: Z.AI integration for higher quotas

Target Audience

  • Beginners: New to Claude Code, need step-by-step guidance
  • Intermediate Users: Want to extend Claude Code with plugins and MCP servers
  • Advanced Users: Building custom subagents, skills, and workflows
  • Power Users: Need comprehensive reference for all configuration options

Compatibility Matrix

ComponentMinimum VersionRecommended
Node.js18+Latest LTS
Git2.30+Latest
Claude AI AccountPro/MaxMax
ripgrep12.0+Latest
fd8.0+Latest
jq1.6+Latest

Table of Contents


Part I: Getting Started

Chapter 1: Prerequisites

1.1 System Requirements

OSSupport LevelNotes
macOSFullAll features supported
LinuxFullAll features supported
WindowsFullPowerShell and CMD supported

1.2 Required Accounts

AccountPurposeLink
Claude AIClaude Code accessclaude.ai
GitHub (optional)Version controlgithub.com

Claude AI Pricing:

PlanMonthly CostUsage Limits
Pro$20Standard quotas
Max$100Higher quotas
Max$200Highest quotas

See official usage limits.

1.3 Required Tools

ToolVersionPurposeInstallation
Node.js18+Runtime environmentnodejs.org
GitLatestVersion controlgit-scm.com
ripgrepLatestFast content searchbrew install ripgrep (macOS)
fdLatestFast file findingbrew install fd (macOS)
jqLatestJSON processingbrew install jq (macOS)

macOS Installation (all tools):

brew install ripgrep fd jq

Chapter 2: Installation

2.1 Installation Methods

Choose the method that best fits your workflow:

Method A: Clone Entire Repository (New Projects)

# 1. Clone this repository as your new project
git clone https://github.com/centminmod/my-claude-code-setup.git my-project
cd my-project

# 2. Remove template README files (create your own project documentation)
rm README.md README-v2.md README-v3.md README-v4.md

# 3. Reinitialize git for your own project (optional)
rm -rf .git
git init

# 4. Launch Claude Code and initialize
claude
# Then run: /init

Method B: Selective Copy (Existing Projects)

For existing projects, copy only the components you need:

# Core files (recommended minimum)
cp /path/to/my-claude-code-setup/CLAUDE.md your-project/
cp -r /path/to/my-claude-code-setup/.claude your-project/

# Or selectively copy specific components:
mkdir -p your-project/.claude
cp -r /path/to/my-claude-code-setup/.claude/settings.json your-project/.claude/
cp -r /path/to/my-claude-code-setup/.claude/commands your-project/.claude/
cp -r /path/to/my-claude-code-setup/.claude/skills your-project/.claude/
cp -r /path/to/my-claude-code-setup/.claude/agents your-project/.claude/
cp -r /path/to/my-claude-code-setup/.claude/hooks your-project/.claude/

Method C: Download from GitHub

Browse the repository on GitHub and download individual files:

ComponentPathPurpose
Memory BankCLAUDE.mdMain context file (Template 3 format)
Template 1CLAUDE-template-1.mdCompact self-contained template
Template 2CLAUDE-template-2.mdMemory bank system template
Template 3CLAUDE-template-3.mdProgressive disclosure template
Migration GuideCLAUDE-migrate-to-new-template.mdAI-prompt migration guide
Rules.claude/rules/core-rules.mdBehavioral rules (required by Template 3)
Settings.claude/settings.jsonConfiguration template
Commands.claude/commands/Custom slash commands
Skills.claude/skills/Custom skills
Agents.claude/agents/Custom subagents
Hooks.claude/hooks/Event hooks

After copying files, launch Claude Code in your project and run /init.

2.2 Via NPM

npm install -g @anthropic-ai/claude-code

2.3 Development Container

For isolated development with YOLO mode support:

VS Code Dev Container Setup

Features:

  • Claude Code with dangerously_skip_permissions
  • Codex CLI with sandbox_mode = danger-full-access
  • Gemini CLI, Vercel CLI, Cloudflare Wrangler
  • Amazon AWS CLI

2.4 Verification

# Verify Claude Code installation
claude --version

# Verify fast tools
rg --version
fd --version
jq --version

Chapter 3: Initial Configuration

3.1 Copying Starter Files

  1. Copy all files from this repository to your project root
  2. Review and modify CLAUDE.md for your project specifics
  3. Modify .claude/settings.json as needed

3.2 First-Time Setup

The .claude/settings.json includes Terminal-Notifier for macOS notifications. Remove if not using macOS. See Terminal-Notifier Setup.

3.3 IDE Integration

VS Code Extension

Git for VS Code


Part II: Memory Bank System

Chapter 4: Architecture

4.1 Design Philosophy

The Memory Bank System enables Claude Code to maintain context across multiple chat sessions through structured markdown files. Instead of starting fresh each session, Claude reads these files to understand:

  • Project patterns and conventions
  • Architecture decisions and rationale
  • Current work state and goals
  • Common issues and solutions

4.2 File Hierarchy

project-root/
├── CLAUDE.md                          # Main entry point (Template 3 format)
├── CLAUDE-template-1.md              # Compact self-contained template
├── CLAUDE-template-2.md              # Memory bank system template
├── CLAUDE-template-3.md              # Progressive disclosure template
├── CLAUDE-migrate-to-new-template.md # Template migration guide
├── CLAUDE-activeContext.md            # Current session state
├── CLAUDE-patterns.md                 # Code patterns
├── CLAUDE-decisions.md                # Architecture Decision Records
├── CLAUDE-troubleshooting.md          # Issue/solution database
├── CLAUDE-config-variables.md         # Configuration reference
├── CLAUDE-temp.md                     # Temporary scratch pad
├── CLAUDE-cloudflare.md               # Optional: Cloudflare/ClerkOS docs
├── CLAUDE-cloudflare-mini.md          # Optional: Cloudflare mini reference
├── CLAUDE-convex.md                   # Optional: Convex database docs
└── .claude/rules/core-rules.md        # Behavioral rules (required by Template 3)

4.3 Loading Behavior

FileWhen LoadedPriority
CLAUDE.mdAlwaysHigh
CLAUDE-activeContext.mdAlways (if exists)High
CLAUDE-patterns.mdAlways (if exists)Medium
CLAUDE-decisions.mdAlways (if exists)Medium
CLAUDE-troubleshooting.mdAlways (if exists)Medium
CLAUDE-config-variables.mdAlways (if exists)Low
CLAUDE-temp.mdOnly when referencedLow

4.4 Context Window Management

Memory bank files consume context window tokens. Optimization strategies:

  • Use HTML comments for free notes: <!-- --> comments in CLAUDE.md are stripped from context at runtime and cost zero tokens — ideal for maintainer notes, TODOs, and placeholder guidance that only humans see
  • Use /cleanup-context command for 15-25% token reduction
  • Archive older decisions and patterns
  • Keep CLAUDE-temp.md empty when not in use
  • Reference supplementary docs (CLAUDE-cloudflare.md) only when needed

4.5 CLAUDE.md Templates

This repo provides 3 modernized templates following official Anthropic best practices:

TemplateLinesPhilosophyRules LocationBest For
CLAUDE-template-1.md~101Compact self-containedInline bulletsQuick starts, small projects
CLAUDE-template-2.md~153Memory bank headline + dual memoryInline grouped sectionsExisting memory bank users
CLAUDE-template-3.md~105Progressive disclosure native.claude/rules/core-rules.mdTeams, max context efficiency

All templates include:

  • Dual-memory architecture: Git-shared CLAUDE-*.md + machine-local auto memory for resilience
  • Progressive disclosure: Memory bank files read on-demand, not @ auto-loaded
  • Standalone behavioral rules: No dependency on ~/.claude/CLAUDE.md

The current CLAUDE.md uses the Template 3 format. Template 3 requires .claude/rules/core-rules.md for externalized behavioral rules; Templates 1 and 2 have rules inline.

Migration: CLAUDE-migrate-to-new-template.md is an AI-prompt guide — paste it as a prompt and Claude Code will migrate an existing CLAUDE.md to the chosen template while preserving all project-specific content.


Chapter 5: Core Context Files

5.1 CLAUDE.md (Main Entry Point)

Primary file containing:

  • Project overview
  • AI guidance rules
  • Memory bank system instructions
  • Tool usage preferences
  • Directory/file exploration commands

5.2 CLAUDE-activeContext.md

Current session state:

  • Active goals and tasks
  • Recent changes
  • Work in progress
  • Session continuity notes

5.3 CLAUDE-patterns.md

Established patterns:

  • Code conventions
  • Naming patterns
  • Architecture patterns
  • API patterns

5.4 CLAUDE-decisions.md

Architecture Decision Records (ADRs):

  • Decision context
  • Options considered
  • Decision made
  • Rationale
  • Consequences

5.5 CLAUDE-troubleshooting.md

Issue/solution database:

  • Common errors
  • Proven fixes
  • Workarounds
  • Prevention tips

5.6 CLAUDE-config-variables.md

Configuration reference:

  • Environment variables
  • Build configuration
  • Runtime settings

5.7 CLAUDE-temp.md

Temporary scratch pad:

  • Only read when explicitly referenced
  • Cleared after use
  • For temporary notes during complex tasks

Chapter 6: Operations

6.1 Initialization (/init)

After launching Claude Code:

/init

Claude Code will:

  1. Analyze your codebase structure
  2. Identify patterns and conventions
  3. Populate memory bank files
  4. Set up context for future sessions

6.2 Updates

After significant work completion:

update memory bank

Claude updates all relevant CLAUDE-*.md files.

6.3 Backups

Memory bank backup (copy to backup directory):

backup memory bank to /path/to/backup

Files copied:

  • All CLAUDE-*.md files
  • .claude/ settings directory

6.4 Example Session Output

> update memory bank

∴ Thinking…

  The user wants me to update the memory bank files. I should update the relevant CLAUDE-*.md files to reflect the v0.1.6 changes and current state. Let me check
   which memory bank files exist and update them.

∴ Thinking…

  I need to continue updating the memory bank files. I'll update:
  1. CLAUDE-patterns.md - Add export path handling pattern (Pattern 22)
  2. CLAUDE-decisions.md - Add ADR-017 for Phoneme API migration and ADR-018 for export path handling
  3. CLAUDE-troubleshooting.md - Add new issues and solutions for v0.1.6

∴ Thinking…

  The memory bank files have been modified but not committed. The v0.1.6 release was already committed and tagged, but the memory bank documentation updates are
  still uncommitted. Let me provide a summary of the completed work and offer to commit these documentation changes.

⏺ Summary: v0.1.6 Release Complete ✅

  Memory Bank Updates Complete:
  - CLAUDE-activeContext.md - v0.1.6 session context
  - CLAUDE-patterns.md - Added patterns 22-24 (Export Path, Format Detection, API Migration)
  - CLAUDE-decisions.md - Added ADR-017 & ADR-018
  - CLAUDE-troubleshooting.md - Added 4 new issue/fix entries

  v0.1.6 Fixes Applied:
  1. Export to absolute paths (e.g., --export /tmp/test.wav)
  2. Format detection from filename extension (prevents .mp3.wav)
  3. Phoneme API migrated to /dev/phonemize
  4. Test scripts updated for --export "" syntax

  Test Results: All 29 tests passing

  The memory bank documentation updates are ready to commit. Would you like me to commit them

Part III: Extensions

Chapter 7: Plugin System

7.1 Plugin Architecture

Claude Code plugins extend functionality through the official marketplace system.

7.2 Official Anthropic Marketplace

Marketplace URL: https://code.claude.com/docs/en/discover-plugins

Installation Commands

# Install plugin
/plugin install plugin-name@claude-plugins-official

# Update marketplace
/plugin marketplace update claude-plugins-official

Plugin Reference Table

PluginPurposeSourceInstall CommandNotes
code-simplifierCode cleanup & maintainabilityclaude-plugins-official/plugin install code-simplifierGitHub
frontend-designProduction-grade UI generationclaude-code-plugins/plugin install frontend-design@claude-code-pluginsGitHub
feature-dev7-phase feature developmentclaude-code-plugins/plugin install feature-dev@claude-code-pluginsGitHub
ralph-wiggumIterative AI loopsclaude-code-plugins/plugin install ralph-wiggum@claude-code-pluginsGitHub

Ralph Wiggum Notes

7.3 Third-Party Marketplaces

Adding Marketplaces

/plugin marketplace add owner/repo-name

Security Considerations

  • Review plugin source code before installation
  • Only install from trusted sources
  • Check for recent updates and maintenance

Third-Party Plugin Reference

PluginSourcePurposeCommands
safety-netcc-marketplaceCatches destructive git/filesystem commands/plugin marketplace add kenryu42/cc-marketplace
/plugin install safety-net@cc-marketplace
glm-plan-usagezai-coding-pluginsQuery Z.AI usage statistics/plugin marketplace add zai/zai-coding-plugins
/plugin install glm-plan-usage@zai-coding-plugins
Cloudflare Skillscloudflare/skillsDevelopment skills for Cloudflare platform (Workers, Pages, Agents SDK)/plugin marketplace add cloudflare/skills

Safety Net: GitHub - Prevents destructive commands like this incident.

Z.AI Usage: Docs

Cloudflare Skills: GitHub - Development skills for Workers, Pages, AI services, and the Agents SDK. Commands: /cloudflare:build-agent, /cloudflare:build-mcp.


Chapter 8: MCP Servers

8.1 Protocol Overview

MCP (Model Context Protocol) enables Claude Code to connect with external tools and services.

8.2 Server Categories

CategoryPurposeExamples
DocumentationLibrary/platform documentation lookupContext7, Cloudflare Docs
Development ToolsBrowser automation, testingChrome DevTools
MetricsUsage tracking, cost monitoringUsage Metrics
AI ModelsAccess to other AI providersGemini CLI
ProductivityWorkspace integrationNotion

8.3 Complete Server Reference

ServerTypeTransportPurposeToken CostGitHub
Context7DocumentationSSE/HTTPLook up docs for any libraryLowupstash/context7
Cloudflare DocsDocumentationSSECloudflare documentationLowcloudflare/mcp-server-cloudflare
Usage MetricsMetricsstdioClaude Code cost trackingLowcentminmod/claude-code-opentelemetry-setup
Gemini CLIAI ModelstdioGemini model accessVariablecentminmod/gemini-cli-mcp-server
NotionProductivitystdioNotion workspace integrationVariablemakenotion/notion-mcp-server
Chrome DevToolsDevelopmentstdioBrowser automation & debugging~17KChromeDevTools/chrome-devtools-mcp

8.4 Installation Commands (Complete)

Context7 MCP

claude mcp add --transport http context7 https://mcp.context7.com/mcp --header "CONTEXT7_API_KEY: YOUR_API_KEY" -s user

Cloudflare Documentation MCP

claude mcp add --transport sse cf-docs https://docs.mcp.cloudflare.com/sse -s user

Usage Metrics MCP

claude mcp add --transport stdio metrics -s user -- uv run --directory /path/to/your/mcp-server metrics-server

Example output from get_current_cost:

{
  "metric": "Total Cost Today",
  "value": 27.149809833783127,
  "formatted": "\$27.1498",
  "unit": "currencyUSD"
}

Gemini CLI MCP

claude mcp add gemini-cli /path/to/.venv/bin/python /path/to/mcp_server.py -s user -e GEMINI_API_KEY='YOUR_GEMINI_KEY' -e OPENROUTER_API_KEY='YOUR_OPENROUTER_KEY'

Notion MCP

claude mcp add-json notionApi '{"type":"stdio","command":"npx","args":["-y","@notionhq/notion-mcp-server"],"env":{"OPENAPI_MCP_HEADERS":"{\"Authorization\": \"Bearer ntn_API_KEY\", \"Notion-Version\": \"2022-06-28\"}"}}' -s user

Chrome DevTools MCP (On-Demand)

Due to high token overhead (~17K across 26 tools), install on-demand:

claude --mcp-config .claude/mcp/chrome-devtools.json

Create .claude/mcp/chrome-devtools.json:

{
  "mcpServers": {
    "chrome-devtools": {
      "command": "npx",
      "args": ["-y", "chrome-devtools-mcp@latest"]
    }
  }
}

8.5 Server-Specific Configuration Notes

Chrome DevTools Token Breakdown

26 tools totaling ~16,977 tokens:

ToolTokens
list_console_messages584
emulate_cpu651
emulate_network694
click636
drag638
fill644
fill_form676
hover609
upload_file651
get_network_request618
list_network_requests783
close_page624
handle_dialog645
list_pages582
navigate_page642
navigate_page_history656
new_page637
resize_page629
select_page619
performance_analyze_insight649
performance_start_trace689
performance_stop_trace586
take_screenshot803
evaluate_script775
take_snapshot614
wait_for643

Verification

claude mcp list
# Output:
# context7: https://mcp.context7.com/sse (SSE) - ✓ Connected
# cf-docs: https://docs.mcp.cloudflare.com/sse (SSE) - ✓ Connected
# metrics: uv run --directory /path/to/mcp-server metrics-server - ✓ Connected

Part IV: Customization

Chapter 9: Subagents

9.1 Subagent Architecture

Subagents are specialized tools that:

  • Handle complex, multi-step tasks autonomously
  • Use their own context window (separate from main conversation)
  • Have custom prompts tailored to their purpose

Official documentation: Claude Code Sub-agents

9.2 Built-in Subagents

Claude Code includes built-in subagent types. See official docs for complete list.

9.3 Creating Custom Subagents

Subagents are defined in .claude/agents/ as markdown files.

9.4 Included Subagent Reference

AgentLocationPurposeKey Features
memory-bank-synchronizer.claude/agents/memory-bank-synchronizer.mdSync documentation with codebasePattern sync, ADR updates, code freshness validation
code-searcher.claude/agents/code-searcher.mdEfficient codebase navigationStandard mode + CoD mode (80% fewer tokens)
get-current-datetime.claude/agents/get-current-datetime.mdBrisbane timezone (GMT+10) valuesMultiple formats, eliminates timezone confusion
ux-design-expert.claude/agents/ux-design-expert.mdUX/UI design guidanceTailwind CSS, Highcharts, accessibility compliance
zai-cli.claude/agents/zai-cli.mdz.ai GLM 4.7 CLI wrapperJSON output, used by consult-zai skill
codex-cli.claude/agents/codex-cli.mdCodex GPT-5.2 CLI wrapperReadonly mode, used by consult-codex skill

memory-bank-synchronizer

Purpose: Maintains consistency between CLAUDE-*.md files and source code.

Responsibilities:

  • Pattern documentation synchronization
  • Architecture decision updates
  • Technical specification alignment
  • Implementation status tracking
  • Code example freshness validation
  • Cross-reference validation

Usage: Proactively maintains documentation accuracy.

code-searcher

Purpose: Efficient codebase navigation and search.

Modes:

  • Standard: Full detailed analysis
  • CoD (Chain of Draft): ~80% fewer tokens with ultra-concise responses

Usage:

# Standard
"Find the payment processing code"

# CoD mode
"Find the payment processing code using CoD"
# Output: "Payment→glob:*payment*→found:payment.service.ts:45"

Trigger phrases for CoD: "use CoD", "chain of draft", "draft mode"

get-current-datetime

Purpose: Accurate Brisbane, Australia (GMT+10) timestamps.

Formats:

  • Default: Standard date output
  • Filename: Safe for file naming
  • Readable: Human-friendly format
  • ISO: ISO 8601 format

Usage: File timestamps, reports, logging.

ux-design-expert

Purpose: Comprehensive UX/UI design guidance.

Capabilities:

  • UX flow optimization
  • Premium UI design with Tailwind CSS
  • Data visualization with Highcharts
  • Accessibility compliance
  • Component library design

zai-cli

Purpose: CLI wrapper for z.ai GLM 4.7 model queries.

Features:

  • Executes z.ai CLI with JSON output format
  • Uses haiku model for minimal overhead
  • Returns raw output for parent skill to process

Usage: Used internally by consult-zai skill; not typically invoked directly.

codex-cli

Purpose: CLI wrapper for OpenAI Codex GPT-5.2 queries.

Features:

  • Executes Codex CLI in readonly mode with JSON output
  • Uses haiku model for minimal overhead
  • Returns raw output for parent skill to process

Usage: Used internally by consult-codex skill; not typically invoked directly.


Chapter 10: Skills

10.1 Skill Architecture

Skills provide specialized capabilities invoked automatically or on-demand.

Official documentation: Agent Skills

10.2 Skill File Structure

Skills are defined in .claude/skills/ directories containing:

  • SKILL.md: Skill definition and instructions
  • Supporting files as needed

10.3 Included Skills Reference

SkillPurposeInvocationLocation
claude-code-guide (built-in)Claude Code CLI features, hooks, MCP, settings, Agent SDK, API usageAutomatic when working on Claude Code featuresBuilt-in (no installation)
consult-zaiDual-AI consultation: z.ai GLM 4.7 vs code-searcher/consult-zai "question" or via Skill tool.claude/skills/consult-zai/
consult-codexDual-AI consultation: Codex GPT-5.2 vs code-searcher/consult-codex "question" or via Skill tool.claude/skills/consult-codex/
ai-image-creatorGenerate PNG images using AI (multiple models via OpenRouter)/ai-image-creator or via Skill tool.claude/skills/ai-image-creator/
session-metricsParse JSONL logs for per-turn token/cost/cache metrics with multi-format exportAuto-triggers on cost/usage questions or manual CLI.claude/skills/session-metrics/

claude-code-guide (Built-in)

Purpose: Natively built-in Claude Code subagent for questions about Claude Code CLI features, hooks, slash commands, MCP servers, settings, IDE integrations, keyboard shortcuts, Claude Agent SDK, and Claude API usage.

Triggers: Automatic when working on Claude Code features or asking about Claude Code capabilities.

Behavior: No installation required — available in all Claude Code sessions. Provides accurate, up-to-date guidance by searching official documentation.

consult-zai

Purpose: Dual-AI consultation comparing z.ai GLM 4.7 and code-searcher responses.

Features:

  • Invokes both zai-cli and code-searcher agents in parallel
  • Enhanced prompts requesting structured output with file:line citations
  • Comparison table showing file paths, line numbers, code snippets, and accuracy
  • Agreement level indicator (High/Partial/Disagreement) for confidence assessment
  • Synthesized summary combining best insights from both AI sources

Usage: /consult-zai "your code analysis question" or invoke via Skill tool.

consult-codex

Purpose: Dual-AI consultation comparing OpenAI Codex GPT-5.2 and code-searcher responses.

Features:

  • Invokes both codex-cli and code-searcher agents in parallel
  • Enhanced prompts requesting structured output with file:line citations
  • Comparison table showing file paths, line numbers, code snippets, and accuracy
  • Agreement level indicator (High/Partial/Disagreement) for confidence assessment
  • Synthesized summary combining best insights from both AI sources

Usage: /consult-codex "your code analysis question" or invoke via Skill tool.

ai-image-creator

Purpose: Generate PNG images using AI (multiple models via OpenRouter including Gemini, FLUX.2, Riverflow, SeedDream, GPT-5 Image, GPT-5.4 Image 2, proxied through Cloudflare AI Gateway BYOK).

Setup: Requires API credentials and optional Cloudflare AI Gateway configuration before use. See setup guide.

Models (selectable via --model keyword):

KeywordModel
geminiGoogle Gemini 3.1 Flash (default)
riverflowSourceful Riverflow v2 Pro
flux2FLUX.2 Max
seedreamByteDance SeedDream 4.5
gpt5OpenAI GPT-5 Image
gpt5.4OpenAI GPT-5.4 Image 2 (272K context)

Providers:

  • OpenRouter (recommended, pay-as-you-go)
  • Google AI Studio (requires billing for image generation)
  • Cloudflare AI Gateway BYOK (secure proxy, stores provider keys server-side)

Features:

  • Model selection via --model keyword
  • Configurable aspect ratios: 1:1, 16:9, 9:16, 3:2, 2:3, 4:3, 3:4, 4:5, 5:4, 21:9, 1:4, 4:1
  • Image sizes: 0.5K, 1K (default), 2K, 4K
  • Automatic fallback from gateway to direct API
  • Transparent background generation (-t) with green-screen chroma key pipeline
  • Reference image editing/style transfer (-r) for multimodal models (gemini, gpt5, gpt5.4)
  • Image analysis/description (--analyze) — text-only output; no image generated. Multimodal models only (gemini, gpt5, gpt5.4)
  • Per-project cost tracking (--costs) with per-model breakdown
  • Prompt enhancement with 11 category-specific professional patterns
  • Composite banners for multi-size logo banners via ImageMagick (no API calls needed)
  • Post-processing with ImageMagick, sips (macOS), or ffmpeg
  • Pure Python (no pip dependencies), requires uv runner

Composite Banners: Generate consistent logo banners across multiple sizes from a JSON config using ImageMagick. Use when the user has an existing logo and wants multi-size branded banners (not creative/artistic designs). Quick start: --init to scaffold config, --validate to check, then generate. See composite reference for full config schema.

Image Analysis: Describe, analyze, or explain existing images using multimodal AI vision (--analyze). Returns text-only JSON output — no image generated. Pass -r with the image file and optionally -p with a custom prompt. Multimodal models only (gemini, gpt5, gpt5.4). Example: --analyze -r photo.png -p "What text is visible?".

Usage: /ai-image-creator or invoke via Skill tool when user asks to generate images, create PNGs, make visual assets, or describe/analyze existing images.

session-metrics

Purpose: Parse Claude Code's JSONL conversation logs into a per-turn breakdown of token usage, cache efficiency, cost, and activity patterns. Useful for spotting cache issues and debugging rate-limit / weekly-session-cap questions.

Location: .claude/skills/session-metrics/

Runtime: Stdlib-only Python via uv run python. Zero network at runtime — JSONL parsing only, no telemetry.

Export formats (via --output):

  • text (default, stdout) — timeline-ordered cost summary
  • json — full structured report with all turns, subtotals, model rates
  • csv — one row per turn (session_id, index, timestamp, model, tokens, cost)
  • md — summary table + per-session Markdown tables
  • html — dark-themed report with summary cards, charts, and insights; 2-page split (dashboard + detail) by default, or --single-page for a single file

Insights produced:

  • Per-turn timeline (timestamp, model, input/output/cache-read/cache-write tokens, cost)
  • Subtotals per session (`--project-cost$) \text{and} \text{project} \text{grand} \text{total}
  • \text{Cache} \text{savings} \text{vs} \text{hypothetical} \text{no}-\text{cache} \text{run} + \text{cache} \text{hit} \text{ratio}
  • 5-\text{hour} \text{session} \text{blocks} \text{with} \text{trailing} 7/14/30-\text{day} \text{counters} — \text{closest} \text{available} \text{signal} \text{for} "\text{am} \text{I} \text{tracking} \text{toward} \text{the} \text{weekly} \text{session} \text{cap}"
  • \text{Weekly} \text{roll}-\text{up}: \text{trailing} 7\text{d} \text{vs} \text{prior} 7\text{d} \text{with} \text{percentage} \text{deltas} (\text{cost}, \text{turns}, \text{prompts}, \text{blocks}, \text{cache} \text{hit} \text{ratio})
  • \text{Session} \text{duration} + \text{burn} \text{rate} ($/\text{min}, \text{tokens}/\text{min}) \text{per} \text{session}
  • \text{Hour}-\text{of}-\text{day} 24-\text{bucket} \text{bars} + \text{weekday} \times \text{hour} 7 \times 24 \text{punchcard} \text{in} \text{chosen} \text{timezone}
  • \text{Optional} \text{peak}-\text{hour} \text{band} ($--peak-hours H-H --peak-tz `) — community-reported, not an Anthropic SLA

Chart library (--chart-lib):

ValueLicenceNotes
highchartsnon-commercial-freeDefault. Richest visualisation. Commercial use needs a paid Highsoft licence.
uplotMITLightweight; good default for commercial contexts.
chartjsMITFamiliar API.
nonen/aNo chart library, smallest output, no JS dependency.

All three libraries are vendored and SHA-256 verified. See .claude/skills/session-metrics/scripts/vendor/charts/README.md for per-library LICENSE.txt files and a refresh recipe.

Security: CLI inputs (--session, --slug) and their env-var equivalents (CLAUDE_SESSION_ID, CLAUDE_PROJECT_SLUG, CLAUDE_PROJECTS_DIR) are validated against strict allowlists; path traversal is rejected; resolved file paths are asserted to live under ~/.claude/projects/ before any read.

Instance-wide dashboard (v1.14.0+, --all-projects): aggregates every project under ~/.claude/projects/ into a single dated export folder (exports/session-metrics/instance/YYYY-MM-DD-HHMMSS/). Contains index.html (summary cards, daily-cost timeline stacked by tokens, projects breakdown table sorted by cost descending, aggregated models/weekly/hour-of-day/punchcard rollups) plus a projects/<slug>.html per project with the full per-turn drilldown, hyperlinked from the index. --no-project-drilldown skips drilldowns for a fast flat index; --projects-dir /path targets a non-default install (also honours CLAUDE_PROJECTS_DIR).

Usage: Auto-triggers when you ask questions like "how much has this session cost?", "show me token usage", "session summary", "cost so far", or "how much have I spent across all my projects?". Manual: uv run python .claude/skills/session-metrics/scripts/session-metrics.py [flags]. Also installable as a Claude Code plugin: /plugin marketplace add centminmod/claude-plugins then /plugin install session-metrics@centminmod.


Chapter 11: Hooks

11.1 Hook Events Reference

Hooks run custom commands before or after tool execution.

11.2 Configuration

Hooks are configured in .claude/hooks/.

11.3 Included Hooks

STOP Notification Hook

Uses Terminal-Notifier to show macOS desktop notifications when Claude Code completes a response.

Setup: Terminal-Notifier


Chapter 12: Slash Commands

12.1 Built-in Commands

Claude Code includes built-in commands like /init, /config, /help.

12.2 Custom Command Structure

Custom commands are defined in .claude/commands/ as markdown files.

12.3 Included Commands Reference

NamespaceCommandPurposeUsage
/anthropicapply-thinking-toEnhanced prompts with extended thinking/apply-thinking-to @/path/to/prompt.md
/anthropicconvert-to-todowrite-tasklist-promptTask optimization (60-70% faster)/convert-to-todowrite-tasklist-prompt @/path/to/command.md
/anthropicupdate-memory-bankUpdate memory bank files/update-memory-bank
/ccusageccusage-dailyUsage cost analysis/ccusage-daily
/cleanupcleanup-contextToken reduction (15-25%)/cleanup-context
/documentationcreate-readme-sectionREADME section generation/create-readme-section "topic"
/documentationcreate-release-noteDual release notes/create-release-note or /create-release-note 20
/securitysecurity-auditOWASP security audit/security-audit
/securitycheck-best-practicesBest practices analysis/check-best-practices
/securitysecure-promptsPrompt injection detection/secure-prompts @file.txt
/architectureexplain-architecture-patternPattern analysis/explain-architecture-pattern
/promptengineeringconvert-to-test-driven-promptTDD-style prompts/convert-to-test-driven-prompt "request"
/promptengineeringbatch-operations-promptParallel processing optimization/batch-operations-prompt "request"
/refactorrefactor-codeRefactoring plans/refactor-code

Command Details

/apply-thinking-to

Transforms prompts using:

  • Progressive reasoning structure
  • Sequential analytical frameworks
  • Systematic verification with test cases
  • Constraint optimization
  • Bias detection
  • Extended thinking budget management
/convert-to-todowrite-tasklist-prompt

Achieves 60-70% speed improvements through:

  • Parallel processing
  • Specialized task delegation
  • Strategic file selection (max 5 files per task)
  • Context overflow prevention
/create-release-note

Two modes:

  • By commit count: /create-release-note 20
  • Interactive selection after viewing commits

Outputs:

  • Customer-facing release note (value-focused)
  • Technical engineering note (SHA references, file paths)
/secure-prompts

Test prompts available at .claude/commands/security/test-examples/:

  • test-encoding-attacks.md
  • test-advanced-injection.md
  • test-basic-role-override.md
  • test-css-hiding.md
  • test-invisible-chars.md
  • test-authority-claims.md

Reports saved to reports/secure-prompts/.

/refactor-code

Analysis-only refactoring that:

  • Analyzes code complexity
  • Assesses test coverage
  • Identifies architectural patterns
  • Creates step-by-step plans
  • Generates risk assessment
  • Outputs to reports/refactor/

Part V: Alternative Providers

Chapter 13: Z.AI Integration

13.1 Overview

Z.AI's GLM Coding Plan provides cost-effective access to GLM models optimized for coding.

Features:

  • 55+ tokens/second performance
  • Vision Understanding
  • Web Search, Web Reader MCP servers
  • GLM-4.7 with state-of-the-art reasoning

13.2 Pricing & Plans

PlanPrompts/5hrsMonthly Costvs Claude
Lite~120~$33× Claude Pro quota
Pro~600Higher3× Claude Max 5x quota
Max~2,400Higher3× Claude Max 20x quota

Each prompt allows 15–20 model calls = billions of tokens monthly at ~1% of standard API pricing.

Discount: 10% off with invite code WWB8IFLROM

13.3 Privacy & Data Handling

AspectDetails
Data LocationSingapore
StorageNo content storage
PolicyPrivacy Policy

13.4 Setup Instructions

Prerequisites

Automated (macOS/Linux)

curl -O "https://cdn.bigmodel.cn/install/claude_code_zai_env.sh" && bash ./claude_code_zai_env.sh

Manual Configuration

Edit ~/.claude/settings.json:

{
  "env": {
    "ANTHROPIC_AUTH_TOKEN": "your-zai-api-key",
    "ANTHROPIC_BASE_URL": "https://api.z.ai/api/anthropic",
    "API_TIMEOUT_MS": "3000000"
  }
}

13.5 Shell Function Launchers

macOS / Linux (Bash/Zsh)

Add to ~/.bashrc, ~/.zshrc, or ~/.bash_aliases:

# Z.AI + Claude Code launcher
zai() {
    export ANTHROPIC_AUTH_TOKEN="your-zai-api-key"
    export ANTHROPIC_BASE_URL="https://api.z.ai/api/anthropic"
    export API_TIMEOUT_MS="3000000"
    claude "$@"
}

Reload: source ~/.bashrc or source ~/.zshrc

Windows PowerShell

Add to PowerShell profile (notepad $PROFILE):

# Z.AI + Claude Code launcher
function zai {
    $env:ANTHROPIC_AUTH_TOKEN = "your-zai-api-key"
    $env:ANTHROPIC_BASE_URL = "https://api.z.ai/api/anthropic"
    $env:API_TIMEOUT_MS = "3000000"
    claude $args
}

Reload: . $PROFILE

Windows CMD Batch

Create zai.bat in a PATH directory:

@echo off
set ANTHROPIC_AUTH_TOKEN=your-zai-api-key
set ANTHROPIC_BASE_URL=https://api.z.ai/api/anthropic
set API_TIMEOUT_MS=3000000
claude %*

13.6 Model Mapping Configuration

Default Mapping:

Claude ModelGLM Model
OpusGLM-4.7
SonnetGLM-4.7
HaikuGLM-4.5-Air

Custom Mapping (optional):

In ~/.claude/settings.json:

{
  "env": {
    "ANTHROPIC_AUTH_TOKEN": "your-zai-api-key",
    "ANTHROPIC_BASE_URL": "https://api.z.ai/api/anthropic",
    "API_TIMEOUT_MS": "3000000",
    "ANTHROPIC_DEFAULT_OPUS_MODEL": "GLM-4.7",
    "ANTHROPIC_DEFAULT_SONNET_MODEL": "GLM-4.5",
    "ANTHROPIC_DEFAULT_HAIKU_MODEL": "GLM-4.5-Air"
  }
}

Or in shell function:

zai() {
    export ANTHROPIC_AUTH_TOKEN="your-zai-api-key"
    export ANTHROPIC_BASE_URL="https://api.z.ai/api/anthropic"
    export API_TIMEOUT_MS="3000000"
    export ANTHROPIC_DEFAULT_OPUS_MODEL="GLM-4.7"
    export ANTHROPIC_DEFAULT_SONNET_MODEL="GLM-4.5"
    export ANTHROPIC_DEFAULT_HAIKU_MODEL="GLM-4.5-Air"
    claude "$@"
}
Windows PowerShell Custom Mapping
function zai {
    $env:ANTHROPIC_AUTH_TOKEN = "your-zai-api-key"
    $env:ANTHROPIC_BASE_URL = "https://api.z.ai/api/anthropic"
    $env:API_TIMEOUT_MS = "3000000"
    $env:ANTHROPIC_DEFAULT_OPUS_MODEL = "GLM-4.7"
    $env:ANTHROPIC_DEFAULT_SONNET_MODEL = "GLM-4.5"
    $env:ANTHROPIC_DEFAULT_HAIKU_MODEL = "GLM-4.5-Air"
    claude $args
}
Windows CMD Custom Mapping
@echo off
set ANTHROPIC_AUTH_TOKEN=your-zai-api-key
set ANTHROPIC_BASE_URL=https://api.z.ai/api/anthropic
set API_TIMEOUT_MS=3000000
set ANTHROPIC_DEFAULT_OPUS_MODEL=GLM-4.7
set ANTHROPIC_DEFAULT_SONNET_MODEL=GLM-4.5
set ANTHROPIC_DEFAULT_HAIKU_MODEL=GLM-4.5-Air
claude %*

Usage:

zai                              # Launch
zai --model sonnet               # Specific model
zai --model opus --permission-mode plan

13.7 Z.AI + Git Worktree Integration

macOS / Linux (Bash/Zsh)

# Z.AI + Claude Code worktree launcher
zaix() {
    local branch_name
    if [ -z "\$1" ]; then
        branch_name="worktree-$(date +%Y%m%d-%H%M%S)"
    else
        branch_name="\$1"
    fi
    git worktree add "../$branch_name" -b "$branch_name" && \
    cd "../$branch_name" || return 1

    export ANTHROPIC_AUTH_TOKEN="your-zai-api-key"
    export ANTHROPIC_BASE_URL="https://api.z.ai/api/anthropic"
    export API_TIMEOUT_MS="3000000"
    claude --model sonnet --permission-mode plan
}
Windows PowerShell Z.AI + Worktree
# Z.AI + Claude Code worktree launcher
function zaix {
    param([string]$BranchName)
    if (-not $BranchName) {
        $BranchName = "worktree-$(Get-Date -Format 'yyyyMMdd-HHmmss')"
    }
    git worktree add "../$BranchName" -b $BranchName
    if ($LASTEXITCODE -eq 0) {
        Set-Location "../$BranchName"
        $env:ANTHROPIC_AUTH_TOKEN = "your-zai-api-key"
        $env:ANTHROPIC_BASE_URL = "https://api.z.ai/api/anthropic"
        $env:API_TIMEOUT_MS = "3000000"
        claude --model sonnet --permission-mode plan
    }
}
Windows CMD Z.AI + Worktree

Create zaix.bat:

@echo off
setlocal enabledelayedexpansion
if "%~1"=="" (
    for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /value') do set datetime=%%I
    set branch_name=worktree-!datetime:~0,8!-!datetime:~8,6!
) else (
    set branch_name=%~1
)
git worktree add "../%branch_name%" -b "%branch_name%"
if %errorlevel% equ 0 (
    cd "../%branch_name%"
    set ANTHROPIC_AUTH_TOKEN=your-zai-api-key
    set ANTHROPIC_BASE_URL=https://api.z.ai/api/anthropic
    set API_TIMEOUT_MS=3000000
    claude --model sonnet --permission-mode plan
)
endlocal

Usage:

zaix feature-auth  # Named worktree
zaix               # Auto-generated name

13.8 GitHub Actions Integration

Claude Code integrates with GitHub Actions to automate AI-powered workflows. With @claude mentions in PRs or issues, Claude can analyze code, implement features, fix bugs, and follow project standards defined in CLAUDE.md.

Key Capabilities:

CapabilityDescription
Issue responseRespond to @claude mentions in issues
PR automationCreate and modify code through pull requests
Standards complianceFollow project guidelines from CLAUDE.md
Slash commandsExecute commands like /review

Official Documentation: Claude Code GitHub Actions

Z.AI Workflow Configuration

Create .github/workflows/claude.yml:

Click to expand workflow YAML
name: Claude Code

on:
  issue_comment:
    types: [created]
  pull_request_review_comment:
    types: [created]
  issues:
    types: [opened, assigned]
  pull_request_review:
    types: [submitted]

jobs:
  claude:
    if: |
      (github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
      (github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
      (github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) ||
      (github.event_name == 'issues' && (contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude')))
    runs-on: ubuntu-latest
    permissions:
      contents: write
      pull-requests: write
      issues: write
      id-token: write
      actions: read
    steps:
      - name: Checkout repository
        uses: actions/checkout@v5
        with:
          fetch-depth: 1

      - name: Run Claude Code
        id: claude
        uses: anthropics/claude-code-action@v1
        env:
          ANTHROPIC_BASE_URL: https://api.z.ai/api/anthropic
          API_TIMEOUT_MS: 3000000
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          claude_args: |
            --model claude-opus
            --max-turns 100

Workflow Component Reference

ComponentPurpose
Event TriggersListens for issue_comment, pull_request_review_comment, issues, and pull_request_review events
Conditional (if)Only runs when @claude is mentioned in the comment/issue body or title
Permissionscontents: write for code changes, pull-requests: write for PRs, issues: write for issue responses, actions: read for CI results
ANTHROPIC_BASE_URLRoutes API calls through Z.AI endpoint for higher quotas
API_TIMEOUT_MSExtended timeout (50 minutes) for complex operations
claude_argsUses claude-opus model with up to 100 turns for complex tasks

Setup Steps

  1. Add API key as secret: Repository Settings → Secrets and variables → Actions → Add ANTHROPIC_API_KEY with your Z.AI API key
  2. Create workflow file: Save the YAML above to .github/workflows/claude.yml
  3. Usage: Mention @claude in any issue or PR comment to trigger the workflow

Part VI: Development Workflows

Chapter 14: Git Worktrees

14.1 Concept & Benefits

Git worktrees enable parallel Claude Code sessions with complete code isolation.

Benefits:

BenefitDescription
Parallel sessionsRun multiple AI coding sessions simultaneously
Code isolationEach worktree has independent file state
Shared historyAll worktrees share the same Git history
YOLO modeSafe experimental environment

Official Documentation: Run parallel Claude Code sessions with git worktrees

14.2 Shell Functions

macOS / Linux Functions

Add to ~/.bashrc, ~/.zshrc, or ~/.bash_aliases:

# Codex CLI worktree launcher
cx() {
    local branch_name
    if [ -z "\$1" ]; then
        branch_name="worktree-$(date +%Y%m%d-%H%M%S)"
    else
        branch_name="\$1"
    fi
    git worktree add "../$branch_name" -b "$branch_name" && \
    cd "../$branch_name" || return 1
    codex -m gpt-5-codex --config model_reasoning_effort='xhigh'
}

# Claude Code worktree launcher
clx() {
    local branch_name
    if [ -z "\$1" ]; then
        branch_name="worktree-$(date +%Y%m%d-%H%M%S)"
    else
        branch_name="\$1"
    fi
    git worktree add "../$branch_name" -b "$branch_name" && \
    cd "../$branch_name" || return 1
    claude --model opusplan --permission-mode plan
}

Reload: source ~/.bashrc or source ~/.zshrc

Windows PowerShell Functions

Add to PowerShell profile (notepad $PROFILE):

# Codex CLI worktree launcher
function cx {
    param([string]$BranchName)
    if (-not $BranchName) {
        $BranchName = "worktree-$(Get-Date -Format 'yyyyMMdd-HHmmss')"
    }
    git worktree add "../$BranchName" -b $BranchName
    if ($LASTEXITCODE -eq 0) {
        Set-Location "../$BranchName"
        codex -m gpt-5-codex --config model_reasoning_effort='xhigh'
    }
}

# Claude Code worktree launcher
function clx {
    param([string]$BranchName)
    if (-not $BranchName) {
        $BranchName = "worktree-$(Get-Date -Format 'yyyyMMdd-HHmmss')"
    }
    git worktree add "../$BranchName" -b $BranchName
    if ($LASTEXITCODE -eq 0) {
        Set-Location "../$BranchName"
        claude --model opusplan --permission-mode plan
    }
}

Reload: . $PROFILE

Windows CMD Batch Files

Create in a PATH directory (e.g., C:\Users\YourName\bin\):

cx.bat - Codex CLI launcher:

@echo off
setlocal enabledelayedexpansion
if "%~1"=="" (
    for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /value') do set datetime=%%I
    set branch_name=worktree-!datetime:~0,8!-!datetime:~8,6!
) else (
    set branch_name=%~1
)
git worktree add "../%branch_name%" -b "%branch_name%"
if %errorlevel% equ 0 (
    cd "../%branch_name%"
    codex -m gpt-5-codex --config model_reasoning_effort='xhigh'
)
endlocal

clx.bat - Claude Code launcher:

@echo off
setlocal enabledelayedexpansion
if "%~1"=="" (
    for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /value') do set datetime=%%I
    set branch_name=worktree-!datetime:~0,8!-!datetime:~8,6!
) else (
    set branch_name=%~1
)
git worktree add "../%branch_name%" -b "%branch_name%"
if %errorlevel% equ 0 (
    cd "../%branch_name%"
    claude --model opusplan --permission-mode plan
)
endlocal

14.3 Usage Examples

# Create worktree with custom name
clx feature-auth
cx bugfix-123

# Create worktree with auto-generated timestamp name
clx
cx

14.4 Worktree Management

CommandPurpose
git worktree listList all worktrees
git worktree remove ../nameRemove a worktree
git worktree pruneClean up stale references

14.5 The .worktreeinclude File

Purpose: Specify which .gitignored files to copy to new worktrees.

How It Works:

  • Uses .gitignore-style patterns
  • Only files matched by both .worktreeinclude AND .gitignore are copied

Example .worktreeinclude:

# Environment files
.env
.env.local
.env.*

# Claude Code local settings
**/.claude/settings.local.json

Common Use Cases:

  • .env files with API keys
  • .env.local for local overrides
  • .claude/settings.local.json for personal settings

14.6 Claude Desktop Integration

SettingValue
Default location~/.claude-worktrees
ConfigurationClaude Desktop app settings
RequirementRepository must be Git initialized

Official Documentation: Claude Code on Desktop

14.7 Local Ignores (.git/info/exclude)

Purpose: Ignore files locally without modifying shared .gitignore.

Usage:

nano .git/info/exclude

Example:

# Local IDE settings
.idea/
*.swp

# Personal scripts
my-local-scripts/

# Local test files
test-local.sh

Comparison:

FileScopeCommitted
.gitignoreTeam-sharedYes
.git/info/excludeLocal onlyNo
~/.config/git/ignoreGlobal (all repos)No

Interaction with .worktreeinclude: Files in .git/info/exclude work the same as .gitignore - patterns must appear in both files for copying to worktrees.


Chapter 15: Status Lines

15.1 Configuration

Add to ~/.claude/settings.json:

{
  "statusLine": {
    "type": "command",
    "command": "~/.claude/statuslines/statusline.sh",
    "padding": 0
  }
}

15.2 JSON Input Structure

The status line script receives JSON input with:

FieldPathDescription
Model.model.display_nameCurrent model name
Directory.workspace.current_dirWorking directory
Input Tokens.context_window.total_input_tokensTotal input tokens
Output Tokens.context_window.total_output_tokensTotal output tokens
Context Size.context_window.context_window_sizeContext window size
Cost.cost.total_cost_usdSession cost in USD
Lines Added.cost.total_lines_addedLines of code added
Lines Removed.cost.total_lines_removedLines of code removed

15.3 Example Script (Complete)

Create ~/.claude/statuslines/statusline.sh:

#!/bin/bash
# Read JSON input from stdin
input=$(cat)

# Extract model and workspace values
MODEL_DISPLAY=$(echo "$input" | jq -r '.model.display_name')
CURRENT_DIR=$(echo "$input" | jq -r '.workspace.current_dir')

# Extract context window metrics
INPUT_TOKENS=$(echo "$input" | jq -r '.context_window.total_input_tokens')
OUTPUT_TOKENS=$(echo "$input" | jq -r '.context_window.total_output_tokens')
CONTEXT_SIZE=$(echo "$input" | jq -r '.context_window.context_window_size')

# Extract cost metrics
COST_USD=$(echo "$input" | jq -r '.cost.total_cost_usd')
LINES_ADDED=$(echo "$input" | jq -r '.cost.total_lines_added')
LINES_REMOVED=$(echo "$input" | jq -r '.cost.total_lines_removed')

# Extract percentage metrics
USED_PERCENTAGE=$(echo "$input" | jq -r '.context_window.used_percentage')
REMAINING_PERCENTAGE=$(echo "$input" | jq -r '.context_window.remaining_percentage')

# Format tokens as Xk
format_tokens() {
    local num="\$1"
    if [ "$num" -ge 1000 ]; then
        echo "$((num / 1000))k"
    else
        echo "$num"
    fi
}

# Generate progress bar for context usage
generate_progress_bar() {
    local percentage=\$1
    local bar_width=20
    local filled=$(awk "BEGIN {printf \"%.0f\", ($percentage / 100) * $bar_width}")
    local empty=$((bar_width - filled))
    local bar=""
    for ((i=0; i<filled; i++)); do bar+="█"; done
    for ((i=0; i<empty; i++)); do bar+="░"; done
    echo "$bar"
}

# Calculate total
TOTAL_TOKENS=$((INPUT_TOKENS + OUTPUT_TOKENS))

# Generate progress bar
PROGRESS_BAR=$(generate_progress_bar "$USED_PERCENTAGE")

# Show git branch if in a git repo
GIT_BRANCH=""
if git -C "$CURRENT_DIR" rev-parse --git-dir > /dev/null 2>&1; then
    BRANCH=$(git -C "$CURRENT_DIR" branch --show-current 2>/dev/null)
    if [ -n "$BRANCH" ]; then
        # Worktree detection
        GIT_DIR=$(git -C "$CURRENT_DIR" rev-parse --git-dir 2>/dev/null)
        WORKTREE=""
        if [[ "$GIT_DIR" == *".git/worktrees/"* ]] || [[ -f "$GIT_DIR/gitdir" ]]; then
            WORKTREE=" 🌳"
        fi
        # Ahead/behind detection
        AHEAD_BEHIND=""
        UPSTREAM=$(git -C "$CURRENT_DIR" rev-parse --abbrev-ref '@{u}' 2>/dev/null)
        if [ -n "$UPSTREAM" ]; then
            AHEAD=$(git -C "$CURRENT_DIR" rev-list --count '@{u}..HEAD' 2>/dev/null || echo 0)
            BEHIND=$(git -C "$CURRENT_DIR" rev-list --count 'HEAD..@{u}' 2>/dev/null || echo 0)
            if [ "$AHEAD" -gt 0 ] && [ "$BEHIND" -gt 0 ]; then
                AHEAD_BEHIND=" ↕${AHEAD}/${BEHIND}"
            elif [ "$AHEAD" -gt 0 ]; then
                AHEAD_BEHIND=" ↑${AHEAD}"
            elif [ "$BEHIND" -gt 0 ]; then
                AHEAD_BEHIND=" ↓${BEHIND}"
            fi
        fi
        GIT_BRANCH=" | 🌿 $BRANCH${WORKTREE}${AHEAD_BEHIND}"
    fi
fi

echo "[$MODEL_DISPLAY] 📁 ${CURRENT_DIR##*/}${GIT_BRANCH}
Context: [$PROGRESS_BAR] ${USED_PERCENTAGE}%
Cost: \$${COST_USD} | +${LINES_ADDED} -${LINES_REMOVED} lines"

Make executable: chmod +x ~/.claude/statuslines/statusline.sh


Part VII: Reference

Chapter 16: Settings

16.1 Configuration Scopes

ScopeLocationAffectsSharedPriority
ManagedSystem directoriesAll usersBy IT1 (highest)
User~/.claude/settings.jsonYou (all projects)No5
Project.claude/settings.jsonAll collaboratorsYes4
Local.claude/settings.local.jsonYou (this project)No3

Precedence Order (highest to lowest):

  1. Enterprise policies
  2. Command line arguments
  3. Local project settings
  4. Shared project settings
  5. User settings

16.2 settings.json Options (Complete)

KeyTypeDescriptionDefaultExample
apiKeyHelperstringScript to generate auth value-/bin/generate_temp_api_key.sh
cleanupPeriodDaysnumberDays to retain chat transcripts3020
envobjectEnvironment variables for sessions{}{"FOO": "bar"}
includeCoAuthoredBybooleanAdd Claude byline to commitstruefalse
permissionsobjectPermission configuration-See below
statusLineobjectStatus line configuration-See Chapter 15

16.3 Permission Settings

KeyTypeDescriptionExample
allowarrayAllowed tool use rules["Bash(git diff:*)"]
denyarrayDenied tool use rules["WebFetch", "Bash(curl:*)"]
additionalDirectoriesarrayExtra working directories["../docs/"]
defaultModestringDefault permission mode"acceptEdits"
disableBypassPermissionsModestringPrevent bypass mode"disable"

16.4 Sandbox Settings

For dev containers and isolated environments, see Dev Container Setup.


Chapter 17: Environment Variables

17.1 Authentication Variables

VariableDescription
ANTHROPIC_API_KEYAPI key sent as X-Api-Key header
ANTHROPIC_AUTH_TOKENCustom value for Authorization header (prefixed with Bearer )
ANTHROPIC_CUSTOM_HEADERSCustom headers in Name: Value format

17.2 Model Configuration Variables

VariableDescription
ANTHROPIC_MODELName of custom model to use
ANTHROPIC_SMALL_FAST_MODELHaiku-class model for background tasks
ANTHROPIC_SMALL_FAST_MODEL_AWS_REGIONAWS region for small/fast model on Bedrock
ANTHROPIC_DEFAULT_OPUS_MODELCustom Opus model mapping
ANTHROPIC_DEFAULT_SONNET_MODELCustom Sonnet model mapping
ANTHROPIC_DEFAULT_HAIKU_MODELCustom Haiku model mapping

17.3 Behavior Variables

VariableDescriptionDefault
BASH_DEFAULT_TIMEOUT_MSDefault bash command timeout-
BASH_MAX_TIMEOUT_MSMaximum bash command timeout-
BASH_MAX_OUTPUT_LENGTHMax characters before truncation-
CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIRReturn to original dir after bash-
CLAUDE_CODE_API_KEY_HELPER_TTL_MSCredential refresh interval-
CLAUDE_CODE_IDE_SKIP_AUTO_INSTALLSkip IDE extension auto-installfalse
CLAUDE_CODE_MAX_OUTPUT_TOKENSMax output tokens per request-
MAX_THINKING_TOKENSForce thinking budget-
MCP_TIMEOUTMCP server startup timeout (ms)-
MCP_TOOL_TIMEOUTMCP tool execution timeout (ms)-
MAX_MCP_OUTPUT_TOKENSMax MCP response tokens25000

17.4 Complete Reference Table

VariablePurpose
ANTHROPIC_API_KEYAPI key for Claude SDK
ANTHROPIC_AUTH_TOKENCustom auth header value
ANTHROPIC_BASE_URLCustom API endpoint
ANTHROPIC_CUSTOM_HEADERSCustom request headers
ANTHROPIC_MODELCustom model name
ANTHROPIC_SMALL_FAST_MODELBackground task model
ANTHROPIC_SMALL_FAST_MODEL_AWS_REGIONAWS region override
BASH_DEFAULT_TIMEOUT_MSDefault bash timeout
BASH_MAX_TIMEOUT_MSMaximum bash timeout
BASH_MAX_OUTPUT_LENGTHMax output characters
CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIRMaintain working dir
CLAUDE_CODE_API_KEY_HELPER_TTL_MSCredential TTL
CLAUDE_CODE_IDE_SKIP_AUTO_INSTALLSkip IDE auto-install
CLAUDE_CODE_MAX_OUTPUT_TOKENSMax output tokens
CLAUDE_CODE_USE_BEDROCKUse Amazon Bedrock
CLAUDE_CODE_USE_VERTEXUse Google Vertex AI
CLAUDE_CODE_SKIP_BEDROCK_AUTHSkip Bedrock auth
CLAUDE_CODE_SKIP_VERTEX_AUTHSkip Vertex auth
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFICDisable non-essential traffic
DISABLE_AUTOUPDATERDisable auto-updates
DISABLE_BUG_COMMANDDisable /bug command
DISABLE_COST_WARNINGSDisable cost warnings
DISABLE_ERROR_REPORTINGOpt out of Sentry
DISABLE_NON_ESSENTIAL_MODEL_CALLSDisable flavor text calls
DISABLE_TELEMETRYOpt out of Statsig
HTTP_PROXYHTTP proxy server
HTTPS_PROXYHTTPS proxy server
MAX_THINKING_TOKENSThinking budget
MCP_TIMEOUTMCP startup timeout
MCP_TOOL_TIMEOUTMCP tool timeout
MAX_MCP_OUTPUT_TOKENSMax MCP tokens
VERTEX_REGION_CLAUDE_3_5_HAIKUVertex region override
VERTEX_REGION_CLAUDE_3_5_SONNETVertex region override
VERTEX_REGION_CLAUDE_3_7_SONNETVertex region override
VERTEX_REGION_CLAUDE_4_0_OPUSVertex region override
VERTEX_REGION_CLAUDE_4_0_SONNETVertex region override

Chapter 18: File Locations

18.1 By Operating System

FilemacOSLinuxWindows
User settings~/.claude/settings.json~/.claude/settings.json%USERPROFILE%\.claude\settings.json
Project settings.claude/settings.json.claude/settings.json.claude\settings.json
Local settings.claude/settings.local.json.claude/settings.local.json.claude\settings.local.json
Managed settings/Library/Application Support/ClaudeCode//etc/claude-code/C:\Program Files\ClaudeCode\
Status line scripts~/.claude/statuslines/~/.claude/statuslines/%USERPROFILE%\.claude\statuslines\
Hooks.claude/hooks/.claude/hooks/.claude\hooks\
Skills.claude/skills/.claude/skills/.claude\skills\
Agents.claude/agents/.claude/agents/.claude\agents\
Commands.claude/commands/.claude/commands/.claude\commands\

18.2 Project Files Reference

FilePurposeCommitted
CLAUDE.mdMain memory bankYes
CLAUDE-*.mdContext filesYes
.claude/settings.jsonShared settingsYes
.claude/settings.local.jsonPersonal settingsNo
.claude/hooks/Custom hooksYes
.claude/skills/Custom skillsYes
.claude/agents/Custom subagentsYes
.claude/commands/Custom commandsYes
.worktreeincludeWorktree file patternsYes

Chapter 19: Tools Available to Claude

19.1 Complete Tool Reference

ToolDescriptionPermission Required
AgentRuns a sub-agent for complex, multi-step tasksNo
BashExecutes shell commands in your environmentYes
EditMakes targeted edits to specific filesYes
GlobFinds files based on pattern matchingNo
GrepSearches for patterns in file contentsNo
LSLists files and directoriesNo
MultiEditPerforms multiple edits on a single file atomicallyYes
NotebookEditModifies Jupyter notebook cellsYes
NotebookReadReads and displays Jupyter notebook contentsNo
ReadReads the contents of filesNo
TodoReadReads the current session's task listNo
TodoWriteCreates and manages structured task listsNo
WebFetchFetches content from a specified URLYes
WebSearchPerforms web searches with domain filteringYes
WriteCreates or overwrites filesYes

Permission Rules: Configure with /allowed-tools or in permission settings.

Extending Tools: Use hooks to run custom commands before/after tool execution.


Chapter 20: Cost & Rate Management

20.1 Weekly Rate Limits

From August 28, 2025, weekly limits apply (in addition to monthly 50x 5hr session limit):

PlanSonnet 4 (hrs/week)Opus 4 (hrs/week)
Pro40–80
Max ($100/mo)140–28015–35
Max ($200/mo)240–48024–40

20.2 Cost Optimization Strategies

StrategyBenefitHow
Z.AI Integration3× higher quotas at ~$3/moUse shell function launcher
CoD Mode80% token reductionRequest "use CoD" in code-searcher
Git WorktreesParallel sessions without duplicating quotaUse shell functions
Status LinesReal-time monitoringConfigure statusline.sh
MCP MetricsCost trackingInstall Usage Metrics MCP
Context Cleanup15-25% token reductionUse /cleanup-context

Appendices

Appendix A: Quick Reference Cards

Installation Checklist

  • Claude AI account (Pro/Max)
  • Node.js 18+
  • Git installed
  • Fast tools: brew install ripgrep fd jq
  • Clone repository
  • Run /init in Claude Code

Common Commands

CommandPurpose
/initInitialize memory bank
/configConfigure Claude Code
/helpShow help
update memory bankUpdate CLAUDE-*.md files
/ccusage-dailyShow usage statistics
/security-auditRun security audit

Keyboard Shortcuts

See official Claude Code documentation for current shortcuts.


Appendix B: Troubleshooting

Common Issues

IssueSolution
Memory bank not loadingEnsure CLAUDE.md exists in project root
MCP server not connectingRun claude mcp list to verify
Slow searchesInstall ripgrep and fd
High token usageUse CoD mode, cleanup context
Z.AI not workingCheck API key and base URL

Error Messages

ErrorCauseFix
No API key foundMissing authenticationSet ANTHROPIC_API_KEY or run /login
MCP timeoutServer startup too slowIncrease MCP_TIMEOUT
Context window exceededToo much contentUse /cleanup-context

Appendix C: Resources

Official Documentation

ResourceURL
Claude Code Overviewhttps://docs.anthropic.com/en/docs/claude-code/overview
Settings Referencehttps://code.claude.com/docs/en/settings
Hooks Documentationhttps://code.claude.com/docs/en/hooks
Skills Documentationhttps://docs.claude.com/en/docs/claude-code/skills
Sub-agentshttps://docs.anthropic.com/en/docs/claude-code/sub-agents
Plugin Marketplacehttps://code.claude.com/docs/en/discover-plugins
Git Worktreeshttps://code.claude.com/docs/en/common-workflows#run-parallel-claude-code-sessions-with-git-worktrees
Claude Desktophttps://code.claude.com/docs/en/desktop#claude-code-on-desktop-preview

YouTube Guides

TopicCreatorURL
Claude Code with Opus 4.5Alex Finnhttps://www.youtube.com/watch?v=UVJXh57MgI0
How To Master Claude Code (7-Hour Course)Anthropic Officialhttps://www.youtube.com/watch?v=XuSFUvUdvQA
Claude Code OverviewMatt Maherhttps://www.youtube.com/watch?v=Dekx_OzRwiI
VS Code Beginner-https://www.youtube.com/watch?v=rPITZvwyoMc
VS Code Advanced-https://www.youtube.com/watch?v=P-5bWpUbO60
Git for VS Code-https://www.youtube.com/watch?v=twsYxYaQikI
Ralph WiggumGreg Isenberghttps://www.youtube.com/watch?v=RpvQH0r0ecM
TopicCreatorURL
31 Days of Claude CodeAdo Kukic (Anthropic)https://adocomplete.com/advent-of-claude-2025/
40+ Claude Code Tipsykdojohttps://github.com/ykdojo/claude-code-tips
OpenClaw: Security, Deployment & Cost Guidecentminmodhttps://github.com/centminmod/explain-openclaw

Community Resources

ResourceURL
Safety Net Pluginhttps://github.com/kenryu42/claude-code-safety-net
Ralph Wiggum Repohttps://github.com/snarktank/ralph
Dev Container Setuphttps://claude-devcontainers.centminmod.com/

Appendix D: Star History & Stats

Star History

Star History Chart

Repository Stats

Alt