Skip to content

Headless & Non-Interactive Mode

claude -p "prompt" runs Claude non-interactively — no terminal UI, no interactive prompts — though by default the run is still saved as a resumable session (see Session continuation below; pass --no-session-persistence to opt out). This is the entry point for all loop automation: scripts, CI pipelines, and scheduled jobs.

Core flags

claude -p "task"                                     # non-interactive, output to stdout
claude -p "task" --output-format json                # structured JSON output
claude -p "task" --output-format stream-json         # streaming JSON for real-time processing
claude -p "task" --max-turns 30                      # hard turn cap
claude -p "task" --max-budget-usd 2.00               # hard cost cap
claude -p "task" --permission-mode auto              # skip permission prompts (unattended)
claude -p "task" --allowedTools "Edit,Bash(git *)"  # scope tools per invocation

Session continuation

Resume a previous session rather than starting fresh — preserves context, file state, and in-progress work across interrupted runs:

claude --continue                                  # resume most recent session
claude --resume <session-id>                       # resume a specific session
claude --continue -p "continue fixing the remaining type errors"

Use --continue in long-running loops to pick up after a crash, budget cap, or rate limit without losing accumulated context.

Prompt and model overrides

# Replace the system prompt entirely (--system-prompt-file <path> for the file form)
claude -p "task" --system-prompt "You are a security auditor."

# Append to the default system prompt
#   also: --append-system-prompt-file <path>
#   also: --append-subagent-system-prompt (every subagent; -p only; v2.1.205+)
claude -p "task" --append-system-prompt "Always return structured JSON."

# Override model
claude -p "task" --model claude-opus-5

# Override effort level
claude -p "task" --effort high

# Fallback if primary model is unavailable (loop resilience)
claude -p "task" --fallback-model claude-sonnet-5,claude-haiku-4-5

Background sessions

claude --bg "task" starts a session detached from the terminal — the session continues running after your shell exits. Manage with claude agents, claude attach, claude logs. See Background Agents for the full pattern.

Bash commands that hang no longer kill the turn (v2.0.19+)

"Auto-background long-running bash commands instead of killing them. Customize with BASH_DEFAULT_TIMEOUT_MS" — CHANGELOG.md, v2.0.19

Before v2.0.19, a Bash command that ran past its timeout was killed and reported as a failure. Now it is auto-backgrounded instead: the tool call returns, Claude is told the command is still running, and the turn continues. This is a different mechanism from claude --bg above — that backgrounds a whole session; this backgrounds one long-running Bash command inside an otherwise normal session.

For an unattended loop, this changes what "the command didn't finish" looks like — and headless mode changes it again. Before v2.0.19, a hung command printed a timeout failure your retry wrapper's ERROR_REGEX (see Fault-tolerant headless loop) could catch. Now it's moved to the background instead, and in a claude -p run that backgrounded shell is terminated about five seconds after Claude returns its final result and stdin closes — a grace period for output that arrives right after, not a wait for the command to finish. So a long build or deploy step that overruns the timeout inside a headless loop's task can be silently killed mid-run: the -p process still exits with whatever code the turn produced (typically 0), nothing matches ERROR_REGEX, and the command's work is simply gone.

  • BASH_DEFAULT_TIMEOUT_MS — how long a command runs before being backgrounded (2 minutes by default)
  • CLAUDE_CODE_DISABLE_BACKGROUND_TASKS (v2.1.4+) — set to disable auto-backgrounding entirely, if a loop needs a hang to fail loudly instead

Prompt cache optimisation for CI

In CI or multi-machine setups, the system prompt varies per machine (working directory, hostname, git config), invalidating the prompt cache on every run:

claude -p "task" --exclude-dynamic-system-prompt-sections            # v2.1.98+

Moves machine-specific sections to the first user message — the system prompt stays identical across machines, cache hits occur, and cost per run drops significantly.

CI-specific flags

# Don't persist session to disk (ephemeral CI runs)
claude -p "task" --no-session-persistence

# Disable ALL customizations (troubleshoot hook/skill/plugin conflicts). Differs from --bare:
#   auth, model selection, built-in tools and permissions still work normally, and managed
#   settings policy still applies. Sets CLAUDE_CODE_SAFE_MODE.
claude -p "task" --safe-mode                                        # v2.1.169+

# Skip all setup: hooks, skills, commands, subagents, plugins, MCP, auto-memory, CLAUDE.md
#   Keeps Bash + file read/edit. Skills under --add-dir still load. Sets CLAUDE_CODE_SIMPLE.
claude -p "task" --bare                                             # v2.1.81+

--bare is the fastest possible headless start — use it for self-contained tasks that do not need any project configuration.

Fail-closed unattended runs (v2.1.259+)

For a headless host with nobody watching, the default direction a prompt fails matters more than usual:

"Added --permission-prompts none for unattended headless hosts: anything that would prompt is denied automatically while the active permission mode (including auto mode) keeps deciding" — v2.1.259 release notes

claude -p "task" --permission-mode auto --permission-prompts none

Contrast the two ways to remove a prompt from a headless loop:

Flag What happens to a prompt Direction
--permission-prompts none Denied automatically; the active mode's own decisions still apply Fail-closed
--dangerously-skip-permissions Never asked; the action runs regardless Fail-open

For a scheduled or unattended --print loop — nobody at the terminal to answer a prompt — --permission-prompts none is the safer default: an action that would have needed a human's yes is skipped, not silently allowed. See Permissions & Auto Mode for the full permission-mode picture.

This is a --print-only guarantee

claude --help scopes the flag explicitly — "Who answers permission prompts with --print" — and --bg conflicts with --print outright, so a background session cannot fail closed this way. Its prompts surface in the agent view and wait for a human. The same applies to --max-budget-usd, whose help reads "(only works with --print)". Verified on claude 2.1.261; see Background Agents § What --bg does not get.

Structured output

For loops that hand off results to downstream processes:

# JSON output
claude -p "List all API endpoints missing auth middleware." \
  --output-format json \
  --append-system-prompt 'Return JSON: [{"file":"...","line":N,"endpoint":"..."}]'

# Stream-JSON for real-time step monitoring
claude -p "Refactor src/auth" --output-format stream-json --verbose \
  | jq 'select(.type=="tool_use") | .name'

Fault-tolerant headless loop

Before hand-rolling this, know what the CLI already does. Claude Code has its own retry/backoff for transient failures:

  • CLAUDE_CODE_RETRY_WATCHDOG (persistent retry mode, meant for unattended sessions such as CI jobs or eval harnesses) raises the default retry count for non-capacity transient errors to 300 and lifts the earlier cap of 15 on CLAUDE_CODE_MAX_RETRIES (v2.1.199), but fails at once — rather than waiting indefinitely — on a 429 that reports an organization spend limit or exhausted usage credits (v2.1.239).
  • API_TIMEOUT_MS governs the per-request timeout, including how long a retry waits when the API sends no response headers at all: 10 minutes by default (600000ms) as of v2.1.261, raised from 3 minutes.

Source: environment variables reference, verified against claude 2.1.261, 2026-09-07.

The wrapper below still earns its place for the git-safety and idempotency checks further down — but a bare retry-on-transient-error loop may now just be duplicating what the CLI already does on its own.

#!/bin/bash
MAX_RETRIES=3
for attempt in $(seq 1 $MAX_RETRIES); do
  echo "Attempt $attempt..."
  claude -p "Fix all TypeScript errors in src/" \
    --max-turns 50 \
    --max-budget-usd 3.00 \
    --permission-mode auto \
    --exclude-dynamic-system-prompt-sections \
    --no-session-persistence \
    && { echo "Done."; exit 0; }
  echo "Attempt $attempt failed — retrying in 15s..."
  sleep 15
done
echo "All attempts failed."
exit 1

Exit code alone is not enough — scan the output too. Two cases break the simple && exit 0 pattern above:

  1. PTY wrappers mask the exit code. If you wrap the call in script (to force live, unbuffered logging — see above), macOS script(1) does not reliably propagate the child's exit code; it often returns 0 even when claude failed.
  2. Transient API drops (API Error: ... ECONNRESET, socket hang up, overloaded_error) are exactly the failures worth retrying, and they print to the output stream.

So treat an attempt as failed if the exit code is non-zero or a transient-error marker appears in that attempt's output:

ERROR_REGEX='API Error:|ECONNRESET|ETIMEDOUT|Unable to connect to API|socket hang up|overloaded_error|529 |503 Service'
script -q "$tmp" "$(command -v claude)" --permission-mode auto -p "/my-loop"; code=$?
if [[ $code -eq 0 ]] && ! grep -Eq "$ERROR_REGEX" "$tmp"; then
  echo "success"; exit 0
fi
# else: back off (e.g. 30s → 90s) and retry

Use exponential-ish backoff (30s, 90s) so a brief provider blip does not lose the whole scheduled run. The production version of this is scripts/run-loop-news.sh.

Don't hardcode the binary path the way an earlier version of this pattern did (/opt/homebrew/bin/claude). claude moved from a homebrew symlink to the native installer path (~/.local/bin/claude) after this pattern was first written, and a hardcoded path silently produced exit code 127 ("no such file") on every attempt once the binary moved — a failure ERROR_REGEX above does not catch. "$(command -v claude)" above resolves the binary at run time instead of assuming a fixed location; for a resolution order that also tolerates claude being absent from PATH, see Worktree isolation below (resolve_claude_bin()).

Only retry when a retry is safe. Blind retries are dangerous when the loop has side effects (file writes, commits, releases): a fresh re-run can duplicate work or hit a tag/release collision. A retry wrapper should refuse to make things worse:

  • Cap the cost — pass --max-budget-usd so 3 attempts can't become an unbounded bill.
  • Retry only on a clean, traceless failure. Before retrying, check that the failed attempt left no durable trace: the tracked tree is still clean and HEAD has not moved. If it already committed or made partial edits, stop and notify a human instead of re-running.
  • Notify on give-up. A silent exit 1 to a log nobody reads is how a daily loop dies unnoticed. Emit a notification (e.g. macOS osascript -e 'display notification …') on final failure.
head_before="$(git rev-parse HEAD)"
run_attempt || {
  [[ "$(git rev-parse HEAD)" != "$head_before" ]] && { notify "failed after commit"; exit 1; }
  git diff --quiet && git diff --cached --quiet || { notify "partial edits"; exit 1; }
  # clean + HEAD unchanged → safe to back off and retry
}

The deeper fix for true safe-to-retry is idempotency inside the loop itself (e.g. a digest section keyed by date that is updated rather than appended, and the commit as the single final atomic step) — the wrapper guard above only refuses to compound damage.

Worktree isolation + a two-session pipeline (the production shape)

scripts/run-loop-news.sh evolved past the single-checkout guard above into a shape worth copying for any self-writing daily loop:

  1. Run in a throwaway git worktree branched off origin/main. The daily cron must not inherit whatever branch or dirty state the primary checkout happens to be in. A worktree (git worktree add -b <temp> <wt> origin/main) gives every run a clean, isolated base and makes a failed attempt's filesystem fully disposable. A trap cleanup EXIT removes it in every path.

  2. Split the loop into two sessions with an artifact handoff. The search half (fetch-loop-news) writes a compact .loop-news/findings.json and stops; the KB half (integrate-loop-news) starts a fresh session that consumes only that artifact, integrates, and pushes. The session boundary keeps the search stage's bulky retrieval context out of the reasoning stage, and makes each half independently testable and retryable.

  3. Granular retry via a per-attempt tree reset. The worktree is created once per run; each attempt first discards the previous attempt's uncommitted edits with git clean -fd plus a conditional reset: to HEAD when Stage-B checkpoint commits already sit ahead of the run's base SHA (so a retry resumes from them), and to origin/main only when there are none. Resetting unconditionally to origin/main, as this once did, threw those checkpoints away on every retry. Because the artifact lives in the gitignored .loop-news/, it survives either path — so a failure in the KB half re-runs only that half against the saved findings, never repeating the expensive search.

  4. Adapt the retry guard to the durable side effect. Worktree isolation makes the tree disposable, but the final git push origin HEAD:main is durable and outlives the worktree. So the guard asks not merely whether origin/main moved but whether the delta contains a matching loop-news commit: if it does, a prior attempt already published → stop and notify, never retry (a blind retry would double-commit the digest). If origin/main advanced for an unrelated reason — a human merging a different PR concurrently — the guard rebases its base SHA forward and keeps retrying instead of abandoning a retriable failure. Every run commits, including a zero-finding day — it publishes an empty digest section rather than discarding it — so "did the run publish?" is answerable from main on every run, not only on productive ones.

That question has three answers, not two, and the third needs a branch per guard. git log A..B requires only that both objects exist, not that A is an ancestor of B, so a rewritten or force-pushed upstream turns the delta into "the new history minus the old one" and a stray matching subject reads as we published. The check must therefore be able to return cannot tell — and the guards must not share one reflex for it, because their conservative directions are opposite. A guard deciding skip the expensive stage? is conservative when it declines to skip on an unanswerable state; a guard deciding retry the push? is conservative when it declines to retry. Wire both to the same "cannot tell" and one of them is wrong. Keep the question in one implementation, and let each caller choose its own safe direction.

  1. Assert on the artifact, not on the run's exit status. claude -p exits 0 whenever the session ended cleanly, which is not the same as the loop having done its job. A guard inside the session — a build gate, a "did you actually write the file" check — aborts the agent's own bash block, not the process, so the wrapper still reads 0 and logs success. This repo shipped exactly that shape for eight weeks. So after the retry loop, re-fetch and require the durable side effect to be present: scripts/assert-published.sh fails the run when origin/main carries no matching commit since the run's base SHA, and fails it just as hard when it cannot tell — an unreachable remote, an unresolvable ref, a rewritten history — on the principle that a check which cannot tell has confirmed nothing.

Two details are load-bearing. Order: the assertion goes before the step that retires the run's resume artifact, because retiring it also disarms the wrapper's resume-preservation path — a check placed after would destroy the expensive search on precisely the failure it exists to catch. Reach: "fail loudly" is only as loud as the channel, and here that is a desktop notification plus a gitignored log on the machine that failed, so the off-machine freshness watchdog remains the real backstop. scripts/verify-publish-guard.sh proves the check fires — including static cases pinning where in the wrapper it is called from and that its failure branch actually terminates, neither of which any amount of behavioural testing of the check itself can see. Two further lessons came out of proving it, and both generalise. A guard added later can silently un-cover an earlier one: once several guards share a single "cannot tell" exit code, removing one is masked by the next and the mutation test stops failing, so the cases assert which guard fired, not merely that one did. And a proof nothing runs decays — the harness is wired into CI on any change to the scripts or the skills, because a check on disk that nobody executes is the same defect one level up.

  1. Preflight the state the sweep depends on, and stop the run — not just the digest — when it is missing. A browser-driven stage reads whatever the browser can see, and a logged-out browser shows a login wall that looks like a result: every search "returns", profiles load with a handful of posts. On 2026-10-19 the search stage swept all 11 X profiles and both X searches that way, 12 coverage records came back partial, the second stage published, the wrapper exited 0, and the only notice was one line inside the digest. Recovery was a logged-in re-sweep by 13 agents. Three parts of the fix each have a reason:

  2. Read the state once, first, and record it in the artifact. Before any X source is dispatched, the search stage loads x.com/home in its own tab and reads three things from the DOM: the path, the account switcher and the Post button. Only that positive reading is logged-in; a tool error, an unrendered page, a changed layout or a login redirect is logged-out or unknown, and both stop the run — "no login wall seen" is not evidence of a login. The state, a timestamp and the raw reading go into the artifact as x_login; each unswept X source gets a blocked: x-login coverage record, so the gap is in the data rather than only in a log.

  3. Decide in the wrapper, from the artifact, with its own exit code. The search stage's claim is prose; the wrapper's reading of it is code. scripts/assert-x-login.sh passes only a logged-in state that is stamped today, carries evidence and is not contradicted by the coverage records; a missing or malformed field fails the same way an unreadable one does. The wrapper runs it straight after the search stage and exits 8 before the integrate stage can start, so nothing is published. It sits ahead of the retry logic on purpose: a login wall is deterministic, and retrying would only spend attempts and backoff.
  4. Keep the work, and make the override a recorded decision. The blocked artifact is preserved unconsumed, so after logging in a re-run resumes it instead of searching twice. Publishing without X is --allow-x-logged-out, per run: the wrapper hands the search stage a file saying so, the stage sweeps every non-X source and records override: true, and the script accepts it only if the artifact honours it in full (complete, flagged, every unswept X source blocked). An artifact cannot grant itself an override the operator did not give, and a standing environment variable is deliberately not the documented route — a default that quietly degrades the run is the failure this exists to end.

scripts/verify-x-login-guard.sh runs the real wrapper end to end against stubbed claude, script and osascript sessions, runs the decision script on fixture artifacts, and runs the skill's own classifier snippet under node against stubbed pages — then breaks the wrapper and the script on purpose and requires each break to be caught. Limits: it cannot see a login that lapses mid-sweep (that still surfaces as partial records), it does not check LinkedIn's separate login, and the logged-out page markers were not verified against the live site — they only choose a label, since every state but logged-in stops the run.

On success the wrapper fast-forwards the primary checkout (git pull --ff-only) only if it is on main, so the local checkout tracks the published run without disturbing other work.

Pitfall: a skill can't tell interactive from headless invocation

A multi-stage pipeline split across skills (search → integrate, in this repo's case) relies on each stage stopping at its boundary so the orchestrator — not the model — decides when the next stage runs. It is tempting to write an escape hatch into the first stage's skill like "if you were invoked interactively, run the next skill yourself" — so a human typing the command by hand still gets the full pipeline without two manual steps.

Don't. A model running headlessly via -p has no reliable signal that distinguishes "interactive" from "orchestrated" — it cannot introspect how it was launched. In production this caused a single search-stage session to also execute the entire integrate stage (digest, KB writes, release, commit, push) inside itself, collapsing a deliberately two-session design (context isolation, independent retry, independent model/effort) back into one — and it happened even with the extra stage's tools (Bash, git) absent from --allowedTools, because --permission-mode auto's classifier approved them anyway (see Core flags on the classifier, not the allowlist, being the real gate).

Rewording the prompt is not the fix — it is not even reliable. The first attempt at a fix removed the interactive exception and told the model, in strong unambiguous language, to stop unconditionally under all circumstances. It collapsed into one session again on the very next real production run anyway. Prose instructions — no matter how forcefully worded — are not a substitute for an actual permission boundary; a headless session under --permission-mode auto has demonstrated willingness to route around them when it decides the surrounding context justifies it.

The actual fix is --disallowedTools, verified experimentally, not assumed (re-verified on claude 2.1.263). Unlike --allowedTools (a pre-approval list the auto classifier can freely expand beyond), --disallowedTools is a genuine deny-list — confirmed by isolated testing (a minimal session with --disallowedTools "Bash(git *)" under --permission-mode auto, asked to run a git command, reported the call was denied — not routed around). Scope the deny to the specific capability that enables the escalation, not a blanket tool name, if the stage has any other legitimate narrow use of that tool (here, Stage A still needs plain Bash for a date call, so the deny is Bash(git *),Bash(gh *),Skill — scoped to git/gh/Skill, not Bash outright).

The full fix layers as follows, from primary to defense-in-depth: 1. Primary, structural — deny the escalation capability itself via --disallowedTools on the first stage's session (verified to hold even under --permission-mode auto). 2. Prose — the skill still says to stop unconditionally, for the case where it's run interactively outside the wrapper (no --disallowedTools applies there) — necessary, but demonstrated insufficient alone. 3. Skill-level defense-in-depth — the second stage's Phase 0 checks (via git log --grep) whether this exact run has already been committed, before doing any real work, and aborts immediately if so. 4. Wrapper-level defense-in-depth (cheapest — zero LLM cost) — after the first stage completes, the orchestrator checks whether the shared remote ref advanced with a commit matching this run (not just "did it move" — an unrelated concurrent commit must not be mistaken for this); if matched, skip the second stage entirely rather than paying for a full session just to have it discover the same thing via reasoning.

Scheduling with macOS LaunchAgent

For daily headless loops that require local tools (Chrome browser automation, local filesystem, system credentials), a LaunchAgent is more reliable than cron — it respects login sessions, can restart on failure (via the optional KeepAlive key, not set in the example below), and survives reboots.

<!-- ~/Library/LaunchAgents/com.user.my-loop.plist -->
<dict>
    <key>Label</key>
    <string>com.user.my-loop</string>

    <key>ProgramArguments</key>
    <array>
        <string>/bin/bash</string>
        <string>/path/to/repo/scripts/run-my-loop.sh</string>
    </array>

    <!-- Run at 05:00 local time daily -->
    <key>StartCalendarInterval</key>
    <dict>
        <key>Hour</key><integer>5</integer>
        <key>Minute</key><integer>0</integer>
    </dict>

    <!-- launchd has minimal PATH — supply homebrew explicitly -->
    <key>EnvironmentVariables</key>
    <dict>
        <key>PATH</key>
        <string>/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin</string>
        <key>HOME</key>
        <string>/Users/yourname</string>
    </dict>

    <key>WorkingDirectory</key>
    <string>/path/to/repo</string>

    <key>StandardOutPath</key>
    <string>/path/to/repo/logs/launchd.log</string>
    <key>StandardErrorPath</key>
    <string>/path/to/repo/logs/launchd.log</string>

    <key>RunAtLoad</key><false/>
</dict>
# Register and trigger
launchctl load ~/Library/LaunchAgents/com.user.my-loop.plist
launchctl start com.user.my-loop   # immediate manual run

# Check status
launchctl list com.user.my-loop

# Remove
launchctl unload ~/Library/LaunchAgents/com.user.my-loop.plist

Reproducing the scheduled environment: the plist is not the whole environment

A scheduled loop fails in ways an interactive run never shows, because an interactive shell has sourced your profile and its PATH is a superset of the scheduler's. The usual remedy is a "run it now, the way launchd would" launcher that replays the plist under env -i. That remedy has a trap worth knowing before you build one.

launchd injects variables the plist never declares. Measured 2026-09-21 with a throwaway GUI agent whose EnvironmentVariables set only HOME and PATH; the job received:

HOME  LOGNAME  OSLogRateLimit  PATH  PWD  SHELL  SHLVL
SSH_AUTH_SOCK  TMPDIR  USER  XPC_FLAGS  XPC_SERVICE_NAME

So a launcher that replays EnvironmentVariables alone builds an environment stricter than the scheduler's — and fails where the scheduled run succeeds. That is the inverse of the problem the launcher was built to solve, and it is harder to spot, because the error usually looks like something else.

The concrete bite: without USER, the Claude CLI cannot reach its Keychain credential and exits with Not logged in · Please run /login. That reads as an expired session, so the natural response is to re-authenticate — which changes nothing, because the login was never the problem. Bisecting the environment, with a negative control, is what identifies it:

Environment Result
env -i + PATH/HOME/TERM Not logged in
…+ USER works
…+ LOGNAME only (control) Not logged in

What to do: synthesize the identity variables from the live user record (id -un) rather than from the plist, which correctly does not declare them. Accept that some launchd-internal variables (SSH_AUTH_SOCK, XPC_*, OSLogRateLimit) cannot be reproduced honestly from outside launchd, and say so in the launcher rather than claiming the environments are identical. A launcher that overclaims fidelity is worse than one that states its gap: the overclaim is what makes "it worked by hand" read as evidence about the scheduled path when it is not.

When to prefer LaunchAgent over Routines: the loop uses --chrome (browser automation), needs local credentials, or reads files not in a git repo. When to prefer Routines: laptop needs to be off during the run, or you want cloud-managed infrastructure. See Routines — but note Routines cannot access local Chrome sessions.