Explainers

Hardening Claude Code Mode in Git Repositories: REPL Hooks, Sandbox Boundaries, and Worktree Safety

·December 1, 2026·10 min read
Architecture schematic comparing Traditional Sequential Tool Loops with Claude Code Experimental Code Mode REPL runtime, showing sandboxed shell calls, unsandboxed JS/file/MCP calls, and PreToolUse and PostToolUse hook gates
In Code Mode, the REPL tool orchestrates shell, file, web, and MCP calls inside one JavaScript turn. Sandboxing is off by default, runs on macOS/Linux/WSL2 only (not native Windows), and covers only shell commands when enabled; harden hooks and worktrees accordingly.

Claude Code experimental Code Mode (native build v2.1.323+, verified locally on v2.1.333) replaces sequential single-tool round trips with a built-in REPL tool that runs short JavaScript programs generated by Claude. A single script can fan out searches, edit files, execute tests, and return only filtered output to the conversation window.

For repository maintainers and DevOps engineers, batching tool calls inside JavaScript changes how permissions, hooks, sandboxes, and git rollbacks behave. Existing guardrails written for one-by-one tool calls can silently miss edge cases unless updated.

1. Why project settings cannot enable Code Mode, and why worktrees come first

Claude Code intentionally ignores CLAUDE_CODE_EXPERIMENTAL_CODE_MODE inside repository-level .claude/settings.json files. A cloned repository cannot silently opt a developer into Code Mode; activation must happen in the user's shell or user-level ~/.claude/settings.json.

Because auto and bypassPermissions modes skip ordinary prompts (only matching ask/deny rules, including REPL if placed in ask, and actions no mode auto-approves still prompt or block) and can run a REPL script in the background for up to two hours (while default and acceptEdits still prompt per call and time out synchronous scripts at 10 minutes), run bulk refactors inside an ephemeral git worktree rather than on main:

Command: git worktree add ../repo-code-mode-batch -b batch/code-mode-refactor
Command: cd ../repo-code-mode-batch
Command: CLAUDE_CODE_EXPERIMENTAL_CODE_MODE=1 claude
Comment: Inspect changes, or return to main checkout and discard cleanly
Command: git diff --stat
Command: git worktree remove --force ../repo-code-mode-batch
Command: git branch -D batch/code-mode-refactor
Run the batch in a dedicated worktree, inspect the diff, and remove both worktree and branch from the main checkout if you discard it.

2. Auditing and gating REPL with PreToolUse hooks and permission rules

Tool calls made from inside Claude's JavaScript still pass through your deny/ask permission rules and PreToolUse hooks under each tool's normal name (Bash, Edit, MCP tool names). However, three behavioral differences matter immediately for repository security:

  • Auto-mode classifier blind spot: In auto mode, the safety classifier reviews the static JavaScript block before execution, not runtime-computed values (such as a file path derived from search output). Keep explicit deny/ask rules and PreToolUse hooks for every operation that must not slip through.
  • Compound Bash commands: A git push executed inside a subdirectory named app can arrive at your PreToolUse Bash hook as cd 'app' && git push. Hooks that only match the prefix of a command string will miss it; parse every sub-command segment.
  • Fail-closed hook enforcement (`onFailure: "block"`): On v2.1.329+, if a command or http PreToolUse hook fails (for example, a missing script or non-zero crash) and onFailure is unset, Claude Code falls through to normal permission checks instead of blocking. Explicitly set "onFailure": "block" across every settings file that declares the hook.

You can also gate the REPL tool itself. Adding "ask": ["REPL"] in ~/.claude/settings.json pauses before every script starts (press Ctrl+O to inspect the collapsed Code row before answering, noting that subagent code does not appear in the main conversation viewer). For programmatic policy checks, attach a PreToolUse hook matching REPL and inspect tool_input.code:

{
  "permissions": {
    "ask": [
      "Bash(git push *)",
      "REPL"
    ]
  },
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "REPL|Bash",
        "hooks": [
          {
            "type": "command",
            "command": "python3 ~/.claude/hooks/check_repl_and_bash.py",
            "onFailure": "block"
          }
        ]
      }
    ]
  }
}

Note two operational caveats with the JSON above. First, Bash(git push *) alone does not match cd 'app' && git push or git -C app push; your PreToolUse hook must split compound shell operators (&&, ||, ;, and |) and inspect each segment. Second, invoking python3 ~/.claude/hooks/... fails on native Windows unless the hook shell is Git Bash with a python3 shim, and with "onFailure": "block" enabled, that startup failure will block every matched REPL and Bash call until fixed.

Know how interruption behaves at a permission prompt while a script is mid-flight: answering No (or pressing Esc) stops the script, while changes from earlier tool calls that already finished stay on disk. Answering No with a comment refuses only that call and lets the script continue. In unattended terminals with no IDE connected, fallback prompts display a 2-minute countdown and auto-block on expiry.

3. Redacting secrets from REPL output with PostToolUse hooks

A JavaScript snippet can read a file containing a token and return it in result, stdout, or stderr. Starting in v2.1.328, UserPromptSubmit hooks no longer receive code output (even from managed settings). Move output inspection and redaction to a PostToolUse hook matching REPL that returns a sanitized updatedToolOutput object:

{
  "hookSpecificOutput": {
    "hookEventName": "PostToolUse",
    "updatedToolOutput": {
      "code": "(await $`cat notes.txt`.text())",
      "result": "deploy token: REDACTED",
      "stdout": "",
      "stderr": "",
      "toolsUsed": ["Bash"]
    }
  }
}
  • Preserve exact schema types: Return code, stdout, and stderr as strings, handle null or missing result, and clear sensitive images, documents, or imagePagesFailed arrays to []. If the JSON shape breaks, or if the hook crashes or times out, Claude receives the original unredacted output.
  • Omit `uncutOutputNote` (`v2.1.331+`): Strip uncutOutputNote from updatedToolOutput so Claude does not receive a filesystem path pointing to the unredacted output.
  • Include the redacted copy even when blocking: Pair "decision": "block" with updatedToolOutput in the same JSON response; blocking alone still lets Claude read the original output.
  • Known leak surface (`refusedCalls`): Do not rely on PostToolUse to hide secrets embedded in a refused tool call's input (such as a Bash command string); refusedCalls can echo that input back to Claude unchanged.

4. Sandbox boundaries: what is isolated and what is not

Anthropic's documentation draws a sharp containment line. Claude Code's built-in sandbox is off by default, runs only on macOS, Linux, and WSL2, and does not run on native Windows (so a Windows PowerShell Code Mode session does not sandbox Bash or PowerShell). When enabled, it covers only shell commands executed by the script (set allowUnsandboxedCommands: false to block unsandboxed retries; do not set failIfUnavailable: true on native Windows because that setting makes Claude Code exit). The JavaScript runtime itself and its file, web, and MCP tool calls stay outside the sandbox. For hard filesystem and network containment on untrusted repositories, run Claude Code inside a container or virtual machine rather than relying on hook regexes or the local shell sandbox alone.

5. OpenTelemetry observability and reproducible A/B repo benchmarks

Teams collecting OpenTelemetry events (v2.1.329+; keep tracing beta off) receive standard tool_decision and tool_result events for nested calls under each tool's normal name. Update dashboards with three rules:

  • Filter nested calls from Code Mode by matching tool_use_id prefixes repl_ or toolu_cc_ (the parent REPL tool emits events without those prefixes).
  • In auto mode, nested calls covered by pre-execution script review carry no classifier_verdict; join on request_id against the parent REPL tool's tool_decision event.
  • Leave OTEL_LOG_TOOL_DETAILS unset if your telemetry sink must not receive secrets passed between chained calls inside a script.

To measure whether Code Mode actually improves throughput and cost on your own repository rather than trusting social benchmarks, run identical prompts across two clean worktrees at the same commit SHA (CLAUDE_CODE_EXPERIMENTAL_CODE_MODE=0 vs. 1) and log test pass rate, wall-clock seconds, /context, and /cost. Remember that Code Mode is interactive-terminal-only and requires the env var on claude --continue / --resume for any session started with it on.

Cross-site resources and sibling guides

Related Resources & Skills

Explore tools, repositories, and categories referenced in this guide:

About the Authors

Jeremy Bengtson

Jeremy Bengtson

Founder & AI Systems Architect · The Search Sherpa

Founder of The Search Sherpa and AI systems engineer designing autonomous agent harnesses, Model Context Protocol (MCP) integrations, 3-tier memory architectures, and disciplined engineering frameworks across Learn Claude Skills and Claude Skills GitHub.