Bounded Automation with Claude Code CLI
Build safe autonomous jobs around claude -p with structured output, turn and cost limits, permission boundaries, and external orchestration.
What You’ll Learn
Claude Code does not need to run as an unbounded daemon to automate useful work. The supported foundation is print mode:
claude -p "Review the current diff"
It accepts a prompt, works through the task, prints the result, and exits. A scheduler, CI runner, or small wrapper owns retries and timing. This separation makes the job observable and killable.
The Safe Automation Envelope
Define five boundaries for every job:
- scope — repository and allowed directories;
- authority — permission mode and tool restrictions;
- time — maximum turns and outer process timeout;
- cost — maximum budget;
- output — text, JSON, stream JSON, or a JSON Schema.
A read-only review job:
claude -p \
--permission-mode plan \
--max-turns 8 \
--max-budget-usd 1.50 \
"Review the current diff. Do not edit files. Return findings by severity."
-p means print mode in Claude Code. Do not assume it means the same thing in another CLI: in Codex, -p selects a configuration profile.
Name the permission mode explicitly. Since Claude Code 2.1.302, a -p run with no mode set starts in Manual mode (config value default): file reads and the built-in read-only commands run, and every call that would need approval is denied unless an allow rule, a hook, or a permission-prompt tool approves it. Choose the mode that matches the job:
| Job | Mode | What runs without a prompt |
|---|---|---|
| Read-only analysis or planning | --permission-mode plan | Reads and exploration; edits stay blocked |
| Locked-down CI with an exact allowlist | --permission-mode dontAsk plus --allowedTools | Reads, read-only commands, and your allowlist; everything else is denied |
| Scoped edits | --permission-mode acceptEdits | File edits and common filesystem commands; other shell commands still need an allow rule |
| Classifier-reviewed autonomy | --permission-mode auto | Actions a classifier model approves |
Machine-Readable Results
Use JSON when another program consumes the final response:
claude -p \
--output-format json \
"Summarize the current git diff"
Constrain the result with a schema:
claude -p \
--output-format json \
--json-schema '{
"type": "object",
"properties": {
"verdict": {"type": "string"},
"findings": {"type": "array", "items": {"type": "string"}}
},
"required": ["verdict", "findings"]
}' \
"Audit the current diff without changing files"
For event-by-event consumers, use --output-format stream-json. Add --include-partial-messages only when your consumer is prepared to process partial streaming events.
Session Continuity
Give a job a name when later work must target it:
claude -p --name nightly-review "Review the repository status"
Resume a known session:
claude -p --resume nightly-review "Re-check only the unresolved findings"
Continue the most recent eligible session:
claude -p --continue "Run the affected tests and report the result"
Use --no-session-persistence for stateless jobs that must not create resumable history.
Put the Loop Outside Claude Code
An external scheduler should decide when to run and whether to retry:
#!/usr/bin/env bash
set -euo pipefail
claude -p \
--permission-mode plan \
--max-turns 6 \
--max-budget-usd 1.00 \
--output-format json \
"Inspect the repository and report whether the documented verification command should run."
The wrapper can enforce an OS timeout, capture exit status, store logs, and notify a human. Claude Code remains one bounded process per attempt. Size the timeout for background work too: a -p run can stay open after its result while a background command or subagent it started finishes. If the wrapper stops a run with SIGTERM, Claude Code exits with code 143 and records no result for the unfinished turn.
Do not place --dangerously-skip-permissions into unattended templates. It removes an important safety boundary and should require a separately reviewed environment.
When the Loop Lives Inside Claude Code
Claude Code also has built-in loops. Each one changes who decides that work continues, so treat it as part of the envelope:
| Command | Next turn starts when | Stops when | Fits |
|---|---|---|---|
/goal <condition> | The previous turn ends and an evaluator model judges the condition not yet met | The evaluator judges it met or impossible, an error you have to fix occurs, or you run /goal clear | Finishing a verifiable end state |
/loop [interval] <prompt> | An interval elapses in an open session, or Claude picks the next wakeup | You cancel it, Claude ends a self-paced loop, or 7 days pass | Polling while a session stays open |
/schedule (cloud scheduled tasks, research preview) | A schedule, API call, or GitHub event fires | You pause or delete the task | Unattended runs on cloud infrastructure |
/goal also works in print mode:
claude -p --max-budget-usd 3.00 \
"/goal CHANGELOG.md has an entry for every PR merged this week"
The run keeps taking turns until the evaluator is satisfied. The evaluator only judges what appears in the conversation, so a clause such as “or stop after 20 turns” is a soft bound. A goal doesn’t change the permission mode, so the authority boundary still applies, and --max-budget-usd plus the wrapper’s timeout remain the process-level stops. Session 31 covers /loop and scheduled autonomy in depth.
CI Pattern
A reliable CI job has explicit input and a non-mutating prompt:
git diff --exit-code -- . >/dev/null || true
claude -p \
--permission-mode dontAsk \
--max-turns 10 \
--output-format json \
--json-schema '{"type":"object","properties":{"pass":{"type":"boolean"},"reason":{"type":"string"}},"required":["pass","reason"]}' \
"Review the checked-out change against AGENTS.md. Do not modify files."
dontAsk lets the review read files and run the built-in read-only commands, such as read-only git forms, and denies anything that would otherwise prompt instead of waiting for an answer. Add --allowedTools entries only for the commands the job truly needs.
Then let CI interpret the structured result. Do not treat a fluent text response as a passing build; tests, lint, type checks, and deployment verifiers remain the authoritative gates.
Operational Checklist
- pin or record the Claude Code version;
- run in a clean, scoped checkout;
- choose a permission mode explicitly (
-pstarts in Manual mode since Claude Code 2.1.302); - add
--barewhen the job must ignore local hooks, plugins, MCP servers, andCLAUDE.md(on the Anthropic API it authenticates only withANTHROPIC_API_KEYor anapiKeyHelperpassed with--settings); - cap turns, budget, and outer runtime;
- request structured output for machine consumers;
- retain stderr and exit status;
- retry only failures known to be safe;
- escalate ambiguous results instead of looping forever.
Next Session
Session 12 adds Git worktree isolation so multiple Claude Code sessions can operate without sharing the same writable checkout.