SPB Git

spb/wp29_uqo

Public

Phase 00: environment audit, corpus retrieval, mandate preservation

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Simon-Pierre Boucher committed (Oct 30, 2026) Browse files

58 changed files +15,528 −0

58 changed files
added .gitignore +14 −0
@@ -0,0 +1,14 @@
1 +.env
2 +*.pyc
3 +__pycache__/
4 +.venv/
5 +paper/*.aux
6 +paper/*.log
7 +paper/*.out
8 +paper/*.bbl
9 +paper/*.blg
10 +paper/*.fls
11 +paper/*.fdb_latexmk
12 +paper/*.synctex.gz
13 +runs/**/raw_stream.jsonl
14 +evidence/restricted/
added CLAUDE.md +7 −0
@@ -0,0 +1,7 @@
1 +# WP29 — Protocol-Guided Autonomous Research with Claude Code (concise root instructions)
2 +
3 +This repository is UQO Working Paper 29. The **complete, immutable research mandate** is `protocol/WP29_FULL_MANDATE.md` (read it in full; this file is only a pointer). Phase log: `reports/phase_status.md`. Human interventions: `reports/interventions.csv`. Amendments to frozen designs: `protocol/amendments.csv`.
4 +
5 +Hard rules (from the mandate): never invent experiments, outputs, costs, screenshots or citations; live Claude Code runs are the only admissible experimental observations; hidden oracles live **outside** this repository (`~/wp29-oracles/`, never copied to executor nodes); executors run in `--bare` mode on cluster nodes with explicitly injected instructions; report null/negative results; do not submit or publish anything.
6 +
7 +Builder/controller/evaluator host = this laptop. Executor hosts = M3U96a, M3U96b, M4M64a, M4M64b (`~/wp29/`). Commands: see `Makefile` and `README.md`.
added docs/claude-code-docs/cli-reference.md +186 −0
@@ -0,0 +1,186 @@
1 +> ## Documentation Index
2 +> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
3 +> Use this file to discover all available pages before exploring further.
4 +
5 +# CLI reference
6 +
7 +> Complete reference for Claude Code command-line interface, including commands and flags.
8 +
9 +## CLI commands
10 +
11 +You can start sessions, pipe content, resume conversations, and manage updates with these commands:
12 +
13 +| Command | Description | Example |
14 +| :- | :- | :- |
15 +| `claude` | Start interactive session | `claude` |
16 +| `claude "query"` | Start interactive session with initial prompt | `claude "explain this project"` |
17 +| `claude -p "query"` | Query via SDK, then exit | `claude -p "explain this function"` |
18 +| `cat file \| claude -p "query"` | Process piped content | `cat logs.txt \| claude -p "explain"` |
19 +| `claude -c` | Continue most recent conversation in current directory | `claude -c` |
20 +| `claude -c -p "query"` | Continue via SDK | `claude -c -p "Check for type errors"` |
21 +| `claude -r "<session>" "query"` | Resume session by ID or name | `claude -r "auth-refactor" "Finish this PR"` |
22 +| `claude update` | Update to latest version | `claude update` |
23 +| `claude gateway` | Start the self-hosted [Claude apps gateway](https://code.claude.com/docs/en/claude-apps-gateway) server, for administrators deploying SSO and policy in front of Claude Code on Amazon Bedrock, Google Cloud's Agent Platform, or Microsoft Foundry. Requires `--config` pointing at a [`gateway.yaml`](https://code.claude.com/docs/en/claude-apps-gateway-config). | `claude gateway --config gateway.yaml` |
24 +| `claude install [version]` | Install or reinstall the native binary. Accepts a version like `2.1.118`, or `stable` or `latest`. See [Install a specific version](https://code.claude.com/docs/en/setup.md#install-a-specific-version) | `claude install stable` |
25 +| `claude auth login` | Sign in to your Anthropic account. Use `--email` to pre-fill your email address, `--sso` to force SSO authentication, and `--console` to sign in with Anthropic Console for API usage billing instead of a Claude subscription | `claude auth login --console` |
26 +| `claude auth logout` | Log out from your Anthropic account | `claude auth logout` |
27 +| `claude auth status` | Show authentication status as JSON. Use `--text` for human-readable output. Exits with code 0 if logged in, 1 if not. The JSON includes a `configDirectory` field naming the [configuration directory](https://code.claude.com/docs/en/claude-directory.md) the CLI uses. The field requires Claude Code v2.1.268 or later. The JSON's `authMethod` field is one of `none`, `claude.ai`, `oauth_token`, `api_key`, `api_key_helper`, or `third_party` | `claude auth status` |
28 +| `claude agents` | Open [agent view](https://code.claude.com/docs/en/agent-view.md) to monitor and dispatch parallel background sessions. Use `--cwd <path>` to show only sessions started under that directory, or `--json` to print active sessions as a JSON array for scripting (`--json --all` also includes completed background sessions). Pass `--permission-mode`, `--model`, `--effort`, or `--agent` to set [defaults for dispatched sessions](https://code.claude.com/docs/en/agent-view.md#permission-mode-model-and-effort). Accepts `--settings`, `--add-dir`, `--plugin-dir`, and `--mcp-config` like the top-level `claude` command. Opening agent view requires an interactive terminal | `claude agents --json` |
29 +| `claude attach <id\|name>` | Attach to a [background session](https://code.claude.com/docs/en/agent-view.md#manage-sessions-from-the-shell) in this terminal. Passing part of a running session's name in place of the ID requires Claude Code v2.1.290 or later | `claude attach 7c5dcf5d` |
30 +| `claude auto-mode defaults` | Print the built-in [auto mode](https://code.claude.com/docs/en/permission-modes.md#eliminate-prompts-with-auto-mode) classifier rules as JSON. Use `claude auto-mode config` to see your effective config with settings applied. `--label <prefix>` prints only the rules whose label starts with that prefix, matched case-insensitively. Requires Claude Code v2.1.208 or later | `claude auto-mode defaults --label 'Git Destructive'` |
31 +| `claude auto-mode reset` | Restore the default [auto mode](https://code.claude.com/docs/en/permission-modes.md#eliminate-prompts-with-auto-mode) configuration by removing the `autoMode` section from your user settings file. Prompts for confirmation before writing; pass `-y`/`--yes` to skip the prompt. Rules from [managed settings](https://code.claude.com/docs/en/server-managed-settings.md) or the `--settings` flag still apply. Requires Claude Code v2.1.212 or later. See [Inspect the defaults and your effective config](https://code.claude.com/docs/en/auto-mode-config.md#inspect-the-defaults-and-your-effective-config) | `claude auto-mode reset --yes` |
32 +| `claude daemon logs` | Follow the background-session [supervisor's](https://code.claude.com/docs/en/agent-view.md#the-supervisor-process) log file, `~/.claude/daemon.log`, printing new lines as they arrive until you press `Ctrl+C` | `claude daemon logs` |
33 +| `claude daemon run` | Run the background-session [supervisor](https://code.claude.com/docs/en/agent-view.md#the-supervisor-process) in the foreground of this terminal, printing its log | `claude daemon run` |
34 +| `claude daemon status` | Print the background-session [supervisor's](https://code.claude.com/docs/en/agent-view.md#the-supervisor-process) state, version, socket directory, and worker count for diagnostics. Exits 1 if the supervisor isn't running | `claude daemon status` |
35 +| `claude daemon stop --any` | Stop the background-session [supervisor](https://code.claude.com/docs/en/agent-view.md#the-supervisor-process) and the sessions it hosts. Pass `--keep-workers` to leave background sessions running for the next supervisor to reconnect to. `--any` confirms stopping an on-demand supervisor, which is the default. Use this to recover from an [unresponsive supervisor](https://code.claude.com/docs/en/agent-view.md#agent-view-says-the-background-service-did-not-respond) | `claude daemon stop --any --keep-workers` |
36 +| `claude doctor` | Print read-only installation and settings diagnostics from the terminal without starting a session, including install health, settings-file validation errors, and Remote Control eligibility. For the in-session setup checkup that can also apply fixes, run [`/doctor`](https://code.claude.com/docs/en/commands#all-commands) | `claude doctor` |
37 +| `claude import [source]` | Start an interactive session that runs [`/import`](https://code.claude.com/docs/en/commands#all-commands) to bring configuration from other coding agents into Claude Code. Accepts the same `--dry-run` and `--yes` options as the command. Not available on Amazon Bedrock, Google Cloud's Agent Platform, Microsoft Foundry, or Claude Platform on AWS. Also unavailable when you turn off [feature-flag fetching](https://code.claude.com/docs/en/env-vars.md#features-that-need-feature-flag-fetching). Requires Claude Code v2.1.213 or later | `claude import codex --dry-run` |
38 +| `claude logs <id\|name>` | Print recent output from a [background session](https://code.claude.com/docs/en/agent-view.md#manage-sessions-from-the-shell). Passing part of a session's name in place of the ID requires Claude Code v2.1.290 or later | `claude logs 7c5dcf5d` |
39 +| `claude mcp` | Configure Model Context Protocol (MCP) servers | See the [Claude Code MCP documentation](https://code.claude.com/docs/en/mcp.md). |
40 +| `claude mcp login <name>` | Run a configured MCP server's OAuth flow without opening the interactive `/mcp` panel. Works for HTTP, SSE, and claude.ai connector servers. Add `--no-browser` over SSH to print the authorization URL instead of opening a browser. For an HTTP or SSE server, paste the redirect URL back at the prompt. For a claude.ai connector, see [Authorize a connector again from your shell](https://code.claude.com/docs/en/remote-control.md#authorize-a-connector-again-from-your-shell). See [Authenticate from the command line](https://code.claude.com/docs/en/mcp.md#authenticate-from-the-command-line) | `claude mcp login sentry` |
41 +| `claude mcp logout <name>` | Clear stored OAuth credentials for an MCP server | `claude mcp logout sentry` |
42 +| `claude plugin` | Manage Claude Code [plugins](https://code.claude.com/docs/en/plugins/overview.md). Alias: `claude plugins`. See [plugin reference](https://code.claude.com/docs/en/plugins/cli-reference.md#claude-plugin-commands) for subcommands | `claude plugin install code-review@claude-plugins-official` |
43 +| `claude purge [path]` | Delete all local Claude Code state for a project: transcripts, task lists, debug logs, file-edit history, prompt history lines, and the project's entry in `~/.claude.json`. Omit `[path]` to pick from an interactive list. Flags: `--dry-run` to preview, `-y`/`--yes` to skip confirmation, `-i`/`--interactive` to confirm each item, `--all` for every project. See [Clear local data](https://code.claude.com/docs/en/claude-directory.md#clear-local-data) | `claude purge ~/work/repo --dry-run` |
44 +| `claude remote-control` | Start a [Remote Control](https://code.claude.com/docs/en/remote-control.md) server to control Claude Code from Claude.ai or the Claude app. Runs in server mode (no local interactive session). See [Server mode flags](https://code.claude.com/docs/en/remote-control.md#start-a-remote-control-session). After you stop the server, you can bring back the sessions it was serving. See [Resume sessions after stopping the server](https://code.claude.com/docs/en/remote-control.md#resume-sessions-after-stopping-the-server) | `claude remote-control --name "My Project"` |
45 +| `claude respawn <id>` | Restart a [background session](https://code.claude.com/docs/en/agent-view.md#manage-sessions-from-the-shell), running or stopped, with its conversation intact. Use `--all` to restart every running session, e.g. to pick up an updated Claude Code binary | `claude respawn 7c5dcf5d` |
46 +| `claude rm <id>` | Remove a [background session](https://code.claude.com/docs/en/agent-view.md#manage-sessions-from-the-shell) from the list. When the removal is [refused over the session's worktree](https://code.claude.com/docs/en/agent-view.md#what-deleting-a-session-removes) and a second `claude rm` can resolve it, the refusal prints the exact flag and value to pass: `--discard-unpushed <commit>@<worktree-id>` discards a worktree that has unpushed commits along with those commits, and `--force-remove-worktree <worktree-id>` deletes a worktree directory that git or the `WorktreeRemove` hook couldn't remove. `--discard-unpushed` requires Claude Code v2.1.260 or later, and `--force-remove-worktree` requires v2.1.268 or later. The conversation transcript stays on your local machine, available through `claude --resume` | `claude rm 7c5dcf5d` |
47 +| `claude self-hosted-runner` | Start a runner process that registers this machine or container with a [self-hosted environment](https://code.claude.com/docs/en/self-hosted-environments) and hosts Claude Code cloud sessions on your infrastructure. Run `claude self-hosted-runner setup` for a guided operator walkthrough, `claude self-hosted-runner doctor` to [diagnose a deployed runner](https://code.claude.com/docs/en/self-hosted-environments-deploy.md#troubleshooting), and `claude self-hosted-runner orchestrator` to spawn [on-demand runners](https://code.claude.com/docs/en/self-hosted-environments-configuration.md#on-demand-runners). Requires Claude Code v2.1.224 or later | `claude self-hosted-runner setup` |
48 +| `claude setup-token` | Generate a long-lived OAuth token for CI and scripts. Prints the token to the terminal without saving it. Requires a Claude subscription. See [Generate a long-lived token](https://code.claude.com/docs/en/authentication.md#generate-a-long-lived-token) | `claude setup-token` |
49 +| `claude stop <id>` | Stop a [background session](https://code.claude.com/docs/en/agent-view.md#manage-sessions-from-the-shell). Also accepts `claude kill` | `claude stop 7c5dcf5d` |
50 +| `claude ultrareview [target]` | Run [ultrareview](https://code.claude.com/docs/en/ultrareview.md#run-ultrareview-non-interactively) non-interactively. Prints findings to stdout and exits 0 on success or 1 on failure. Use `--json` for the raw payload and `--timeout <minutes>` to override the 45-minute default. Use `--post` on a `github.com` pull request target to post the finished findings to the PR as one plain comment from your GitHub account. `--no-post` is the default. `--post` and `--no-post` require Claude Code v2.1.227 or later. See [Post findings to the pull request](https://code.claude.com/docs/en/ultrareview.md#post-findings-to-the-pull-request) | `claude ultrareview 1234 --json` |
51 +
52 +If you mistype a subcommand, Claude Code suggests the closest match and exits without starting a session. For example, `claude udpate` prints `Did you mean claude update?`.
53 +
54 +`claude --dangerously-skip-permissions daemon <subcommand>` runs the `daemon` subcommand, so the subcommand works when `claude` is aliased to include the flag. Only a leading `--dangerously-skip-permissions` or `--allow-dangerously-skip-permissions` routes to `daemon` this way; with any other flag ahead of `daemon`, the subcommand doesn't run.
55 +
56 +## CLI flags
57 +
58 +Customize Claude Code's behavior with these command-line flags. `claude --help` does not list every flag, so a flag's absence from `--help` does not mean it is unavailable.
59 +
60 +| Flag | Description | Example |
61 +| :- | :- | :- |
62 +| `--add-dir` | Add additional working directories for Claude to read and edit files. Grants file access; Claude Code [doesn't discover](https://code.claude.com/docs/en/permissions.md#additional-directories-grant-file-access-not-configuration) most `.claude/` configuration from these directories. Validates that each path exists as a directory. You can't add most [network paths](https://code.claude.com/docs/en/errors.md#working-directory-is-a-network-path), such as `\\server\share`. To persist these directories across sessions, set [`permissions.additionalDirectories`](https://code.claude.com/docs/en/settings-reference#permissions-additionaldirectories) in settings | `claude --add-dir ../apps ../lib` |
63 +| `--advisor <model>` | Enable the server-side [advisor tool](https://code.claude.com/docs/en/advisor.md) for this session with a model alias, `fable`, `opus`, or `sonnet`, or a full model ID. Takes precedence over the `advisorModel` setting for the session. `fable` requires [Fable access](https://code.claude.com/docs/en/advisor.md#choose-an-advisor-model) | `claude --advisor opus` |
64 +| `--agent` | Specify an agent for the current session (overrides the `agent` setting) | `claude --agent my-custom-agent` |
65 +| `--agents` | Define custom subagents dynamically via JSON. Accepts the [fields listed for CLI-defined subagents](https://code.claude.com/docs/en/sub-agents.md#choose-the-subagent-scope). With `--print`, the value can instead be the path to a JSON file holding the object; the file form requires Claude Code v2.1.281 or later. Claude Code validates the value at startup and exits on an invalid one; see [`Invalid --agents configuration`](https://code.claude.com/docs/en/errors#invalid-agents-configuration) for the message and for the flags and environment variable that skip the validation. Validation requires Claude Code v2.1.242 or later | `claude --agents '{"reviewer":{"description":"Reviews code","prompt":"You are a code reviewer"}}'` |
66 +| `--allow-dangerously-skip-permissions` | Add `bypassPermissions` to the `Shift+Tab` mode cycle without starting in it. Lets you begin in a different mode like `plan` and switch to `bypassPermissions` later. See [permission modes](https://code.claude.com/docs/en/permission-modes.md#skip-all-checks-with-bypasspermissions-mode) | `claude --permission-mode plan --allow-dangerously-skip-permissions` |
67 +| `--allowedTools`, `--allowed-tools` | Tools that execute without prompting for permission, apart from reads from [network paths](https://code.claude.com/docs/en/permissions.md#network-paths). See [permission rule syntax](https://code.claude.com/docs/en/settings-reference.md#permission-rule-syntax) for pattern matching. To restrict which tools are available, use `--tools` instead. If you name one of the [task-tracking tools](https://code.claude.com/docs/en/tools-reference.md#task-tool-availability) here, Claude Code also opts the session in | `"Bash(git log *)" "Bash(git diff *)" "Read"` |
68 +| `--append-subagent-system-prompt` | Append custom text to the end of every [subagent](https://code.claude.com/docs/en/sub-agents.md)'s system prompt, nested subagents included, apart from a [forked subagent](https://code.claude.com/docs/en/sub-agents.md#fork-the-current-conversation), which reuses the conversation's own prompt. Only applies in non-interactive mode with `-p`. Requires Claude Code v2.1.205 or later | `claude -p --append-subagent-system-prompt "Cite file paths in every answer" "query"` |
69 +| `--append-subagent-system-prompt-file` | Load text from a file and append it to [subagent](https://code.claude.com/docs/en/sub-agents.md) system prompts. An alternative to `--append-subagent-system-prompt` for text too long to pass on the command line. The two flags can't be combined. Only applies in non-interactive mode with `-p`. Requires Claude Code v2.1.261 or later | `claude -p --append-subagent-system-prompt-file ./subagent-rules.txt "query"` |
70 +| `--append-system-prompt` | Append custom text to the end of the default system prompt | `claude --append-system-prompt "Always use TypeScript"` |
71 +| `--append-system-prompt-file` | Load additional system prompt text from a file and append to the default prompt | `claude --append-system-prompt-file ./extra-rules.txt` |
72 +| `--autocompact <auto\|tokens>` | Set the [auto-compact window](https://code.claude.com/docs/en/model-config.md#set-the-auto-compact-window) for this session without changing your saved settings. Accepts the same values as `/autocompact`; that section covers the value forms and what overrides the flag. Requires Claude Code v2.1.221 or later | `claude --autocompact 500k` |
73 +| `--ax-screen-reader` | Render screen-reader friendly output: flat text without decorative borders or animations. Forces the classic renderer, so the [`tui`](https://code.claude.com/docs/en/settings-reference#tui) setting has no effect; attached [background sessions](https://code.claude.com/docs/en/agent-view.md) still render fullscreen. Takes precedence over [`CLAUDE_AX_SCREEN_READER`](https://code.claude.com/docs/en/env-vars) and the [`axScreenReader`](https://code.claude.com/docs/en/settings-reference#axscreenreader) setting. Requires Claude Code v2.1.181 or later | `claude --ax-screen-reader` |
74 +| `--bare` | Minimal mode: skip auto-discovery of hooks, skills, custom commands, subagents, installed plugins, MCP servers, auto memory, and CLAUDE.md so scripted calls start faster. Skills in a directory you pass with `--add-dir` still load. Claude has access to Bash, file read, and file edit tools. Sets [`CLAUDE_CODE_SIMPLE`](https://code.claude.com/docs/en/env-vars). See [bare mode](https://code.claude.com/docs/en/headless.md#start-faster-with-bare-mode) | `claude --bare -p "query"` |
75 +| `--betas` | Beta headers to include in API requests (API key users only) | `claude --betas interleaved-thinking` |
76 +| `--bg`, `--background` | Start the session as a [background agent](https://code.claude.com/docs/en/agent-view.md) and return immediately. Prints the session ID and management commands. Combine with `--exec` to run a shell command as a background job instead of a Claude session, or with `--agent` to run a specific subagent. Checks [workspace trust](https://code.claude.com/docs/en/permissions.md#project-allow-rules-and-workspace-trust) for the directory before it starts. Can't be combined with `-p`/`--print`; see the [error reference](https://code.claude.com/docs/en/errors.md#command-line-errors) | `claude --bg "investigate the flaky test"` |
77 +| `--channels` | (Research preview) MCP servers whose [channel](https://code.claude.com/docs/en/channels.md) notifications Claude should listen for in this session. Space-separated list of `plugin:<name>@<marketplace>` entries. Requires Anthropic authentication through claude.ai or a Console API key | `claude --channels plugin:my-notifier@my-marketplace` |
78 +| `--chrome` | Enable [Chrome browser integration](https://code.claude.com/docs/en/chrome.md) for web automation and testing | `claude --chrome` |
79 +| `--cloud` | With a task description, create a new [cloud session](https://code.claude.com/docs/en/claude-code-on-the-web.md). With a session ID (`session_...` or `cse_...`) or a claude.ai/code URL, queue a message into that existing session instead, with `-p`. See [send a follow-up message](https://code.claude.com/docs/en/claude-code-on-the-web.md#send-follow-ups-from-the-cli). | `claude --cloud "Fix the login bug"` |
80 +| `--continue`, `-c` | Load the most recent conversation in the current directory, including a [background session that has finished](https://code.claude.com/docs/en/sessions.md#where-the-session-picker-looks); opening finished background sessions requires Claude Code v2.1.257 or later. Skips sessions created with `claude -p` or the Agent SDK, and sessions whose first prompt was `/loop`. `claude -p --continue` includes `-p`, SDK, and `/loop` sessions. Includes sessions that added this directory with `/add-dir` | `claude --continue` |
81 +| `--dangerously-load-development-channels` | Enable [channels](https://code.claude.com/docs/en/channels-reference.md#test-during-the-research-preview) that are not on the approved allowlist, for local development. Accepts `plugin:<name>@<marketplace>` and `server:<name>` entries. Prompts for confirmation, so it takes effect in interactive sessions. With `-p`, Claude Code ignores the flag | `claude --dangerously-load-development-channels server:webhook` |
82 +| `--dangerously-skip-permissions` | Skip permission prompts. Equivalent to `--permission-mode bypassPermissions`. See [permission modes](https://code.claude.com/docs/en/permission-modes.md#skip-all-checks-with-bypasspermissions-mode) for what this does and does not skip. For sessions started with `--bg`, the mode [persists when the supervisor restarts the session](https://code.claude.com/docs/en/agent-view.md#permission-mode-model-and-effort) | `claude --dangerously-skip-permissions` |
83 +| `--debug` | Enable debug mode with optional category filtering, such as `--debug='mcp,startup'` or `--debug='!mcp'`. The filter binds only in the `=` form; a space-separated filter enables debug mode without filtering | `claude --debug='mcp,startup'` |
84 +| `--debug-file <path>` | Write debug logs to a specific file path. Implicitly enables debug mode. Takes precedence over `CLAUDE_CODE_DEBUG_LOGS_DIR` | `claude --debug-file /tmp/claude-debug.log` |
85 +| `--desktop` | Open the [Claude Desktop app](https://code.claude.com/docs/en/desktop.md) on the current directory and exit without starting a session in the terminal. Add `--continue`, or `--resume` with a session ID, to [open that session in Desktop](https://code.claude.com/docs/en/desktop.md#coming-from-the-cli) instead. `--resume` here takes only a session ID, not a name or transcript path. Takes no prompt and no other flags except `--verbose` and the `--debug` flags, since the app starts the session itself. Available on macOS and x64 Windows when you're signed in with a Claude subscription. Requires Claude Code v2.1.285 or later | `claude --desktop` |
86 +| `--disable-slash-commands` | Disable all skills and commands for this session | `claude --disable-slash-commands` |
87 +| `--disallowedTools`, `--disallowed-tools` | Deny rules. A bare tool name removes the matching tools from Claude's context: `"Edit"` removes Edit, `"*"` removes every tool, and `"mcp__*"` removes every MCP tool. A scoped rule such as `Bash(rm *)` leaves the tool available and denies only calls that match [as written](https://code.claude.com/docs/en/permissions.md#bash-rule-limits). A rule naming [`EndConversation`](https://code.claude.com/docs/en/tools-reference#endconversation-tool-behavior) can't remove it while any other tool remains | `"Bash(git log *)" "Bash(git diff *)" "Edit"` |
88 +| `--effort` | Set the [effort level](https://code.claude.com/docs/en/model-config.md#adjust-effort-level) for the current session. Options: `low`, `medium`, `high`, `xhigh`, `max`, or `ultracode`. Available levels depend on the model. `ultracode` requests `xhigh` effort with [ultracode](https://code.claude.com/docs/en/workflows.md#let-claude-decide-with-ultracode) turned on, and requires Claude Code v2.1.203 or later. Overrides the [`modelSettings`](https://code.claude.com/docs/en/settings-reference#modelsettings) and [`effortLevel`](https://code.claude.com/docs/en/settings-reference#effortlevel) settings for this session and does not persist | `claude --effort high` |
89 +| `--enable-auto-mode` | Removed in v2.1.111. Auto mode is now in the `Shift+Tab` cycle by default; use `--permission-mode auto` to start in it | `claude --permission-mode auto` |
90 +| `--environment <environment-id>` | Create a new cloud session that runs on the [self-hosted environment](https://code.claude.com/docs/en/self-hosted-environments) with the given ID. Environment IDs start with `ccpool_`. See [`--environment` dispatch behavior](https://code.claude.com/docs/en/self-hosted-environments-testing#environment-dispatch-behavior) for dispatch behavior and the flag combinations it rejects. Requires Claude Code v2.1.224 or later | `claude -p "Fix the login bug" --environment ccpool_abc123` |
91 +| `--exclude-dynamic-system-prompt-sections` | Move per-user context, such as the auto memory location, out of the system prompt and into the first user message. Improves prompt-cache reuse across different users and machines running the same task. Only applies with the default system prompt; ignored when `--system-prompt` or `--system-prompt-file` is set. Use with `-p` for scripted, multi-user workloads | `claude -p --exclude-dynamic-system-prompt-sections "query"` |
92 +| `--exec` | Run a shell command as a PTY-backed background job instead of starting a Claude session. Use with `--bg` to launch from the shell | `claude --bg --exec 'pytest -x'` |
93 +| `--fallback-model` | Enable automatic fallback to the specified model(s) when the primary model is overloaded or not available, for example a retired model. Accepts a comma-separated list tried in order. See [Fallback model chains](https://code.claude.com/docs/en/model-config.md#fallback-model-chains). To persist a chain across sessions, use the [`fallbackModel` setting](https://code.claude.com/docs/en/settings-reference#fallbackmodel), which this flag overrides | `claude --fallback-model sonnet,haiku` |
94 +| `--fork-session` | When resuming, create a new session ID instead of reusing the original (use with `--resume` or `--continue`) | `claude --resume abc123 --fork-session` |
95 +| `--forward-subagent-text` | Emit [subagent](https://code.claude.com/docs/en/sub-agents.md) text and thinking blocks in the output stream as `assistant` and `user` messages with `parent_tool_use_id` set, so you can reconstruct each subagent's transcript. Without this flag, Claude Code omits the text and thinking blocks of a subagent that runs in the [foreground](https://code.claude.com/docs/en/sub-agents.md#run-subagents-in-foreground-or-background). Requires `--print` and `--output-format stream-json`. For nested subagents, forked skills, and the version each needs, see [Follow subagent messages](https://code.claude.com/docs/en/headless.md#follow-subagent-messages). The [`CLAUDE_CODE_FORWARD_SUBAGENT_TEXT`](https://code.claude.com/docs/en/env-vars) environment variable enables the same behavior. Requires Claude Code v2.1.211 or later | `claude -p --output-format stream-json --verbose --forward-subagent-text "query"` |
96 +| `--from-pr` | Open the session picker filtered to sessions linked to a specific pull request. Accepts a PR number, a GitHub or GitHub Enterprise PR URL, a GitLab merge request URL, or a Bitbucket pull request URL. Sessions are linked automatically when Claude creates the pull request | `claude --from-pr 123` |
97 +| `--ide` | Automatically connect to IDE on startup if exactly one valid IDE is available | `claude --ide` |
98 +| `--init` | Run [Setup hooks](https://code.claude.com/docs/en/hooks.md#setup) with the `init` matcher before the session (print mode only) | `claude -p --init "query"` |
99 +| `--init-only` | Run [Setup](https://code.claude.com/docs/en/hooks.md#setup) and `SessionStart` hooks, then exit without starting a conversation | `claude --init-only` |
100 +| `--include-hook-events` | Include hook lifecycle events in the output stream. `SessionStart` and `Setup` hook events are always included and don't need this flag. Some hook events, such as `Notification`, `SessionEnd`, `PreCompact`, and `PostCompact`, never produce a `hook_started` event, even with this flag. For those events, Claude Code still emits `hook_progress` while a command hook that runs for more than a second produces output, and emits `hook_response` only when a [hook that runs in the background](https://code.claude.com/docs/en/hooks.md#run-hooks-in-the-background) finishes. Requires `--output-format stream-json` | `claude -p --output-format stream-json --verbose --include-hook-events "query"` |
101 +| `--include-partial-messages` | Include partial streaming events in output. Requires `--print` and `--output-format stream-json` | `claude -p --output-format stream-json --verbose --include-partial-messages "query"` |
102 +| `--input-format` | Specify input format for print mode (options: `text`, `stream-json`) | `claude -p --output-format json --input-format stream-json` |
103 +| `--json-schema` | Get validated JSON output matching a JSON Schema after the agent completes its workflow (print mode only). See [structured outputs](https://code.claude.com/docs/en/agent-sdk/structured-outputs.md). Claude Code exits with an error on an invalid schema and accepts the `format` keyword as an annotation without client-side validation | `claude -p --json-schema '{"type":"object","properties":{...}}' "query"` |
104 +| `--maintenance` | Run [Setup hooks](https://code.claude.com/docs/en/hooks.md#setup) with the `maintenance` matcher before the session (print mode only) | `claude -p --maintenance "query"` |
105 +| `--max-budget-usd` | Stop the run once estimated spend on API calls reaches this amount (print mode only). Claude Code checks the cap against its [client-side cost estimate](https://code.claude.com/docs/en/agent-sdk/cost-tracking.md#estimates-not-billing), which can differ from your bill. Spend from [subagents](https://code.claude.com/docs/en/sub-agents.md) counts toward the cap. Spend can pass the cap, so [leave headroom](https://code.claude.com/docs/en/agent-sdk/agent-loop.md#budget-headroom). When you return to a conversation with `--continue` or `--resume`, totals [restored from earlier runs](https://code.claude.com/docs/en/agent-sdk/cost-tracking.md#accumulate-costs-across-multiple-calls) don't count toward it. Once spend reaches the cap, spawning another subagent fails with `Budget limit reached`, and Claude Code stops background subagents that are still running; the cap-enforcement behaviors require Claude Code v2.1.217 or later | `claude -p --max-budget-usd 5.00 "query"` |
106 +| `--max-turns` | Limit the number of agentic turns (print mode only). Exits with an error when the limit is reached. No limit by default. With `--input-format stream-json`, a message still queued when the limit ends a turn stays queued and starts a new turn with its own limit | `claude -p --max-turns 3 "query"` |
107 +| `--mcp-config` | Load MCP servers from JSON files or strings (space-separated). When you pass this flag with `-p`, Claude Code waits for still-pending servers to connect before running the first turn, up to the [`MCP_TIMEOUT`](https://code.claude.com/docs/en/env-vars) startup timeout, 30 seconds by default; a server with a [cached tool list](https://code.claude.com/docs/en/mcp.md#managing-your-servers) skips the wait and connects on first use. In a [self-hosted environment](https://code.claude.com/docs/en/self-hosted-environments-configuration.md#connection-timing), a shorter wait applies instead. The wait requires Claude Code v2.1.221 or later | `claude --mcp-config ./mcp.json` |
108 +| `--model` | Sets the model for the current session with a [model alias](https://code.claude.com/docs/en/model-config.md#model-aliases) such as `sonnet`, `opus`, `haiku`, or `fable`, or a model's full name. Overrides the [`model`](https://code.claude.com/docs/en/settings-reference#model) setting and [`ANTHROPIC_MODEL`](https://code.claude.com/docs/en/model-config#environment-variables) | `claude --model claude-sonnet-5` |
109 +| `--name`, `-n` | Set a display name for the session, shown in `/resume` and the terminal title. You can resume a named session with `claude --resume <name>`. [`/rename`](https://code.claude.com/docs/en/commands) changes the name mid-session and also shows it on the prompt bar | `claude -n "my-feature-work"` |
110 +| `--no-chrome` | Disable [Chrome browser integration](https://code.claude.com/docs/en/chrome.md) for this session | `claude --no-chrome` |
111 +| `--no-session-persistence` | Disable session persistence so sessions are not saved to disk and cannot be resumed. Print mode only. The [`CLAUDE_CODE_SKIP_PROMPT_HISTORY`](https://code.claude.com/docs/en/env-vars) environment variable does the same in any mode | `claude -p --no-session-persistence "query"` |
112 +| `--output-format` | Specify output format for print mode (options: `text`, `json`, `stream-json`) | `claude -p "query" --output-format json` |
113 +| `--permission-mode` | Begin in a specified [permission mode](https://code.claude.com/docs/en/permission-modes.md). Accepts `default`, `acceptEdits`, `plan`, `auto`, `dontAsk`, `bypassPermissions`, or `manual` as an alias for `default`. The `manual` alias selects the permission mode the UI labels Manual and requires Claude Code v2.1.200 or later; `claude --help` lists it in place of `default`, and both values work. Overrides `defaultMode` from settings files. Without this flag or `--dangerously-skip-permissions`, a new session starts in the permission mode described in [which permission mode a session starts in](https://code.claude.com/docs/en/permission-modes.md#which-mode-a-session-starts-in), which also covers what a `-p` run starts in | `claude --permission-mode plan` |
114 +| `--permission-prompt-tool` | Specify an MCP tool to handle permission prompts in non-interactive mode. Pass the full name, such as `mcp__<server>__<tool>`, of a tool on an MCP server that the run loads. Claude Code waits for that tool's MCP server to connect before running the first turn, up to the [`MCP_TIMEOUT`](https://code.claude.com/docs/en/env-vars) startup timeout, 30 seconds by default. The prompt tool can't approve an MCP tool marked as [requiring user interaction](https://code.claude.com/docs/en/mcp.md#require-approval-for-a-specific-tool): Claude Code converts an `allow` result for one to a deny. This restriction requires Claude Code v2.1.199 or later | `claude -p --mcp-config ./mcp.json --permission-prompt-tool mcp__permissions__approve "query"` |
115 +| `--permission-prompts` | Set who answers permission prompts in print mode. With the default `host`, Claude Code sends them to the Agent SDK host or the `--permission-prompt-tool` tool. Pass `none` when nobody can answer, and Claude Code denies them instead. See [Turn off permission prompts in unattended runs](https://code.claude.com/docs/en/headless.md#turn-off-permission-prompts-in-unattended-runs). Requires Claude Code v2.1.259 or later | `claude -p --permission-prompts none "query"` |
116 +| `--plugin-dir` | Load a plugin from a directory or `.zip` archive, or several from a [folder of plugins](https://code.claude.com/docs/en/plugins/create.md#load-a-directory-or-archive-for-one-session), for this session only. Each flag takes one path. Repeat the flag for more paths: `--plugin-dir A --plugin-dir B.zip`. Passing a folder of plugins requires Claude Code v2.1.265 or later | `claude --plugin-dir ./my-plugin` |
117 +| `--plugin-url` | Fetch a plugin `.zip` archive from a URL for this session only. Repeat the flag for multiple plugins, or pass space-separated URLs in a single quoted value | `claude --plugin-url https://example.com/plugin.zip` |
118 +| `--print`, `-p` | Print response without interactive mode (see [Agent SDK documentation](https://code.claude.com/docs/en/agent-sdk/overview.md) for programmatic usage details). For `--resume` on a background session that is still running, see [Resume a running background session](https://code.claude.com/docs/en/sessions.md#resume-a-running-background-session) | `claude -p "query"` |
119 +| `--prompt-suggestions` | Emit a `prompt_suggestion` message with a predicted next user prompt after each turn that generates one; very short conversations can produce none. Requires `--print`, `--output-format stream-json`, and `--verbose`. See [Prompt suggestions](https://code.claude.com/docs/en/interactive-mode.md#prompt-suggestions) | `claude -p --prompt-suggestions --output-format stream-json --verbose "query"` |
120 +| `--ref <branch>` | With `--environment`, base the new session's checkout on a named ref instead of local `HEAD` | `claude -p "Run the smoke test" --environment ccpool_abc123 --ref main` |
121 +| `--remote` | Deprecated alias for `--cloud`, including the existing-session form | `claude --remote "Fix the login bug"` |
122 +| `--remote-control`, `--rc` | Start an interactive session with [Remote Control](https://code.claude.com/docs/en/remote-control.md#start-a-remote-control-session) enabled so you can also control it from claude.ai or the Claude app. Optionally pass a name for the session | `claude --remote-control "My Project"` |
123 +| `--remote-control-session-name-prefix <prefix>` | Prefix for auto-generated [Remote Control](https://code.claude.com/docs/en/remote-control.md) session names when no explicit name is set. Defaults to your machine's hostname, producing names like `myhost-graceful-unicorn`. Set `CLAUDE_REMOTE_CONTROL_SESSION_NAME_PREFIX` for the same effect | `claude remote-control --remote-control-session-name-prefix dev-box` |
124 +| `--replay-user-messages` | Re-emit user messages from stdin back on stdout for acknowledgment. Requires `--input-format stream-json` and `--output-format stream-json` | `claude -p --input-format stream-json --output-format stream-json --verbose --replay-user-messages` |
125 +| `--restricted` | Start in restricted mode. Use it when an evaluation harness drives `claude` on a shared machine and Claude Code must not run commands or read that machine's user and project settings. Claude Code removes the built-in tools that run commands or code, and WebFetch, unless you name them individually in `--tools`, not through the `default` preset. It also confines the built-in file tools to the [working directories](https://code.claude.com/docs/en/permissions.md#working-directories), loads only [managed settings](https://code.claude.com/docs/en/managed-settings.md) and `--settings`, refuses [`bypassPermissions`](https://code.claude.com/docs/en/permission-modes#skip-all-checks-with-bypasspermissions-mode), and [refuses to create cloud sessions](https://code.claude.com/docs/en/errors.md#cloud-sessions-cannot-be-created-from-a-restricted-session). Requires Claude Code v2.1.248 or later | `claude --restricted -p "query"` |
126 +| `--resume`, `-r` | Resume a specific session by ID or name, or show an interactive picker to choose a session. In place of an ID, you can pass the absolute path to a session's `.jsonl` [transcript file](https://code.claude.com/docs/en/sessions.md#where-transcripts-are-stored). The picker and name search include sessions that added this directory with `/add-dir`. When you pass a session ID, Claude Code searches the current project directory and its git worktrees, then every other project on this machine. Before v2.1.223, the ID search covered only the current project directory and its git worktrees. [Background sessions](https://code.claude.com/docs/en/agent-view.md) appear in the picker marked with `bg`. Resuming one that is still running [opens that session](https://code.claude.com/docs/en/sessions.md#resume-a-running-background-session) in this terminal through `claude attach`, and a prompt you pass on the command line goes to it as its next turn. Before v2.1.285, Claude Code refused and printed the `claude attach` command to run instead | `claude --resume auth-refactor` |
127 +| `--safe-mode` | Start with all customizations disabled to troubleshoot a broken configuration: CLAUDE.md, skills, plugins, hooks, MCP servers, custom commands and agents, output styles, workflows, custom themes, custom keybindings, status line and file-suggestion commands, LSP servers, and auto memory do not load. Authentication, model selection, built-in tools, and permissions work normally, which differs from [`--bare`](https://code.claude.com/docs/en/headless#start-faster-with-bare-mode). Managed settings policy still applies, including policy-configured hooks, status line, and file-suggestion commands; managed plugins, managed skills, managed CLAUDE.md, and policy-configured MCP servers do not. Useful for checking whether a customization is what triggers [automatic model fallback](https://code.claude.com/docs/en/model-config.md#automatic-model-fallback). Sets [`CLAUDE_CODE_SAFE_MODE`](https://code.claude.com/docs/en/env-vars) | `claude --safe-mode` |
128 +| `--session-id` | Use a specific session ID for the conversation (must be a valid UUID) | `claude --session-id "550e8400-e29b-41d4-a716-446655440000"` |
129 +| `--setting-sources` | Comma-separated list of setting sources to load (`user`, `project`, `local`). See [agent view](https://code.claude.com/docs/en/agent-view.md#what-carries-over-when-you-background) and [agent teams](https://code.claude.com/docs/en/agent-teams.md#context-and-communication) for the sessions you start from this one that inherit the list | `claude --setting-sources user,project` |
130 +| `--settings` | Path to a settings JSON file or an inline JSON string. Values you set here override the same keys in your `settings.json` files for this session. Keys you omit keep their file-based values. The file must be a regular file no larger than 2 MiB. See [settings precedence](https://code.claude.com/docs/en/settings.md#settings-precedence) | `claude --settings ./settings.json` |
131 +| `--strict-mcp-config` | Only use MCP servers from `--mcp-config`, ignoring all other MCP configurations. See [Exclusive control with managed-mcp.json](https://code.claude.com/docs/en/managed-mcp.md#exclusive-control-with-managed-mcp-json) for what the flag does under a managed MCP file | `claude --strict-mcp-config --mcp-config ./mcp.json` |
132 +| `--system-prompt` | Replace the entire system prompt with custom text | `claude --system-prompt "You are a Python expert"` |
133 +| `--system-prompt-file` | Load system prompt from a file, replacing the default prompt | `claude --system-prompt-file ./custom-prompt.txt` |
134 +| `--system-prompt-snapshot` | Pass `off` to rebuild the system prompt on every request instead of reusing the prompt [recorded on the conversation's first request](#system-prompt-flags-in-resumed-conversations), for example while you iterate on `--append-system-prompt` text across `--continue` runs. Requires Claude Code v2.1.257 or later | `claude --system-prompt-snapshot off` |
135 +| `--teleport` | Resume a [cloud session](https://code.claude.com/docs/en/claude-code-on-the-web.md) in your local terminal | `claude --teleport` |
136 +| `--teammate-mode` | Set how [agent team](https://code.claude.com/docs/en/agent-teams.md) teammates display: `in-process` (default), `auto`, `tmux`, or `iterm2`. Overrides the [`teammateMode`](https://code.claude.com/docs/en/settings-reference#teammatemode) setting for this session. See [Choose a display mode](https://code.claude.com/docs/en/agent-teams.md#choose-a-display-mode) | `claude --teammate-mode auto` |
137 +| `--tmux` | Create a tmux session for the worktree. Requires `--worktree`. Uses iTerm2 native panes when available; pass `--tmux=classic` for traditional tmux | `claude -w feature-auth --tmux` |
138 +| `--tools` | Restrict which built-in tools Claude can use. Use `""` to disable all, `"default"` for the default set, or tool names like `"Bash,Edit,Read"`. On macOS, Linux, and WSL, the default set leaves out `Glob` and `Grep`, as described under [Glob tool behavior](https://code.claude.com/docs/en/tools-reference.md#glob-tool-behavior). If you name one of the [task-tracking tools](https://code.claude.com/docs/en/tools-reference.md#task-tool-availability) here, Claude Code also opts the session in. The flag doesn't affect MCP tools; to deny those too, use `--disallowedTools "mcp__*"`. A list that omits [`EndConversation`](https://code.claude.com/docs/en/tools-reference#endconversation-tool-behavior) doesn't remove it; `""` removes it only when no MCP tools remain | `claude --tools "Bash,Edit,Read"` |
139 +| `--verbose` | Enable verbose logging, shows full turn-by-turn output. Overrides the [`viewMode`](https://code.claude.com/docs/en/settings-reference#viewmode) setting for this session | `claude --verbose` |
140 +| `--version`, `-v` | Output the version number | `claude -v` |
141 +| `--worktree`, `-w` | Start Claude in an isolated [git worktree](https://code.claude.com/docs/en/worktrees.md) at `<repo>/.claude/worktrees/<name>`. If you don't give a name, Claude Code generates one. Pass `#<number>`, a GitHub pull request URL, or a GitLab merge request URL to [fetch that PR or MR from `origin` and branch the worktree from it](https://code.claude.com/docs/en/worktrees#branch-from-a-pull-request). Branching from a GitLab merge request requires Claude Code v2.1.233 or later | `claude -w feature-auth` |
142 +
143 +### System prompt flags
144 +
145 +Claude Code provides five flags for customizing the system prompt. Four set its text, and with `--system-prompt-snapshot` you control whether a conversation keeps the text it started with. All five work in both interactive and non-interactive modes.
146 +
147 +| Flag | Behavior | Example |
148 +| :- | :- | :- |
149 +| `--system-prompt` | Replaces the entire default prompt | `claude --system-prompt "You are a Python expert"` |
150 +| `--system-prompt-file` | Replaces with file contents | `claude --system-prompt-file ./prompts/review.txt` |
151 +| `--append-system-prompt` | Appends to the default prompt | `claude --append-system-prompt "Always use TypeScript"` |
152 +| `--append-system-prompt-file` | Appends file contents to the default prompt | `claude --append-system-prompt-file ./style-rules.txt` |
153 +| `--system-prompt-snapshot` | With `off`, rebuilds the prompt on every request. With `on`, the default, reuses a recorded prompt where [recording applies](#system-prompt-flags-in-resumed-conversations) | `claude --append-system-prompt "Draft rules" --system-prompt-snapshot off` |
154 +
155 +You can combine these flags. To replace the default prompt and still append your own text, pass `--append-system-prompt` or `--append-system-prompt-file` together with `--system-prompt` or `--system-prompt-file`. With Claude Code v2.1.283 or later, you can also pass a flag together with its own file form, such as `--append-system-prompt` with `--append-system-prompt-file`, and Claude Code uses both.
156 +
157 +For example, run the following in your shell to append both a style guide from a file and one extra instruction:
158 +
159 +```bash theme={null}
160 +claude -p --append-system-prompt-file ./style.md --append-system-prompt "Always reply in French" "Summarize README.md"
161 +```
162 +
163 +Claude receives the default system prompt followed by the contents of `style.md`, a blank line, and then `Always reply in French`. The file's contents come first even if you pass `--append-system-prompt` before `--append-system-prompt-file`.
164 +
165 +When the replacement text combines instructions that are the same on every run with context that changes per run, add a line containing only `__SYSTEM_PROMPT_DYNAMIC_BOUNDARY__` between the instructions and the context. Claude Code splits the prompt at the first such line and removes that line, so the part above it stays cached while the part below changes. Requires Claude Code v2.1.275 or later. [Cache the static part of a custom prompt](https://code.claude.com/docs/en/agent-sdk/modifying-system-prompts.md#cache-the-static-part-of-a-custom-prompt) lists the configurations where the split applies.
166 +
167 +Choose based on whether Claude Code's default identity still fits your task. Use an append flag when Claude should remain a coding assistant that also follows your extra rules: per-invocation instructions, output formatting, or domain context for a `-p` script. Appending preserves the default tool guidance, safety instructions, and coding conventions, so you only supply what differs. Use a replacement flag when the surface, identity, or permission model differs from Claude Code's, like a non-coding agent in a pipeline that no human watches. Replacing drops all of the default prompt, including tool guidance and safety instructions, so you take responsibility for whatever your task still needs.
168 +
169 +For persistent personas you can switch between and share across a project, use [output styles](https://code.claude.com/docs/en/output-styles.md). For project conventions Claude should always follow, use [CLAUDE.md](https://code.claude.com/docs/en/memory.md). The [Agent SDK guide on system prompts](https://code.claude.com/docs/en/agent-sdk/modifying-system-prompts.md#decide-on-a-starting-point) covers the same decision in more depth.
170 +
171 +#### System prompt flags in resumed conversations
172 +
173 +By default, Claude Code builds the system prompt once, on a conversation's first request, with the text from any system prompt flags applied, and records it in the session. Until the conversation is compacted, every later request uses that recorded prompt, including after you return to the conversation with `--resume` or `--continue`. If you pass different system prompt flag text, or none, on that later launch, it takes effect once the conversation is compacted or when you start a new conversation.
174 +
175 +Outside of [cloud sessions](https://code.claude.com/docs/en/cloud-environments.md), if you start Claude Code in [bare mode](https://code.claude.com/docs/en/headless.md#start-faster-with-bare-mode) by passing `--bare` or setting `CLAUDE_CODE_SIMPLE=1`, recording stays off unless you pass `--system-prompt-snapshot on`. Before v2.1.268, sessions that don't [fetch feature flags](https://code.claude.com/docs/en/env-vars.md#features-that-need-feature-flag-fetching), including sessions on Amazon Bedrock, Google Cloud's Agent Platform, and Microsoft Foundry, rebuilt the prompt on every request and `--system-prompt-snapshot` had no effect.
176 +
177 +To rebuild the prompt on every request instead, for example while you iterate on its wording across `--continue` runs, pass `--system-prompt-snapshot off`. Before v2.1.265, passing any of the system prompt flags also turned recording off unless you passed `--system-prompt-snapshot on`.
178 +
179 +## See also
180 +
181 +* [Chrome extension](https://code.claude.com/docs/en/chrome.md) - Browser automation and web testing
182 +* [Interactive mode](https://code.claude.com/docs/en/interactive-mode.md) - Shortcuts, input modes, and interactive features
183 +* [Quickstart guide](https://code.claude.com/docs/en/quickstart.md) - Getting started with Claude Code
184 +* [Common workflows](https://code.claude.com/docs/en/common-workflows.md) - Advanced workflows and patterns
185 +* [Settings](https://code.claude.com/docs/en/settings.md) - Configuration options
186 +* [Agent SDK documentation](https://code.claude.com/docs/en/agent-sdk/overview.md) - Programmatic usage and integrations
added docs/claude-code-docs/headless.md +416 −0
@@ -0,0 +1,416 @@
1 +> ## Documentation Index
2 +> Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt
3 +> Use this file to discover all available pages before exploring further.
4 +
5 +# Run Claude Code programmatically
6 +
7 +> Use the Agent SDK to run Claude Code programmatically from the CLI, Python, or TypeScript.
8 +
9 +The [Agent SDK](https://code.claude.com/docs/en/agent-sdk/overview.md) gives you the same tools, agent loop, and context management that power Claude Code. It's available as a CLI for scripts and CI/CD, or as [Python](https://code.claude.com/docs/en/agent-sdk/python.md) and [TypeScript](https://code.claude.com/docs/en/agent-sdk/typescript.md) packages for full programmatic control.
10 +
11 +To run Claude Code in non-interactive mode, pass `-p` with your prompt and the [CLI options](https://code.claude.com/docs/en/cli-reference.md) you need:
12 +
13 +```bash theme={null}
14 +claude -p "Find and fix the bug in auth.py" --allowedTools "Read,Edit,Bash"
15 +```
16 +
17 +This page covers using the Agent SDK via the CLI (`claude -p`). For the Python and TypeScript SDK packages with structured outputs, tool approval callbacks, and native message objects, see the [full Agent SDK documentation](https://code.claude.com/docs/en/agent-sdk/overview.md).
18 +
19 +## Basic usage
20 +
21 +Add the `-p` (or `--print`) flag to any `claude` command to run it non-interactively. Not every [CLI option](https://code.claude.com/docs/en/cli-reference.md) combines with `-p`. Claude Code rejects `--bg`, and rejects `--cloud` with a task description, with an error naming the conflict; `--cloud` with a session ID and `-p` instead [queues a message into that cloud session](https://code.claude.com/docs/en/claude-code-on-the-web.md#send-follow-ups-from-the-cli) and exits. Options you'll combine with `-p` often include:
22 +
23 +* `--continue` for [continuing conversations](#continue-conversations)
24 +* `--allowedTools` for [auto-approving tools](#auto-approve-tools)
25 +* `--output-format` for [structured output](#get-structured-output)
26 +
27 +This example asks Claude a question about your codebase and prints the response:
28 +
29 +```bash theme={null}
30 +claude -p "What does the auth module do?"
31 +```
32 +
33 +Claude Code exits with code 0 on success and a non-zero code when the run fails, so your scripts can branch on the exit status. If you pass an invalid flag, Claude Code reports the error to stderr before the run starts. When a failure happens inside the run, such as missing authentication, Claude Code prints the failure as the result on stdout.
34 +
35 +### Start faster with bare mode
36 +
37 +Add `--bare` to reduce startup time by skipping auto-discovery of hooks, skills, custom commands, [subagents](https://code.claude.com/docs/en/sub-agents.md), installed plugins, MCP servers, auto memory, and CLAUDE.md. Without it, `claude -p` discovers and loads them as an interactive session would, including anything configured in the working directory or `~/.claude`.
38 +
39 +Bare mode is useful for CI and scripts where you need the same result on every machine. A hook in a teammate's `~/.claude` or an MCP server in the project's `.mcp.json` won't run, because bare mode never reads them. A directory you name with `--add-dir` is a partial exception: bare mode loads skills from its `.claude/skills/` folder, but still skips its `.claude/commands/` and `.claude/agents/` folders. [Skills from additional directories](https://code.claude.com/docs/en/skills.md#skills-from-additional-directories) covers what does and doesn't load.
40 +
41 +Without `--bare`, a `-p` session runs the hooks in a project's `.claude/settings.json` and connects the servers in its `.mcp.json`, even in a folder you've never trusted. A `-p` session shows no workspace trust dialog and no per-server approval prompt. [What runs before you trust a folder](https://code.claude.com/docs/en/permissions.md#what-runs-before-you-trust-a-folder) covers each kind of repository content under `-p` and how to keep it out.
42 +
43 +This example runs a one-off summarize task in bare mode and pre-approves the Read tool so the call completes without a permission prompt. Set `ANTHROPIC_API_KEY` before running it, because bare mode doesn't use your subscription login:
44 +
45 +```bash theme={null}
46 +claude --bare -p "Summarize README.md" --allowedTools "Read"
47 +```
48 +
49 +In bare mode, Claude Code never reads OAuth credentials or the system keychain. For the Anthropic API, set `ANTHROPIC_API_KEY` in the environment, with a key created in the [Claude Console](https://platform.claude.com), or supply an `apiKeyHelper` in the `--settings` JSON. Amazon Bedrock, Google Cloud's Agent Platform, and Microsoft Foundry continue to read their own provider credentials as usual.
50 +
51 +In bare mode Claude has access to the Bash, file read, and file edit tools. Pass any context you need with a flag:
52 +
53 +| To load | Use |
54 +| - | - |
55 +| System prompt additions | `--append-system-prompt`, `--append-system-prompt-file` |
56 +| Settings | `--settings <file-or-json>` |
57 +| MCP servers | `--mcp-config <file-or-json>` |
58 +| [Custom agents](https://code.claude.com/docs/en/sub-agents.md#choose-the-subagent-scope) | `--agents <file-or-json>` |
59 +| A plugin | `--plugin-dir <path>`, `--plugin-url <url>` |
60 +
61 +Bare mode also limits what happens while the session runs:
62 +
63 +* **MCP servers**: only servers supplied on the command line connect, for example with `--mcp-config`. In an interactive session, Claude Code also skips the automatic IDE connection unless you pass `--ide`.
64 +* **System reminders**: Claude gets your prompts and the tool results without the [system reminders](https://code.claude.com/docs/en/glossary.md#system-reminder) Claude Code would add alongside them. For example, Claude isn't told when a file it read earlier changes on disk, and it doesn't get the list of available skills, including skills from an `--add-dir` folder.
65 +* **Background tasks**: Claude can't run background commands or background subagents, and the other features that [`CLAUDE_CODE_DISABLE_BACKGROUND_TASKS`](https://code.claude.com/docs/en/env-vars) turns off are off too. A command that reaches its [timeout](https://code.claude.com/docs/en/tools-reference.md#timeout-and-output-limits) stops instead of [moving to the background](https://code.claude.com/docs/en/tools-reference.md#background-commands).
66 +
67 +Before v2.1.286, these limits held only partly: an interactive `--bare` session connected the MCP servers that a normal session would, every `--bare` session sent system reminders, and background tasks stayed available.
68 +
69 +> [!NOTE]
70 +>
71 +> `--bare` is the recommended mode for scripted and SDK calls, and will become the default for `-p` in a future release.
72 +
73 +### Background tasks at exit
74 +
75 +After Claude finishes its turn and stdin has closed, a `claude -p` run can stay open to wait for background work that Claude started.
76 +
77 +Unless a background command that the main conversation started is still running, Claude Code stops whatever is still running after 10 minutes of continuous idle waiting by default and drops its partial result. To change the 10-minute cap, set [`CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS`](https://code.claude.com/docs/en/env-vars), or set it to `0` to wait without one.
78 +
79 +The run waits for background work such as background commands, subagents and workflows, Monitor watches, and pending `/loop` wakeups:
80 +
81 +* **[Background commands](https://code.claude.com/docs/en/tools-reference.md#background-commands)**: for a command that the main conversation started, for example a dev server or a watch build, the run waits until the command exits or reaches its [time limit](https://code.claude.com/docs/en/tools-reference.md#time-limit-for-background-commands). Claude then takes one more turn with the outcome. While the command runs, the 10-minute cap doesn't end the wait.
82 +* **Background [subagents](https://code.claude.com/docs/en/sub-agents.md) and workflows**: the run stays open until that work completes, because its result is part of the final output.
83 +* **[Monitor](https://code.claude.com/docs/en/tools-reference.md#monitor-tool) watches**: the run waits until the watch times out or the 10-minute cap ends the wait, whichever comes first. While it waits, Claude keeps responding to what the watch reports. By default, a watch times out five minutes after Claude starts it.
84 +* **Pending wakeups**: in a run whose prompt you passed as text rather than with `--input-format stream-json`, when Claude has scheduled a [self-paced `/loop` wakeup](https://code.claude.com/docs/en/scheduled-tasks#let-claude-choose-the-interval), the run waits for each wakeup to fire and runs its iteration until the [loop ends](https://code.claude.com/docs/en/scheduled-tasks.md#stop-a-loop), even past the 10-minute cap.
85 +
86 +When stderr is a terminal and the run has waited five seconds, Claude Code prints a line to stderr that starts with `Waiting for background work to finish` and names the work. With [`json` or `stream-json` output](#get-structured-output), the line prints only when stdout isn't a terminal, so the JSON your script reads never carries it.
87 +
88 +If the run reaches its [`--max-budget-usd`](https://code.claude.com/docs/en/cli-reference#cli-flags) cap, Claude Code stops the remaining background work instead of waiting.
89 +
90 +When background work starts another turn, the run prints each turn's result with the default `text` output and the last turn's result with `json` output. Before v2.1.295, the run printed only the last turn's result with `text` output too.
91 +
92 +#### MCP work when a non-interactive run ends
93 +
94 +A `claude -p` run doesn't wait for MCP work in the background:
95 +
96 +* **[MCP tasks](https://code.claude.com/docs/en/mcp.md#mcp-tasks-that-run-on-the-server)**: on a remote server the job goes on. To follow it again, [resume that session](https://code.claude.com/docs/en/mcp.md#exit-clear-or-resume-while-an-mcp-task-runs), not as a one-shot `claude -p "<prompt>"` run.
97 +* **MCP calls that [automatic backgrounding](https://code.claude.com/docs/en/mcp.md#automatic-backgrounding-of-long-tool-calls) moved**: the call's result is lost.
98 +
99 +### Stop a run with SIGTERM
100 +
101 +If you stop a `claude -p` run with SIGTERM, for example with `kill` or from a process supervisor, Claude Code exits with code 143. Claude Code leaves the turn that was in progress unfinished and records no result for it. To end the turn instead, send SIGINT, or call the Agent SDK's `interrupt()`, before you stop the process.
102 +
103 +On SIGTERM, Claude Code terminates the process tree of any Bash command that is still running. Claude Code then runs [`SessionEnd` hooks](https://code.claude.com/docs/en/hooks#sessionend) and exits. While exiting, Claude Code starts no new tool call, sends no new model request, and runs no hook other than `SessionEnd`. If the run was in the middle of a command or waiting on a permission prompt when the signal arrived, Claude Code handles that step as follows:
104 +
105 +* **Running a command**: Claude Code records the command as killed in the session.
106 +* **Waiting for an answer to a permission prompt**: if you send SIGTERM to the process, Claude Code leaves the prompt unanswered. If your program closes the session through the Agent SDK, the SDK ends Claude Code's input before sending any signal, and Claude Code cancels the prompt as soon as the input ends.
107 +
108 +When you [resume the session](#continue-conversations), Claude Code leaves the interrupted turn as it is, and your next prompt drives the conversation. To have Claude Code continue the interrupted turn on resume instead, set [`CLAUDE_CODE_RESUME_INTERRUPTED_TURN=1`](https://code.claude.com/docs/en/env-vars).
109 +
110 +### If the working directory is deleted
111 +
112 +If the working directory of a `claude -p` or Agent SDK session is deleted mid-session, the session keeps running. When a turn starts while the directory is missing, Claude Code emits a [warning message](https://code.claude.com/docs/en/agent-sdk/typescript.md#sdkinformationalmessage) in `stream-json` output, and shell commands fail until the directory exists again.
113 +
114 +## Examples
115 +
116 +These examples highlight common CLI patterns. Where a command names a file such as `auth.py` or `build-error.txt`, substitute a file from your own project. In CI or other scripted environments, add [`--bare`](#start-faster-with-bare-mode) so Claude Code starts without loading the host's hooks, plugins, auto memory, or `CLAUDE.md`.
117 +
118 +### Pipe data through Claude
119 +
120 +Non-interactive mode reads stdin, so you can pipe data in and redirect the response out like any other command-line tool.
121 +
122 +This example pipes a build log into Claude and writes the explanation to a file:
123 +
124 +```bash theme={null}
125 +cat build-error.txt | claude -p 'concisely explain the root cause of this build error' > output.txt
126 +```
127 +
128 +With `--output-format json`, the response payload includes `total_cost_usd` and a per-model cost breakdown, so scripted callers can track spend without consulting the [usage dashboard](https://code.claude.com/docs/en/costs.md). When you continue an earlier conversation with `--continue` or `--resume`, the run reports the conversation's whole total, [earlier runs' spend included](https://code.claude.com/docs/en/agent-sdk/cost-tracking.md#accumulate-costs-across-multiple-calls). Both figures are [client-side estimates](https://code.claude.com/docs/en/agent-sdk/cost-tracking.md) and can differ from your actual bill.
129 +
130 +> [!NOTE]
131 +>
132 +> Piped stdin is capped at 10MB. If you exceed the cap, Claude Code exits with a clear error and a non-zero status. To work with larger inputs, write the content to a file and reference the file path in your prompt instead of piping it.
133 +
134 +If Claude Code can't read stdin, for example because the process that started it disconnected its end, Claude Code prints a warning to stderr and continues with the prompt from the command line.
135 +
136 +### Add Claude to a build script
137 +
138 +You can wrap a non-interactive call in a script to use Claude as a project-specific linter or reviewer.
139 +
140 +This `package.json` script pipes the diff against `main` into Claude and asks it to report typos. Piping the diff means Claude doesn't need Bash permission to read it, and the escaped double quotes keep the script portable to Windows:
141 +
142 +```json theme={null}
143 +{
144 + "scripts": {
145 + "lint:claude": "git diff main | claude -p \"you are a typo linter. for each typo in this diff, report filename:line on one line and the issue on the next. return nothing else.\""
146 + }
147 +}
148 +```
149 +
150 +Run it with `npm run lint:claude`.
151 +
152 +### Get structured output
153 +
154 +Use `--output-format` to control how responses are returned:
155 +
156 +* `text` (default): plain text output
157 +* `json`: structured JSON with result, session ID, and metadata
158 +* `stream-json`: newline-delimited JSON for real-time streaming
159 +
160 +This example returns a project summary as JSON with session metadata, with the text result in the `result` field:
161 +
162 +```bash theme={null}
163 +claude -p "Summarize this project" --output-format json
164 +```
165 +
166 +To get output conforming to a specific schema, use `--output-format json` with `--json-schema` and a [JSON Schema](https://json-schema.org/) definition. The response includes metadata about the request (session ID, usage, etc.) with the structured output in the `structured_output` field.
167 +
168 +This example extracts function names and returns them as an array of strings:
169 +
170 +```bash theme={null}
171 +claude -p "Extract the main function names from auth.py" \
172 + --output-format json \
173 + --json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}'
174 +```
175 +
176 +If the value isn't a valid JSON Schema, `claude` exits with `Error: --json-schema is not a valid JSON Schema` followed by the validator's diagnostic. Claude Code accepts schemas that use the `format` keyword, such as `"format": "email"`, but treats `format` as an annotation and doesn't enforce it.
177 +
178 +If a run ends without valid structured output, for example because Claude declined the request, the response has no `structured_output` field. Before your script uses `structured_output`, check that the field is present.
179 +
180 +> [!TIP]
181 +>
182 +> Use a tool like [jq](https://jqlang.org/) to parse the response and extract specific fields:
183 +>
184 +> ```bash theme={null}
185 +> # Extract the text result
186 +> claude -p "Summarize this project" --output-format json | jq -r '.result'
187 +>
188 +> # Extract structured output
189 +> claude -p "Extract function names from auth.py" \
190 +> --output-format json \
191 +> --json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}' \
192 +> | jq '.structured_output'
193 +> ```
194 +
195 +### Stream responses
196 +
197 +Use `--output-format stream-json` with `--verbose` and `--include-partial-messages` to receive tokens as they're generated. Each line is a JSON object representing an event:
198 +
199 +```bash theme={null}
200 +claude -p "Explain recursion" --output-format stream-json --verbose --include-partial-messages
201 +```
202 +
203 +The last line of the stream is a `result` message with the final response text, cost, and session metadata.
204 +
205 +If your consumer reads the stream slowly, Claude Code waits for the queued output to drain before exiting, scaling the wait with how much is still queued, capped at 30 seconds.
206 +
207 +The following example uses [jq](https://jqlang.org/) to filter for text deltas and display only the streaming text. The `-r` flag outputs raw strings (no quotes) and `-j` joins without newlines so tokens stream continuously:
208 +
209 +```bash theme={null}
210 +claude -p "Write a poem" --output-format stream-json --verbose --include-partial-messages | \
211 + jq -rj 'select(.type == "stream_event" and .event.delta.type? == "text_delta") | .event.delta.text'
212 +```
213 +
214 +For programmatic streaming with callbacks and message objects, see [Stream responses in real-time](https://code.claude.com/docs/en/agent-sdk/streaming-output.md) in the Agent SDK documentation.
215 +
216 +#### Follow subagent messages
217 +
218 +Messages from [subagents](https://code.claude.com/docs/en/sub-agents.md) and from skills that [run in a subagent](https://code.claude.com/docs/en/skills.md#run-skills-in-a-subagent) appear in the stream as `assistant` and `user` messages. Their `parent_tool_use_id` field says which run each one belongs to. Messages from the main conversation carry `null` in that field.
219 +
220 +The first message from a forked skill, or from a subagent running in the [foreground](https://code.claude.com/docs/en/sub-agents.md#run-subagents-in-foreground-or-background), is a `user` message carrying the prompt or skill content that drives it. After that first message, Claude Code emits:
221 +
222 +* **By default**: the run's `tool_use` and `tool_result` blocks.
223 +* **With [`--forward-subagent-text`](https://code.claude.com/docs/en/cli-reference#cli-flags) or [`CLAUDE_CODE_FORWARD_SUBAGENT_TEXT`](https://code.claude.com/docs/en/env-vars)**: the run's text and thinking blocks too, so you can reconstruct each run's transcript.
224 +
225 +When you enable either option, Claude Code forwards messages from [subagents at every nesting depth](https://code.claude.com/docs/en/sub-agents.md#let-subagents-spawn-their-own-subagents), whether each one was spawned with the Agent tool or started as a forked skill. In `parent_tool_use_id`, the nested subagent's messages carry the ID of the Agent or Skill tool call that started it, so you can rebuild the full nesting tree by following those IDs.
226 +
227 +A run that Claude starts with a tool call carries that tool call's ID. A forked skill that you start by passing `/<skill-name>` as the prompt has no tool call, so its messages carry a `forked-command-` value instead and arrive after it finishes. Find how the run started in the first column:
228 +
229 +| How the run starts | `parent_tool_use_id` | When its messages arrive |
230 +| :- | :- | :- |
231 +| Claude calls the Agent tool from the main conversation | The ID of that Agent `tool_use` block | While the subagent works |
232 +| Claude calls the Skill tool for a forked skill from the main conversation | The ID of that Skill `tool_use` block | While the forked skill works |
233 +| You pass `/<skill-name>` as the prompt | A value that starts with `forked-command-` | Together and in order after the forked skill finishes |
234 +
235 +For a forked skill started from the prompt, match `parent_tool_use_id` on the `forked-command-` prefix, because the name after it can differ from the one you typed.
236 +
237 +If some of these messages are missing from your stream, check your Claude Code version against these minimums:
238 +
239 +* **A forked skill that Claude starts with the Skill tool from the main conversation**: v2.1.86 or later for its `tool_use` and `tool_result` blocks, and v2.1.265 or later for its first `user` message and its text and thinking blocks
240 +* **Messages of subagents that a forked skill spawns, and of forked skills started inside a subagent or another forked skill**: v2.1.275 or later
241 +* **Messages of a forked skill you start by passing `/<skill-name>` as the prompt**: v2.1.287 or later
242 +
243 +#### Handle API retries
244 +
245 +When an API request fails with a retryable error, Claude Code emits a `system/api_retry` event before retrying. On v2.1.246 or later, when a `401` or `403` rejects an [`apiKeyHelper`](https://code.claude.com/docs/en/settings-reference#apikeyhelper) credential, Claude Code makes the first two retries quietly with no event, then emits the event as usual from the third consecutive retry onward. The quiet retries still count toward `attempt`. You can use the event to show retry progress in your own interface.
246 +
247 +| Field | Type | Description |
248 +| - | - | - |
249 +| `type` | `"system"` | message type |
250 +| `subtype` | `"api_retry"` | identifies this as a retry event |
251 +| `attempt` | integer | current attempt number, starting at 1 |
252 +| `max_retries` | integer | total retries permitted for this failure's cause |
253 +| `retry_delay_ms` | integer | milliseconds until the next attempt |
254 +| `error_status` | integer or null | HTTP status code of the failed attempt, or `null` when the attempt got no HTTP response from the API |
255 +| `no_response` | object, optional | present only when the failed attempt got [no response headers in time](https://code.claude.com/docs/en/errors.md#no-response-from-api). `waited_ms` is how long that attempt waited and `retry_wait_ms` is how long the retry will wait. Requires Claude Code v2.1.261 or later |
256 +| `error` | string | error category: `authentication_failed`, `oauth_org_not_allowed`, `account_on_hold`, `billing_error`, `rate_limit`, `overloaded`, `invalid_request`, `model_not_found`, `server_error`, `max_output_tokens`, `cloud_credential_error`, or `unknown` |
257 +| `uuid` | string | unique event identifier |
258 +| `session_id` | string | session the event belongs to |
259 +
260 +#### Read session metadata
261 +
262 +The `system/init` event reports session metadata including the model, tools, MCP servers, and loaded plugins. It is the first event in the stream unless startup events precede it:
263 +
264 +* `plugin_install` events, when [`CLAUDE_CODE_SYNC_PLUGIN_INSTALL`](https://code.claude.com/docs/en/env-vars) is set.
265 +* [`hook_started`, `hook_progress`, and `hook_response` events](https://code.claude.com/docs/en/agent-sdk/typescript#sdkhookstartedmessage), while a configured [`SessionStart`](https://code.claude.com/docs/en/hooks#sessionstart) or [`Setup`](https://code.claude.com/docs/en/hooks#setup) hook runs. These stream as the hook produces them.
266 +
267 +The event also carries an optional `capabilities` array of strings naming the protocol behaviors this Claude Code version implements, such as `interrupt_receipt_v1` or `interrupt_cancel_queued_v1`. Check it to feature-detect instead of comparing version strings, and ignore values you don't recognize. See [`SDKSystemMessage`](https://code.claude.com/docs/en/agent-sdk/typescript#sdksystemmessage) for the capability list.
268 +
269 +#### Fail CI when a plugin or MCP server doesn't load
270 +
271 +Use the plugin fields in the `system/init` event to catch a plugin that didn't load:
272 +
273 +| Field | Type | Description |
274 +| - | - | - |
275 +| `plugins` | array | plugins that loaded successfully, each with `name` and `path` |
276 +| `plugin_errors` | array | plugin load-time errors, each with `plugin`, `type`, and `message`. Includes unsatisfied dependency versions and `--plugin-dir` load failures such as a missing path or invalid archive. A plugin that didn't load is absent from `plugins`. The key is omitted when there are no errors |
277 +
278 +When a `--plugin-dir` directory or archive itself fails to load, its `plugin_errors` entry includes the resolved absolute path as `path`. Use it to tell which of several `--plugin-dir` values failed. The `path` field requires Claude Code v2.1.283 or later.
279 +
280 +Use the MCP server fields the same way. When you pass [`--mcp-config`](https://code.claude.com/docs/en/cli-reference#cli-flags) with `-p`, Claude Code waits for still-pending servers before running the first turn, up to the [`MCP_TIMEOUT`](https://code.claude.com/docs/en/env-vars) startup timeout, 30 seconds by default. A remote server with a [cached tool list](https://code.claude.com/docs/en/agent-sdk/mcp.md#connection-timing) skips the wait, shows `pending` in `system/init`, and connects on its first tool call. In a [self-hosted environment](https://code.claude.com/docs/en/self-hosted-environments-configuration.md#connection-timing), a shorter wait applies instead. The wait requires Claude Code v2.1.221 or later.
281 +
282 +Claude Code validates each `--mcp-config` entry at startup and skips entries that fail validation, for example a `url` entry with no `type`. The run continues and exits cleanly, so check these fields to catch a server that never loaded:
283 +
284 +| Field | Type | Description |
285 +| - | - | - |
286 +| `mcp_servers` | array | MCP servers in the session, each with `name` and `status` |
287 +| `mcp_server_errors` | array | `--mcp-config` entries skipped by config validation, each with `name`, `type`, and `message`. `type` is a skip category such as `unknown_type`, `url_missing_type`, `invalid_config`, or `reserved_name`; treat values you don't recognize as a generic skip. Affected servers are absent from `mcp_servers`. The key is omitted when there are no errors, so a CI gate can fail on a non-empty array |
288 +
289 +When you run the command yourself in a terminal, Claude Code also prints a startup warning to stderr, such as `Warning: 1 MCP server skipped due to invalid config:`, followed by the reason for each skipped entry.
290 +
291 +When you redirect stderr, or when a program such as a CI runner or an SDK host captures it, Claude Code prints no warning. It reports the skipped entries only in the `mcp_server_errors` field.
292 +
293 +#### Track plugin installs
294 +
295 +When [`CLAUDE_CODE_SYNC_PLUGIN_INSTALL`](https://code.claude.com/docs/en/env-vars) is set, Claude Code emits `system/plugin_install` events while marketplace plugins install before the first turn. Use these to surface install progress in your own UI.
296 +
297 +| Field | Type | Description |
298 +| - | - | - |
299 +| `type` | `"system"` | message type |
300 +| `subtype` | `"plugin_install"` | identifies this as a plugin install event |
301 +| `status` | `"started"`, `"installed"`, `"failed"`, or `"completed"` | `started` and `completed` bracket the overall install; `installed` and `failed` report individual marketplaces |
302 +| `name` | string, optional | marketplace name, present on `installed` and `failed` |
303 +| `error` | string, optional | failure message, present on `failed` |
304 +| `uuid` | string | unique event identifier |
305 +| `session_id` | string | session the event belongs to |
306 +
307 +### Auto-approve tools
308 +
309 +Use `--allowedTools` to let Claude use certain tools without prompting. Listing `Read` and `Edit` lets Claude read and edit files without asking for permission, apart from reads from [network paths](https://code.claude.com/docs/en/permissions.md#network-paths). Listing `Bash` does the same for shell commands, except in a run that starts in [auto mode](https://code.claude.com/docs/en/permission-modes.md#how-auto-mode-evaluates-actions), where Claude Code drops a bare `Bash` entry as a broad allow rule and auto mode evaluates each command instead. This example runs a test suite and fixes failures with those three tools listed:
310 +
311 +```bash theme={null}
312 +claude -p "Run the test suite and fix any failures" \
313 + --allowedTools "Bash,Read,Edit"
314 +```
315 +
316 +Calls to tools you didn't list run if they need no approval. In a [Manual mode](https://code.claude.com/docs/en/permission-modes.md#available-modes) `claude -p` run, a call that needs approval is denied unless something approves it, such as a [`PermissionRequest` hook](https://code.claude.com/docs/en/hooks#permissionrequest) or a [`--permission-prompt-tool`](https://code.claude.com/docs/en/cli-reference#cli-flags). With Claude Code v2.1.302 or later, `claude -p` runs start in Manual mode when [nothing sets a permission mode](https://code.claude.com/docs/en/permission-modes.md#which-mode-a-non-interactive-run-starts-in).
317 +
318 +To set a baseline for the whole session instead of listing individual tools, pass a [permission mode](https://code.claude.com/docs/en/permission-modes.md) with `--permission-mode`, such as `auto`, `dontAsk`, or `acceptEdits`:
319 +
320 +* **`auto`**: pass `--permission-mode auto` to have a classifier review most actions instead of you
321 +* **`dontAsk`**: Claude Code denies every call that would otherwise prompt, which is useful for locked-down CI runs, though a [mod](https://code.claude.com/docs/en/plugins/mods/overview.md) you installed can still approve some of those calls. To check which calls a mod can approve, see [Extend permissions with hooks](https://code.claude.com/docs/en/permissions.md#precedence-among-rules-hooks-and-mods).
322 +
323 + Actions that need no approval in Manual mode still run, such as file reads in your working directories and the [read-only command set](https://code.claude.com/docs/en/permissions.md#read-only-commands). Actions covered by your `--allowedTools` entries or `permissions.allow` rules also run. `AskUserQuestion`, connector tools [your organization set to `ask`](https://code.claude.com/docs/en/mcp#organization-controls-on-connector-tools), MCP tools marked [`requiresUserInteraction`](https://code.claude.com/docs/en/mcp#require-approval-for-a-specific-tool), and [reads from network paths](https://code.claude.com/docs/en/permissions.md#network-paths) are denied even when an allow rule matches
324 +* **`acceptEdits`**: Claude writes files without prompting, and Claude Code auto-approves common filesystem commands such as `mkdir`, `touch`, `mv`, and `cp`. The [actions no mode auto-approves](https://code.claude.com/docs/en/permission-modes.md#actions-no-mode-auto-approves) still apply. Apart from the read-only command set, other shell commands and network requests still need an `--allowedTools` entry or a `permissions.allow` rule. See [what `acceptEdits` auto-approves](https://code.claude.com/docs/en/permission-modes#auto-approve-file-edits-with-acceptedits-mode) for the full list
325 +
326 +This example applies lint fixes with `acceptEdits` as the baseline:
327 +
328 +```bash theme={null}
329 +claude -p "Apply the lint fixes" --permission-mode acceptEdits
330 +```
331 +
332 +### Turn off permission prompts in unattended runs
333 +
334 +Pass `--permission-prompts none` when nobody is available to answer permission prompts, for example in a scheduled job. The flag matters most when your run has a permission host: an Agent SDK app with a [`canUseTool` callback](https://code.claude.com/docs/en/agent-sdk/user-input), or an MCP tool you pass with [`--permission-prompt-tool`](https://code.claude.com/docs/en/cli-reference#cli-flags). Without the flag, your run waits for that host to answer each permission request.
335 +
336 +With the flag, your run doesn't consult the host or wait on it. Anything that would prompt is denied unless a `PermissionRequest` hook allows it, Claude is told that nobody can approve the request and not to retry it, and the run continues. In a `-p` run with no host, these requests are denied either way, and the flag also tells Claude not to retry them. Permission rules, [`PermissionRequest` hooks](https://code.claude.com/docs/en/hooks#permissionrequest), and the permission mode you set still decide every call first; Claude Code denies only the requests that nothing else resolves.
337 +
338 +This example runs an unattended task in [auto mode](https://code.claude.com/docs/en/permission-modes.md#eliminate-prompts-with-auto-mode). The classifier reviews each action as usual, and Claude Code denies anything that would have fallen back to a prompt:
339 +
340 +```bash theme={null}
341 +claude -p "Update the dependency pins and run the tests" --permission-mode auto --permission-prompts none
342 +```
343 +
344 +With `--permission-prompts none`, Claude Code removes the tools that need an answer from a person, such as [`AskUserQuestion`](https://code.claude.com/docs/en/tools-reference#askuserquestion-tool-behavior), so Claude can't call them. Any [MCP elicitation request](https://code.claude.com/docs/en/mcp.md#respond-to-mcp-elicitation-requests) that no [`Elicitation` hook](https://code.claude.com/docs/en/hooks#elicitation) answers is cancelled.
345 +
346 +With `--output-format stream-json`, denials appear as `permission_denied` system messages, and the final result message lists them in `permission_denials`.
347 +
348 +> [!NOTE]
349 +>
350 +> The `--permission-prompts` flag requires Claude Code v2.1.259 or later. Earlier versions reject it with an unknown-option error.
351 +
352 +### Create a commit
353 +
354 +This example reviews staged changes and creates a commit with an appropriate message:
355 +
356 +```bash theme={null}
357 +claude -p "Look at my staged changes and create an appropriate commit" \
358 + --allowedTools "Bash(git diff *),Bash(git log *),Bash(git status *),Bash(git commit *)"
359 +```
360 +
361 +The `--allowedTools` flag uses [permission rule syntax](https://code.claude.com/docs/en/settings-reference.md#permission-rule-syntax). The trailing ` *` enables prefix matching, so `Bash(git diff *)` allows any command starting with `git diff`. The space before `*` is important: without it, `Bash(git diff*)` would also match `git diff-index`.
362 +
363 +> [!NOTE]
364 +>
365 +> Command support differs in `-p` mode:
366 +>
367 +> * User-invoked [skills](https://code.claude.com/docs/en/skills.md) and custom commands work. Include `/skill-name` in the prompt string and Claude Code expands it before running.
368 +> * Built-in commands that only run in the terminal interface, such as `/login`, aren't available.
369 +> * `/model`, `/effort`, `/fast`, `/color`, and `/rename` accept the value as an argument, for example `/model sonnet`, and `/mcp` with no argument prints a text summary of server status. These forms follow each command's [availability notes](https://code.claude.com/docs/en/commands.md#all-commands).
370 +> * To change a setting, pass `key=value` to `/config`, for example `/config thinking=false`.
371 +> * `/output-style <style>` switches [output styles](https://code.claude.com/docs/en/output-styles.md) and `/output-style` alone lists them. Requires Claude Code v2.1.269 or later.
372 +
373 +### Customize the system prompt
374 +
375 +Use `--append-system-prompt` to add instructions while keeping Claude Code's default behavior. This example pipes a PR diff to Claude and instructs it to review for security vulnerabilities. Save it as a shell script, for example `review.sh`:
376 +
377 +```bash theme={null}
378 +gh pr diff "$1" | claude -p \
379 + --append-system-prompt "You are a security engineer. Review for vulnerabilities." \
380 + --output-format json
381 +```
382 +
383 +In the script, `"$1"` stands for the first argument you pass on the command line. Run `bash review.sh 123` and the shell replaces `"$1"` with `123`, so the script fetches the diff for PR 123. Claude Code prints the review as JSON, with the text in the `result` field.
384 +
385 +See [system prompt flags](https://code.claude.com/docs/en/cli-reference.md#system-prompt-flags) for more options including `--system-prompt` to fully replace the default prompt. If you replace it, the run also starts without the [git status snapshot](https://code.claude.com/docs/en/settings-reference.md#includegitinstructions).
386 +
387 +### Continue conversations
388 +
389 +Use `--continue` to continue the most recent conversation, or `--resume` with a session ID to continue a specific conversation. On Claude Code v2.1.257 or later, when you pass `--continue`, Claude Code opens a [background session](https://code.claude.com/docs/en/sessions.md#where-the-session-picker-looks) that has finished, but not one that is still running. This example runs a review, then sends follow-up prompts:
390 +
391 +```bash theme={null}
392 +# First request
393 +claude -p "Review this codebase for performance issues"
394 +
395 +# Continue the most recent conversation
396 +claude -p "Now focus on the database queries" --continue
397 +claude -p "Generate a summary of all issues found" --continue
398 +```
399 +
400 +If you're running multiple conversations, capture the session ID to resume a specific one:
401 +
402 +```bash theme={null}
403 +session_id=$(claude -p "Start a review" --output-format json | jq -r '.session_id')
404 +claude -p "Continue that review" --resume "$session_id"
405 +```
406 +
407 +You can run the two commands from different directories: Claude Code [finds the session by its ID](https://code.claude.com/docs/en/sessions.md#where-the-session-picker-looks) in any project on this machine.
408 +
409 +In place of the session ID, you can pass `--resume` the absolute path to a session's `.jsonl` [transcript file](https://code.claude.com/docs/en/sessions.md#where-transcripts-are-stored), and Claude Code continues the conversation stored in that file.
410 +
411 +## Next steps
412 +
413 +* [Agent SDK quickstart](https://code.claude.com/docs/en/agent-sdk/quickstart.md): build your first agent with Python or TypeScript
414 +* [CLI reference](https://code.claude.com/docs/en/cli-reference.md): all CLI flags and options
415 +* [GitHub Actions](https://code.claude.com/docs/en/github-actions.md): use the Agent SDK in GitHub workflows
416 +* [GitLab CI/CD](https://code.claude.com/docs/en/gitlab-ci-cd.md): use the Agent SDK in GitLab pipelines
added docs/claude-code-docs/hooks.md +4244 −0
Large diff (4,244 lines) is not loaded by default to keep the page fast.Load diff
added docs/claude-code-docs/memory.md +664 −0
Large diff (664 lines) is not loaded by default to keep the page fast.Load diff
added docs/claude-code-docs/permissions.md +824 −0
Large diff (824 lines) is not loaded by default to keep the page fast.Load diff
added docs/claude-code-docs/retrieved_utc.txt +1 −0
Large diff (1 lines) is not loaded by default to keep the page fast.Load diff
added protocol/WP29_FULL_MANDATE.md +962 −0
Large diff (962 lines) is not loaded by default to keep the page fast.Load diff
added protocol/amendments.csv +1 −0
Large diff (1 lines) is not loaded by default to keep the page fast.Load diff
added reports/environment_audit.md +77 −0
Large diff (77 lines) is not loaded by default to keep the page fast.Load diff
added reports/interventions.csv +2 −0
Large diff (2 lines) is not loaded by default to keep the page fast.Load diff
added reports/phase_status.md +16 −0
Large diff (16 lines) is not loaded by default to keep the page fast.Load diff
added research/arxiv_seed.xml +165 −0
Large diff (165 lines) is not loaded by default to keep the page fast.Load diff
added research/corpus/WP15_CLAUDE.md +2165 −0
Large diff (2,165 lines) is not loaded by default to keep the page fast.Load diff
added research/corpus/WP15_PROMPT_PROMPT_INITIAL_CLAUDE.md +2165 −0
Large diff (2,165 lines) is not loaded by default to keep the page fast.Load diff
added research/corpus/WP18_CLAUDE.md +98 −0
Large diff (98 lines) is not loaded by default to keep the page fast.Load diff
added research/corpus/WP19_CLAUDE.md +49 −0
Large diff (49 lines) is not loaded by default to keep the page fast.Load diff
added research/corpus/WP20_CLAUDE.md +179 −0
Large diff (179 lines) is not loaded by default to keep the page fast.Load diff
added research/corpus/WP21_CLAUDE.md +100 −0
Large diff (100 lines) is not loaded by default to keep the page fast.Load diff
added research/corpus/WP22_CLAUDE.md +127 −0
Large diff (127 lines) is not loaded by default to keep the page fast.Load diff
added research/corpus/WP23_CLAUDE.md +43 −0
Large diff (43 lines) is not loaded by default to keep the page fast.Load diff
added research/corpus/WP24_CLAUDE.md +107 −0
Large diff (107 lines) is not loaded by default to keep the page fast.Load diff
added research/corpus/WP25_CLAUDE.md +96 −0
Large diff (96 lines) is not loaded by default to keep the page fast.Load diff
added research/corpus/WP26_CLAUDE.md +135 −0
Large diff (135 lines) is not loaded by default to keep the page fast.Load diff
added research/corpus/WP27_BRIEF_DESIGN-BRIEF.md +59 −0
Large diff (59 lines) is not loaded by default to keep the page fast.Load diff
added research/corpus/WP28_CLAUDE.md +1055 −0
Large diff (1,055 lines) is not loaded by default to keep the page fast.Load diff
added research/corpus_manifest.csv +15 −0
Large diff (15 lines) is not loaded by default to keep the page fast.Load diff
added research/verify_cache/https_api_crossref_org_works_10_1002_2Fadma_202413523 +1 −0
Large diff (2 lines) is not loaded by default to keep the page fast.Load diff
added research/verify_cache/https_api_crossref_org_works_10_1038_2Fs41586_023_06221_2 +1 −0
Large diff (2 lines) is not loaded by default to keep the page fast.Load diff
added research/verify_cache/https_api_crossref_org_works_10_1038_2Fs41586_023_06792_0 +1 −0
Large diff (2 lines) is not loaded by default to keep the page fast.Load diff
added research/verify_cache/https_api_crossref_org_works_10_1038_2Fs41586_025_09442_9 +1 −0
Large diff (2 lines) is not loaded by default to keep the page fast.Load diff
added research/verify_cache/https_export_arxiv_org_api_query_id_list_2211_11501 +52 −0
Large diff (52 lines) is not loaded by default to keep the page fast.Load diff
added research/verify_cache/https_export_arxiv_org_api_query_id_list_2305_02251 +41 −0
Large diff (41 lines) is not loaded by default to keep the page fast.Load diff
added research/verify_cache/https_export_arxiv_org_api_query_id_list_2310_03302 +34 −0
Large diff (34 lines) is not loaded by default to keep the page fast.Load diff
added research/verify_cache/https_export_arxiv_org_api_query_id_list_2310_06770 +45 −0
Large diff (45 lines) is not loaded by default to keep the page fast.Load diff
added research/verify_cache/https_export_arxiv_org_api_query_id_list_2401_05507 +74 −0
Large diff (74 lines) is not loaded by default to keep the page fast.Load diff
added research/verify_cache/https_export_arxiv_org_api_query_id_list_2404_07738 +36 −0
Large diff (36 lines) is not loaded by default to keep the page fast.Load diff
added research/verify_cache/https_export_arxiv_org_api_query_id_list_2404_17605 +37 −0
Large diff (37 lines) is not loaded by default to keep the page fast.Load diff
added research/verify_cache/https_export_arxiv_org_api_query_id_list_2407_01214 +38 −0
Large diff (38 lines) is not loaded by default to keep the page fast.Load diff
added research/verify_cache/https_export_arxiv_org_api_query_id_list_2407_13168 +113 −0
Large diff (113 lines) is not loaded by default to keep the page fast.Load diff
added research/verify_cache/https_export_arxiv_org_api_query_id_list_2408_06292 +41 −0
Large diff (41 lines) is not loaded by default to keep the page fast.Load diff
added research/verify_cache/https_export_arxiv_org_api_query_id_list_2408_09667 +70 −0
Large diff (70 lines) is not loaded by default to keep the page fast.Load diff
added research/verify_cache/https_export_arxiv_org_api_query_id_list_2409_05556 +31 −0
Large diff (31 lines) is not loaded by default to keep the page fast.Load diff
added research/verify_cache/https_export_arxiv_org_api_query_id_list_2409_07703 +49 −0
Large diff (49 lines) is not loaded by default to keep the page fast.Load diff
added research/verify_cache/https_export_arxiv_org_api_query_id_list_2409_11363 +39 −0
Large diff (39 lines) is not loaded by default to keep the page fast.Load diff
added research/verify_cache/https_export_arxiv_org_api_query_id_list_2410_05080 +84 −0
Large diff (84 lines) is not loaded by default to keep the page fast.Load diff
added research/verify_cache/https_export_arxiv_org_api_query_id_list_2410_07095 +58 −0
Large diff (58 lines) is not loaded by default to keep the page fast.Load diff
added research/verify_cache/https_export_arxiv_org_api_query_id_list_2410_07331 +56 −0
Large diff (56 lines) is not loaded by default to keep the page fast.Load diff
added research/verify_cache/https_export_arxiv_org_api_query_id_list_2411_00816 +46 −0
Large diff (46 lines) is not loaded by default to keep the page fast.Load diff
added research/verify_cache/https_export_arxiv_org_api_query_id_list_2501_04227 +54 −0
Large diff (54 lines) is not loaded by default to keep the page fast.Load diff
added research/verify_cache/https_export_arxiv_org_api_query_id_list_2502_18864 +182 −0
Large diff (182 lines) is not loaded by default to keep the page fast.Load diff
added research/verify_cache/https_export_arxiv_org_api_query_id_list_2504_01848 +62 −0
Large diff (62 lines) is not loaded by default to keep the page fast.Load diff
added research/verify_cache/https_export_arxiv_org_api_query_id_list_2504_08066 +47 −0
Large diff (47 lines) is not loaded by default to keep the page fast.Load diff
added research/verify_cache/https_export_arxiv_org_api_query_id_list_2505_13400 +53 −0
Large diff (53 lines) is not loaded by default to keep the page fast.Load diff
added research/verify_cache/https_export_arxiv_org_api_query_id_list_2505_18705 +34 −0
Large diff (34 lines) is not loaded by default to keep the page fast.Load diff
added research/verify_cache/https_export_arxiv_org_api_query_id_list_2509_26603 +43 −0
Large diff (43 lines) is not loaded by default to keep the page fast.Load diff
added research/verify_cache/https_export_arxiv_org_api_query_id_list_2511_02824 +133 −0
Large diff (134 lines) is not loaded by default to keep the page fast.Load diff
Menu

Theme