Claude Code Automation: Every Way to Run It Unattended
Claude Code can work without you. There are eight or so ways to make it do so, from a single claude -p in a cron job to cloud scheduled tasks that fire on a GitHub event, and they differ on what matters: where the run happens, what it can see, what triggers it, and what becomes of it when your laptop is closed. This page puts them all on one map, with a decision table, a tested recipe for each, and the four problems every unattended run hits. Every behavior marked as tested comes from 17 runs we made on 2026-11-17 with Claude Code 2.1.326, in disposable Docker containers; the rest is quoted from the official docs, with the link. Each topic that deserves more than a section links to its own deep dive.
The short answer: claude -p is the building block. Run it from cron on a machine that stays on when the job needs your local files and services, from GitHub Actions when it reacts to the repository, and as a cloud scheduled task when it needs neither your machine nor more than one run an hour. Whatever the trigger, decide the permissions in advance and check the JSON result, not just the exit code.
Claude Code automation at a glance
| Mechanism | Trigger | Runs on | Sees your local files | Minimum interval | Laptop closed | Billing | Best for |
|---|---|---|---|---|---|---|---|
claude -p (headless) |
Whatever calls it | Wherever you run it | Yes | – | Depends on the host | Subscription login or API key | The building block of everything below |
cron / systemd timer + claude -p |
Schedule | Your machine or server | Yes | 1 minute | Stops on a laptop, fine on a server | Same as claude -p |
Nightly jobs that need local services, databases, other CLIs |
/loop |
Interval, inside an open session | Your terminal session | Yes | 1 minute | Stops | Subscription | Watching a deploy or a PR for an afternoon |
| Desktop scheduled tasks | Schedule | Your machine, through Claude Desktop | Yes | 1 hour in the forms | Skipped, one catch-up on wake | Subscription | Personal daily routines on your own computer |
| Cloud scheduled tasks (ex routines) | Schedule, API call, GitHub event | Anthropic's cloud | No, fresh clone | 1 hour | Keeps running | Subscription usage (Pro and up) | Repository jobs that need no local state |
GitHub Actions + claude-code-action |
PR, issue, comment, @claude, schedule |
A GitHub runner | Repository checkout only | 5 minutes (GitHub's limit) | Keeps running | API key or subscription token, plus Actions minutes | PR review, issue to PR, CI fixes |
| Hooks | Events inside a session (tool call, stop) | Wherever Claude Code runs | Yes | – | – | Nothing extra | Guards, logs and notifications around any of the above |
| Agent SDK | Your code | Anywhere | Yes | – | Depends on the host | API key | Building your own agent or product |
Sources: scheduled tasks (comparison table), cloud scheduled tasks, Desktop scheduled tasks, GitHub Actions, Agent SDK.
One line per row:
claude -p: learn it first, every other row is a way of calling it.- cron: the most capable and the least supervised. Full access to your machine, no view of the run unless you build one.
/loop: a session feature, not a scheduler. It dies with the terminal.- Desktop tasks: local and convenient, but only while the app is open and the computer awake.
- Cloud tasks: the only built-in option that survives a closed laptop, at the price of a fresh clone with none of your local setup, and one run an hour at most.
- GitHub Actions: the natural home for anything that starts from a pull request or an issue.
- Hooks: not a trigger for new work, but how you get notified and how you enforce rules in every row above.
- Agent SDK: when a shell script is no longer enough and you want the agent loop inside your own program.
Recent versions also have claude --bg: it starts a session in the background and returns at once, and claude agents, claude logs <id> and claude attach <id> find it again. It keeps a long task running without a terminal, but it is not a trigger: something still has to start it.
The building block: headless mode (claude -p)
-p (or --print) runs one prompt with no interactive interface and exits. The dedicated Claude Code headless mode article goes deeper; here is what an automation needs.
Prompt, output formats and exit codes
claude -p "Reply with exactly the word pong and nothing else." --output-format json--output-format takes text (the default), json (one result object at the end) or stream-json (one JSON event per line, as it happens). stream-json needs --verbose: without it, our run stopped before starting with Error: When using --print, --output-format=stream-json requires --verbose and exit code 1.
The JSON result is what your script should read. From our run:
{"type":"result","subtype":"success","is_error":false,"num_turns":1,"result":"pong",
"total_cost_usd":0.0724,"permission_denials":[],"terminal_reason":"completed", "session_id":"..."}total_cost_usd is a client-side estimate at API prices, also shown on a subscription. session_id lets a later step continue the same conversation with --resume. Add --json-schema '<schema>' and the validated answer lands in structured_output, which saves you from parsing prose: our test asked whether a README existed and got {"status":"ok","summary":"..."} back, ready for jq.
The docs say Claude Code "exits with code 0 on success and a non-zero code when the run fails". What that means in practice, on 2.1.326:
| Situation (tested) | Exit code | What the JSON says |
|---|---|---|
| Task done | 0 | "subtype":"success" |
| Every tool call refused (nothing allowed) | 0 | permission_denials lists the refused calls |
--max-turns 1 reached |
1 | "subtype":"error_max_turns", "is_error":true |
--max-budget-usd 0.01 reached |
1 | "subtype":"error_max_budget_usd", spent $0.074 |
| Not logged in | 1 | "is_error":true, "result":"Not logged in · Please run /login", but "subtype":"success" |
--bare with only a subscription login |
1 | Same "Not logged in" |
stream-json without --verbose |
1 | Nothing, the error is on stderr |
Stopped by timeout --preserve-status (SIGTERM) |
143 | Nothing |
Stopped by timeout (default) |
124 | Nothing |
claude not on cron's PATH |
127 | Nothing, claude: not found on stderr |
Two lessons. Read is_error, not subtype: the "not logged in" run says success there. And an exit code of 0 does not mean the work was done, as the next sections show.
Pre-approving tools: --allowedTools, permission modes, --max-turns
Since v2.1.302, a claude -p run with no permission mode set starts in Manual mode and denies any call that would need approval (headless docs). So you decide in advance what the job may do:
claude -p "Use the Write tool to create stamp.txt containing the single word ok. Then run: git status --short" \
--output-format json --permission-mode dontAsk \
--allowedTools "Write" "Bash(git status *)"That run wrote the file and ran git status, nothing else. The tools that matter:
--allowedTools: rules that run without asking, in permission rule syntax. Mind the space:Bash(git diff *)matchesgit diffand its arguments,Bash(git diff*)also matchesgit diff-index.--disallowedTools: a bare name removes the tool from Claude's context, a scoped rule such asBash(git push *)only denies the matching calls.--permission-mode:dontAskrefuses everything not pre-approved, the honest mode for scheduled jobs;acceptEditslets Claude write files but still needs rules for shell commands;autosends each action to a classifier.--permission-prompts none(v2.1.259+): anything that would prompt is denied, and Claude is told not to retry.--max-turnsand--max-budget-usd: caps, print mode only. Both are rough. Our--max-turns 1run wrote all three files it was asked for in one turn of parallel tool calls, and still reportederror_max_turnswith exit code 1. Our--max-budget-usd 0.01run spent $0.074 before stopping, because the first request alone cost more than the cap; the docs warn that "spend can pass the cap, so leave headroom". Put atimeoutaround the process as well.
The silent refusal when nothing is allowed
Run the same kind of task without any rule, and nothing happens, successfully:
$ claude -p "Run this exact shell command and nothing else: date -u > stamp.txt" --output-format json; echo "exit=$?"
{"subtype":"success","is_error":false,"result":"I ran `date -u > stamp.txt`, but it didn't go through. Claude Code needs
your approval before a shell command writes a file...","permission_denials":[{"tool_name":"Bash", ...}]}
exit=0No file, exit code 0. A cron job that only checks the exit code reports success for a run that did nothing. Check the denials:
jq -e '.is_error == false and (.permission_denials | length == 0)' out.json >/dev/null || echo "run failed or was refused"Our dangerously-skip-permissions guide covers every permission mode, the hard stops that hold even with the flag, and 24 tests of them.
Reusable units: skills, slash commands, CLAUDE.md
A scheduled job with a 40-line prompt in a crontab is unmaintainable. Put the prompt in the repository instead.
Turn a repeated prompt into a skill, call it headless
A skill is a folder with a SKILL.md. Ours, committed in .claude/skills/release-notes/SKILL.md:
---
name: release-notes
description: Summarize the last commits as release notes
---
Run `git log --oneline -5` and write the result as a markdown bullet list under a "## Release notes" heading. Output only the list.Then the job is one line:
claude -p "/release-notes" --output-format json --allowedTools "Bash(git log *)"Our run returned the heading and the three commits of the test repository, in 2 turns. The docs confirm that "user-invoked skills and custom commands work" in -p: Claude Code expands /skill-name before running. Terminal-only commands such as /login don't. The prompt is now versioned, reviewed in pull requests, and the same for a person typing /release-notes and for cron. CLAUDE.md plays the same role for conventions every run should follow (test command, branch naming, what never to touch).
One caveat: --bare, which the docs recommend for scripted calls and which "will become the default for -p in a future release", skips the auto-discovery of hooks, plugins, MCP servers and CLAUDE.md, and only accepts an API key. Skills still resolve via /skill-name; pass the rest explicitly (--append-system-prompt-file, --settings, --mcp-config).
Hooks: run a check or a notification on every tool call or stop
Hooks are shell commands Claude Code runs on lifecycle events, and they fire in -p too. Our test passed this settings file with --settings:
{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"echo stop-hook-fired $(date -u +%H:%M:%S) >> /out/hook.log"}]}]}}and the log got its line, stop-hook-fired 09:07:12, when the run ended. Three hooks matter for automation:
Stop: the turn is over. Post the result to a chat, write a status file.StopFailurewith the matcherrate_limit|billing_error: the turn stopped on the plan's limit (hooks reference). This is how you learn a job ran out of quota instead of finding out the next morning.PreToolUse: runs before every tool call and can deny it, even in bypass mode. Your policy as code: refusegit push, log every command.
A future best Claude Code hooks article will collect the useful ones.
Running it on a schedule
Four schedulers, four very different contracts. The planned Claude Code scheduled tasks article covers the built-in ones in depth.
cron or systemd timers on your own machine
The most flexible option, and the one where you build the safety yourself. Our wrapper, with every piece tested in a container:
#!/bin/bash
# /usr/local/bin/claude-nightly.sh, called by cron
set -uo pipefail
export PATH="$HOME/.local/bin:/usr/local/bin:/usr/bin:/bin" # cron's PATH doesn't have claude
cd /srv/repos/myapp || exit 1
exec 9>/tmp/claude-nightly.lock # one run at a time
flock -n 9 || { echo "$(date -u +%FT%TZ) previous run still going, skipping" >&2; exit 75; }
claude auth status >/dev/null || { echo "claude is not logged in" >&2; exit 1; }
LOG="$HOME/logs/claude-nightly-$(date -u +%F).json"
timeout --preserve-status 30m claude -p "/nightly-triage" \
--output-format json --permission-mode dontAsk \
--allowedTools "Read" "Grep" "Glob" "Bash(gh issue list *)" "Bash(gh issue view *)" "Bash(gh issue edit *)" \
--max-turns 40 --max-budget-usd 3 --no-session-persistence < /dev/null > "$LOG"
code=$?
ok=$(jq -r 'if .is_error == false and (.permission_denials | length == 0) then "yes" else "no" end' "$LOG" 2>/dev/null || echo no)
if [ "$code" -ne 0 ] || [ "$ok" != yes ]; then
curl -fsS -X POST -d "claude-nightly failed: exit=$code, see $LOG" "$ALERT_WEBHOOK_URL"
fi
exit "$code"0 2 * * * . $HOME/.claude-cron.env; /usr/local/bin/claude-nightly.sh >> $HOME/logs/cron.log 2>&1Why each line is there:
PATH: the native installer putsclaudein~/.local/bin, which cron doesn't know. Our test with cron's minimal environment gotclaude: not foundand exit code 127.flock: if Tuesday's run is still going when Wednesday's starts, the second one logs and quits (exit 75 in our test) instead of two agents editing the same checkout.claude auth status: exits 0 if logged in, 1 if not (CLI reference). A failed login is the most common reason a job that worked for weeks stops.timeout --preserve-status: a hung run is killed after 30 minutes and exits 143, which your alert sees.< /dev/null: nothing waits on stdin.- The
jqcheck: catches the exit-0 refusal. .claude-cron.env: on a server with no browser, runclaude setup-tokenonce and putCLAUDE_CODE_OAUTH_TOKEN=...there, or anANTHROPIC_API_KEY.
A systemd timer does the same with Persistent=true to run a missed job at boot, and journalctl for the logs.
/loop: repeat a prompt inside an open session
/loop 5m check whether the deploy finished and tell me if it failed/loop turns a prompt into a session-scoped cron task (the CronCreate tool). The limits, from the docs: 1 minute minimum, up to 50 tasks per session, recurring tasks expire after 7 days, times are in local time, and runs are shifted by a jitter (an hourly task can run up to 30 minutes late). "Closing the terminal or letting the session exit stops them firing", and there is no catch-up: a fire missed while Claude was busy runs once when it becomes idle. CLAUDE_CODE_DISABLE_CRON=1 turns the scheduler off.
We tried the obvious shortcut, /loop inside claude -p. Claude created the task (CronCreate with * * * * *), answered once, and the process exited after 12 seconds with code 0. No tick ever fired. The docs only mention self-paced loops keeping a -p run open. Use /loop to watch something for an afternoon in a session you keep open; for anything that must happen tomorrow, pick another row.
Desktop scheduled tasks: local, while the app is open
The Claude Desktop app (1.1.5368 or later) can schedule a task on a local folder: hourly, daily, weekdays, weekly or a custom cron, at most once an hour from the forms. It "only fires while the app is open and your computer is awake"; "closing the laptop lid still puts it to sleep". If the computer sleeps through a run, that run is skipped, and on wake Desktop starts exactly one catch-up run for the most recent missed time within the last seven days (docs).
Runs use your Claude Code permission settings unless you set a mode on the task; a run that needs a permission waits for you in its session. Turn on Worktree in the task's form so each run gets its own git worktree: by default it works in your folder, "including uncommitted changes".
Cloud scheduled tasks (formerly routines)
Anthropic renamed routines to scheduled tasks; the CLI command is /schedule (alias /routines), the web page is claude.ai/code/routines. They run on Anthropic's cloud, so they are the built-in way to keep going with your laptop closed. What the docs say, as of today:
- Status and plans: research preview, on Pro, Max, Ultra, Team and Enterprise.
/scheduleneeds a claude.ai login, not an API key. - Triggers: a schedule (hourly, daily, weekly, one-off, or a custom cron in UTC; "expressions that run more often than once per hour are rejected"), an API trigger, and GitHub events on pull requests, releases and issues, with filters on author, branch, labels and more. The Claude GitHub App must be installed.
- Environment: each run clones the repository fresh, from the default branch, in a cloud environment with limited network access by default. Your claude.ai connectors are available, including writes; MCP servers added with
claude mcp addare not, unless committed in.mcp.json. Your local files, databases and other CLIs are not there. - Permissions: a run "begins in auto mode", with the classifier reviewing actions.
- Results: each run is a full session you can open; Claude pushes to a branch prefixed
claude/unless the prompt says otherwise, so protect your main branch with GitHub rules. - Billing and caps: runs "count against your account's usage and limits". The docs list hourly caps per account and per task (at the time of writing, 100 scheduled runs per hour per account, and 30 "Run now" or API fires per hour per task); events beyond the limit are dropped.
The API trigger turns any system into an event source:
curl -X POST "https://api.anthropic.com/v1/claude_code/routines/$TRIGGER_ID/fire" \
-H "Authorization: Bearer $ROUTINE_TOKEN" \
-H "anthropic-beta: experimental-cc-routine-2026-04-01" \
-H "anthropic-version: 2023-06-01" -H "Content-Type: application/json" \
-d '{"text": "Sentry issue 4812: TypeError in checkout.ts line 88"}'The text reaches the run wrapped as untrusted input, and the saved prompt has to refer to it. The token is per task, shown once.
Which scheduler for which job
| The job needs | Pick |
|---|---|
| Your local services, a database, another CLI, a GPU | cron or systemd on a machine that stays on |
| To run with your laptop closed, on the repository alone | Cloud scheduled task, or a GitHub Actions schedule: |
| More than one run an hour | cron, or GitHub Actions (5 minutes minimum) |
| To watch something for the next few hours | /loop in a session you keep open |
| A personal routine on your own computer, with a UI | Desktop scheduled task |
| A result you can open as a session and continue | Cloud or Desktop scheduled task |
Cloud vs your own machine is the same trade-off as with other agents; our Cursor background agents post compares both sides.
Reacting to events: GitHub Actions and webhooks
anthropics/claude-code-action on PRs, issues and comments
The fastest setup is /install-github-app in Claude Code: it installs the Claude GitHub App, stores a secret and opens a pull request with the workflow files (you need admin rights on the repository and an authenticated gh). The action has two modes (docs):
- Interactive: no
promptinput, Claude waits for@claudein an issue, a PR comment or a review comment, and answers there. - Automation: a
promptinput, Claude runs on the event without being mentioned.
name: Claude
on:
issue_comment:
types: [created]
pull_request_review_comment:
types: [created]
jobs:
claude:
if: contains(github.event.comment.body, '@claude')
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write
issues: write
id-token: write
steps:
- uses: actions/checkout@v6
with:
fetch-depth: 1
- uses: anthropics/claude-code-action@v1
with:
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }} # or anthropic_api_keyThings that bite: the action runs Claude in auto mode by default (pass --permission-mode in claude_args to change it); only users with write access can trigger it on issue and PR events; secrets are not given to pull requests from forks on public repositories; and commits made with the default GITHUB_TOKEN don't trigger your other workflows, so CI won't run on Claude's commits if you pass it. Flags such as --max-turns and --model go in claude_args. The planned Claude Code GitHub Actions article goes deeper.
Scheduled workflows in Actions
on:
schedule:
- cron: "0 7 * * 1" # Mondays 07:00 UTCGitHub's cron is in UTC, runs only from the default branch, can start late under load, and the shortest interval is 5 minutes. In public repositories, GitHub turns schedules off after 60 days without activity. With a plain-text prompt, Claude has no shell or GitHub API access until you grant tools with --allowedTools in claude_args. Each run also costs Actions minutes.
Webhooks and the API trigger of cloud tasks
For events that don't come from GitHub (a Sentry alert, a form, a failed deploy), you have two built-in paths: the API trigger of a cloud scheduled task shown above, or a GitHub workflow started by repository_dispatch that runs the action. Outside these, any small endpoint that receives the webhook and runs claude -p on your machine does the job, with the same wrapper as the cron one.
Chaining steps: from one prompt to a workflow
Shell pipelines and the Agent SDK
A session id is all you need to chain claude -p calls:
sid=$(claude -p "Read ISSUE.md and plan the fix. Do not edit anything yet." \
--output-format json --permission-mode dontAsk --allowedTools "Read" "Grep" "Glob" | jq -r .session_id)
claude -p "Implement the plan. Run the tests. Commit on a new branch." --resume "$sid" \
--output-format json --permission-mode acceptEdits \
--allowedTools "Bash(npm test *)" "Bash(git switch *)" "Bash(git add *)" "Bash(git commit *)" \
--disallowedTools "Bash(git push *)"When the glue grows past a page of bash, the Agent SDK gives you the same agent loop in TypeScript (@anthropic-ai/claude-agent-sdk) or Python (claude-agent-sdk):
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "Review utils.py for bugs that would cause crashes. Fix any issues you find.",
options: { allowedTools: ["Read", "Edit", "Glob"], permissionMode: "acceptEdits" },
})) {
if (message.type === "result") console.log(message.result);
}Authentication is an API key. The SDK docs are explicit: "Unless previously approved, Anthropic does not allow third party developers to offer claude.ai login or rate limits for their products, including agents built on the Claude Agent SDK."
Handing work between Claude Code and another CLI
The most useful chain we run is two different models: one writes, the other reviews. Codex has its own headless mode, codex exec:
git diff main...HEAD > /tmp/change.diff
codex exec --sandbox read-only "Review this diff for bugs and missing tests. List each finding with file and line: $(cat /tmp/change.diff)"Then feed the remarks back to Claude with --resume "$sid". A reviewer that didn't write the code finds different things; our Codex vs Claude Code benchmark measured how differently the two work on the same tasks. The headless flags of Copilot CLI and Gemini CLI are in our Copilot and Gemini comparisons.
What breaks when nobody is watching
Permissions: allowlist, or skip everything inside a box
Two sane setups, nothing in between:
- On a machine you care about:
--permission-mode dontAskwith an exact--allowedToolslist, plus--disallowedTools "Bash(git push *)". The job can only do what the list says. - Inside a container or VM with no personal credentials:
--dangerously-skip-permissionsfor long open-ended tasks, with deny rules and aPreToolUsehook for what must still never happen.
Remember that -p skips the workspace trust dialog: per the docs, a -p run without --bare runs the project's hooks and connects its .mcp.json servers "even in a folder you've never trusted". Don't point a scheduled job at a repository you haven't read. The full picture is in the dangerously-skip-permissions guide.
Knowing it failed: exit codes, logs, notifications
Three checks, in this order: the exit code (non-zero means crashed, capped, killed or not logged in), is_error in the JSON, then permission_denials. Keep the JSON of every run, dated, for a few weeks: it has the result, the cost and the session id to --resume and ask "what happened?". Send an alert on any of the three, and use a Stop or StopFailure hook for notifications that must leave even when your wrapper is not involved. The silent failure to fear most is the one that didn't run at all: a cron line with a typo, a cloud task turned off after its GitHub connection broke for 72 hours. A daily "I ran" message is cheaper than discovering a week of silence.
Usage limits in the middle of a run
Scheduled runs draw from the same five-hour and weekly windows as your interactive use (cloud tasks included). Anthropic's support page says that when the five-hour limit hits mid-response, Claude Code may finish the current step and show "Usage limit reached · wrapping up", then stops until the window resets, unless usage credits are on. What a claude -p run does then is not documented, and we did not reach a limit for this article. Plan for it anyway: a StopFailure hook on rate_limit|billing_error, nightly jobs scheduled away from your working hours so they don't eat the window you need in the morning, and --fallback-model for the case where a model is busy rather than your plan exhausted.
Subscription or API key for unattended runs
What the docs say today:
- Your own jobs, the unmodified CLI, your subscription: documented.
claude setup-token"requires a Claude subscription" and prints a one-year OAuth token for CI and scripts; the GitHub Action takes it asCLAUDE_CODE_OAUTH_TOKEN(authentication). The legal page adds that advertised limits "assume ordinary, individual usage of Claude Code and the Agent SDK". - A secret shared across an organization: the GitHub Actions docs recommend an API key, "since an OAuth token is tied to the subscription of the person who ran
claude setup-token". - A product built on the Agent SDK for other people: API key, as quoted above.
Two traps. ANTHROPIC_API_KEY takes precedence over CLAUDE_CODE_OAUTH_TOKEN, so a key left in the environment silently moves your jobs to API billing. And --bare never reads OAuth: our --bare run with a valid subscription login answered "Not logged in" and exited with 1.
Review before anything ships
An unattended agent that pushes to main is a deploy pipeline with no reviewer. Let it commit on a branch, deny git push (or allow only pushes to its own prefix, as cloud tasks do with claude/), and have a person read the diff before it merges. For pull requests, require a review in the branch protection rules, so even an agent with write access can't merge its own work.
Claude Code automation examples you can copy
Each recipe gives the trigger, the command, the permissions and where the result lands. The linked templates are the same jobs as ready-made SideHub workflows.
- Nightly issue triage. cron at 02:00 (or a cloud task).
claude -p "/triage"withdontAskandRead,Grep,Glob,Bash(gh issue list *),Bash(gh issue view *),Bash(gh issue edit *): labels, duplicate links, questions for missing details. Lands as labels and comments, plus a morning digest. Template. - Weekly dependency updates. Tuesdays 06:00.
acceptEdits,Bash(npm outdated *),Bash(npm audit *),Bash(npm install *),Bash(npm test *),Bash(git *)withgit pushdenied: safe updates on a branch, tests run. Lands as a branch you push after reading, or a PR. Template. - Daily PR review. Weekdays 08:00, or the action's
pull_requestevent. Read-only tools plusBash(gh pr list *),Bash(gh pr diff *),Bash(gh pr review *). Lands as review comments before stand-up. Template. - Fix a failed CI run. GitHub
workflow_runwithconclusion == 'failure', running the action or calling your webhook.acceptEditsplus the test command: reproduce, fix, commit on a branch. Lands as a branch or PR for review, never onmain. Template. - Monday report. Mondays 07:00. Read-only,
Bash(git log *),Bash(gh pr list *),Bash(gh run list *),--json-schemafor a fixed shape. Lands as a message in your team chat from the wrapper or aStophook. Template. - Test automation. On every push or nightly:
claude -p "Run the test suite, find the failing tests, fix them, commit."withBash(npm test *)andacceptEdits. For browser tests, add the Playwright MCP server (claude mcp add playwright npx @playwright/mcp@latest, or a committed.mcp.json) and allowmcp__playwright: Claude drives a real browser, reads the page and writes the test. Lands as a commit to review. - Errors from production. A Sentry alert calls a webhook, Claude reproduces the error in a test and fixes it, another CLI reviews. Template.
How we automate Claude Code on our own machines (SideHub)
The built-in options leave a gap we kept falling into. Cloud scheduled tasks run on a fresh clone, without our local services, databases or other CLIs. Desktop tasks and /loop stop when the app or the session closes. cron and CI run anywhere, but give no view of the run and no review step. SideHub is what we built for that: an agent you install on your own machine runs the same CLIs, in a terminal on that machine, launched from the web.
- Triggers: a schedule (local time, every 15 minutes at most on Pro, 5 on Business), a secret webhook URL whose JSON body fills the workflow's inputs, a REST API key, or events inside SideHub (a document created, a task that changes status, another workflow that finishes). GitHub and Sentry come in through the webhook, called from a GitHub Action or a Sentry integration: there are no native GitHub or Sentry triggers.
- Workflows: up to 50 steps, each with its own CLI (Claude Code, Codex, Antigravity CLI, Copilot CLI, Gemini CLI or a shell script) and model, the output of one step passed to the next, approval steps for a person, interactive steps you chat with. The Claude codes, Codex reviews template is the chain from the section above.
- Watching and counting: any run's terminal opens live from the browser; tokens are recorded per run, with an estimated cost at API prices in the cockpit; a run that stopped on Claude Code's, Codex's or Antigravity's plan limit ends as "plan limit reached" (Claude through the same
StopFailurehook), and failures are notified by e-mail, an outgoing webhook or Telegram (Business plan). - Nothing ships unreviewed: a run that changed the repository lands in To review with its diff, which you can read and validate from a phone; the push happens from To push, confirmed by a person, never forced and never automatic.
What it does not do: it needs the agent running on a machine that stays on. A scheduled run that fires while the machine is offline is skipped; when the agent comes back, the last missed one is caught up once, not every one, and you get one alert per outage. Webhook and event triggers are not retried. There is no automatic switch to another CLI when a plan runs out, yet. Schedules, webhooks and event triggers need the Pro plan.
This article went through that pipeline: a weekly workflow chose the keyword and wrote the brief, a Claude Code step ran the tests and drafted the page, a person approved it, and a last step opened the pull request that published it.
Troubleshooting
- The run hangs. In interactive mode it waits for a permission; in
-pthat can't happen, so look at MCP servers: Claude waits up toMCP_TIMEOUT(30 seconds by default) for each one to start. Run with--strict-mcp-configand only the servers the job needs. Atimeoutaround the process makes a hang visible. - Exit code 0, nothing done. The calls were refused. Read
permission_denialsin the JSON and add the exact rules; remember that a shell redirect (> file) is checked against yourEditrules, not theBashrule. - cron can't find
claude. Exit code 127,claude: not found. SetPATHin the script or call~/.local/bin/claudeby its full path. - "Not logged in · Please run /login" on a server. Exit code 1. Check
claude auth statusas the user cron runs as, generate a token withclaude setup-tokenon a machine with a browser and export it asCLAUDE_CODE_OAUTH_TOKEN, or use an API key. With--bare, only an API key works. - The job stopped with
error_max_turnsbut the work is there.--max-turnscounts agent turns, not tool calls, and stops the run even when the last turn finished the job. Raise it and rely ontimeoutand the budget. - The scheduled task did not fire. Desktop: the computer was asleep or the app closed (look for the reason in the task's history). Cloud: the hourly caps, a missing GitHub connection (runs skipped up to 72 hours, then the task turns off), or a schedule that runs "several minutes late" on the hour. GitHub Actions: not on the default branch, or turned off after 60 days without activity.
/loop: the session exited, or 7 days passed.
How we tested
Each case ran in its own docker run --rm container from debian:bookworm-slim with git, jq and flock, as a non-root user (uid 1001), on a fresh git repository. Only a copy of the Claude Code 2.1.326 binary and a read-only copy of its sign-in file were mounted: no home directory, no other credentials.
docker run --rm --user 1001:1001 -e HOME=/home/dev \
-v "$PWD/scripts:/bench/scripts:ro" -v "$PWD/results:/out" \
-v "$PWD/creds/claude:/opt/claude:ro" \
-v "$PWD/creds/credentials.json:/creds/credentials.json:ro" \
ccabench:1 /bench/scripts/in-container.sh refusalThe script copies the binary to ~/.local/bin, as the native installer does, then runs one claude -p per case with --strict-mcp-config --no-session-persistence < /dev/null, and records the exit code, stdout, stderr and the files left on disk. 17 cases: JSON output, the silent refusal (with and without --permission-prompts none), an exact allowlist, --max-turns, --max-budget-usd, a skill called headless, a Stop hook, --bare, no login, cron's PATH, stream-json without --verbose, --json-schema, timeout with and without --preserve-status, a flock wrapper, and /loop inside -p. Default model (Claude Opus 5.5) on a Claude Max plan, $0.90 in total at API prices according to total_cost_usd for the 10 runs that reported it. One run per case: these tests check what the CLI does, not how often a model gets a task right. Facts about cloud and Desktop scheduled tasks and GitHub Actions are quoted from Anthropic's docs as of 2026-11-17; cloud scheduled tasks are a research preview and their limits may change.
The verdict
Claude Code automation is not one feature but one command, claude -p, and a choice of who calls it. Pick by where the job must run: cron or systemd on a machine that stays on when it needs your local world, GitHub Actions when it starts from the repository, a cloud scheduled task when it needs neither and once an hour is enough, /loop and Desktop tasks for what can stop when you close the lid. Then do the four things every unattended run needs: permissions decided in advance with an exact allowlist, a check of is_error and permission_denials rather than the exit code alone, a notification when it fails or hits the plan limit, and a person who reads the diff before anything is pushed. The template gallery has the examples above as ready-made workflows, if you'd rather start from one.