u/Ill-Leopard-6559

Claude Code Source Deep Dive (Part 5) — Literal Translation & Tool-Call Loop Self-Repair Core Mechanism

3.14 EnterWorktree Tool (Enter Worktree)

Create isolated git worktree and switch current session into it.

When to Use:
- User explicitly says "worktree"

When NOT to Use:
- User asks to create/switch branches
- User asks to fix bug or work on feature without mentioning worktrees
- NEVER use unless user explicitly mentions "worktree"

Behavior:
- Creates new git worktree inside `.claude/worktrees/` with new branch
- Switches session's working directory to new worktree

3.15 AskUserQuestion Tool (Ask User Question)

Ask user multiple choice questions to gather info, clarify ambiguity, understand preferences, make decisions, offer choices.

Usage Notes:
- Users always able to select "Other" for custom text input
- Use multiSelect: true to allow multiple answers
- If recommend specific option, make first option with "(Recommended)" at end

Preview Feature:
- Use optional `preview` field on options when presenting concrete artifacts needing visual comparison (ASCII/HTML mockups, code snippets, diagrams)
- Preview content rendered as monospace markdown
- When any option has preview, UI switches to side-by-side layout

3.16 LSP Tool (Language Server)

Interact with Language Server Protocol servers for code intelligence.

Supported Operations:
- goToDefinition, findReferences, hover, documentSymbol, workspaceSymbol,
  goToImplementation, prepareCallHierarchy, incomingCalls, outgoingCalls

All Operations Require:
- filePath, line (1-based), character (1-based)

3.17 Sleep Tool (Wait)

Wait for specified duration.

Usage:
- When user tells to sleep/rest
- When nothing to do / waiting for something
- May receive periodic check-ins (tick tags)
- Can call concurrently with other tools
- Prefer over `Bash(sleep ...)` — doesn't hold shell process
- Each wake-up costs API call
- Prompt cache expires after 5 min inactivity

3.18 CronCreate Tool (Scheduled Task)

Schedule prompts to run at future times.
Uses standard 5-field cron in user's local timezone.

One-Shot Tasks (recurring: false):
- "remind me at X" → pin minute/hour/day to specific values

Recurring Jobs (recurring: true, default):
- "every 5 min" → "*/5 * * * *"
- "hourly" → "0 * * * *"

CRITICAL: Avoid :00 and :30 Minute Marks (when task allows)
- Every user asking "9am" gets 0 9, causing thundering herd
- When approximate: pick minute NOT 0 or 30
  - "every morning around 9" → "57 8 * * *" (not "0 9 * * *")

Durability:
- Default (durable: false): lives only in Claude session
- durable: true: writes to .claude/scheduled_tasks.json

Recurring tasks auto-expire after 7 days.

3.19 TeamCreate Tool (Create Team)

Create team to coordinate multiple agents working on project.

When to Use (Proactively):
- User explicitly asks to use team, swarm, or group agents
- Task complex enough for parallel work

Team Workflow:
1. Create team with TeamCreate
2. Create tasks using Task tools
3. Spawn teammates using Agent tool with team_name + name params
4. Assign tasks using TaskUpdate with owner
5. Teammates work on assigned tasks
6. Shutdown gracefully via SendMessage with shutdown_request

IMPORTANT: Always refer to teammates by NAME. Plain text output NOT visible to other agents — MUST call SendMessage tool to communicate.

3.20 ToolSearch Tool (Deferred Tool Search)

Fetch full schema definitions for deferred tools so they can be called.

Query Forms:
- "select:Read,Edit,Grep" — fetch exact tools by name
- "notebook jupyter" — keyword search, up to max_results best matches
- "+slack send" — require "slack" in name, rank by remaining terms

Part IV: Tool-Call Loop Self-Repair Core Mechanism

4.1 Core Principle

Claude Code's "auto bug-fixing" capability is fundamentally a tool-call feedback loop:

Claude generates tool_use
    ↓
Tool executes (success or failure)
    ↓
tool_result returned to Claude (with is_error flag)
    ↓
Claude sees the error message in the next round
    ↓
Analyze cause → try new strategy
    ↓
Call tool again → loop continues

Key design: errors and successes use exactly the same message format. The only difference is is_error: true:

// Successful tool_result
{ type: 'tool_result', tool_use_id: 'call_abc', content: 'file content...', is_error: false }

// Failed tool_result
{ type: 'tool_result', tool_use_id: 'call_abc', content: 'Error: File not found', is_error: true }

4.2 Key Guidance in the System Prompt

If an approach fails, diagnose why before switching tactics—read the error, check your assumptions, try a focused fix. Don't retry the identical action blindly, but don't abandon a viable approach after a single failure either.

4.3 Four-Layer Error Recovery Strategy

Layer 1: Prompt-Too-Long recovery
PTL error → Strategy 1: context-collapse drain
         → Strategy 2: reactive compact (summarize history)
         → Strategy 3: report error to user

Layer 2: Output token limit recovery
Limit hit → Strategy 1: escalate from 8K to 64K (ESCALATED_MAX_TOKENS)
         → Strategy 2: recovery message "Output token limit hit. Resume directly..."
         → Strategy 3: give up after at most 3 times

Layer 3: Model overload fallback
Consecutive 529 errors (3x) → switch to fallbackModel
                          → discard failed attempt result
                          → retry with backup model

Layer 4: Natural recovery from tool errors
Tool execution error → error message fed back as tool_result
                    → Claude analyzes root cause
                    → adjusts strategy (read file/change method/modify params)
                    → retries

4.4 Error Message Truncation

Error messages over 10K characters keep the first and last 5K:
`${start}\n\n... [${length - 10000} characters truncated] ...\n\n${end}`

4.5 Turn-Level Error Tracking

// Use watermark to isolate errors for each Turn:
const errorLogWatermark = getInMemoryErrors().at(-1) // Turn start snapshot
// ... turn execution ...
const turnErrors = getInMemoryErrors().slice(watermarkIndex + 1) // only new errors

(End of Part 4 — translated literally from the extracted source segment.)

reddit.com
u/Ill-Leopard-6559 — 1 day ago